Log MCPServer handler exceptions by kind and keep crash details off the wire
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 oneINFOrecord 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 oneERRORrecord with the traceback. Nothing from the exception's text goes on the wire, and nothing is logged twice.
Motivation and Context
On main the three primitives each hand-roll their own except ladder and each made a different choice:
| handler raises | logged | client sees |
|---|---|---|
| tool | nothing | is_error=True, "Error executing tool X: {e}" — the raw exception text |
| static resource / template | ERROR + traceback, once | -32603 "Error reading resource {uri}" (text withheld) |
| prompt | ERROR + traceback, twice | legacy 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.runvalidates arguments first (a schema rejection is a plainToolErrorchained to theValidationError; a validator that raises anything else is a crash). The body then runs under an except ladder:ToolErrororResourceError(from the tool, a resolver, orctx.read_resource()) is re-raised asToolErrorwith its message; anything else becomes the newUnexpectedToolError(ToolError)whose message is onlyError executing tool <name>and whose__cause__is the original._handle_call_tool/_handle_read_resourcelog at the point the failure becomes a response:INFOfor the anticipated types (rejected arguments log field names, not values),logger.exceptionfor theUnexpected*wrappers.- Resources get the matching
UnexpectedResourceError(ResourceError), raised inMCPServer.read_resource(andResourceTemplate.create_resource), so__cause__is always the original. Built-inResource.read()implementations no longer wrap. - Prompts drop the inner
logger.exceptioninget_prompt(the dispatcher boundary's record is the only one), andPrompt.renderno longer interpolates the exception text into its message. @mcp.completion()gets the same treatment: a crash is oneERRORrecord 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_jsonleaves strings the JSON parser refuses (over-long integers, deep nesting) for argument validation to reject; andResource.read()returning something other thanstr | bytesis a crash rather thanInvalid request parameters. FuncMetadata.call_fn()is the new "call with already-validated arguments" stepTool.runuses;call_fn_with_arg_validation()remains as a thin wrapper, deprecated withMCPDeprecationWarningfor 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→contentisError executing tool <name>(was…: <str(exc)>). Same for a crashing resolver, a crashing validator, and an output-schema failure. Prompt.renderfailure on the legacy path →Error rendering prompt <name>(was…: <str(exc)>).@mcp.completion()crash →-32603 Error completing argument <name>(legacy path wascode=0, str(exc)).ResourceError/ResourceNotFoundErrorfrom 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 viactx.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, lowlevelServerincluded) is unchanged; it has its own TODO /protocol:error:internal-errordivergence 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 deliberateToolError(#2984 territory). - Bounding peer-supplied values in log records composes with #2238.
MCPServer's defaultRichHandlerrenders 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 (includingOpenTelemetryMiddleware) as the sanitisedMCPError, so its span recordserror.type=-32603without an exception event, the way resource crashes already did. Whether spans should record the chained cause for-32603is a follow-up for_otel.py. - A
Sample/ListRootsresolver on a legacy connection whose peer answers with a result of the wrong shape is classified as a crash (theinput_requiredpath calls it aToolError). 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,ToolErrorsubclass, bad arguments (INFO names fields;__cause__is theValidationError), validator crash vs validatorMCPError,ValidationErrorinside the body / output-schema failure (crashes), unknown tool,MCPError(no record), resolverToolErrorvs crash,ResourceNotFoundErrorvs resource crash escaping a tool, a tool that recovers from a missing resource (nothing logged), static / template / custom-subclass resource crash, staticResourceNotFoundError, deliberateResourceError, completion crash vsMCPError, prompt crash logged once, nested tool crash, and the directcall_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.