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

feat(activity): reuse MCP client connections in @temporalio/ai-sdk (idle-timeout pooling)

Open wankhede04 opened this issue 4 months ago • 6 comments

What was changed

contrib/ai-sdk/src/activities.ts's listToolsActivity/callToolActivity created a brand new MCP client via mcpClientFactory on every single invocation and closed it in a finally block. This ports the idle-timeout connection pooling pattern already shipped in @temporalio/strands-agents (StrandsPluginOptions.mcpConnectionIdleTimeout):

  • A worker-process cache keyed by ${server name}:${clientArgs} reuses one MCP client connection across repeated listTools/callTool activity invocations, resetting an idle timer on every reuse.
  • A new mcpConnectionIdleTimeout option on createActivities(provider, mcpClientFactories, options?) and AiSdkPluginOptions, defaulting to 5 minutes (matching strands).
  • Passing mcpConnectionIdleTimeout: 0 opts out and restores the original create-then-close-per-call behavior, for MCP servers/transports that don't tolerate a reused or concurrent session.
  • AiSdkPlugin's runContext now evicts (closes) any cached connections for its registered MCP server names on worker teardown, mirroring StrandsPlugin.
  • Also includes an unrelated one-line fix in packages/common/src/__tests__/test-payload-visitor.ts, found while verifying this change: it called the removed visitWorkflowActivation export directly instead of visit(activation, walkWorkflowActivation, ...) (the pattern every other test in the file uses), which broke tsc --build on main as of commit 4862844e. Happy to split that into its own PR if preferred — flagging it here since I needed it fixed locally just to get a clean build/typecheck for this change.

Why?

In a multi-turn agent loop — the normal usage pattern where an LLM calls the same MCP server's tools repeatedly across steps — the underlying MCP transport (stdio subprocess spawn, SSE/HTTP handshake, OAuth token exchange) was being torn down and rebuilt on every single tool call and every listTools refresh. This adds avoidable latency and resource churn to every agent step, especially for stdio-based or OAuth-secured MCP servers.

How tested

  • pnpm -C contrib/ai-sdk build (tsc --build) passes cleanly.
  • pnpm exec eslint contrib/ai-sdk/src and pnpm exec prettier --check contrib/ai-sdk/src both pass cleanly.
  • Added unit tests in contrib/ai-sdk/src/__tests__/test-ai-sdk.ts (mocked mcpClientFactory, no live MCP server needed) covering:
    • the client factory is called once and the same connection is reused across repeated tools()/callTool invocations within the idle window
    • an idle connection is closed and evicted once the idle timeout elapses, and the next call reconnects via a fresh factory call
    • mcpConnectionIdleTimeout: 0 opts out and restores the original create-then-close-per-call behavior
    • updated the existing callToolActivity awaits tool.execute before closing MCP client test to opt out (mcpConnectionIdleTimeout: 0), since its assertion only holds under the non-pooled path
  • Was not able to run the AVA suite end-to-end in my local environment (this package's tests require Node >= 22.12 plus a prebuilt @temporalio/core-bridge native addon, which I could not build locally — no Rust toolchain / no prebuilt binary for this dev commit). The new tests were designed to run standalone against createActivities directly (no Worker/Temporal dev server needed) so a maintainer or CI can validate them directly.

Risks

  • Scoped to connection lifecycle only inside activities.ts and the new plugin option — no change to tool-calling semantics, schema handling, or the ai@7 provider surface.
  • The opt-out (mcpConnectionIdleTimeout: 0) preserves today's exact behavior for any MCP server/transport that can't tolerate a reused or concurrent session.

Checklist

  • [x] Closes #2222
  • [x] Tests added/updated
  • [ ] Docs needed? Not beyond the JSDoc added on the new option (no user-facing docs site changes identified for this package)

Closes #2222

wankhede04 avatar Jul 21 '26 07:07 wankhede04

Thanks for the detailed review! Both issues are addressed, pushed as two separate commits so each maps to a review point:

1. Idle timer armed at call start (4ad6c846)

Went with the refcount option: acquireMcpConnection no longer arms the idle timer — it just clears any pending timer and increments an in-flight refCount. The timer is only armed in releaseMcpConnection, and only once refCount drops back to 0. So a connection's idle window is now measured from when it was last actually used, not from call start, and a long-running call can never be evicted mid-flight regardless of how long it takes.

2. Error-path eviction closing a connection shared by a concurrent activity (573f36d2)

Also went with the refcount approach here, since @ai-sdk/mcp doesn't expose a clean way to distinguish transport-level errors from tool-execution errors. The catch no longer calls evictMcpConnection directly — it flags the connection as broken and defers the decision to releaseMcpConnection, which only evicts once refCount reaches 0. So a tool-level failure in one call can no longer tear down a session a concurrent sibling is still mid-execute() on; the connection is still dropped and reconnected on the next call once it's safe to do so.

Both fixes share the same underlying refcount mechanism in acquireMcpConnection/releaseMcpConnection, guarded by entry identity (not just the cache key) so a release can never disturb a different connection that got cached under the same key in the meantime.

Added two new tests covering each fix directly (a long-running call surviving a short idle timeout, and a tool-level error on one concurrent call not disrupting a sibling sharing the same connection), plus reconfirmed the existing reuse/idle-eviction/opt-out tests still pass unchanged.

wankhede04 avatar Jul 22 '26 10:07 wankhede04

@brianstrauch Thanks for approving this! Since both review points are addressed, would you be able to merge it whenever convenient?

wankhede04 avatar Jul 22 '26 18:07 wankhede04

@wankhede04 Happy to do so once the merge conflict is resolved! (If I remember correctly, this test file is unrelated to your PR and has been fixed upstream)

brianstrauch avatar Jul 22 '26 19:07 brianstrauch

Rebased onto latest main — the merge conflict in test-payload-visitor.ts is resolved (upstream's fix was equivalent, so d071e85 was dropped as redundant). Build/lint/format all pass. Ready to merge whenever convenient!

wankhede04 avatar Jul 23 '26 06:07 wankhede04

@wankhede04 CI is looking for a brief changelog entry, and we might have introduced a flaky test here as well.

brianstrauch avatar Jul 23 '26 16:07 brianstrauch

@brianstrauch Fixed both — added the missing CHANGELOG.md entry and fixed the failing test's mock (it needed jsonSchema() wrapping, not actually flaky). Pushed in 262809d. Could you approve/re-run the CI workflow when you get a chance? Thanks!

wankhede04 avatar Jul 24 '26 06:07 wankhede04

@copilot resolve the merge conflicts in this pull request

brianstrauch avatar Aug 04 '26 17:08 brianstrauch