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
Resolve cancel scope error in MCP session cleanup with lifetime task (#931)
Previously, session cleanup was calling client.__aexit__() from a different task context than where __aenter__() was called, violating anyio's CancelScope requirement that enter and exit must happen in the same task. This caused "Attempted to exit cancel scope in a different task" errors during session cleanup.
Solution:
- Introduce a per-client lifetime task that manages the entire client lifecycle
- The lifetime task enters the client context (async with client:) and waits for a stop_event signal before exiting
- Session cleanup now signals the stop_event and waits for the lifetime task to complete, ensuring __aexit__ runs in the correct task context
This ensures proper cancel scope handling and prevents resource leaks while maintaining thread-safe session management.
## By Submitting this PR I confirm:
- I am familiar with the [Contributing Guidelines](https://github.com/NVIDIA/NeMo-Agent-Toolkit/blob/develop/docs/source/resources/contributing.md).
- We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license.
- Any contribution which contains commits that are not Signed-Off will not be accepted.
- When the PR is ready for review, new or existing tests cover these changes.
- When the PR is ready for review, the documentation is up to date with these changes.
## Summary by CodeRabbit
* **Bug Fixes**
* Sessions now shut down cleanly (stop signaling and fallback cleanup), reducing hangs and timeouts; inactive sessions are reliably removed.
* **Refactor**
* Session lifecycle reworked to include explicit stop events and managed background lifetime tasks for more robust session management.
* **Chores**
* Initialization and cleanup wiring improved to avoid orphaned tasks and lower resource use during idle/long runs.
* **Tests**
* Test harness updated with session cleanup helpers to ensure per-session tasks are torn down and improve isolation.
Authors:
- Anuradha Karuppiah (https://github.com/AnuradhaKaruppiah)
Approvers:
- Yuchen Zhang (https://github.com/yczhang-nv)
URL: #931
0 commit comments