Title: Cleanly terminated streamable-HTTP sessions are never deregistered: the DELETE path skips its own cleanup · Issue #3300 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: Cleanly terminated streamable-HTTP sessions are never deregistered: the DELETE path skips its own cleanup · Issue #3300 · modelcontextprotocol/python-sdk
X Title: Cleanly terminated streamable-HTTP sessions are never deregistered: the DELETE path skips its own cleanup · Issue #3300 · modelcontextprotocol/python-sdk
Description: Credit This was found and reported by @pete-builds in a comment on #3228, which ended with an offer to split it out. I own #3228, so I am taking them up on that. This is their finding, not an independent discovery. What this issue adds i...
Open Graph Description: Credit This was found and reported by @pete-builds in a comment on #3228, which ended with an offer to split it out. I own #3228, so I am taking them up on that. This is their finding, not an indep...
X Description: Credit This was found and reported by @pete-builds in a comment on #3228, which ended with an offer to split it out. I own #3228, so I am taking them up on that. This is their finding, not an indep...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/3300
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Cleanly terminated streamable-HTTP sessions are never deregistered: the DELETE path skips its own cleanup","articleBody":"### Credit\n\nThis was found and reported by @pete-builds in [a comment on #3228](https://github.com/modelcontextprotocol/python-sdk/issues/3228#issuecomment-5276126635), which ended with an offer to split it out. I own #3228, so I am taking them up on that. This is their finding, not an independent discovery.\n\nWhat this issue adds is **isolation**. The repro in that comment establishes each session with a bare `GET` (no `Accept: text/event-stream`), which is itself refused with 406 — so every session it counts was created by a *rejected* request, i.e. by #3228. That evidence cannot separate \"leaked because refused\" from \"leaked because DELETEd.\" The repro below establishes sessions with a real `initialize` handshake returning **200**, leaving the `DELETE` as the only variable.\n\nThis is **orthogonal to #3229**. That PR discards a session only when the *establishing* request returns ≥ 400; a successful `initialize` returns 200, so its branch never fires here. The run below is on the #3229 branch and still leaks.\n\n### Description\n\nOn the handshake-era streamable-HTTP path, a session terminated **cleanly** by `DELETE` is never removed from `StreamableHTTPSessionManager._server_instances`.\n\n`StreamableHTTPServerTransport.terminate()` sets `self._terminated = True` **before** closing the streams that let the session task unwind. When `run_server`'s `finally` block runs, its `and not http_transport.is_terminated` conjunct is false, so the `del` is skipped — for exactly the sessions that shut down correctly. The only other removal is `_server_instances.clear()` at manager shutdown.\n\nThe sharpest form of this is not \"a dict grows.\" It is that **the guard defeats the SDK's only mitigation, and penalizes well-behaved clients**: with `session_idle_timeout` configured, a session whose client simply vanishes *is* reclaimed; a session the client explicitly `DELETE`s is not. Terminating a session politely is strictly worse than abandoning it rudely.\n\n### Scope, stated up front\n\n- **Handshake-era path only** (`2024-11-05` … `2025-11-25`). `_handle_request` routes any `MCP-Protocol-Version` outside `HANDSHAKE_PROTOCOL_VERSIONS` to `handle_modern_request`, and `_streamable_http_modern.py` has zero references to `_server_instances`. The 2.x client default `mode=\"auto\"` negotiates `2026-07-28` and leaks nothing (scenario D below).\n- Sessions and `DELETE` carry `removed_in=\"2026-07-28\"` in this repo's own conformance table (SEP-2567). **This is a bug on a deprecated-but-still-supported path** — I would rather say that myself than have you say it.\n- It still covers the entire pre-2026 installed base and any `mode=\"legacy\"` client, where `terminate_on_close=True` is the default, so the `DELETE` is the happy path there.\n- `stateless_http=True` is immune. `session_idle_timeout` is **not** a workaround (scenario B) and is not a parameter of `streamable_http_app()` or `MCPServer` anyway.\n\n### Reproduction\n\nReal uvicorn on a real socket, this SDK's own client, no monkeypatching and no in-process ASGI shim.\n\n```\nA leaked : sessions=3 mode=legacy delete=True idle_timeout=None | registry immediate=3 after_checkpoints=3 after_2.0s=3 is_terminated=[True, True, True]\nB leaked : sessions=3 mode=legacy delete=True idle_timeout=0.3 | registry immediate=3 after_checkpoints=3 after_3.0s=3 is_terminated=[True, True, True]\nC reaped : sessions=3 mode=legacy delete=False idle_timeout=0.3 | registry immediate=3 after_checkpoints=3 after_3.0s=0 is_terminated=[]\nD modern : sessions=3 mode=auto delete=True idle_timeout=None | registry immediate=0 after_checkpoints=0 after_1.0s=0 is_terminated=[]\n```\n\n**B vs C is the whole bug.** Same idle timeout; the client that politely `DELETE`s leaks, the client that vanishes is reaped. The registry is drained through 1000 event-loop checkpoints plus a settle window before each count, so this is not a premature read.\n\n\u003cdetails>\n\u003csummary>repro.py\u003c/summary>\n\n```python\n\"\"\"Repro: streamable-HTTP session registry leak on cleanly terminated sessions.\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport socket\n\nimport anyio\nimport uvicorn\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\nfrom mcp.client.client import Client\nfrom mcp.client.streamable_http import streamable_http_client\nfrom mcp.server.lowlevel.server import Server\nfrom mcp.server.streamable_http_manager import StreamableHTTPSessionManager\nfrom mcp.server.transport_security import TransportSecuritySettings\n\n\ndef free_port() -> int:\n s = socket.socket()\n s.bind((\"127.0.0.1\", 0))\n port = s.getsockname()[1]\n s.close()\n return port\n\n\n@contextlib.asynccontextmanager\nasync def serve(manager: StreamableHTTPSessionManager):\n @contextlib.asynccontextmanager\n async def lifespan(_app):\n async with manager.run():\n yield\n\n star = Starlette(routes=[Mount(\"/mcp\", app=manager.handle_request)], lifespan=lifespan)\n port = free_port()\n server = uvicorn.Server(uvicorn.Config(star, host=\"127.0.0.1\", port=port, log_level=\"error\"))\n async with anyio.create_task_group() as tg:\n tg.start_soon(server.serve)\n for _ in range(500):\n if server.started:\n break\n await anyio.sleep(0.02)\n try:\n yield f\"http://127.0.0.1:{port}/mcp\"\n finally:\n server.should_exit = True\n await anyio.sleep(0.3)\n tg.cancel_scope.cancel()\n\n\nasync def scenario(\n name: str, *, n: int, mode: str, terminate_on_close: bool, idle_timeout: float | None, settle: float\n) -> None:\n manager = StreamableHTTPSessionManager(\n app=Server(\"repro\"),\n session_idle_timeout=idle_timeout,\n security_settings=TransportSecuritySettings(enable_dns_rebinding_protection=False),\n )\n async with serve(manager) as url:\n for _ in range(n):\n async with Client(streamable_http_client(url, terminate_on_close=terminate_on_close), mode=mode):\n pass\n immediate = len(manager._server_instances)\n for _ in range(1000): # drain every pending event-loop checkpoint\n await anyio.sleep(0)\n checkpoints = len(manager._server_instances)\n await anyio.sleep(settle)\n settled = len(manager._server_instances)\n terminated = [t.is_terminated for t in manager._server_instances.values()]\n print(\n f\"{name}: sessions={n} mode={mode} delete={terminate_on_close} idle_timeout={idle_timeout} \"\n f\"| registry immediate={immediate} after_checkpoints={checkpoints} \"\n f\"after_{settle}s={settled} is_terminated={terminated}\"\n )\n\n\nasync def main() -> None:\n await scenario(\"A leaked \", n=3, mode=\"legacy\", terminate_on_close=True, idle_timeout=None, settle=2.0)\n await scenario(\"B leaked \", n=3, mode=\"legacy\", terminate_on_close=True, idle_timeout=0.3, settle=3.0)\n await scenario(\"C reaped \", n=3, mode=\"legacy\", terminate_on_close=False, idle_timeout=0.3, settle=3.0)\n await scenario(\"D modern \", n=3, mode=\"auto\", terminate_on_close=True, idle_timeout=None, settle=1.0)\n\n\nanyio.run(main, backend=\"asyncio\")\n```\n\n\u003c/details>\n\nThe retained transport is inert — `terminate()` does empty `_request_streams` and `_sse_stream_writers`, and the orphan does not reference the `Server` app, the manager, the task group, tool arguments, or tool results. It is a dead stub of a few KB per session, never reclaimed, growing linearly. I am deliberately not quoting a precise byte figure: my two measurement harnesses disagreed by several KB because same-process client allocations contaminate both.\n\n`_session_owners` leaks identically — its `pop` sits inside the same `if` — but only when auth is in play, since it is written only for an `AuthenticatedUser`. It stores an `authorization_context(user)`; I checked that the raw bearer token is **not** reachable from it, so this is not credential retention.\n\n### Root cause\n\n`git log -S \"not http_transport.is_terminated\"` returns exactly one commit: `7b1078b5` *\"Fix: Prevent session manager shutdown on individual session crash (#841)\"*. The whole `try/except/finally` arrived there for **crash** cleanup, with the guard under the comment `# Only remove from instances if not terminated`.\n\nIt is not a race guard. The idle reaper did not exist yet, and every terminate path that exists today pops *before* calling `terminate()`, so the `in self._server_instances` check short-circuits first. What the guard actually buys is a nicer 404 body: retention routes post-`DELETE` requests to the transport's own `_terminated` check (`\"Not Found: Session has been terminated\"`) instead of the manager's `\"Session not found\"`.\n\n### Suggested fix\n\nPop in the same turn that answers the request, rather than leaving it to the session task's `finally`:\n\n```python\n# streamable_http_manager.py, existing-session branch, after handle_request:\n await transport.handle_request(scope, receive, send)\n+ if transport.is_terminated:\n+ self._server_instances.pop(request_mcp_session_id, None)\n+ self._session_owners.pop(request_mcp_session_id, None)\n return\n```\n\nplus dropping `and not http_transport.is_terminated` from the `finally` guard.\n\nDeregistering **synchronously** matters. Dropping the guard alone also fixes the leak, but then deregistration happens asynchronously a few event-loop checkpoints later, leaving a window where a follow-up request could observe either 404 body — a flaky assertion waiting to happen. With the patch above, `immediate=0` in every scenario.\n\n`SseServerTransport` is the clean counterexample: it pops `_session_owners` unconditionally in its `finally`, with no `is_terminated`-style guard. The streamable-HTTP manager is the outlier.\n\n### The objection you are going to raise\n\n`tests/interaction/transports/test_hosting_session.py` currently asserts `session_id in manager._server_instances`, with a comment framing the retention as deliberate — \"the manager keeps the terminated transport registered, so the next request reaches the transport's own `_terminated` check.\"\n\n**This fix does change observable behavior, and I would rather flag that than have it found in review.** The post-termination 404 body changes from `\"Not Found: Session has been terminated\"` to `\"Session not found\"`, and that 404 stops echoing `Mcp-Session-Id`. That assertion and its snapshot would need updating.\n\nWhy I think it is still right:\n\n- The status code (404) and JSON-RPC error code (-32600) are unchanged, and the conformance requirement `hosting:session:post-termination-404` reads *\"answered with 404 Not Found\"* — status only, no body. The spec's MUST is on the status code.\n- The special message was never reliable. Idle-reaped, crashed, and gracefully-exited sessions have **always** answered `\"Session not found\"`; only `DELETE` got the nicer string. Three of four termination modes already behave the way this fix makes the fourth behave.\n- Session ids are `uuid4().hex`, so a forgotten id can never be revived — the manager's unknown-session branch answers 404 for it indefinitely.\n- A deliberate tombstone would be a bounded set of ids with eviction, not a permanent strong reference to a whole transport in two dicts with no reclamation path.\n\n### Prior art\n\n- **#791** — *\"Clean up sessions from manager when terminated via DELETE request\"*, the same defect on 1.x. Self-closed by the author in May 2025 with no maintainer review. It used an `on_session_terminated` callback.\n- **#1283** — closed *not planned*; that one is about **idle** sessions and explicitly disclaims this case. Resolved by the idle-timeout work in #1994/#2022, which does not reach terminated sessions.\n- **#3192** (open, transport rewrite) re-adds the identical guard, so this would survive that refactor.\n\nI am happy to open a PR with the fix and the test updates if you would like it.\n\n### Environment\n\nReproduced on `upstream/main` and on the #3229 branch. Also present in released `mcp` 1.29.0 per @pete-builds' original report.\n","author":{"url":"https://github.com/sainikhiljuluri","@type":"Person","name":"sainikhiljuluri"},"datePublished":"2026-08-13T05:44:51Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/3300"}
| 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:0e624c9b-8610-2642-58da-775ee62b5e8d |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8354:E9EFB:37E578:4CA414:6B00B594 |
| html-safe-nonce | 36b06a95cd8fc11d0ea0cc7f9727cf7401c55917a246c0162159ce6546291135 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4MzU0OkU5RUZCOjM3RTU3ODo0Q0E0MTQ6NkIwMEI1OTQiLCJ2aXNpdG9yX2lkIjoiNTI4NDEwNTkyNzI2MjY3Mjg0IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 8115c5da79f4cd09753993b0740889891a8575b052fc9ec10ff8340e956bb05e |
| hovercard-subject-tag | issue:5138222050 |
| 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/3300/issue_layout |
| twitter:image | https://opengraph.githubassets.com/f6091512ac6e65e20047f96ae40f083dfc443c1edf3bed51a85b7e76a8fa3373/modelcontextprotocol/python-sdk/issues/3300 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/f6091512ac6e65e20047f96ae40f083dfc443c1edf3bed51a85b7e76a8fa3373/modelcontextprotocol/python-sdk/issues/3300 |
| og:image:alt | Credit This was found and reported by @pete-builds in a comment on #3228, which ended with an offer to split it out. I own #3228, so I am taking them up on that. This is their finding, not an indep... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | sainikhiljuluri |
| hostname | github.com |
| expected-hostname | github.com |
| None | 1d07c25977adfc5ff6acb0a962a9bc168c07afbda6fef765f9761c350c2ae4a2 |
| 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 | 5429cbfc6aca8c7b9a086a3c8f47400346f38cc9 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width