Skip to content

Commit 7de20f5

Browse files
author
Hoa Lam
committed
Fix clean up memory when sse disconnect
1 parent 922461e commit 7de20f5

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

src/mcp/server/sse.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,12 @@ async def sse_writer():
145145

146146
async with anyio.create_task_group() as tg:
147147

148-
async def response_wrapper(scope: Scope, receive: Receive, send: Send):
148+
async def response_wrapper(
149+
scope: Scope,
150+
receive: Receive,
151+
send: Send,
152+
transport: SseServerTransport,
153+
):
149154
"""
150155
The EventSourceResponse returning signals a client close / disconnect.
151156
In this case we close our side of the streams to signal the client that
@@ -156,10 +161,13 @@ async def response_wrapper(scope: Scope, receive: Receive, send: Send):
156161
)(scope, receive, send)
157162
await read_stream_writer.aclose()
158163
await write_stream_reader.aclose()
164+
await read_stream.aclose()
165+
await write_stream.aclose()
166+
transport._read_stream_writers.pop(session_id)
159167
logging.debug(f"Client session disconnected {session_id}")
160168

161169
logger.debug("Starting SSE response task")
162-
tg.start_soon(response_wrapper, scope, receive, send)
170+
tg.start_soon(response_wrapper, scope, receive, send, self)
163171

164172
logger.debug("Yielding read and write streams")
165173
yield (read_stream, write_stream)

tests/server/test_sse_disconnect.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,8 @@ async def send(message: Message) -> None:
4646
session_id = next(iter(transport._read_stream_writers.keys()))
4747
assert isinstance(session_id, UUID)
4848

49-
# Check that the writer is still open
50-
writer = transport._read_stream_writers[session_id]
51-
assert writer is not None
49+
# Check that the session_id should be clean up
50+
assert session_id not in transport._read_stream_writers
5251

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

0 commit comments

Comments
 (0)