Skip to content

[Bug] mcp: an MCP error from a client built with a factory argument is retried forever #381

Closed

Description

@campoy

Package: temporalio-mcp 0.2.0 and main (1acb19f), whose python/mcp is unchanged since ca669af.

What happens

_MCPActivities._run turns an MCPError into an ApplicationError of type MCPProtocolError, non-retryable for the codes a retry can't fix, such as invalid params. It only sees a bare MCPError when the client comes from a factory with no argument.

With a factory argument (TemporalMCPClient("docs", factory_argument="acme") and a factory that takes it), the operation runs inside async with factory(factory_argument) as backend (_pool.py). The error leaves through mcp.Client.__aexit__, whose task groups wrap it twice in an ExceptionGroup. _run doesn't catch the group, so the Activity fails with it and Temporal retries it: under the default retry policy, forever. An MCPError raised while connecting, for example a JSON-RPC error in answer to initialize, is wrapped the same way with either kind of factory.

This affects MCPPlugin users who pass a factory argument. The Strands plugin always calls a factory with no argument, and the review found the OpenAI Agents plugin's backends unaffected. Found in the review of #379 (comment).

Reproduction

One file, no Temporal server, network or API key. The script reads a resource the in-process server doesn't have through MCPPlugin's read-resource Activity, with each kind of factory, and exits 1 when the second failure is one Temporal retries.

"""An MCP error from a client built with a factory argument is retried forever.

python repro.py    (no Temporal server, network or API key needed)

Reads a resource that the in-process MCP server doesn't have, through MCPPlugin's
read-resource Activity: once with a factory that takes no argument, and once with
one that takes a factory argument. The first fails with a non-retryable
MCPProtocolError. The second fails with the same MCPError wrapped twice in an
ExceptionGroup, which Temporal retries: under the default retry policy, forever.
Exits 1 when that happens.
"""

import asyncio
import sys
from collections.abc import Callable
from typing import Any

from mcp import Client
from mcp.server.mcpserver import MCPServer

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

SERVER = MCPServer("docs")


@SERVER.resource("docs://known")
def known() -> str:
    return "known"


async def read_unknown(factory: Callable[..., Client], factory_argument: Any) -> bool:
    """Read docs://unknown; return whether Temporal would retry the failure."""
    activities = MCPPlugin({"docs": factory}).activities
    assert isinstance(activities, list)
    read = next(
        a
        for a in activities
        if a.__temporal_activity_definition.name.endswith("read-resource")
    )
    request = {"factory_argument": factory_argument, "uri": "docs://unknown"}
    try:
        await ActivityEnvironment().run(read, request)
    except ApplicationError as err:
        print(f"  ApplicationError {err.type} non_retryable={err.non_retryable}: {err.message}")
        return not err.non_retryable
    except Exception as err:
        print(f"  {type(err).__name__} (retried by Temporal): {err!r}")
        return True
    raise AssertionError("docs://unknown was read")


async def main() -> int:
    print("factory with no argument:")
    await read_unknown(lambda: Client(SERVER), None)
    print("factory with a factory argument:")
    retried = await read_unknown(lambda tenant: Client(SERVER), "acme")
    return 1 if retried else 0


sys.exit(asyncio.run(main()))

Output, with temporalio 1.34.0, temporalio-mcp 0.2.0 and mcp 2.1.1 on Python 3.13 (the same on main with mcp 2.2.0):

$ python repro.py; echo "exit=$?"
factory with no argument:
  ApplicationError MCPProtocolError non_retryable=True: Unknown resource: docs://unknown
factory with a factory argument:
  ExceptionGroup (retried by Temporal): ExceptionGroup('unhandled errors in a TaskGroup', [ExceptionGroup('unhandled errors in a TaskGroup', [MCPError(-32602, 'Unknown resource: docs://unknown', {'uri': 'docs://unknown'})])])
exit=1

Suggested change

From the review: catch the MCPError inside the factory-argument async with in _pool.py and raise it after the client has closed, so _run classifies it. For errors while connecting, unwrap a group whose only leaf is an MCPError before classifying. Then add a factory-argument case to the streamable-HTTP tests.

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