Repository navigation
[typescript/google-adk] breaking: reject invalid MCP factory results - #534
Conversation
The error now says what the factory returned, such as `undefined` or the `Promise` an async factory gives back. A factory that isn't a function fails when the Worker is built instead of in every MCP Activity. The invalid-result test checks the message for each value and also passes each value in place of the factory.
## 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.
…sn't a server (#589) ## What was changed When an OpenAI Agents TypeScript MCP factory returns something that isn't a server, the Activity error now says what came back: ``` MCP server factory 'files' returned Promise, not a server with connect(), close(), listTools() and callTool() methods. ``` Before, it said `returned an invalid server` for every value. The name helps: `undefined` points at a missing `return`, and `Promise` at an `async` factory. The error type (`MCPServerFactoryTypeError`) and the non-retryable flag don't change. ## Why? The review on #529 asked for errors that name the bad value. The Vercel AI SDK (#529), Strands (#535) and Google ADK (#534, #536) plugins do that now. #530 merged before that review, so OpenAI Agents TypeScript is the one left. This PR is stacked on #555, which adds the `describeValue` helper it uses. Merge #555 first. GitHub then moves this PR to `main`, and I'll rebase it so the diff shows only this change. ## Checklist 1. Closes: no issue. Follow-up to #530. 2. How was this tested: - The existing test in `mcp-provider.test.ts` now checks the full message for each invalid result: `undefined`, `null`, a number, a plain object, a `Promise` and an incomplete server. It fails with the old message and passes with the new one. - 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. 3. Any docs updates needed? No. The README doesn't quote the message.
… 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.
The factory must now return an ADK BaseToolset, such as McpToolset. BaseToolset defines get_tools() and close(), the only methods the providers call, and the ADK TypeScript plugin (#534) does the same check. A duck-typed toolset that doesn't subclass BaseToolset now fails too, and a rejected result is no longer closed. The test fakes register as virtual BaseToolset subclasses.
## What was changed An MCP toolset factory that returns `None` or another wrong type currently fails with a retryable `AttributeError`, often from cleanup rather than the requested operation. Check that each factory result is an ADK `BaseToolset`, such as `McpToolset`, before using it. An invalid result fails with a non-retryable `MCPToolsetFactoryTypeError` that names the factory and what it returned: ``` MCP toolset factory 'weather' returned builtins.NoneType, not a BaseToolset ``` Both stateless operations and the stateful session use the check. `BaseToolset` defines `get_tools()` and `close()`, the only methods the providers call, and #534 does the same check in TypeScript. Factory exceptions keep their existing handling. A factory that isn't callable, such as a toolset passed in its place, now fails with a `TypeError` when `TemporalMcpToolSetProvider` or `TemporalStatefulMcpToolSetProvider` is built: ``` MCP toolset factory 'weather' is google.adk.tools.mcp_tool.mcp_toolset.McpToolset, not callable ``` This changes only factory validation and needs no new dependency or MCP package release. ## Is it breaking? (Breaking) Invalid results now stop the Activity without retries, including on the next attempt of an in-flight Activity. This includes a duck-typed toolset that doesn't subclass `BaseToolset`. Fix these factories before upgrading Workers. Deploying a corrected Worker will not automatically resume an Activity that has already failed. No production Workflow code or Activity names change. A toolset factory that isn't callable now stops the Worker from starting, even when no Workflow uses that server. ## Checklist 1. Related: #451, #529 and #530. No issue to close. 2. Validation: - The stateless wrong-result cases fail on the original code and pass with the check. They cover `None`, `object()` and a duck-typed toolset that isn't a `BaseToolset`, check the message for each, and pass each value in place of the factory to both providers to check the `TypeError`. - The stateful case uses the default retry policy and verifies a typed non-retryable failure, naming `builtins.NoneType`, after one factory call. Existing valid-toolset and factory-failure cases pass. - Removing the callable check fails both stateless cases. Removing the `BaseToolset` check fails them and the stateful case, and going back to the duck-typed check fails both stateless cases. - `make test PYTEST_ARGS='-n 4'`: 331 passed, 6 skipped. - `make lint`, `make build` and `git diff --check` passed. - Python checks used uv 0.13.5, with the committed lockfile unchanged. 3. Docs: the README names the required type and has the upgrade warning.
There was a problem hiding this comment.
LGTM overall - I see that now wrong factory results fail fast with a clear message, and the new tests pass here on the locked ADK 2.2.0.
Two things I'd look at before merging: a rejecting async factory still crashes the process, and on ADK before 2.3 an SSE result is still retried. A few smaller questions on tests, docs and the failure type. Thanks!
| } | ||
|
|
||
| function createMcpToolset(name: string, factory: MCPToolsetFactory): ReturnType<MCPToolsetFactory> { | ||
| const produced = factory(); |
There was a problem hiding this comment.
When an async factory rejects, this throws the type error but leaves the returned Promise's rejection unhandled, and a plain node process then exits with code 1. Could this attach a no-op catch to a Promise result before throwing?
There was a problem hiding this comment.
Fixed: a Promise result now gets a no-op catch before the check throws. The test adds a rejecting async factory, which fails with an unhandled rejection without the fix.
| const MCP_CONNECTION_PARAMS_TYPES: ReadonlySet<unknown> = new Set([ | ||
| 'StdioConnectionParams', | ||
| 'SseConnectionParams', | ||
| 'StreamableHTTPConnectionParams', | ||
| ]); |
There was a problem hiding this comment.
On ADK 2.0 to 2.2 an SseConnectionParams result passes this check and then fails with a retryable Not connected on every attempt, which is what this PR removes for other wrong types. ADK exports version, so could SSE be refused below 2.3? Also, what keeps this list current when the ADK range widens?
There was a problem hiding this comment.
Agreed: ADK before 2.3 has no SSE transport. The check now reads version and accepts SseConnectionParams only from 2.3. As for the list: the peer range stops below 2.4, so widening it means rechecking this list. A comment there says so.
| const stopHeartbeat = startAdaptiveHeartbeat(); | ||
| try { | ||
| const produced = factory(); | ||
| const produced = createMcpToolset(name, factory); |
There was a problem hiding this comment.
On the loadMcpResourceTool path, appendResourcesToLlmRequest catches this failure and logs a warning built from String(err), which doesn't include the cause, so the run goes on without resources. Is that the outcome you want for a wrong factory result?
There was a problem hiding this comment.
Skipping matches ADK's LoadMcpResourceTool, so I kept it, but the warning now includes the Activity's error message. If the toolset also provides tools, listTools fails the run anyway.
| } | ||
| throw ApplicationFailure.nonRetryable( | ||
| `MCP toolset factory '${name}' returned ${describeValue(produced)}, not a BaseToolset or MCPConnectionParams.`, | ||
| 'MCPToolsetFactoryTypeError' |
There was a problem hiding this comment.
Should this be a constant in error-types.ts, exported from workflow like MCP_RESOURCES_UNSUPPORTED_FAILURE_TYPE, rather than a hardcoded string? Every other type in this plugin lives there with the GoogleAdk prefix.
There was a problem hiding this comment.
Done: MCP_TOOLSET_FACTORY_TYPE_FAILURE_TYPE (GoogleAdkMCPToolsetFactoryTypeError), exported from workflow.
| return produced; | ||
| } | ||
| throw ApplicationFailure.nonRetryable( | ||
| `MCP toolset factory '${name}' returned ${describeValue(produced)}, not a BaseToolset or MCPConnectionParams.`, |
There was a problem hiding this comment.
For an object with an unrecognised type, could the message name the tag? A misspelled one such as StreamableHttpConnectionParams reads as returned Object, which doesn't point at the mistake.
There was a problem hiding this comment.
Done: it now says returned Object with type 'StreamableHttpConnectionParams', ....
| test(`${operation} passes SSE connection params to ADK`, async (t) => { | ||
| // ADK fails these itself: 2.3 cannot fetch port 9, and earlier releases never connect. | ||
| const sse = { type: 'SseConnectionParams', url: 'http://127.0.0.1:9/sse' } as unknown as MCPConnectionParams; | ||
| const activities = createMCPActivities({ testServer: () => sse }); | ||
| const activity = activities[`testServer-${operation}`] as (args: unknown) => Promise<unknown>; | ||
| const err = await t.throwsAsync( | ||
| new MockActivityEnvironment().run(activity, { toolName: 'echo', args: {}, name: 'file:///test' }) | ||
| ); | ||
| t.not((err as ApplicationFailure).type, 'MCPToolsetFactoryTypeError'); | ||
| }); |
There was a problem hiding this comment.
Could this also cover StreamableHTTPConnectionParams? Dropping that tag from the allowed set leaves all 48 tests in the three MCP test files passing. This test also passes on any failure other than the factory type, so asserting the expected GoogleAdkMCPError would tighten it.
There was a problem hiding this comment.
Done: it covers all three tags and expects GoogleAdkMCPError. Dropping StreamableHTTP now fails it.
| A factory must return a `BaseToolset` or `MCPConnectionParams` with type | ||
| `StdioConnectionParams`, `StreamableHTTPConnectionParams` or, with ADK 2.3, | ||
| `SseConnectionParams`. Other results now | ||
| fail the Activity without retries with type `MCPToolsetFactoryTypeError`. Fix | ||
| these factories before upgrading; the next attempt of an in-flight Activity | ||
| also runs this check. |
There was a problem hiding this comment.
Should this also say that a factory that isn't a function throws a TypeError when the plugin is constructed? And for a toolset built lazily, that the factory should throw until it is ready, since undefined is no longer retried but exceptions are?
There was a problem hiding this comment.
Added both to the README.
- Catch the rejection of a Promise an async factory returns, so it doesn't stop the Worker process. - Accept SseConnectionParams only from ADK 2.3. ADK 2.0 to 2.2 return an unconnected session for it, which retried forever. - Name the type tag of an unknown MCPConnectionParams in the error. - Move the type to MCP_TOOLSET_FACTORY_TYPE_FAILURE_TYPE as GoogleAdkMCPToolsetFactoryTypeError, exported from workflow. - Add the Activity's own error to the resource tool's skip warnings. - Test each connection type, and document the TypeError and lazy factories.
DABH
left a comment
There was a problem hiding this comment.
LGTM - thanks for the quick fixes! All seven check out here on the locked ADK 2.2.0, and on ADK 2.3.0 the MCP tests pass with SSE reaching ADK.
Four small follow-ups inline, none blocking. The SSE reconnect one is upstream, but worth knowing about.
| throw ApplicationFailure.nonRetryable( | ||
| `MCP toolset factory '${name}' returned ${describeValue(produced)}, not a BaseToolset or MCPConnectionParams.`, |
There was a problem hiding this comment.
On ADK before 2.3 an SSE result now reads returned Object with type 'SseConnectionParams', not a BaseToolset or MCPConnectionParams, which points at a typo rather than the ADK version. Could that case say SSE needs ADK 2.3 and name the installed version?
There was a problem hiding this comment.
Good point. It now says returned SseConnectionParams, which needs ADK 2.3 or later; this Worker has ADK 2.2.0.
| const MCP_CONNECTION_PARAMS_TYPES: ReadonlySet<unknown> = new Set([ | ||
| 'StdioConnectionParams', | ||
| 'StreamableHTTPConnectionParams', | ||
| ...(adkMajor > 2 || (adkMajor === 2 && adkMinor >= 3) ? ['SseConnectionParams'] : []), |
There was a problem hiding this comment.
Not from this PR, but on ADK 2.3 a failed SSE connect keeps reconnecting after the Activity has failed: after four failed Activities a probe process logged about 800 MCP transport error lines in ten minutes and never exited. With SSE now documented, is a README note or an upstream issue worth it?
There was a problem hiding this comment.
It reproduces with the MCP SDK alone: after a failed SSE connect(), the EventSource keeps reconnecting. I filed modelcontextprotocol/typescript-sdk#3193 and added a README note that links it.
| A factory must return a `BaseToolset` or `MCPConnectionParams` with type | ||
| `StdioConnectionParams`, `StreamableHTTPConnectionParams` or, from ADK 2.3, | ||
| `SseConnectionParams`. Other results now fail the Activity without retries with | ||
| `MCP_TOOLSET_FACTORY_TYPE_FAILURE_TYPE` (`GoogleAdkMCPToolsetFactoryTypeError`, | ||
| exported from `@temporalio/google-adk/workflow`). A factory whose toolset isn't | ||
| ready yet should throw rather than return `undefined`: exceptions are still | ||
| retried. A factory that isn't a function makes `new GoogleAdkPlugin(...)` throw | ||
| a `TypeError`, so the Worker doesn't start. Fix these factories before | ||
| upgrading; the next attempt of an in-flight Activity also runs this check. |
There was a problem hiding this comment.
Should this say the factory must be synchronous, since a Promise result is refused? And could the MCPToolsetFactory JSDoc carry the same rules? That is what editor users read.
There was a problem hiding this comment.
Done: the README and the MCPToolsetFactory JSDoc now both say the factory must be synchronous.
| const skips = logged.mock.calls | ||
| .map((call) => String(call.arguments[1])) | ||
| .filter((message) => message.startsWith('Failed to')); | ||
| t.is(skips.length, 3, skips.join('\n')); | ||
| for (const message of skips) t.true(message.endsWith(': MCP server unavailable.'), message); |
There was a problem hiding this comment.
Could this match the two warning prefixes and assert at least one of each? It counts every Failed to line the Runtime logs and needs exactly three, so a Workflow Task that is retried and warns again would fail it.
There was a problem hiding this comment.
Done: it now asks for at least one list and one read warning, each ending with the cause.
- On ADK before 2.3, an SSE result now says it needs ADK 2.3 and names the installed version, instead of reading like a typo. - Say the factory must be synchronous, in the README and in the MCPToolsetFactory JSDoc. - Note in the README that a failed SSE connect on ADK 2.3 keeps reconnecting (modelcontextprotocol/typescript-sdk#3193). - The resource warning test matches the list and read warnings on their own and no longer needs exactly three.
What was changed
An MCP factory that returns
undefined,nullor another wrong type currently fails with a retryable error. Validate the factory result before using it in any of the four MCP Activities.The result must pass ADK's
isBaseToolsetcheck or have anMCPConnectionParamstype tag that the installed ADK connects:StdioConnectionParams,StreamableHTTPConnectionParamsor, from ADK 2.3,SseConnectionParams. Other results fail with a non-retryableGoogleAdkMCPToolsetFactoryTypeError(MCP_TOOLSET_FACTORY_TYPE_FAILURE_TYPE, exported from@temporalio/google-adk/workflow) that names the factory and what it returned. For example, an async factory gives:and a misspelled tag gives:
When an async factory rejects, its rejection is handled, so it doesn't stop the Worker process. Factory exceptions keep their existing classification.
What about SSE params on ADK 2.0 to 2.2? Those releases have no SSE transport and return an unconnected session, which used to retry forever. They now fail the check, with a message that says SSE needs ADK 2.3 and names the installed version.
A factory that isn't a function, such as an
MCPToolsetpassed in its place, makesnew GoogleAdkPlugin(...)throw aTypeError:loadMcpResourceToolstill logs and skips a resource Activity that fails, like ADK's ownLoadMcpResourceTool. Its warning now adds the Activity's error, so a wrong factory result shows up there instead of onlyActivityFailure: Activity task failed.This checks only the factory and its result type. Connection settings and other MCP error handling are unchanged. No new dependency or MCP package release is needed.
Is it breaking? (Breaking)
Wrong factory results now stop the Activity without retries, including on the next attempt of an in-flight Activity. That includes SSE params on ADK 2.0 to 2.2. Fix these factories before upgrading Workers. A factory whose toolset isn't ready yet should throw rather than return
undefined, since exceptions are still retried. 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.
Checklist
Promisefrom an async factory and a misspelled tag, and pass each value in place of the factory to check theTypeError.typeofinstead of the class name.catchon aPromiseresult, ava failsmcp.test.jswith an unhandled rejection; droppingStreamableHTTPConnectionParamsfrom the list fails the connection-params test for all four operations, and so does accepting SSE on every ADK; dropping the cause from the warning fails the failing-server resource test.make build,make lintandmake testpassed (275 tests). Lint reports one existing telemetry deprecation warning. After the last commit, the MCP test files (41 tests) andmake lintpassed again.tscis clean and the MCP test files passed (41 tests), with SSE params reaching ADK. Same after the last commit.SseConnectionParamsfactories succeed for all four operations. (Run before this round's changes.)git diff --checkpassed.MCPToolsetFactoryJSDoc include the result types and the synchronous rule. The README also covers theTypeError, lazy factories, the upgrade warning, and the SSE reconnect problem on ADK 2.3 (SSEClientTransport keeps reconnecting after Client.connect() rejects modelcontextprotocol/typescript-sdk#3193).