Skip to content

[Bug] strands_agents: TemporalMCPClient ignores MCPClient(prefix=...) and drops MCP tool annotations #147

Closed

Description

@avanish-garg

What are you really trying to do?

Give an agent tools from two MCP servers that both expose a tool with the same name (for example echo), using MCPClient(prefix="gh") and MCPClient(prefix="gl") in the worker-side factories so the model sees gh_echo and gl_echo, the way plain Strands does.

Describe the bug

The README ("MCP" section) says each mcp_clients factory "returns a fully configured MCPClient, so you can pass options like tool_filters, prefix, ...". tool_filters is honoured, but prefix is not. In python/strands_agents/src/temporalio/strands_agents/_temporal_mcp_client.py, _tool_infos builds a prefixed MCPAgentTool only to evaluate the filters and then records the unprefixed tool.name in _MCPToolInfo. TemporalMCPTool uses that name for tool_name and tool_spec["name"], so:

  • the model is offered echo, not gh_echo, and a call to gh_echo comes back as Unknown tool: gh_echo;
  • two servers that expose the same tool name collide, which is the case prefix exists for: only one echo reaches the model and the other server's tool silently disappears.

TemporalMCPTool.tool_spec also drops the MCP tool annotations (readOnlyHint, destructiveHint, ...) that Strands' MCPAgentTool.tool_spec includes, so a model, hook or guardrail that reads them sees nothing.

In plain Strands the agent-facing name is the prefixed one while the server is still called with the original MCP tool name (MCPAgentTool.stream uses self.mcp_tool.name), so the call-tool activity must keep sending the original name.

Minimal Reproduction

Runs against main @ 5e91c26 with the plugin installed from the checkout (cd python/strands_agents && make sync, then .venv/bin/python repro.py). The MCP server is a few lines of FastMCP run as a stdio subprocess, so nothing else is needed. The model is a scripted stub that records the tool specs it is offered and calls gh_echo once.

import asyncio
import json
import sys
import uuid
from datetime import timedelta
from typing import Any

from mcp import StdioServerParameters, stdio_client
from strands import Agent
from strands.models import Model
from strands.tools.mcp import MCPClient

from temporalio import workflow
from temporalio.strands_agents import StrandsPlugin, TemporalAgent, TemporalMCPClient
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker

# A tiny stdio MCP server with one annotated tool, `echo`.
SERVER = """
from mcp.server.fastmcp import FastMCP
from mcp.types import ToolAnnotations

mcp = FastMCP("echo")

@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False))
def echo(message: str) -> str:
    return message

mcp.run()
"""
SPECS: list[Any] = []


def mcp_client(prefix: str) -> MCPClient:
    params = StdioServerParameters(command=sys.executable, args=["-c", SERVER])
    return MCPClient(lambda: stdio_client(params), prefix=prefix)


class Spy(Model):
    """Records the tool specs it is offered, then calls `gh_echo` once."""

    def update_config(self, **_: Any) -> None: ...

    def get_config(self) -> dict[str, Any]:
        return {}

    def structured_output(self, *a: Any, **k: Any):
        raise NotImplementedError

    async def stream(self, messages, tool_specs=None, *_a, **_k):
        first_turn = len(messages) == 1
        if first_turn:
            SPECS.append([(s["name"], s.get("annotations")) for s in tool_specs or []])
        yield {"messageStart": {"role": "assistant"}}
        if first_turn:
            yield {"contentBlockStart": {"start": {"toolUse": {"toolUseId": "t1", "name": "gh_echo"}}}}
            yield {"contentBlockDelta": {"delta": {"toolUse": {"input": json.dumps({"message": "hi"})}}}}
            yield {"contentBlockStop": {}}
            yield {"messageStop": {"stopReason": "tool_use"}}
        else:
            result = messages[-1]["content"][0]["toolResult"]
            yield {"contentBlockDelta": {"delta": {"text": f"{result['status']}: {result['content'][0]['text']}"}}}
            yield {"contentBlockStop": {}}
            yield {"messageStop": {"stopReason": "end_turn"}}


@workflow.defn
class OneServer:
    @workflow.run
    async def run(self) -> str:
        agent = TemporalAgent(
            model="spy",
            tools=[TemporalMCPClient("gh", start_to_close_timeout=timedelta(seconds=20))],
            start_to_close_timeout=timedelta(seconds=10),
        )
        return str(await agent.invoke_async("go"))


@workflow.defn
class TwoServers:
    @workflow.run
    async def run(self) -> str:
        agent = TemporalAgent(
            model="spy",
            tools=[
                TemporalMCPClient("gh", start_to_close_timeout=timedelta(seconds=20)),
                TemporalMCPClient("gl", start_to_close_timeout=timedelta(seconds=20)),
            ],
            start_to_close_timeout=timedelta(seconds=10),
        )
        return str(await agent.invoke_async("go"))


async def main() -> None:
    # Control: plain Strands applies the prefix and exposes the annotations.
    agent = Agent(model=Spy(), tools=[mcp_client("gh")], callback_handler=None)
    result = await agent.invoke_async("go")
    print("plain Strands: specs =", SPECS, "|", str(result).strip())

    plugin = StrandsPlugin(
        models={"spy": Spy},
        mcp_clients={"gh": lambda: mcp_client("gh"), "gl": lambda: mcp_client("gl")},
    )
    async with await WorkflowEnvironment.start_local() as env:
        async with Worker(env.client, task_queue="q", workflows=[OneServer, TwoServers], plugins=[plugin]):
            for wf in (OneServer, TwoServers):
                SPECS.clear()
                out = await env.client.execute_workflow(
                    wf.run, id=f"wf-{uuid.uuid4()}", task_queue="q", execution_timeout=timedelta(seconds=30)
                )
                print(f"Temporal {wf.__name__}: specs = {SPECS} | {out.strip()}")


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

Output on main:

plain Strands: specs = [[('gh_echo', {'readOnlyHint': True, 'destructiveHint': False})]] | success: hi
Temporal OneServer: specs = [[('echo', None)]] | error: Unknown tool: gh_echo
Temporal TwoServers: specs = [[('echo', None)]] | error: Unknown tool: gh_echo

Expected, and what plain Strands does (first line): the model is offered gh_echo (and gl_echo in the two-server workflow) with the annotations, and the call succeeds.

Environment/Versions

  • OS and processor: macOS 26.3, arm64
  • Temporal Version: temporalio 1.34.0 (local dev server via WorkflowEnvironment.start_local()), temporalio-strands-agents from main @ 5e91c26, strands-agents 1.56.0, mcp 1.30.0, Python 3.14.7
  • Are you using Docker or Kubernetes or building Temporal from source? No

Additional context

I have a fix ready: _MCPToolInfo gets agent_name and annotations fields (both default None), filled in _tool_infos from the MCPAgentTool that is already built for the filters, and TemporalMCPTool uses them for its name and spec. The call-tool activity keeps receiving the original MCP tool name. Because the new fields default to None, list-tools results already recorded in a workflow history still decode and resolve to the old name. I will open a PR for it.

Open PR #137 touches the same file, but only the connection bookkeeping and the call_tool / list_tools error paths, not _tool_infos; a trial merge of the two applies cleanly.

Activity

  1. added
    bug
    on Oct 23, 2026
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

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions