Repository navigation
Breaking: retry an MCP operation whose session the server lost (HTTP 404) - #379
Conversation
…404) A streamable-HTTP server on an older MCP protocol answers HTTP 404 for a session it no longer knows, and the client must start a new session. mcp reports that as INVALID_REQUEST with no data and the message "Session terminated" (its own, for a 404 whose body is not a JSON-RPC error) or "Session not found" (the MCP Python SDK server's body). temporalio-mcp marked every INVALID_REQUEST non-retryable, so the Activity failed at once although a retry on a new connection succeeds. Keep such an error retryable on connections that have a session, which temporalio-mcp opens for each Activity attempt. Other invalid requests stay non-retryable.
DABH
left a comment
There was a problem hiding this comment.
Review at head d26d70b (one commit over ca669af; main has since gained only #363, which touches nothing under python/mcp). On a worktree at the head: make lint clean, make test 91 passed, make build, check_wheel.py and check_conventions.py pass. Run against the base source, the head's test_activities.py fails exactly the four new lost-session cases and passes the other 13, controls included. #378's script fails attempt 1 non-retryably on the base and retryably here, with attempt 2 returning ok. End to end on a dev server, a workflow calling one tool through TemporalMCPClient against an older-protocol server that forgets its first session fails with a non-retryable Session terminated on the base and completes on attempt 2 with a second session here; each build replays the other's history, so replay is unaffected. Against mcp 2.2.0's own session manager (Client(..., mode="legacy")), a lost session gives a retryable Session not found and a successful retry. With this head's wheel installed in the OpenAI Agents plugin's environment, MCPServerStreamableHttp through the plugin's backend adapter retries both 404 forms on a new session, for parameterless and factory_argument factories; with max_retry_attempts=2 the Agents SDK sends the call three times on the lost session before the Temporal retry opens a new one, as the body says. Also checked: the two messages are the same in mcp 2.1.1 (Strands' lock); the MCP TypeScript SDK 1.31.0 server answers with -32001 and Content-Type: application/json, which the Python client surfaces as -32001, already retried; the Not Found: ... messages come only from the server transport's own checks, as the body says. Refuted: a lost session during connect slipping past the has_session gate (mcp's Client.__aenter__ sends no session-bearing request besides the initialized notification, whose 404 the client ignores); the session-closing DELETE masking the error (mcp only logs its 404); Session terminated on a 2026-07-28 connection (the client never holds a session id there). Cross-language: TypeScript OpenAI Agents' MCP Activities and Python Google ADK's already retry every MCP failure, so this brings Python in line rather than splitting the languages. Not repeated here: the body's OpenAI Agents suite run and the Strands run against an mcp 1.30.0 server.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Where the problems cluster: nothing in the diff itself is wrong. What is left is who receives the change, which depends on the version it ships in, and a pre-existing gap in how mcp.Client errors reach _run that confines this rule, like every other classification there, to operations on parameterless clients.
Approving: the rule is correct on every path it covers, verified against the base and end to end, replay is unaffected and CI is green; the two P2s are a release-version decision and a pre-existing bug for its own issue, and neither needs to hold this merge.
| type="MCPProtocolError", | ||
| non_retryable=err.code in _NON_RETRYABLE_PROTOCOL_ERRORS, | ||
| non_retryable=err.code in _NON_RETRYABLE_PROTOCOL_ERRORS | ||
| and not session_lost, |
There was a problem hiding this comment.
P2 (non-blocking): shipped as temporalio-mcp 0.2.x, this also changes the published GA temporalio-openai-agents 1.0.0 and 1.1.0, not only the next OpenAI Agents and Strands releases, and neither plugin's release notes will describe it. Both published wheels require temporalio-mcp<0.3,>=0.2.0; extra == "mcp" (PyPI metadata, and pyproject.toml at tags python/openai_agents/v1.0.0 and v1.1.0) and send mcp_servers through this _run with the same cacheable adapter, so a 0.2.1 reaches every 1.x install with the mcp extra at its next resolve. With this head's wheel in the OpenAI Agents environment, MCPServerStreamableHttp through _OpenAIMCPServerBackend does pick up the new rule (attempt 1 retryable for both 404 forms, attempt 2 ok). Release notes list only commits that touch the plugin's own directory (release_tool.py:456), so this subject appears in temporalio-mcp's notes alone, and this class's docstring calls a change to it 'a coordinated release across both packages' (_activities.py:94-95), while the body says the plugins 'change with no plugin release'. Published Strands 0.1.0 predates #190 and is unaffected. Suggested: say in the body which temporalio-mcp version this is for. If 0.3.0 (the 0.1 to 0.2 break was a minor bump), the body's 'no plugin release' sentence is wrong: OpenAI Agents and Strands get the change only when a commit in each widens its <0.3 pin (openai_agents, strands_agents), and that commit carries a note into their release notes. If 0.2.1, name OpenAI Agents 1.0.0 and 1.1.0 among the affected installs, since a 'Breaking' change then reaches a GA 1.x line with no OpenAI Agents release.
There was a problem hiding this comment.
Agreed: this goes out as temporalio-mcp 0.3.0, not 0.2.x, so OpenAI Agents 1.0.0 and 1.1.0 installs stay on 0.2.x and don't change at their next resolve. I updated the body. It names the version, drops the "no plugin release" sentence, and says each plugin gets the change when a later commit widens its <0.3 pin, whose release note should name it. That also fits the "coordinated release" docstring. No code change.
| # Activity attempt opens its own, so a retry starts a new one. | ||
| has_session = not backend.cacheable | ||
| return await operation(backend) | ||
| except MCPError as err: |
There was a problem hiding this comment.
P2 (pre-existing on main, not introduced here; non-blocking): this except MCPError only sees errors from operations on parameterless clients. An mcp.Client error raised while connecting, or by any operation of a client from a factory_argument factory, reaches _run as an ExceptionGroup, so the new rule and every other classification here skip it. In the factory_argument branch the operation runs inside async with factory(factory_argument) as backend (_pool.py:146-150), so the MCPError unwinds through Client.__aexit__, whose anyio task groups (streamable_http_client and ClientSession) re-raise it wrapped twice; connect errors are wrapped the same way by Client.__aenter__ in both paths (the pooled path stores the group in the record's owner task, _pool.py:37-47). Probes, identical on the base and this head: read-resource for an unknown URI on an in-process MCPServer fails as MCPProtocolError (-32602, {'uri': 'test://unknown'}), non_retryable=True, through lambda: ..., but as a bare ExceptionGroup (leaf MCPError: Unknown resource) through lambda tenant: ... with factory_argument="acme", which the default policy retries without limit; an initialize answered with a JSON-RPC error fails as an ExceptionGroup through both factories; and against mcp 2.2.0's session manager a lost session through the factory_argument factory fails attempt 1 as that ExceptionGroup, not as the invalid-request MCPProtocolError the new README paragraph describes (it is still retried, so the outcome matches). OpenAI Agents backends are unaffected (their cleanup() never receives the error; both factory forms checked) and Strands always calls a parameterless wrapper, so this hits MCPPlugin users who pass a factory argument. The new tests cover only the parameterless path. Worth its own issue: for operation errors, catching the MCPError inside the factory-argument async with and raising it after the client has closed lets _run classify it (probe: the unknown resource then fails as a non-retryable MCPProtocolError, and the next call through the same factory succeeds); connect errors need a group whose only leaf is an MCPError unwrapped before classification. Then add a factory_argument case to the streamable-HTTP test.
There was a problem hiding this comment.
Confirmed, on this head and on main with 0.2.0: through a factory-argument client the unknown resource comes out as a doubly wrapped ExceptionGroup, and an initialize error is wrapped with either kind of factory. Filed as #381, with a one-file reproduction and your suggested change. I kept it out of this PR. The body's "Not covered" list now mentions it, and notes that a lost session through such a client was already retried as an unknown error. The README paragraph becomes exact once #381 is fixed.
| { | ||
| "jsonrpc": "2.0", | ||
| "id": None, | ||
| "error": {"code": INVALID_REQUEST, "message": "Session not found"}, |
There was a problem hiding this comment.
P3 (tests, non-blocking): the Session not found case hands the client a 404 body the test wrote itself, so it would still pass if mcp's session manager changed the one server message the rule matches. The client half of both cases is mcp's real code; the server half of this one is not. The real manager can drive it with public API and no socket: app = server.streamable_http_app(), async with server.session_manager.run():, an httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), event_hooks={"request": [hook]}) whose hook replaces mcp-session-id on the first tools/call with an id the server never issued, and Client(streamable_http_client("http://127.0.0.1:8000/mcp", http_client=...), mode="legacy") (the port satisfies the default DNS-rebinding check; without mode="legacy" mcp 2.x negotiates the sessionless protocol). Probe: attempt 1 MCPProtocolError 'Session not found' (-32600,), non_retryable=False here and True on the base; attempt 2 ok. The nightly sync-latest lane would then catch a message change in a new mcp release.
There was a problem hiding this comment.
Done in fd1b210. The Session not found case now runs against mcp's own session manager, as you described: ASGITransport over streamable_http_app(), a request hook that gives the first tools/call a session id the server never issued, and mode="legacy". It's a separate test, test_lost_session_from_the_sdk_session_manager_is_retried, since its server setup doesn't fit the hand-written one. The empty-404 test keeps the client's Session terminated case and is renamed to say so. On main's code the new test fails with non_retryable True; with the fix it passes.
The "Session not found" case used a 404 body the test wrote itself, so it would still pass if mcp's session manager changed that message. Drive the real manager instead: an ASGI transport over MCPServer's streamable HTTP app, with a request hook that sends the first tools/call with a session id the server never issued. The empty-404 test keeps the client's own "Session terminated" case.
|
Thanks for the review. Round 1 is in fd1b210 (tests only) and the body:
Rerun at fd1b210 (Docker, Python 3.13): |
## What was changed - OpenAI Agents and Strands (Python) require `temporalio-mcp>=0.4.0,<0.5` instead of `>=0.2.0,<0.3`, in their `mcp` extra and dev group. - Both `uv.lock` files now resolve the published 0.4.0. No other locked package changes. - The `temporal_mcp_server()` docstring now says its MCP operations get a 10-second heartbeat timeout by default, and how to turn it off. ## Why? The `temporalio-mcp` 0.3.0 release notes say OpenAI Agents and Strands keep 0.2.0 behavior until their pins move: both plugins pin `<0.3`. This PR makes them require 0.4, which includes 0.3.0's changes, before GA. 0.3.0 changes how these plugins' MCP calls fail. I ran each change through each plugin's own MCP wiring, against an in-process streamable-HTTP MCP server, on 0.2.0 and 0.3.0: | Case | OpenAI Agents (`mcp_servers`) | Strands (`mcp_clients`) | |---|---|---| | A tool result the MCP client rejects (#437) | Retried forever → fails at once | Retried forever → fails at once | | A lost session, HTTP 404 (#379) | No session in my test (see below) | Failed at once → retried with a new session | | Repeated pagination cursor, MCP error | Already failed at once | Already failed at once | - The rejected-result fix reaches both plugins, with and without a factory argument. Strands turns the failure into a tool error the model sees, instead of the run hanging. - #379 is Caller-breaking for Strands: a lost session used to become a tool error; now the run waits for a new session under its retry policy. Taking it after GA would mean a new major, so before GA is the cheapest moment. - With OpenAI Agents, the Agents SDK used the current MCP protocol, which has no sessions, so I couldn't trigger the 404 path. - The factory-argument `ExceptionGroup` fixes (#411, #433, #455) don't change either plugin: Strands' factories take no argument, and OpenAI Agents' backend doesn't wrap errors in groups. 0.4.0 adds one more change (#494): MCP operations heartbeat while they run, with a 10-second `heartbeat_timeout` when the Activity config leaves it out. So a cancel reaches a running MCP request, and a request longer than a `heartbeat_timeout` you set no longer fails with a heartbeat timeout. - OpenAI Agents: `workflow.temporal_mcp_server()` passes `activity_config` to `TemporalMCPClient` as it is, so its MCP operations now heartbeat by default. In Temporal Cloud, that's at most one Action every 8 seconds of a running request. `heartbeat_timeout=None` turns it off. - Strands: `TemporalMCPClient` always passes `heartbeat_timeout`, `None` unless you set it, so heartbeats stay off by default. If you set it, long requests stop failing with a heartbeat timeout. Why not allow 0.2 or 0.3 too? Every GA install should get the same retry behavior, and CI only tests the locked version, so nobody would test older versions with the GA plugins. The cost: if you use an older `temporalio-mcp` with these plugins, you upgrade it together with the plugin. Does OpenAI Agents need code changes? No. It imports `temporalio.mcp._backend`, which is unchanged since 0.2.0, and `temporalio.mcp._activities._MCPActivities`, whose constructor and Activities are unchanged; 0.3.0 changes only how they classify errors, and 0.4.0 only adds the heartbeats. ## What's left? - Add a Breaking line to both plugins' release notes: they now require `temporalio-mcp` 0.4, with its lost-session retry and its default heartbeat timeout. ## Checklist 1. Closes: no issue. 2. How was this tested: - On this branch, with uv 0.12.24: `make sync`, `make lint` and `make test` pass in both plugins with `temporalio-mcp` 0.4.0 installed (OpenAI Agents: 626 passed, 2 skipped; Strands: 279 passed, 1 skipped). - Before the release, I re-ran the analysis' 178 feature and defect checks for both plugins with the 0.4.0 wheel the release dry run built, which is byte for byte the one on PyPI. Only the intended #494 change shows up: a `heartbeat_timeout` set on Strands' `TemporalMCPClient` no longer times out MCP requests, and `temporal_mcp_server()` operations are scheduled with a 10-second heartbeat timeout. Everything else matches the 0.3.0 run. - At `main` 10f9082, both suites give the same per-test results on 0.2.0 and 0.3.0 (OpenAI Agents: 565 passed, 1 skipped; Strands: 245 passed). 3. Any docs updates needed? The `temporal_mcp_server()` docstring is updated here; no README changes. The release notes need the Breaking line under "What's left?".
What was changed
temporalio-mcpnow retries an MCP operation when the server answered HTTP 404 for a session it no longer knows, instead of failing the Activity at once._activities.py:_MCPActivities._runkeeps anMCPErrorretryable when it reports a lost session (_session_lost): codeINVALID_REQUEST, no error data, and the messageSession terminated(mcp's client, for a 404 whose body is not a JSON-RPC error) orSession not found(the MCP Python SDK server's 404 body), on a connection that has a session. Only older-protocol connections have one (backend.cacheableis false), andtemporalio-mcpopens one for each Activity attempt, so the retry starts a new session. Every otherINVALID_REQUESTstays non-retryable, and the failure keeps its type and details.test_activities.pynow covers both lost-session messages on an older-protocol connection (retryable) and three controls that stay non-retryable: the same error with data, the same error on a current-protocol connection, and another invalid request. Two new tests run the call-tool Activity through mcp's real streamable-HTTP client, with the first call on a lost session: one against a server that answers it with an empty 404 (Session terminated), and one against mcp's own session manager, given a session id it never issued (Session not found). In both, attempt 1 fails retryably and attempt 2 succeeds on a new session.mcp gives no other mark for this 404: no exception type, no error data, and
mcp.Clientdoes not expose the transport. The messages are the same inmcp2.1.1 and 2.2.0. The MCP TypeScript SDK server answers a lost session with-32001, which is already retried.Breaking change (callers): an operation that hit this 404 used to fail at once, and a workflow (or a plugin such as Strands or OpenAI Agents) that turned that failure into a tool error went on. Now the Activity is retried under its retry policy, which by default has no limit, so against a server that keeps answering 404 the run waits instead of going on. Before upgrading, set a bounded
retry_policyor aschedule_to_close_timeouton the MCP operations where the run should go on. Release it astemporalio-mcp0.3.0, not 0.2.x. The OpenAI Agents plugin'smcp_servers(including the released GA 1.0.0 and 1.1.0) and the Strands Agents plugin'smcp_clients(since #190) taketemporalio-mcp>=0.2.0,<0.3, so a 0.2.x release would change them with no plugin release and no note in their release notes. With 0.3.0,MCPPluginusers get the change in that release, and each plugin gets it when a later commit widens its pin; that commit's release note should name it.Replay is not affected: no workflow code changes, and the change adds no commands or events. A history holds a failed or a completed Activity as before.
Why?
Closes #378. A server restart, or a load balancer that sends a request to a replica that does not know the session, ended the call with an error even though a retry, on a new session, succeeds.
Checklist
Closes [Bug] temporalio-mcp: an MCP call whose session the server lost (HTTP 404) fails without retry #378
How was this tested:
Supplemental local runs in Docker (Python 3.13.16,
temporalio1.34.0,mcp2.2.0 from the lock, Temporal CLI 1.9.1), onmainatca669af:python/mcp:make lint(ruff, pyright, mypy, basedpyright, pydocstyle),make test(91 passed),make buildandscripts/ci/check_conventions.pypass.main(onlytest_activities.pychanged): 4 fail, as intended (both lost-session cases in the protocol-error test and both streamable-HTTP tests reportnon_retryableTrue), and the 13 others pass, including the three controls.temporalio-mcpinstalled: 447 passed.mainattempt 1 fails non-retryably; with the change it fails retryably, and attempt 2 returnsokon a new session.temporalio-mcp(183 tests passed): through aTemporalAgentand anmcp1.30.0 server, a 404 with an empty body and a 404 from the SDK's session manager are each retried, and attempt 2 returnsokto the model; withtemporalio-mcp0.2.0 both fail at attempt 1 and the model gets the error.fd1b210(review round 1, a test change only): thepython/mcpchecks (91 passed), the changed tests onmain(the same 4 fail, 13 pass) and the OpenAI Agents suite (447 passed). The other runs above are fromd26d70b, whose codefd1b210doesn't change.Any docs updates needed?
The
python/mcpREADME's errors section. Release notes should name the caller change above.Not covered:
max_retry_attempts, the SDK first retries on the session the server lost; the Temporal retry then starts a new one.Not Found: Session has been terminatedandNot Found: Invalid or expired session IDare left out: they come only from a race, or from a transport used without the SDK's session manager.MCPError(INVALID_REQUEST, "Session not found")for its own reasons on an older-protocol connection is now retried._runwrapped in anExceptionGroup, so this rule, like the other classifications there, doesn't see it (pre-existing, [Bug] mcp: an MCP error from a client built with a factory argument is retried forever #381). Such a lost session was already retried as an unknown error, and still is.Open questions: none.