Skip to content

[Bug] temporalio-mcp: an MCP call whose session the server lost (HTTP 404) fails without retry #378

Closed

Description

@campoy

What happens

A streamable-HTTP MCP server on an older protocol (one that hands out an Mcp-Session-Id)
answers HTTP 404 when it no longer knows a session, for example after a restart or behind
replicas that do not share sessions. The MCP specification says the client must then start a
new session. mcp's Python client reports that 404 as JSON-RPC error INVALID_REQUEST (-32600):
with the message Session terminated when the 404 body is not a JSON-RPC error, or with the
server's own error when it is, which for the MCP Python SDK server is Session not found.

temporalio-mcp marks every INVALID_REQUEST as an error a retry cannot fix, so the Activity
fails at once with a non-retryable MCPProtocolError. Temporal never runs the retry, although a
retry opens a new connection, starts a new session and succeeds.

This affects MCPPlugin, the OpenAI Agents plugin's mcp_servers, which runs on the same
Activities, and the Strands Agents plugin, which #190 moved onto temporalio-mcp. #375, which
#190 closed, names this as the one case that still fails at once.

Expected: like a closed connection, a lost session is retried under the Activity's retry
policy, on a new connection.

Reproduction

One file, no Temporal server needed. It starts a small MCP server on the older protocol that
answers the first tools/call with HTTP 404 and an empty body, and runs MCPPlugin's
call-tool Activity twice in an ActivityEnvironment: attempt 1 gets the 404, attempt 2 is
what a Temporal retry would run.

"""temporalio-mcp fails a call at once when the MCP server lost the session (HTTP 404).

    python issue_repro.py   (temporalio-mcp, mcp 2 and uvicorn installed; no Temporal server needed)

Starts a small streamable-HTTP MCP server on the older protocol (it hands out an
`mcp-session-id`). It answers the first `tools/call` with HTTP 404 and an empty body, which the
MCP spec says a server sends for a session it no longer knows (for example after a restart);
the client must then start a new session. Later calls return "ok". The script runs
`MCPPlugin`'s `call-tool` Activity twice in an `ActivityEnvironment`: attempt 1 gets the 404,
attempt 2 is what a Temporal retry would run. Exits 0 when attempt 1 fails retryably and
attempt 2 succeeds, 1 otherwise.
"""

import asyncio
import json
import socket
import threading
import time

import uvicorn
from mcp import Client

from temporalio.exceptions import ApplicationError
from temporalio.mcp import MCPPlugin
from temporalio.testing import ActivityEnvironment

calls = 0


async def app(scope, receive, send):
    """A minimal MCP server: JSON responses, one session id, a 404 for the first call."""
    global calls
    if scope["type"] != "http":
        return

    async def reply(status, body=None, headers=()):
        data = b"" if body is None else json.dumps(body).encode()
        hdrs = [(b"content-type", b"application/json"), *headers]
        await send({"type": "http.response.start", "status": status, "headers": hdrs})
        await send({"type": "http.response.body", "body": data})

    if scope["method"] != "POST":
        return await reply(405 if scope["method"] == "GET" else 200)
    body, more = b"", True
    while more:
        message = await receive()
        body += message.get("body", b"")
        more = message.get("more_body", False)
    rpc = json.loads(body)
    method, rid = rpc.get("method"), rpc.get("id")
    if rid is None:  # a notification
        return await reply(202)
    if method == "initialize":
        result = {
            "protocolVersion": "2025-06-18",
            "capabilities": {"tools": {}},
            "serverInfo": {"name": "lost-session", "version": "1"},
        }
        return await reply(200, {"jsonrpc": "2.0", "id": rid, "result": result}, [(b"mcp-session-id", b"s1")])
    if method == "tools/list":
        result = {"tools": [{"name": "lookup", "inputSchema": {"type": "object"}}]}
        return await reply(200, {"jsonrpc": "2.0", "id": rid, "result": result})
    if method == "tools/call":
        calls += 1
        if calls == 1:
            return await reply(404)  # the server no longer knows session s1
        result = {"content": [{"type": "text", "text": "ok"}], "isError": False}
        return await reply(200, {"jsonrpc": "2.0", "id": rid, "result": result})
    error = {"code": -32601, "message": f"Method not found: {method}"}
    return await reply(200, {"jsonrpc": "2.0", "id": rid, "error": error})


async def main() -> int:
    sock = socket.socket()
    sock.bind(("127.0.0.1", 0))
    port = sock.getsockname()[1]
    server = uvicorn.Server(uvicorn.Config(app, log_level="warning"))
    threading.Thread(target=server.run, kwargs={"sockets": [sock]}, daemon=True).start()
    while not server.started:
        time.sleep(0.05)

    plugin = MCPPlugin({"srv": lambda: Client(f"http://127.0.0.1:{port}/mcp")})
    call_tool = next(fn for fn in plugin.activities if fn.__name__ == "call_tool")
    request = {"name": "lookup", "arguments": {}}
    try:
        await ActivityEnvironment().run(call_tool, request)
        print("attempt 1: succeeded (unexpected)")
        return 1
    except ApplicationError as err:
        print(f"attempt 1: ApplicationError type={err.type} details={err.details} message={err.message!r} non_retryable={err.non_retryable}")
        retryable = not err.non_retryable
    result = await ActivityEnvironment().run(call_tool, request)
    print(f"attempt 2: {result['content'][0]['text']!r}; server tools/call requests: {calls}")
    print("OK: retryable, and a retry succeeds" if retryable else "BUG: non-retryable, so Temporal never runs the retry that succeeds")
    return 0 if retryable else 1


if __name__ == "__main__":
    raise SystemExit(asyncio.run(main()))

Output with temporalio-mcp from main at ca669af (mcp 2.2.0, temporalio 1.34.0):

attempt 1: ApplicationError type=MCPProtocolError details=(-32600,) message='Session terminated' non_retryable=True
attempt 2: 'ok'; server tools/call requests: 2
BUG: non-retryable, so Temporal never runs the retry that succeeds
exit=1

The same happens through an agent. With the Strands plugin on main, a TemporalAgent and an
mcp 1.30.0 server whose first tools/call gets a 404, the call-tool Activity fails at
attempt 1 as non-retryable and the model gets Session terminated. When the 404 comes from the
MCP SDK's own session manager (the call carries a session id it does not know), the model gets
Session not found. The server ran no tool either time.

Versions

temporalio-mcp 0.2.0 and main at ca669af; mcp 2.2.0 (also 2.1.1, as the Strands plugin
locks it); temporalio 1.34.0; Python 3.13.

Impact

A server restart, or a load balancer that sends a request to a replica that does not know the
session, ends the call with an error even though the Activity's retry policy would have
recovered. Servers on the current MCP protocol have no sessions and are not affected. The MCP
TypeScript SDK server answers a lost session with -32001, which is already retried.

Proposed fix

In _MCPActivities._run, keep an MCPError retryable when it reports a lost session:
INVALID_REQUEST, no error data, and the message Session terminated or Session not found,
on a connection that has a session (an older-protocol one, which temporalio-mcp opens for
each Activity attempt, so the retry starts a new session). mcp offers no other mark for this
404: no exception type, no error data, and the transport's state is not reachable through
mcp.Client. Other INVALID_REQUEST errors stay non-retryable. If
modelcontextprotocol/python-sdk#3799 gives a lost session its own error type, temporalio-mcp
can match that instead of the messages.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions