Skip to content

Commit d543469

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

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

src/mcp/server/sse.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ 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(scope: Scope, receive: Receive, send: Send, transport: SseServerTransport):
149149
"""
150150
The EventSourceResponse returning signals a client close / disconnect.
151151
In this case we close our side of the streams to signal the client that
@@ -156,10 +156,13 @@ async def response_wrapper(scope: Scope, receive: Receive, send: Send):
156156
)(scope, receive, send)
157157
await read_stream_writer.aclose()
158158
await write_stream_reader.aclose()
159+
await read_stream.aclose()
160+
await write_stream.aclose()
161+
transport._read_stream_writers.pop(session_id)
159162
logging.debug(f"Client session disconnected {session_id}")
160163

161164
logger.debug("Starting SSE response task")
162-
tg.start_soon(response_wrapper, scope, receive, send)
165+
tg.start_soon(response_wrapper, scope, receive, send, self)
163166

164167
logger.debug("Yielding read and write streams")
165168
yield (read_stream, write_stream)

tests/server/test_sse_disconnect.py

+2-3
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)