Repository navigation
Breaking: reject wrong MCP factory return types in Google GenAI Python - #531
Conversation
A value passed in place of a factory, such as an already-built context manager, failed every MCP Activity with a retryable TypeError. The plugin now refuses it when it builds the MCP Activities, so the Worker fails at start with an error that names the server and what was passed.
## What was changed When a Vercel AI SDK MCP client factory resolves to `undefined`, `null`, or an object without the required methods, the Activity fails with an opaque `TypeError`. The default retry policy repeats that failure without limit, and cleanup can hide the original error with another `TypeError` about `close`. Validate each factory result before using it. A client must expose callable `tools()` and `close()` methods, the two methods this adapter uses. An invalid result fails with a non-retryable `MCPClientFactoryTypeError` that names the factory and what it returned: ``` MCP client factory 'weather' returned Client, not a client with tools() and close() methods. ``` If a rejected result still has a callable `close()`, such as a connected MCP SDK `Client`, it is closed first so the connection doesn't leak. An error from that `close()` doesn't replace the validation failure. A factory that isn't a function, such as a connected client passed in its place, fails with a `TypeError` when the Worker is built: ``` MCP client factory 'weather' is DefaultMCPClient, not a function. ``` The check covers list-tools and call-tool Activities, with connection pooling enabled or disabled. Factories that throw or reject pass their errors through to the Activity retry policy. Objects that implement the required methods, including test doubles, remain supported. ## Why? Wrong factory results are configuration errors. Failing them without retries is the behavior we agreed for the MCP factory checks in the other plugins: OpenAI Agents TypeScript (#530), OpenAI Agents Python (#451), Strands Python (#377), Strands TypeScript (#535), Google GenAI (#531) and Google ADK (#534, #536). This change is contained in the Vercel AI SDK plugin and needs no `temporalio-mcp` release. ## Is it breaking? (Breaking) Invalid clients now stop the Activity without retries. A client missing `close()` could previously serve pooled requests until eviction; it is now rejected before use. The check also runs on the next attempt of an in-flight Activity. Fix these factories before upgrading: deploying a corrected Worker will not automatically resume an Activity that has already failed. A factory that isn't a function now stops the Worker from starting, even when no Workflow uses that server. No Workflow code or Activity names change. The README includes the factory requirements and upgrade warning. ## Checklist 1. Closes: no issue. Related to #451, #377 and #530. 2. How was this tested: - The invalid-client cases fail on the original code with `TypeError`s from `tools` or `close`, and pass with the change. They check the message for each returned value, and that rejected clients with a callable `close()` are closed, including when `close()` throws or rejects. They also pass each invalid value in place of the factory and check the `TypeError`. - The same test returns a connected MCP SDK `Client` from the factory and checks that its in-memory server sees the connection close, in all four operation and pooling combinations. - Removing each fix in turn (the factory check, closing rejected clients, closing only the MCP SDK `Client`) fails all four invalid-client tests. - `make test TEST_ARGS='lib/__tests__/test-ai-sdk-mcp-connections.js'`: 14 passed. Covers invalid clients, unchanged factory failures, and existing connection reuse and cleanup behavior. - `make test TEST_ARGS='lib/__tests__/test-ai-sdk-mcp-tools.js lib/__tests__/test-ai-sdk-plugin.js'`: 5 passed, 1 existing test skipped. The MCP Workflow test uses a real AI SDK MCP client. - `make lint`, `make build` and `git diff --check` passed. - Local checks used Node 22.23.4 and the repository's pinned pnpm 10.27.0. The lockfile and package-manager settings are unchanged. 3. Any docs updates needed? The plugin README is updated.
When an MCP factory failed before its session was ready, the owner task handed the error to the waiting calls and then raised it again. Nobody awaits that task once its record is dropped, so asyncio logged "Task exception was never retrieved" for every failed connect, including a wrong factory return type. The owner task now gives the error only to the waiting calls, which raise it unchanged. Cancellation and interpreter exits still propagate. The factory-type test now fails if asyncio reports an unretrieved error.
Same advice in three lines instead of five.
There was a problem hiding this comment.
Thanks for this! The return-type check and the callable check look good, and the factory, transport and protocol tests pass for me locally. Most of my comments are about older code in _ConnectionRecord._run that this PR touches. python/mcp's _pool.py already handles most of those cases, so following it might be simplest.
| # retries instead of awaiting a permanently rejected future. | ||
| if not self._ready.done(): | ||
| self._ready.set_exception(err) | ||
| _CONNECTIONS.pop(self._server, None) |
There was a problem hiding this comment.
Should this drop the entry only when it's still self, and cancel _idle_handle too? If an evicted record's close raises after a new call cached a fresh record, this drops the fresh one without closing it, and the old idle timer can later close a newer connection. Older than this PR, but this block is changing anyway.
There was a problem hiding this comment.
Agreed, this can affect a replacement connection. I’d like to fix it in a follow-up with concurrency tests for cleanup and idle eviction. It predates this change and needs its own review.
| if self._ready.done(): | ||
| raise | ||
| self._ready.set_exception(err) |
There was a problem hiding this comment.
python/mcp's _pool.py awaits _ready through asyncio.shield and keeps a failure after connect on the record instead of raising. Should this follow it? Here, cancelling one waiting Activity cancels _ready for every other caller, and a session that fails after it's ready still logs "Task exception was never retrieved".
There was a problem hiding this comment.
These make sense, but I'd rather handle them in a future follow-up - as it wouldn't be a breaking change.
This PR keeps the error-handling change limited to failures before readiness.
| raise ApplicationError( | ||
| f"MCP server factory {self._server!r} returned " | ||
| f"{kind.__module__}.{kind.__qualname__}, not an async context manager", | ||
| type="MCPServerFactoryTypeError", | ||
| non_retryable=True, | ||
| ) |
There was a problem hiding this comment.
Strands and temporalio-mcp both make this same error retryable on purpose ("so a run waits for the worker to be fixed instead of failing"), and this module says it's modeled on Strands. Should this match them, or could the PR say why Google GenAI differs?
| # retries instead of awaiting a permanently rejected future. | ||
| if not self._ready.done(): | ||
| self._ready.set_exception(err) | ||
| _CONNECTIONS.pop(self._server, None) |
There was a problem hiding this comment.
This pops by name, so if an evicted record's teardown raises after a newer record is cached, the newer connection is dropped and never closed (reproduced locally). The idle timer also survives, so _maybe_evict can close a newer record mid-call. Should this check _CONNECTIONS.get(self._server) is self, as release() does, and cancel _idle_handle?
There was a problem hiding this comment.
Agreed. I’d keep this in the lifecycle follow-up we discussed, with concurrency tests for replacement connections and stale timers.
There was a problem hiding this comment.
Tracking the cleanup and idle-timer fix in #570.
| if self._ready.done(): | ||
| raise |
There was a problem hiding this comment.
This still raises from a task nobody awaits when the session dies after it's ready, or when _ready was cancelled first. session() doesn't shield _ready, so cancelling one waiting Activity hands CancelledError to its peers too. Could _run store the failure and session() shield _ready, like _pool.py?
There was a problem hiding this comment.
Same follow-up for these. They need their own concurrency tests; this PR keeps the error-handling change limited to failures before readiness.
| activities: list[Callable] = [] | ||
| for server, factory in mcp_servers.items(): | ||
| # Fail when the Worker is built, not in every MCP Activity. | ||
| if not callable(factory): |
There was a problem hiding this comment.
Could this also reject async def and async generator functions (inspect.iscoroutinefunction / isasyncgenfunction)? Forgetting @asynccontextmanager is an easy mistake, and right now it still starts the Worker and fails each Activity.
There was a problem hiding this comment.
I’d keep this PR to the callable and return-value checks. Rejecting these functions during construction adds another startup behavior change, so I’d consider that separately.
DABH
left a comment
There was a problem hiding this comment.
Approving on the condition that you file some follow-up issues for the outstanding comments in the discussion here :) Agree those shouldn't block this PR but don't want to forget about them
MCPPlugin(...) now raises TypeError for a factory that isn't callable, so the Worker doesn't start. When an async factory returns a coroutine, the coroutine is closed before the Activity fails, so Python doesn't warn that it was never awaited. Google GenAI does the same since #531.
…uilt StrandsPlugin(mcp_clients=...) now raises TypeError for a factory that isn't callable, such as a client passed in its place, so the worker doesn't start. When an async factory returns a coroutine, the coroutine is closed before the Activity fails, so Python doesn't warn that it was never awaited. Google GenAI does the same since #531.
… a function (#555) ## What was changed `StatelessMCPServerProvider` and `StatefulMCPServerProvider` now check that their factory is a function when you create them. If it isn't, they throw a `TypeError` that says what was passed, such as `MCP server factory 'files' is Object, not a function.`, so the Worker doesn't start. The message matches the Vercel AI SDK, Strands and Google ADK plugins. ## Why? Today a factory that isn't a function, say a server instead of a function that returns one, gets past Worker start. Then every MCP Activity for that server fails with a plain `TypeError` that retries forever. #530 only checks what the factory returns. #529 added this check to the Vercel AI SDK plugin, and #531, #534, #535 and #536 add it to the other plugins. This does the same here, before 2.0, since adding it later would stop Workers that start today. ## Is it breaking? (Breaking) A Worker with a factory that isn't a function used to start, even though each MCP Activity for that server failed. Now it doesn't start, even when no Workflow uses that server. Fix the factory before upgrading. No Workflow code or Activity names change. ## Checklist 1. Related: #529 and #530. No issue to close. 2. How was this tested: - A new test in `mcp-provider.test.ts` checks that both providers throw the `TypeError` for `undefined`, `null`, a number and a server object, and that the message names each one. With the check turned off, it fails. - On macOS with Node 22: the TypeScript build and the `mcp-provider` test file (6 passed). - In a Linux container with Node 24: ESLint (0 errors; the 8 warnings are the existing `ActivityOptions` ones). I left the full `make test` to CI. - `git diff --check` passes. 3. Any docs updates needed? The README's factory section now says it.
…lable (#593) ## What was changed `OpenAIAgentsPlugin(mcp_servers=...)` now checks that each factory is callable when the plugin is built. If it isn't, it raises `TypeError`, so the Worker doesn't start: ``` MCP server factory 'filesystem' is agents.mcp.server.MCPServerStreamableHttp, not callable ``` Today a server passed in place of its factory gets past Worker start. Then every MCP Activity for that server fails with `TypeError: 'MCPServerStreamableHttp' object is not callable`, which the default retry policy retries forever. There's a second, smaller fix. When an async factory returns a coroutine, the Activity already fails with `MCPServerFactoryTypeError` (#451), but Python also warns that the coroutine was never awaited. The coroutine is now closed first. Both checks live in this plugin's `_mcp_server_backend_factory`, like `MCPPlugin`'s in #539, not in the `_FactoryInvoker` this plugin imports from `temporalio-mcp`. ## Why? The other MCP plugins refuse a factory that isn't a function when the Worker is built: #529, #531, #534, #535, #536 and #555, plus `temporalio-mcp` and Strands Python with #539 and #377. #531 also closes a returned coroutine, after its review asked for it. This brings OpenAI Agents Python in line. ## Is it breaking? (Breaking) A Worker with a factory that isn't callable used to start, even though every MCP Activity for that server failed and retried. Now it doesn't start, even when no workflow uses that server. Fix the factory before upgrading. No Workflow code or Activity names change. The deprecated `mcp_server_providers` route doesn't change. Its providers don't check what the factory returns at all, and I left them alone because they're deprecated. ## Checklist 1. Closes: no issue. Follow-up to #451. 2. How was this tested: - The existing test in `test_mcp_v2.py` now also runs with an async factory, and first passes the returned value in place of the factory. Without the startup check it fails with `DID NOT RAISE TypeError`, and without the `close()` with `CORO_CREATED`. It passes with both. - `make test` on Python 3.12: 644 passed, 2 skipped. - `make lint` passed. - `git diff --check` passed. 3. Any docs updates needed? The README's MCP section now describes both factory errors.
What was changed
A Google GenAI MCP factory that returns
Noneor another value that is not an async context manager currently fails with a retryable runtime error.Check the factory's return value with
isinstance(context, AbstractAsyncContextManager)before entering it. A wrong type fails with a non-retryableMCPServerFactoryTypeErrorthat names the factory and the returned type. A returned coroutine is closed before rejection so Python doesn't warn that it was never awaited.This follows #451 and #530: invalid factory results are configuration errors, while connection failures stay retryable. #377 and #539 propose the same change for Strands Python and
temporalio-mcp.A factory that isn't callable, such as an already-built context manager passed in its place, now fails with a
TypeErrorwhen the plugin builds its MCP Activities, so the Worker doesn't start:A factory that fails before its session is ready, including one that returns the wrong type, no longer makes asyncio log "Task exception was never retrieved". The connection's owner task now gives the error only to the waiting calls, which raise it unchanged.
The yielded session is not inspected. No dependency changes or new
temporalio-mcprelease are needed.Is it breaking? (Breaking)
Wrong factory return types now stop the Activity without retries, including on the next attempt of an in-flight Activity.
Fix these factories before upgrading Workers. Deploying a corrected Worker will not automatically resume an Activity that has already failed. No Workflow code changes.
A factory that isn't callable now stops the plugin from being built, so the Worker doesn't start, even when no Workflow uses that server.
Checklist
Related: Breaking: report an OpenAI Agents MCP server factory that returns the wrong type #451 and Breaking: reject invalid MCP factories in OpenAI Agents TypeScript #530. No issue to close.
How was this tested:
TypeErrorand the Activity's named, non-retryable error.ConnectionRefusedErrorbefore readiness for both MCP Activities. It checks that the same exception reaches the caller, Temporal converts it to a retryable failure, the connection is evicted, and asyncio reports no unobserved exception.make lintpassed: ruff, formatting, pyright, mypy, basedpyright and pydocstyle.git diff --checkpassed.Any docs updates needed? The README explains the factory contract and upgrade impact.