Skip to content

fix(mcp): reset AsyncExitStack after cleanup for reconnect (#618)#2882

Draft
Abdeltoto wants to merge 1 commit intoopenai:mainfrom
Abdeltoto:fix/mcp-exit-stack-reset-618
Draft

fix(mcp): reset AsyncExitStack after cleanup for reconnect (#618)#2882
Abdeltoto wants to merge 1 commit intoopenai:mainfrom
Abdeltoto:fix/mcp-exit-stack-reset-618

Conversation

@Abdeltoto
Copy link
Copy Markdown

Problem

\AsyncExitStack\ cannot be reused after \�close(). After \cleanup(), a second \connect()\ (e.g. \MCPServerManager.reconnect()) would call \enter_async_context\ on a closed stack, which is invalid and can contribute to resource leaks / shutdown warnings (see #618).

Change

  • In _MCPServerWithClientSession.cleanup(), after clearing session state, assign a new \AsyncExitStack()\ and clear \server_initialize_result.
  • Add \ est_connect_after_cleanup_uses_fresh_exit_stack\ (connect → cleanup → connect → cleanup).

Testing

Made with Cursor

AsyncExitStack cannot be reused after aclose(). Second connect()/reconnect() must use a fresh stack.

Clear server_initialize_result on teardown. Add regression test for connect->cleanup->connect->cleanup.

Made-with: Cursor
@seratch
Copy link
Copy Markdown
Member

seratch commented Apr 15, 2026

I think we should be a bit more careful about resetting self.exit_stack in the finally block.

MCPServerManager can run cleanup() under a timeout, so self.exit_stack.aclose() may be cancelled while it is still unwinding callbacks. In that case cleanup() re-raises CancelledError, but this change still replaces the original stack with a fresh AsyncExitStack().

If aclose() was interrupted partway through, that drops the remaining callbacks from the original stack, and a later cleanup retry can no longer finish closing the transport/process. That seems like it could turn a teardown timeout into a resource leak.

Could we keep the existing stack on cancellation, and only create a fresh AsyncExitStack() after aclose() completes successfully?

@seratch seratch marked this pull request as draft April 15, 2026 19:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working feature:mcp

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Resource tracker warning (leaked semaphores) with MCPServerStdio

2 participants