Troubleshooting and Error Handling
Relevant source files
The following files were used as context for generating this wiki page:
This document provides a comprehensive overview of the error handling mechanisms, exception types, and troubleshooting procedures within the MCP Python SDK. It covers errors at the transport, protocol, and application layers, offering guidance for both developers using the SDK and those extending its functionality.
The system employs a layered approach to error handling. At the lowest level, the StreamableHTTP transport uses standard HTTP status codes for connection and request-level issues. Above that, the MCP protocol uses the McpError structure for protocol-specific failures. Finally, at the application level, such as within FastMCP, Python exceptions raised in tools or resources are caught and gracefully converted into structured error responses sent back to the client.
Core Exception Class: McpError
The cornerstone of error communication in the MCP protocol is the McpError class. It provides a standardized structure for reporting problems from the server to the client.
Sources: src/mcp/shared/exceptions.py
McpError Structure
The McpError class encapsulates all necessary information about a failure.
This diagram shows the structure of the McpError class and its relationship with the base Exception.
Sources: src/mcp/shared/exceptions.py:7-16
| Attribute | Type | Description |
|---|---|---|
code | int | A number that indicates the error type. |
message | str | A string providing a short description of the error. |
data | Any | A primitive value that contains additional information. |
Sources: src/mcp/shared/exceptions.py:7-16
Transport-Level Errors (StreamableHTTP)
The StreamableHTTP transport handles initial request validation and session management, reporting errors using standard HTTP status codes.
Sources: tests/shared/test_streamable_http.py
Common HTTP Errors
The server will respond with specific HTTP 4xx status codes if a request is malformed before it can be processed by the MCP application logic.
This sequence diagram illustrates a client making a request with an invalid Content-Type header and the server responding with a 400 Bad Request error.
The following table summarizes common HTTP errors encountered when interacting with the StreamableHTTP endpoint.
| Status Code | Reason | Cause |
|---|---|---|
400 | Bad Request | Invalid JSON, malformed JSON-RPC, missing session ID for non-initialize requests, or invalid protocol version. |
404 | Not Found | The requested session ID does not exist or has been terminated. |
405 | Method Not Allowed | An unsupported HTTP method was used (e.g., PUT). Only POST, GET, and DELETE are supported. |
406 | Not Acceptable | The Accept header is missing or does not include application/json or text/event-stream. |
409 | Conflict | A client attempts to establish a second GET stream for the same session ID. |
Sources: tests/shared/test_streamable_http.py:397-505
Session Management Errors
Session lifecycle events can also produce errors.
- Missing Session ID: Any request other than
initializesent without themcp-session-idheader will result in a400 Bad Request.
Sources: tests/shared/test_streamable_http.py:470-484 - Terminated Session: Attempting to use a session ID after the session has been terminated (via a
DELETErequest) will result in a404 Not Found.
Sources: tests/shared/test_streamable_http.py:530-560 - Invalid Session ID: A session ID containing non-visible ASCII characters will be rejected with a
ValueErroron the server side during transport initialization.
Sources: tests/shared/test_streamable_http.py:508-528
Application-Level Errors (FastMCP)
FastMCP provides a high-level framework for building MCP servers and includes robust error handling for application logic, particularly within tools, resources, and prompts.
Sources: tests/server/fastmcp/test_server.py
Tool Execution Errors
When a function decorated with @mcp.tool raises a Python exception, FastMCP catches it and converts it into a structured CallToolResult that is sent to the client.
The following flowchart shows how a tool call is processed, including the path taken when an exception occurs.
The resulting CallToolResult will have these properties:
isError:Truecontent: A list containing a singleTextContentblock with the exception message and traceback.structuredContent:None
Sources: tests/server/fastmcp/test_server.py:280-282, tests/server/fastmcp/test_server.py:702-710
Prompt and Resource Errors
Similar to tools, errors can occur when handling prompts and resources.
- Unknown Prompt: Requesting a prompt that has not been registered with
@mcp.promptwill raise anMcpErrorwith the message "Unknown prompt".
Sources: tests/server/fastmcp/test_server.py:1260-1264 - Missing Prompt Arguments: Calling
get_promptwithout providing all required arguments for the prompt function will result in anMcpErrorindicating missing arguments.
Sources: tests/server/fastmcp/test_server.py:1266-1276 - Unknown Resource: Attempting to read a resource URI that does not match any registered resource or resource template will raise a
ValueErroron the server, typically resulting in an error response to the client.
Sources: tests/server/fastmcp/resources/test_resource_manager.py:133-136 - Resource Function Error: If a function backing a resource or resource template raises an exception, it is caught and reported back to the client, similar to tool exceptions. For example, a
FileNotFoundErrorin a resource function is returned as a specific message in the content.
Sources: tests/server/fastmcp/servers/test_file_server.py:88-93
Development and Logging Guidelines
The project has specific guidelines for how developers should handle exceptions in their own code to ensure consistency and effective debugging.
Sources: CLAUDE.md
Exception Logging
- Always use
logger.exception()when catching exceptions to automatically include stack trace information. Do not include the exception object in the log message itself.- Correct:
logger.exception("Failed to process data") - Incorrect:
logger.exception(f"Failed to process data: {e}")
- Correct:
- Catch specific exceptions whenever possible (e.g.,
except (OSError, PermissionError):) instead of genericException. - Only catch a base
Exceptionin top-level handlers that must not crash or in cleanup blocks.
Sources: CLAUDE.md:83-93
CI and Common Issues
When contributing, developers may encounter CI failures. The recommended resolution order is:
- Formatting errors (
ruff format) - Type errors (
pyright) - Linting errors (
ruff check)
Common issues include line length violations and type errors related to Optional types, which often require explicit None checks to resolve.
Sources: CLAUDE.md:57-78