Skip to content

[Bug] strands_agents: an MCP tool call that raises returns a tool error at once, so the call Activity's retry policy never applies #375

Closed

Description

@campoy

Summary

TemporalMCPClient takes Activity options for the {server}-call-tool Activity, including
retry_policy. But that Activity catches every exception from opening the MCP connection or from
session.call_tool and returns a Strands tool error
(_temporal_mcp_client.py L374-L390). Temporal records the Activity as completed, so the
retry policy never applies. A refused connection, a JSON-RPC error reply, or a server that exits
during the call reaches the model as Tool execution failed: ... after one try, even when a retry
would succeed.

Versions

temporalio-strands-agents 0.1.0 and main at 88745dc catch these errors the same way. Run with
main's lock: Python 3.13.16, temporalio 1.34.0, strands-agents 1.56.0, mcp 1.30.0, and a
Temporal CLI 1.9.1 dev server.

Reproduction

One file. It also runs the MCP server (stdio), which fails the first tools/call and answers the
next ones, like a transient failure: in rpc mode it sends a JSON-RPC error reply (-32603), in
crash mode it exits during the call. The script first shows with mcp's own ClientSession
that the first call raises and the second returns ok. Then a Workflow runs the plugin's
{server}-call-tool Activity with RetryPolicy(maximum_attempts=2). The script exits 0 when the
bug shows: one server call, a completed Activity, no failed attempt.

repro.py
"""Run against a local Temporal server with temporalio-strands-agents (main) and mcp 1.30.0.

The same file is also the MCP server: `repro.py serve MODE COUNT_FILE` runs a
stdio server that appends one line to COUNT_FILE per tools/call. The first call
fails and later calls succeed, like a transient failure:
- MODE=rpc: the first call gets a JSON-RPC error reply.
- MODE=crash: the server process exits during the first call.
"""

import asyncio
import os
import sys
import tempfile
from datetime import timedelta
from uuid import uuid4


def serve(mode: str, count_file: str) -> None:
    import anyio
    from mcp import types
    from mcp.server.lowlevel import Server
    from mcp.server.stdio import stdio_server
    from mcp.shared.exceptions import McpError

    server = Server(mode)

    @server.list_tools()
    async def list_tools() -> list[types.Tool]:
        return [types.Tool(name="lookup", inputSchema={"type": "object", "properties": {}})]

    async def call_tool(request: types.CallToolRequest):
        with open(count_file, "a") as f:
            f.write("call\n")
        if len(open(count_file).read().splitlines()) == 1:
            if mode == "rpc":
                raise McpError(types.ErrorData(code=-32603, message="injected JSON-RPC error"))
            os._exit(1)
        return types.ServerResult(types.CallToolResult(content=[types.TextContent(type="text", text="ok")]))

    # A handler that raises McpError makes the server send a JSON-RPC error reply.
    server.request_handlers[types.CallToolRequest] = call_tool

    async def run() -> None:
        async with stdio_server() as (read, write):
            await server.run(read, write, server.create_initialization_options())

    anyio.run(run)


if len(sys.argv) > 3 and sys.argv[1] == "serve":
    serve(sys.argv[2], sys.argv[3])
    sys.exit(0)

from mcp import ClientSession, StdioServerParameters, stdio_client
from mcp.shared.exceptions import McpError
from strands.tools.mcp.mcp_client import MCPClient
from temporalio import workflow
from temporalio.api.enums.v1 import EventType
from temporalio.client import Client
from temporalio.common import RetryPolicy
from temporalio.strands_agents import StrandsPlugin
from temporalio.strands_agents._temporal_mcp_client import _CallToolArgs
from temporalio.worker import Worker


@workflow.defn
class CallTool:
    @workflow.run
    async def run(self, server: str) -> dict:
        return await workflow.execute_activity(
            f"{server}-call-tool",
            _CallToolArgs(tool_name="lookup", tool_use_id="use-1"),
            start_to_close_timeout=timedelta(seconds=10),
            retry_policy=RetryPolicy(maximum_attempts=2),
            result_type=dict,
        )


def params(mode: str, count_file: str) -> StdioServerParameters:
    return StdioServerParameters(command=sys.executable, args=[os.path.abspath(__file__), "serve", mode, count_file])


async def native_calls(mode: str, count_file: str) -> None:
    """Prerequisite: the first call raises McpError from session.call_tool; the next succeeds."""
    async with stdio_client(params(mode, count_file)) as (read, write), ClientSession(read, write) as session:
        await session.initialize()
        try:
            await session.call_tool("lookup", {})
            raise AssertionError("expected McpError")
        except McpError as err:
            print(f"{mode}: native call 1 raised McpError code={err.error.code} message={err.error.message!r}")
    async with stdio_client(params(mode, count_file)) as (read, write), ClientSession(read, write) as session:
        await session.initialize()
        second = await session.call_tool("lookup", {})
        print(f"{mode}: native call 2 returned isError={second.isError} text={second.content[0].text!r}")


