Skip to content

Commit 410be5b

Browse files
Fix race condition in session roaming
The transport could be removed from _server_instances by the cleanup task if it crashed immediately after being started. This caused a KeyError when trying to access it from the dictionary. Fixed by keeping a local reference to the transport instead of looking it up again from the dictionary after starting the server task.
1 parent 22a82b7 commit 410be5b

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/mcp/server/streamable_http_manager.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -242,12 +242,14 @@ async def _handle_stateful_request(
242242
logger.info(f"Created transport for roaming session: {request_mcp_session_id}")
243243

244244
await self._start_transport_server(http_transport)
245+
transport = http_transport # Use local reference to avoid race condition
246+
else:
247+
# Another request created it while we waited for the lock
248+
transport = self._server_instances[request_mcp_session_id]
245249

246-
# Get the transport (either newly created or created by another request)
247-
transport = self._server_instances[request_mcp_session_id]
248-
await transport.handle_request(scope, receive, send)
249-
250-
return
250+
# Use the local transport reference (safe even if cleaned up from dict)
251+
await transport.handle_request(scope, receive, send)
252+
return
251253

252254
if request_mcp_session_id is None:
253255
# New session case

0 commit comments

Comments
 (0)