fix(contrib): pool and idle-evict MCP connections in google_adk_agents
What was changed
TemporalMcpToolSetProvider's {name}-list-tools and {name}-call-tool activities in temporalio/contrib/google_adk_agents/_mcp.py now pool and reuse a single McpToolset connection per activity name, instead of constructing a brand-new one on every single invocation.
- Added
_ConnectionRecord+ a module-level connection pool keyed by activity name. get_connection()reuses an existing live connection (refcounted) or lazily opens a new one via the existingtoolset_factory.- Idle eviction: once no calls are in flight, a timer (default 5 minutes) closes and evicts the connection. Configurable via a new
mcp_connection_idle_timeoutparameter onTemporalMcpToolSetProvider. - Error-triggered eviction: if
get_tools()/run_async()raises, the connection is evicted immediately so the next call gets a fresh one. A "no matching tool" business-logic error does not evict a healthy connection. - Added regression tests in
tests/contrib/google_adk_agents/test_mcp_pool.pycovering connection reuse, list-tools/call-tool sharing a connection, idle eviction, in-flight calls blocking eviction, and error eviction.
Why?
Every activity invocation called self._toolset_factory(args.factory_argument), constructing a new ADK McpToolset (and therefore a new MCPSessionManager) with no .close()/cleanup ever called on it. For stdio-transport MCP servers this spawns a new child process on every single activity execution and never cleans it up — a genuine subprocess leak under sustained load, not just a missed optimization.
This brings google_adk_agents to parity with the pooling already implemented in the strands (_temporal_mcp_client.py) and google_genai (_mcp.py) contribs, both of which pool and idle-evict connections the same way.
How tested
- Added 7 unit tests in
tests/contrib/google_adk_agents/test_mcp_pool.pyexercising the pool directly against a fakeMcpToolset(no real MCP server needed): connection reuse across N calls, list-tools/call-tool sharing one connection, idle eviction after timeout, in-flight calls blocking premature eviction, and eviction-then-reconnect on bothget_tools()andrun_async()failures. - Ran
ruff check/ruff format --checkandmypy --namespace-packages --check-untyped-defsagainst the changed file — clean. - Ran the existing non-integration tests in
tests/contrib/google_adk_agents/test_google_adk_agents.pyto confirm no regressions.
Risks
factory_argumentis only consulted the first time a connection opens for a given activity name; a warm connection is reused regardless of later calls'factory_argumentvalues. This matches howstrands/google_genaipool a single connection per name (they have no per-callfactory_argumentconcept at all), but is a behavior change if any caller relied onfactory_argumentselecting a different backend on every call for the same provider name.- No worker-shutdown drain hook is added — checking the
strands/google_genaiimplementations directly, neither actually wires one in either (despite that being suggested in the tracking issue); idle + error eviction is the actual existing pattern, which this PR now matches.
Closes #1663
Thanks for the detailed review — reworked this to match openai_agents's stateless/stateful split rather than the strands/google_genai worker-wide pool.
Pushed 3 new commits:
-
fix(contrib): make google_adk_agents MCP toolsets stateless (fixes factory_argument mis-routing)— Removed the cross-workflow_CONNECTIONSpool entirely.TemporalMcpToolSetProvider'sget_tools/call_toolactivities now build a freshMcpToolsetviatoolset_factory(factory_argument)on every call and always close it in afinally, mirroringStatelessMCPServerProvider.factory_argumentis honored on every single call now, with zero cross-workflow sharing — this alone is a complete fix for #1663. -
feat(contrib): add stateful pooled MCP toolset provider for google_adk_agents— Added an opt-inTemporalStatefulMcpToolSetProvider+TemporalStatefulMcpToolSetfor callers who want connection reuse, mirroringStatefulMCPServerProvider: a dedicated{name}-server-sessionactivity on aname@run_id-scoped task queue builds the toolset once per workflow run, runs a nestedWorkerfor the run-scoped-list-tools/-call-toolactivities, and tears the toolset down on cleanup. Dedicated-worker failures surface asApplicationError(type="DedicatedWorkerFailure"). -
fix(contrib): guarantee heartbeat task cleanup in stateful MCP server-session activity— Found in follow-up review: the heartbeat task in the-server-sessionactivity could leak (keep heartbeating after the activity exited) on two paths — a duplicateconnect()for an already-running run, andtoolset.close()raising during teardown. Restructured so the heartbeat task is only created after the duplicate-connect guard and is always cancelled in an outermostfinally.
Tests rewritten accordingly (test_mcp_pool.py → test_mcp.py for the stateless path, new test_stateful_mcp.py for the stateful path) — covering fresh-toolset-per-call, factory_argument honored per call/per run, no cross-run sharing, and teardown on completion/cancellation.
ruff, ruff format, mypy, and the full tests/contrib/google_adk_agents/ suite all pass locally.
Thanks for the fix in 02f2cd7! While double-checking, I noticed the same wording bug ("Unable too many matching mcp tools by name") was also present in the stateful call_tool implementation (a separate code path from the stateless one you fixed), so I've applied the identical wording fix there in 726469c.
Verified with ruff, mypy, and the existing test suite for google_adk_agents — all pass. Ready for another look whenever you get a chance, and happy to merge once approved. Thanks again for the review!
FYI @wankhede04, looks like there are a few pyright errors
@brianstrauch Thanks for flagging the pyright errors — fixed and pushed in 493ad314.
The failures were in tests/contrib/google_adk_agents/test_mcp.py and test_stateful_mcp.py: the fake toolset factories used in the unit tests were typed as returning _FakeToolset (a duck-typed stand-in for ADK's McpToolset), which pyright/basedpyright correctly rejected against toolset_factory's Callable[[Any | None], McpToolset] parameter type since McpToolset is a concrete class, not a Protocol. Annotated the factories as returning McpToolset and cast the fake instance through object first (basedpyright's reportInvalidCast requires that for unrelated concrete types).
Verified locally: pyright, mypy, and basedpyright all clean on the changed files, ruff check/ruff format --check clean, and the full tests/contrib/google_adk_agents/ suite passes (28 passed, 3 skipped).
Can you please rerun the jobs and if everything works Perfect we can merge this out
Pushed a fix for the failing `build-lint-test` CI jobs.
Root cause: `basedpyright` exits non-zero on warnings (not just errors), and it was flagging `reportUnusedParameter` on the `tool_context` parameter in the mocked `run_async` fakes in `tests/contrib/google_adk_agents/test_mcp.py` and `test_stateful_mcp.py`. That parameter name has to stay `tool_context` to match the real `McpTool.run_async` keyword-only interface being mocked, so I suppressed the warning with `# pyright: ignore[reportUnusedParameter]` rather than renaming it.
Verified locally: `ruff check`, `ruff format --check`, `pyright`, `mypy`, `basedpyright`, and the affected test suite all pass. Also merged in the latest `main` to pick up unrelated fixes already on the branch.
Ready for another look — please merge when convenient. Thanks!
Force-pushed a small correction to fix commit author identity on the branch. CI should retrigger automatically on the new push — could someone please re-run/confirm CI and merge this PR when it's green? Thanks!
@wankhede04 please take a look at CI!
Thanks for flagging! The CI failure was from pydocstyle (D105) — missing docstrings on the __aenter__/__aexit__ magic methods in temporalio/contrib/google_adk_agents/_mcp.py. Added docstrings for both and pushed the fix. Re-running CI now.