You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Create and Close multiple client session result "RuntimeError: Attempted to exit a cancel scope that isn't the current tasks's current cancel scope" #922
This is actually the simplified way how ClientSessionGroup() did it. This code will except in "await context1.aclose()". Please note if change the order:
await context2.aclose()
await context1.aclose()
This will go through without exception.
After some further looking, the ClientSession is use BaseSession, iwhere n its aenter(), BaseSession created a Task Group (to run receive_loop), and try to aexit() the task group during BaseSession's aexit()
The Task Group, among creation, will bind a "cancel scope" with "current_task". So when second ClientSession created, a new "cancel scope 2" is binding the "current_task", replace the first one. When you try to tear down the session1 now, evantually it try to call task_group.aexit() which lead to CancelScope().exit(), there it find the current_task() is binding to a different cancel_scope, thus the runtime.
The code below, demostrate the task group issue (without any mcp releated code):
Seems like an issue that's not specific to MCP and potentially with anyio implementation details - we're unlikely to move away from anyio in the short term as this would be a major refactor.
Activity
felixweinberger commentedon Sep 26, 2025
Seems like an issue that's not specific to
MCPand potentially withanyioimplementation details - we're unlikely to move away fromanyioin the short term as this would be a major refactor.felixweinberger commentedon Sep 26, 2025
THis may be a duplicate of #922
cwegener commentedon Dec 3, 2025
Is there any discussion or work happening around this?