-
Notifications
You must be signed in to change notification settings - Fork 1.5k
RuntimeError: Attempted to exit cancel scope in a different task
when cleaning up multiple MCPClient instances out-of-order
#577
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
Comments
Facing the same issue when connectng trying to use FastAPI and async methods with mcp to work with frontend
|
Faced the same issue. My custom context manager class was doing simple iteration of the clients list to attempt cleanup (FIFO). In line with the workaround detailed above, fixed with FILO: e.g. finally:
# Clean up in the same task context
# MUST BE FILO, FIFO fails
# https://github.com/modelcontextprotocol/python-sdk/issues/577
for client in reversed(self.clients):
try:
await client.cleanup() |
… order Fixed a bug where closing MCPClient instances in FIFO order (first created, first cleaned up) would raise RuntimeError with 'Attempted to exit cancel scope in a different task'. The issue was in the stdio_client context manager's cleanup sequence. The fix properly structures the async context management in stdio_client to ensure resources are cleaned up in the correct order: first canceling tasks, then closing streams, and finally terminating the process. Added robust test cases that verify the fix works correctly. Github-Issue: modelcontextprotocol#577
How to achieve free management of multiple MCPClient instances under such conditions, enabling instant exit and connection establishment |
Trying OpenAI Codex to fix the issue: |
Describe the bug
If two
MCPClient
objects are instantiated and cleaned up in non-FILO order (i.e., the first-created client is cleaned up before the second), teardown fails with a cascade ofRuntimeError
/CancelledError
exceptions coming fromanyio
andmcp.client.stdio.
To Reproduce
Minimal repro:
Expected behavior
cleanup()
should succeed regardless of the order in which multipleMCPClient
instances are closed, as long as each instance’s own exit_stack is intact. A single client ought to manage its own lifetime without depending on external FILO discipline.Actual Traceback
Environment
The text was updated successfully, but these errors were encountered: