Skip to content

Raise distinct errors for the SDK's own request timeout and closed connection, not a server's -32001/-32000 #3963

Backlog

Description

@a-akimov

Problem

When a request times out or the connection closes, the client raises a plain MCPError with code REQUEST_TIMEOUT (-32001) or CONNECTION_CLOSED (-32000). Both codes are in the range JSON-RPC 2.0 §5.1 reserves for implementation-defined server errors, and servers do send them in their own error responses. A server's error and the SDK's own failure therefore reach the caller as the same exception type with the same code. The only way to tell them apart is to match the message text.

Reproduced with mcp 2.3.0. A Streamable HTTP server answers prompts/list at once with its own -32001 error, and never answers tools/list:

error = {"code": -32001, "message": "Unauthorized"}          # prompts/list, HTTP 200, answered at once
async with ClientSession(read, write, read_timeout_seconds=0.5) as session:
    await session.list_prompts()   # the server answered
    await session.list_tools()     # the SDK gave up waiting
server answered  mcp.shared.exceptions.MCPError code=-32001 data=None message='Unauthorized'
SDK timed out    mcp.shared.exceptions.MCPError code=-32001 data=None message="Request 'tools/list' timed out"

The code is unchanged on main (77001c9):

Where What it raises
src/mcp/shared/jsonrpc_dispatcher.py:442 MCPError(code=REQUEST_TIMEOUT, message=f"Request {method!r} timed out")
src/mcp/shared/direct_dispatcher.py:288 MCPError(code=REQUEST_TIMEOUT, message=f"Timed out after {timeout}s waiting for {method!r}")
src/mcp/shared/jsonrpc_dispatcher.py:340, :413, direct_dispatcher.py:149, :231, client/session.py:1402 MCPError(code=CONNECTION_CLOSED, message="Connection closed")
src/mcp/client/streamable_http.py:522 (_resolve_abandoned_request) a synthesized -32000 error, e.g. "SSE stream ended without a response"

mcp_types/jsonrpc.py documents both codes as SDK-only, but servers use them too:

  • The TypeScript SDK's Streamable HTTP server answers an unknown session with -32001 "Session not found" (Clarify JSON-RPC error code for 'session not found' responses #1821, Raise a distinct error when a Streamable HTTP session is lost (HTTP 404) #3799).
  • In the wild, a hosted commerce MCP server answers a refused prompts/list with -32001 "UCP discovery failed" at HTTP 422, and an API-key-gated server answers every call with -32001 "X-API-Key header is required" at HTTP 200.
  • -32000 is the first code in the server range and the one servers most often pick for a generic error.
  • This SDK sends CONNECTION_CLOSED to the peer when shutdown interrupts a request (jsonrpc_dispatcher.py:765), so a client can receive it from another Python SDK server. This contradicts the "never emitted on the wire" note on the constant.

This matters to any caller that handles "no answer" differently from "the server said no". Retry logic should retry a timeout or a dropped connection, but not a server's refusal. Monitoring and audit tools should report "server is slow" or "server rejected the request", not mix the two up. Today a caller who checks exc.code == REQUEST_TIMEOUT treats a server's instant -32001 answer as a timeout. Matching the message text instead breaks silently whenever the wording changes.

Proposal

Raise dedicated MCPError subclasses for the SDK's own failures, keeping today's code, message and data. Existing except MCPError handlers and exc.code checks keep working. UrlElicitationRequiredError and NoBackChannelError already use this pattern, and #3799 proposes the same thing for a lost session.

class RequestTimeoutError(MCPError):
    """The SDK stopped waiting for a response; the peer never answered."""

class ConnectionClosedError(MCPError):
    """The connection closed before a response arrived."""
try:
    result = await session.list_tools()
except RequestTimeoutError:
    ...  # no answer: retry or report slowness
except ConnectionClosedError:
    ...  # reconnect
except MCPError as exc:
    ...  # the server answered with an error, whatever its code

An error that arrives from the peer (MCPError.from_error_data) stays a plain MCPError, even when its code is -32001 or -32000.

Tasks

  • Add RequestTimeoutError and ConnectionClosedError to src/mcp/shared/exceptions.py and export them next to MCPError.
  • Raise RequestTimeoutError at the timeout sites in jsonrpc_dispatcher.py and direct_dispatcher.py.
  • Raise ConnectionClosedError at the connection-closed sites in jsonrpc_dispatcher.py, direct_dispatcher.py and client/session.py.
  • Make the errors the client synthesizes for itself (streamable_http.py _resolve_abandoned_request with CONNECTION_CLOSED) surface as ConnectionClosedError, without changing errors that arrive from the server.
  • Update the CONNECTION_CLOSED note in mcp_types/jsonrpc.py, which says it is never emitted on the wire.
  • Add tests: a server error with code -32001 and one with -32000 each raise a plain MCPError; a real timeout and a real closed connection raise the new subclasses.
  • Document the new exceptions where client error handling is described.

Out of scope

Acceptance criteria

  • isinstance(exc, RequestTimeoutError) is true only when the SDK stopped waiting, and isinstance(exc, ConnectionClosedError) only when the connection closed before a response.
  • A server's own error with code -32001 or -32000 raises a plain MCPError whose code, message and data come from the server.
  • except MCPError and exc.code == REQUEST_TIMEOUT / CONNECTION_CLOSED checks behave as before for the SDK's own failures.

Activity

  1. bunnysayzz commented on Dec 2, 2026

    @bunnysayzz

    Same collision on my read of the code. The SDK raises plain MCPError with -32001/-32000 from jsonrpc_dispatcher.py (the timeout at :442, the closed-connection raises at :340/:413), which is the range servers use for their own errors, so the caller really cannot tell them apart without matching message text.

    Two shapes come to mind: distinct exception subclasses for the SDKs own timeout/close, or SDK-reserved codes outside the server-error range. The subclass route looks less breaking since existing except MCPError still catches them. Happy to work it up if you have a preference, or leave it for triage.

  2. MrStark65 commented on Dec 2, 2026

    @MrStark65

    Hi @a-akimov, I'm interested in working on this issue if it's still available.

    I would follow the proposed exception subclass approach, preserve the existing error codes, and add regression tests to distinguish SDK-side failures from server-returned errors.

    Please let me know if this approach is acceptable and whether the issue is available for contribution.

    Disclosure: AI-assisted drafting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions