fix(mcp): reset stdio session stack state on cleanup #2461
+71
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR hardens MCP server teardown by resetting
_MCPServerWithClientSessionstate aftercleanup().Changes:
exit_stackto a freshAsyncExitStackafter every cleanup.server_initialize_resultduring cleanup, alongsidesession.MCPServerStdioinstance works reliably.Why
When cleanup reuses the same exit stack object across connection lifecycles, callbacks/references from prior connection attempts can be retained longer than needed, especially after recoverable cleanup errors. Resetting teardown state makes MCP stdio lifecycle behavior deterministic and reduces risk of lingering subprocess/stream resources.
Testing
uv run ruff check src/agents/mcp/server.py tests/mcp/test_connect_disconnect.pyenv -u ALL_PROXY -u all_proxy -u HTTPS_PROXY -u https_proxy -u HTTP_PROXY -u http_proxy -u NO_PROXY -u no_proxy uv run pytest tests/mcp/test_connect_disconnect.py tests/mcp/test_server_errors.py -qenv -u ALL_PROXY -u all_proxy -u HTTPS_PROXY -u https_proxy -u HTTP_PROXY -u http_proxy -u NO_PROXY -u no_proxy uv run python -m trace --count --coverdir /tmp/openai_agents_618_trace --module pytest tests/mcp/test_connect_disconnect.py -qIssue: #618