python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

Rejected streamable-HTTP requests leave live sessions behind: the session is registered before the request is validated

Open sainikhiljuluri opened this issue 4 months ago • 5 comments

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 session task before the request has been validated in any way. Every actual check lives downstream in the transport, so a request the server itself refuses — 400, 406, or 421 — still leaves a fully registered, non-terminated session behind.

Nothing reclaims it. session_idle_timeout defaults to None and is not reachable from streamable_http_app() (that half is #2455), so the only reaper cannot be switched on by an operator using the documented API.

Not filed as a security issue, and why

I originally wrote this up as a vulnerability report and then talked myself out of it, so it seems worth stating plainly rather than leaving you to work it out.

It is unauthenticated, remotely triggerable, present on the documented default configuration, and retains roughly 22.6 KiB per rejected request (measured two independent ways, ~2,240 req/s from a single client). But it grants an attacker nothing they did not already have: on the same no-auth server, 200 valid initialize requests create 200 sessions — verified — so unbounded session growth is already reachable with entirely legitimate traffic. Closing the rejected-request path does not change that, and I am not claiming otherwise. The real availability gap is the absence of a session cap plus an idle reaper that is off by default and unreachable, which is #2455.

So this is a correctness / defense-in-depth defect, and a public issue is the honest channel for it.

What is worth fixing regardless of any attacker

  1. Requests the server itself refuses leave live state behind — which contradicts a property the test suite already asserts by name for the 413 path (see below).
  2. Requests blocked by the default-on DNS-rebinding protection (421) create a session anyway, so a security control fires and state is created regardless.
  3. Ordinary incidental traffic — scanners, health checks, a stray probe at /mcp — accumulates sessions forever on a default server.
  4. A refused 406 still returns a usable Mcp-Session-Id, and a follow-up request on that never-initialized id is served 200 by the leaked session's running server loop. An unauthenticated caller obtains a working session handle from a request the server rejected.

Affected

Any server built the documented way — MCPServer(...).streamable_http_app(), Server(...).streamable_http_app(), or mcp.run("streamable-http") — i.e. stateless_http=False (default), session_idle_timeout=None (default).

Not affected: stateless_http=True (transport terminated per request); servers behind RequireAuthMiddleware, where 401 is returned before the manager runs; requests carrying MCP-Protocol-Version: 2026-07-28, which route to the sessionless modern handler. Note that header is client-controlled — omitting it selects the sessionful path — so it is not something an operator can rely on.

Root cause

src/mcp/server/streamable_http_manager.py, _handle_stateful_request: the branch is taken purely on request_mcp_session_id is None. Inside it the code mints uuid4().hex, constructs a StreamableHTTPServerTransport, inserts it into self._server_instances, and await self._task_group.start(run_server) — and only then calls http_transport.handle_request(...), which is where every check lives (Host / DNS-rebinding, Accept, Content-Type, JSON parse, JSON-RPC validation, and the "Missing session ID" check for non-initialize POSTs).

No error path calls terminate() or pops the dict, and run_server's finally only runs when the session task exits — which it never does, because serve_loop blocks on its read stream and the idle scope has no deadline when session_idle_timeout is None.

Steps to reproduce

Default configuration, zero arguments. _server_instances is only read, to observe the effect.

import anyio, httpx2 as httpx
from mcp.server.lowlevel import Server

server = Server("leak-probe")
app = server.streamable_http_app()          # no arguments: the documented default
mgr = server.session_manager

HDRS = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json"}

async def main():
    async with anyio.create_task_group() as tg:
        await tg.start(serve)
        async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),
                                     base_url="http://localhost:8000") as c:
            before = len(mgr._server_instances)
            for _ in range(300):
                await c.post("/mcp", json={"jsonrpc": "2.0", "id": 1,
                                           "method": "tools/list", "params": {}}, headers=HDRS)
            after = len(mgr._server_instances)
            live = sum(1 for t in mgr._server_instances.values() if not t.is_terminated)
            print(f"sessions {before} -> {after}; non-terminated: {live}")
        tg.cancel_scope.cancel()

async def serve(*, task_status):
    async with mgr.run():
        task_status.started()
        await anyio.sleep_forever()

anyio.run(main)

Actual behaviour

Every session-less vector leaks exactly one session, each rejected with a different status:

vector status session leaked
GET no session id 400 yes
DELETE no session id 400 yes
POST non-initialize 400 yes
POST malformed body 400 yes
POST bad Accept 406 yes
GET bad Host (DNS-rebinding protection) 421 yes

300 rejected POSTs → sessions 2 -> 302, exactly one per request, 302 non-terminated transports still registered.

The one pre-session guard that does exist works correctly: an oversized declared body is rejected 413 by RequestBodyLimitMiddleware with no session created.

