Skip to content
Open
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
1 change: 1 addition & 0 deletions src/mcp/server/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ async def response_wrapper(scope: Scope, receive: Receive, send: Send):
)
await read_stream_writer.aclose()
await write_stream_reader.aclose()
await sse_stream_reader.aclose()
logging.debug(f"Client session disconnected {session_id}")

logger.debug("Starting SSE response task")
Expand Down
25 changes: 21 additions & 4 deletions src/mcp/server/streaming_asgi_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

import typing
from collections.abc import Awaitable, Callable
from typing import Any, cast

import anyio
Expand Down Expand Up @@ -65,6 +66,8 @@ async def handle_async_request(
) -> Response:
assert isinstance(request.stream, AsyncByteStream)

disconnect_event = anyio.Event()

# ASGI scope.
scope = {
"type": "http",
Expand Down Expand Up @@ -97,11 +100,17 @@ async def handle_async_request(
content_send_channel, content_receive_channel = anyio.create_memory_object_stream[bytes](100)

# ASGI callables.
async def send_disconnect() -> None:
disconnect_event.set()

async def receive() -> dict[str, Any]:
nonlocal request_complete

if disconnect_event.is_set():
return {"type": "http.disconnect"}

if request_complete:
await response_complete.wait()
await disconnect_event.wait()
return {"type": "http.disconnect"}

try:
Expand Down Expand Up @@ -140,7 +149,9 @@ async def process_messages() -> None:
async with asgi_receive_channel:
async for message in asgi_receive_channel:
if message["type"] == "http.response.start":
assert not response_started
if response_started:
# Ignore duplicate response.start from ASGI app during SSE disconnect
continue
status_code = message["status"]
response_headers = message.get("headers", [])
response_started = True
Expand Down Expand Up @@ -176,7 +187,7 @@ async def process_messages() -> None:
return Response(
status_code,
headers=response_headers,
stream=StreamingASGIResponseStream(content_receive_channel),
stream=StreamingASGIResponseStream(content_receive_channel, send_disconnect),
)


Expand All @@ -192,12 +203,18 @@ class StreamingASGIResponseStream(AsyncByteStream):
def __init__(
self,
receive_channel: anyio.streams.memory.MemoryObjectReceiveStream[bytes],
send_disconnect: Callable[[], Awaitable[None]],
) -> None:
self.receive_channel = receive_channel
self.send_disconnect = send_disconnect

async def __aiter__(self) -> typing.AsyncIterator[bytes]:
try:
async for chunk in self.receive_channel:
yield chunk
finally:
await self.receive_channel.aclose()
await self.aclose()

async def aclose(self) -> None:
await self.receive_channel.aclose()
await self.send_disconnect()
Loading