async def main():
    files = {mode: os.path.join(tempfile.mkdtemp(), "calls.txt") for mode in ("rpc", "crash")}
    for mode, count_file in files.items():
        open(count_file, "w").close()
        await native_calls(mode, count_file)
        open(count_file, "w").close()

    plugin = StrandsPlugin(
        models={},
        mcp_clients={
            mode: (lambda p=params(mode, count_file): MCPClient(lambda: stdio_client(p)))
            for mode, count_file in files.items()
        },
    )
    client = await Client.connect(os.getenv("TEMPORAL_ADDRESS", "localhost:7233"))
    async with Worker(client, task_queue="strands-mcp-call-repro", workflows=[CallTool], plugins=[plugin]):
        for mode, count_file in files.items():
            handle = await client.start_workflow(
                CallTool.run, mode, id=f"strands-mcp-{mode}-{uuid4()}", task_queue="strands-mcp-call-repro"
            )
            result = await handle.result()
            history = await handle.fetch_history()
            events = [event.event_type for event in history.events]
            completed = events.count(EventType.EVENT_TYPE_ACTIVITY_TASK_COMPLETED)
            failed = events.count(EventType.EVENT_TYPE_ACTIVITY_TASK_FAILED)
            calls = len(open(count_file).read().splitlines())
            print(f"{mode}: result={result}")
            print(f"{mode}: server_calls={calls}, completed={completed}, failed={failed}")
            assert result["status"] == "error"
            assert calls == 1
            assert (completed, failed) == (1, 0)


if __name__ == "__main__":
    asyncio.run(main())
TEMPORAL_ADDRESS=127.0.0.1:7233 python repro.py

Expected

An error a retry can fix fails the attempt, and Temporal retries the call under the Activity's retry
policy: here the second attempt would return ok. An error a retry cannot fix, such as invalid
params (-32602) or an unknown tool, can still reach the model at once as a failed tool result.

Observed

3.13.16 temporalio==1.34.0 temporalio-strands-agents==0.0.0 strands-agents==1.56.0 mcp==1.30.0
rpc: native call 1 raised McpError code=-32603 message='injected JSON-RPC error'
rpc: native call 2 returned isError=False text='ok'
crash: native call 1 raised McpError code=-32000 message='Connection closed'
crash: native call 2 returned isError=False text='ok'
rpc: result={'content': [{'text': 'Tool execution failed: injected JSON-RPC error'}], 'status': 'error', 'toolUseId': 'use-1'}
rpc: server_calls=1, completed=1, failed=0
crash: result={'content': [{'text': 'Tool execution failed: Connection closed'}], 'status': 'error', 'toolUseId': 'use-1'}
crash: server_calls=1, completed=1, failed=0
exit=0

The same happens on the agent route: with a Strands Agent whose MCP tool gets the -32603 error
once, call-tool attempt 1 completes, the model sees error: Tool execution failed: injected JSON-RPC error -32603, and the run goes on.

Impact

A transient MCP failure, such as a server restart, a dropped connection or a busy server's internal
error, reaches the model as a failed tool call instead of being retried, even when the application
set a retry policy for it. The model goes on without the tool's result, or calls the tool again
itself.

Proposed fix

Let connection and call exceptions fail the {server}-call-tool Activity, so its retry policy
applies, except JSON-RPC errors a retry cannot fix, such as invalid params, which still reach the
model at once. In the Workflow, turn the final failure into a Strands tool error in
TemporalMCPTool, so the model still gets a failed tool result once retries run out.

This changes behavior. Under Temporal's default retry policy, which has no attempt limit, a call to
a server that stays down is retried until the server recovers, so the turn waits instead of going on
with an error. A server that exits after a tool's side effect runs the tool again on the retry. An
application that wants today's behavior passes a bounded retry_policy to TemporalMCPClient.

#190 makes this change as part of moving the MCP Activities onto temporalio-mcp. On #190 at
7a139a1, with the script changed only as #190's API requires (mcp.Client factories and the
temporalio.mcp.{server}.call-tool Activity), both modes take two server calls and return ok
on attempt 2. On the agent route, a -32602 error fails without a retry and reaches the model, and
a -32603 error on every call reaches the model once the retries run out. One case is still not
retried on #190: an HTTP 404 for a known streamable HTTP session fails at once with
Session terminated.

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