Expected behaviour

A request the server refuses does not leave a registered, non-terminated session behind, and a refused response does not hand back a usable Mcp-Session-Id.

Why this is not already covered

  • #2455 (open) — session_idle_timeout not exposed via streamable_http_app() — covers only the unreachable-mitigation half. It does not mention that a rejected request creates a session.
  • #1283 (closed) — idle-session memory growth — concerns legitimate sessions from real clients accumulating, and was closed by the idle-timeout feature, which is off by default.
  • #3129 (open PR) — "return 405 for pre-session GET the server won't serve as SSE" — its own comment says "Reject with 405 BEFORE creating any transport or session to avoid leaking resources", so the concern is understood — but the guard is request.method == "GET" only. The POST and DELETE vectors above survive it unchanged.
  • #3192 (open PR) rewrites the transport but leaves the relevant manager block byte-for-byte.

Existing evidence this is unintended

tests/server/test_streamable_http_manager.py contains test_oversized_content_length_is_rejected_before_body_read_or_session_creation, asserting manager._server_instances == {}. "Rejected without creating a session" is already treated as the desired property — it was simply only implemented for the 413 path.

docs/run/legacy-clients.md likewise describes session creation as a consequence of initialize: "The moment a pre-2026 client sends initialize, the SDK mints an Mcp-Session-Id … and keeps a live record behind it."

Suggested fix

Two shapes; you are better placed to choose.

A. Only initialize may establish a session. When there is no session id, reject anything that is not a POST carrying an initialize request before creating a transport. Most faithful to the documented model, and subsumes #3129. Cost: the manager must peek the body, which currently lives in the transport (is_initialization_request).

B. Discard a provisional session whose establishing request was refused. Wrap send to observe the response status; if >= 400, pop the session and terminate() the transport. Smaller, needs no body parsing. I have a working patch that closes all vectors in the table (0 leaked across 300 requests) while a legitimate initialize still establishes a session and follow-up requests still return 200.

One thing to know before fixing, whichever shape you pick

tests/server/test_streamable_http_manager.py currently establishes sessions via requests the transport rejects: _open_session POSTs an empty body, which is answered 400/406 and yet returns a session id. Eight tests depend on it, so any correct fix fails them until that helper uses a real initialize. The suite encodes the buggy behaviour as the way to obtain a session, which is plausibly why this went unnoticed.

With patch B applied and no test changes the suite is 5572 passed / 8 failed — all 8 in that one file, all from that helper. Rewriting it is not a one-liner: a successful initialize in SSE mode keeps handle_request open, so the helper must read the response headers without waiting for the stream to finish.

Disclosure

Investigated with AI assistance (Claude Code). Filed by me as the human contributor. Happy to open a PR once you have indicated which fix shape you prefer.

sainikhiljuluri avatar Jul 30 '26 20:07 sainikhiljuluri

Good catch on the session registration ordering. The root issue is that StreamableHTTPSessionManager treats session creation as a pre-validation step, while the actual request validation lives downstream in the transport. Flipping the order — validate first, then register — is the correct fix, but there are some subtleties worth calling out:

Why validation-before-registration is tricky here:

The session_id is generated before validation because the transport needs it to construct the response headers (specifically Mcp-Session-Id). But you can generate the ID, validate the request, and only then call _server_instances[sid] = transport — the ID itself doesn't need to be registered to be generated.

Two concrete fix approaches:

  1. Deferred registration: Generate the session ID early (for header construction), but defer _server_instances insertion until after the transport's handle_request() returns a non-error status. If validation fails, the ID is simply discarded — it was never registered, so there's nothing to clean up.

  2. Validation gate in the manager: Move the basic validation (method check, Accept header, content-type for POST) into StreamableHTTPSessionManager itself, before the transport is even consulted. This catches 400/406 before we allocate anything.

Approach 1 is lower-risk because it doesn't duplicate validation logic.

On session_idle_timeout:

The #2455 issue you referenced is the real longer-term fix — without it, even valid sessions accumulate unboundedly. The session_idle_timeout parameter exists in the code but isn't wired to streamable_http_app(). For operators running 36+ connectors (our case at corpusiq.io), session accumulation is the #1 memory leak vector — we had to add external session reaping before the SDK exposed it. Wiring that parameter through the public API surface would solve both the legitimate-session growth and the rejected-request leak at once.

Quick fix for operators hitting this now:

Until the SDK fix lands, a reverse proxy rate limit on the MCP endpoint (e.g., 50 POST/min per IP for the initialize method specifically) provides effective mitigation — rejected requests still leak sessions, but at a bounded rate that won't exhaust memory before the process restarts.

