Log MCPServer handler exceptions by kind and keep crash details off the wire

Merged
MA
3mo ago
+1427-310

MCPServer now treats an exception from a tool, resource, or prompt handler in one of two ways, decided by its type:

  • Anticipated (ToolError, ResourceError/ResourceNotFoundError, a schema rejection of the arguments, an unknown name): the message reaches the client as before, and the server writes one INFO record with no traceback.
  • A crash (anything else): the client learns only that it failed (Error executing tool <name>, Error reading resource <uri>, Error rendering prompt <name>), and the server writes one ERROR record with the traceback. Nothing from the exception's text goes on the wire, and nothing is logged twice.

Fixes #3266. Fixes #698.

Motivation and Context

On main the three primitives each hand-roll their own except ladder and each made a different choice:

handler raisesloggedclient sees
toolnothingis_error=True, "Error executing tool X: {e}" — the raw exception text
static resource / templateERROR + traceback, once-32603 "Error reading resource {uri}" (text withheld)
promptERROR + traceback, twicelegacy path: code=0 with the raw text; modern: Internal server error

Two problems in that table. A crashing tool leaves no trace on the server (#3266): for a KeyError('id') the model reads 'id' and the traceback exists nowhere. And a crashing tool or prompt sends str(exc) to the client (#698), which can describe server internals; for an output-schema failure it echoes the tool's return value.

Rather than an eighth site-specific patch (#3267 / #3271 / #2198), the exception's type now carries "was this anticipated?" to one decision point per primitive:

  • Tool.run validates arguments first (a schema rejection is a plain ToolError chained to the ValidationError; a validator that raises anything else is a crash). The body then runs under an except ladder: ToolError or ResourceError (from the tool, a resolver, or ctx.read_resource()) is re-raised as ToolError with its message; anything else becomes the new UnexpectedToolError(ToolError) whose message is only Error executing tool <name> and whose __cause__ is the original.
  • _handle_call_tool / _handle_read_resource log at the point the failure becomes a response: INFO for the anticipated types (rejected arguments log field names, not values), logger.exception for the Unexpected* wrappers.
  • Resources get the matching UnexpectedResourceError(ResourceError), raised in MCPServer.read_resource (and ResourceTemplate.create_resource), so __cause__ is always the original. Built-in Resource.read() implementations no longer wrap.
  • Prompts drop the inner logger.exception in get_prompt (the dispatcher boundary's record is the only one), and Prompt.render no longer interpolates the exception text into its message.
  • @mcp.completion() gets the same treatment: a crash is one ERROR record and -32603 "Error completing argument <name>".
  • Also kept out of the crash path: a returned CallToolResult(is_error=True) from a tool with an output schema is no longer validated against that schema (its message reaches the client as written); pre_parse_json leaves strings the JSON parser refuses (over-long integers, deep nesting) for argument validation to reject; and Resource.read() returning something other than str | bytes is a crash rather than Invalid request parameters.
  • FuncMetadata.call_fn() is the new "call with already-validated arguments" step Tool.run uses; call_fn_with_arg_validation() remains as a thin wrapper, deprecated with MCPDeprecationWarning for removal in 3.0.

Why level, not "log everything at ERROR": level is the one filter operators get for free and what Sentry/Datadog integrations key on. External FastMCP shipped logger.exception for every tool failure and walked it back over PrefectHQ/fastmcp#4036, #4029, #4392 once deliberate ToolErrors and model typos flooded error monitoring. #2422 and #2346 are the same signal here.

Why withhold crash text: it's the call already made for resources (#1957) and prompts, it's what #698 / #2386 ask for, and it's the default in every framework surveyed (Starlette/uvicorn, Flask, Django, gRPC-java, the C# SDK). Model self-correction is preserved because the two channels the model can act on, ToolError and argument-validation text, still pass through.

Client-visible changes

  • A tool that raises something other than ToolError/ResourceError/MCPError → content is Error executing tool <name> (was …: <str(exc)>). Same for a crashing resolver, a crashing validator, and an output-schema failure.
  • Prompt.render failure on the legacy path → Error rendering prompt <name> (was …: <str(exc)>).
  • @mcp.completion() crash → -32603 Error completing argument <name> (legacy path was code=0, str(exc)).
  • ResourceError / ResourceNotFoundError from a static resource now pass through (-32602 / your message) as they already did from a template. Also visible one level up when a tool reads such a resource via ctx.read_resource().

Not in here

  • The legacy dispatcher's catch-all (code=0, str(e) for any other unmapped handler exception on 2025-era transports, lowlevel Server included) is unchanged; it has its own TODO / protocol:error:internal-error divergence and a wider blast radius.
  • A resource template parameter that fails its type annotation is still logged as a crash: templates run through validate_call, which fuses validation with the call. Not a regression. Follow-up.
  • Dropping the Error executing tool X: prefix for a deliberate ToolError (#2984 territory).
  • Bounding peer-supplied values in log records composes with #2238.
  • MCPServer's default RichHandler renders a crash as 100+ stderr lines at 80 columns under a stdio host; tool crashes now join resources/prompts there. Separate conversation.
  • Telemetry: a crashing @mcp.completion() handler now reaches middleware (including OpenTelemetryMiddleware) as the sanitised MCPError, so its span records error.type=-32603 without an exception event, the way resource crashes already did. Whether spans should record the chained cause for -32603 is a follow-up for _otel.py.
  • A Sample/ListRoots resolver on a legacy connection whose peer answers with a result of the wrong shape is classified as a crash (the input_required path calls it a ToolError). Only a non-conformant client can produce it.

How Has This Been Tested?

  • tests/server/mcpserver/test_server.py: level, message, traceback identity and wire result per class — crash, ToolError, ToolError subclass, bad arguments (INFO names fields; __cause__ is the ValidationError), validator crash vs validator MCPError, ValidationError inside the body / output-schema failure (crashes), unknown tool, MCPError (no record), resolver ToolError vs crash, ResourceNotFoundError vs resource crash escaping a tool, a tool that recovers from a missing resource (nothing logged), static / template / custom-subclass resource crash, static ResourceNotFoundError, deliberate ResourceError, completion crash vs MCPError, prompt crash logged once, nested tool crash, and the direct call_tool() / read_resource() type and __cause__ contracts.
  • Interaction suite: existing wire snapshots updated to the sanitised text; one new wire test for static ResourceNotFoundError → -32602.
  • tests/docs_src/*: every rewritten docs claim is exercised.
  • End-to-end over real stdio and streamable HTTP with a small server: one record per failure at the expected level, crash text absent from every client-visible result, log_level="WARNING" leaves only the crash records.
  • ./scripts/test: 100% coverage, strict-no-cover, pyright, pre-commit clean.

Breaking Changes

The client-visible changes listed above. docs/servers/handling-errors.md now teaches ToolError as the way to hand the model a message; code that raised a plain exception expecting the model to read its text should switch to ToolError. The new exception types subclass the existing ones, so except ToolError / except ResourceError and the documented Raises: contracts keep working. Softer differences: FunctionResource.read() / FileResource.read() called directly raise the original exception instead of a ValueError. MCPServer.read_resource() / get_prompt() no longer log by themselves. FuncMetadata.call_fn_with_arg_validation() warns (MCPDeprecationWarning) and is slated for 3.0. Log message wording changed.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Supersedes #3267, #3271, and #2198 (thank you all — the diagnoses were right; this moves the fix to where all three primitives share it). Related: #2153, #2386, #2422.

AI Disclaimer