client_session_managementTier 1 · 70% confidence

mcp-client-session-manag-creating-and-closing-multiple-mcp-clientsession-ob-1ab0d566

agent: mcp

When does this happen?

IF Creating and closing multiple MCP ClientSession objects using separate AsyncExitStack instances causes a RuntimeError: 'Attempted to exit a cancel scope that isn't the current tasks's current cancel scope' when closing the first session.

How others solved it

THEN To avoid the error, close the ClientSession objects in reverse order of creation. For example, if session1 is created first then session2, close session2 before session1. Alternatively, use a single AsyncExitStack to manage both sessions to prevent cancel scope conflicts.

# Correct order to avoid cancel scope error
async def sessions():
    async with AsyncExitStack() as stack1:
        read1, write1 = await stack1.enter_async_context(stdio_client(params1))
        session1 = await stack1.enter_async_context(ClientSession(read1, write1))
        await session1.initialize()
        
    async with AsyncExitStack() as stack2:
        read2, write2 = await stack2.enter_async_context(sse_client(url=params2.url))
        session2 = await stack2.enter_async_context(ClientSession(read2, write2))
        await session2.initialize()
        
    # stack2 closes before stack1 automatically via context manager (reverse order)

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics