Skip to content

Fix clean up sse disconnect event (not upgrade lib) #703

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
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
12 changes: 10 additions & 2 deletions src/mcp/server/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,12 @@ async def sse_writer():

async with anyio.create_task_group() as tg:

async def response_wrapper(scope: Scope, receive: Receive, send: Send):
async def response_wrapper(
scope: Scope,
receive: Receive,
send: Send,
transport: SseServerTransport,
):
"""
The EventSourceResponse returning signals a client close / disconnect.
In this case we close our side of the streams to signal the client that
Expand All @@ -156,10 +161,13 @@ async def response_wrapper(scope: Scope, receive: Receive, send: Send):
)(scope, receive, send)
await read_stream_writer.aclose()
await write_stream_reader.aclose()
await read_stream.aclose()
await write_stream.aclose()
transport._read_stream_writers.pop(session_id)
logging.debug(f"Client session disconnected {session_id}")

logger.debug("Starting SSE response task")
tg.start_soon(response_wrapper, scope, receive, send)
tg.start_soon(response_wrapper, scope, receive, send, self)

logger.debug("Yielding read and write streams")
yield (read_stream, write_stream)
Expand Down
53 changes: 53 additions & 0 deletions tests/server/test_sse_disconnect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import asyncio
from uuid import UUID

import pytest
from starlette.types import Message, Scope

from mcp.server.sse import SseServerTransport


@pytest.mark.anyio
async def test_sse_disconnect_handle():
transport = SseServerTransport(endpoint="/sse")
# Create a minimal ASGI scope for an HTTP GET request
scope: Scope = {
"type": "http",
"method": "GET",
"path": "/sse",
"headers": [],
}
send_disconnect = False

# Dummy receive and send functions
async def receive() -> dict:
nonlocal send_disconnect
if not send_disconnect:
send_disconnect = True
return {"type": "http.request"}
else:
return {"type": "http.disconnect"}

async def send(message: Message) -> None:
await asyncio.sleep(0)

# Run the connect_sse context manager
async with transport.connect_sse(scope, receive, send) as (
read_stream,
write_stream,
):
# Assert that streams are provided
assert read_stream is not None
assert write_stream is not None

# There should be exactly one session
assert len(transport._read_stream_writers) == 1
# Check that the session key is a UUID
session_id = next(iter(transport._read_stream_writers.keys()))
assert isinstance(session_id, UUID)

# Check that the session_id should be clean up
assert session_id not in transport._read_stream_writers

# After context exits, session should be cleaned up
assert len(transport._read_stream_writers) == 0
Loading