Skip to content

[Bug] strands_agents: two MCP servers that list the same tool name silently replace each other's tool #183

Closed

Description

@campoy

Package: temporalio-strands-agents 0.1.0 and main (495e507); also temporalio.contrib.strands in temporalio 1.34.0.

What happens

Strands refuses two tools with the same name on one agent. Building a plain Agent with two MCP
servers that both list echo raises ValueError: ... Tool name 'echo' already exists. Cannot register tools with exact same name.

TemporalAgent does not. Its refresh hook, TemporalAgent._reconcile_mcp_tools, calls
registry.replace() for every listed name that is already registered, so the later server's tool
silently takes the name:

  • the model is offered one echo;
  • a call meant for the first server runs on the second, with no error;
  • the same happens when an MCP tool has the name of another tool on the agent, such as a local
    @tool.

Since #148, giving each server its own prefix keeps the names apart. Without a prefix, or with
the same prefix on both servers, the tool is still replaced.

Reproduction

One file. Each MCP server is a few lines of FastMCP run as a stdio subprocess, and the Temporal
server comes from WorkflowEnvironment.start_local(), so nothing else is needed. A scripted model
records the tools it is offered and calls echo once. The Workflow catches ValueError, so a
refusal shows up as its result. The script exits 1 when the plugin does not refuse the duplicate
name.

"""Two MCP servers list the same tool name: through the plugin, the second one silently wins.

Servers `a` and `b` both serve `echo` (answering `a:<message>` and `b:<message>`), with no
prefix. Plain Strands refuses the duplicate name. A TemporalAgent with both servers offers the
model one `echo`, and the model's call runs on `b`.

Exit 0: the plugin refuses the duplicate name, as Strands does. Exit 1: it does not (the bug).
"""

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 tool, `echo`, that tags its reply with the server's label.
SERVER = """
import sys
from mcp.server.fastmcp import FastMCP

label = sys.argv[1]
mcp = FastMCP(label)

@mcp.tool()
def echo(message: str) -> str:
    return f"{label}:{message}"

mcp.run()
"""
OFFERED: list[list[str]] = []


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


class Scripted(Model):
    """Records the tools it is offered, calls `echo` once, then answers with the result."""

    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):
        yield {"messageStart": {"role": "assistant"}}
        if len(messages) == 1:
            OFFERED.append(sorted(s["name"] for s in tool_specs or []))
            yield {"contentBlockStart": {"start": {"toolUse": {"toolUseId": "t1", "name": "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 TwoServers:
    @workflow.run
    async def run(self) -> str:
        agent = TemporalAgent(
            model="scripted",
            tools=[
                TemporalMCPClient("a", start_to_close_timeout=timedelta(seconds=20)),
                TemporalMCPClient("b", start_to_close_timeout=timedelta(seconds=20)),
            ],
            start_to_close_timeout=timedelta(seconds=10),
            callback_handler=None,
        )
        try:
            return str(await agent.invoke_async("go")).strip()
        except ValueError as err:
            return f"refused: {err}"


async def main() -> int:
    # Control: plain Strands refuses the duplicate name when the agent is built.
    try:
        Agent(model=Scripted(), tools=[mcp_client("a"), mcp_client("b")], callback_handler=None)
        print("plain Strands: no error")
    except ValueError as err:
        print(f"plain Strands: ValueError: {err}")

    plugin = StrandsPlugin(
        models={"scripted": Scripted},
        mcp_clients={"a": lambda: mcp_client("a"), "b": lambda: mcp_client("b")},
    )
    async with await WorkflowEnvironment.start_local() as env:
        async with Worker(env.client, task_queue="q", workflows=[TwoServers], plugins=[plugin]):
            handle = await env.client.start_workflow(
                TwoServers.run, id=f"wf-{uuid.uuid4()}", task_queue="q", execution_timeout=timedelta(seconds=60)
            )
            result = await handle.result()
        history = await handle.fetch_history()
    calls = [
        e.activity_task_scheduled_event_attributes.activity_type.name
        for e in history.events
        if e.HasField("activity_task_scheduled_event_attributes")
        and e.activity_task_scheduled_event_attributes.activity_type.name.endswith("-call-tool")
    ]
    print(f"Temporal: offered {OFFERED[0] if OFFERED else None} | tool calls {calls} | {result}")
    return 0 if result.startswith("refused:") else 1


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

Output on main at 495e507 (temporalio 1.34.0, strands-agents 1.56.0, mcp 1.30.0,
Python 3.13.16):

Temporal CLI 1.9.1 (Server 1.32.0, UI 2.54.1)

Temporal Server:      localhost:35383
Temporal Persistence: in-memory
Temporal Metrics:     http://localhost:42781/metrics
plain Strands: ValueError: Failed to load tool <strands.tools.mcp.mcp_client.MCPClient object at 0xffffb556f610>: Tool name 'echo' already exists. Cannot register tools with exact same name.
Temporal: offered ['echo'] | tool calls ['b-call-tool'] | success: b:hi
exit=1

temporalio-strands-agents 0.1.0 gives the same result.

Expected

As in Strands: the duplicate name raises ValueError, and the caller gives one server a prefix
or drops the tool with tool_filters.

Proposed fix

In _reconcile_mcp_tools, raise Strands' ValueError when a listed name is held by another tool,
instead of replacing it. A server that lists its own tools again still replaces them. Each agent
records which tool each server registered, so agents that share one TemporalMCPClient do not
refuse each other's tools, and a server never removes a name another server holds. Gate the new
behavior with workflow.patched(...), called only where the outcome would differ, so runs that
already replaced a duplicate keep doing so on replay.

This is a breaking change: an agent whose tools share a name now raises at its first model call.
Earlier versions cannot replay runs that record the patch marker, so a rollback needs Worker
Versioning. A branch with the change, tests in tests/test_mcp.py and replay checks is ready.

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