You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
StreamableHTTPServerTransport: TOCTOU race between GET 409 conflict check and standalone SSE slot registration allows concurrent GET streams #3891
In src/mcp/server/streamable_http.py (StreamableHTTPServerTransport._handle_get_request), the check rejecting a second standalone GET SSE stream (if GET_STREAM_KEY in self._request_streams: -> 409 Conflict) and the registration of self._request_streams[GET_STREAM_KEY] are not atomic:
The conflict check runs synchronously in _handle_get_request() (~line 768).
The slot is only inserted inside the async standalone_sse_writer() task (~line 783), which sse-starlette's EventSourceResponse schedules via task_group.start_soon(...) after the response begins.
By contrast, both POST paths register self._request_streams[request_id] synchronously before yielding control.
When two GET /mcp (Accept: text/event-stream) requests arrive concurrently for the same session:
Both pass if GET_STREAM_KEY in self._request_streams: before either standalone_sse_writer() runs.
Both return HTTP 200 instead of [200, 409].
The second writer overwrites self._request_streams[GET_STREAM_KEY], leaving the first stream orphaned (receiving no server-initiated messages), and when the first connection later closes its finally cleanup closes the second connection's active stream.
Minimal Reproduction
In tests/shared/test_streamable_http.py, dispatch two concurrent GET /mcp streams for the same initialized session via anyio.create_task_group():
Register self._request_streams[GET_STREAM_KEY] synchronously in _handle_get_request() immediately after the GET_STREAM_KEY in self._request_streams conflict check (matching the POST paths), reuse standalone_stream_reader inside standalone_sse_writer(), and ensure await self._clean_up_memory_streams(GET_STREAM_KEY) runs in the finally: block to cover cancellation/errors before standalone_sse_writer() starts.
Verified locally: concurrent GET test fails [200, 200] before the fix and passes [200, 409] after, with full test_streamable_http.py + ruff/pyright clean. Happy to submit a PR if helpful.
AI disclosure: AI assistance was used to help investigate and draft this issue; the reproduction and observed output were verified locally.
Opened a branch with a fix for this: fix/3891-get-stream-toctou on my fork.
Root cause._handle_get_request made the 409 decision by inspecting self._request_streams, but the slot itself was only inserted inside standalone_sse_writer(), which EventSourceResponse starts after the response has begun. Two concurrent GETs therefore both ran the check against a mapping without the key, both were accepted with 200, and the second writer replaced the first slot, orphaning the first stream and letting its cleanup close the second connection's stream.
The fix registers self._request_streams[GET_STREAM_KEY] synchronously immediately after the conflict check, matching the two POST paths, and takes the reader from that registration instead of creating the stream inside the writer. Cleanup moved into the request's finally and now runs before the SSE streams are closed, so a request cancelled before its writer starts cannot leak the slot, and a GET that registers after this slot is popped is never torn down by this request.
Before, on main@77001c96: 1 failed, 73 passed, the new test failing with AssertionError: assert [200, 200] == [200, 409].
After: 74 passed.
Branch coverage for src/mcp/server/streamable_http.py across the transport related test modules: 100.00% (427 statements, 118 branches, 0 missed, 0 partial). ruff check and ruff format --check clean.
One existing test, test_standalone_stream_teardown_between_dequeues_is_not_an_error, relied on registration happening inside the writer to know the writer was parked at dequeue. It now waits for a waiting receiver on the buffered stream before sending, which keeps the same scenario deterministic without the old timing assumption.
AI assisted preparation: the reproduction, the fix and the test runs above were executed locally with AI assistance.
This is a very subtle and critical race condition for high-concurrency MCP servers.
Beyond Synchronous Insertion: Two Edge Cases to Address
Moving the slot insertion synchronously into _handle_get_request() directly closes the TOCTOU window, but in production HTTP transports, two secondary failure modes must be guarded:
1. The Premature Disconnect Lockout (Two-Phase Claim & Rollback)
If the slot is claimed synchronously before returning the EventSourceResponse, what happens if Starlette/Uvicorn fails during response initialization (e.g. client resets TCP connection before TLS handshake completes, or middleware throws an error)?
If the slot is stored as a bare entry without an auto-reaping timeout or rollback, that session key becomes permanently stuck in a "claimed" state, causing all future legitimate reconnects to fail with 409 Conflict.
Remediation: Treat slot reservation as a two-phase state machine:
PENDING: Claimed synchronously during routing.
ACTIVE: Promoted when the first SSE event / comment heartbeat is written.
If PENDING exceeds an inactivity timeout (e.g. 5.0s) without promoting to ACTIVE, the slot automatically expires to allow recovery.
2. Monotonic Generation Fencing Against Delayed Teardowns
Consider this sequence under network jitter:
Stream 1 is active on GET_STREAM_KEY.
Client drops connection and immediately attempts reconnection (Stream 2).
Stream 2 arrives, passes check, and claims the slot.
Without a generation barrier or object identity check, Stream 1's teardown will silently evict Stream 2's active slot!
# Generation-safe slot releaseclassStreamSlot:
def__init__(self, key: str, generation: int):
self.key=keyself.generation=generationself.state="PENDING"# PENDING -> ACTIVE -> RELEASEDdefrelease_slot(self, stream_key: str, generation: int) ->bool:
slot=self._request_streams.get(stream_key)
# Monotonic barrier: only evict if the slot belongs to this exact generationifslotandgetattr(slot, "generation", None) ==generation:
delself._request_streams[stream_key]
returnTruereturnFalse
3. Spec-Compliant 409 Conflict Headers
When returning 409 Conflict, appending a Retry-After: 1 or 2 header helps upstream agent runtimes (Claude, Cursor, LangChain) back off predictably rather than entering immediate high-frequency retry loops.
(Disclosure: As maintainers of the open-source MCP Production Kit, we have integrated this two-phase slot reservation and generation barrier pattern into our production hardening test suite).
Verified locally (AI-assisted analysis & testing): _handle_get_request in src/mcp/server/streamable_http.py has a TOCTOU window because _get_request_stream is only populated once EventSourceResponse schedules standalone_sse_writer(), allowing concurrent GET requests to bypass 409 Conflict.
I have a minimal tested fix using a synchronous _get_stream_claimed guard and regression test in tests/shared/test_streamable_http.py. If no existing volunteer is assigned, I'd be happy to open a PR once assigned or labeled help wanted.
Activity
Shanmukh-l33t commentedon Nov 22, 2026
Opened a branch with a fix for this:
fix/3891-get-stream-toctouon my fork.Root cause.
_handle_get_requestmade the 409 decision by inspectingself._request_streams, but the slot itself was only inserted insidestandalone_sse_writer(), whichEventSourceResponsestarts after the response has begun. Two concurrent GETs therefore both ran the check against a mapping without the key, both were accepted with 200, and the second writer replaced the first slot, orphaning the first stream and letting its cleanup close the second connection's stream.The fix registers
self._request_streams[GET_STREAM_KEY]synchronously immediately after the conflict check, matching the two POST paths, and takes the reader from that registration instead of creating the stream inside the writer. Cleanup moved into the request'sfinallyand now runs before the SSE streams are closed, so a request cancelled before its writer starts cannot leak the slot, and a GET that registers after this slot is popped is never torn down by this request.Branch:
fix/3891-get-stream-toctouCompare: main...Shanmukh-l33t:python-sdk:fix/3891-get-stream-toctou
Numbers, module
tests/shared/test_streamable_http.py:main@77001c96:1 failed, 73 passed, the new test failing withAssertionError: assert [200, 200] == [200, 409].74 passed.src/mcp/server/streamable_http.pyacross the transport related test modules: 100.00% (427 statements, 118 branches, 0 missed, 0 partial).ruff checkandruff format --checkclean.One existing test,
test_standalone_stream_teardown_between_dequeues_is_not_an_error, relied on registration happening inside the writer to know the writer was parked at dequeue. It now waits for a waiting receiver on the buffered stream before sending, which keeps the same scenario deterministic without the old timing assumption.AI assisted preparation: the reproduction, the fix and the test runs above were executed locally with AI assistance.
A7mdMe commentedon Nov 26, 2026
This is a very subtle and critical race condition for high-concurrency MCP servers.
Beyond Synchronous Insertion: Two Edge Cases to Address
Moving the slot insertion synchronously into
_handle_get_request()directly closes the TOCTOU window, but in production HTTP transports, two secondary failure modes must be guarded:1. The Premature Disconnect Lockout (Two-Phase Claim & Rollback)
If the slot is claimed synchronously before returning the
EventSourceResponse, what happens if Starlette/Uvicorn fails during response initialization (e.g. client resets TCP connection before TLS handshake completes, or middleware throws an error)?If the slot is stored as a bare entry without an auto-reaping timeout or rollback, that session key becomes permanently stuck in a "claimed" state, causing all future legitimate reconnects to fail with
409 Conflict.Remediation: Treat slot reservation as a two-phase state machine:
PENDING: Claimed synchronously during routing.ACTIVE: Promoted when the first SSE event / comment heartbeat is written.PENDINGexceeds an inactivity timeout (e.g. 5.0s) without promoting toACTIVE, the slot automatically expires to allow recovery.2. Monotonic Generation Fencing Against Delayed Teardowns
Consider this sequence under network jitter:
GET_STREAM_KEY.finally: self._request_streams.pop(GET_STREAM_KEY, None)) fires late.Without a generation barrier or object identity check, Stream 1's teardown will silently evict Stream 2's active slot!
3. Spec-Compliant 409 Conflict Headers
When returning
409 Conflict, appending aRetry-After: 1or2header helps upstream agent runtimes (Claude, Cursor, LangChain) back off predictably rather than entering immediate high-frequency retry loops.(Disclosure: As maintainers of the open-source MCP Production Kit, we have integrated this two-phase slot reservation and generation barrier pattern into our production hardening test suite).
buildwithpnj commentedon Nov 28, 2026
Verified locally (AI-assisted analysis & testing):
_handle_get_requestinsrc/mcp/server/streamable_http.pyhas a TOCTOU window because_get_request_streamis only populated onceEventSourceResponseschedulesstandalone_sse_writer(), allowing concurrentGETrequests to bypass409 Conflict.I have a minimal tested fix using a synchronous
_get_stream_claimedguard and regression test intests/shared/test_streamable_http.py. If no existing volunteer is assigned, I'd be happy to open a PR once assigned or labeledhelp wanted.