Title: Rejected streamable-HTTP requests leave live sessions behind: the session is registered before the request is validated · Issue #3228 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: Rejected streamable-HTTP requests leave live sessions behind: the session is registered before the request is validated · Issue #3228 · modelcontextprotocol/python-sdk
X Title: Rejected streamable-HTTP requests leave live sessions behind: the session is registered before the request is validated · Issue #3228 · modelcontextprotocol/python-sdk
Description: Release line 2.x (main), reproduced at a4f4ccd0. Bug description In the default stateful streamable-HTTP configuration, StreamableHTTPSessionManager mints a session id, registers a transport in _server_instances, and starts a long-lived ...
Open Graph Description: Release line 2.x (main), reproduced at a4f4ccd0. Bug description In the default stateful streamable-HTTP configuration, StreamableHTTPSessionManager mints a session id, registers a transport in _se...
X Description: Release line 2.x (main), reproduced at a4f4ccd0. Bug description In the default stateful streamable-HTTP configuration, StreamableHTTPSessionManager mints a session id, registers a transport in _se...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/3228
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Rejected streamable-HTTP requests leave live sessions behind: the session is registered before the request is validated","articleBody":"### Release line\n\n2.x (`main`), reproduced at `a4f4ccd0`.\n\n### Bug description\n\nIn the default stateful streamable-HTTP configuration, `StreamableHTTPSessionManager` mints a\nsession id, registers a transport in `_server_instances`, and starts a long-lived session task\n**before the request has been validated in any way**. Every actual check lives downstream in the\ntransport, so a request the server itself refuses — `400`, `406`, or `421` — still leaves a fully\nregistered, non-terminated session behind.\n\nNothing reclaims it. `session_idle_timeout` defaults to `None` and is not reachable from\n`streamable_http_app()` (that half is #2455), so the only reaper cannot be switched on by an\noperator using the documented API.\n\n### Not filed as a security issue, and why\n\nI originally wrote this up as a vulnerability report and then talked myself out of it, so it seems\nworth stating plainly rather than leaving you to work it out.\n\nIt is unauthenticated, remotely triggerable, present on the documented default configuration, and\nretains roughly **22.6 KiB per rejected request** (measured two independent ways, ~2,240 req/s from a\nsingle client). But **it grants an attacker nothing they did not already have**: on the same no-auth\nserver, 200 *valid* `initialize` requests create 200 sessions — verified — so unbounded session\ngrowth is already reachable with entirely legitimate traffic. Closing the rejected-request path does\nnot change that, and I am not claiming otherwise. The real availability gap is the absence of a\nsession cap plus an idle reaper that is off by default and unreachable, which is #2455.\n\nSo this is a correctness / defense-in-depth defect, and a public issue is the honest channel for it.\n\n### What is worth fixing regardless of any attacker\n\n1. Requests the server *itself refuses* leave live state behind — which contradicts a property the\n test suite already asserts by name for the `413` path (see below).\n2. Requests blocked by the default-on DNS-rebinding protection (`421`) create a session anyway, so a\n security control fires and state is created regardless.\n3. Ordinary incidental traffic — scanners, health checks, a stray probe at `/mcp` — accumulates\n sessions forever on a default server.\n4. **A refused `406` still returns a usable `Mcp-Session-Id`**, and a follow-up request on that\n never-initialized id is served `200` by the leaked session's running server loop. An unauthenticated\n caller obtains a working session handle from a request the server rejected.\n\n### Affected\n\nAny server built the documented way — `MCPServer(...).streamable_http_app()`,\n`Server(...).streamable_http_app()`, or `mcp.run(\"streamable-http\")` — i.e. `stateless_http=False`\n(default), `session_idle_timeout=None` (default).\n\nNot affected: `stateless_http=True` (transport terminated per request); servers behind\n`RequireAuthMiddleware`, where `401` is returned before the manager runs; requests carrying\n`MCP-Protocol-Version: 2026-07-28`, which route to the sessionless modern handler. Note that header\nis client-controlled — omitting it selects the sessionful path — so it is not something an operator\ncan rely on.\n\n### Root cause\n\n`src/mcp/server/streamable_http_manager.py`, `_handle_stateful_request`: the branch is taken purely\non `request_mcp_session_id is None`. Inside it the code mints `uuid4().hex`, constructs a\n`StreamableHTTPServerTransport`, inserts it into `self._server_instances`, and\n`await self._task_group.start(run_server)` — and only *then* calls `http_transport.handle_request(...)`,\nwhich is where every check lives (Host / DNS-rebinding, `Accept`, `Content-Type`, JSON parse,\nJSON-RPC validation, and the \"Missing session ID\" check for non-`initialize` POSTs).\n\nNo error path calls `terminate()` or pops the dict, and `run_server`'s `finally` only runs when the\nsession task exits — which it never does, because `serve_loop` blocks on its read stream and the idle\nscope has no deadline when `session_idle_timeout is None`.\n\n### Steps to reproduce\n\nDefault configuration, zero arguments. `_server_instances` is only *read*, to observe the effect.\n\n```python\nimport anyio, httpx2 as httpx\nfrom mcp.server.lowlevel import Server\n\nserver = Server(\"leak-probe\")\napp = server.streamable_http_app() # no arguments: the documented default\nmgr = server.session_manager\n\nHDRS = {\"Accept\": \"application/json, text/event-stream\", \"Content-Type\": \"application/json\"}\n\nasync def main():\n async with anyio.create_task_group() as tg:\n await tg.start(serve)\n async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),\n base_url=\"http://localhost:8000\") as c:\n before = len(mgr._server_instances)\n for _ in range(300):\n await c.post(\"/mcp\", json={\"jsonrpc\": \"2.0\", \"id\": 1,\n \"method\": \"tools/list\", \"params\": {}}, headers=HDRS)\n after = len(mgr._server_instances)\n live = sum(1 for t in mgr._server_instances.values() if not t.is_terminated)\n print(f\"sessions {before} -> {after}; non-terminated: {live}\")\n tg.cancel_scope.cancel()\n\nasync def serve(*, task_status):\n async with mgr.run():\n task_status.started()\n await anyio.sleep_forever()\n\nanyio.run(main)\n```\n\n### Actual behaviour\n\nEvery session-less vector leaks exactly one session, each rejected with a different status:\n\n| vector | status | session leaked |\n|---|---|---|\n| `GET` no session id | 400 | yes |\n| `DELETE` no session id | 400 | yes |\n| `POST` non-`initialize` | 400 | yes |\n| `POST` malformed body | 400 | yes |\n| `POST` bad `Accept` | 406 | yes |\n| `GET` bad `Host` (DNS-rebinding protection) | 421 | yes |\n\n300 rejected POSTs → `sessions 2 -> 302`, exactly one per request, 302 non-terminated transports\nstill registered.\n\nThe one pre-session guard that *does* exist works correctly: an oversized declared body is rejected\n`413` by `RequestBodyLimitMiddleware` with no session created.\n\n### Expected behaviour\n\nA request the server refuses does not leave a registered, non-terminated session behind, and a\nrefused response does not hand back a usable `Mcp-Session-Id`.\n\n### Why this is not already covered\n\n- **#2455** (open) — `session_idle_timeout` not exposed via `streamable_http_app()` — covers only the\n unreachable-mitigation half. It does not mention that a rejected request creates a session.\n- **#1283** (closed) — idle-session memory growth — concerns *legitimate* sessions from real clients\n accumulating, and was closed by the idle-timeout feature, which is off by default.\n- **#3129** (open PR) — \"return 405 for pre-session GET the server won't serve as SSE\" — its own\n comment says *\"Reject with 405 BEFORE creating any transport or session to avoid leaking resources\"*,\n so the concern is understood — but the guard is `request.method == \"GET\"` only. The POST and DELETE\n vectors above survive it unchanged.\n- **#3192** (open PR) rewrites the transport but leaves the relevant manager block byte-for-byte.\n\n### Existing evidence this is unintended\n\n`tests/server/test_streamable_http_manager.py` contains\n`test_oversized_content_length_is_rejected_before_body_read_or_session_creation`, asserting\n`manager._server_instances == {}`. \"Rejected without creating a session\" is already treated as the\ndesired property — it was simply only implemented for the `413` path.\n\n`docs/run/legacy-clients.md` likewise describes session creation as a consequence of `initialize`:\n*\"The moment a pre-2026 client sends `initialize`, the SDK mints an `Mcp-Session-Id` … and keeps a\nlive record behind it.\"*\n\n### Suggested fix\n\nTwo shapes; you are better placed to choose.\n\n**A. Only `initialize` may establish a session.** When there is no session id, reject anything that is\nnot a POST carrying an `initialize` request *before* creating a transport. Most faithful to the\ndocumented model, and subsumes #3129. Cost: the manager must peek the body, which currently lives in\nthe transport (`is_initialization_request`).\n\n**B. Discard a provisional session whose establishing request was refused.** Wrap `send` to observe\nthe response status; if `>= 400`, pop the session and `terminate()` the transport. Smaller, needs no\nbody parsing. I have a working patch that closes **all** vectors in the table (0 leaked across 300\nrequests) while a legitimate `initialize` still establishes a session and follow-up requests still\nreturn `200`.\n\n### One thing to know before fixing, whichever shape you pick\n\n`tests/server/test_streamable_http_manager.py` currently establishes sessions *via requests the\ntransport rejects*: `_open_session` POSTs an empty body, which is answered `400`/`406` and yet returns\na session id. Eight tests depend on it, so any correct fix fails them until that helper uses a real\n`initialize`. The suite encodes the buggy behaviour as the way to obtain a session, which is plausibly\nwhy this went unnoticed.\n\nWith patch B applied and no test changes the suite is 5572 passed / 8 failed — all 8 in that one file,\nall from that helper. Rewriting it is not a one-liner: a successful `initialize` in SSE mode keeps\n`handle_request` open, so the helper must read the response headers without waiting for the stream to\nfinish.\n\n### Disclosure\n\nInvestigated with AI assistance (Claude Code). Filed by me as the human contributor. Happy to open a\nPR once you have indicated which fix shape you prefer.\n","author":{"url":"https://github.com/sainikhiljuluri","@type":"Person","name":"sainikhiljuluri"},"datePublished":"2026-07-30T20:45:47Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/3228"}
| 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:a0f4fb5b-bfe6-2eab-7448-30edb25ea160 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BF2E:229F8E:7FCC55:AA1037:6B00B186 |
| html-safe-nonce | bee63f5fc1cdf0aa67578ed11b894ceaeef46484a1b0d320c6e45e67adaeb301 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCRjJFOjIyOUY4RTo3RkNDNTU6QUExMDM3OjZCMDBCMTg2IiwidmlzaXRvcl9pZCI6IjI2MjAxMDA3NDI5NDU0ODUxOTAiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | d377b3da22d040dc503c2f5e5d2573356efc256ae8f1e8db64eece9eaa6e6a15 |
| hovercard-subject-tag | issue:5023849010 |
| 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/3228/issue_layout |
| twitter:image | https://opengraph.githubassets.com/c4fe711ea2a42ac354f93a959d2f41ace49c6c52747c9ed9c11805bf30c821f2/modelcontextprotocol/python-sdk/issues/3228 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/c4fe711ea2a42ac354f93a959d2f41ace49c6c52747c9ed9c11805bf30c821f2/modelcontextprotocol/python-sdk/issues/3228 |
| og:image:alt | Release line 2.x (main), reproduced at a4f4ccd0. Bug description In the default stateful streamable-HTTP configuration, StreamableHTTPSessionManager mints a session id, registers a transport in _se... |
| 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 | c0dd5f5d6f515a591019ecd66df2c4eab3379c2d3b0777568a90d8c7ae10b79e |
| 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 | 729d8cda69b3d267995675dfbf89ff27ccf61bf6 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width