Repository navigation
fix: route MCP production mode through JSON-RPC #1169
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
Changes from all commits
d08b249
f996142
d165323
9dc05e3
1244762
59d2e3b
434ac3d
2df3e1f
a8eec75
77a9915
17006d5
41cb4e5
715d5af
00173d4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -248,6 +248,8 @@ def __init__( | |
| self._session_executors: Dict[str, ThreadPoolExecutor] = {} | ||
| self._session_stacks: Dict[str, AsyncExitStack] = {} | ||
| self._session_info: Dict[str, SessionInfo] = {} | ||
| self._session_websocket_attachments: set[str] = set() | ||
| self._session_pending_closes: set[str] = set() | ||
| self._session_lock = asyncio.Lock() | ||
|
|
||
| # Create thread pool for running sync code in async context | ||
|
|
@@ -451,6 +453,8 @@ async def _destroy_session(self, session_id: str) -> None: | |
| executor = self._session_executors.pop(session_id, None) | ||
| stack = self._session_stacks.pop(session_id, None) | ||
| self._session_info.pop(session_id, None) | ||
| self._session_websocket_attachments.discard(session_id) | ||
| self._session_pending_closes.discard(session_id) | ||
|
|
||
| await self._cleanup_session_resources(env, executor, stack) | ||
|
|
||
|
|
@@ -522,7 +526,10 @@ async def _reap_idle_sessions(self) -> None: | |
| stale_ids: list[str] = [] | ||
| async with self._session_lock: | ||
| for sid, info in self._session_info.items(): | ||
| if now - info.last_activity_at > timeout: | ||
| if ( | ||
| sid not in self._session_websocket_attachments | ||
| and now - info.last_activity_at > timeout | ||
| ): | ||
| stale_ids.append(sid) | ||
| for sid in stale_ids: | ||
| # Re-check under lock: activity may have arrived since | ||
|
|
@@ -532,7 +539,11 @@ async def _reap_idle_sessions(self) -> None: | |
| now = time.time() | ||
| async with self._session_lock: | ||
| info = self._session_info.get(sid) | ||
| if info is None or (now - info.last_activity_at) <= timeout: | ||
| if ( | ||
| info is None | ||
| or sid in self._session_websocket_attachments | ||
| or (now - info.last_activity_at) <= timeout | ||
| ): | ||
| continue | ||
| await self._destroy_session(sid) | ||
| except asyncio.CancelledError: | ||
|
|
@@ -804,15 +815,33 @@ async def mcp_handler( | |
| ) | ||
|
|
||
| async with self._session_lock: | ||
| env = self._sessions.pop(target_session_id, _MISSING) | ||
| if env is not _MISSING: | ||
| if target_session_id in self._session_websocket_attachments: | ||
| env = _MISSING | ||
| attached = True | ||
| self._session_pending_closes.add(target_session_id) | ||
| executor = None | ||
| stack = None | ||
| else: | ||
| attached = False | ||
| env = self._sessions.pop(target_session_id, _MISSING) | ||
| if not attached and env is not _MISSING: | ||
| executor = self._session_executors.pop(target_session_id, None) | ||
| stack = self._session_stacks.pop(target_session_id, None) | ||
| self._session_info.pop(target_session_id, None) | ||
| else: | ||
| elif not attached: | ||
| executor = None | ||
| stack = None | ||
|
|
||
| if attached: | ||
| return JsonRpcResponse.success( | ||
| result={ | ||
| "session_id": target_session_id, | ||
| "closed": False, | ||
| "closing": True, | ||
| }, | ||
| request_id=request_id, | ||
| ) | ||
|
|
||
| if env is _MISSING: | ||
| return JsonRpcResponse.error_response( | ||
| JsonRpcErrorCode.INVALID_PARAMS, | ||
|
|
@@ -1487,18 +1516,48 @@ async def websocket_endpoint(websocket: WebSocket): | |
| """ | ||
| WebSocket endpoint for persistent environment sessions. | ||
|
|
||
| Each WebSocket connection gets its own environment instance. The client sends | ||
| WSResetMessage, WSStepMessage, WSStateMessage, or WSCloseMessage; the server | ||
| responds with WSObservationResponse, WSStateResponse, or WSErrorResponse. | ||
| By default, each WebSocket connection gets its own environment instance. | ||
| A client can instead attach to an existing HTTP MCP session by passing its | ||
| session ID in the query string. The client sends WSResetMessage, | ||
| WSStepMessage, WSStateMessage, or WSCloseMessage; the server responds with | ||
| WSObservationResponse, WSStateResponse, or WSErrorResponse. | ||
| """ | ||
| await websocket.accept() | ||
|
|
||
| session_id = None | ||
| session_env = None | ||
| owns_session = False | ||
| attached_session = False | ||
|
|
||
| try: | ||
| # Create session with dedicated environment | ||
| session_id, session_env = await self._create_session() | ||
| requested_session_id = websocket.query_params.get("session_id") | ||
| if requested_session_id: | ||
| async with self._session_lock: | ||
| attached_env = self._sessions.get( | ||
| requested_session_id, _MISSING | ||
| ) | ||
| if attached_env is _MISSING: | ||
| raise RuntimeError( | ||
| f"Unknown session_id: {requested_session_id}" | ||
| ) | ||
| if attached_env is None: | ||
| raise RuntimeError( | ||
| f"Session {requested_session_id} is still initializing" | ||
| ) | ||
| if requested_session_id in self._session_websocket_attachments: | ||
| raise RuntimeError( | ||
| f"Session {requested_session_id} already has " | ||
| "an attached WebSocket" | ||
| ) | ||
| self._session_websocket_attachments.add(requested_session_id) | ||
| session_id = requested_session_id | ||
| session_env = attached_env | ||
| attached_session = True | ||
| self._update_session_activity(session_id) | ||
| else: | ||
| session_id, session_env = await self._create_session() | ||
| owns_session = True | ||
|
|
||
| if session_env is None: | ||
| raise RuntimeError( | ||
| "Session environment not initialized for websocket" | ||
|
|
@@ -1509,7 +1568,7 @@ async def websocket_endpoint(websocket: WebSocket): | |
|
|
||
| async with AsyncExitStack() as stack: | ||
| mcp_session_factory = getattr(session_env, "mcp_session", None) | ||
| if callable(mcp_session_factory): | ||
| if owns_session and callable(mcp_session_factory): | ||
| mcp_session_cm = cast( | ||
| AsyncContextManager[Any], mcp_session_factory() | ||
| ) | ||
|
|
@@ -1688,7 +1747,14 @@ async def websocket_endpoint(websocket: WebSocket): | |
| ) | ||
| await websocket.send_text(error_resp.model_dump_json()) | ||
| finally: | ||
| if session_id: | ||
| if attached_session and session_id: | ||
| # Do not await the lock before releasing ownership: a task | ||
| # cancelled while waiting would leave this session | ||
| # permanently exempt from idle reaping. | ||
| self._session_websocket_attachments.discard(session_id) | ||
| if session_id in self._session_pending_closes: | ||
| await asyncio.shield(self._destroy_session(session_id)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pending close can destroy reattached sessionMedium Severity Deferred session close drops the WebSocket attachment and then awaits Additional Locations (2)Reviewed by Cursor Bugbot for commit 715d5af. Configure here. |
||
| elif owns_session and session_id: | ||
| await self._destroy_session(session_id) | ||
| try: | ||
| await websocket.close() | ||
|
|
||


Uh oh!
There was an error while loading. Please reload this page.