sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

fix(contrib): pool and idle-evict MCP connections in google_adk_agents

Open wankhede04 opened this issue 4 months ago • 7 comments

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 existing toolset_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_timeout parameter on TemporalMcpToolSetProvider.
  • 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.py covering 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.py exercising the pool directly against a fake McpToolset (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 both get_tools() and run_async() failures.
  • Ran ruff check / ruff format --check and mypy --namespace-packages --check-untyped-defs against the changed file — clean.
  • Ran the existing non-integration tests in tests/contrib/google_adk_agents/test_google_adk_agents.py to confirm no regressions.

Risks

  • factory_argument is only consulted the first time a connection opens for a given activity name; a warm connection is reused regardless of later calls' factory_argument values. This matches how strands/google_genai pool a single connection per name (they have no per-call factory_argument concept at all), but is a behavior change if any caller relied on factory_argument selecting a different backend on every call for the same provider name.
  • No worker-shutdown drain hook is added — checking the strands/google_genai implementations 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

wankhede04 avatar Jul 21 '26 08:07 wankhede04

CLA assistant check
All committers have signed the CLA.

CLAassistant avatar Jul 21 '26 08:07 CLAassistant

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:

  1. fix(contrib): make google_adk_agents MCP toolsets stateless (fixes factory_argument mis-routing) — Removed the cross-workflow _CONNECTIONS pool entirely. TemporalMcpToolSetProvider's get_tools/call_tool activities now build a fresh McpToolset via toolset_factory(factory_argument) on every call and always close it in a finally, mirroring StatelessMCPServerProvider. factory_argument is honored on every single call now, with zero cross-workflow sharing — this alone is a complete fix for #1663.

  2. feat(contrib): add stateful pooled MCP toolset provider for google_adk_agents — Added an opt-in TemporalStatefulMcpToolSetProvider + TemporalStatefulMcpToolSet for callers who want connection reuse, mirroring StatefulMCPServerProvider: a dedicated {name}-server-session activity on a name@run_id-scoped task queue builds the toolset once per workflow run, runs a nested Worker for the run-scoped -list-tools/-call-tool activities, and tears the toolset down on cleanup. Dedicated-worker failures surface as ApplicationError(type="DedicatedWorkerFailure").

  3. fix(contrib): guarantee heartbeat task cleanup in stateful MCP server-session activity — Found in follow-up review: the heartbeat task in the -server-session activity could leak (keep heartbeating after the activity exited) on two paths — a duplicate connect() for an already-running run, and toolset.close() raising during teardown. Restructured so the heartbeat task is only created after the duplicate-connect guard and is always cancelled in an outermost finally.

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.

wankhede04 avatar Jul 22 '26 12:07 wankhede04

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!

wankhede04 avatar Jul 23 '26 06:07 wankhede04

FYI @wankhede04, looks like there are a few pyright errors

brianstrauch avatar Jul 23 '26 16:07 brianstrauch

@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

wankhede04 avatar Jul 24 '26 06:07 wankhede04

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!

wankhede04 avatar Jul 28 '26 08:07 wankhede04

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 avatar Jul 28 '26 09:07 wankhede04

@wankhede04 please take a look at CI!

brianstrauch avatar Aug 04 '26 17:08 brianstrauch

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.

wankhede04 avatar Aug 05 '26 06:08 wankhede04