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/copilot): run a tool reached by capability id through the normal tool path (#14714)

Reinier van der Leer7d283b0785b2
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index 1709d2a2ac..3a1a6b6e9e 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -45,6 +45,7 @@ from backend.copilot.builder_context import (
build_builder_context_turn_prefix,
build_builder_system_prompt_suffix,
)
+from backend.copilot.capabilities.dispatch import resolve_tool_dispatch
from backend.copilot.config import CopilotLlmAuthProvider, CopilotLLMModel
from backend.copilot.context import get_workspace_manager, set_execution_context
from backend.copilot.expert_context import build_expert_identity_suffix
@@ -1152,32 +1153,27 @@ async def _baseline_tool_executor(
)
)
+ # A dispatch of a platform tool IS a call to that tool, so everything below
+ # names the tool that runs rather than the dispatcher it arrived through.
+ # ``execute_tool`` still gets the call the model made: refusing a deferred
+ # tool named directly is a judgement about that call, not this one.
+ called_name, called_args = tool_name, tool_args
+ if dispatch := resolve_tool_dispatch(tool_name, tool_args):
+ called_name, called_args = dispatch.name, dispatch.args
+
_emit(
state,
- StreamToolInputStart(toolCallId=tool_call_id, toolName=tool_name),
+ StreamToolInputStart(toolCallId=tool_call_id, toolName=called_name),
)
_emit(
state,
StreamToolInputAvailable(
toolCallId=tool_call_id,
- toolName=tool_name,
- input=tool_args,
+ toolName=called_name,
+ input=called_args,
),
)
- # Announce the tool call to the session so in-turn guards like
- # ``require_guide_read`` can see it *right now*, before the tool
- # actually runs. Without this, the tool_call row lives only in
- # ``state.session_messages`` until the ``finally`` block flushes it
- # into ``session.messages`` at turn end — so a second tool in the
- # same turn (e.g. ``create_agent`` after ``get_agent_building_guide``)
- # scans a stale ``session.messages`` and the guard re-fires despite
- # the guide having been called. The announce-set is cleared at turn
- # end; we deliberately don't touch ``session.messages`` here to avoid
- # duplicating the assistant row that ``_baseline_conversation_updater``
- # persists at turn end.
- session.announce_inflight_tool_call(tool_name, tool_args)
-
def on_display_name(name: str) -> None:
state.tool_persistence.set_display_name(tool_call_id, name)
_emit(
@@ -1206,7 +1202,7 @@ async def _baseline_tool_executor(
return state.tool_persistence.record_result(
ToolCallResult(
tool_call_id=tool_call_id,
- tool_name=tool_name,
+ tool_name=called_name,
content=tool_output,
)
)
@@ -1214,7 +1210,7 @@ async def _baseline_tool_executor(
error_output = f"Tool execution error: {e}"
logger.error(
"[Baseline] Tool %s failed: %s",
- tool_name,
+ called_name,
error_output,
exc_info=True,
)
@@ -1222,7 +1218,7 @@ async def _baseline_tool_executor(
state,
StreamToolOutputAvailable(
toolCallId=tool_call_id,
- toolName=tool_name,
+ toolName=called_name,
output=error_output,
success=False,
),
@@ -1230,7 +1226,7 @@ async def _baseline_tool_executor(
return state.tool_persistence.record_result(
ToolCallResult(
tool_call_id=tool_call_id,
- tool_name=tool_name,
+ tool_name=called_name,
content=error_output,
is_error=True,
)
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/dispatch.py b/autogpt_platform/backend/backend/copilot/capabilities/dispatch.py
new file mode 100644
index 0000000000..4e2bcdce5d
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/capabilities/dispatch.py
@@ -0,0 +1,60 @@
+"""Resolve a ``run_capability`` dispatch into the tool call it is.
+
+Deferred tools are absent from the model's tool list and reached by id
+(#14569), so every engine sees the dispatcher's name where the tool's should
+be. Each engine resolves the call here and then runs the inner tool through
+its normal path, so the announce, the history row, the permission gate, the
+circuit breaker and the frontend events all name the tool that ran.
+"""
+
+import logging
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, NamedTuple
+
+from backend.copilot.capabilities.registry import configured_tool, get_registry
+from backend.copilot.capabilities.resolve import resolve_entry
+
+if TYPE_CHECKING:
+ from backend.copilot.tools.base import BaseTool
+
+logger = logging.getLogger(__name__)
+
+DISPATCHER_TOOL_NAME = "run_capability"
+
+
+class DispatchedToolCall(NamedTuple):
+ tool: "BaseTool"
+ name: str
+ args: dict[str, Any]
+
+
+def resolve_tool_dispatch(
+ tool_name: str, args: Mapping[str, Any] | None
+) -> DispatchedToolCall | None:
+ """The platform tool a ``run_capability`` call runs, or None when the call
+ is not one — another tool, a block or MCP id, or ``validate_only``.
+
+ Never raises: it runs on the streaming path, where a bad id must degrade to
+ the dispatcher's own "unknown capability" answer rather than break the turn.
+ """
+ if tool_name != DISPATCHER_TOOL_NAME or not isinstance(args, Mapping):
+ return None
+ if args.get("validate_only"):
+ return None
+ try:
+ entry = resolve_entry(get_registry(), str(args.get("id") or ""))
+ if entry is None or entry.kind != "tool" or not entry.implementations:
+ return None
+ name = entry.implementations[0].ref
+ tool = configured_tool(name)
+ except Exception:
+ logger.warning("Could not resolve capability dispatch", exc_info=True)
+ return None
+ if tool is None:
+ return None
+ payload = args.get("input")
+ if payload is not None and not isinstance(payload, Mapping):
+ # Coercing it to {} would run the tool on its defaults; the dispatcher
+ # owns the "input must be an object" answer, so leave the call to it.
+ return None
+ return DispatchedToolCall(tool, name, dict(payload or {}))
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/dispatch_test.py b/autogpt_platform/backend/backend/copilot/capabilities/dispatch_test.py
new file mode 100644
index 0000000000..c35bd4fe72
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/capabilities/dispatch_test.py
@@ -0,0 +1,343 @@
+"""A dispatched tool call takes the path a direct tool call takes.
+
+Deferred tools are reached as ``run_capability(id="tool:<name>")`` (#14569).
+Each engine resolves that back into a call to the tool itself, so the tests
+below drive a real dispatch through each engine's executor and assert that
+what it records — the announce, the emitted events, the persisted row, the
+failure count — names the tool that ran, never the dispatcher.
+"""
+
+import json
+from unittest.mock import patch
+
+import pytest
+
+from backend.copilot.baseline.service import (
+ _baseline_tool_executor,
+ _BaselineStreamState,
+)
+from backend.copilot.capabilities.dispatch import resolve_tool_dispatch
+from backend.copilot.model import ChatSession
+from backend.copilot.permissions import ALL_TOOL_NAMES, CopilotPermissions
+from backend.copilot.response_model import (
+ StreamToolInputAvailable,
+ StreamToolOutputAvailable,
+)
+from backend.copilot.sdk.tool_adapter import (
+ _check_circuit_breaker,
+ _make_truncating_wrapper,
+ _text_from_mcp_result,
+ pop_pending_tool_output,
+ reset_pending_tool_outputs,
+ reset_tool_failure_counters,
+ set_execution_context,
+)
+from backend.copilot.tools import execute_tool
+from backend.copilot.tools.base import BaseTool
+from backend.copilot.tools.models import ErrorResponse
+from backend.util.tool_call_loop import LLMToolCall
+
+# A real deferred tool, so ``resolve_entry`` finds a real registry entry; its
+# implementation is stubbed because only the bookkeeping around it is on trial.
+INNER = "list_schedules"
+ARGS = {"x": "1"}
+USER = "user-dispatch"
+
+
+class _StubTool(BaseTool):
+ """A real BaseTool, so ``execute``'s own bookkeeping runs for real."""
+
+ def __init__(self, name: str, fails: bool = False) -> None:
+ self._name = name
+ self._fails = fails
+ self.seen: dict | None = None
+
+ @property
+ def name(self) -> str:
+ return self._name
+
+ @property
+ def description(self) -> str:
+ return "stub"
+
+ @property
+ def parameters(self) -> dict:
+ return {"type": "object", "properties": {"x": {"type": "string"}}}
+
+ async def _execute(self, user_id, session, **kwargs):
+ self.seen = kwargs
+ return ErrorResponse(
+ message="boom" if self._fails else "ran", session_id=session.session_id
+ )
+
+
+def _dispatch_of(tool: BaseTool):
+ """Patch the resolver's tool lookup so the dispatch lands on *tool*."""
+ return patch(
+ "backend.copilot.capabilities.dispatch.configured_tool", return_value=tool
+ )
+
+
+# ------------------------------------------------------------ the resolver
+
+
+def test_resolver_yields_the_inner_call():
+ for capability_id in (f"tool:{INNER}", INNER):
+ call = resolve_tool_dispatch(
+ "run_capability", {"id": capability_id, "input": ARGS}
+ )
+ assert call is not None and call.name == INNER
+ assert call.args == ARGS
+
+
+ "tool_name,args",
+ [
+ # validate_only describes the call; it must not run the tool.
+ ("run_capability", {"id": f"tool:{INNER}", "input": {}, "validate_only": True}),
+ ("run_capability", {"id": "block:1234", "input": {}}),
+ ("run_capability", {"id": "https://mcp.example/sse", "input": {}}),
+ ("run_capability", {"id": "", "input": {}}),
+ ("run_capability", {"id": 42}),
+ ("run_capability", None),
+ ("find_capability", {"query": "schedules"}),
+ ],
+)
+def test_resolver_leaves_everything_else_alone(tool_name, args):
+ assert resolve_tool_dispatch(tool_name, args) is None
+
+
[email protected]("payload", ["a string", [1, 2], 42, True])
+def test_resolver_refuses_an_input_that_is_not_an_object(payload):
+ """Coercing a malformed ``input`` to ``{}`` would run the tool on its
+ defaults, and disagree with the dispatcher, which answers "input must be an
+ object" for the same call. Declining here routes it back to that answer."""
+ assert (
+ resolve_tool_dispatch(
+ "run_capability", {"id": f"tool:{INNER}", "input": payload}
+ )
+ is None
+ )
+
+
+ "args", [{"id": f"tool:{INNER}", "input": {}}, {"id": f"tool:{INNER}"}]
+)
+def test_resolver_runs_on_defaults_when_input_is_empty_or_absent(args):
+ """An absent or empty ``input`` is a legitimate "run with defaults"."""
+ call = resolve_tool_dispatch("run_capability", args)
+ assert call is not None and call.name == INNER and call.args == {}
+
+
+# ------------------------------------------------------- the baseline engine
+
+
+async def test_baseline_dispatch_is_recorded_as_the_inner_call():
+ session = ChatSession.new(USER, dry_run=False)
+ state = _BaselineStreamState()
+ tool = _StubTool(INNER)
+
+ with _dispatch_of(tool):
+ await _baseline_tool_executor(
+ LLMToolCall(
+ id="call-1",
+ name="run_capability",
+ arguments=json.dumps({"id": f"tool:{INNER}", "input": ARGS}),
+ ),
+ tools=[],
+ state=state,
+ user_id=USER,
+ session=session,
+ disabled_groups=[],
+ disabled_tools=frozenset(),
+ )
+
+ assert tool.seen == ARGS
+ # The announce a same-turn gate reads.
+ assert session.has_tool_been_called(INNER) is True
+ assert session.get_inflight_tool_call_args(INNER) == [ARGS]
+ # The row that lands in history, and the result event the frontend keys on.
+ recorded = list(state.tool_persistence.results.values())
+ assert [r.tool_name for r in recorded] == [INNER]
+ events = state.emitted_events
+ inputs = [e for e in events if isinstance(e, StreamToolInputAvailable)]
+ assert [(e.toolName, e.input) for e in inputs] == [(INNER, ARGS)]
+ outputs = [e for e in events if isinstance(e, StreamToolOutputAvailable)]
+ assert [e.toolName for e in outputs] == [INNER]
+
+
+async def test_baseline_answers_a_malformed_input_without_running_anything():
+ """What the model sees for a malformed ``input``: the dispatcher's own
+ validation error, under the dispatcher's name, and the target untouched."""
+ session = ChatSession.new(USER, dry_run=False)
+ state = _BaselineStreamState()
+ tool = _StubTool(INNER)
+
+ with _dispatch_of(tool):
+ await _baseline_tool_executor(
+ LLMToolCall(
+ id="call-3",
+ name="run_capability",
+ arguments=json.dumps({"id": f"tool:{INNER}", "input": "a string"}),
+ ),
+ tools=[],
+ state=state,
+ user_id=USER,
+ session=session,
+ disabled_groups=[],
+ disabled_tools=frozenset(),
+ )
+
+ assert tool.seen is None
+ assert session.has_tool_been_called(INNER) is False
+ outputs = [
+ e for e in state.emitted_events if isinstance(e, StreamToolOutputAvailable)
+ ]
+ assert [e.toolName for e in outputs] == ["run_capability"]
+ assert "input must be an object" in str(outputs[0].output)
+
+
+async def test_baseline_still_refuses_a_deferred_tool_named_directly():
+ """The dispatch resolves after that refusal, so naming a deferred tool
+ outright stays refused — it is the one way to reach one unguarded."""
+ result = await execute_tool(
+ tool_name=INNER,
+ parameters={},
+ user_id=USER,
+ session=ChatSession.new(USER, dry_run=False),
+ tool_call_id="call-2",
+ disabled_groups=[],
+ disabled_tools=frozenset(),
+ )
+ assert result.success is False
+ assert "not available in this session" in result.output
+
+
+# ------------------------------------------------------------ the SDK engine
+
+
+def _sdk_context():
+ session = ChatSession.new(USER, dry_run=False)
+ set_execution_context(USER, session)
+ reset_pending_tool_outputs()
+ reset_tool_failure_counters()
+ yield session
+ set_execution_context(None, None)
+
+
+async def _never(args):
+ raise AssertionError("the dispatcher's own handler must not run")
+
+
+async def test_sdk_dispatch_is_recorded_as_the_inner_call(_sdk_context):
+ session = _sdk_context
+ tool = _StubTool(INNER)
+ wrapper = _make_truncating_wrapper(
+ _never,
+ "run_capability",
+ input_schema={"type": "object", "properties": {"id": {}}},
+ required_args=["id", "input"],
+ )
+
+ with _dispatch_of(tool):
+ result = await wrapper({"id": f"tool:{INNER}", "input": ARGS})
+
+ assert result.get("isError") is not True
+ assert tool.seen == ARGS
+ # The announce a same-turn gate reads.
+ assert session.has_tool_been_called(INNER) is True
+ assert session.get_inflight_tool_call_args(INNER) == [ARGS]
+ # The output the response adapter pops is keyed by the inner call, so a
+ # key written under the dispatcher would silently lose the payload.
+ assert pop_pending_tool_output(INNER, ARGS) is not None
+
+
+async def test_sdk_dispatch_failure_counts_against_the_inner_tool(_sdk_context):
+ """One dispatcher key per engine would let a failing tool alternate with a
+ healthy one forever without ever tripping the breaker."""
+ tool = _StubTool(INNER, fails=True)
+ wrapper = _make_truncating_wrapper(_never, "run_capability", required_args=["id"])
+
+ with _dispatch_of(tool), patch(
+ "backend.copilot.sdk.tool_adapter.truncate",
+ side_effect=lambda r, _: {**r, "isError": True},
+ ):
+ for _ in range(3):
+ await wrapper({"id": f"tool:{INNER}", "input": ARGS})
+
+ assert _check_circuit_breaker("run_capability", {"id": f"tool:{INNER}"}) is None
+ stop = _check_circuit_breaker(INNER, ARGS)
+ assert stop is not None and f"Tool '{INNER}'" in stop
+
+
+async def test_sdk_history_row_names_the_inner_call():
+ """The persisted assistant row comes from the response adapter, not the
+ tool handler, so it has to resolve the dispatch too or the gates read
+ ``run_capability`` out of history for the rest of the session."""
+ from claude_agent_sdk import AssistantMessage, ToolUseBlock
+
+ from backend.copilot.sdk.response_adapter import SDKResponseAdapter
+
+ adapter = SDKResponseAdapter(session_id="s-1")
+ message = AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id="tu-1",
+ name="mcp__copilot__run_capability",
+ input={"id": f"tool:{INNER}", "input": ARGS},
+ )
+ ],
+ model="claude-opus-5",
+ )
+
+ with _dispatch_of(_StubTool(INNER)):
+ responses = adapter.convert_message(message)
+
+ rows = [r for r in responses if isinstance(r, StreamToolInputAvailable)]
+ assert [(r.toolName, r.input) for r in rows] == [(INNER, ARGS)]
+
+
+async def test_a_whitelist_grants_the_dispatcher_but_not_every_tool(_sdk_context):
+ """Allowing a deferred tool implies ``run_capability``, so the dispatcher is
+ reachable whenever any deferred tool is allowed. Denial then rests entirely
+ on gating the RESOLVED tool: without that, one whitelisted tool would open
+ every other one through the same dispatcher."""
+ session = _sdk_context
+ permissions = CopilotPermissions(tools=[INNER], tools_exclude=False)
+ set_execution_context(USER, session, permissions=permissions)
+ assert "run_capability" in permissions.effective_allowed_tools(ALL_TOOL_NAMES)
+
+ denied = _StubTool("hire_expert")
+ wrapper = _make_truncating_wrapper(_never, "run_capability", required_args=["id"])
+ with _dispatch_of(denied):
+ result = await wrapper({"id": "tool:hire_expert", "input": {}})
+
+ assert result.get("isError") is True
+ assert "tool_disabled" in _text_from_mcp_result(result)
+ assert denied.seen is None
+ assert session.has_tool_been_called("hire_expert") is False
+
+
+async def test_sdk_leaves_a_non_dispatch_call_alone(_sdk_context):
+ """The wrapper's own tool keeps its name, args and handler."""
+ seen = {}
+
+ async def handler(args):
+ seen.update(args)
+ return {"content": [{"type": "text", "text": "ok"}], "isError": False}
+
+ wrapper = _make_truncating_wrapper(handler, "find_capability", required_args=["q"])
+ result = await wrapper({"q": "schedules"})
+
+ assert seen == {"q": "schedules"}
+ assert result.get("isError") is not True
+ assert pop_pending_tool_output("find_capability", {"q": "schedules"}) is not None
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/sources/static_tools.py b/autogpt_platform/backend/backend/copilot/capabilities/sources/static_tools.py
index 5567b4822b..e60aa1ce24 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/sources/static_tools.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/sources/static_tools.py
@@ -43,6 +43,10 @@ EAGER_CORE: frozenset[str] = frozenset(
# and a deferred tool named directly is refused. Eager, the screen
# goes on in one call instead of a find/run round trip every turn.
"start_desktop",
+ # The refusal the building gate prints tells the model to call
+ # ``enter_agent_building_mode``, which a deferred tool named directly
+ # refuses — the same bind ``start_desktop`` was in.
+ "enter_agent_building_mode",
# ``kickoff_turn_disabled_tools`` narrows a hire's first turn to this
# one tool. Deferred, that gate leaves the turn with no tools at all:
# the card it exists to open is unreachable, and so is the
diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.py
index b761c1db2a..db2d9971f8 100644
--- a/autogpt_platform/backend/backend/copilot/model.py
+++ b/autogpt_platform/backend/backend/copilot/model.py
@@ -546,8 +546,9 @@ class ChatSession(ChatSessionInfo):
) -> None:
"""Record that *tool_name* is being dispatched in the current turn.
- Called by the baseline tool executor **before** the tool actually
- runs (the announcement is about dispatch, not success). If the
+ Called by :meth:`BaseTool.execute` — the one path both engines take —
+ after its gates and **before** the tool actually runs (the
+ announcement is about dispatch, not success). If the
tool raises, the name stays in the buffer for the rest of the
turn — that matches the guide-read gate's contract ("was the tool
called?") but means any future gate wanting *successful*
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index 074ca64948..e985bed2c8 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -348,10 +348,24 @@ _IMPLIED_GRANTS: dict[str, tuple[str, ...]] = {
def _with_implied_grants(allowed: frozenset[str]) -> frozenset[str]:
- """Expand an allow set with the tools its entries imply."""
- return allowed.union(
+ """Expand an allow set with the tools its entries imply.
+
+ A deferred tool is no longer handed to the model, so allowing it without
+ ``run_capability`` allows nothing: the dispatcher is the only way in.
+ """
+ grants = allowed.union(
implied for name in allowed for implied in _IMPLIED_GRANTS.get(name, ())
)
+ if grants & _deferred_tool_names():
+ grants = grants | {"run_capability"}
+ return grants
+
+
+def _deferred_tool_names() -> frozenset[str]:
+ """The registry's deferred set, imported late (heavy tool imports)."""
+ from backend.copilot.tools import DEFERRED_TOOL_NAMES # noqa: PLC0415
+
+ return DEFERRED_TOOL_NAMES
# ---------------------------------------------------------------------------
diff --git a/autogpt_platform/backend/backend/copilot/permissions_aliases_test.py b/autogpt_platform/backend/backend/copilot/permissions_aliases_test.py
index f6d48828f3..9387c77242 100644
--- a/autogpt_platform/backend/backend/copilot/permissions_aliases_test.py
+++ b/autogpt_platform/backend/backend/copilot/permissions_aliases_test.py
@@ -66,3 +66,23 @@ def test_legacy_names_validate():
def test_denied_tool_names_empty_without_filter():
assert denied_tool_names(None) == frozenset()
assert denied_tool_names(CopilotPermissions()) == frozenset()
+
+
+def test_allowing_a_deferred_tool_grants_the_dispatcher():
+ """A deferred tool is not in the model's tool list (#14569), so a list
+ naming one and not ``run_capability`` hands the model no way to reach it."""
+ from backend.copilot.tools import DEFERRED_TOOL_NAMES
+
+ for name in ("list_schedules", "hire_expert", "memory_store"):
+ assert name in DEFERRED_TOOL_NAMES
+ allowed = CopilotPermissions(
+ tools=[name], tools_exclude=False
+ ).effective_allowed_tools(ALL_TOOL_NAMES)
+ assert {name, "run_capability"} <= allowed
+
+
+def test_allowing_an_eager_tool_does_not_grant_the_dispatcher():
+ allowed = CopilotPermissions(
+ tools=["web_fetch"], tools_exclude=False
+ ).effective_allowed_tools(ALL_TOOL_NAMES)
+ assert allowed == frozenset({"web_fetch"})
diff --git a/autogpt_platform/backend/backend/copilot/permissions_test.py b/autogpt_platform/backend/backend/copilot/permissions_test.py
index c5a063c2fd..65970550b1 100644
--- a/autogpt_platform/backend/backend/copilot/permissions_test.py
+++ b/autogpt_platform/backend/backend/copilot/permissions_test.py
@@ -747,9 +747,11 @@ class TestDreamPermissionsPreset:
assert tool not in effective, f"{tool} must be blocked for dream sub-agent"
def test_effective_set_matches_whitelist_intersection(self):
- # Sanity: effective set = whitelist ∩ known universe. web_fact_check
- # is intentionally absent from the universe until P0.5 lands, so the
- # effective set today is the four memory tools.
+ # Sanity: effective set = whitelist ∩ known universe, plus the
+ # dispatcher the whitelist needs — all four memory tools are deferred
+ # (#14569), so without run_capability the dream pass could reach none
+ # of them. web_fact_check is intentionally absent from the universe
+ # until P0.5 lands.
effective = DREAM_PERMISSIONS.effective_allowed_tools(ALL_TOOL_NAMES)
assert effective == frozenset(
{
@@ -757,6 +759,7 @@ class TestDreamPermissionsPreset:
"memory_store",
"memory_forget_search",
"memory_forget_confirm",
+ "run_capability",
}
)
diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
index f646347792..21ba36dcd6 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
@@ -24,6 +24,7 @@ from claude_agent_sdk import (
UserMessage,
)
+from backend.copilot.capabilities.dispatch import resolve_tool_dispatch
from backend.copilot.constants import FRIENDLY_TRANSIENT_MSG, is_transient_api_error
from backend.copilot.response_model import (
StreamBaseResponse,
@@ -357,6 +358,11 @@ class SDKResponseAdapter:
# instead of "mcp__copilot__find_block".
tool_name = block.name.strip().removeprefix(MCP_TOOL_PREFIX)
tool_input = strip_display_token(block.input)
+ # A dispatch of a platform tool IS a call to that tool, so
+ # the row this persists and the key the result is popped
+ # under name it — the same resolve the MCP handler runs.
+ if dispatch := resolve_tool_dispatch(tool_name, tool_input):
+ tool_name, tool_input = dispatch.name, dispatch.args
responses.append(
StreamToolInputStart(toolCallId=block.id, toolName=tool_name)
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index 375de64e7b..564a838455 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -4881,6 +4881,10 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
# get_agent_building_guide skip redundant guide round-trips when the
# guide is already in this turn's cached system prompt.
session.sdk_turn_active = True
+ # Turn-scoped, as the baseline's turn-end clear makes it: without
+ # this the buffer the adapter fills would carry a previous turn's
+ # calls into a gate that asks about *this* turn.
+ session.clear_inflight_tool_calls()
session.guide_in_system_prompt = bool(builder_session_suffix)
system_prompt = (
base_system_prompt
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
index f60554fc6c..91f5878d2c 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Any
from claude_agent_sdk import create_sdk_mcp_server, tool
from mcp.types import ToolAnnotations
+from backend.copilot.capabilities.dispatch import resolve_tool_dispatch
from backend.copilot.context import (
_current_envelope,
_current_hidden_tools,
@@ -761,6 +762,21 @@ def _make_truncating_wrapper(
"""
async def execute(args: dict[str, Any]) -> dict[str, Any]:
+ # A dispatch of a platform tool IS a call to that tool: resolve it once,
+ # here, so the circuit breaker, the file-ref expansion, the output stash
+ # and the handler below all see the call the model made rather than the
+ # dispatcher it arrived through. The display bridge stays bound to the
+ # dispatcher in ``wrapper`` above, which is what the hook registered.
+ dispatch = resolve_tool_dispatch(tool_name, args)
+ if dispatch is not None:
+ name, args = dispatch.name, dispatch.args
+ run = create_tool_handler(dispatch.tool)
+ schema = dispatch.tool.parameters
+ required = list(schema.get("required") or ())
+ else:
+ name, run = tool_name, fn
+ schema, required = input_schema, required_args
+
# Detect empty-args truncation: args is empty AND the original tool
# declared at least one *required* property. Tools whose params are all
# optional (filters-only tools like list_schedules) legitimately accept
@@ -769,17 +785,17 @@ def _make_truncating_wrapper(
# SDK-visible schema to avoid SDK-side validation rejecting truncated
# calls before reaching this handler. We carry required_args through
# the wrapper instead.
- if not args and required_args:
+ if not args and required:
logger.warning(
- f"[MCP] {tool_name} called with empty args (truncated or "
+ f"[MCP] {name} called with empty args (truncated or "
f"schema-rejected input) — returning guidance"
)
- stop_msg = _check_circuit_breaker(tool_name, args)
- _record_tool_failure(tool_name, args)
+ stop_msg = _check_circuit_breaker(name, args)
+ _record_tool_failure(name, args)
if stop_msg:
return _mcp_error(stop_msg)
return _mcp_error(
- f"Your call to {tool_name} arrived with empty arguments. "
+ f"Your call to {name} arrived with empty arguments. "
f"This means the arguments were dropped in transit: either "
f"your response hit the output-token limit mid-call, or an "
f"argument value did not match the parameter's declared "
@@ -787,13 +803,13 @@ def _make_truncating_wrapper(
f"way. Instead, write the large argument value to a file "
f"first (bash_exec with cat >>, appending section by "
f"section, or reuse a file you already wrote), then call "
- f'{tool_name} again passing the string "@@agptfile:<path>" '
+ f'{name} again passing the string "@@agptfile:<path>" '
f"as that argument's value. Object parameters such as "
f"agent_json accept this file-reference string directly."
)
original_args = args
- stop_msg = _check_circuit_breaker(tool_name, original_args)
+ stop_msg = _check_circuit_breaker(name, original_args)
if stop_msg:
return _mcp_error(stop_msg)
@@ -801,23 +817,23 @@ def _make_truncating_wrapper(
if session is not None:
try:
args = await expand_file_refs_in_args(
- args, user_id, session, input_schema=input_schema
+ args, user_id, session, input_schema=schema
)
except FileRefExpansionError as exc:
- _record_tool_failure(tool_name, original_args)
+ _record_tool_failure(name, original_args)
return _mcp_error(
f"@@agptfile: reference could not be resolved: {exc}. "
"Ensure the file exists before referencing it. "
"For sandbox paths use bash_exec to verify the file exists first; "
"for workspace files use a workspace:// URI."
)
- result = await fn(args)
+ result = await run(args)
truncated = truncate(result, _MCP_MAX_CHARS)
if truncated.get("isError"):
- _record_tool_failure(tool_name, original_args)
+ _record_tool_failure(name, original_args)
else:
- _clear_tool_failures(tool_name)
+ _clear_tool_failures(name)
# Stash the raw tool output for the frontend SSE stream so widgets
# (bash, tool viewers) receive clean JSON. Mid-turn user follow-up
@@ -831,7 +847,7 @@ def _make_truncating_wrapper(
# 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)
+ stash_pending_tool_output(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/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index 2b20017272..6b2ffb1f3e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any, Literal
from openai.types.chat import ChatCompletionToolParam
+from backend.copilot.capabilities.dispatch import resolve_tool_dispatch
from backend.copilot.capabilities.registry import configure_tools
from backend.copilot.capabilities.sources import EAGER_CORE
from backend.copilot.response_model import StreamToolOutputAvailable
@@ -463,9 +464,9 @@ async def execute_tool(
here makes the capability gate an enforcement boundary, matching the SDK
engine where hidden tools are never registered with the MCP server at all.
- ``DEFERRED_TOOL_NAMES`` are refused outright: they are reached by id
- through ``run_capability``, which applies the permission and envelope
- gates this function does not.
+ ``DEFERRED_TOOL_NAMES`` are refused when the model names one directly:
+ they are reached by id through ``run_capability``, whose dispatch this
+ function resolves back into a call to the tool itself.
``disabled_groups`` and ``disabled_tools`` are keyword-only and have no
default on purpose: they are an enforcement boundary, so a new call site
@@ -504,6 +505,12 @@ async def execute_tool(
success=False,
)
+ # A dispatch of a platform tool IS a call to that tool, so it runs the rest
+ # of this path under its own name: the refusal above still answers the model
+ # that named a deferred tool directly, because it ran before the resolve.
+ if dispatch := resolve_tool_dispatch(tool_name, parameters):
+ tool, tool_name, parameters = dispatch
+
# Track tool call in PostHog
logger.info(
f"Tracking tool call: tool={tool_name}, user={user_id}, "
diff --git a/autogpt_platform/backend/backend/copilot/tools/base.py b/autogpt_platform/backend/backend/copilot/tools/base.py
index fba7841931..0abcbaa523 100644
--- a/autogpt_platform/backend/backend/copilot/tools/base.py
+++ b/autogpt_platform/backend/backend/copilot/tools/base.py
@@ -15,6 +15,7 @@ from backend.data.db_accessors import activity_event_db, workspace_db
from backend.util.truncate import truncate
from backend.util.workspace import WorkspaceManager
+from .capability_gates import gate_denied, gate_denied_error
from .models import ErrorResponse, NeedLoginResponse, ToolResponseBase
logger = logging.getLogger(__name__)
@@ -418,6 +419,24 @@ class BaseTool:
success=False,
)
+ # A deferred tool arrives here resolved out of a ``run_capability``
+ # dispatch, so gating it by name has to happen on the way in or it
+ # does not happen at all.
+ if gate_denied(self.name):
+ return StreamToolOutputAvailable(
+ toolCallId=tool_call_id,
+ toolName=self.name,
+ output=gate_denied_error(
+ self.name, session.session_id
+ ).model_dump_json(),
+ success=False,
+ )
+
+ # After the gates, so a refused call never looks to a turn-scoped gate
+ # like the tool having run, and before the await, because the gates ask
+ # whether it was dispatched rather than whether it succeeded.
+ session.announce_inflight_tool_call(self.name, kwargs)
+
try:
result = await self._execute(user_id, session, **kwargs)
if user_id:
diff --git a/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py b/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py
index ba278e1f64..e2382ae904 100644
--- a/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py
@@ -67,6 +67,14 @@ def test_eager_and_deferred_split_the_registry():
assert len(get_available_tools(include_deferred=True)) > len(shown)
+def test_enter_building_mode_stays_eager_because_the_refusal_names_it():
+ """The building gate's refusal says to call ``enter_agent_building_mode``;
+ deferred, that instruction cannot be followed, because naming a deferred
+ tool directly is refused."""
+ assert "enter_agent_building_mode" in EAGER_CORE
+ assert "enter_agent_building_mode" not in DEFERRED_TOOL_NAMES
+
+
def test_start_desktop_stays_eager_because_the_prompt_names_it():
"""``expert_context`` tells the model "Use start_desktop"; a deferred
tool called by name is refused, so the instruction only works eager."""
@@ -213,17 +221,25 @@ def _stub_tool(name: str) -> MagicMock:
return tool
-async def test_run_tool_dispatches_to_the_deferred_tool():
+async def test_run_tool_describes_without_running():
+ """Running a platform tool never reaches the dispatcher — the engines
+ resolve the dispatch into a call to the tool itself (see
+ ``capabilities/dispatch_test.py``). What is left here is the description
+ ``validate_only`` asks for, which must not run anything."""
stub = _stub_tool("list_schedules")
with patch(
"backend.copilot.tools.run_capability.configured_tool", return_value=stub
):
result = await RunCapabilityTool()._execute(
- USER, make_session(USER), id="tool:list_schedules", input={"x": "1"}
+ USER,
+ make_session(USER),
+ id="tool:list_schedules",
+ input={"x": "1"},
+ validate_only=True,
)
- assert result.message == "ran"
- stub._execute.assert_awaited_once()
- assert stub._execute.await_args.kwargs == {"x": "1"}
+ assert isinstance(result, CapabilityDetailsResponse)
+ assert result.parameters == stub.parameters
+ stub._execute.assert_not_awaited()
async def test_run_tool_respects_turn_hidden_tools():
@@ -234,7 +250,7 @@ async def test_run_tool_respects_turn_hidden_tools():
"backend.copilot.tools.run_capability.configured_tool", return_value=stub
):
result = await RunCapabilityTool()._execute(
- USER, session, id="tool:list_schedules", input={}
+ USER, session, id="tool:list_schedules", input={}, validate_only=True
)
assert isinstance(result, ErrorResponse) and result.error == "tool_disabled"
stub._execute.assert_not_awaited()
@@ -523,3 +539,22 @@ async def test_resume_mcp_review_waits_for_approval():
USER, session, review_id=review_id
)
assert isinstance(result, ErrorResponse) and "not been approved" in result.message
+
+
+async def test_validating_a_dispatch_never_satisfies_a_gate():
+ """``validate_only`` describes the call without running it, so nothing
+ about it may look like the tool having run."""
+ session = make_session(USER)
+ stub = _stub_tool("enter_agent_building_mode")
+ with patch(
+ "backend.copilot.tools.run_capability.configured_tool", return_value=stub
+ ):
+ await RunCapabilityTool()._execute(
+ USER,
+ session,
+ id="tool:enter_agent_building_mode",
+ input={},
+ validate_only=True,
+ )
+ assert session.has_tool_been_called("enter_agent_building_mode") is False
+ stub._execute.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
index 4e243c7556..f61e6aaa91 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
@@ -1801,6 +1801,47 @@ class TestRequireLibraryCheck:
result = require_library_check(session, "create_agent")
assert isinstance(result, ErrorResponse)
+ async def test_sdk_dispatch_satisfies_the_gate(self):
+ """The SDK engine is the one that runs this gate in production, and it
+ reaches ``find_library_agent`` through the MCP adapter rather than the
+ baseline executor — so a real call there has to register or the gate
+ refuses create_agent forever. Every other test here fabricates the
+ announcement, which is why the hole stayed green.
+
+ The tool is a real ``BaseTool``: the announce lives in
+ ``BaseTool.execute``, after its gates, so a mock standing in for the
+ tool would skip the very line under test."""
+ from backend.copilot.sdk.tool_adapter import _execute_tool_sync
+ from backend.copilot.tools.base import BaseTool
+ from backend.copilot.tools.models import ErrorResponse
+
+ class _FindLibraryAgent(BaseTool):
+ @property
+ def name(self) -> str:
+ return "find_library_agent"
+
+ @property
+ def description(self) -> str:
+ return "stub"
+
+ @property
+ def parameters(self) -> dict:
+ return {"type": "object", "properties": {}}
+
+ async def _execute(self, user_id, session, **kwargs):
+ return ErrorResponse(message="ran", session_id=session.session_id)
+
+ session = make_session("user-lib-check", guide_read=False, library_check=False)
+
+ await _execute_tool_sync(
+ _FindLibraryAgent(),
+ "user-lib-check",
+ session,
+ {"for_creation": True, "goal_summary": "summarise emails"},
+ )
+
+ assert require_library_check(session, "create_agent") is None
+
def test_inflight_name_only_does_not_satisfy(self):
session = make_session("user-lib-check", guide_read=False, library_check=False)
session.announce_inflight_tool_call("find_library_agent")
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_capability.py b/autogpt_platform/backend/backend/copilot/tools/run_capability.py
index 99a5e15114..10f8313e0d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_capability.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_capability.py
@@ -140,7 +140,7 @@ class RunCapabilityTool(BaseTool):
if entry.kind == "block":
return await _run_block(entry, user_id, session, payload, validate_only)
if entry.kind == "tool":
- return await _run_tool(entry, user_id, session, payload, validate_only)
+ return await _describe_tool(entry, session)
if entry.kind == "mcp_server":
server_url = entry.implementations[0].ref
if not server_url:
@@ -178,28 +178,27 @@ async def _run_block(
)
-async def _run_tool(
- entry: CapabilityEntry,
- user_id: str,
- session: ChatSession,
- payload: dict[str, Any],
- validate_only: bool,
+async def _describe_tool(
+ entry: CapabilityEntry, session: ChatSession
) -> ToolResponseBase:
+ """What a platform tool needs, without running it.
+
+ Running one never reaches here: the engines resolve the dispatch into a
+ call to the tool itself (``capabilities/dispatch.py``) and run it through
+ the one tool path, so its gate, announce, history row and events name it.
+ """
name = entry.implementations[0].ref
tool = configured_tool(name)
if tool is None:
return ErrorResponse(message=UNKNOWN_ID_HINT, session_id=session.session_id)
if gate_denied(name):
return gate_denied_error(name, session.session_id)
- if validate_only:
- return CapabilityDetailsResponse(
- message=f"{tool.description} Call again without validate_only to run.",
- capability=entry.listing(),
- parameters=tool.parameters,
- session_id=session.session_id,
- )
- emit_tool_display_name(name)
- return await tool._execute(user_id, session, **payload)
+ return CapabilityDetailsResponse(
+ message=f"{tool.description} Call again without validate_only to run.",
+ capability=entry.listing(),
+ parameters=tool.parameters,
+ session_id=session.session_id,
+ )
async def _run_mcp(