Skip to content

Breaking: refuse duplicate Strands MCP tool names and give each Python agent its MCP tools at its model calls - #184

Merged
campoy merged 17 commits into
mainfrom
fix/strands-python-duplicate-mcp-tool-names
Nov 3, 2026
Merged

campoy merged 17 commits into
mainfrom
fix/strands-python-duplicate-mcp-tool-names

Conversation

@campoy

@campoy campoy commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

TemporalAgent now refuses two tools with the same name, as Strands does, instead of letting the
later MCP server's tool silently replace the earlier one.

  • One BeforeModelCallEvent hook per agent (it was one per MCP server) lists each server that is
    due, in order, as before, and checks the listings so far after each one: a name that is taken,
    or that differs from a taken one only by - or _, raises MCPToolNameConflictError, a
    ValueError and a non-retryable ApplicationError. Names are checked against each other and
    against the agent's other tools as they are after each listing, so a tool that a Signal handler
    adds while a listing runs counts, as ToolRegistry.register_tool() does (dynamic tools such as
    structured output's by exact name).
    A refused turn lists no further servers and leaves the registry as it was. Otherwise the turn's
    tools are applied together, so a name can move from one server to another in one turn.
  • The error gives Strands' message, the servers involved, with each server's own name for the tool
    when a prefix changes it (tool_filters match that name), and a fix: set a prefix (or a
    different one) on the server's TemporalMCPClient, or drop the tool with its tool_filters; for
    two handles of one server, give one a different prefix, narrow one's tool_filters, or pass only
    one.
  • MCPToolNameConflictError is an ApplicationError with non_retryable=True, so an uncaught
    refusal fails the run instead of retrying its Workflow Task (replay would raise it again), and a
    Workflow retry policy does not start another run. This holds with StrandsPlugin on the Worker
    only, whose failure converter does not apply, and on the client.
  • After a tool call, Strands runs the next model call inside its event loop and wraps most errors
    from it in EventLoopException. TemporalAgent re-raises a wrapped MCPToolNameConflictError
    as itself, so a refusal on a later turn can be caught and fails the Workflow like one on the first
    turn. Like Strands' stream_async, it closes Strands' event loop in a finally and awaits it, so
    closing the agent's stream early still waits for AfterInvocationEvent hooks.
  • TemporalMCPClient.load_tools() returns no tools, so every agent gets its MCP tools from the
    hook, whether it was built before or after its clients listed, and has none until its first
    model call. Before, an agent built after a listing got them at construction, where a clash
    raised Strands' plain ValueError, a hot-reloadable @tool could replace a listed tool or the
    other way round, and a listed tool took a sandbox tool's name.
  • A cache_tools=True server is listed once, as before. Later turns check and apply its stored
    listing again, so a refusal lasts as long as the duplicate, an agent that shares an
    already-listed client gets its tools without listing again, and a tool of the server that
    Workflow code replaced or removed is back at the next model call.
  • The agent tracks its MCP tools by name. While a server lists a name, the name is the server's: a
    tool put under it (for example a wrapper) is replaced at the next turn, and removed, also from
    dynamic_tools, when the server stops listing it.
  • A client passed twice to one agent is listed twice per turn, as before, and is not a duplicate. A
    server that lists one name twice is. So is an MCP tool named like a TemporalSandbox tool.
  • README: the duplicate rule, when the error is raised, the failure type, the messages the error
    leaves in agent.messages, how to recover a run that met it, a structured_output_model named
    like an MCP tool (Strands' own ValueError, as in Strands), and which earlier runs can fail to
    replay. The TemporalMCPClient docstring says that two handles of one server on one agent must
    not list the same name (different prefixes or disjoint tool_filters). Breaking: run the Strands MCP activities through temporalio-mcp #190's upgrade note now
    says that same-named tools of different servers are refused, not replaced.
  • TypeScript: TemporalAgent still registers one AfterToolsEvent hook per cacheTools: false
    client, and each still lists only its own server, so the listTools Activities keep their order
    and timing unless a re-listing is refused. The listings go into one round per agent: the hook
    that runs first starts it, and the one that runs last checks the new listings against each
    other, the agent's other tools and Strands' name rules, and applies them together. A name that
    another tool of the agent has (another server's tool or a tool in tools), that differs from one
    only by - or _, that a listing has twice, or that Strands rejects throws Strands'
    ToolValidationError and leaves the registry as it was. Before, addOrReplace() replaced that
    tool. A name can move from one server to another between tool rounds. For a cacheTools: false
    server, a name is the server's from when Strands adds its tool until a re-listing drops it, so a
    tool put under it is replaced at the next listing; a cacheTools: true server is not listed
    again. As at the first listing, the error fails the Workflow Task, not the run. The README states
    the rule, how to fix a refused name, and the upgrade note.

Breaking change: an agent whose tools share a name (two MCP servers that list the same tool
without distinct prefixes, two handles of one server, a server that lists a name twice, or an MCP
tool named like another tool on the agent, including a sandbox tool) now raises
MCPToolNameConflictError at the model call after the listing, and fails the Workflow if the error
is not caught. Before, the later tool replaced the earlier one. Give one server's
TemporalMCPClient a prefix, or drop the tool with its tool_filters. Since #190 both live in
Workflow code: a new prefix renames that server's tools, and new tool_filters can drop some, in
every replay, so an open run whose model called such a tool, or whose Workflow code acted on one
among the agent's tools, fails to replay, whether or not it met the error. Deploy such a change with Worker Versioning; the README says which reset point
recovers a run that met the error. In the TypeScript plugin, a re-listed server that starts
listing such a name now throws Strands' ToolValidationError instead of replacing the other tool,
and the re-listed servers' new tools are applied together. The title starts with Breaking:
because release notes come from commit subjects, and it names the second change too, for Python
only: runs with no duplicate names can fail to replay as well.

The change has no version gate, by decision: for now these plugin fixes add no gates and accept that
some runs from earlier versions do not replay. A run that met one of these duplicates before this
version fails replay with [TMPRL1100]. Runs with names that differ only by - or _ replay when
the earlier version raised Strands' error at the same listing, and fail otherwise: for example with
cache_tools=True, where it went on after one refusal, or when that listing came after a tool call
and Workflow code caught Strands' EventLoopException and went on, since this version raises
MCPToolNameConflictError itself there. Runs whose servers changed their tools during
the run can fail too, though no names clashed: a tool that moves from one server to another in one
turn now stays (the earlier version could lose it), and an agent that shares an uncached client with
another agent now drops the tools the server stopped listing (the earlier version kept them). And
an agent built after another agent listed a client they share has no MCP tools until its first
model call, where the earlier version gave it the last listing at construction: a run whose
Workflow code read that agent's tool_names or tool_registry before then can schedule other
commands and fail too, though no names clashed and the servers kept their tools. So does a run in
which that agent's initial messages end with a call to one of the client's tools: Strands runs it
before the first model call, and it now finds no such tool. An agent that shares a
cache_tools=True client with another agent and was built before that agent's first listing now
gets the client's tools at its first model call, where the earlier version never gave it those
tools: a run whose Workflow code read that agent's tools can take another path, and a run in which
it calls them fails to replay on the earlier version. Last, a turn's
listings are applied together, once every server due that turn has listed, where the earlier
version added each server's tools as soon as it listed. Until then the agent's tools stay as they
were before that turn, and they stay so if a listing fails. A run whose Workflow code read the
agent's tools before the turn's listings were applied can schedule other commands and fail too,
though no names clashed and the servers kept their tools: for example a Signal or Update handler
that ran while a later server listed, even if every listing then succeeded, or code that caught a
failed listing. Two more: a run whose Workflow code replaced or removed a tool of a
cache_tools=True client between model calls, which the earlier version kept for the run and this
version undoes at the next model call; and a run with proactive context compression and an agent
built after another agent listed a client they share, since Strands estimates that agent's first
model call's input tokens before the hooks run, and the estimate now leaves those tools out, so the
summary can run at another model call. Other runs whose tool names never clashed, whose servers
kept their tools, whose Workflow code read an agent's tools only when none of its listings was
pending or unapplied (not during a turn's discovery, not after a failed listing, not on an agent
built after a shared client listed before its first model call, and not on an agent that shares a
cached client with an agent that listed it first) and did not replace or remove a cached client's
tool, whose agents' initial messages do not end with a call to an MCP tool, and that do not
compress context proactively with an agent built after a shared client listed, schedule the same
commands (replay checks below).

Upgrade: let the runs above finish on the earlier version before you upgrade, or keep them
there with Worker Versioning: runs whose agents met a duplicate tool name, runs whose servers
changed their tools, runs whose Workflow code reads the tools of an agent built after a shared
client listed, before that agent's first model call, runs with an agent whose initial messages
end with a call to an MCP tool, runs with an agent that shares a cached client with an agent that
listed it first, runs whose Workflow code can read an agent's tools while its servers list
(Signal and Update handlers, other coroutines) or after catching a failed listing, runs whose
Workflow code replaces or removes a tool of a cache_tools=True client, and runs with proactive
context compression and an agent built after a shared client listed.

The branch has the two earlier commits, four merges of main, d3f653a (one hook per agent, after
the first review), 487e5aa (after the second review), f2a5bf1 (after the third review), and
2819ae6 and 9c219ce after the fourth (the event loop closed and awaited when the stream closes,
the replay tests pinned to where they fail, the registry read after each listing, the
non-retryable error with the plugin on the Worker only, and the upgrade notes on tool visibility
during and after discovery), and 3fddb6d after the fifth (docs and tests: the Update-handler and
Swarm limits of the failure, two more upgrade cases, and tests for a dynamic tool added during a
listing, a listing read when it arrives, and other errors after a tool call staying wrapped).
The last merge, 7834296, ports the change to #190, which runs the MCP Activities through
temporalio-mcp and puts prefix and tool_filters on TemporalMCPClient: the conflict hint
points there, and the tests use temporalio-mcp's names and types. be33d1e answers the sixth
review: hints that name the server's tool, the README's recovery advice now that the prefix lives
in Workflow code, two more upgrade cases, the TypedEvent import dropped, four more tests, and the
TypeScript refusal. 668dc2f merges main (one README conflict next to #371's connection
paragraph, both kept), and eeb69d2 answers the seventh review: the TypeScript servers of a tool
round are listed and checked together, a name is a client's from when Strands adds its tool, more
TypeScript tests, and the Python README's reset advice. 5e14534 answers the eighth review: the
TypeScript hooks per client are back, with the round applied in the last one, so main histories of
two agents side by side replay; Strands' name rules are checked before anything changes; and more
TypeScript tests, a main history and README notes. 3e54d90 answers the ninth review: the reset
advice in both READMEs, a second main history for the replay test, and the TypeScript comments and
declarations.
Review the combined diff against main.

Why?

See #183. _reconcile_mcp_tools called registry.replace() for every listed name already in the
registry. Since #148, distinct prefixes keep two servers apart, but without them a call meant for
one server still runs on the other, with no error.

Checklist

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

  2. How was this tested:

    • 33 new test cases in tests/test_mcp.py (37 in the file). One runs Workflows with two servers
      that list echo, with the plugin on the Worker only: the one that catches the error gets the
      refusal, its Activities are checked and its history replays; the one that does not fails with
      a non-retryable MCPToolNameConflictError. Another runs a tool call, then a listing that
      clashes, caught and uncaught, with the plugin on the Worker only and on the client, and
      maximum_attempts=2; the uncaught run fails with a non-retryable MCPToolNameConflictError
      and is not retried. Four replay histories recorded on main at
      275b1e6 (after Breaking: run the Strands MCP activities through temporalio-mcp #190): distinct names must replay; duplicate names, a shared client whose server dropped a
      tool, and a tool that moved between servers in one turn must fail with a nondeterminism error.
      The others run the agent's hooks through agent.hooks with stand-in listings, for agents built
      before and after their clients listed, check registry entries by identity against each
      server's latest listing, count the listings, add or remove a tool (also a dynamic one) while a
      listing runs, and check that a listing is read when it arrives, not after another agent lists
      the same client. Another checks that Strands still wraps errors other than this one after a
      tool call.
      The replay tests for old histories match the Activity pair where the replay fails.
      The sixth review's four mutants each fail one test: the seen check by exact name (a server
      listing x-y after another's x_y), an unnormalized name map (a local x-y against a listed
      x_y), a dropped name never freed, and the two-servers message without its hint. Another
      test goes through the real _refresh() with only the durable listing stubbed: two servers
      with prefix p both listing x are named with (as 'x'), and rejecting x on one passes; a
      local p_x against a prefixed server gets "drop 'x'"; two handles of one server are refused
      with overlapping tool_filters and accepted with disjoint ones.
      On 487e5aa, the head before the third review, 7 of the cases then in the file fail: the
      refusal after a tool call, agents built after a listing, and a listed name held by another
      tool, its -/_ twin or a sandbox tool. On f2a5bf1, 3 fail: the two Worker-only
      non-retryable checks and the tool added during a listing.

    • A new test in tests/test_hooks.py closes the agent's stream after its first event, and in a
      control reads it to the end; an async AfterInvocationEvent hook runs an Activity. In both,
      the hook finishes and its Activity completes before the Workflow returns, and the history
      replays. It passes on main; without the finally that closes Strands' event loop, the early
      close returns before the hook finishes and Python logs async generator ignored GeneratorExit.

    • The recorded-history loader now lives in tests/common.py, for the two older legacy tests
      too.

    • Locally, ruff check --select I, ruff format --check, pyright, mypy, basedpyright,
      pydocstyle and scripts/ci/check_conventions.py pass, and the full suite passes (217 tests).
      These ran with Python 3.13 and uv 0.13.1, outside the plugin's required-version, so not
      through make. CI covers make lint and make test.

    • [Bug] strands_agents: two MCP servers that list the same tool name silently replace each other's tool #183's reproduction exits 1 on main (the call runs on server b) and 0 with the change
      (refused, naming both servers; run on d3f653a).

    • Replay checks on f2a5bf1, before Breaking: run the Strands MCP activities through temporalio-mcp #190 moved the MCP Activities (not rerun since), without a
      gate, on Workers against a dev server, with stdio MCP servers. 20 runs recorded on main 63d7aec: duplicates with and without cache_tools, a
      server that stops listing a duplicate, -/_ near-duplicates, shared clients with and without
      a local tool of the same name, names moving between servers, and prefixed servers. The 9 whose
      names never clashed, or that met Strands' own -/_ refusal at the same listing, replay on
      the change; the 11 that met a duplicate main let through, or went on past a cached
      near-duplicate, fail with [TMPRL1100]. Every run recorded with the change replays on it; a
      run that does not catch the refusal ends with WorkflowExecutionFailed
      (MCPToolNameConflictError). Of 10 runs started on a main Worker and finished on a new
      Worker with the change, 6 finish: 3 whose names never clashed, one whose duplicate appears
      after the upgrade and is refused then, and 2 whose turn before the upgrade met Strands' own
      -/_ refusal after the same listings. The other 4 fail with [TMPRL1100]. On main, the
      runs of these scenarios recorded with the change whose names never clashed replay; none of
      them reads an agent's tools (see below for runs that do). A server renamed in the
      Workflow fails replay with [TMPRL1100] (control). These scenarios do not hit the
      shared-client drop or the one-turn move; the two recorded histories above cover those. Breaking: run the Strands MCP activities through temporalio-mcp #190
      renamed the MCP Activities, so these histories now fail at their first listing on this head;
      only the four recorded on 275b1e6 above check replay after the port.

    • Stand-in MCP Activities, on f2a5bf1 and 9c219ce, before Breaking: run the Strands MCP activities through temporalio-mcp #190 (their main histories,
      recorded at 3488fbe, now fail at the Activity rename instead; the reviewer reran these three
      shapes and round five's two on post-Breaking: run the Strands MCP activities through temporalio-mcp #190 code, and each still changes commands both ways): a Signal that adds a local echo
      while the listing runs is now refused, and no remote call runs (on f2a5bf1 the call ran on
      the server). With maximum_attempts=2 and the plugin on the Worker only, an uncaught refusal,
      on the first turn and after a tool call, is non-retryable and fails one run (on f2a5bf1,
      retryable, and a second run started). A run recorded on main at 3488fbe whose Workflow
      code schedules an Activity when a second agent sharing a listed client has echo in
      tool_names replays on main and fails with [TMPRL1100] on this PR, cached and uncached.
      A run recorded on main whose agent lists server pa (echo), then fails to list server
      pb, and whose Workflow code catches the ActivityError and schedules an Activity when echo
      is in tool_names, kept echo and scheduled it on main; with this PR the agent has no
      tools and the Activity is not scheduled, so the main history fails with [TMPRL1100]. Runs
      where the first listing fails, or where both listings succeed, replay both ways (controls).
      A run recorded on main whose agent lists server pa (echo) and then server pw, both
      successfully, and whose Signal handler, run while pw lists, schedules an Activity when
      echo is in tool_names, saw ['echo'] and scheduled it on main; with this PR the handler
      sees no tools, so the main history fails with [TMPRL1100]. The same Signal sent after the
      turn's listings sees both tools on both versions, and its runs replay both ways (control).
      Rolling back is affected the same way: the runs of these three kinds recorded with this PR,
      with stable, distinct tool names, fail to replay on main with [TMPRL1100], so a run with
      no clash is not by that alone safe to move back to the earlier version.

    • TypeScript: one test runs each case with maxCachedWorkflows: 0, so every Workflow Task
      replays, and replays its history at the end; each result ends with the agent's tool names.
      Refused, with no call to the new tool and the tools unchanged: a server that starts listing
      another server's tool, with the servers in either order; two servers that start listing -/_
      twins; a server that starts listing the name of a tool in tools, a -/_ twin of one, a
      name twice, two -/_ twins, or a name Strands rejects; and a failing listing after another
      server's adds a tool. Accepted: a tool that moves from one server to another, with the
      servers in either order (the model's call runs on the new server); a tool that Workflow code
      puts under the server's name in the first tool round (the server's tool is back); and a name
      the server drops (it is gone, also with a tool put under it). Mutants that register the hooks
      in reverse, skip the removal of dropped names, key the -/_ checks between or within
      listings by the exact name, apply each listing as it arrives, or skip Strands' name rules
      each fail the tests.

    • TypeScript, timing: histories/mcp-side-by-side-017d88a.json was recorded on main at
      017d88a with two agents side by side, one re-listing servers a and b and one with server
      c and an Activity hook, whose completions land in one Workflow Task. A test replays it. Of
      six such histories, the three where b's re-listing completed first fail to replay on the
      previous head, eeb69d2, which listed all servers in one hook; all six replay on this head.
      The same test replays histories/mcp-beside-coroutine-017d88a.json, also recorded on main:
      an agent re-listing a and b, with a coroutine beside it whose Activity completes in the
      same Workflow Task as b's re-listing. Main scheduled a-listTools before the coroutine's
      next Activity, so a re-listing scheduled one microtask later fails the test.
      Locally make lint and make test pass (92 tests), with Node 24.

  3. Any docs updates needed?
    The MCP section of the Python README now states the duplicate rule, the failure type, how to
    recover a run that met it, and which earlier runs can fail to replay. The TypeScript README
    states the rule for re-listed servers, including that a name can move between them, and adds an
    upgrade note.

Not covered:

  • A mixed rollout, with old and new Workers on one Task Queue.
  • A TemporalMCPClient that outlives a run in one Worker process (an unsandboxed runner) keeps
    _fetched and _tools, so with cache_tools=True a second run skips the listing that a replay
    in a fresh process schedules. This is the same on main, and the change does not touch it.
  • A failed or cancelled model Activity after a tool call is still wrapped in EventLoopException by
    Strands and leaves the run open, as on main; this PR unwraps only its own error.
  • A Signal handler that adds a BeforeModelCallEvent callback with a lower order while a
    listing runs makes this version list every due server again, where main re-ran only the
    in-flight server's hook (Strands iterates the live callback list).
  • The hook still runs after user BeforeModelCallEvent hooks, as before. Running it first would
    move its Activities before theirs, which changes the commands of runs without a clash.
  • temporalio 1.34.x still bundles the old code as temporalio.contrib.strands. No backport here.

When two MCP servers listed the same tool name on one TemporalAgent, or an
MCP tool had the name of another tool on the agent, the later tool silently
replaced the earlier one, so a call meant for one server ran on the other.
Strands refuses duplicate tool names with ValueError.

TemporalAgent now raises Strands' ValueError at the model call when a listed
name is already held by another tool. A server that lists its own tools
again still replaces them. Each agent keeps track of which server registered
each tool, so agents that share one TemporalMCPClient keep their tools when
the other agent lists it, and a server never removes a name another server
holds. Duplicates are found before the registry changes, and a name Strands
refuses during registration restores the registry. An agent lists a refused
server again on its next turn, even with cache_tools=True, so a caught error
is raised again while the conflict lasts. When a listed name is held by a
server that lists again later in the same turn, those servers are listed
first and the listings are checked together, so a name can move between
servers in one turn.

Breaking change: an agent whose tools share a name now raises ValueError at
its first model call. Give one server a prefix or drop the tool with
tool_filters. Runs that already replaced a duplicate keep the old behavior
(patch "strands-refuse-duplicate-mcp-tool-names"). Earlier versions cannot
replay runs that record the patch marker, so roll back only with Worker
Versioning or after those runs finish.
Fixes add no version gates for now, so remove the
`strands-refuse-duplicate-mcp-tool-names` patch and the old rules it
kept for earlier runs: the later tool replacing the earlier one, the old
removal rule, and the partial registration when Strands refuses a name.
The three tests of those old rules go too.

Breaking change: a run started before this version whose agent had two
tools with the same name, whose server stopped listing a name another
server held, or whose registration Strands refused, now takes the new
path on replay. It raises `ValueError` where the history has a model or
tool call, so it fails to replay. Let those runs finish before you
upgrade, or use Worker Versioning.
@campoy
campoy marked this pull request as ready for review October 28, 2026 23:57
@campoy
campoy requested a review from a team as a code owner October 28, 2026 23:57

@DABH DABH left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the duplicate-tool-name refusal. The main concern is the PR's claim that "runs whose tool names never clashed schedule the same commands": three paths below break that claim and were proven by recording a history on main and replaying it on this branch against a dev server. Lint and all 78 tests pass on the head.

Gate. Per the PR body, the first commit had a workflow.patched gate and the replay checks ran only on that gated version. The repo has two earlier command-altering Python changes that are gated with legacy-history tripwire tests (_temporal_model.py context-window-overflow recovery, and the deepagents retire-result-cache change). Old code emitted no marker when it silently replaced a duplicate, so operators cannot tell which in-flight runs are affected and the README remedy must be applied blind. Either restore the gate or record the decision explicitly, rerun the replay checks on the ungated build, and add main-recorded legacy_*.json histories for the clash and non-clash paths.

Altitude. A single BeforeModelCallEvent hook per agent (list every uncached provider in order, validate the turn's whole MCP tool set once against the agent's other tools, apply in place) matched main's list-tools sequence on every non-clash scenario tried and removes about 130 lines of per-provider state. See the comment on line 121.

Note on the private-API tests and one more README item are inline below.

self._mcp_unaccepted: set[TemporalMCPClient] = set()
# Providers listed early in this turn by an earlier provider's hook.
self._mcp_listed_early: set[TemporalMCPClient] = set()
for provider in self._mcp_providers:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Altitude. Per-provider hooks exist because the old code had them, and this PR then rebuilds a whole-set view by special-casing hook order (_held_by early-lists later providers, _mcp_listed_early tells their hooks to skip, _mcp_unaccepted remembers refusals, two except BaseException blocks repair those sets). Each new interaction in the findings below needed one more set or branch, the ownership predicate is written four times, and the __init__ comment above still says cache_tools=True is "guarded by _fetched". A prototype with one hook per agent matched main turn by turn on the scenarios I tried (including the shared-later-agent case this PR gets wrong), produced the same 14-activity history under old, PR and prototype with clean cross-replays, and passed the PR's 11 end-to-end tests (the 9 hook-level tests would need rewriting). Trade-offs to decide on purpose: every uncached provider is listed before a refusal, and a refused cached provider is not re-listed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, done in d3f653a. There's now one BeforeModelCallEvent hook per agent: it lists each server that is due, in order, then checks the turn's whole MCP tool set against itself and the agent's other tools, and applies it. _held_by, the early listing, _mcp_unaccepted, _mcp_listed_early and both except BaseException blocks are gone, and the __init__ comment is true again.

I took both trade-offs: every uncached server is listed before a refusal (this only changes turns that clash), and a refused cached server is not listed again. Each turn checks its stored listing again instead.

self, provider: TemporalMCPClient
) -> HookCallback[BeforeModelCallEvent]:
registry = self.tool_registry.registry
self._mcp_owned.setdefault(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_mcp_owned is seeded from provider._tools at construction. If a TemporalMCPClient object survives across workflow runs in one worker process (unsandboxed runner, passthrough_all_modules, or the handle defined in a module passed through the sandbox, which the class docstring recommends), run 2 starts from run 1's stale listing and makes different early-listing decisions than a fresh-process replay, which then fails with [TMPRL1100]. Not reproducible under the default sandbox (the module is re-imported per run), so this one is plausible rather than confirmed. Keeping listing state per run, or documenting that handles must be constructed inside the workflow, would close it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The hook no longer uses this state to decide what to list. It lists every server that is due, in order, as main does, so a stale _tools can't change the commands with cache_tools=False.

What's left is main's own problem with a handle that outlives a run: _fetched and _tools carry over, so with cache_tools=True run 2 skips a listing that a fresh-process replay schedules. This PR doesn't change that, so I listed it under "Not covered" in the description and would fix it separately.

later = [
other
for other in self._mcp_providers[
self._mcp_providers.index(provider) + 1 :

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same client instance listed twice refuses its own listing. self._mcp_providers.index(provider) returns the first occurrence. With a = TemporalMCPClient('a'); TemporalAgent(tools=[a, a]) (or nested lists that share a client, such as [*BASE, *RESEARCH]), hook #2 computes later = [a], _held_by is true because _mcp_owned[a] already holds echo, so it lists a a third time and seen flags echo: ValueError: Tool name 'echo' already exists on every turn, with a prefix/tool_filters hint that cannot apply. Main listed twice and replace()d with no error, and I verified a main-recorded history ['echo_a-list-tools','echo_a-list-tools','invoke_model'] fails replay on this branch with [TMPRL1100] even though no two tools ever shared a name. Fix: give each hook its position (enumerate in __init__) and use later = [o for o in self._mcp_providers[pos+1:] if o is not provider and not self._cached(o)]. Do not dedupe _mcp_providers, which would change main's command sequence.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: the hook keeps one listing per client, so tools=[a, a] lists a twice per turn, as main does, and is not a duplicate. test_mcp_same_client_twice_on_one_agent covers it.

]
if not self._cached(other)
]
if self._held_by(event, listing, later):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A dash/underscore near-duplicate moving between servers changes the command sequence. On main, when server A lists x_y while B's x-y is registered, register_tool raises Strands' normalised-name error after one list-tools. Here _held_by normalises names, so B is early-listed (two commands) and the move succeeds. A main-recorded history in which the workflow caught the error and kept going fails replay on this branch ([TMPRL1100], "Activity machine does not handle this event ... TimerStarted"). Low likelihood, so the actionable part is the PR description and README scope: the README's "such a duplicate" carve-out describes replaced tools, not this case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, kept as is. On main that turn raised after one listing; here it lists every due server first. The PR description now says that a main run that caught that error and went on doesn't replay, and the README rule names -/_ near-duplicates.

self._mcp_listed_early.add(other)
except BaseException:
# Nothing was checked; the next turn lists them again.
self._mcp_unaccepted.update(u.provider for u in listings)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A refused or failed batch re-lists cache_tools=True providers that main would skip. Marking every already-listed provider _mcp_unaccepted here (and in refuse() below) includes a cached provider whose own listing succeeded. Scenario: agent built after shared client q listed echo, plus p = TemporalMCPClient('p', cache_tools=True); p lists, _held_by early-lists q, that activity fails, the workflow catches and re-invokes. Next turn main runs ['q-list-tools']; this branch runs ['p-list-tools','q-list-tools']. Verified on a dev server: a main-recorded history fails replay with [TMPRL1100], and the main run never raised a ValueError, so the README's "with such a duplicate" warning would not reach this user. It also means cache_tools=True stops meaning "list once" after any refusal (a cached server is re-listed every turn while the workflow keeps catching the error). Suggest keeping the refused _MCPListing on the agent for cached providers and re-reconciling from it instead of re-running the activity.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed by the rewrite: a cached server is listed once, refused or not, and later turns check its stored listing again. In your scenario the next turn runs only q-list-tools, as on main. test_mcp_duplicate_refused_again_after_caught[True] and test_mcp_failed_listing_changes_nothing assert the listing counts.

seen: set[str] = set()
for listing, new in news:
for name in new:
if name in seen or (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An MCP tool named like a sandbox-vended default is refused, unlike native Strands. TemporalAgent(tools=[TemporalMCPClient('s')], sandbox=TemporalSandbox('sb')) where s exposes sandbox_shell (directly, or via MCPClient(prefix='sandbox') over a server exposing shell): load_tools() is empty at construction, so Agent.__init__ registers the vended sandbox_shell, and the first-turn hook finds the listed name held by a tool it does not own and raises on every turn. Native strands.Agent(tools=[provider], sandbox=...) lets the provider tool win (Strands skips the sandbox tool with a debug log), and so did main. The outcome also depends on construction order (an agent built after the shared client listed accepts it). Either let listings replace sandbox-vended defaults (record their identities at construction) or narrow the README claim and add a test documenting the refusal.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went with the first option. TemporalSandbox.get_tools() now returns the same tool objects on every call, the agent records the ones Strands registered, and a listed tool with the same name replaces them, as on main and in native Strands. A -/_ variant of a sandbox tool's name is still refused, as Strands does when it registers the sandbox tools. test_mcp_tool_takes_a_sandbox_tool_name covers it.

for listing, new in news:
for name in new:
if name in seen or (
name in reg.registry

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

taken consults only reg.registry, never reg.dynamic_tools. With structured_output_model=Weather and an MCP tool whose agent name is Weather, Strands registers the structured-output tool in dynamic_tools before the hook, so this check passes and the MCP tool is registered. get_all_tools_config prefers registry (the model sees the MCP schema) but _lookup_tool prefers dynamic_tools (calls hit the pydantic validator); with cache_tools=False the cycle-2 re-list's replace() then deletes the structured-output tool, the forced structured-output call is dispatched to the server as a real p-call-tool, and the next invocation raises from register_dynamic_tool before any hook runs, wedging the agent. Reproduced on this branch and on main. Pre-existing, but the README now promises "raises ValueError, as Strands does". One-line fix: name in reg.registry or name in reg.dynamic_tools, and check identity before the dynamic_tools.pop in the drop loop below.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: the check includes dynamic_tools, so an MCP tool named like the structured-output tool is refused. The drop no longer touches dynamic_tools: MCP tools are never dynamic, so there it could only remove another tool's entry. test_mcp_tool_named_like_a_dynamic_tool_is_refused covers it.

"with exact same name. Set a different prefix on the "
"MCPClient or drop the tool with tool_filters."
)
registry, dynamic_tools = dict(reg.registry), dict(reg.dynamic_tools)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two refusal mechanisms with two message formats. The exact-name taken check hand-copies Strands' message and adds the prefix/tool_filters hint, while the -/_ case is left to Strands behind this two-dict snapshot and the clear()+update() rollback below. Inside the try, replace() runs only for names already registered and register_tool() only for new names, so the only exception it can raise is Strands' normalised-name check (verified by instrumenting about 28k hook calls). A user whose second server lists foo_bar beside another server's foo-bar gets Strands' message with no hint, while the same-name case gets the hint (the tests pin both texts). One up-front validation of exact and normalised names against set(reg.registry) - drop plus the batch so far makes the mutation loop infallible and removes the snapshot, the rollback and the second refuse(). A variant doing this passed the PR's hook-level tests and a 3000-scenario differential against this PR with identical exceptions and state.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: one check up front covers exact and -/_ names, against each other and the agent's other tools, so registration can't fail afterwards. The snapshot, the rollback and the second refuse() are gone, and both cases get the same hint.

Comment thread python/strands_agents/README.md Outdated

Each factory returns a fully configured `MCPClient`, so you can pass options like `tool_filters`, `prefix`, `elicitation_callback`, or `tasks_config` to it.

Tool names must be unique on one agent: when two tools have the same name, for example two servers that both list `search`, the agent's first model call raises `ValueError`, as Strands does when it builds the agent. Give one server a `prefix`, or drop the tool with `tool_filters`. Earlier versions let the later server's tool replace the earlier one, so a run that started before you deploy this version with such a duplicate can fail to replay on it: let those runs finish first, or use Worker Versioning.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documentation and diagnostics do not match the behavior: (1) "the agent's first model call raises ValueError" is wrong for cache_tools=False, where a clash that appears after a server restart raises at that later turn (the PR's own test_mcp_name_moves_between_servers does exactly this). (2) The unchanged next paragraph's "list the tools just once ... one fewer activity per turn" is false after a refusal. (3) The TemporalMCPClient docstring's "Multiple handles may reference the same server name" now yields a first-turn refusal if two such handles are on one agent. (4) The error names neither the holding server nor that prefix/tool_filters cannot unstick an in-flight run, because the recorded listing replays. The upgrade note should also name the version once chosen.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All four addressed:

  1. The README now says the model call after the listing raises: the first one, or, with cache_tools=False, a later one if a server starts listing such a name.
  2. True again: a refused cached server is not listed again.
  3. The docstring now says two handles for one server go on different agents.
  4. The error names the servers (MCP servers 'echo_a' and 'echo_b' both list it.), and the README says a new prefix or filter doesn't fix a run that already met the error: reset it to before that listing.

I'll put the version in the upgrade note once the release is picked.

Comment thread python/strands_agents/tests/test_mcp.py Outdated
return TemporalMCPTool(server, info, {})


async def _run_hook(hook: Any, event: Any) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The hook-level tests call closures from the private _make_mcp_refresh_hook with SimpleNamespace events, so they never execute the callbacks registered on agent.hooks. Verified with mutants: registering the MCP hooks in reverse order leaves these tests identical and green, while the production path (agent.hooks.invoke_callbacks_async(BeforeModelCallEvent(...)), which works outside a workflow) lists server c twice per turn and keeps c's tool instead of a's. A mutant that leaves a stale tool object in place instead of reg.replace(tool) passes all 9 hook cases because registry[name]._server == 'a' holds for any object the client ever produced. test_mcp_duplicate_tool_names_are_refused also does not assert get_activities(history) == ['echo_a-list-tools', 'echo_b-list-tools'], unlike its siblings. Suggest driving the in-order scenarios through invoke_callbacks_async, asserting identity against the provider's latest listing, and asserting the activity sequence; only the failed-listing test needs direct out-of-order invocation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reworked: the hook tests now go through agent.hooks.invoke_callbacks_async(BeforeModelCallEvent(agent=agent)), compare registry entries by identity with each server's latest listing, and count the listings. With one hook there's no order left to get wrong. test_mcp_duplicate_tool_names_are_refused now asserts the Activity list too.

One BeforeModelCallEvent hook per agent lists every provider that is due, in
order, as the hooks per provider did, then checks the turn's MCP tools against
each other and the agent's other tools, and applies them. This replaces the
early listing, the per-provider refusal state and the registry rollback.

- A provider passed twice keeps one listing and is not a duplicate.
- A cached provider is listed once; later turns check its stored listing again,
  so an agent that shares an already-listed cached client gets its tools, and a
  refusal does not make it list again.
- The check covers exact and '-'/'_' names, a name one server lists twice, and
  dynamic tools such as structured output's, and names the servers involved.
- MCP tools are tracked by name, so one replaced in place stays its server's.
- A listed tool takes the name of a TemporalSandbox tool, as a tool passed in
  tools=[...] does; TemporalSandbox now returns the same tools on every call.
- README: when the error is raised, the prompt left in agent.messages, and how
  to recover a run that met it.
- Hook tests run through agent.hooks; two histories recorded on main check
  which runs replay.
@campoy

campoy commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

On the gate from the review summary: no gate, by decision. For now these plugin fixes add no version gates and accept that some runs from earlier versions don't replay; the description says which runs and how to upgrade.

I reran the replay checks on the ungated build (d3f653a) against a dev server, with runs recorded on main at 63d7aec: the 9 runs whose names never clashed replay, and the 11 that met a duplicate don't. Details are in the description. I also added two main-recorded histories as tests: legacy_mcp_distinct_names.json must replay and legacy_mcp_duplicate_names.json must fail with a nondeterminism error.

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed d3f653a against base 63d7aec. make lint and all 153 existing tests pass with Python 3.13 and uv 0.12.5. Two additional hook-level regression checks pass against the base implementation and fail against this head; details are inline.

Comment on lines +203 to +204
if provider not in listed and tool.tool_name in self._mcp_names:
continue

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Scope the cached-tool skip to the provider this agent accepted.

_mcp_names records names across every provider, so this condition can skip a cached provider whose tool has never been installed on this agent. Reproduction:

  1. Let a warm-up agent list client A's echo.
  2. Construct the target agent with [A, B], where B has cache_tools=True and has not listed yet. Construction installs A's echo through load_tools().
  3. Let another agent list B's echo.
  4. Have A stop listing echo, then run the target's before-model hooks.

Validation succeeds, but echo is in both new and the old _mcp_names, so it is not removed; B is then skipped here. The registry retains A's old stub and tool calls dispatch to a-call-tool even though only B now lists the name. On the base implementation this scenario loses the tool; this change newly leaves a callable routed to the wrong server.

Only skip a cached listing when this agent already accepted that provider's tool, rather than any MCP tool with the same name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in 487e5aa by dropping the skip, which the other review also suggested. Every listed tool is now applied each turn, so in your scenario echo comes from B. test_mcp_name_moves_to_a_cached_server follows your steps.

Comment on lines +196 to 197
for name in self._mcp_names - new:
reg.registry.pop(name, None)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Remove a dropped MCP-owned tool's dynamic replacement too.

Removing only reg.registry[name] leaves the tool callable if its in-place replacement is dynamic. Reproduction: accept an MCP echo, load a replacement @tool(name="echo") through agent.tool_registry.process_tools([path]), then have the server return an empty listing. Strands marks the loaded replacement dynamic and stores it in both maps, but this loop removes only the main entry.

After refresh, get_all_tools_config() still advertises echo from dynamic_tools, and Strands' executor still resolves and executes that replacement. This regresses the base implementation, which removed it from both maps. Remove the matching dynamic entry when dropping the MCP-owned name, with an ownership check if needed to preserve unrelated dynamic tools.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 487e5aa: a dropped name is removed from dynamic_tools too, as on main. No ownership check is needed there: register_dynamic_tool refuses names that are in the registry, so a dynamic entry under an MCP name can only be a replacement of the MCP tool. test_mcp_listing_replaces_a_tool_replaced_in_place now drops a dynamic replacement and checks both maps.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second pass, on the rewritten head. The single-hook design, the name-based ownership set, the dynamic_tools check, the sandbox precedence rule, the legacy histories and the README notes address most of the previous round: the duplicate-instance, shared-cached-client, refused-batch and dynamic-tools findings no longer reproduce, and the hook-level tests now drive the real hook registry. Lint and the 17 hook-level plus legacy-replay tests pass; one finder fuzzed the hook with 12,000 random multi-turn trials and found no leaked Strands error. What follows was reproduced on this head unless marked otherwise.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

The gate question stands as documented (the author's call; the precedent is the gated context-window change in _temporal_model.py). The one new replay note is below on line 186: the old version also raised for some clashes, and those runs break too.

Not re-raised: the altitude alternatives weighed this round (listing in _convert_prompt_to_messages, a probe ToolRegistry to inherit Strands' rule, identity-based ownership) are not clearly better than what is here; _check_mcp_tools copies Strands' two-line rule and message text, which is a maintenance coupling worth a comment but not a defect. Deduping _mcp_providers or listing providers concurrently would both need a workflow.patched gate and are out of scope.

# Tools the servers dropped or renamed since the last turn. There is no
# public unregister, so remove them from the registry directly.
for name in self._mcp_names - new:
reg.registry.pop(name, None)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: the drop loop no longer pops reg.dynamic_tools, which main did. If a user replaced an MCP tool in place with a dynamic-marked tool (wrapper.mark_dynamic(); agent.tool_registry.replace(wrapper), or a path-loaded tool via process_tools, which Strands marks dynamic and lets overwrite because DecoratedFunctionTool.supports_hot_reload is True), then the server drops the name: only registry is popped, dynamic_tools['echo'] survives, get_all_tools_config() still advertises it and the executor resolves dynamic_tools first, so the model keeps calling a tool the server removed. When the server lists the name again, held (built from dynamic_tools) contains it and _check_mcp_tools raises 'another tool of the agent has it' on every later turn (reproduced by four independent probes). Either pop both dicts as before, or neither.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 487e5aa: it pops both dicts again, as on main. test_mcp_listing_replaces_a_tool_replaced_in_place now covers a dynamic replacement.

self._vended = {
tool.tool_name: tool
for tool in (sandbox.get_tools() if sandbox is not None else [])
if registry.get(tool.tool_name) is tool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _vended is an identity match against sandbox.get_tools(), which breaks in both directions. (1) A TemporalSandbox subclass that overrides get_tools() to build fresh tools per call (the pattern Strands' own DockerSandbox/SSHSandbox use, e.g. to customize descriptions) yields _vended == {}, so a server listing sandbox_shell is refused with 'another tool of the agent has it' instead of taking the name as the README promises and as main did (reproduced). (2) A sandbox tool the user passed explicitly, tools=[*sb.get_tools(), a] or tools=[sb.get_tools()[1]], is the same object, so it is classified as vended and silently replaced by a listed tool, contrary to the rule that tools=[...] wins (reproduced). Nothing documents that get_tools() must return stable instances. Record what the sandbox loop in Agent.__init__ actually registered (by name plus origin) rather than relying on object identity, or state the contract on TemporalSandbox.get_tools.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the identity match was fragile. I switched to the other option from your first round: an MCP tool named like a sandbox tool is now refused, like any other tool of the agent, and TemporalSandbox is back to main's version. The README rule lists sandbox tools, and test_mcp_tool_named_like_a_sandbox_tool_is_refused documents the refusal.

new = {tool.tool_name for tools in listings.values() for tool in tools}
# Tools the servers dropped or renamed since the last turn. There is no
# public unregister, so remove them from the registry directly.
for name in self._mcp_names - new:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: a vended tool that gave way to an MCP tool is never restored. Turn 1: server a (cache_tools=False) lists sandbox_shell, the takeover is allowed and replace() installs the MCP tool. Turn 2: the restarted server no longer lists it, this loop pops the name, and the registry is left with sandbox_file_editor only while _vended still holds the shell tool (reproduced). The agent loses its shell for the rest of the run after a transient name overlap, which neither the tools=[...] analogy nor native Strands (static tool set) predicts. Re-registering self._vended[name] when popping a name it holds makes the precedence symmetric.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moot now: a listed tool no longer takes a sandbox tool's name (see the thread on line 173), so a sandbox tool is never replaced.

if holder is provider:
source = f"MCP server '{provider.server}' lists it twice."
elif holder is not None:
source = (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the two-servers message is unactionable for two handles of one server. TemporalAgent(tools=[TemporalMCPClient('x'), TemporalMCPClient('x', cache_tools=True)]) (the case the TemporalMCPClient docstring now describes) produces "MCP servers 'x' and 'x' both list it. Set a different prefix on one server's MCPClient", but both handles resolve to the single worker-side factory for x, so there is no second prefix to set (reproduced). holder is provider is False so the 'lists it twice' branch is not taken either, and that branch's wording is also off for one server listing foo-bar and foo_bar (two distinct names). Two handles with the same server are knowable in __init__; refusing there with 'pass one handle', or a dedicated message when holder.server == provider.server, would help. The two-handle case previously worked (the second handle's tools won), so in-flight runs using it also stop replaying.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Two handles of one server now get "The agent has two TemporalMCPClient handles for MCP server 'x'. Pass only one.", and one server that lists foo-bar and foo_bar gets "MCP server 'x' lists both names." Both are cases in test_mcp_server_listing_a_name_twice_is_refused, and the README replay note names the two-handle case.



async def test_mcp_same_client_twice_on_one_agent(monkeypatch: pytest.MonkeyPatch):
"""A client passed twice is listed twice per turn, as before, and is not a duplicate."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: 'is not a duplicate' holds only before the client has listed. load_tools() returns the current _tools, so an agent built after a shared client listed (a module-level client, as the docstring recommends, with a second agent later in the workflow) fails at construction from Strands: TemporalAgent(tools=[a, a]) raises ValueError: Failed to load tool <TemporalMCPClient ...>: Tool name 'echo' already exists. Cannot register tools with exact same name. (reproduced); tools=[_local_echo, a] fails the same way, while tools=[a, _local_echo] constructs because @tool functions are hot-reloadable and silently overwrite the MCP tool, which the hook then refuses on turn 1. Pre-existing Strands behavior, but this test and the README present construction order as irrelevant; mention construction-time refusal for agents built after a listing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added. The README now says that an agent built after its clients listed gets their tools at construction, so Strands may raise there instead. This test also checks that TemporalAgent(tools=[a, a]) raises at construction once a has listed.

tool.tool_name
for provider in self._mcp_providers
for tool in provider._tools
if registry.get(tool.tool_name) is tool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 simplification: if registry.get(tool.tool_name) is tool is dead on the normal path and wrong on the only other one. After a successful Agent.__init__ every tool a provider's load_tools() returned is in the registry (process_tools raises otherwise). The only way the condition is false is an AgentInitializedEvent hook that replace()s a provider tool during construction, and there the filter leaves the wrapped name out of _mcp_names, so the first turn refuses the server's own tool with 'another tool of the agent has it', contradicting the in-place-replacement rule the tests pin. {t.tool_name for p in self._mcp_providers for t in p._tools} is simpler and consistent. The same identity filter on _vended (line 173) is subsumed by the check-time identity test at line 235, so _vended could be the plain list of the sandbox's tools (or read at check time) and the vended is None or ... clause goes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: _mcp_names is now the plain set of the providers' tool names. _vended is gone with the sandbox change.

if registry.get(tool.tool_name) is tool
}
if self._mcp_providers:
self.hooks.add_callback(BeforeModelCallEvent, self._refresh_mcp_tools)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the refresh hook is registered last at default order, so every user hook from hooks=[...] and Strands' own before-model hooks observe the previous turn's registry. A user hook that gates or cancels the model call based on available tools decides on stale data (and the listing activities, and the duplicate refusal, still run even though the model call is cancelled), and event.projected_input_tokens (consumed by ConversationManager proactive compression) excludes all MCP tool specs on turn 1 (reproduced). Pre-existing ordering, but the single-hook rewrite is the natural place to register with order=HookOrder.SDK_FIRST.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left the order as is. Moving the hook first would schedule the list-tools Activities before any Activities that user BeforeModelCallEvent hooks schedule (for example with activity_as_hook). That changes the commands of runs whose names never clashed, so like deduping or listing concurrently, it belongs in its own change.

}
# The same tools on every call, so an agent can tell them from a tool of
# the same name passed in tools=[...].
self._tools: list[AgentTool] = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: vended tool objects are now shared by every agent that receives the same TemporalSandbox, so per-instance mutable state (mark_dynamic(), the tool_spec setter) leaks between agents where main vended fresh instances (reproduced: a1.tool_registry.registry['sandbox_shell'] is a2... is True). No Strands library path mutates vended tools, so this needs user code; low. The eager construction also runs make_file_editor/make_shell (two pydantic create_model calls, ~0.8 ms) on every TemporalSandbox(...) even when it is used standalone and never attached to an agent; building lazily on the first get_tools() keeps the identity the agent relies on.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moot now: TemporalSandbox is back to main's version, which makes new tools on each call.

Comment thread python/strands_agents/tests/test_mcp.py Outdated
# The run now completes where it scheduled the model call.
with pytest.raises(
NondeterminismError,
match="Complete workflow machine does not handle this event.*ActivityTaskScheduled",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this pins sdk-core's exact nondeterminism wording. A temporalio bump picked by the nightly sync-latest lane that rewords 'Complete workflow machine does not handle this event' (it has changed before) breaks the test and opens a spurious nightly issue although replay still correctly raises NondeterminismError. Matching only the exception type, or ActivityTaskScheduled, checks what the test proves.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: it now matches only NondeterminismError.

Comment thread python/strands_agents/tests/test_mcp.py Outdated
).replay_workflow(history)


def _legacy_history(name: str) -> WorkflowHistory:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: _legacy_history is the third in-plugin copy of the recorded-history loader (tests/test_legacy_history_replay.py has HISTORIES plus _legacy_history, and tests/test_model_context_overflow_legacy_replay.py inlines it again), each with a different workflow-id argument. Promote one load_history(name, workflow_id=...) to tests/common.py, which this file already imports.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: load_history(name, workflow_id=...) is in tests/common.py, and all three files use it.

- Check the listings so far after each one, so a refused turn lists no
  further servers, as one hook per server did when Strands refused a name.
- Raise MCPToolNameConflictError, a ValueError that StrandsPlugin registers as
  a Workflow failure type, so an uncaught refusal fails the run instead of
  retrying its Workflow Task.
- Apply every listed tool each turn: drop the skip for cached listings, which
  could keep another server's tool under a moved name.
- Remove a dropped name from dynamic_tools too, as before.
- Compare dynamic tools' names exactly, as Strands does.
- Refuse an MCP tool named like a sandbox tool, as for the agent's other tools,
  and stop sharing the sandbox's tool objects between agents.
- Name two handles of one server, and two names one server lists, in the error.
- README: the failure type, construction-time refusals, which earlier runs
  can fail to replay, and that a listed name stays the server's.
- Tests: one history loader in tests/common.py; the legacy replay test matches
  only the error type.
@campoy

campoy commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks both. Round 2 is in 487e5aa, after a merge of main. Replies are inline. I also added a comment on _check_mcp_tools saying it applies ToolRegistry.register_tool()'s rule, and updated the description with the new replay results.

@campoy
campoy requested review from DABH and brianstrauch October 29, 2026 20:06

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 487e5aa. make lint and all 190 shipped tests pass. One remaining upgrade-warning gap was confirmed with an additional recorded-history replay check.

new = {tool.tool_name for tools in listings.values() for tool in tools}
# Tools the servers dropped or renamed since the last turn. There is no
# public unregister, so remove them from the registry directly.
for name in self._mcp_names - new:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Include shared-client tool removals in the upgrade warning.

Tracking removals per agent also changes replay for runs whose tool names never clashed. Reproduction: construct agents A and B with the same workflow-local, uncached TemporalMCPClient; A lists echo, B subsequently lists other, then A runs again with other still listed. The base implementation retains A's old echo because it computes old_names from the shared client's latest listing; this loop now removes it.

I recorded a run on the exact base agent where the model calls echo on A's later turn. The history replays successfully on base but fails on this head with [TMPRL1100]: the scheduled review-call-tool Activity is replaced by a review-list-tools command because echo is no longer registered. No duplicate names occur, and the client is created inside the Workflow, so this is separate from the acknowledged cross-run client-state issue.

The new removal behavior fixes stale tools, but the README's duplicate-only upgrade warning and the PR's claim that non-clashing runs retain their command sequence miss this case. Please expand the warning to cover shared clients whose listings drop or rename tools, and add a recorded-history regression test; alternatively preserve compatibility for this path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I kept the new behavior, which drops the stale tool, and covered it in f2a5bf1:

  • The README upgrade note now names an agent that shares an uncached client whose listing drops or renames tools.
  • legacy_mcp_shared_client_drop.json, recorded on main at 63d7aec with your scenario (A lists echo, B lists other, A calls echo on its second turn), is a new case in test_mcp_rejects_history_with_changed_tools, which expects its replay to fail.
  • The PR description no longer says that every run without a clash keeps its commands.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Third round, at head 487e5aa (six commits over 3488fbe). Recipe: the finder angles plus a replay-semantics finder, 32 candidates and checks in total (including a 14-mutant run of _refresh_mcp_tools and _check_mcp_tools in a separate synced worktree and seven wrapper-semantics probes), each settled by a fresh reproduction against an independent worktree: hook-level probes against both the head and main's agent class, end-to-end dev-server runs with WorkflowTaskFailed and attempt-counter evidence, and a real recording replayed across versions. Confirmed 10, merged into 8 findings; 1 plausible; 7 probes and 11 mutants clean. make lint and make test (190 tests) pass on the head; the conventions check is OK. Not verified: the shared-client history a commenter recorded (not attached; reproduced at hook level, and the sibling one-turn-move case with a real recording), a mixed old-and-new Worker rollout, and cross-run client state on an unsandboxed Worker, which the PR lists as not covered.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Round one is addressed or superseded throughout: one hook per agent with the identity bookkeeping gone, listings keyed by provider, cached providers not re-listed, the dedicated MCPToolNameConflictError registered as a failure type, the shared cached client getting its tools, the twice-listed name, name-based ownership for in-place replacement, dynamic_tools included, a single up-front check, the README and docstrings, and the tests driving agent.hooks. Round two: the drop loop pops dynamic_tools, the two-handles message is actionable, the check runs inside the loop, exact comparison for dynamic names, the loader shared, the nondeterminism assertion narrowed, the vended-tool threads superseded by the refuse decision. Decisions I take as recorded: no gate, the name-is-the-server's ownership rule, the hook order, the AfterModelCallEvent note. Still partial, and the source of this round's items: _mcp_names is still seeded from provider._tools at construction, the failure-type guarantee holds only for a cycle-one refusal, and the upgrade note lists only the duplicate cases.

Where this round's problems cluster: two things decide whether the new guarantee holds. First, where the refusal is raised: after a tool use, Strands wraps it in EventLoopException, which is not a registered failure type, so the run strands exactly on the mid-run duplicate the README documents. Second, when the agent was built: an agent constructed after its clients already listed takes the construction-time path, where the same duplicate is a bare ValueError, a user tool is silently replaced, and a sandbox-named tool is accepted. Both are fixable in the plugin without changing commands for runs that never clash.

Findings on lines outside the diff

  • python/strands_agents/src/temporalio/strands_agents/_temporal_agent.py:167: P2: the same duplicate reached at construction, for an agent built after its clients listed, surfaces as Strands' bare ValueError, not MCPToolNameConflictError, so it is not a failure type, cannot be caught with the documented except, and strands the run; its message names a TemporalMCPClient object address instead of the server. Module-level clients a and b (the pattern the TemporalMCPClient docstring recommends): agent one tools=[a, b] is refused at its hook (both list echo), the Workflow catches it as README line 643 suggests, then builds agent two from the same clients (or any second agent with tools=[local_echo, a] or [a, a] after a listed). super().__init__ here runs Strands' process_tools, load_tools() (_temporal_mcp_client.py:114-123) returns the stored listing, and register_tool raises ValueError: Failed to load tool <temporalio.strands_agents._temporal_mcp_client.TemporalMCPClient object at 0x...>: Tool name 'echo' already exists. End to end: the run stays RUNNING with one WorkflowTaskFailed of type ValueError, non_retryable: false, and the pending task attempt climbing 2, 3, 4 over 35 s. README line 641 hedges 'Strands may raise there instead', but line 643 promises 'StrandsPlugin fails the Workflow when the error escapes Workflow code', which is false on this path, and the PR's own test_mcp_same_client_twice_on_one_agent (line 552) pins the bare ValueError. Check each provider's current _tools names against tools=[...] and each other before super().__init__ and raise MCPToolNameConflictError (replay-neutral: no Activity is scheduled at construction), or translate the construction-time ValueError; and give the client a __repr__ naming the server.
  • python/strands_agents/src/temporalio/strands_agents/_failure_converter.py:29: P3: MCPToolNameConflictError fails the Workflow as a retryable ApplicationError (non_retryable=False), unlike the plugin's other deterministic Strands failures in _TERMINAL_EXCEPTIONS. A parent running execute_child_workflow(..., retry_policy=RetryPolicy(maximum_attempts=0)), or a Workflow started with a retry policy, for an agent whose two servers both list search lists both, refuses, fails with type MCPToolNameConflictError, and is retried with backoff for a configuration error that cannot succeed (observed end to end: cause.non_retryable = False). Adding the type here, converted with non_retryable=True, matches how MaxTokensReachedException, ContextWindowOverflowException, StructuredOutputException and SessionException are treated.
  • python/strands_agents/src/temporalio/strands_agents/_temporal_mcp_client.py:123: P3 (design alternative, plausible): load_tools() returning the process-local _tools at construction, plus seeding _mcp_names from it, is the single root of the construction-order dependence behind the construction-time ValueError, the clobber and the sandbox-order items; returning [] and starting _mcp_names empty is replay-neutral and makes every clash a hook-level MCPToolNameConflictError. Simulated without editing the package: list-tools counts are identical to the head for an agent built after an uncached listing (one on its first turn), after a cached listing (zero; tools applied from the stored listing via 215-219), a shared cached client (one listing), and [a, a] after a listing (two per turn, as a fresh [a, a] agent); [local_echo, a], [a, local_echo] and a sandbox agent built after a listing are all refused uniformly by the hook. Running the PR's hook-level tests under the variant: 16 pass, 1 fails, the failure being test_mcp_same_client_twice_on_one_agent's assertion that construction raises after a listing, which the variant removes on purpose. Costs: agent.tool_names and the registry are empty before the first hook for an agent built after a listing (nothing in the plugin reads them earlier; user BeforeModelCallEvent hooks already observe the previous turn's registry), and the README sentence about construction-time raising would go. A smaller alternative is restoring d3f653a's identity guard for _mcp_names plus the construction-time translation above.

Minor doc nit: README line 641 says a tool put under a server's name 'is replaced at the next listing'; with cache_tools=True there is no next listing, so it is replaced at the next turn. Process note: the automated run fetched pull/184/head into the local checkout's pr-184-review branch ref; the working tree and index were not touched, and all verification used an independent clone.

# manager cannot reduce the context any further, and a duplicate tool name
# replays the same listing; fail the workflow instead of retrying the task
# forever.
workflow_failure_exception_types=[

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: a refusal raised on any event-loop cycle after a tool use is wrapped by Strands into EventLoopException, which is not a registered Workflow failure type, so the run strands in Workflow Task retries and the documented except MCPToolNameConflictError or except ValueError never runs. Default cache_tools=False, TemporalAgent(tools=[TemporalMCPClient('a'), TemporalMCPClient('b')]): cycle one lists a {safe} and b {echo}, the model calls safe; before cycle two's model call a now also lists echo (a server redeployed mid-run, the case README line 641 covers: 'with cache_tools=False, a later one if a server starts listing such a name'). _refresh_mcp_tools raises at _temporal_agent.py:220, but cycle two runs inside recurse_event_loop, inside the outer cycle's second try in strands/event_loop/event_loop.py:394-410, whose pass-through list is only StructuredOutputException, EventLoopException, ContextWindowOverflowException, MaxTokensReachedException and InterruptException; everything else becomes EventLoopException(e) from e. Only a cycle-one refusal (the model-call try at 296-310) propagates unwrapped, which is the one case the PR's end-to-end test (tests/test_mcp.py:377) exercises. Reproduced on the dev server: activities [strands_get_model_config, a-list-tools, b-list-tools, invoke_model, a-call-tool, a-list-tools, b-list-tools], then RUNNING after 12 s with one failed task of type EventLoopException (cause MCPToolNameConflictError), retried with backoff until a reset or terminate. The caught variant: except ValueError does not fire; except Exception sees the chain [EventLoopException, MCPToolNameConflictError] with agent.messages holding prompt, tool use and tool result, so README line 643's 'remove the prompt that Strands added' is incomplete there too. The same wrapping turns an invoke_model ActivityError after a tool use into a task-failure loop on main as well, so one fix covers both: in TemporalAgent, unwrap an EventLoopException whose __cause__ is a FailureError or a registered failure type and re-raise the cause; registering EventLoopException itself would be too broad. README 641-643 and the MCPToolNameConflictError docstring (_temporal_mcp_client.py:36-42) should say which exception actually escapes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f2a5bf1: TemporalAgent._run_loop re-raises an MCPToolNameConflictError that Strands wrapped in EventLoopException, so Workflow code can catch it, and the plugin fails the Workflow with it. test_mcp_conflict_after_a_tool_call runs your shape end to end (a tool call, then a listing that clashes), both caught and uncaught; without the change it times out. The README now says to remove every message the call added (the prompt, and any tool calls and results).

I kept the broader unwrap for Temporal failures out of this PR. A failed or cancelled model Activity after a tool call is an existing problem on main that needs its own fix (it also has to cover cancels and Signal and Update handlers), so I'll track it separately.

# construction, then each turn's. A name stays the servers' while they
# list it: a tool put under it meanwhile is replaced at the next listing,
# and removed with the name.
self._mcp_names = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _mcp_names is seeded by name from provider._tools even when the registry entry under that name is the user's own tools=[...] tool, so the first hook silently replaces an explicitly passed tool instead of refusing the duplicate README line 641 promises. a already listed echo (earlier agent in the run, module-level client); TemporalAgent(tools=[a, local_echo]) with @tool(name='echo') local_echo: process_tools registers a's echo, then the hot-reloadable @tool overwrites it without error, so registry['echo'] is local_echo while _mcp_names == {'echo'}; the hook's held excludes echo (line 210), _check_mcp_tools passes, and reg.replace() at 232 installs the TemporalMCPTool over the user's tool (probe: hook: NO error; registry['echo'] type = TemporalMCPTool). The same agent with a not-yet-listed client is refused, so the outcome depends on whether another agent listed the client first. Main clobbered in both cases, so the behaviour is pre-existing; what is new is the README rule it contradicts and the inconsistency with the fresh-client path. The identity guard d3f653a had (if registry.get(tool.tool_name) is tool, removed in 487e5aa on the premise that every load_tools() tool stays in the registry) would exclude echo from _mcp_names and make the hook refuse; or seed nothing at construction (last comment).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f2a5bf1 with your last option: TemporalMCPClient.load_tools() now returns no tools and _mcp_names starts empty, so every agent gets its MCP tools from the hook, whether it was built before or after the listing. [a, local_echo] built after a listed is now refused like a fresh agent, and the user's tool stays. test_mcp_tool_named_like_another_tool_is_refused builds agents both before and after the listing.

Comment thread python/strands_agents/README.md Outdated

`StrandsPlugin` fails the Workflow when the error escapes Workflow code, because replay would raise it again. If Workflow code catches it and calls the agent again, first remove the prompt that Strands added to `agent.messages`, as for any error during an agent call. A run that met the error keeps the listing in its history, so a new `prefix` or filter does not fix it: reset the Workflow to a point before that listing.

Earlier versions let the later tool replace the earlier one in most of these cases. A run that started before you deploy this version can fail to replay on it if one of its agents met such a duplicate, including two handles of one server and names that differ only by `-` or `_`. Let those runs finish first, or use Worker Versioning.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: two non-clashing paths change the command sequence relative to main and are missing from this upgrade note and from the PR's 'runs whose tool names never clashed schedule the same commands' claim. (a) Shared uncached client c in agents A and B: A lists {echo}; B then lists {other} (server changed); A runs again. Main computed old_names from the client-wide c._tools (B's listing), so A kept its stale echo stub; the head's per-agent self._mcp_names - new (lines 224-226) pops it (probe: head A tools = ['other'], main ['echo', 'other'], identical list-tools logs). If the model calls echo on A's later turn, main schedules c-call-tool and the head does not, so a main-recorded history fails replay with TMPRL1100; the still-unanswered comment 4417600465 on this PR reports exactly that recording. (b) tools=[b, a], uncached; turn one a={safe, echo}, b={other}; turn two a={safe, other}, b={echo}; the model calls echo. On main, hook(a)'s old_names - new popped the echo hook(b) had just installed, so the model got 'Unknown tool: echo' and no Activity; the head keeps b's echo (221-235, the intended 'a name can move' behaviour) and schedules b-call-tool. Reproduced end to end: a history recorded with main's agent class replays on main and fails on the head with [TMPRL1100] ... Activity type of scheduled event 'gap_mv_b-list-tools' does not match activity type of activity command 'gap_mv_b-call-tool'. The head's behaviour is the better one in both cases; the actionable part is this note (today it lists only duplicates, two handles and '-'/'_' names), the PR body, and main-recorded regression histories for both paths next to legacy_mcp_duplicate_names.json.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on both. In f2a5bf1:

  • The README upgrade note covers them: a tool that moves between servers in one turn now stays, and an agent that shares an uncached client now drops the tools the server stopped listing. The PR description says the same.
  • Both have main-recorded histories next to legacy_mcp_duplicate_names.json: legacy_mcp_shared_client_drop.json, and legacy_mcp_tool_moves.json (your tools=[b, a] swap; on main the model's echo call found no tool). test_mcp_rejects_history_with_changed_tools expects both to fail replay.

new = {tool.tool_name for tools in listings.values() for tool in tools}
# Tools the servers dropped or renamed since the last turn. There is no
# public unregister, so remove them from the registry directly.
for name in self._mcp_names - new:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: whether an MCP tool named like a TemporalSandbox tool is refused depends on construction order; an agent built after its client listed silently takes sandbox_shell, and this drop loop then removes it without restoring the vended shell when the server stops listing it. a lists sandbox_shell (for example MCPClient(prefix='sandbox') over a server exposing shell). Built before the listing, TemporalAgent(tools=[a], sandbox=TemporalSandbox('sb')) is refused at the first hook, as README line 641 and tests/test_mcp.py:729 say. Built after it, process_tools registers a's sandbox_shell, Strands' Agent.__init__ skips the vended tool with a debug log, line 190 claims the name for the servers, the hook accepts it, and when a later lists nothing, this line pops the name and the registry is left with sandbox_file_editor only for the rest of the run (probe output: (b) hook: NO error, then registry={'sandbox_file_editor': ...}). Main behaved like the second path on both, so the PR adds the inconsistency and the README claim; the 'moot' reply on the vended-tool-restore thread holds only for the first path. Either refuse at construction too (replay-neutral), or record what the sandbox loop registered and restore it on drop, or narrow the README sentence.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed by the same change as the thread on line 190. With load_tools() returning nothing, an agent built after its client listed gets the sandbox tools at construction, and the hook refuses sandbox_shell, as for a fresh agent. So a listed tool never takes a sandbox name, and the drop can't remove one. test_mcp_tool_named_like_another_tool_is_refused covers both build orders.

for name in reg.registry
if name not in self._mcp_names
}
dynamic = set(reg.dynamic_tools) - self._mcp_names

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: a structured_output_model whose tool name equals an MCP tool the agent already accepted raises Strands' bare ValueError from register_dynamic_tool before any hook runs; the dynamic check here covers only the opposite order, and the error is neither MCPToolNameConflictError nor a failure type. Server a lists Weather, the agent accepts it on turn one; invoke_async(prompt, structured_output_model=Weather) runs StructuredOutputContext.register_tool in _execute_event_loop_cycle (strands/agent/agent.py around 1693, before the BeforeModelCallEvent hook) and gets ValueError: Tool 'Weather' already exists. A plain Strands registry with a user tool named Weather raises the same, so this is Strands parity and pre-existing; uncaught, it fails the Workflow Task repeatedly like the construction case. README line 641 and the body ('dynamic tools such as structured output's by exact name') read as if both directions are covered. Either compare _mcp_names with the structured-output tool name before the cycle (_convert_prompt_to_messages does not receive structured_output_model; the check belongs in invoke_async, stream_async or _execute_event_loop_cycle) or document the gap.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented in f2a5bf1 rather than checked: Strands does the same with any tool of that name. The README now says that a structured_output_model named like an MCP tool the agent already has gets Strands' own ValueError when the call starts, as in Strands.

await _before_model_call(agent)


async def test_mcp_tool_named_like_a_dynamic_tool_is_refused(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests): three behaviour-changing mutants of _refresh_mcp_tools and _check_mcp_tools survive this file, including one that turns the user-tool '-'/'_' twin path into a bare Strands ValueError and a task-failure loop. From a 14-mutant run in a separate synced worktree (baseline 24 passed): (M5) comparing name in held instead of the normalized key in held at _temporal_agent.py:80 passes all 24, yet with a user @tool(name='foo-bar') and a server listing foo_bar the head refuses via MCPToolNameConflictError while the mutant lets register_tool raise Strands' 'already exists as' ValueError; no test has a user tool whose name differs from a listed name only by '-' or '_'. (M2) dropping - self._mcp_names from dynamic at 212 passes; it would refuse a re-listing of a name whose MCP tool a dynamic replacement currently holds instead of replacing it, and test_mcp_listing_replaces_a_tool_replaced_in_place (706) covers a dynamic replacement only when the server drops the name. (M13) removing the 'Set a prefix ... tool_filters' hint passes; the tests match only the message prefix. The other 11 mutants are killed. Add a user foo-bar plus listed foo_bar refusal test, a re-listing over a dynamic in-place replacement, and pin the full hint once.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the mutant run. Added in f2a5bf1:

  • A user foo_bar with a listed foo-bar, as a case of test_mcp_tool_named_like_another_tool_is_refused. I used this direction because it also catches a mutant that compares the raw name with held's values; the same test pins the full hint once.
  • A re-listing over a dynamic in-place replacement, in test_mcp_listing_replaces_a_tool_replaced_in_place.

…apped

- TemporalMCPClient.load_tools() returns no tools, so an agent built after its
  clients listed gets them from the hook too: a clash with its other tools,
  a sandbox tool or another server is MCPToolNameConflictError at the first
  model call, as for an agent built before the listing.
- TemporalAgent re-raises a conflict that Strands wraps in EventLoopException
  after a tool call, so Workflow code can catch it and the plugin fails the
  Workflow with it.
- The failure converter makes MCPToolNameConflictError non-retryable.
- README: the messages to remove after a caught error, structured output named
  like an MCP tool, and the runs whose servers changed their tools that can
  fail to replay.
- Tests: a refusal after a tool call, agents built after a listing, a user
  '-'/'_' twin, a re-listing over a dynamic replacement, and two histories
  recorded on main for a shared client that drops a tool and a tool that
  moves between servers.
@campoy

campoy commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks both. Round 3 is in f2a5bf1, with replies inline. The items in the review summary:

  • Construction-time ValueError (P2): gone. load_tools() now returns no tools, so an agent built from clients that already listed gets them from the hook, which raises MCPToolNameConflictError as for any agent. test_mcp_duplicate_refused_again_after_caught now builds a second agent from the same clients and expects that. With no construction-time message left, the client __repr__ isn't needed.
  • Retryable failure (P3): MCPToolNameConflictError is now in _TERMINAL_EXCEPTIONS, so the Workflow fails with a non-retryable ApplicationError. test_mcp_conflict_after_a_tool_call checks cause.non_retryable, with the plugin on the client, since the failure converter comes from the client's data converter.
  • Design alternative: taken, as above.
  • Doc nit: the README now says a tool put under a server's name is replaced at the next turn.

The replay checks were rerun on this head; the results are in the description.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fourth round, at head f2a5bf1 (one commit over 487e5aa). make lint passes and make test runs 195 tests green on the head; CI is green. Each item below was settled by a reproduction in a separate worktree: end-to-end dev-server runs comparing the head's TemporalAgent with a subclass that restores main's _run_loop, the two new histories replayed on main's agent (the plugin's source on main is unchanged since 63d7aec), a rerun of the two round-three mutants that had survived, and Strands' source from 1.51.0 to 1.56.0 and at 1.62.0. Checked and clean: both new histories replay on main and fail on the head with the Activity swaps the PR describes; M5 (name in held) and M2 (dynamic without - self._mcp_names) now fail one test each; each of those Strands releases sends stream_async through _run_loop and wraps the later-cycle error as EventLoopException(e) from e, so the unwrap applies across the declared range; an agent built after a listing schedules the same list-tools Activities as on main (the hook still skips _refresh for a fetched cached client and applies its stored listing); the exception cycle that raise err.__cause__ from None leaves through __context__ is harmless, since from None clears __cause__ and both failure converters build a fresh ApplicationError for this error that carries only __cause__. Not verified: the 20-run replay matrix and the old-to-new Worker runs in the PR body (not re-run), and a mixed rollout, which the PR lists as not covered.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Round three is resolved. The P1 is addressed: _run_loop re-raises a conflict that Strands wrapped after a tool call, and test_mcp_conflict_after_a_tool_call runs that shape caught and uncaught. The construction-time ValueError, the silent replacement of a user tool and the sandbox-name order dependence are gone with load_tools() returning [] and _mcp_names starting empty (the design alternative, taken), with tests for both build orders. The upgrade note and the PR body now cover the shared-client drop and the one-turn move, each with a main-recorded history, which also answers the other reviewer's shared-client comment. MCPToolNameConflictError is in _TERMINAL_EXCEPTIONS; the surviving mutants are killed and the full hint is pinned; the doc nit is fixed. Declines I accept: the structured_output_model name clash documented as Strands parity; the broader EventLoopException unwrap for failed or cancelled model Activities, pre-existing on main and tracked separately; the client __repr__, moot without the construction path. Earlier decisions (no gate, the name-is-the-server's ownership rule, the hook order) stand.

Decision: comment rather than approve, because every earlier item is resolved and the one new defect is an edge-case regression in the new _run_loop wrapper with a three-line fix; with that in, nothing here blocks.

#190: it moves prefix and tool_filters from the worker-side MCPClient factory to TemporalMCPClient (there, a factory that still passes prefix= fails every MCP Activity) and edits the same load_tools() lines. Whichever PR lands second should keep load_tools() returning [] and point the conflict hint (_temporal_agent.py:45-47 and 59-61) and README line 641 at TemporalMCPClient(prefix=..., tool_filters=...).

# tool name conflict as itself, so Workflow code can catch it and
# StrandsPlugin fails the Workflow with it.
try:
async for event in super()._run_loop(*args, **kwargs):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: this wrapper never closes Strands' own _run_loop generator, so when stream_async is closed early, an AfterInvocationEvent hook that awaits anything stops at that await and the hooks after it never run, for every TemporalAgent, with or without MCP clients. Since Strands 1.55 (the lock has 1.56), stream_async ends with finally: await events.aclose(), so that _run_loop's finally (conversation management, then the AfterInvocationEvent hooks) runs on the event loop when the caller stops iterating or a callback_handler raises. That aclose() now reaches this wrapper, and the async for here does not forward it: the inner generator is released with the wrapper's frame and closed synchronously when it is collected, because the Workflow loop installs no async-generator finalizer, so its first suspending await ends the close with RuntimeError: async generator ignored GeneratorExit, reported as unraisable for Agent._run_loop.

Reproduced on the dev server with an async AfterInvocationEvent hook that logs, awaits an Activity (the README's activity_as_hook pattern) and logs again. A Workflow that breaks out of agent.stream_async('hi') and closes it: main's _run_loop (a subclass with _run_loop = Agent._run_loop) logs ['after-start', 'after-end'], the head ['after-start']. A callback_handler that raises on the first text chunk: the same split, with invoke_async re-raising the handler's error in both. The hook's Activity is still scheduled and runs; the code after the await is lost. Strands 1.51 to 1.54 have no explicit close, so main already lost such a hook there; the regression is from 1.55.

Fix, verified (the probe then logs after-end in both cases; make lint is clean and the 195 tests pass):

events = super()._run_loop(*args, **kwargs)
try:
    async for event in events:
        yield event
except EventLoopException as err:
    if isinstance(err.__cause__, MCPToolNameConflictError):
        raise err.__cause__ from None
    raise
finally:
    await events.aclose()

contextlib.aclosing does the same.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in 2819ae6 with your version: the wrapper keeps Strands' generator and closes it in finally, so Strands' cleanup, including AfterInvocationEvent hooks that await, still runs when the stream is closed early. test_after_invocation_hook_finishes_when_stream_closed_early in tests/test_hooks.py breaks out of stream_async and closes it, with a hook that awaits. On f2a5bf1 that hook logs only start, and Strands reports async generator ignored GeneratorExit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: 9c219ce keeps the same finally and replaces my test with test_closed_stream_awaits_after_invocation_hooks. Its hook runs an Activity, and a control reads the stream to the end.

ContextWindowOverflowException,
StructuredOutputException,
SessionException,
MCPToolNameConflictError,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the failure is non-retryable only when StrandsPlugin is on the client; with the plugin on the Worker only, as in the README quick start (line 44) and the MCP example (line 627), an uncaught conflict still fails the Workflow, but as a retryable ApplicationError. SimplePlugin.configure_worker does not apply data_converter, so such a Worker keeps the client's default failure converter. Probe: MCPConflictAfterToolWorkflow with catch=False on a Worker with plugins=[StrandsPlugin(...)] and a plain client fails with cause.type == 'MCPToolNameConflictError' and cause.non_retryable == False; the PR's test passes because it adds the plugin to the client, as its comment at tests/test_mcp.py:559 says. The PR body says 'with a non-retryable ApplicationError' without that condition. Add to README line 643 what line 552 says for interrupts (attach the plugin to the client for the failure to be non-retryable), and qualify the PR body.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 2819ae6: the README now says to attach StrandsPlugin to the client for that failure to be non-retryable, as it already says for interrupts. The PR description now says the same.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: 9c219ce goes further. MCPToolNameConflictError is now an ApplicationError with non_retryable=True (and still a ValueError), so the failure is non-retryable with the plugin on the Worker only too. The README sentence about the client is gone, and so are the failure-converter and failure-type entries. test_mcp_conflict_after_a_tool_call now runs with the plugin on the Worker and on the client, with maximum_attempts=2, and checks that only one run fails.

Comment thread python/strands_agents/tests/test_mcp.py Outdated
)
async def test_mcp_rejects_history_with_changed_tools(workflow_class: type, name: str):
"""Runs whose servers changed their tools now keep the right ones, so they differ."""
with pytest.raises(NondeterminismError):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests): this test accepts any NondeterminismError, so it would keep passing for an unrelated reason, for example once #190 renames the MCP Activities to temporalio.mcp.{server}.list-tools and call-tool and every earlier MCP history fails at its first listing. On the head the two histories fail exactly where the PR says ([TMPRL1100] ... scheduled event 'shifting-call-tool' does not match activity type of activity command 'shifting-list-tools', and 'mv_b-list-tools' against 'mv_b-call-tool'), and both replay cleanly on main's agent. Pin that with match= on the Activity pair (one more parametrized value); the duplicate-names test at line 446 can do the same.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 2819ae6: the two changed-tools cases now match their Activity pair ('shifting-call-tool' against 'shifting-list-tools', and 'mv_b-list-tools' against 'mv_b-call-tool'). The duplicate-names history fails where the run completes instead of scheduling the model call, so its message has no Activity pair. That test now matches ActivityTaskScheduled, which a failure at the first listing, such as one from #190's renamed Activities, would not match.

- TemporalAgent._run_loop closes Strands' generator in `finally`, so Strands'
  cleanup, including AfterInvocationEvent hooks that await, still runs when
  stream_async is closed early. Before, the wrapper left it to be closed
  synchronously, and such a hook stopped at its first await.
- README: attach StrandsPlugin to the client for a tool name conflict to fail
  the Workflow as non-retryable.
- Tests: an AfterInvocationEvent hook that awaits on a stream closed early, and
  the replay tests for old histories match where the replay fails.
@campoy

campoy commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Round 4 is in 2819ae6, with replies inline. On #190: noted. Whichever of the two lands second keeps load_tools() returning [], and if #190 moves prefix and tool_filters to TemporalMCPClient, points the conflict hint and the README at TemporalMCPClient(prefix=..., tool_filters=...).

… without retry on any Worker

The agent's other tool names were read before the first listing was awaited, so a tool that a Signal
handler registered while a listing ran was not checked, and the MCP tool replaced it. Read the
registry each time the listings are checked; the last check follows the last listing, with no await
before the registry changes.

MCPToolNameConflictError is now a non-retryable ApplicationError, and still a ValueError. The plugin's
failure converter applies only when StrandsPlugin is on the client, so with the plugin on the Worker
only the error was retryable. The failure converter and failure type entries are no longer needed,
and the README no longer asks for the plugin on the client.

The README's upgrade note now names Workflow code that reads a later agent's tool_names before its
first model call: since load_tools() returns no tools, such an agent has none until then. It also
names Workflow code that reads an agent's tools before a turn's listings are applied: they are
applied together once every due server has listed, so a Signal or Update handler that runs while a
later server lists sees none of that turn's tools, even when every listing succeeds, and the agent
keeps none of them when a later listing fails.

Tests: the conflict after a tool call runs with the plugin on the Worker only and on the client; a
tool added or removed while a listing runs; the early-close hook test now awaits an Activity and
reads the stream to the end as a control.
@campoy

campoy commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 9c219ce on top of 2819ae6, with three more fixes from our own review of f2a5bf1:

  • Tool added while a listing runs: the agent's other tool names were taken before the first listing was awaited. A Signal handler that registered a local echo during {server}-list-tools was not checked, so the listed echo replaced it and the call ran on the server. The check now reads the registry after each listing, and nothing is awaited between the last check and the registry changes. test_mcp_tool_added_while_listing_is_refused covers a tool added during a listing (refused, kept) and one removed (the name goes to the server).
  • Retryable with the plugin on the Worker only: StrandsFailureConverter applies only when StrandsPlugin is on the client, so Worker(client, plugins=[StrandsPlugin(...)]) failed the Workflow with a retryable error, and a retry policy started a second run. MCPToolNameConflictError is now a non-retryable ApplicationError (and still a ValueError), so the failure-converter and failure-type entries are gone, and so is the README sentence 2819ae6 added about the client. test_mcp_conflict_after_a_tool_call runs with the plugin on the Worker and on the client, with maximum_attempts=2, and checks that one run fails.
  • Two upgrade notes: since load_tools() returns no tools, an agent built after another agent listed a shared client has an empty tool_names until its first model call; on main it had the last listing. And since d3f653a, a turn's listings are applied together once every due server has listed, where main added each server's tools as soon as it listed, so a Signal handler that runs while a later server lists, or code that catches a failed later listing, sees none of that turn's tools. Workflow code that reads tool_names at those points can schedule other commands, and main histories that did so fail to replay, though no names clashed. The README and the PR body now name these cases. The designs stay.

The _run_loop change from 2819ae6 is unchanged; 9c219ce replaces its test with one whose hook runs an Activity, plus a control that reads the stream to the end.

# Conflicts:
#	python/strands_agents/tests/common.py

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fifth round, at head 1405eff (2819ae6 and 9c219ce over f2a5bf1, then a merge of main whose one conflict, tests/common.py, keeps both sides). Of the 6,059 added lines, 5,136 are the four recorded histories, 755 tests and 168 source and README. make lint passes and make test runs 211 tests green on the head; CI is green. Recipe: the round-four reproductions rerun on the head, then three finder angles (exception and wrapper semantics, replay against main, tests and docs), each candidate settled by a probe in a separate worktree: dev-server runs, histories recorded on unmodified main (05a81ce) and replayed on the head and back, and a 44-mutant run of _check_mcp_tools, _refresh_mcp_tools, _run_loop and MCPToolNameConflictError against the full suite. Checked and clean: the error class (str, args, message, pickle and deepcopy; the default, encoded-attribute and both Strands failure converters all give type MCPToolNameConflictError, non-retryable, no cause; escaping @workflow.run or a Signal handler it fails the run, sandboxed and unsandboxed, and a parent sees it as the cause of ChildWorkflowError); the _run_loop close with a callback_handler that raises, a cancellation while a hook awaits an Activity during the close (with and without a workflow cache), a hook that raises during the close, and AfterInvocationEvent.resume, all matching main's _run_loop; the registry read after each listing, including two agents sharing an uncached client under asyncio.gather; the apply loop, which cannot reach a bare Strands ValueError for anything the check lets through (register_tool and replace are unchanged from Strands 1.51 to 1.63); the four histories, which replay on main and fail on the head where stated, while a #190-style rename of the MCP Activities matches none of the match= patterns; runs that main left retrying a Workflow Task on Strands' own -/_ error, which fail with MCPToolNameConflictError once a head Worker picks them up, as the body says; and the body's counts (27 new cases; 3 tests failing on f2a5bf1, 7 on 487e5aa). Dropped: the duplicate-names replay test's looser match= (settled last round, and test_mcp_duplicate_tool_names_are_refused pins the refusal point), counts in the body written before the merge, and the early-close guarantee on Strands 1.51 to 1.54 (there stream_async never closes _run_loop, so the head behaves as main, as round four noted). Not verified: the body's 20-run and 10-run replay matrices (not re-run) and a mixed rollout (listed as not covered).

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Round four is resolved, each item checked by rerunning its reproduction. The _run_loop wrapper closes Strands' generator in finally: the round-four probe (breaking out of stream_async, and a callback_handler that raises on the first chunk, each with an AfterInvocationEvent hook that awaits an Activity) now logs after-start, after-end on the head as on main's _run_loop, and test_closed_stream_awaits_after_invocation_hooks fails without the finally. The retryable failure with the plugin on the Worker only is fixed beyond the ask: MCPToolNameConflictError is an ApplicationError with non_retryable=True (and still a ValueError), the round-four probe now reports non_retryable=True with a plain client, and the test runs both placements with maximum_attempts=2 and checks that one run fails. The changed-tools replay tests match their Activity pairs; for the duplicate-names one I take your explanation, and ActivityTaskScheduled does not match a renamed-Activity failure. The registry read after each listing (from your own review) works as described, and its test fails on f2a5bf1. Earlier decisions stand (no gate, the name-is-the-server's rule, the hook order, load_tools() returning []), and brianstrauch's three items were closed in earlier rounds. #190 is still open; last round's note on load_tools() and the hint text applies to whichever lands second.

Where this round's items cluster: the code is right; what is left is what the docs promise. One more shape changes commands without a name clash and is missing from the upgrade note and from the body's list of runs that keep their commands; the failure contract says 'fails the Workflow', which an Update handler does not do; and three branches of the per-listing logic have no test.

Decision: comment rather than approve, because every earlier item is fixed and nothing here is a code defect, but the upgrade note, which stands in for a version gate, misses one verified replay-changing shape; with that sentence added I would approve.

PR body: besides the shape in the README comment, 'Runs with names that differ only by - or _ replay when the earlier version raised Strands' error at the same listing' also fails when that listing came after a tool call and Workflow code caught Strands' EventLoopException: main wrapped the error and the code went on, the head raises MCPToolNameConflictError itself, and the main history fails with [TMPRL1100] Nondeterminism error: Fail workflow machine does not handle this event: HistoryEvent(id: 29, ActivityTaskScheduled). The README's 'can fail' covers it; one clause in the body would too.

Parity: the TypeScript plugin on main refuses a duplicate only at an agent's first listing (Strands' ToolRegistry.add throws ToolValidationError) and lets a later re-listing replace another server's or a local tool silently (refreshTools calls registry.addOrReplace), so after this PR the two languages differ for duplicates that appear mid-run. Not for this PR; worth an issue.

Comment thread python/strands_agents/README.md Outdated

The error fails the Workflow when it escapes Workflow code, with `StrandsPlugin` on the client or only on the Worker, because replay would raise it again. If Workflow code catches it and calls the agent again, first remove the messages that Strands added to `agent.messages` during that call (the prompt, and any tool calls and results), as for any error during an agent call. A run that met the error keeps the listing in its history, so a new `prefix` or filter does not fix it: reset the Workflow to a point before that listing.

Earlier versions let the later tool replace the earlier one in most of these cases. A run that started before you deploy this version can fail to replay on it if one of its agents met such a duplicate, including two handles of one server and names that differ only by `-` or `_`. It can also fail if a server's tools changed during the run: a tool that moves from one server to another in one turn now stays, where earlier versions could lose it, and an agent that shares an uncached client with another agent now drops the tools the server stopped listing, where earlier versions kept them. And an agent built after another agent listed a client they share has none of that client's tools until its first model call, where earlier versions gave it the last listing at construction: Workflow code that reads its `tool_names` or `tool_registry` before then can take another path, though no names clashed and the servers kept their tools. Last, an agent now applies a turn's listings together, once every server due that turn has listed, where earlier versions added each server's tools as soon as it listed. Until then the agent's tools stay as they were before that turn, and they stay so if a listing fails. Workflow code that reads the agent's tools before the turn's listings are applied can take another path, though no names clashed and the servers kept their tools: for example a Signal or Update handler that runs while a later server lists, even if every listing then succeeds, or code that catches a failed listing. Let those runs finish first, or use Worker Versioning.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: one more shape changes commands without a name clash and is missing from this note and from the PR body: an agent that shares a cache_tools=True client with another agent and was built before that agent's first listing. On main such an agent never gets the client's tools: its load_tools() ran before the listing and returned [], and its hook returns early once the shared client is _fetched (main _temporal_agent.py:134). On the head it gets them from the stored listing at its first model call (_temporal_agent.py:212-218). That is the fix round one asked for (that item described the gap as the branch's; main has it too), and I called the fix replay-neutral because it schedules no listing. It is not neutral for Workflow code that reads that agent's tools, and it breaks rollback whenever the agent calls them. Probe, a planner and an executor built together in run from one cached client, the planner called first: main ends with executor tools=[], the head with ['echo']. A main history whose Workflow code then branches on 'echo' in executor.tool_names fails on the head with [TMPRL1100] Nondeterminism error: Activity machine does not handle this event: HistoryEvent(id: 35, WorkflowExecutionCompleted), although the read comes after the executor's model call with no listing pending, which the body's 'Other runs ... schedule the same commands' counts as safe. A head history in which the executor calls echo fails on main with [TMPRL1100] ... Activity type of scheduled event 'rv5sc-call-tool' does not match activity type of activity command 'invoke_model'.

Related, for the sentence about agents built after another agent listed a shared client: such an agent now answers a tool call that its initial messages end with as an unknown tool, because Strands runs that call before the first model call (strands/event_loop/event_loop.py:295 in 1.56), where main ran it from the construction-time listing (main _temporal_mcp_client.py:112). Recorded both ways with no reads in Workflow code: main schedules pu-call-tool before pu-list-tools, the head only pu-list-tools, and each history fails on the other ([TMPRL1100] ... scheduled event 'pu-call-tool' does not match ... activity command 'pu-list-tools', and the reverse).

Suggested sentences, here and in the body's upgrade and rollback lists: 'An agent that shares a cache_tools=True client with another agent and was built before that agent's first listing now gets the client's tools at its first model call; earlier versions never gave it those tools. Workflow code that reads its tools can take another path, and runs in which it calls them fail to replay on earlier versions.' And after 'until its first model call': 'so a call to one of them that its initial messages end with, which Strands runs before that model call, finds no such tool'.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, added in 3fddb6d with your sentences, in the README upgrade note and in the PR body's upgrade and rollback lists:

  • An agent that shares a cache_tools=True client with another agent and was built before that agent's first listing now gets the client's tools at its first model call, where earlier versions never gave it those tools. Workflow code that reads its tools can take another path, and runs in which it calls them fail to replay on earlier versions.
  • For an agent built after a shared client listed: a call to one of that client's tools that its initial messages end with, which Strands runs before the first model call, now finds no such tool.

The body no longer counts those runs among the ones that keep their commands.

Comment thread python/strands_agents/README.md Outdated

Tool names must be unique on one agent. Two tools may not have the same name, or names that differ only by `-` or `_`: for example two servers that both list `search`, a server that lists a name twice, or a server tool named like a tool in `tools=[...]`, a `TemporalSandbox` tool or a tool a Signal handler adds while the servers list. `TemporalAgent` learns its MCP tools only when it lists them, so the model call after that listing raises `MCPToolNameConflictError`, a `ValueError` and a non-retryable `ApplicationError`: the first one, or, with `cache_tools=False`, a later one if a server starts listing such a name. This holds for an agent built before or after its clients listed. Give one server a `prefix`, or drop the tool with `tool_filters`. While a server lists a name, the name is the server's: a tool you put under it is replaced at the next turn. A `structured_output_model` named like an MCP tool the agent already has gets Strands' own `ValueError` when the call starts, as in Strands.

The error fails the Workflow when it escapes Workflow code, with `StrandsPlugin` on the client or only on the Worker, because replay would raise it again. If Workflow code catches it and calls the agent again, first remove the messages that Strands added to `agent.messages` during that call (the prompt, and any tool calls and results), as for any error during an agent call. A run that met the error keeps the listing in its history, so a new `prefix` or filter does not fix it: reset the Workflow to a point before that listing.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: 'The error fails the Workflow when it escapes Workflow code' does not hold for an Update handler, the usual shape for a chat agent: the SDK fails only the Update, the run stays open, and the prompt Strands appended stays in agent.messages. Probe on the dev server: two stand-in servers both list search, and @workflow.update async def chat(...) calls agent.invoke_async; each execute_update raises WorkflowUpdateFailedError whose cause is an ApplicationError of type MCPToolNameConflictError with non_retryable=True, describe() stays RUNNING, and the message roles go from ['user'] to ['user', 'user']. That is how the SDK treats any failure exception from an Update handler (temporalio/worker/_workflow_instance.py:762), and it behaved the same on f2a5bf1, so only the sentence needs it: 'escaping an Update handler, it fails only that Update; remove the prompt from agent.messages before the next call'. Two related limits of the same paragraph: Strands' Swarm records the error as a failed node and an agent used as a tool turns it into an Agent error: ... tool result (multiagent/swarm.py:877-881, agent/_agent_as_tool.py:306-318 in 1.56), so neither fails the Workflow; and 'a new prefix or filter does not fix it' holds for a failed run and for a cached client, while an open run with an uncached client (one that caught the error, or whose Update failed) lists again on its next turn and picks up the Worker's new prefix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 3fddb6d. The README and the error's docstring now say the error fails the Workflow when it escapes the run method or a Signal handler, and that escaping an Update handler it fails only that Update and the run stays open. The README also says Strands' Swarm records it as a failed node and an agent used as a tool returns it as an error result, so neither fails the Workflow. The advice to remove the call's messages now covers a failed Update too. "A new prefix or filter does not fix it" now applies to a failed run or a cache_tools=True client, and the README says an open run with a cache_tools=False client picks up the new prefix at its next listing.

Comment thread python/strands_agents/README.md Outdated

Each factory returns a fully configured `MCPClient`, so you can pass options like `tool_filters`, `prefix`, `elicitation_callback`, or `tasks_config` to it.

Tool names must be unique on one agent. Two tools may not have the same name, or names that differ only by `-` or `_`: for example two servers that both list `search`, a server that lists a name twice, or a server tool named like a tool in `tools=[...]`, a `TemporalSandbox` tool or a tool a Signal handler adds while the servers list. `TemporalAgent` learns its MCP tools only when it lists them, so the model call after that listing raises `MCPToolNameConflictError`, a `ValueError` and a non-retryable `ApplicationError`: the first one, or, with `cache_tools=False`, a later one if a server starts listing such a name. This holds for an agent built before or after its clients listed. Give one server a `prefix`, or drop the tool with `tool_filters`. While a server lists a name, the name is the server's: a tool you put under it is replaced at the next turn. A `structured_output_model` named like an MCP tool the agent already has gets Strands' own `ValueError` when the call starts, as in Strands.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: two clauses here undersell the rule. 'the first one, or, with cache_tools=False, a later one': once raised, the refusal repeats at every later model call while the duplicate lasts, and a clash between cache_tools=True listings lasts for the rest of the run, since later turns re-check the stored listing (test_mcp_duplicate_refused_again_after_caught[True]); with line 645 describing how to catch the error and call again, say so. 'Give one server a prefix, or drop the tool with tool_filters' cannot separate two handles of one server, which share the Worker-side MCPClient factory; the error itself says 'Pass only one.' (_temporal_agent.py:53-57), and this sentence could add 'or pass only one handle of a server'.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both added in 3fddb6d. The README now says the error is raised again at every later model call while the duplicate lasts, which between cache_tools=True listings is the rest of the run. The fix list now ends with "or pass only one handle of a server".


``TemporalAgent`` raises it before a model call when a listed tool's name,
or the name with ``-`` and ``_`` swapped, is taken. It is a non-retryable
``ApplicationError``, so it fails the Workflow when it escapes Workflow

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this docstring makes the same unconditional 'fails the Workflow when it escapes Workflow code' claim; from an Update handler the error fails only the Update (README comment). Also, 'or the name with - and _ swapped' undersells the rule for mixed names: a listed a-b-c is refused against a local a_b-c (already exists as 'a_b-c'), since both normalize to a_b_c; 'or differs from a taken name only by - or _', as the README says, is exact.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3fddb6d. The docstring now says "is taken, or differs from a taken name only by - or _", and that the error fails the Workflow when it escapes the run method or a Signal handler, while escaping an Update handler it fails only that Update.

assert _sources(agent, a) == {"foo-bar": "a"}


async def test_mcp_tool_added_while_listing_is_refused(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests): three branches of the per-listing logic survive the full suite (211 passed under each mutant). (a) Freezing reg.dynamic_tools before the loop while still reading reg.registry live (_temporal_agent.py:81): a dynamic tool that a Signal handler registers during a listing is then not compared, the listed tool goes into registry beside it, and the model is offered the MCP spec while calls run the dynamic tool (Strands' get_all_tools_config prefers the registry entry, _lookup_tool the dynamic one); this test only uses register_tool. (b) Re-reading every provider's _tools after the loop instead of as each listing arrives (the 'Read now' comment at 215-216): an agent then applies, unchecked, a listing that another agent sharing the client made meanwhile. (c) Widening the unwrap at 247 to any ValueError: nothing checks that a user hook's ValueError after a tool call stays wrapped, which the body's 'unwraps only its own error' relies on. Tests for (a) and (b), each passing on the head and failing on its mutant:

async def test_mcp_dynamic_tool_added_while_listing_is_refused(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    a, b = TemporalMCPClient("a"), TemporalMCPClient("b")
    agent = TemporalAgent(model="m", tools=[a, b])
    listing_b = _listing(b, "echo")

    async def b_while_signal_adds_dynamic_echo() -> None:
        agent.tool_registry.register_dynamic_tool(_local_echo)
        await listing_b()

    monkeypatch.setattr(a, "_refresh", _listing(a, "safe"))
    monkeypatch.setattr(b, "_refresh", b_while_signal_adds_dynamic_echo)
    with pytest.raises(MCPToolNameConflictError, match="MCP server 'b' lists it"):
        await _before_model_call(agent)
    assert agent.tool_registry.registry == {}
    assert agent.tool_registry.dynamic_tools == {"echo": _local_echo}


async def test_mcp_listing_is_read_when_it_arrives(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    p1, p2 = TemporalMCPClient("p1"), TemporalMCPClient("p2")
    first = TemporalAgent(model="m", tools=[p1, p2])
    second = TemporalAgent(model="m", tools=[p1])
    monkeypatch.setattr(p1, "_refresh", _listing(p1, "x"))
    listing_p2 = _listing(p2, "y")

    async def p2_while_second_lists_p1() -> None:
        monkeypatch.setattr(p1, "_refresh", _listing(p1, "y"))
        await _before_model_call(second)
        await listing_p2()

    monkeypatch.setattr(p2, "_refresh", p2_while_second_lists_p1)
    await _before_model_call(first)
    assert set(first.tool_registry.registry) == {"x", "y"}
    assert first.tool_registry.registry["y"] is p2._tools[0]

Separately, test_mcp_name_moves_to_a_cached_server (line 843) no longer exercises a move: since load_tools() returns [], its agent has no tools before its first hook, so the comment on line 850 ('with a's echo from load_tools()') is stale and the test repeats the late-agent tests; rewrite its docstring and comment, or drop it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the mutants. In 3fddb6d:

  • (a) and (b): your two tests, test_mcp_dynamic_tool_added_while_listing_is_refused and test_mcp_listing_is_read_when_it_arrives.
  • (c): test_other_errors_after_a_tool_call_stay_wrapped runs a tool call, then a BeforeModelCallEvent hook that raises ValueError, and expects Workflow code to catch Strands' EventLoopException around it. With the unwrap widened to any ValueError, it fails.
  • test_mcp_name_moves_to_a_cached_server is dropped. With load_tools() returning [], an agent can't hold one server's tool before its first turn, and a cached server's listing doesn't change later, so the move it covered can't happen any more.

…hree more paths

- README and the error's docstring: the error fails the Workflow from the run
  method or a Signal handler, only the Update from an Update handler; Strands'
  Swarm and agents used as tools keep it as a failed node or an error result.
  It repeats at every model call while the duplicate lasts; two handles of one
  server are fixed by passing only one; a new prefix reaches an open run with an
  uncached client. The rule names names that differ from a taken one only by
  '-' or '_'.
- README upgrade note: an agent that shares a cache_tools=True client with
  another agent and was built before its first listing now gets the client's
  tools, and a tool call that an agent's initial messages end with finds no MCP
  tool before the first model call.
- Tests: a dynamic tool added during a listing, a listing read when it
  arrives, and errors other than this one after a tool call staying wrapped by
  Strands. The cached-server move test is gone: that move can no longer happen.
@campoy

campoy commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Round 5 is in 3fddb6d, with replies inline. From the summary:

  • PR body: the clause on -/_ names now says those runs also fail when the listing came after a tool call and Workflow code caught Strands' EventLoopException, since this version raises MCPToolNameConflictError itself there.
  • Parity: agreed. The TypeScript plugin's mid-run duplicates are out of scope here and should get their own issue.

main now runs the MCP Activities through temporalio-mcp (#190), with
`prefix` and `tool_filters` on TemporalMCPClient. Port #184 to it:

- Keep MCPToolNameConflictError and load_tools() returning [] in the rewritten
  _temporal_mcp_client.py. Two handles of one server clash on one agent only with the same
  prefix; the docstring says so.
- The conflict hint points at the server's TemporalMCPClient and its tool_filters; for two
  handles of one server it suggests a different prefix too.
- README: #184's duplicate-name paragraphs follow main's new MCP paragraphs. A new prefix is a
  Workflow code change, so an open run that met the error still needs a reset.
- Tests: the stand-in tools and list-tools Activity use temporalio-mcp's types and names; the
  four main histories are re-recorded on main at 275b1e6, the distinct-names one with the
  prefix on echo_b's TemporalMCPClient.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sixth round, at head 7834296 (3fddb6d, then a merge of main that ports the change onto #190: temporalio-mcp Activities, and prefix and tool_filters on TemporalMCPClient). About 5,300 of the 6,349 added lines are the four re-recorded histories. make lint passes and make test runs 213 tests green on the head; CI is green. Recipe: last round's reproductions rerun on the post-#190 Activity names, then two finder angles (Temporal semantics and replay; line by line, messages, docs and tests), each candidate settled by a probe in separate worktrees: histories recorded on unmodified main (ea04762, whose Strands plugin is identical to the merge base 275b1e6) and replayed on the head and back, a real ResetWorkflowExecution on the dev server, hook-level probes through the real _refresh(), pyright against Strands 1.61.1 and 1.63.0 trees, a differential fuzz of the hook against Strands' own registry rule (about 147k hook runs; its one mismatch, a dynamic tool left under a server-held name after an explicit removal, behaves the same on main), and a mutation pass over the lines changed since 1405eff. Checked and clean: the four histories replay on main, fail on the head at the stated Activity pairs, and decode consistently with the workflows that replay them; the body's three read-the-tools shapes (a late agent reading tool_names before its first model call, Workflow code that catches a failed listing, a Signal handler reading during a later listing) still change commands both ways on post-#190 code, as disclosed; the failure contract holds for Graph (it re-raises), Swarm, an agent used as a tool, the forced structured-output cycle and a stream_async consumer; register_tool, replace, register_dynamic_tool, process_tools and the hook registry are unchanged from Strands 1.51 to 1.63; and the body's counts (29 new cases, 33 in the file). Refuted: a bare Strands ValueError from the apply loop for anything the check accepts, a listing other than the checked one being applied, and command differences for asyncio.gather, a client passed twice, AfterModelCallEvent retries, interrupts and Continue-As-New. Not verified: the body's 20-run and 10-run matrices (run on f2a5bf1 before #190, not rerun) and a mixed rollout (listed as not covered).

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Round five is resolved, each item checked by rerunning its reproduction on the post-#190 Activity names. The shared cache_tools=True shape and the initial-messages tool call are in the README upgrade note and in the body's lists, and still behave as described: main ends with executor tools=[] and the head with ['echo'], and each history fails on the other; the resumed agent now answers Unknown tool: echo and schedules only list-tools, where main schedules call-tool first. The failure contract names the run method, Signal handlers, the Update, Swarm and agent-as-tool, in the README and in the error's docstring, and the docstring states the -/_ rule exactly. The repeat-while-the-duplicate-lasts clause is in, and the 'pass only one handle' clause is superseded by #190's handle-level prefix. Last round's three mutants are each killed by one new test (test_mcp_dynamic_tool_added_while_listing_is_refused, test_mcp_listing_is_read_when_it_arrives, test_other_errors_after_a_tool_call_stay_wrapped), and the stale cached-move test is gone. The body's -/_ clause covers the caught EventLoopException. Round four's #190 note is done in the merge: load_tools() still returns [] and the hints name TemporalMCPClient. Earlier decisions stand (no gate, the name-is-the-server's rule, the hook order), brianstrauch's items were closed in earlier rounds, and the TypeScript parity issue you agreed to has not been filed yet.

Where this round's items cluster: the code is right. What is left is again what the docs promise, now partly because of the port: two more replay-changing shapes are missing from the upgrade note and from the body's list of runs that keep their commands (one follows from my round-two suggestion), and the recovery advice after a clash no longer holds for the prefix fix now that the prefix lives in Workflow code. The rest is small: hints that name the prefixed tool, one import that breaks the nightly lint in two days, four branches without a test, and one sentence of #190's that this PR makes false.

Decision: comment rather than approve, because every earlier item is fixed and the code is right, but the upgrade note, which stands in for a version gate, misses two verified replay-changing shapes and the recovery advice fails for the fix the error suggests; with those sentences and the one-line import fix in, I would approve.

Findings on lines outside the diff

  • python/strands_agents/README.md:698: P3: #190's 'Without a prefix, same-named tools from different servers replace each other.' is false with this PR: they are refused with MCPToolNameConflictError (line 673; test_mcp_duplicate_tool_names_are_refused). Suggested: 'Without distinct prefixes, same-named tools from different servers are refused (see above).'

PR body: 'They were run on f2a5bf1 and again on this head, with the same results; every run recorded on f2a5bf1 replays on this head' is false at 7834296 and contradicts '(not rerun since)' in the same bullet: #190 renamed the MCP Activities, so every MCP run recorded before it fails at its first listing (the f2a5bf1-tree legacy_mcp_distinct_names.json on this head: Activity type of scheduled event 'echo_a-list-tools' does not match activity type of activity command 'temporalio.mcp.echo_a.list-tools'). For the same reason the 'Stand-in MCP Activities' histories recorded on main at 3488fbe now fail at the rename, not at the shapes they describe. I reran those three shapes and round five's two on post-#190 code, and each still changes commands both ways as disclosed, so only the evidence needs updating. Release notes are the commit subject alone, so consider naming the second change in the title (for example '... and give each agent its MCP tools at its model calls'): runs with no duplicate names can fail to replay too.

Comment thread python/strands_agents/README.md Outdated

The error fails the Workflow when it escapes the Workflow's run method or a Signal handler, with `StrandsPlugin` on the client or only on the Worker, because replay would raise it again. Escaping an Update handler, it fails only that Update, and the run stays open. Strands' `Swarm` records it as a failed node, and an agent used as a tool returns it as an error result, so neither fails the Workflow. If Workflow code catches it, or an Update failed, and calls the agent again, first remove the messages that Strands added to `agent.messages` during that call (the prompt, and any tool calls and results), as for any error during an agent call. A run that met the error has the refusal in its history. A new `prefix` or `tool_filters` in Workflow code changes what a replay of that history does, so a run that is still open needs a reset to a point before that listing, or Worker Versioning.

Earlier versions let the later tool replace the earlier one in most of these cases. A run that started before you deploy this version can fail to replay on it if one of its agents met such a duplicate, including two handles of one server and names that differ only by `-` or `_`. It can also fail if a server's tools changed during the run: a tool that moves from one server to another in one turn now stays, where earlier versions could lose it, and an agent that shares an uncached client with another agent now drops the tools the server stopped listing, where earlier versions kept them. And an agent built after another agent listed a client they share has none of that client's tools until its first model call, where earlier versions gave it the last listing at construction. A call to one of them that its initial `messages` end with, which Strands runs before that model call, now finds no such tool, and Workflow code that reads its `tool_names` or `tool_registry` before then can take another path, though no names clashed and the servers kept their tools. An agent that shares a `cache_tools=True` client with another agent and was built before that agent's first listing now gets the client's tools at its first model call; earlier versions never gave it those tools. Workflow code that reads its tools can take another path, and runs in which it calls them fail to replay on earlier versions. Last, an agent now applies a turn's listings together, once every server due that turn has listed, where earlier versions added each server's tools as soon as it listed. Until then the agent's tools stay as they were before that turn, and they stay so if a listing fails. Workflow code that reads the agent's tools before the turn's listings are applied can take another path, though no names clashed and the servers kept their tools: for example a Signal or Update handler that runs while a later server lists, even if every listing then succeeds, or code that catches a failed listing. Let those runs finish first, or use Worker Versioning.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: two more shapes change commands without a name clash, and neither is in this note or in the body's list of runs that keep their commands.

(1) Workflow code that replaces or removes the tool of a cache_tools=True client between model calls, for example a wrapper put in with agent.tool_registry.replace(...). Main's hook returns before applying anything once a cached client has listed (main _temporal_agent.py:133-135), so such a change lasted for the run; the head skips only the listing and applies the stored listing at every model call (_temporal_agent.py:213-217, 227-232), so the server's tool is back at the next one. Probe: one agent with one cached client, a text turn, then replace(local_echo) or registry.pop("echo"), then the model calls echo. Main runs the local tool (LOCAL:hi, no call-tool) or answers Unknown tool: echo; the head schedules temporalio.mcp.f1c.call-tool in both cases. Main's histories fail on the head with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'invoke_model' does not match activity type of activity command 'temporalio.mcp.f1c.call-tool', the head's fail on main the other way, and the uncached controls replay both ways. This follows from my round-two suggestion to drop the cached skip: I noted the asymmetry with uncached clients, not that main kept such changes. Line 673 states the head's rule but not that it is new for cached clients, and the body's 'Later turns check its stored listing again' should say 'check and apply'.

(2) An agent built after another agent listed a shared client: Strands estimates the first model call's input tokens before the hooks run (strands/event_loop/event_loop.py:509 in 1.56), and with no usage metadata in the messages the estimate counts the registry's tool specs (:159). Main counted the client's tools there, from construction; the head counts none. So proactive compression (context_manager; its "auto" preset summarizes at 85% utilization) can run a summary invoke_model on one version and not the other, with no read in Workflow code and no initial tool call. Probe with one long tool description, a 2,000-token window and six initial messages: main schedules the summary invoke_model before the late agent's listing, the head does not, and each history fails on the other (scheduled event 'invoke_model' does not match ... 'temporalio.mcp.f1big.list-tools', and the reverse). User hooks that read projected_input_tokens see the same difference.

Suggested sentences: 'An agent whose cache_tools=True client's tool Workflow code replaced or removed now gets the server's tool back at the next model call; earlier versions kept the change.' And after 'can take another path': 'So can Strands' estimate of that call's input tokens, which now leaves those tools out, so proactive context compression can run at a different model call.' Widen the body's list to match. Exposure today is runs started on main builds since #190 (the only release, v0.1.0, predates it, and #190's rename already stops its MCP runs from replaying) and any release cut before this lands. A third difference is contrived enough for 'Not covered': a Signal handler that adds a BeforeModelCallEvent callback with a lower order while a listing runs makes the head list every due server again, where main re-ran only the in-flight server's hook (Strands iterates the live callback list, hooks/registry.py:441-448).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, both added in be33d1e, with your sentences:

  • The upgrade note now says that an agent whose cache_tools=True client's tool Workflow code replaced or removed gets the server's tool back at the next model call, where earlier versions kept the change. The rule above it now says a removed tool comes back too, also with cache_tools=True.
  • After "can take another path": Strands' estimate of that model call's input tokens now leaves those tools out, so proactive context compression can run at a different model call.

The body lists both among the runs that can fail to replay and in the upgrade list, and says "check and apply". The Signal handler that adds a BeforeModelCallEvent callback during a listing is under "Not covered".

Comment thread python/strands_agents/README.md Outdated

Tool names must be unique on one agent. Two tools may not have the same name, or names that differ only by `-` or `_`: for example two servers that both list `search`, a server that lists a name twice, or a server tool named like a tool in `tools=[...]`, a `TemporalSandbox` tool or a tool a Signal handler adds while the servers list. `TemporalAgent` learns its MCP tools only when it lists them, so the model call after that listing raises `MCPToolNameConflictError`, a `ValueError` and a non-retryable `ApplicationError`: the first one, or, with `cache_tools=False`, a later one if a server starts listing such a name. It is raised again at every later model call while the duplicate lasts; between `cache_tools=True` listings, that is the rest of the run. This holds for an agent built before or after its clients listed. Give one `TemporalMCPClient` a different `prefix`, or drop the tool with its `tool_filters`. While a server lists a name, the name is the server's: a tool you put under it is replaced at the next turn. A `structured_output_model` named like an MCP tool the agent already has gets Strands' own `ValueError` when the call starts, as in Strands.

The error fails the Workflow when it escapes the Workflow's run method or a Signal handler, with `StrandsPlugin` on the client or only on the Worker, because replay would raise it again. Escaping an Update handler, it fails only that Update, and the run stays open. Strands' `Swarm` records it as a failed node, and an agent used as a tool returns it as an error result, so neither fails the Workflow. If Workflow code catches it, or an Update failed, and calls the agent again, first remove the messages that Strands added to `agent.messages` during that call (the prompt, and any tool calls and results), as for any error during an agent call. A run that met the error has the refusal in its history. A new `prefix` or `tool_filters` in Workflow code changes what a replay of that history does, so a run that is still open needs a reset to a point before that listing, or Worker Versioning.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: since #190 the prefix is applied in Workflow code, so the recovery this sentence gives fails for the fix the error suggests, and the same change breaks open runs that never met the error. _refresh() builds TemporalMCPTool(self._client, tool, self._prefix) (_temporal_mcp_client.py:160), so a new prefix renames that server's tools in every replay, including tools the model called before the clash. Probe on the dev server: ra lists safe and later safe and echo, rb lists echo; the model calls safe, the next turn is refused, and the Workflow catches the error and waits on a Signal. A real reset to the Workflow Task completed just before the refused listing (event 34), with prefix="pa" on ra, fails the new run's Workflow Task with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'temporalio.mcp.ra.call-tool' does not match activity type of activity command 'temporalio.mcp.ra.list-tools' and leaves it open; the same reset with tool_filters={"rejected": ["echo"]} completes. Replaying the history cut before the clash, a run that never met the error but called safe, also fails with the prefix change. Before the port the prefix sat on the Worker-side factory and its effect was recorded in the listing, so the old advice held. Suggested: 'A new prefix renames that server's tools, and new tool_filters can drop some, in every replay: an open run whose model called a renamed or dropped tool fails to replay, whether or not it met the error, so deploy such a change with Worker Versioning. To recover a run that met the error, reset it to before the first model call that used one of that server's tools (with a new prefix, usually before its first listing); dropping only the clashing tool with tool_filters needs only a reset to before the refused listing.' The body's Breaking paragraph, which ends on 'Give one server's TemporalMCPClient a prefix', needs the same caveat.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, thanks for the reset probe. In be33d1e the sentence is now:

A new prefix renames that server's tools, and new tool_filters can drop some, in every replay: an open run whose model called a renamed or dropped tool fails to replay, whether or not it met the error, so deploy such a change with Worker Versioning. To recover a run that met the error, reset it to before the refused listing if you drop, with tool_filters, a clashing tool the model never called. With a new prefix, reset it to before the first model call that used one of that server's tools.

I limited the filter case to a tool the model never called, since dropping one it called fails replay the same way. The body's Breaking paragraph has the same caveat.

elif holder.server == provider.server:
source = (
"The agent has two TemporalMCPClient handles for MCP server "
f"'{provider.server}'. Give one a different prefix, or pass only one."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: with prefix and tool_filters on the handle, three of these hints point at the wrong fix. Through the real _refresh(), with only the durable list_tools stubbed: (a) servers a and b, both with prefix="p", both list x; the message names 'p_x', but tool_filters match the server's name (_temporal_mcp_client.py:185), so following it with {"rejected": ["p_x"]} on b is refused again and only ["x"] works. (b) A local p_x against a with prefix="p": 'Set a prefix on the server's TemporalMCPClient', though it has one. (c) This branch, for two handles of one server with the same prefix and overlapping filters (allowed: ["search", "create_pr"] and ["create_pr"], the per-tool activity options case): 'Give one a different prefix, or pass only one.', where narrowing one handle's tool_filters is the fix that keeps both; with disjoint filters the same two handles are accepted ({'search': 'fast', 'create_pr': 'slow'}), so the docstring at _temporal_mcp_client.py:81-82 ('two handles of a server with the same prefix list the same names, which are refused') is too broad. Fix: pass the clashing tools in and name the server's tool when it differs ('MCP servers 'a' and 'b' both list it (as 'x')', 'drop 'x' with its tool_filters'), write 'Set a prefix (or a different one)', add 'or narrow one handle's tool_filters' here, and say in the docstring that two handles of a server on one agent must not list the same name: give them different prefixes or disjoint tool_filters.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in be33d1e. The check now passes the clashing tools in, and the message names each server's own tool name when a prefix changes it:

  • MCP servers 'a' (as 'x') and 'b' (as 'x') both list it. Set a prefix (or a different one) on one server's TemporalMCPClient, or drop the tool from one with its tool_filters. Here the hint doesn't name one tool, since the two servers' names can differ; the (as ...) parts show them.
  • MCP server 'a' (as 'x') lists it, and another tool of the agent has it. Set a prefix (or a different one) on the server's TemporalMCPClient, or drop 'x' with its tool_filters.
  • Two handles: Give one a different prefix, narrow one's tool_filters, or pass only one.

The docstring now says two handles of a server on one agent must not list the same name: give them different prefixes or disjoint tool_filters. test_mcp_conflict_names_the_servers_tool runs your three cases through the real _refresh() with only the durable listing stubbed, and checks that rejecting x on b passes and that your disjoint-filters pair is accepted.

from strands.hooks import BeforeModelCallEvent, HookCallback
from strands.hooks import BeforeModelCallEvent
from strands.tools.registry import ToolRegistry
from strands.types._events import TypedEvent

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this import fails make lint once the nightly lane resolves Strands 1.62 or later, which the two-week cooldown allows from 2026-11-04 (1.62.0 was uploaded 2026-10-21). From 1.62.0, strands/types/_events.py:21 imports TypedEvent from .events without re-exporting it (the two names above it use as re-exports), and Strands ships py.typed. Pyright against an extracted 1.63.0 tree, in its default mode, which the shared config does not change for this rule: error: "TypedEvent" is not exported from module "strands.types._events" Import from "strands.types.events" instead (reportPrivateImportUsage); against 1.61.1, clean. strands.types.events does not exist before 1.62, so annotate _run_loop as AsyncGenerator[Any, None] and drop the import, or add # pyright: ignore[reportPrivateImportUsage]. Runtime is unaffected. Nit: Strands 1.63 adds a public ToolRegistry.remove(), so 'There is no public unregister' (lines 220-221) holds only up to 1.62.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. In be33d1e _run_loop is annotated AsyncGenerator[Any, None] and the import is gone. The comment now says ToolRegistry.remove() needs Strands 1.63, so the loop removes the tools directly (the plugin's floor is 1.51).

Comment thread python/strands_agents/tests/test_mcp.py Outdated
)
assert (await handle.result()).startswith(
"refused: Tool name 'echo' already exists. "
"MCP servers 'echo_a' and 'echo_b' both list it."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests): four behaviour-changing mutants of the new code survive the full suite (213 passed under each). (a) if name in seen for if key in seen (_temporal_agent.py:87): with s1 listing x_y and s2 listing x-y, underscore form first, the check passes and the apply loop raises Strands' bare ValueError after registering x_y, which fails the Workflow Task in a loop; every test that lists both forms lists the hyphen form first. (b) An unnormalized held (lines 78-80): a local x-y against a listed x_y fails the same way; the test covers only a local foo_bar against a listed foo-bar. (c) self._mcp_names |= new (line 233): a dropped name is never freed, so a local tool later put under it is deleted at the next turn and the server takes the name back without a refusal; on the head the local tool stays and the re-listing is refused. (d) Dropping the hint from the two-servers message (lines 59-62): the tests pin it only up to 'both list it.' (here and at 721, 732 and 843), so a revert to 3fddb6d's 'MCPClient' wording, which since #190 points at a factory option that fails every MCP Activity, passes too. Tests that kill them: pin the full two-servers message once; [s1: x_y, s2: x-y]; a local x-y with a listed x_y; and a name the server dropped is the agent's again (a local tool kept after the drop, refused when the server lists the name again).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, all four now fail a test in be33d1e. I ran tests/test_mcp.py against each mutant:

  • (a) test_mcp_refused_listing_registers_nothing also runs with x_y on the first server and x-y on the second; both cases fail under the mutant.
  • (b) test_mcp_tool_named_like_another_tool_is_refused has a local x-y against a listed x_y.
  • (c) test_mcp_listing_replaces_a_tool_replaced_in_place now puts a local tool under the name the server dropped: it stays at the next turn, and the server listing the name again is refused.
  • (d) test_mcp_duplicate_tool_names_are_refused pins the whole two-servers message.

…on TypeScript re-listing

- The conflict message names each server's own tool name when a prefix
  changes it, which tool_filters match, and suggests a different prefix,
  narrower tool_filters for two handles of one server, or dropping the tool.
- The README says a new prefix or tool_filters changes every replay, so
  deploy it with Worker Versioning, and which reset point recovers a run.
  It adds two more runs that can fail to replay, and fixes the upgrade
  note that said same-named tools replace each other.
- Drop the private TypedEvent import, which Strands 1.62 no longer
  re-exports.
- Tests for the '-'/'_' order across servers, a local x-y against a listed
  x_y, a name the server dropped, and the full two-servers message.
- TypeScript: a re-listed server that starts listing a name another tool
  of the agent has now throws Strands' ToolValidationError and leaves the
  registry as it was, instead of replacing that tool.
@campoy campoy changed the title Breaking: refuse duplicate MCP tool names in Strands agents Breaking: refuse duplicate MCP tool names and give each Strands agent its MCP tools at its model calls Nov 2, 2026
@campoy

campoy commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the sixth round. It's answered in be33d1e, with replies in the threads. The items outside the threads:

  • README line 698 (Breaking: run the Strands MCP activities through temporalio-mcp #190's upgrade note): now "Without distinct prefixes, same-named tools from different servers are refused (see above)." [strands-agents-python] breaking: refuse misconfigured MCP factories and correct the MCP README #377 rewrites that bullet too, so whichever lands second keeps both changes.
  • PR body: the false "run on f2a5bf1 and again on this head" claim is gone. The body now says the 20-run matrix and the stand-in histories predate Breaking: run the Strands MCP activities through temporalio-mcp #190 and fail at the Activity rename, that only the four 275b1e6 histories check replay after the port, and that you reran the shapes on post-Breaking: run the Strands MCP activities through temporalio-mcp #190 code. It also says "check and apply", lists the two new shapes, and has the prefix caveat.
  • Title: renamed to "Breaking: refuse duplicate MCP tool names and give each Strands agent its MCP tools at its model calls", as you suggested.
  • TypeScript: fixed here instead of filed, since it's the same defect. When a re-listed server starts listing a name another tool of the agent has (another server's tool, a tool in tools, or a -/_ twin), refreshTools() now throws Strands' ToolValidationError and leaves the registry as it was. That's the error Strands throws at the agent's first listing; before, addOrReplace() replaced the other tool. A name stays the server's while it lists it, as in Python, so a tool put under it is still replaced. As at the first listing, the error fails the Workflow Task, not the run; making both fail the run would be a separate change. The new test in test-strands.ts fails without the change (both runs end with done), and the README has the rule and an upgrade note.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seventh round, at head be33d1e (one commit since 7834296: the conflict hints, the README's recovery advice and two upgrade cases, the dropped import, four tests, and a new TypeScript refusal on re-listing). make lint and make test pass in both plugins at the head (Python 217, TypeScript 88), and CI is green. The PR conflicts with main in one hunk of typescript/strands-agents/README.md: the new duplicate-name paragraph sits just above the connection paragraph that #371 rewrote, so keep both. temporal-mcp-client.ts merges cleanly, since #371 changed only the Activity-side connections. On a local trial merge with that hunk resolved, lint and tests pass in both plugins (Python 217, its tree unchanged by the merge; TypeScript 91). How I checked: round six's reproductions rerun at this head (the hint probe through the real _refresh(), a mutation pass over last round's four mutants plus three on the new message code, pyright against the extracted Strands 1.63 tree, and real ResetWorkflowExecution calls on the dev server for the new recovery advice), and the TypeScript change read against @strands-agents/sdk 1.19's ToolRegistry and hook registry, with Worker probes run once with main's refreshTools and once with this head's, plus a history recorded with main's replayed on this head. Checked and clean: the PR's TypeScript test fails with main's refreshTools (its first run returns done), as the body says; the reverse of the move in the P2 below runs the same with both; the PR now adds only public Strands imports, each defined in its module in 1.63. Not verified: a mixed rollout (listed as not covered) and Strands TypeScript releases other than the locked 1.19.0.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Every round-six item is fixed, each checked by rerunning its reproduction. The upgrade note has both shapes (a cache_tools=True tool that Workflow code replaced or removed comes back; the late agent's token estimate), the rule above it says so, and the body says 'check and apply'. The recovery advice now holds: with prefix="pa" on ra, a reset to the Workflow Task that scheduled the first model call completes (the model calls pa_safe, and call-tool gets the server's safe), the same reset without the fix is refused again, and tool_filters with a reset to just before the refused listing completes. The hints name the server's tool (MCP servers 'a' (as 'x') and 'b' (as 'x') both list it), so rejected: ['x'] on b passes, the local p_x case says drop 'x', the two-handles hint offers narrowing tool_filters, and the docstring says disjoint filters. The TypedEvent import is gone. The four mutants each fail at least one test now, as do three more on the new message code (_listed_as never naming the server's tool, _server_name returning the agent's name, the old two-handles hint). README line 698, the stale replay claim in the body and the title are fixed. Earlier decisions stand (no gate, the name-is-the-server's rule, the hook order), and I take the TypeScript refusal failing the Workflow Task rather than the run as your stated follow-up. The TypeScript parity item is fixed here instead of filed, and that is where this round's findings are.

Where the problems cluster: the Python side is done and I found nothing new in it; on its own I would approve it. Everything this round is in the TypeScript code added in be33d1e: each server's refresh checks its own listing against the live registry, which refuses a tool that moves between servers; its test covers only exact-name refusals; and the title's second clause will land in the TypeScript release notes.

Decision: request changes, because the new TypeScript refresh turns a tool that moves from one re-listed server to a later one, which main handles, into a Workflow Task failure loop that only a code change, a reset or termination ends; checking each round's listings together, as the Python hook does, or moving the TypeScript change to its own PR would clear it.

PR title (P3): each plugin's release notes list the subjects of the commits that touch its directory (scripts/release/release_tool.py:456), so this squash commit's subject goes into the TypeScript notes too, where 'give each Strands agent its MCP tools at its model calls' describes nothing that changed: TypeScript agents still get their MCP tools from Strands' first listing. A separate TypeScript PR would get its own subject and take the README conflict with it; otherwise name the languages, for example 'Breaking: refuse duplicate Strands MCP tool names and give each Python agent its MCP tools at its model calls'.

for (const tool of registry.list()) {
if (tool instanceof TemporalMCPTool && tool.server === this.server && !freshNames.has(tool.name)) {
registry.remove(tool.name);
if (!held.has(tool.name)) taken.set(normalized(tool.name), tool);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: each server's refresh is checked against the live registry, so a tool that moves to a re-listed server whose hook runs first is refused, and an uncaught refusal leaves the run stuck. TemporalAgent adds one AfterToolsEvent hook per uncached client (temporal-agent.ts:85-89), and Strands runs After* callbacks in reverse registration order (hooks/registry.js:84-94 in @strands-agents/sdk 1.19), so with tools: [a, b] server b refreshes first, while a's listFiles from the last round is still registered and lands in taken here. Probe with the PR's ChangingMcpClient and mcpServersAgent: a lists listFiles and then nothing, b lists other and then other and listFiles, and the model calls listFiles twice. With main's refreshTools the run returns done and the second call runs on b (["a:listFiles","b:listFiles"]); on this head it is refused with Tool with name 'listFiles' already registered. MCP servers 'a' and 'b' both list it., though after the round only b would have the name. Without the try/catch the run stays RUNNING with a failed Workflow Task on every attempt, and the history recorded with main's refreshTools fails to replay on this head with the same message (ReplayError). Changing the servers does not help, since the refused listing is already in the history. The move from b to a passes on both, so one direction is refused whichever order the hooks run in. Python accepts both by checking a turn's listings together (_refresh_mcp_tools, _temporal_agent.py:224-253), and the body says a name stays the server's 'as in Python'. Fix: register one AfterToolsEvent hook per agent that lists the uncached clients in the order the per-client hooks run now (reverse of tools, so the listTools Activities keep their order), checks the listings against each other and against the registry tools that none of those clients holds, and only then removes and adds. Add the move as a test (it fails on this head), and say in the README rule that a name can move from one server to another between listing rounds.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, agreed. Fixed as you suggested in eeb69d2. TemporalAgent now registers one AfterToolsEvent hook per agent (TemporalMCPClient.refreshAll). It lists the cacheTools: false clients last to first, the order the hooks per client ran in, so the listTools Activities keep their order. Then it checks the new listings against each other and against the registry tools that none of those clients holds, and only then removes and adds. Your move now passes in both directions: the test moves x from b to a with the servers in either order, and the model's call runs on a. On the previous head the order with a listed first is refused with MCP servers 'b' and 'a' both list it.

The same code had a second problem: until a client had re-listed once, its names came from the tools it had created. So a tool that Workflow code put under the server's name in the first tool round made the first re-listing refuse the server's own name. TemporalAgent now records a name as the client's when Strands adds its tool (TemporalMCPClient.holdAdded, which wraps the registry's add(); Strands' initialize() adds MCP tools only through it). The test covers that case too; the previous head refuses it.

The README rule now says the re-listed servers' listings are checked and applied together, so a name can move between servers. The upgrade note adds that their new tools now appear once all of them have listed (none if a listing fails), and that a tool put under a server's name is removed by the listing that drops the name.

t.is(counters.listCalls, 1);
});

test('a re-listed MCP tool name that another tool of the agent has is refused', async (t) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests): this test pins only exact-name refusals, so two branches that the README and the refreshTools docstring describe have no test. Mutants run against it: normalized() returning the name unchanged (no -/_ rule) passes, and so does skipping the seen check (a server re-listing one name twice). Without the -/_ check, a re-listed x-y against a tool named x_y falls through to Strands' own check in addOrReplace, which throws partway through applying the listing, after any dropped names were removed; without the seen check, a name listed twice is accepted. Add a re-listed x-y against an x_y in tools (registry unchanged), a server that re-lists a name twice, and the move from the comment on temporal-mcp-client.ts.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in eeb69d2, in the same test: a re-listed take-note against a take_note in tools, and a server that re-lists other twice. Both are refused, and the agent keeps the listFiles that the refused listing drops, so the registry is unchanged. I ran the test against your two mutants: without the -/_ rule, Strands' own check throws after listFiles was removed; without the check for a name listed twice, the run ends with done. Both fail the test. The move from the other thread is in it too, and each case now runs with maxCachedWorkflows: 0 and replays its history.

…s from when Strands adds them

- TemporalAgent registers one AfterToolsEvent hook per agent instead of one
  per uncached client. It lists the clients in the order the hooks per client
  ran in, so the listTools activities keep their order, then checks the new
  listings against each other and the agent's other tools, and applies them
  together. A name can now move from one server to another in either order.
- A name is a client's from when Strands adds its tool: TemporalAgent wraps
  its registry's add(), so a tool that workflow code puts under the name in
  the first tool round no longer makes the first re-listing refuse it.
- Tests for a '-'/'_' twin of a tool in tools, a name listed twice, both
  move orders and the first-round replacement, each replayed at every
  workflow task.
- The TypeScript README says a name can move between servers and adds the
  upgrade cases. The Python README's reset advice now covers workflow code
  that acted on a renamed or dropped tool.
@campoy campoy changed the title Breaking: refuse duplicate MCP tool names and give each Strands agent its MCP tools at its model calls Breaking: refuse duplicate Strands MCP tool names and give each Python agent its MCP tools at its model calls Nov 3, 2026
@campoy

campoy commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the seventh round. It's answered in eeb69d2, after 668dc2f merges main: the README conflict next to #371's connection paragraph keeps both paragraphs. Replies are in the threads. Also:

  • TypeScript refresh: one hook per agent, as you suggested, which lists the re-listed servers in the same order, checks their listings together, then applies them. A name is now a client's from when Strands adds its tool, which fixes a refusal of the server's own name after Workflow code put a tool under it in the first tool round.
  • Python README: the reset advice now also covers Workflow code that acted on a renamed or dropped tool among the agent's tools (for example 'x' in agent.tool_names, then an Activity). It says to reset to before the first listing that returned such a tool, or to a later point only if nothing used those tools before it. A real reset on a dev server fails with [TMPRL1100] at a point just before the refused listing when the code read x, and completes from before the first listing of x.
  • Title: now "Breaking: refuse duplicate Strands MCP tool names and give each Python agent its MCP tools at its model calls", as you suggested.

@campoy
campoy requested a review from DABH November 3, 2026 05:36

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eighth round, at head eeb69d2 (since be33d1e: 668dc2f merges main with #371, and eeb69d2 re-lists a TypeScript agent's uncached servers in one hook, checks a round's listings together, holds a name from when Strands adds its tool, extends the TypeScript test, and rewrites the Python README's reset advice). make lint and make test pass in both plugins at the head (Python 217, TypeScript 91), CI is green, and the PR merges cleanly. How I checked: last round's tool-move reproduction rerun on this head; histories recorded with main for moves in both directions and across three servers, no-clash runs (also two agents in parallel), a true duplicate, a tool put under a name its server then drops, caught refusals that Strands raises itself, a server that re-lists a name twice, and workflows that run a second coroutine beside an agent, each replayed on this head and on main; mutation passes over the new refresh code; a replay probe for the Python reset advice; and the PR's new test run with main's refresh code (its first case returns done, as the body says). The fix suggested in the blocking comment was tried locally against the same histories and the PR's test. Checked and clean: every main history without a duplicate or rejected name replays, except the concurrent shapes in the first comment (four runs of two agents that each re-list two servers replay, since both shift alike); the true duplicate fails to replay at that listing, as the upgrade note says; and the stand-in under a dropped name is now removed without changing commands. Not verified: a mixed rollout (listed as not covered) and Strands TypeScript releases other than the locked 1.19.0.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. The round-seven P2 is fixed: with a listing listFiles and then nothing and b listing other and then other and listFiles, the run returns done and the second call runs on b (["a:listFiles","b:listFiles"]), as with main, with and without the try/catch, and last round's main history of that run, which failed with ReplayError, now replays; so do the reverse move and a move from a to c past b. The test P3 is fixed: the take-note/take_note and listed-twice cases are in, and mutants without the -/_ rule, without the listed-twice check, without the check between listings, without holdAdded, applying each listing as it arrives, keeping freed names in taken, or not updating held each fail the test. The title now limits its second clause to Python. Earlier decisions stand (no gate, the name-is-the-server's rule, the hook order, and the TypeScript refusal failing the Workflow Task as a follow-up). The Python code has not changed since last round, when I found it ready; the README's new reset advice is right in its main case, with one gap noted inline.

Where the problems cluster: everything this round is in eeb69d2. The blocking item comes from the one-hook shape I suggested last round: awaiting the listings in one loop reaches each re-listing after the first a few microtasks sooner than main's hooks did, which reorders commands against a second coroutine and breaks replay of main histories with no name clash. One hook per client, with the round applied in the last one, keeps main's timing. The rest is narrower: a name Strands rejects is still applied part-way and can leave a server unable to re-list after a caught error; the TypeScript upgrade note misses caught refusals that Strands raises itself and a server that re-lists a name twice; the TypeScript README gives no fix for a refusal; the Python reset advice misses runs that went on after the error; and the new test leaves the listing order, the removal and the -/_ check between listings unpinned.

Decision: request changes, because the single refresh hook makes histories recorded with main fail to replay with [TMPRL1100] when a workflow runs another coroutine beside an agent with two or more uncached MCP servers, with no name clash and nothing in the upgrade notes; keeping one hook per client and applying the round in the last one fixes it.

const mcpClients = collectMcpClients(rest.tools);
const relisted = mcpClients.filter((client) => !client.cacheTools);
if (relisted.length > 0) {
this.addHook(AfterToolsEvent, (event) => TemporalMCPClient.refreshAll(relisted, event.agent.toolRegistry));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: awaiting the listings in one hook reaches each re-listing after the first sooner than main's per-client hooks did, so a history recorded with main fails to replay when another coroutine's Activity completes in the same Workflow Task, with no name clash. On main the next server's listTools was scheduled only after refreshTools returned and Strands' invokeCallbacks loop (hooks/registry.js:52-55 in 1.19) resumed and called the next hook; refreshAll schedules it as soon as its own await resumes. The Worker resolves a Workflow Task's Activity results in one batch, so whichever coroutine needs fewer microtasks issues its command first, and that order has moved. Probe: two TemporalAgents under Promise.all; A has tools: [a, b] (both cacheTools: false, the default); B has tools: [c] and an audit hook, agentB.addHook(AfterToolsEvent, workflow.activityAsHook('z-listTools', ...)); each model calls one tool, then answers. When A's first re-listing (b-listTools) and B's hook Activity complete in one Workflow Task, main issues c-listTools before a-listTools, and this head can issue a-listTools first: of eight histories recorded with main (worker-side gates put the two completions in one task), four fail to replay on this head with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'c-listTools' does not match activity type of activity command 'a-listTools', and all eight replay on main. A side coroutine, started from an AfterToolsEvent hook, that awaits one Activity, then an async helper (const next = await pick()), then another Activity breaks the same way (two of six main histories fail, ... 'y-listTools' does not match ... 'a-listTools'). Two agents that both re-list two servers shift alike, which is why plain parallel runs replay. This is the one-hook shape I suggested last round, and stream()'s comment (temporal-agent.ts:124-126) describes exactly this sensitivity. Fix: keep one AfterToolsEvent hook per uncached client, registered as on main, each awaiting only its own listTools() into a per-agent round; the hook that runs first (the last client's) clears the round, and the one that runs last (the first client's) calls apply(). Tried locally: all eight two-agent and six helper histories replay, so do the main histories from my other probes (the true duplicate still fails, as documented), and the PR's test passes. Committing one of these main histories with a replay test would keep it that way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for finding this, and for the fix. Done in 5e14534. It's back to one AfterToolsEvent hook per uncached client, registered as on main (TemporalMCPClient.refreshHooks). Each hook awaits only its own listTools(), as refreshTools() did, and adds the listing to a round for the agent. The hook that runs first (the last client's) starts the round, and the one that runs last (the first client's) checks and applies it.

I recorded six mcpAgentsSideBySide histories on main at 017d88a, in your shape: first with a and b, and second with c and an auditHook Activity hook. Worker-side gates put b's re-listing and the hook Activity in one Workflow Task. Main schedules c-listTools before a-listTools in all six. The three where b's completion comes first fail to replay on eeb69d2 (nondeterminism error), and all six replay on this head. One of them is committed as histories/mcp-side-by-side-017d88a.json with a replay test, which also fails if the hooks run first to last.

registry.addOrReplace(fresh);
for (const { client, tools } of listings) {
registry.addOrReplace(tools as never[]);
client.held.set(registry, new Set(tools.map((t) => t.name)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 (non-blocking): a re-listing with a name Strands rejects is still applied part-way, and the failing client's held is not updated, so after a caught error that server's next valid listing is refused for its own tool. The check phase above covers clashes only. Strands' addOrReplace also validates each name (1 to 64 characters of [a-zA-Z0-9_-], tool-registry.js:114-124 in 1.19), and MCP allows names it rejects, such as files.read. So addOrReplace throws here after the removals at 225-230 and any earlier listing were applied, and this line never runs for the failing client. Probe, with workflow code that catches the error and calls the agent again: c lists [listFiles], then [listFiles, newTool, bad.name], then [listFiles, newTool]. On main the second call returns done; on this head it is refused with Tool with name 'newTool' already registered. MCP server 'c' lists it, and another tool of the agent has it., which is c's own tool, and so is every later listing while c lists newTool. With [listFiles] as the third listing, newTool@c stays on the agent after c drops it (main removes it). With a second server a listing [x] then [y], the round that throws still applies a's change (main had not listed a yet). Fix: in the check loop, validate each listed tool as _validateProperties does, so that every refusal changes nothing, and record held only once the round has applied; failing that, let heldIn() also count the registry tools this client listed. Also, 'as Strands does when the agent first lists the server' in the refreshTools comment (138-140) is not quite right: Strands' first listing keeps the tools it added before the refused one, as the holdAdded comment says.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5e14534. The check now also applies Strands' name rules (1 to 64 characters of [a-zA-Z0-9_-]), with Strands' words and the server, so every refusal changes nothing. With that, addOrReplace can't throw part-way any more, so held is only updated once the round has applied. Descriptions can't fail Strands' check, since TemporalMCPTool fills in an empty one. The test adds c re-listing [newTool, bad.name], which is refused with Tool name must contain only alphanumeric characters, hyphens, and underscores. MCP server 'c' lists 'bad.name'.; the agent keeps listFiles and gets no newTool. The refreshTools comment no longer says "as Strands does when the agent first lists the server".

Comment thread typescript/strands-agents/README.md Outdated
- **Your failure converter.** Earlier versions replaced the failure converter your client and worker set with the plugin's, so workflow code now decodes the failures of earlier runs with yours. If yours decodes a failure into another error than the SDK's default converter and that changes which commands the workflow issues, the run fails to replay. If it only changes a value the workflow keeps or returns, the run replays without error and continues with the new value, so replay tests do not catch it.
- **Errors from a turn.** Workflow code that catches errors from `invoke()` by class now gets an `ApplicationFailure` or `ActivityFailure` instead of the Strands error. If it acts on the difference, the run fails to replay.
- **Context overflow.** A run whose workflow code caught a context overflow from the agent now trims and calls the model again on replay instead, and fails to replay.
- **Duplicate MCP tool names.** When a re-listed server starts listing a name that another tool of the agent has, the listing now throws Strands' `ToolValidationError`, where earlier versions let the new tool replace the other one. A run in which that happened fails to replay at that listing. The new tools of the re-listed servers are now applied together, once all of them have listed, and not at all if a listing fails; earlier versions applied each server's tools as soon as it listed. So workflow code that reads the agent's tools in between, or after catching a failed listing, can take another path. And a tool that workflow code put under the name of a server's tool is now removed by the listing in which that server drops the name, where earlier versions kept it. A run whose model or workflow code used that tool after that listing can fail to replay, though no names clashed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this note covers a name that another tool already has, but other re-listing changes also break replay of earlier runs. First, a re-listing that Strands' own rules refuse (a name that differs from another tool's only by - or _, or a name Strands rejects) threw from that server's hook in earlier versions, so the servers whose hooks come after it were not listed; now every re-listed server lists before the check throws. A main run whose workflow code caught it and went on fails here: with tools: [echo, take_note, a, c] and c starting to list take-note (or bad.name), main's history has c-listTools and then completes, while this head also lists a ([TMPRL1100] Nondeterminism error: Activity machine does not handle this event: HistoryEvent(id: 38, WorkflowExecutionCompleted)). For the same reason, 'where earlier versions let the new tool replace the other one' is not true of -/_ names (Strands threw then as well, after applying part of the listing), and a -/_ name that moves from one server to another is now accepted where earlier versions threw. Second, a re-listed server that lists one name twice was accepted, with the later copy kept, and is now refused; main's history of such a run fails here with Complete workflow machine does not handle this event: HistoryEvent(id: 44, ActivityTaskScheduled). Fix: add both to this bullet, and qualify 'so their listTools activities keep their order' in the refreshAll comment and the body (it holds unless a re-listing is refused).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added both in 5e14534. The bullet now says:

  • A re-listed server that lists one name twice is now refused, where earlier versions kept the later copy.
  • For a name that differs from another tool's only by - or _, or that Strands rejects, earlier versions threw Strands' own error from that server's hook, after applying part of its listing and before listing the servers after it. Now every re-listed server lists first, the refusal applies nothing, and a -/_ name that moves between servers is accepted. So a run whose workflow code caught such an error and went on can fail to replay.

The refreshAll comment went away with the one-hook shape. The new refreshHooks comment and the body say the listTools activities keep their order and timing unless a re-listing is refused.

Comment thread typescript/strands-agents/README.md Outdated
});
```

Tool names must be unique on one agent, as in Strands: two tools may not have the same name, or names that differ only by `-` or `_`. Strands refuses such a name when the agent first lists its MCP servers. After each tool round, the agent re-lists its `cacheTools: false` servers, checks their new listings against each other and against its other tools, and then applies them together, so a name can move from one server to another. When a re-listed server starts listing a name that another tool of the agent has, such as a tool of another server or a tool in `tools`, the listing throws Strands' `ToolValidationError` and leaves the agent's tools as they were. Like other errors thrown in workflow code, it fails the workflow task on every attempt, until the run is reset or terminated. A name is a server's from the listing that added its tool under it until a re-listing of that server drops the name: a tool you put under it is replaced at the next listing, and removed by the listing that drops the name.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: neither this paragraph nor the error says how to fix a refused name in TypeScript, and the obvious worker-side fix does not work. TemporalMCPClient here has no prefix or tool filter, and the message names only the sources (MCP servers 'a' and 'b' both list it.). The factory's McpClient has both options. Its toolFilters work, since the {name}-listTools activity returns the filtered list. Its prefix breaks every call of that server: the {name}-callTool activity passes a fresh { name: input.toolName } (temporal-mcp-client.ts:492), and Strands maps a prefixed name back only for tool objects it listed (this._serverToolNames.get(tool) ?? tool.name, mcp/client.js:289 in 1.19), so the server is asked for p_echo and the model gets an error result. That predates this PR and deserves its own issue, but the README should steer around it. Suggested addition: 'To fix it, stop one server from listing the name, or drop the tool with the toolFilters of the McpClient that the server's factory returns (not its prefix). The refused listing's result is in the run's history, so then reset the run to before that listing.' Also, the last sentence holds for cacheTools: false servers only: a cacheTools: true server is not listed again, so a tool put under one of its names stays for the run, unlike Python, which re-applies cached listings (the body's 'as in Python' does not cover them).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 5e14534, with your sentences: to fix it, stop one server from listing the name, or drop the tool with the toolFilters of the McpClient that the server's factory returns (not its prefix), then reset the run to before the refused listing. The last sentence now covers cacheTools: false servers only, and adds that a cacheTools: true server is not listed again, so a tool put under one of its names stays for the run. The body's "as in Python" is limited the same way. The factory prefix breaking callTool predates this PR, so I've left it for a separate issue.

Comment thread python/strands_agents/README.md Outdated

Tool names must be unique on one agent. Two tools may not have the same name, or names that differ only by `-` or `_`: for example two servers that both list `search`, a server that lists a name twice, or a server tool named like a tool in `tools=[...]`, a `TemporalSandbox` tool or a tool a Signal handler adds while the servers list. `TemporalAgent` learns its MCP tools only when it lists them, so the model call after that listing raises `MCPToolNameConflictError`, a `ValueError` and a non-retryable `ApplicationError`: the first one, or, with `cache_tools=False`, a later one if a server starts listing such a name. It is raised again at every later model call while the duplicate lasts; between `cache_tools=True` listings, that is the rest of the run. This holds for an agent built before or after its clients listed. Give one `TemporalMCPClient` a different `prefix`, or drop the tool with its `tool_filters`. While a server lists a name, the name is the server's: a tool you put under it is replaced at the next model call, and a tool you remove comes back, also with `cache_tools=True`. A `structured_output_model` named like an MCP tool the agent already has gets Strands' own `ValueError` when the call starts, as in Strands.

The error fails the Workflow when it escapes the Workflow's run method or a Signal handler, with `StrandsPlugin` on the client or only on the Worker, because replay would raise it again. Escaping an Update handler, it fails only that Update, and the run stays open. Strands' `Swarm` records it as a failed node, and an agent used as a tool returns it as an error result, so neither fails the Workflow. If Workflow code catches it, or an Update failed, and calls the agent again, first remove the messages that Strands added to `agent.messages` during that call (the prompt, and any tool calls and results), as for any error during an agent call. A new `prefix` renames that server's tools, and new `tool_filters` can drop some, in every replay: an open run fails to replay if its model called a renamed or dropped tool, or if its Workflow code acted on one among the agent's tools (for example on `'x' in agent.tool_names`), whether or not it met the error. So deploy such a change with Worker Versioning. To recover a run that met the error, reset it to before the first listing that returned a tool the change renames or drops. A later reset point, such as just before the refused listing, recovers it only if neither the model nor Workflow code used those tools before that point.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the new recovery advice misses runs that met the error and went on, and a later reset point has to come before the first refusal. A new prefix or tool_filters also lifts the refusal in replay, so the refused turn now proceeds: a run whose Workflow code caught the error (or whose Update failed) and went on fails to replay even if neither the model nor Workflow code used the tool. Probe: echo_a and echo_b both list echo; Workflow code catches the refusal, removes the turn's messages and calls the agent again, and is refused twice. Replayed with tool_filters={"rejected": ["echo"]} on echo_b, the history fails with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'temporalio.mcp.echo_a.list-tools' does not match activity type of activity command 'invoke_model'; cut before the Workflow Task that scheduled the first refused listing it replays, and cut before the second it fails the same way. Suggested wording: '..., or if it met the error and went on, since the refused turn now proceeds' after the agent.tool_names example, and 'A later reset point, such as just before the first refused listing, recovers it only if neither the model nor Workflow code used those tools before that point.'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5e14534 with your wording. The README now says an open run also fails to replay if it met the error and went on, since the refused turn now proceeds, and the later reset point is "just before the first refused listing".

{ b: [['x'], ['later']], a: [['other'], ['x']] },
{ a: [['other'], ['x']], b: [['x'], ['later']] },
] as Record<string, [string[], string[]]>[]) {
t.deepEqual(await run(servers, ['other', 'x']), { result: 'done', calls: ['a:other', 'a:x'] });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests, non-blocking): the new test does not pin the listing order, the removal of a dropped name, or the -/_ check between or within new listings. Mutants that pass all 91 tests: listing the clients first to last (temporal-mcp-client.ts:158-159), though every main history with two or more uncached servers then fails to replay with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'b-listTools' does not match activity type of activity command 'a-listTools' (this test replays only histories its own code recorded); and skipping the removal loop (225-230), which leaves r on an agent whose server b listed r and then s, and keeps a tool put under a dropped name, though the README says the listing that drops the name removes it. Mutants that pass this test: keying seen by the exact name (so a re-listing x_y and b re-listing x-y reach Strands' own check part-way through apply()) and keying own by the exact name (one listing with both); and no case has a failing listTools, so 'not at all if a listing fails' is untested. Fix: commit a history recorded with main for two uncached servers and replay it, as the Python side does with legacy_mcp_*.json (a history of the shape in the temporal-agent.ts comment would pin both the order and the timing); and add a server that drops a name no other server lists (the tool, and a stand-in put under it, are gone from Tools:), { a: [['p'], ['x_y']], b: [['q'], ['x-y']] } and { c: [['p'], ['x-y', 'x_y']] } as refusals, and a failing listTools while another server adds a tool (tools unchanged).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. In 5e14534, each case's result now ends with the agent's tool names, and the test adds:

  • Order and timing: the main history from the other thread, with a replay test. A mutant that registers the hooks in reverse fails it.
  • Removal: b lists r and then s, alone and with a tool put under r in the first tool round. Both end with Tools: s.; a mutant that skips the removal loop fails.
  • -/_ between and within listings: { a: [['p'], ['x_y']], b: [['q'], ['x-y']] } and c re-listing ['x-y', 'x_y'] are refused. Mutants that key seen or own by the exact name fail.
  • A failing listing: a's re-listing fails after b's adds new, and the tools stay other, p. A mutant that applies each listing as it arrives fails.

…trands' name rules first

- One AfterToolsEvent hook per uncached client again, registered as on main,
  each awaiting only its own listing, so the listTools activities keep main's
  order and timing against other coroutines. The listings go into one round
  per agent, which the hook that runs last checks and applies.
- The check also applies Strands' tool name rules, so a refusal never
  applies part of a round.
- A history recorded on main with two agents side by side, whose activity
  completions land in one workflow task, now has a replay test.
- Tests for the removal of a dropped name, '-'/'_' twins between and within
  listings, a name Strands rejects, and a failing listing.
- The TypeScript README says how to fix a refused name, limits the
  name-is-the-server's rule to cacheTools: false servers, and adds the
  upgrade cases for Strands' own refusals and names listed twice. The Python
  README's reset advice covers runs that met the error and went on.
@campoy

campoy commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the eighth round. It's answered in 5e14534, with replies in the threads.

  • Blocking item: it's back to one hook per client, with the round applied in the last one, as you suggested. A history of your side-by-side shape, recorded on main, is committed with a replay test. It fails on eeb69d2 and replays on this head.
  • Strands' name rules are now checked before anything changes.
  • TypeScript README: it says how to fix a refusal and has the cacheTools: true caveat. The upgrade note now covers Strands' own refusals and names listed twice.
  • Python README: the reset advice covers runs that met the error and went on.
  • Tests: they now cover the removal of a dropped name, the -/_ checks between and within listings, and a failing listing.

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ninth round, at head 5e14534 (one commit since eeb69d2: one AfterToolsEvent hook per uncached client again, with the round applied in the hook that runs last; Strands' name rules in the check; a committed main history with a replay test; more TypeScript tests; README fixes in both plugins). make lint and make test pass in both plugins at the head (Python 217, TypeScript 92), CI is green, and the PR merges cleanly with main (017d88a). How I checked: last round's concurrency reproduction rerun against this head (its eight two-agent and six side-coroutine histories recorded with main, the batch and grab variants, and fresh recordings of both shapes on this head); the other main histories from rounds seven and eight replayed; last round's invalid-name probes rerun; the PR's two new tests run against eeb69d2's source; a mutation pass over the new refresh code; 77 more histories recorded with main in shapes not tried before (three uncached servers with a second coroutine at each microtask offset from 0 to 8, mixed cached and uncached servers, Signal and Update handlers that schedule Activities while the round lists, caught failing listings, interrupt and resume with a throwing Strands-plugin hook ordered before or after the client hooks, and one set of clients shared by two agents), of which the 75 without a refused listing replay on this head and the other two fail as the upgrade bullet says; and real ResetWorkflowExecution calls on a dev server for the new TypeScript recovery advice. Refuted: that the per-agent round can mix two events' listings (the start hook runs first in every event's callback list, ConcurrentInvocationError rules out overlapping rounds on one agent, and a round cut short by a failed listing is emptied by the next one); that a hook with another order, from the user or a Strands plugin, can run between the client hooks (Strands reverses After* callbacks and then sorts them stably by order); and that apply() can still change the registry part-way (the check now covers every rule addOrReplace applies to a listed tool, and TemporalMCPTool never leaves a description empty). Replay: of the main histories I have, the ones that fail on this head are all cases the upgrade notes list (a true duplicate, a caught Strands-own refusal, a -/_ move, a name listed twice), and the rest replay. Cross-language: both plugins now refuse a re-listed duplicate and apply a turn's listings together; the remaining difference, the TypeScript refusal failing the Workflow Task rather than the run, is the agreed follow-up. Not verified: a mixed rollout (listed as not covered) and Strands TypeScript releases other than the locked 1.19.0.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. The blocking round-eight P2 is fixed. All eight two-agent and all six side-coroutine histories recorded with main replay on this head (four and two of them failed on eeb69d2), as do the batch and grab variants; fresh runs on this head schedule c-listTools (two agents, 8 of 8) and y-listTools (side coroutine, 16 of 16) before a-listTools, as main does; and the committed mcp-side-by-side-017d88a.json fails on eeb69d2 with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'c-listTools' does not match activity type of activity command 'a-listTools' and passes here. The non-blocking P2 is fixed: c re-listing [listFiles, newTool, bad.name] is refused with the server and the name and changes nothing, and its next listing, [listFiles, newTool], is accepted (done, listFiles@c, newTool@c); a 65-character name behaves the same, a later [listFiles] leaves no newTool behind, and with a second server the refused round leaves x@a as it was. The P3s are addressed: the upgrade bullet now has caught Strands-own refusals and a name listed twice, and last round's main histories of those runs fail just as it says (the single-server invalid-name runs that went on now replay); the README gives the toolFilters fix and limits the ownership rule to cacheTools: false servers; the Python reset advice covers runs that went on; and each new test case kills its mutant (hooks registered in reverse fail both new tests; skipping the removal, keying seen or own by the exact name, applying each listing as it arrives, or dropping the name rules or the taken check each fail the refusal test). The two reset sentences I suggested need one more correction each (inline). Earlier decisions stand: no gate, the name-is-the-server's rule, the hook order, the TypeScript refusal failing the Workflow Task as a follow-up, and the factory prefix bug left for its own issue.

Where the problems cluster: nothing blocks. Two of the four items are in the recovery sentences I suggested last round, one is a timing direction the committed history does not pin, and one is comment and API-surface cleanup.

Decision: approve, because round eight's blocking replay break and its non-blocking P2 are fixed, each verified by rerunning its original reproduction, CI is green, and what remains are non-blocking docs, test and cleanup points.

Comment thread typescript/strands-agents/README.md Outdated
});
```

Tool names must be unique on one agent, as in Strands: two tools may not have the same name, or names that differ only by `-` or `_`. Strands refuses such a name when the agent first lists its MCP servers. After each tool round, the agent re-lists its `cacheTools: false` servers, checks their new listings against each other and against its other tools, and then applies them together, so a name can move from one server to another. When a re-listed server starts listing a name that another tool of the agent has, such as a tool of another server or a tool in `tools`, or lists a name twice or one that Strands rejects, the listing throws Strands' `ToolValidationError` and leaves the agent's tools as they were. Like other errors thrown in workflow code, it fails the workflow task on every attempt, until the run is reset or terminated. To fix it, stop one server from listing the name, or drop the tool with the `toolFilters` of the `McpClient` that the server's factory returns (not its `prefix`). The refused listing's result is in the run's history, so then reset the run to before that listing. For a `cacheTools: false` server, a name is the server's from the listing that added its tool under it until a re-listing of that server drops the name: a tool you put under it is replaced at the next listing, and removed by the listing that drops the name. A `cacheTools: true` server is not listed again, so a tool you put under one of its names stays for the run.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (docs, non-blocking): the reset sentence I suggested last round can leave the run stuck again, because the refusal comes after the round's last listing, whichever server started listing the name. Each re-listing lands in its own workflow task, the last client's first, and apply() runs only in the first client's hook (temporal-mcp-client.ts:163,172); the error names the servers in tools order, so it does not say which one started listing the name. Probe with real McpClients over in-memory MCP servers: tools: [a, b], a lists [echo], b lists [other] and then [other, echo], the model calls other, and the uncaught refusal (MCP servers 'a' and 'b' both list it.) fails the workflow task. After restarting the worker with toolFilters: { rejected: ['echo'] } on b's factory McpClient, a reset to before the round's last listing, a's, which is also what temporal workflow reset --type LastWorkflowTask picks ('Resetting workflow … to event ID 37'), is refused again with the same message, because b's recorded listing comes before that point; a reset to before b's listing completes, with echo running on a. With tools: [b, a] and the filter on a instead, a reset to before b's listing (the refused server's, and the round's last) is refused again, and one to before a's completes. A reset to before the round's first listing completed in all four combinations, and the repeated workflow task failures did not get in the way of any reset. Suggested: 'The round's listings are in the run's history, and the agent checks them only after the last one, so then reset the run to before that tool round's first {name}-listTools activity, or, if you changed a cacheTools: true server, to before its only listing.' (The last clause is from the code: a cached server is listed once, when the agent first lists its servers.) For the same reason, 'fails to replay at that listing' in the upgrade bullet (line 401) should be 'fails to replay after that tool round's last listing'.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for checking this with real resets. Applied your sentence in 3e54d90: reset to before that tool round's first {name}-listTools activity, or, if you changed a cacheTools: true server, to before its only listing. The upgrade bullet now says the run "fails to replay after that tool round's last listing".

Comment thread python/strands_agents/README.md Outdated

Tool names must be unique on one agent. Two tools may not have the same name, or names that differ only by `-` or `_`: for example two servers that both list `search`, a server that lists a name twice, or a server tool named like a tool in `tools=[...]`, a `TemporalSandbox` tool or a tool a Signal handler adds while the servers list. `TemporalAgent` learns its MCP tools only when it lists them, so the model call after that listing raises `MCPToolNameConflictError`, a `ValueError` and a non-retryable `ApplicationError`: the first one, or, with `cache_tools=False`, a later one if a server starts listing such a name. It is raised again at every later model call while the duplicate lasts; between `cache_tools=True` listings, that is the rest of the run. This holds for an agent built before or after its clients listed. Give one `TemporalMCPClient` a different `prefix`, or drop the tool with its `tool_filters`. While a server lists a name, the name is the server's: a tool you put under it is replaced at the next model call, and a tool you remove comes back, also with `cache_tools=True`. A `structured_output_model` named like an MCP tool the agent already has gets Strands' own `ValueError` when the call starts, as in Strands.

The error fails the Workflow when it escapes the Workflow's run method or a Signal handler, with `StrandsPlugin` on the client or only on the Worker, because replay would raise it again. Escaping an Update handler, it fails only that Update, and the run stays open. Strands' `Swarm` records it as a failed node, and an agent used as a tool returns it as an error result, so neither fails the Workflow. If Workflow code catches it, or an Update failed, and calls the agent again, first remove the messages that Strands added to `agent.messages` during that call (the prompt, and any tool calls and results), as for any error during an agent call. A new `prefix` renames that server's tools, and new `tool_filters` can drop some, in every replay: an open run fails to replay if its model called a renamed or dropped tool, if its Workflow code acted on one among the agent's tools (for example on `'x' in agent.tool_names`), or if it met the error and went on, since the refused turn now proceeds. So deploy such a change with Worker Versioning. To recover a run that met the error, reset it to before the first listing that returned a tool the change renames or drops. A later reset point, such as just before the first refused listing, recovers it only if neither the model nor Workflow code used those tools before that point.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (docs, non-blocking): the later-reset sentence I suggested last round misses one condition: the run must not have met the error before that point. Last round's probe, on Python code that has not changed since: echo_a and echo_b both list echo; Workflow code catches the refusal, removes the turn's messages and calls the agent again, and is refused twice, without a model call. Replayed with tool_filters={"rejected": ["echo"]} on echo_b, the history cut before the Workflow Task that scheduled the second refused listing fails with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'temporalio.mcp.echo_a.list-tools' does not match activity type of activity command 'invoke_model', though neither the model nor Workflow code used echo before that point; cut before the first refused listing, it replays. Suggested: 'A later reset point, such as just before the first refused listing, recovers it only if the run had not met the error before that point and neither the model nor Workflow code used those tools before it.'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied your sentence in 3e54d90: a later reset point now recovers the run only if it had not met the error before that point and neither the model nor Workflow code used those tools before it.

}
});

test('a history of two agents side by side recorded on main still replays', async (t) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (tests, non-blocking): the committed history catches a re-listing scheduled sooner than on main, but not one scheduled later. With await null added at the top of listInRound (one microtask more per hook, which an added await or an async apply() would also cost), all 92 tests pass, but six of last round's histories recorded with main fail to replay. Five of them have an agent with tools: [a, b] and an AfterToolsEvent hook, added after construction, that on the first tool round starts a coroutine which runs one Activity (z-listTools), awaits null twice and runs another (y-listTools), with worker-side gates so that b's re-listing and z-listTools complete in one workflow task. Main schedules a-listTools first, and the mutant fails with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'a-listTools' does not match activity type of activity command 'y-listTools'. eeb69d2's shape, which scheduled them sooner, fails this test, as the body says. Committing one history of that shape as well, where main's re-listing comes first by one microtask, would pin main's timing from both sides.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 3e54d90. mcpAgentBesideCoroutine is your shape: an agent with tools: [a, b] and a hook, added after construction, that at the first tool round starts a coroutine that lists z, awaits null twice and lists y. mcp-beside-coroutine-017d88a.json was recorded on main with Worker gates so that b's re-listing and z-listTools complete in one workflow task, and main scheduled a-listTools before y-listTools. The main-history replay test now replays both histories. With await null at the top of listInRound, it fails on the new one with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'a-listTools' does not match activity type of activity command 'y-listTools'; at the head, all 92 tests pass.

if (!client.cacheTools) {
this.addHook(AfterToolsEvent, (event) => client.refreshTools(event.agent.toolRegistry));
}
// One hook per client, as each lists its server; the last of them checks

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 (cleanup, non-blocking): three comments describe the previous shape or say more than the code does, and the two @internal statics are public API. 'the last of them checks the round's listings together' (here) reads as the last client's hook, which starts the round; the check runs in the first client's hook, which Strands runs last (temporal-mcp-client.ts:163,172). Line 92's 'is that client's from then on' holds only until a re-listing of that client drops the name (temporal-mcp-client.ts:240-248). The refreshTools docstring's 're-lists its cacheTools: false clients together after each tool round instead' (temporal-mcp-client.ts:135-136) is left from the one-hook version; they are now listed one hook per client and checked and applied together. And with no stripInternal in this package's tsconfig, refreshHooks and holdAdded are emitted as public statics of the exported TemporalMCPClient (lib/temporal-mcp-client.d.ts), so a user can call holdAdded on an agent's registry and wrap its add a second time. "stripInternal": true in compilerOptions drops both from the declarations (checked: the build passes and refreshTools stays) without changing the emitted JavaScript.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3e54d90:

  • The hooks comment now says Strands runs them last to first, so the first client's hook runs last and checks and applies the round.
  • Line 92 now says a name is the client's until a re-listing of that client drops it.
  • The refreshTools docstring says TemporalAgent re-lists each cacheTools: false client in its own hook and checks and applies their listings together.
  • "stripInternal": true is in the package's tsconfig.json. refreshHooks and holdAdded are gone from lib/temporal-mcp-client.d.ts, and refreshTools stays.

… internal statics

- TypeScript README: after a refused re-listing, reset to before that tool
  round's first {name}-listTools activity, or before a changed cacheTools: true
  server's only listing, since the agent checks a round's listings only after
  the last one. The upgrade bullet says such a run fails to replay after that
  round's last listing.
- Python README: a later reset point also needs the run not to have met the
  error before it.
- The main-history replay test also replays mcp-beside-coroutine-017d88a.json,
  where main scheduled the re-listing of a before a coroutine's next activity,
  so a re-listing scheduled later than on main fails it too.
- The temporal-agent.ts comments and the refreshTools docstring describe the
  hooks per client, and stripInternal drops refreshHooks and holdAdded from
  the declarations.
@campoy

campoy commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the ninth round and the approval. The four points are in 3e54d90, with replies in the threads:

  • Reset advice: both READMEs take your sentences, and the TypeScript upgrade bullet now says "after that tool round's last listing".
  • Timing test: a second main history, where main schedules the re-listing before a coroutine's next activity, is replayed by the same test, so a re-listing scheduled later than on main fails it too.
  • Cleanup: the three comments match the code, and stripInternal drops the two @internal statics from the declarations.

@campoy
campoy merged commit 224d7cf into main Nov 3, 2026
35 checks passed
@campoy
campoy deleted the fix/strands-python-duplicate-mcp-tool-names branch November 3, 2026 19:02
campoy added a commit that referenced this pull request Nov 14, 2026
Take main's tool cancellation from #497, which replaces this branch's
change to activity and MCP tools. List a summarization agent's MCP tools
through the hook from #184. Move the blocking MCP tool and the
summarizer's MCP test to the temporalio.mcp API from #190.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants