Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend): pair copilot tool outputs by name+input, not name alone (#13372)

Abhimanyu Yadav843920750659
diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
index 4280b1d89f..ac5031f069 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
@@ -96,7 +96,11 @@ class SDKResponseAdapter:
# so the empty-completion guard doesn't false-fire on a benign empty
# trailing ResultMessage when the prior attempt already streamed content.
self.prior_attempt_emitted_visible_content = False
- self.current_tool_calls: dict[str, dict[str, str]] = {}
+ # Maps tool_use_id → {"name": <tool name>, "input": <call args>}.
+ # ``input`` is carried so the response adapter can pop the matching
+ # stashed output via ``_output_key`` when several same-name tools run
+ # in parallel (OPEN-3158).
+ self.current_tool_calls: dict[str, dict[str, Any]] = {}
self.resolved_tool_calls: set[str] = set()
self.step_open = False
# Track whether any ``TextBlock`` was emitted after the most recent
@@ -362,7 +366,10 @@ class SDKResponseAdapter:
input=block.input,
)
)
- self.current_tool_calls[block.id] = {"name": tool_name}
+ self.current_tool_calls[block.id] = {
+ "name": tool_name,
+ "input": block.input,
+ }
elif isinstance(sdk_message, UserMessage):
# UserMessage carries tool results back from tool execution.
@@ -395,9 +402,9 @@ class SDKResponseAdapter:
# (potentially truncated) ToolResultBlock content.
# The SDK truncates large results, writing them to disk,
# which breaks frontend widget parsing.
- output = pop_pending_tool_output(tool_name) or (
- _extract_tool_output(block.content)
- )
+ output = pop_pending_tool_output(
+ tool_name, tool_info.get("input")
+ ) or (_extract_tool_output(block.content))
responses.append(
StreamToolOutputAvailable(
@@ -422,7 +429,7 @@ class SDKResponseAdapter:
# Try stashed output first (from PostToolUse hook),
# then tool_use_result dict, then string content.
- output = pop_pending_tool_output(tool_name)
+ output = pop_pending_tool_output(tool_name, tool_info.get("input"))
if not output:
tur = sdk_message.tool_use_result
if tur is not None:
@@ -1005,7 +1012,7 @@ class SDKResponseAdapter:
flips to ``False`` after the first invocation.
"""
unresolved = [
- (tid, info.get("name", "unknown"))
+ (tid, info.get("name", "unknown"), info.get("input"))
for tid, info in self.current_tool_calls.items()
if tid not in self.resolved_tool_calls
]
@@ -1021,13 +1028,13 @@ class SDKResponseAdapter:
"[SDK] [%s] Flushing %d unresolved tool call(s): %s",
sid,
len(unresolved),
- ", ".join(f"{name}({tid[:12]})" for tid, name in unresolved),
+ ", ".join(f"{name}({tid[:12]})" for tid, name, _ in unresolved),
)
self._any_orphan_flush_seen = True
flushed = False
- for tool_id, tool_name in unresolved:
- output = pop_pending_tool_output(tool_name)
+ for tool_id, tool_name, tool_input in unresolved:
+ output = pop_pending_tool_output(tool_name, tool_input)
if output is not None:
responses.append(
StreamToolOutputAvailable(
diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
index a1e8a07b07..2eb1b7a608 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
@@ -1260,9 +1260,9 @@ def test_flush_with_stashed_output():
"""Stashed output from PostToolUse hook is used when flushing."""
adapter = _adapter()
- # Simulate PostToolUse hook stashing output
+ # Simulate PostToolUse hook stashing output (keyed by tool name + input).
_pto.set({})
- _stash("WebSearch", "Search result: 5 items found")
+ _stash("WebSearch", "Search result: 5 items found", {"query": "test"})
all_responses: list[StreamBaseResponse] = []
@@ -1301,6 +1301,65 @@ def test_flush_with_stashed_output():
_pto.set({}) # type: ignore[arg-type]
+def test_parallel_same_tool_outputs_not_swapped():
+ """OPEN-3158: two parallel calls to the SAME tool must keep each call's
+ output attached to its OWN tool_call_id.
+
+ The outputs are stashed in COMPLETION order (call B finishes first here)
+ but the tool_result blocks arrive in CALL order (A then B). A name-only
+ stash key would hand call A the next-oldest output (B's) and vice-versa,
+ swapping the two search-result cards in the UI. Keying the stash by
+ (tool_name + input) keeps the pairing correct.
+ """
+ adapter = _adapter()
+ _pto.set({})
+
+ # Two parallel web_search calls with DIFFERENT queries.
+ adapter.convert_message(
+ AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id="call-a",
+ name=f"{MCP_TOOL_PREFIX}web_search",
+ input={"query": "alpha"},
+ ),
+ ToolUseBlock(
+ id="call-b",
+ name=f"{MCP_TOOL_PREFIX}web_search",
+ input={"query": "beta"},
+ ),
+ ],
+ model="test",
+ )
+ )
+
+ # Outputs stashed in COMPLETION order: B finishes before A. Stripped of
+ # the MCP prefix exactly as the truncating wrapper stashes them.
+ _stash("web_search", "results for beta", {"query": "beta"})
+ _stash("web_search", "results for alpha", {"query": "alpha"})
+
+ # Tool results arrive in CALL order (A then B).
+ results = adapter.convert_message(
+ UserMessage(
+ content=[
+ ToolResultBlock(tool_use_id="call-a", content="truncated-a"),
+ ToolResultBlock(tool_use_id="call-b", content="truncated-b"),
+ ]
+ )
+ )
+
+ outputs = {
+ r.toolCallId: r.output
+ for r in results
+ if isinstance(r, StreamToolOutputAvailable)
+ }
+ assert outputs["call-a"] == "results for alpha"
+ assert outputs["call-b"] == "results for beta"
+
+ # Cleanup
+ _pto.set({}) # type: ignore[arg-type]
+
+
# -- wait_for_stash synchronisation tests --
@@ -2136,7 +2195,7 @@ def test_real_tool_result_flag_set_by_stashed_flush():
# Initialise the stash ContextVar (normally done by set_execution_context).
_pto.set({})
# Simulate PostToolUse hook stashing real output for a built-in tool.
- _stash("ReadFile", "file content here")
+ _stash("ReadFile", "file content here", {"path": "/x"})
adapter.convert_message(
AssistantMessage(
content=[ToolUseBlock(id="t-real", name="ReadFile", input={"path": "/x"})],
diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
index 94e9f00ffb..c855167a15 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
@@ -327,7 +327,11 @@ def create_security_hooks(
len(str(tool_response)),
resp_preview,
)
- stash_pending_tool_output(tool_name, tool_response)
+ # Key by the call's input so the response adapter pops the
+ # output for the RIGHT tool_call_id when the model fired
+ # several same-name calls in parallel (OPEN-3158).
+ tool_input = input_data.get("tool_input")
+ stash_pending_tool_output(tool_name, tool_response, tool_input)
else:
logger.warning(
"[SDK] PostToolUse for builtin %s but tool_response is None",
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
index b622610303..cc9915003f 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
@@ -94,8 +94,9 @@ _STRIP_FROM_LLM: frozenset[str] = frozenset(["is_dry_run"])
# Stash for MCP tool outputs before the SDK potentially truncates them.
-# Keyed by tool_name → full output string. Consumed (popped) by the
-# response adapter when it builds StreamToolOutputAvailable.
+# Keyed by a (tool_name + canonical input) composite — see ``_output_key`` —
+# → FIFO of full output strings. Consumed (popped) by the response adapter
+# when it builds StreamToolOutputAvailable.
_pending_tool_outputs: ContextVar[dict[str, list[str]]] = ContextVar(
"pending_tool_outputs",
default=None, # type: ignore[arg-type]
@@ -176,10 +177,11 @@ def reset_tool_failure_counters() -> None:
def reset_pending_tool_outputs() -> None:
"""Drop stashed tool outputs left over from a previous stream attempt.
- The stash is a FIFO keyed by tool *name*, not tool_call_id. A rolled-back
- attempt that executed tools but never consumed their results leaves
- orphaned entries, so on the retry every ``pop_pending_tool_output`` for
- that tool name returns the stale first-attempt output — shifting all
+ The stash is a per-call FIFO (see ``_output_key``), not keyed by
+ tool_call_id. A rolled-back attempt that executed tools but never consumed
+ their results leaves orphaned entries, so on the retry every
+ ``pop_pending_tool_output`` for that key returns the stale first-attempt
+ output — shifting all
subsequent pops off-by-one and attaching wrong payloads to the frontend's
``StreamToolOutputAvailable`` events (e.g. a ``setup_requirements`` card
silently replaced by an older result). Called at the top of each retry
@@ -188,41 +190,73 @@ def reset_pending_tool_outputs() -> None:
_pending_tool_outputs.set({})
-def pop_pending_tool_output(tool_name: str) -> str | None:
- """Pop and return the oldest stashed output for *tool_name*.
+def _output_key(tool_name: str, tool_input: Any = None) -> str:
+ """Build the stash key correlating a tool call to its output.
+
+ Tool *name* alone is insufficient (OPEN-3158): the model can issue two
+ parallel calls to the same tool in one turn (e.g. two ``web_search``
+ queries). Their outputs are stashed in completion order but consumed in
+ tool-result order — with a name-only key those orders diverge and the
+ outputs attach to the wrong ``tool_call_id``, swapping the two cards in
+ the UI. Including a canonical serialization of the call's input
+ disambiguates the common case where the two calls differ.
+
+ The in-process MCP handler never sees the SDK ``tool_use_id`` (only the
+ arguments), so the input is the most specific key available on the stash
+ side. Empty/falsy input falls back to the name-only key: such calls
+ can't be disambiguated, and two identical calls produce interchangeable
+ outputs so a swap between them is not user-visible.
+ """
+ if not tool_input:
+ return tool_name
+ try:
+ canonical = json.dumps(tool_input, sort_keys=True, default=str)
+ except (TypeError, ValueError):
+ canonical = str(tool_input)
+ return f"{tool_name}\x00{canonical}"
+
+
+def pop_pending_tool_output(tool_name: str, tool_input: Any = None) -> str | None:
+ """Pop and return the oldest stashed output for a tool call.
The SDK CLI may truncate large tool results (writing them to disk and
replacing the content with a file reference). This stash keeps the
original MCP output so the response adapter can forward it to the
frontend for proper widget rendering.
- Uses a FIFO queue per tool name so duplicate calls to the same tool
- in one turn each get their own output.
+ Matched by ``_output_key(tool_name, tool_input)`` so parallel calls to
+ the same tool with different inputs each get their own output instead of
+ being swapped. Falls back to a FIFO queue when several calls share the
+ same key.
- Returns ``None`` if nothing was stashed for *tool_name*.
+ Returns ``None`` if nothing was stashed for this call.
"""
pending = _pending_tool_outputs.get(None)
if pending is None:
return None
- queue = pending.get(tool_name)
+ key = _output_key(tool_name, tool_input)
+ queue = pending.get(key)
if not queue:
- pending.pop(tool_name, None)
+ pending.pop(key, None)
return None
value = queue.pop(0)
if not queue:
- del pending[tool_name]
+ del pending[key]
return value
-def stash_pending_tool_output(tool_name: str, output: Any) -> None:
+def stash_pending_tool_output(
+ tool_name: str, output: Any, tool_input: Any = None
+) -> None:
"""Stash tool output for later retrieval by the response adapter.
- Used by the PostToolUse hook to capture SDK built-in tool outputs
- (WebSearch, Read, etc.) that aren't available through the MCP stash
- mechanism in ``_execute_tool_sync``.
+ Used by the MCP truncating wrapper and the PostToolUse hook (for SDK
+ built-in tools like WebSearch/Read that aren't available through the MCP
+ stash mechanism in ``_execute_tool_sync``).
- Appends to a FIFO queue per tool name so multiple calls to the same
- tool in one turn are all preserved.
+ Keyed by ``_output_key(tool_name, tool_input)`` so the response adapter
+ can pop the output belonging to a *specific* tool call rather than the
+ next one for that tool name — see ``_output_key`` for why this matters.
"""
pending = _pending_tool_outputs.get(None)
if pending is None:
@@ -234,7 +268,7 @@ def stash_pending_tool_output(tool_name: str, output: Any) -> None:
text = json.dumps(output)
except (TypeError, ValueError):
text = str(output)
- pending.setdefault(tool_name, []).append(text)
+ pending.setdefault(_output_key(tool_name, tool_input), []).append(text)
# Signal any waiters that new output is available.
event = _stash_event.get(None)
if event is not None:
@@ -770,7 +804,10 @@ def _make_truncating_wrapper(
if not truncated.get("isError"):
text = _text_from_mcp_result(truncated)
if text:
- stash_pending_tool_output(tool_name, text)
+ # Key by the model's ORIGINAL args (pre file-ref expansion) so
+ # it matches the ToolUseBlock.input the response adapter pops
+ # with — see ``_output_key`` (OPEN-3158).
+ stash_pending_tool_output(tool_name, text, original_args)
# Strip is_dry_run only when the session itself is in dry_run mode.
# In that case the LLM must not know it is simulating — it should act
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py
index a432f8c032..fe29e146f4 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py
@@ -138,6 +138,26 @@ class TestToolOutputStash:
assert pop_pending_tool_output("b") == "beta"
assert pop_pending_tool_output("a") == "alpha"
+ def test_same_tool_different_input_not_swapped(self):
+ """OPEN-3158: parallel calls to the same tool with different inputs
+ keep their own output regardless of stash vs pop order."""
+ # Stashed in completion order (beta first), popped in call order.
+ stash_pending_tool_output("web_search", "beta-out", {"query": "beta"})
+ stash_pending_tool_output("web_search", "alpha-out", {"query": "alpha"})
+ assert pop_pending_tool_output("web_search", {"query": "alpha"}) == "alpha-out"
+ assert pop_pending_tool_output("web_search", {"query": "beta"}) == "beta-out"
+
+ def test_same_input_key_order_insensitive(self):
+ """Dict key ordering must not change the composite key."""
+ stash_pending_tool_output("t", "out", {"a": 1, "b": 2})
+ assert pop_pending_tool_output("t", {"b": 2, "a": 1}) == "out"
+
+ def test_empty_input_falls_back_to_name_key(self):
+ """Falsy input uses the name-only key, so a name-only pop still finds
+ it (back-compat for tools called with no meaningful args)."""
+ stash_pending_tool_output("t", "out", {})
+ assert pop_pending_tool_output("t") == "out"
+
def test_reset_pending_tool_outputs_drops_orphans(self):
"""A retry attempt must not inherit stashed outputs from a rolled-back
attempt — orphaned entries shift the name-keyed FIFO off-by-one and