Skip to content

Commit a8f72c1

Browse files
author
RJ Lopez
committed
Fix #915: Resolve AnyIO cancellation scope RuntimeError in ClientSessionGroup on connection disconnects
1 parent 005926c commit a8f72c1

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

src/mcp/client/session_group.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,11 @@ async def __aexit__(
165165
if self._owns_exit_stack:
166166
await self._exit_stack.aclose()
167167

168-
# Concurrently close session stacks.
169-
async with anyio.create_task_group() as tg:
170-
for exit_stack in self._session_exit_stacks.values():
171-
tg.start_soon(exit_stack.aclose)
168+
# Sequentially close session stacks to preserve AnyIO task contexts.
169+
# Concurrent teardown spawns task groups that cross cancel scopes, leading
170+
# to RuntimeError: Attempted to exit cancel scope in a different task.
171+
for exit_stack in list(self._session_exit_stacks.values()):
172+
await exit_stack.aclose()
172173

173174
@property
174175
def sessions(self) -> list[mcp.ClientSession]:

0 commit comments

Comments
 (0)