Skip to content

fix(strands): close a failed Python MCP connection only after in-flight calls finish - #137

Merged
brianstrauch merged 3 commits into
temporalio:mainfrom
wankhede04:fix/strands-python-mcp-defer-evict-on-failure
Oct 26, 2026
Merged

brianstrauch merged 3 commits into
temporalio:mainfrom
wankhede04:fix/strands-python-mcp-defer-evict-on-failure

Conversation

@wankhede04

Copy link
Copy Markdown
Contributor

What was changed

When a {server}-call-tool or {server}-list-tools Activity fails in python/strands_agents, the pooled MCP
connection is now marked broken instead of being disconnected immediately. A broken connection is no longer
handed out, so the next call opens a fresh one, and it is disconnected once the last Activity using it finishes.

  • _ConnectionRecord gets a _broken flag and mark_broken(), which removes the record from _CONNECTIONS
    (only if it is still the cached record) and cancels its idle timer.
  • release() closes a broken record in a retained background task when its in-flight count reaches 0;
    otherwise it behaves as before and re-arms the idle timer.
  • _ConnectionRecord._run only removes _CONNECTIONS[server] when it is itself the cached record, so a late
    failure of an old connection cannot unpublish its replacement.

This mirrors #101 for typescript/strands-agents, and python/mcp's _pool.py (retire, then close on last
release). python/google_genai has the same pop pattern and is left for a follow-up.

Why?

The failure path used to await _evict_connection(server) right away, so other calls running on the shared
connection never got their result (they hang until the Activity timeout, then retry), which can repeat side
effects of non-idempotent tools. Client-side failures over a healthy connection, such as non-object arguments or
a result that fails the tool's output schema, were enough to trigger it.

Checklist

  1. Closes [Bug] strands-agents (Python): a failed MCP call closes the shared connection under in-flight calls #136

  2. How was this tested:
    Ran in python/strands_agents (Python 3.14.7, uv 0.12.8):

  • make sync, make lint (clean) and make test: 56 passed, 0 failed (52 existing tests plus 4 new). The
    unmodified tree gives 52 passed.
  • New tests/test_mcp_connection_eviction.py (4 tests; real activities in ActivityEnvironment and a fake
    MCP session that fails in-flight requests with "Connection closed" when it is closed): a slow call and a
    concurrent failing call on one server (the slow call succeeds, one connection is opened for both, a call made
    after the failure opens a fresh connection, and the broken one is closed once drained); a failing list-tools
    does not close the connection under an in-flight call-tool; a failure with nothing else in flight still
    closes the connection and the next call reconnects; a late-dying old record does not unpublish its
    replacement.
  • Against the original _temporal_mcp_client.py the new file gives 1 passed and 3 failed (the two
    sibling-call tests and the replacement test); with the change all 4 pass.
  • Also reproduced against a real stdio MCP server: before, the slow call never returned after a concurrent
    client-side failure; after, it returns its result.
  1. Any docs updates needed?

None.

…ht calls finish

When a call-tool or list-tools Activity failed, the pooled MCP connection was disconnected immediately, so other calls running on it never got their result and hung until the Activity timeout.

Mark the connection broken instead: it is no longer handed out, so later calls open a fresh one, and it is closed when the last in-flight call releases it, as in the TypeScript fix (temporalio#101). Also only drop the cached record from the record's own run loop when it is still the cached one, so a record that dies late cannot remove its replacement. Adds tests for a failing call next to an in-flight call.

Signed-off-by: wankhede04 <[email protected]>
@wankhede04
wankhede04 requested a review from a team as a code owner October 22, 2026 16:31

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reproduced two connection-lifecycle regressions below. Both regression probes pass against the parent commit and fail against this commit. make lint and all 56 existing tests pass.

Copy link
Copy Markdown
Member

One additional test-helper issue in tests/test_mcp_connection_eviction.py: _request() uses asyncio.ensure_future(coro), which returns an asyncio.Task for the coroutines passed here, and stores it in _inflight. _FakeSession.__aexit__() then calls future.set_exception(RuntimeError("Connection closed")) on those tasks.

I reproduced closing the fake session while a tool request was pending. Instead of rejecting that request with Connection closed, __aexit__() raises:

RuntimeError: Task does not support set_exception operation

The pending request remains running, so the fake does not currently simulate the connection-close behavior described in its docstring. Could you use a separate response future, or race the request against a connection-closed signal, and add a small test proving that closing the fake session makes an in-flight request fail with Connection closed?

…ed idle eviction

A queued idle-eviction task could close a replacement connection: the old record was already unpublished by a failed call, but _maybe_evict() only checked its in-flight count and evicted whatever was cached under the server name. Only evict when the record is still the cached one.

Broken connections are closed in the background after being unpublished, so StrandsPlugin's run context never saw them and worker shutdown could return while their transport teardown was still pending. Wait for the tracked closing tasks when the run context exits.

Make the test fake reject in-flight requests with "Connection closed" when its session closes (it called set_exception on a Task), and add regression tests for the replacement eviction, the shutdown wait, and the fake itself.

Signed-off-by: wankhede04 <[email protected]>
@wankhede04

Copy link
Copy Markdown
Contributor Author

Thanks @brianstrauch, I reproduced all three and pushed fixes!

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@brianstrauch
brianstrauch enabled auto-merge (squash) October 26, 2026 18:30
@brianstrauch
brianstrauch merged commit fb7bd0e into temporalio:main Oct 26, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] strands-agents (Python): a failed MCP call closes the shared connection under in-flight calls

2 participants