Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions src/mcp/server/streamable_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -773,18 +773,18 @@ async def _handle_get_request(self, request: Request, send: Send) -> None:
await response(request.scope, request.receive, send)
return

# Register the standalone message stream synchronously before starting the response
# so concurrent GET requests cannot race past the 409 check.
self._request_streams[GET_STREAM_KEY] = anyio.create_memory_object_stream[EventMessage](
REQUEST_STREAM_BUFFER_SIZE
)
standalone_stream_reader = self._request_streams[GET_STREAM_KEY][1]

# Create SSE stream
sse_stream_writer, sse_stream_reader = anyio.create_memory_object_stream[SSEEvent](0)

async def standalone_sse_writer():
try:
# Create a standalone message stream for server-initiated messages

self._request_streams[GET_STREAM_KEY] = anyio.create_memory_object_stream[EventMessage](
REQUEST_STREAM_BUFFER_SIZE
)
standalone_stream_reader = self._request_streams[GET_STREAM_KEY][1]

async with sse_stream_writer, standalone_stream_reader:
# Process messages from the standalone stream
async for event_message in standalone_stream_reader:
Expand Down Expand Up @@ -817,8 +817,8 @@ async def standalone_sse_writer():
await response(request.scope, request.receive, send)
except Exception: # pragma: lax no cover
logger.exception("Error in standalone SSE response")
await self._clean_up_memory_streams(GET_STREAM_KEY)
finally:
await self._clean_up_memory_streams(GET_STREAM_KEY)
await sse_stream_writer.aclose()
await sse_stream_reader.aclose()

Expand Down
40 changes: 40 additions & 0 deletions tests/shared/test_streamable_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -902,6 +902,41 @@ async def test_get_sse_stream(basic_app: Starlette) -> None:
assert second_get.status_code == 409


@pytest.mark.anyio
async def test_concurrent_get_sse_streams_reject_second_with_409(basic_app: Starlette) -> None:
"""Concurrent GET SSE requests for the same session must yield [200, 409] without racing."""
async with make_client(basic_app) as client:
init_response = await client.post(
"/mcp",
headers={
"Accept": "application/json, text/event-stream",
"Content-Type": "application/json",
},
json=INIT_REQUEST,
)
assert init_response.status_code == 200
session_id = init_response.headers.get(MCP_SESSION_ID_HEADER)
assert session_id is not None
negotiated_version = extract_protocol_version_from_sse(init_response)

get_headers = {
"Accept": "text/event-stream",
MCP_SESSION_ID_HEADER: session_id,
MCP_PROTOCOL_VERSION_HEADER: negotiated_version,
}
statuses: dict[str, int] = {}

async def open_stream(key: str) -> None:
async with client.stream("GET", "/mcp", headers=get_headers) as response:
statuses[key] = response.status_code

async with anyio.create_task_group() as tg:
tg.start_soon(open_stream, "first")
tg.start_soon(open_stream, "second")

assert sorted(statuses.values()) == [200, 409]


@pytest.mark.anyio
async def test_get_validation(basic_app: Starlette) -> None:
"""A GET without an Accept header covering text/event-stream is rejected with 406."""
Expand Down Expand Up @@ -2318,10 +2353,13 @@ def __setitem__(
transport._request_streams = SignalingStreams() # pyright: ignore[reportPrivateUsage]

gate = anyio.Event()
response_started = anyio.Event()
sent: list[Message] = []

async def asgi_send(message: Message) -> None:
sent.append(message)
if message["type"] == "http.response.start":
response_started.set()
await gate.wait()

# Never delivers anything, parking the response's disconnect listener.
Expand All @@ -2347,7 +2385,9 @@ async def asgi_receive() -> Message:
standalone_send = transport._request_streams[GET_STREAM_KEY][0] # pyright: ignore[reportPrivateUsage]
# Zero-buffer rendezvous: once send() returns, the writer has dequeued the event
# and is blocked forwarding it past the closed gate — the between-dequeues window.
await response_started.wait()
await standalone_send.send(EventMessage(notification))
await anyio.sleep(0.01)
await transport._clean_up_memory_streams(GET_STREAM_KEY) # pyright: ignore[reportPrivateUsage]
# Unblock the response; the writer's next dequeue hits its closed stream.
gate.set()
Expand Down
Loading