Title: Server stop hangs while a 2026-07-28 subscriptions/listen stream is open · Issue #3806 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: Server stop hangs while a 2026-07-28 subscriptions/listen stream is open · Issue #3806 · modelcontextprotocol/python-sdk
X Title: Server stop hangs while a 2026-07-28 subscriptions/listen stream is open · Issue #3806 · modelcontextprotocol/python-sdk
Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before openi...
Open Graph Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontex...
X Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/mod...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/3806
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Server stop hangs while a 2026-07-28 subscriptions/listen stream is open","articleBody":"### Initial Checks\n\n- [x] I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)\n- [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue\n\n### Release line\n\n2.x (current stable)\n\n### Description\n\nWhile a 2026-07-28 client has a `subscriptions/listen` stream open, the server does not stop on SIGTERM. uvicorn logs `Waiting for connections to close.` and waits until the process is killed.\n\n**Why.** The listen stream is served by `handle_modern_request` in `mcp/server/_streamable_http_modern.py`. Its SSE loop (in 2.3.0, lines 499 to 524: `with anyio.move_on_after(_SSE_PING_INTERVAL): event = await recv_ch.receive()`, then a ping) ends only when the handler completes or when `watch_disconnect` sees the client go away. Nothing ends it when the server shuts down. uvicorn's `Server.shutdown` waits for every open connection before it runs the lifespan shutdown, inside `asyncio.wait_for(self._wait_tasks_to_complete(), timeout=config.timeout_graceful_shutdown)`, and that timeout defaults to `None`. So the wait has no end, and the session manager's own shutdown cannot help: it runs in the lifespan, which uvicorn reaches only after the connections close.\n\n**The 2025-era stream on the same server does stop.** A `2025-06-18` GET stream is an sse-starlette `EventSourceResponse`, which watches uvicorn's exit and ends itself, so the same server exits in 0.6 s. The 2026-07-28 path writes `http.response.body` messages directly (`grep -c EventSourceResponse` is 6 in `streamable_http.py` and 0 in `_streamable_http_modern.py`), so it does not get that behaviour.\n\n**Expected.** Open 2026-07-28 SSE responses, `subscriptions/listen` in particular, end when the server shuts down (for example by watching for uvicorn's exit the way `EventSourceResponse` does), so the stop completes without a timeout or forced cancellation.\n\n**Impact.** Under systemd every stop waits out `TimeoutStopSec` (90 s by default) and ends in SIGKILL, and `docker stop` kills after 10 s. On two production servers with five long-lived client streams open on each, every stop over 30 days, 12 of 12, logged `Waiting for connections to close.` and ended in SIGKILL after 90 s. On staging servers with the same clients, every task uvicorn cancelled under the workaround below was this listen handler.\n\n**Workaround.** `uvicorn.run(..., timeout_graceful_shutdown=5)`. uvicorn then cancels the stream after 5 s and the stop completes (5.2 s below), but the stop logs `ERROR: Cancel N running task(s), timeout graceful shutdown exceeded` once and each open stream logs an `Exception in ASGI application` traceback ending in `CancelledError`. Applied downstream in rstierli/fortimanager-mcp#113 and rstierli/fortianalyzer-mcp#165, where it took a production-like stop from 90.2 s (SIGKILL) to 5.2 s.\n\n**Related, not the same path.** #1272 (stop hangs with a client connected, reported before the 2026-07-28 path existed; the 2025-06-18 control below no longer hangs on 2.3.0), #2150 (the session manager cancels open streams at shutdown without a response), and #2181 (a session-manager-side fix, closed unmerged). A fix in the session manager's shutdown would not reach this case, for the ordering reason above.\n\n### Example Code\n\n```Python\n# server.py\n\"\"\"Minimal MCP server: one tool, streamable HTTP, uvicorn defaults.\"\"\"\nimport sys\n\nimport uvicorn\nfrom mcp.server.mcpserver import MCPServer\n\nmcp = MCPServer(\"shutdown-repro\")\n\n\n@mcp.tool()\ndef ping() -> str:\n return \"pong\"\n\n\nif __name__ == \"__main__\":\n graceful = float(sys.argv[2]) if len(sys.argv) > 2 else None\n uvicorn.run(mcp.streamable_http_app(), host=\"127.0.0.1\", port=int(sys.argv[1]), timeout_graceful_shutdown=graceful)\n```\n\n```Python\n# repro.py\n\"\"\"Time how long server.py takes to exit on SIGTERM while one client stream is open.\n\n python repro.py # 2026-07-28 subscriptions/listen stream\n python repro.py legacy # 2025-06-18 GET stream, for comparison\n python repro.py 5 # listen stream, uvicorn timeout_graceful_shutdown=5\n\"\"\"\n\nimport http.client\nimport json\nimport os\nimport signal\nimport socket\nimport subprocess\nimport sys\nimport time\n\nPORT = 18900\nlegacy = \"legacy\" in sys.argv[1:]\ngraceful = [a for a in sys.argv[1:] if a != \"legacy\"]\nhere = os.path.dirname(os.path.abspath(__file__))\nserver = subprocess.Popen(\n [sys.executable, os.path.join(here, \"server.py\"), str(PORT), *graceful],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,\n env={**os.environ, \"PYTHONUNBUFFERED\": \"1\"},\n)\nfor _ in range(100):\n try:\n socket.create_connection((\"127.0.0.1\", PORT), timeout=0.2).close()\n break\n except OSError:\n time.sleep(0.1)\n\n\ndef post(body, headers):\n conn = http.client.HTTPConnection(\"127.0.0.1\", PORT, timeout=60)\n conn.request(\"POST\", \"/mcp\", body=json.dumps(body), headers={\n \"Content-Type\": \"application/json\", \"Accept\": \"application/json, text/event-stream\", **headers})\n return conn, conn.getresponse()\n\n\nif legacy:\n _, r = post({\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\", \"params\": {\n \"protocolVersion\": \"2025-06-18\", \"capabilities\": {}, \"clientInfo\": {\"name\": \"repro\", \"version\": \"0\"}}}, {})\n r.read()\n session = {\"mcp-session-id\": r.getheader(\"mcp-session-id\"), \"MCP-Protocol-Version\": \"2025-06-18\"}\n post({\"jsonrpc\": \"2.0\", \"method\": \"notifications/initialized\"}, session)[1].read()\n stream = http.client.HTTPConnection(\"127.0.0.1\", PORT, timeout=60)\n stream.request(\"GET\", \"/mcp\", headers={\"Accept\": \"text/event-stream\", **session})\n r = stream.getresponse()\n time.sleep(1)\nelse:\n meta = {\n \"io.modelcontextprotocol/protocolVersion\": \"2026-07-28\",\n \"io.modelcontextprotocol/clientInfo\": {\"name\": \"repro\", \"version\": \"0\"},\n \"io.modelcontextprotocol/clientCapabilities\": {},\n }\n stream, r = post(\n {\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"subscriptions/listen\",\n \"params\": {\"_meta\": meta, \"notifications\": {\"toolsListChanged\": True}}},\n {\"MCP-Protocol-Version\": \"2026-07-28\", \"Mcp-Method\": \"subscriptions/listen\"},\n ) # the response starts at the first ping, about 15 s in\nprint(f\"stream open: HTTP {r.status} {r.getheader('content-type')}\")\n\nt0 = time.monotonic()\nserver.send_signal(signal.SIGTERM)\ntry:\n server.wait(timeout=30)\n print(f\"server exited {time.monotonic() - t0:.1f} s after SIGTERM\")\nexcept subprocess.TimeoutExpired:\n print(\"server still running 30.0 s after SIGTERM, killing it\")\n server.kill()\n server.wait()\nfor line in server.stdout.read().splitlines():\n if any(k in line for k in (\"Shutting down\", \"Waiting for\", \"Cancel \", \"Finished server\")):\n print(\" \" + line)\n```\n\nOutput with mcp 2.3.0:\n\n```\n$ python repro.py\nstream open: HTTP 200 text/event-stream\nserver still running 30.0 s after SIGTERM, killing it\n INFO: Waiting for application startup.\n INFO: Shutting down\n INFO: Waiting for connections to close. (CTRL+C to force quit)\n\n$ python repro.py legacy\nstream open: HTTP 200 text/event-stream\nserver exited 0.6 s after SIGTERM\n INFO: Waiting for application startup.\n INFO: Shutting down\n INFO: Waiting for connections to close. (CTRL+C to force quit)\n INFO: Waiting for application shutdown.\n INFO: Finished server process [51748]\n\n$ python repro.py 5\nstream open: HTTP 200 text/event-stream\nserver exited 5.2 s after SIGTERM\n INFO: Waiting for application startup.\n INFO: Shutting down\n INFO: Waiting for connections to close. (CTRL+C to force quit)\n ERROR: Cancel 1 running task(s), timeout graceful shutdown exceeded\n INFO: Waiting for application shutdown.\n INFO: Finished server process [52313]\n```\n\n### Python & MCP Python SDK\n\n```Text\nReproduced with both:\n Python 3.15.2, mcp 2.3.0, uvicorn 0.54.0, sse-starlette 3.6.0 (macOS)\n Python 3.12.16, mcp 2.1.1, uvicorn 0.49.0, sse-starlette 3.4.5 (macOS)\nSeen in production on Linux with Python 3.12, mcp 2.0.0 and 2.1.1, uvicorn 0.49.0.\nThe listen handler on main has the same shape (no shutdown handling) as in 2.3.0.\n```\n","author":{"url":"https://github.com/inxbit","@type":"Person","name":"inxbit"},"datePublished":"2026-11-02T22:55:30Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/3806"}
| 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:ae7382e8-a4e7-9209-6463-aa8cfc81814c |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9A14:30AF58:1B29B67:25F515A:6AFD0238 |
| html-safe-nonce | e3b0b99895ad18788fbba1098c00570e353414f2fec814f86bca83b676197a0f |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5QTE0OjMwQUY1ODoxQjI5QjY3OjI1RjUxNUE6NkFGRDAyMzgiLCJ2aXNpdG9yX2lkIjoiOTAwMTAwNDM4ODk4MTczNTk5MiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 3136123e4a1d3b54a2254503d919f80ed09241264f0e194e0cfe1cbeb04b2c80 |
| hovercard-subject-tag | issue:6172549421 |
| 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/3806/issue_layout |
| twitter:image | https://opengraph.githubassets.com/b0daf99b72d5d93568756280532d383ed01f25f4a445a3d90316e87d312a9348/modelcontextprotocol/python-sdk/issues/3806 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/b0daf99b72d5d93568756280532d383ed01f25f4a445a3d90316e87d312a9348/modelcontextprotocol/python-sdk/issues/3806 |
| og:image:alt | Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontex... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | inxbit |
| hostname | github.com |
| expected-hostname | github.com |
| None | 8fd5a24ae29aa78df114eaaf1f9a839e8c3b7c0d27549e4f54678bb7cf3166d4 |
| 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 | dd0990b833f227378ab84f1d9519db1a04660550 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width