Title: StreamableHTTP client: _handle_reconnection resets attempt counter to 0, causing infinite retry loop · Issue #2393 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: StreamableHTTP client: _handle_reconnection resets attempt counter to 0, causing infinite retry loop · Issue #2393 · modelcontextprotocol/python-sdk
X Title: StreamableHTTP client: _handle_reconnection resets attempt counter to 0, causing infinite retry loop · Issue #2393 · modelcontextprotocol/python-sdk
Description: Bug Description _handle_reconnection() in streamable_http.py resets the attempt counter to 0 on line 494 when a reconnection succeeds but the stream ends without delivering a complete response. This makes MAX_RECONNECTION_ATTEMPTS ineffe...
Open Graph Description: Bug Description _handle_reconnection() in streamable_http.py resets the attempt counter to 0 on line 494 when a reconnection succeeds but the stream ends without delivering a complete response. Thi...
X Description: Bug Description _handle_reconnection() in streamable_http.py resets the attempt counter to 0 on line 494 when a reconnection succeeds but the stream ends without delivering a complete response. Thi...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/2393
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"StreamableHTTP client: _handle_reconnection resets attempt counter to 0, causing infinite retry loop","articleBody":"## Bug Description\n\n`_handle_reconnection()` in `streamable_http.py` resets the `attempt` counter to `0` on line 494 when a reconnection succeeds but the stream ends without delivering a complete response. This makes `MAX_RECONNECTION_ATTEMPTS` ineffective — the counter only applies to consecutive exceptions, not total reconnection attempts. If the server accepts the connection but the stream drops repeatedly, the client retries forever.\n\n## Reproduction\n\n**MCP version:** 1.26.0 (also confirmed unpatched in 1.27.0 `main` branch)\n\n### SSCE — Minimal reproducer\n\n**Server** (`server.py`): A server that accepts SSE connections but closes them before sending a complete response, with a `last-event-id` header to trigger the reconnection path.\n\n```python\n\"\"\"Minimal MCP server that drops SSE streams to trigger infinite reconnect.\"\"\"\nimport asyncio\nfrom starlette.applications import Starlette\nfrom starlette.routing import Route\nfrom starlette.responses import Response\nfrom sse_starlette.sse import EventSourceResponse\nimport uvicorn, json, uuid\n\nsession_id = str(uuid.uuid4())\n\nasync def handle_mcp(request):\n if request.method == \"POST\":\n body = await request.json()\n method = body.get(\"method\")\n\n if method == \"initialize\":\n resp = {\n \"jsonrpc\": \"2.0\",\n \"id\": body[\"id\"],\n \"result\": {\n \"protocolVersion\": \"2025-06-18\",\n \"capabilities\": {\"tools\": {}},\n \"serverInfo\": {\"name\": \"drop-server\", \"version\": \"0.1.0\"},\n },\n }\n return Response(\n json.dumps(resp),\n media_type=\"application/json\",\n headers={\"mcp-session-id\": session_id},\n )\n\n if method == \"notifications/initialized\":\n return Response(status_code=202, headers={\"mcp-session-id\": session_id})\n\n if method == \"tools/call\":\n # Return SSE that sends a priming event with an ID, then drops\n async def event_generator():\n yield {\"event\": \"message\", \"id\": \"evt-1\", \"data\": \"\"}\n # Close without sending the actual response\n return\n\n return EventSourceResponse(\n event_generator(),\n headers={\"mcp-session-id\": session_id},\n )\n\n return Response(status_code=404)\n\n if request.method == \"GET\":\n # GET stream for server-initiated messages — also drop immediately\n async def get_stream():\n yield {\"event\": \"message\", \"id\": \"evt-get-1\", \"data\": \"\"}\n return\n\n return EventSourceResponse(\n get_stream(),\n headers={\"mcp-session-id\": session_id},\n )\n\n if request.method == \"DELETE\":\n return Response(status_code=200)\n\napp = Starlette(routes=[Route(\"/mcp\", handle_mcp, methods=[\"POST\", \"GET\", \"DELETE\"])])\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"0.0.0.0\", port=9999)\n```\n\n**Client** (`client.py`): Connects and calls a tool, demonstrating the infinite loop.\n\n```python\n\"\"\"Client that demonstrates infinite reconnection loop.\"\"\"\nimport asyncio, logging\nlogging.basicConfig(level=logging.INFO)\n\nfrom mcp import ClientSession\nfrom mcp.client.streamable_http import streamable_http_client\n\nasync def main():\n async with streamable_http_client(\"http://localhost:9999/mcp\") as (read, write, _):\n async with ClientSession(read, write) as session:\n await session.initialize()\n print(\"Initialized. Calling tool (will hang forever)...\")\n # This call will trigger _handle_reconnection with attempt=0 reset\n try:\n result = await asyncio.wait_for(\n session.call_tool(\"any_tool\", {}),\n timeout=30,\n )\n except asyncio.TimeoutError:\n print(\"CONFIRMED: call_tool hung for 30s (infinite reconnect loop)\")\n\nasyncio.run(main())\n```\n\n### Steps\n\n1. `pip install mcp[cli] sse-starlette uvicorn`\n2. Run server: `python server.py`\n3. Run client: `python client.py`\n4. Observe: client logs show repeated `\"GET stream disconnected, reconnecting in 1000ms...\"` messages. The `call_tool` never returns. After 30s the `wait_for` timeout fires, confirming the hang.\n\n## Root Cause\n\nIn `streamable_http.py`, `_handle_reconnection` (line 437):\n\n```python\nasync def _handle_reconnection(self, ctx, last_event_id, retry_interval_ms, attempt=0):\n if attempt >= MAX_RECONNECTION_ATTEMPTS: # Only 2\n return\n\n # ... reconnects, iterates SSE ...\n\n # Line 494: Stream ended without response — resets attempt to 0!\n await self._handle_reconnection(ctx, reconnect_last_event_id, reconnect_retry_ms, 0)\n```\n\nWhen the reconnection *succeeds* (HTTP 200) but the stream ends without a complete `JSONRPCResponse`, line 494 recurses with `attempt=0`, restarting the counter. Only the exception path (line 498) increments the counter. A server that accepts connections but drops streams causes infinite recursion at 1-second intervals.\n\n## Expected Behavior\n\nAfter `MAX_RECONNECTION_ATTEMPTS` total reconnection attempts (regardless of whether they succeeded at the HTTP level), the client should give up and propagate an error to the caller.\n\n## Suggested Fix\n\nTrack total attempts across the recursion rather than resetting on successful connect:\n\n```python\n# Line 494: increment instead of reset\nawait self._handle_reconnection(ctx, reconnect_last_event_id, reconnect_retry_ms, attempt + 1)\n```\n\nOr add a separate `max_total_reconnection_attempts` counter that is never reset.\n\n## Impact\n\nIn production, this causes MCP client coroutines to hang forever when a server experiences transient stream drops. The calling application has no way to recover without wrapping every MCP call in `asyncio.wait_for()`. We discovered this when an agentquant research job hung for 5+ hours in a reconnection loop after an MCP server's SSE stream dropped.","author":{"url":"https://github.com/jeffplourde","@type":"Person","name":"jeffplourde"},"datePublished":"2026-04-05T11:29:06Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/2393"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:16128a6c-55ed-e59a-e9c2-5f8b6f272c76 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | CED0:25A204:344A4C:46C0D3:6B00C508 |
| html-safe-nonce | c056ed449c7e2ac25cfd08cee7b051153257eedf8c45cfa674a6e267b3268a45 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDRUQwOjI1QTIwNDozNDRBNEM6NDZDMEQzOjZCMDBDNTA4IiwidmlzaXRvcl9pZCI6IjUxNjAwODg0NDY5NjU5NTc4OTYiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 96954e1819e4ce556fbc03cfa916d3d3cff883595f1eba98b5e2a5380a4ae1fa |
| hovercard-subject-tag | issue:4207294746 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/2393/issue_layout |
| twitter:image | https://opengraph.githubassets.com/db03275a57b237b415df0a349facc8278b5b0b6a037f512e9c6b90ea0716e0d7/modelcontextprotocol/python-sdk/issues/2393 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/db03275a57b237b415df0a349facc8278b5b0b6a037f512e9c6b90ea0716e0d7/modelcontextprotocol/python-sdk/issues/2393 |
| og:image:alt | Bug Description _handle_reconnection() in streamable_http.py resets the attempt counter to 0 on line 494 when a reconnection succeeds but the stream ends without delivering a complete response. Thi... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | jeffplourde |
| hostname | github.com |
| expected-hostname | github.com |
| None | 93edd3bebc4afb7ce711ee74cb5d2a95927850b082a4d43e212222389cb1c415 |
| turbo-cache-control | no-preview |
| go-import | github.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git |
| octolytics-dimension-user_id | 182288589 |
| octolytics-dimension-user_login | modelcontextprotocol |
| octolytics-dimension-repository_id | 862584018 |
| octolytics-dimension-repository_nwo | modelcontextprotocol/python-sdk |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 862584018 |
| octolytics-dimension-repository_network_root_nwo | modelcontextprotocol/python-sdk |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 1fee81a280ea86312b69448e261b418189bfd5b5 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width