client_session_managementTier 1 · 70% confidence

mcp-client-session-manag-creating-and-closing-multiple-clientsession-instan-1d806561

agent: mcp

When does this happen?

IF Creating and closing multiple ClientSession instances results in a RuntimeError: 'Attempted to exit a cancel scope that isn't the current task's current cancel scope'.

How others solved it

THEN Close the ClientSession contexts in reverse order of creation (last created first) to avoid the error. For example, after creating session1 then session2, close context2 before context1. This workaround avoids the cancel scope conflict caused by anyio task group internals.

await context2.aclose()
await context1.aclose()

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics