fix(session): return INVALID_REQUEST error instead of crashing on pre-init requests#2411
fix(session): return INVALID_REQUEST error instead of crashing on pre-init requests#2411Smeet23 wants to merge 1 commit into
Conversation
…-init requests When an MCP client sends a request (e.g. tools/list) before completing the initialize handshake, the server now responds with a proper INVALID_REQUEST JSON-RPC error instead of raising a RuntimeError that propagates through the anyio task group and crashes the ASGI application. This affects real-world clients such as Cursor, MCP Inspector, and anything-llm that skip re-initialization after a server restart or dropped SSE connection. Github-Issue: modelcontextprotocol#423
|
Hi team — just a gentle ping on this PR. All checks are passing. Would appreciate a review when you get a chance. Happy to address any feedback. Thanks! |
|
Thanks @Smeet23 for putting this patch together. We build an MCP server using this library and bundle it in Docker. Whenever we rebuild the image, connected clients have to reconnect to the new container. If we forget to reconnect the client, its next tool call hits this pre-init path and the user (or the AI agent driving the client) sees We worked around it with a monkey-patch on This PR would make our workaround obsolete: it solves the same problem at the source, in a cleaner way (uses the spec-aligned |
Problem
When an MCP client sends a request (e.g.
tools/list) before completing theinitializehandshake, the server raises aRuntimeErrorthat propagates through the anyio task group and crashes the entire ASGI application:This affects real-world clients such as Cursor, MCP Inspector, and anything-llm that skip re-initialization after a server restart or dropped SSE connection. The server dies instead of returning a useful error.
Fixes #423.
Solution
Replace the
raise RuntimeError(...)inServerSession._received_requestwith a proper JSON-RPCINVALID_REQUEST(-32600) error response sent via the responder. The server stays alive and the client receives a meaningful error it can act on.Test
Added
test_request_before_initialization_returns_errortotests/server/test_session.pythat sends atools/listrequest without any priorinitializehandshake and asserts that:JSONRPCErrorwith codeINVALID_REQUESTExceptionGroup)