Raise distinct errors for the SDK's own request timeout and closed connection, not a server's -32001/-32000
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 55/100
- Tipo de issue
- Nueva funcionalidad
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- python
- Área
- backend-api-design, testing
Línea de trabajo
Start by reading src/mcp/shared/exceptions.py and the timeout and connection closed sites named in jsonrpc_dispatcher.py, direct_dispatcher.py, and client/session.py; then inspect streamable_http.py at _resolve_abandoned_request. Trace how peer errors are created so they remain plain MCPError, and review the tests and client error handling documentation. Done means SDK timeouts and closed connections use the new subclasses while server errors with the same codes remain plain MCPError.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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"(#1821, #3799). - In the wild, a hosted commerce MCP server answers a refused
prompts/listwith-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. -32000is the first code in the server range and the one servers most often pick for a generic error.- This SDK sends
CONNECTION_CLOSEDto 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
RequestTimeoutErrorandConnectionClosedErrortosrc/mcp/shared/exceptions.pyand export them next toMCPError. - Raise
RequestTimeoutErrorat the timeout sites injsonrpc_dispatcher.pyanddirect_dispatcher.py. - Raise
ConnectionClosedErrorat the connection-closed sites injsonrpc_dispatcher.py,direct_dispatcher.pyandclient/session.py. - Make the errors the client synthesizes for itself (
streamable_http.py_resolve_abandoned_requestwithCONNECTION_CLOSED) surface asConnectionClosedError, without changing errors that arrive from the server. - Update the
CONNECTION_CLOSEDnote inmcp_types/jsonrpc.py, which says it is never emitted on the wire. - Add tests: a server error with code
-32001and one with-32000each raise a plainMCPError; 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
- Changing the numeric values of
REQUEST_TIMEOUTorCONNECTION_CLOSED. That would break callers that check the code, and the subclasses make it unnecessary. - Which JSON-RPC code servers should use for "session not found" (#1821).
Acceptance criteria
isinstance(exc, RequestTimeoutError)is true only when the SDK stopped waiting, andisinstance(exc, ConnectionClosedError)only when the connection closed before a response.- A server's own error with code
-32001or-32000raises a plainMCPErrorwhosecode,messageanddatacome from the server. except MCPErrorandexc.code == REQUEST_TIMEOUT/CONNECTION_CLOSEDchecks behave as before for the SDK's own failures.
- Lenguaje dominante
- Python
- Estrellas
- 25k
- Forks
- 4.2k
- Merge medio
- 10 min
- PR fusionados (30 d)
- 1
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de modelcontextprotocol/python-sdk
-
v2
Dificultad 1/5 Menos de una hora Aptitud para principiantes 86/100
modelcontextprotocol/python-sdk#3978 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
Client serves cached tools after its context exits with an exceptionPosiblemente ocupada @jonxsong la tomó hace 1 día. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
modelcontextprotocol/python-sdk#3968 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
modelcontextprotocol/python-sdk#3957 ·
Los mantenedores suelen responder en 1 día
-
v2
Dificultad 1/5 Menos de una hora Aptitud para principiantes 91/100
modelcontextprotocol/python-sdk#3934 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
bug v1
Dificultad 2/5 1-3 horas Aptitud para principiantes 79/100
modelcontextprotocol/python-sdk#3929 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
Todos los issues de modelcontextprotocol/python-sdk
Issues similares
-
soup prune-prompt exits 1 after writing its output on a file over 100,000 rows, and reports a capped row count otherwisePosiblemente ocupada @abdulwaarith0 la tomó hoy. Abiertoneeds-triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
MakazhanAlpamys/Soup#3690 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
-
bug data-types native-format
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
ClickHouse/clickhouse-connect#1320 ·
Los mantenedores suelen responder en 1 día
-
Public benchmark import end-to-end test fails when the test stack's worker runs the parity jobAbiertoaccepted
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
future-agi/future-agi#6392 ·
Los mantenedores suelen responder en 1 día