Repository navigation
Conversation
atishay-kasliwal
left a comment
There was a problem hiding this comment.
The new test fails on main and passes here. test_client.py + test_client_caching.py go from 113 to 114 passed.
I also checked the client after three kinds of exit, using the _varying_tools_server helper. After a normal exit, list_tools() and client.session raise on both branches. After a RuntimeError inside the block, and after an outer anyio.CancelScope cancels the block, main still serves the cached ['t0'] and returns the session object. Here both raise Client must be used within an async context manager and the server sees no extra fetch. Re-entering after an exceptional exit still raises Client is already entered, so the docs line about creating a new Client matches.
The cancel case goes through the same finally, so I think the one new test is enough. Looks good to me.
Raghucharan16
left a comment
There was a problem hiding this comment.
Thanks for this. It's a small, correct fix. I checked it locally:
- I wrote a small in-memory repro (an in-process
MCPServer, no network). Onmain,_sessionis still set after the block exits with a plain exception, with an anyio cancellation (move_on_after), and with anExceptionGroupfrom a task group. With this PR it's cleared in all three cases, and the normal exit still works as before. - The new regression test fails on
mainand passes here.tests/client/test_client_caching.pyplustests/client/test_client.pygive 114 passed on Windows. - Re-entering after an exceptional exit is still rejected by the existing
_enteredguard, which matches the updated docs.
Optional nits: you could also reset _exit_stack = None in the finally for tidiness, and a small cancellation case (e.g. anyio.move_on_after around the block) would lock in the cancellation behaviour too. Neither is blocking.
LGTM 👍
Fixes #3968
Clear the client session reference when the async context exits, even if the exit stack raises.
Motivation and Context
An application exception can skip the session reference cleanup in
Client.__aexit__. A laterlist_tools()call can then return a cached result after the connection has closed. Clearing the reference infinallylets the existing connection guard reject the call while the application exception propagates.How Has This Been Tested?
Breaking Changes
The existing closed-client error now applies after an exceptional exit, as it already does after a normal exit.
Types of changes
Additional context
Codex helped with implementation and testing. Report written, review, and validation by Jon Zhang.