Ben-Home avatar Jul 31 '26 00:07 Ben-Home

Independent confirmation on the released line, plus one behavior that I think is a separate defect from the one described here.

Reproduced on mcp 1.29.0 from PyPI (this issue is against 2.x main), lowlevel Server wired straight to StreamableHTTPSessionManager with stock defaults, no FastMCP. Session counts read from _server_instances, 100 requests per probe:

GET      -> 406   +100 sessions
HEAD     -> 405   +100 sessions
OPTIONS  -> 405   +100 sessions

GET + DELETE -> DELETE returns 200, +100 sessions
total still registered in _server_instances: 400

refused GET returned 406 with Mcp-Session-Id: 4dfad7d0d20e4c8e888e10ed5ab56ca1
  reusing it on a valid SSE GET -> 200

Three notes.

1. It covers 405 as well, so the property is method-independent. HEAD and OPTIONS are refused with 405 from inside StreamableHTTPServerTransport.handle_request, which runs after the session is already registered. So the "server refuses the request and keeps the session anyway" behavior is not limited to 400/406/421; it includes requests whose method the transport does not implement at all.

2. A successful DELETE does not deregister the session either. This is the one I would flag as distinct from this issue. 100 GETs, each followed by a DELETE of the returned session id, all returning 200, still leave +100 entries in _server_instances.

The cause is in run_server's finally:

if (http_transport.mcp_session_id
        and http_transport.mcp_session_id in self._server_instances
        and not http_transport.is_terminated):
    del self._server_instances[http_transport.mcp_session_id]

terminate() sets _terminated = True before the session task unwinds, so the cleanup is skipped for exactly the sessions that shut down cleanly. The transport's own streams are closed, so most of the memory is released, but the registry entry is permanent and the dict grows without bound.

That is the well-behaved client path rather than the rejected-request path, so a fix scoped to "validate before registering" would not address it. Happy to split it into its own issue if you would rather keep this one focused.

3. Confirming your RequireAuthMiddleware exemption. I checked this because I had assumed the opposite. 300 unauthenticated requests behind auth return 401 and create zero sessions, with no session-id header, since the middleware wraps the ASGI app and returns before the manager runs. Your "not affected" note is correct, and it is worth keeping visible: it is the difference between this being reachable pre-auth and post-auth.

Reproduction (SDK only, uv run)
# /// script
# requires-python = ">=3.10"
# dependencies = ["mcp==1.29.0", "httpx>=0.27", "uvicorn>=0.30", "starlette>=0.37"]
# ///
import contextlib, socket, threading, time
import httpx, uvicorn
from starlette.applications import Starlette
from starlette.routing import Mount
from mcp.server.lowlevel import Server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager

N = 100
manager = StreamableHTTPSessionManager(app=Server("repro"))  # stateful, no idle timeout

async def handle(scope, receive, send):
    await manager.handle_request(scope, receive, send)

@contextlib.asynccontextmanager
async def lifespan(app):
    async with manager.run():
        yield

app = Starlette(routes=[Mount("/mcp", app=handle)], lifespan=lifespan)

with socket.socket() as s:
    s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error"))
threading.Thread(target=server.run, daemon=True).start()
while not server.started:
    time.sleep(0.05)

base = f"http://127.0.0.1:{port}/mcp/"
sessions = lambda: len(manager._server_instances)

with httpx.Client(timeout=10.0) as c:
    for method in ("GET", "HEAD", "OPTIONS"):
        before, status = sessions(), None
        for _ in range(N):
            status = c.request(method, base).status_code
        print(f"{method:<8} -> {status}   +{sessions() - before} sessions")

    before = sessions()
    for _ in range(N):
        sid = c.get(base).headers.get("mcp-session-id")
        if sid:
            d = c.request("DELETE", base, headers={"Mcp-Session-Id": sid}).status_code
    print(f"\nGET + DELETE -> DELETE returns {d}, +{sessions() - before} sessions")
    print(f"total still registered: {sessions()}")

pete-builds avatar Aug 13 '26 04:08 pete-builds

Thanks — this is a genuinely useful report, and confirming it on the released line rather than main is the part I could not do myself.

On 405. You are right that the property is method-independent, and it is a better framing than the one I opened with. _handle_unsupported_request runs downstream of registration exactly like the validation failures, and it echoes the session id back the same way. The fix in #3229 already covers it without a production change, because it keys off the establishing response status (>= 400) rather than an enumerated list of validation failures — so 405 was subsumed by construction. I have pushed a commit adding HEAD and OPTIONS params to that PR's test so a later refactor cannot narrow the predicate and silently reopen the method-independent half. Credited to you in the commit message.

