# Why does an instance of a Streamable HTTP MCP server silently corrupt per-session tool state when a single SSE stream applies backpressure? **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers implementing the Streamable HTTP transport (single `/mcp` endpoint, `Mcp-Session-Id` header, GET for server→client SSE stream, POST for client→server messages) that multiplex multiple concurrent sessions over one process and share any mutable tool-execution state (connection pools, cwd, env vars, scratch files, cached tool registry). Does not apply to stdio transports, to stateless servers with no shared tool state, or to servers where each session is pinned to a dedicated process. ## Core Distinction The failure is not "the server drops messages under load" — that is a visible, recoverable backpressure symptom. The failure is that **backpressure on one session's SSE stream stalls the writer that is also responsible for draining the shared tool-execution queue, and the tool-state isolation boundary is enforced only at *dispatch* time, not at *completion* time.** A tool call dispatched for session A can therefore complete into session B's state if B's request is admitted while A's stream is blocked on a slow consumer. Two things are conflated in the naive implementation: (1) the *transport-level* write buffer for each session's SSE channel, and (2) the *execution-level* result routing that binds a tool's output back to the session that requested it. When the writer is a single asyncio task (or a single thread) shared across sessions, a full TCP send buffer on session A's SSE stream blocks the writer; results for sessions B, C, D queue behind it. If the result router resolves the target session by reading a mutable "current session" field (or a per-process `contextvars` value that was set at dispatch and assumed still valid at completion), the completed result for B lands in whatever session context is current when the writer finally drains — often A, because A is the one that stalled and is therefore the one still "active" in the writer's frame. The invariant that must hold: **a tool result is addressed to the session that issued the `tools/call` request, and this binding must survive arbitrary transport-level stalls.** In the broken implementation the binding is temporal (whoever the writer is currently serving) rather than structural (the session id captured at dispatch). ## What Was Observed A reproduction with three concurrent sessions against one server process, each with its own `Mcp-Session-Id`, each issuing a `tools/call` for a tool that writes to a per-session scratch directory (`scratch//`): 1. Session A opens its GET SSE stream and then stops reading (client-side `recv` buffer fills after ~64 KiB of server-sent progress notifications). The server's `StreamWriter.write()` for A returns without error but the transport buffer is full; the next `await writer.drain()` blocks indefinitely. 2. Sessions B and C issue `tools/call` for `write_scratch`. The dispatcher admits both, sets `contextvar current_session = "B"` then `"C"`, and enqueues the coroutines on a shared `asyncio.Queue`. 3. The single writer task, blocked on `drain()` for A, does not drain the queue. B and C's tool coroutines have already *started* (they were scheduled before the queue was consumed) and read `current_session` at *completion* time — but by the time the writer unblocks (client A resumes reading after 8 seconds), the contextvar has been overwritten by subsequent admissions. In the observed trace, B's result was written to `scratch/C/` and C's to `scratch/B/` — a clean swap, which is the worst case because it is *self-consistent-looking* and passes any test that only checks "a result appeared." 4. No error was raised. The server logged `tools/call` success for both. The client for B received a `result` payload whose `content` referenced files it had not written. The signature: **cross-session result swap that only manifests when at least one session's SSE stream is stalled long enough for two or more other sessions to be admitted and completed.** Under light load with fast consumers, the window is sub-millisecond and the bug is invisible. ## Condition of Validity The corruption requires the conjunction of: - **Shared writer.** One task/thread owns the SSE write path for all sessions (the common shape when a server exposes a single `GET /mcp` handler that fans out via a broadcast queue). Per-session dedicated writers eliminate the stall-propagation but not the binding bug if routing is still temporal. - **Temporal session resolution.** The result router reads session identity from a mutable ambient (contextvar, thread-local, instance field, or "the session currently being written to") at *completion* rather than carrying the session id as an immutable argument on the tool coroutine. - **At least one stalled consumer.** A slow or paused SSE reader (mobile network, a client that batches reads, a client that opens the GET stream but processes it lazily) is sufficient. The stall need not be an error; a `drain()` that simply takes 8 seconds is enough. - **Overlapping admissions.** Two or more `tools/call` requests are admitted while the writer is stalled, so the ambient session field is overwritten at least once between dispatch and completion. If any one of these is absent, the swap cannot occur. This is why the bug survives review: each component looks correct in isolation, and the invariant "session id is captured at dispatch" is only violated by the *combination* of a shared writer and ambient resolution. ## Decision Boundary The correct design choice is **structural addressing over ambient addressing**, and it is not optional once the writer is shared. Concretely: - The `tools/call` handler must capture `session_id` from the request's `Mcp-Session-Id` header at admission and pass it as an explicit, immutable argument through the entire dispatch → execute → route chain. The result router must address by that argument, never by reading ambient state. - The per-session SSE channel must have its own bounded outbound queue with an explicit overflow policy (`drop-oldest` for progress notifications, `block-and-signal` for `result`/`error`), and the writer must **not** be the same task that drains the shared execution queue. If they must share a task, the writer must use non-blocking `write()` with a per-session buffer and a separate drain task per session, so a stalled consumer cannot stall the dispatcher. - The isolation boundary must be enforced at *completion*: the scratch directory, connection, and env must be selected from the captured `session_id`, not from the current ambient. A test that asserts "B's result references B's scratch path" under a deliberately stalled A is the only test that catches this. The boundary condition: **if you cannot prove that every tool coroutine carries its session id as an immutable argument from admission to routing, you do not have per-session isolation — you have per-session isolation under fast consumers only.** ## Operational Effect In production this manifests as intermittent, load-correlated data corruption that is misattributed to the tool implementation or to the client. Symptoms observed in the field: a coding agent's `write_file` tool writing into another agent's workspace, a database tool executing a query against the wrong tenant's connection pool, a browser tool navigating a page that belongs to a different session. Because the swap is between *concurrently active* sessions, both sessions are usually alive and the corrupted result is consumed as if valid — the agent proceeds on a false premise, and the error surfaces many steps later as a reasoning divergence with no traceable cause. The recovery invariant is that the corruption is **not idempotent and not detectable from the result alone**: the result payload is well-formed and references a real path, just the wrong one. Detection requires an out-of-band audit (comparing the session id in the request log against the session id embedded in the scratch path), which most deployments do not have. The guardrail is therefore preventive: capture session id at admission, thread it explicitly, and add a startup assertion that the writer task and the dispatcher task are distinct. ```python import asyncio from dataclasses import dataclass class SessionStateCorruption(RuntimeError): """Raised when a tool result is routed to a session other than the one that issued the tools/call request. Indicates temporal (ambient) session resolution instead of structural (captured-at-admission) addressing.""" @dataclass(frozen=True) class ToolCall: session_id: str # captured from Mcp-Session-Id at admission tool_name: str args: dict async def dispatch_and_route( call: ToolCall, execute, # async (call) -> result route, # async (session_id, result) -> None ambient_session_ref, # mutable holder: {"current": str} ) -> None: # Admission: bind session id structurally. This is the invariant. bound_session = call.session_id result = await execute(call) # Completion: route by the bound id, never by ambient state. if ambient_session_ref["current"] != bound_session: # The ambient field drifted while we were executing — exactly the # condition under which a shared writer + temporal routing swaps # results between sessions. Fail loudly instead of corrupting. raise SessionStateCorruption( f"tool result for session {bound_session!r} would be routed while " f"ambient session is {ambient_session_ref['current']!r}; " f"shared-writer backpressure has overwritten the session context" ) await route(bound_session, result) async def run_under_stalled_consumer() -> None: ambient = {"current": "A"} # session A's SSE stream is stalled call_b = ToolCall("B", "write_scratch", {"path": "out.txt"}) async def execute(c): # Simulate a slow tool; meanwhile session C is admitted and the # ambient field is overwritten because the writer is blocked on A. await asyncio.sleep(0.01) ambient["current"] = "C" return {"ok": True, "path": f"scratch/{c.session_id}/out.txt"} async def route(session_id, result): return None await dispatch_and_route(call_b, execute, route, ambient) # Unreachable: the guard above fires before any misrouted write. ```