On DELETE. Confirmed, and I have split it out as #3300 as you offered. Your root-cause read is exactly right: terminate() sets _terminated = True before the streams close, so run_server's finally guard skips the del for precisely the sessions that shut down cleanly.

One thing worth flagging about the evidence, since it took me a while to convince myself. Your probe establishes each session with c.get(base) — a bare GET with no Accept: text/event-stream — which the transport refuses with 406. So all 100 sessions in the GET + DELETE row were created by a request that was itself rejected, which is the defect this issue describes. The numbers are real, but they cannot separate "leaked because refused" from "leaked because DELETEd." I re-ran it establishing sessions with a real initialize returning 200, which leaves the DELETE as the only variable, and it still leaks — so the conclusion holds, it just needed a cleaner isolation to be safe from that objection in review.

The sharpest version turned out to be a contrast rather than a count. Same idle timeout, two clients:

B  legacy, client DELETEs on close,  idle_timeout=0.3  ->  3 of 3 still registered after 3s
C  legacy, client just vanishes,     idle_timeout=0.3  ->  0    reaped correctly

The polite client is punished and the rude one is cleaned up. That reads better to a maintainer than "the dict grows," and it also makes clear that session_idle_timeout is not a workaround.

Two scope corrections I put in #3300 that are worth knowing here, because they cut against us: the leak is confined to the handshake-era path — the 2.x client default mode="auto" negotiates 2026-07-28, routes to handle_modern_request, and never touches _server_instances at all (measured 0 entries) — and sessions plus DELETE are marked removed_in="2026-07-28" in this repo's own conformance table. So it is a real bug on a deprecated-but-supported path covering the entire pre-2026 installed base, which is a narrower claim than either of us started with. There is also prior art in #791, which fixed this on 1.x in May 2025 and was self-closed without review.

On the auth exemption. Thanks for checking it independently — that is the kind of confirmation that is easy to skip because it only produces a negative result.

sainikhiljuluri avatar Aug 13 '26 05:08 sainikhiljuluri

Confirming this with production numbers on mcp 1.27.1. In one 18.2 hour run, 109 of 224 created sessions came from POST /mcp requests that ended in 400. In streamable_http_manager.py, self._server_instances[http_transport.mcp_session_id] = http_transport runs at line 254 and the task is started at line 303, but the request is not validated until http_transport.handle_request(...) at line 306 (validation lives in streamable_http.py:487-505 / _validate_request_headers at line 825). A request that fails validation therefore leaves a fully registered session and a live run_server task behind, with no client and no way to ever reach them again, since the client never learned the session id.

The ordering is unchanged in 2.0.0 (streamable_http_manager.py:302 registers, then the request is handled), so the fix is still needed there.

Suggested fix: either validate before registering, or register only after handle_request has produced a non-error response, or pop the session id and terminate the transport when the initializing request is rejected.

finedesignz avatar Aug 19 '26 16:08 finedesignz

Thanks @finedesignz — production numbers are the thing this issue was missing, and yours are worse than I expected. 109 of 224 sessions in an 18.2 hour window is roughly half of everything the manager registered being unreachable garbage.

Consolidating what's now on the thread, since it's spread across two issues:

Source Line Evidence
@pete-builds released 1.29.0 400 leaked sessions across GET/HEAD/OPTIONS/DELETE probes; also found refusals hand back a usable Mcp-Session-Id
@finedesignz released 1.27.1 109/224 sessions leaked in 18.2h of production traffic
this issue 2.x main ordering unchanged — register at streamable_http_manager.py:302, validate inside handle_request at :359

Three independent reproductions on three different versions, one of them from production.

@finedesignz your third suggested option — pop the session id and terminate the transport when the establishing request is rejected — is what #3229 implements. It keys off the establishing response status rather than an enumerated list of validation failures, so it also covers the 405 case @pete-builds found (HEAD/OPTIONS are refused by _handle_unsupported_request, which runs downstream of registration in the same way). CI is green there.

Two process notes rather than a nudge:

#3229 is still a draft. I opened it that way by mistake and can't flip it — markPullRequestReadyForReview needs write access on the base repo, so it returns FORBIDDEN for the PR's own author. It needs a maintainer to either mark it ready or assign me to this issue, at which point require-linked-issue is satisfied too. Happy for someone else to carry the fix instead if that's easier — the diff is small and the approach is in the PR.

Also worth noting the leak has no deployable mitigation on the affected path: session_idle_timeout defaults to None and isn't exposed by streamable_http_app(), MCPServer, or FastMCP, so a server built the documented way can't configure the reaper at all. Given that plus @finedesignz's ~49% figure, the current P3 may be worth a second look — entirely your call.

sainikhiljuluri avatar Aug 19 '26 17:08 sainikhiljuluri