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.

feat(platform): swap copilot discovery to find/describe/run_capability (#14569)

Nicholas Tindled52b5adcd2dc
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 8c0b92cd71..762e182e59 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -354,7 +354,7 @@ class CreateSessionRequest(BaseModel):
hides tools that conflict with the panel's scope
(``create_agent`` / ``customize_agent`` / ``get_agent_building_guide``
— see :data:`BUILDER_BLOCKED_TOOLS`). Read-side lookups
- (``find_block``, ``find_agent``, ``search_docs``, …) stay open.
+ (``find_capability``, ``find_agent``, ``search_docs``, …) stay open.
``expert_id`` scopes the session to a hired expert. It must reference
an expert owned by the caller that is neither a template nor archived,
@@ -749,7 +749,7 @@ async def create_session(
Two modes, selected by the request body:
- Default: create a fresh session for the user. ``dry_run=True`` forces
- run_block and run_agent calls to use dry-run simulation.
+ run_capability and run_agent calls to use dry-run simulation.
- Builder-bound: when ``builder_graph_id`` is set, get-or-create keyed
on ``(user_id, builder_graph_id)``. Returns the existing session for
that graph or creates one locked to it. Graph ownership is validated
diff --git a/autogpt_platform/backend/backend/api/features/experts/spend_approval.py b/autogpt_platform/backend/backend/api/features/experts/spend_approval.py
index 099f007120..95675a400a 100644
--- a/autogpt_platform/backend/backend/api/features/experts/spend_approval.py
+++ b/autogpt_platform/backend/backend/api/features/experts/spend_approval.py
@@ -186,7 +186,7 @@ async def open_chat_spend_review(
organization_id: str | None = None,
team_id: str | None = None,
) -> str:
- """Park a paid ``run_block`` on the session's review rails and return the
+ """Park a paid ``run_capability`` block run on the session's review rails and return the
review id. An open row for the same expert is reused so a model retry
does not stack cards."""
synthetic_graph_id = f"{COPILOT_SESSION_PREFIX}{session_id}"
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py
index a86324d6ec..b97b43e6ea 100644
--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py
+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py
@@ -65,7 +65,7 @@ class PendingHumanReviewModel(BaseModel):
)
library_agent_id: str | None = Field(default=None, description="For run deep links")
session_id: str | None = Field(
- default=None, description="Chat session id for copilot run_block reviews"
+ default=None, description="Chat session id for copilot run_capability reviews"
)
was_edited: bool | None = Field(
description="Whether the data was modified during review", default=None
diff --git a/autogpt_platform/backend/backend/api/features/mcp/routes.py b/autogpt_platform/backend/backend/api/features/mcp/routes.py
index ef1732aa2e..4a7d142eb6 100644
--- a/autogpt_platform/backend/backend/api/features/mcp/routes.py
+++ b/autogpt_platform/backend/backend/api/features/mcp/routes.py
@@ -635,7 +635,7 @@ async def mcp_store_token(
Used by the Copilot MCPSetupCard when the server doesn't support the MCP
OAuth discovery flow (returns 400 from /oauth/login). Subsequent
- ``run_mcp_tool`` calls will automatically pick up the credential via
+ ``run_capability`` MCP calls will automatically pick up the credential via
``_auto_lookup_credential``.
"""
try:
diff --git a/autogpt_platform/backend/backend/blocks/autopilot.py b/autogpt_platform/backend/backend/blocks/autopilot.py
index f3641e096f..7b683d6265 100644
--- a/autogpt_platform/backend/backend/blocks/autopilot.py
+++ b/autogpt_platform/backend/backend/blocks/autopilot.py
@@ -225,7 +225,7 @@ class AutoPilotBlock(Block):
blocks: list[str] = SchemaField(
description=(
- "Block identifiers to filter when the copilot uses run_block. "
+ "Block identifiers to filter when the copilot runs blocks via run_capability. "
"Each entry can be: a block name (e.g. 'HTTP Request'), "
"a full block UUID, or the first 8 hex characters of the UUID "
"(e.g. 'c069dc6b'). Works with blocks_exclude. "
@@ -248,7 +248,7 @@ class AutoPilotBlock(Block):
dry_run: bool = SchemaField(
description=(
- "When enabled, run_block and run_agent tool calls in this "
+ "When enabled, run_capability and run_agent tool calls in this "
"autopilot session are forced to use dry-run simulation mode. "
"No real API calls, side effects, or credits are consumed "
"by those tools. Useful for testing agent wiring and "
@@ -777,7 +777,7 @@ async def _build_and_validate_permissions(
if invalid_blocks:
return (
f"Unknown block identifier(s) in 'blocks': {invalid_blocks}. "
- "Use find_block to discover valid block names and IDs. "
+ "Use find_capability to discover valid block names and IDs. "
"You may also use the first 8 characters of a block UUID."
)
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index 4a6d78b209..1709d2a2ac 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -79,6 +79,7 @@ from backend.copilot.pending_messages import (
drain_pending_messages,
format_pending_as_user_message,
)
+from backend.copilot.permissions import denied_tool_names
from backend.copilot.prompting import (
SHARED_TOOL_NOTES,
get_chat_platform_supplement,
@@ -131,6 +132,7 @@ from backend.copilot.tools import (
get_available_tools,
kickoff_turn_disabled_tools,
origin_disabled_tools,
+ tool_names_in_groups,
)
from backend.copilot.tools.e2b_sandbox import (
count_expert_turn,
@@ -2288,6 +2290,22 @@ async def stream_chat_completion_baseline(
if permissions is not None:
tools = _filter_tools_by_permissions(tools, permissions)
+ # run_capability reaches deferred tools by id; bound it with the same
+ # hidden set that shaped the schema list above.
+ set_execution_context(
+ user_id,
+ session,
+ sandbox=e2b_sandbox,
+ sdk_cwd=working_dir,
+ permissions=permissions,
+ envelope=envelope,
+ hidden_tools=(
+ tool_names_in_groups(disabled_tool_groups)
+ | disabled_tools
+ | denied_tool_names(permissions)
+ ),
+ )
+
# Pre-mark cache_control on the last tool schema once per session. The
# tool set is static within a request, so doing this here (instead of in
# _baseline_llm_caller) avoids re-copying ~43 tool dicts on every LLM
@@ -2322,7 +2340,7 @@ async def stream_chat_completion_baseline(
user_id=user_id,
session_id=session_id,
trace_name="copilot-baseline",
- tags=["baseline"],
+ tags=["baseline", "tool_surface:registry"],
)
_trace_ctx.__enter__()
except Exception:
diff --git a/autogpt_platform/backend/backend/copilot/builder_context.py b/autogpt_platform/backend/backend/copilot/builder_context.py
index 8e94a68c56..36e2a96fc6 100644
--- a/autogpt_platform/backend/backend/copilot/builder_context.py
+++ b/autogpt_platform/backend/backend/copilot/builder_context.py
@@ -67,7 +67,7 @@ _BUILDER_TOOL_GUIDANCE = (
"including populating an empty graph (version=1, no nodes) — "
"`edit_agent` accepts the same node/link payload that `create_agent` "
"would, so there is no reason to reach for `create_agent` here. "
- "Typical sequence for a new request: call `find_block` to discover "
+ 'Typical sequence for a new request: call `find_capability(context="graph")` to discover '
"the block ids and input schemas you need, then call `edit_agent` "
"once with the full set of nodes and links. "
"Never ask the user to approve or allow a tool — there is no "
diff --git a/autogpt_platform/backend/backend/copilot/builder_context_test.py b/autogpt_platform/backend/backend/copilot/builder_context_test.py
index 0486ecf474..44b66b64b1 100644
--- a/autogpt_platform/backend/backend/copilot/builder_context_test.py
+++ b/autogpt_platform/backend/backend/copilot/builder_context_test.py
@@ -122,9 +122,9 @@ async def test_system_prompt_suffix_steers_to_edit_agent():
# The "no permission prompt UI" framing is what stops the model from
# asking the user to "click Allow" when a tool is unavailable.
assert "no permission prompt UI" in suffix
- # Concrete sequence (find_block → edit_agent) gives the model a
+ # Concrete sequence (find_capability → edit_agent) gives the model a
# template to follow instead of reaching for the blocked tools.
- assert "find_block" in suffix
+ assert "find_capability" in suffix
@pytest.mark.asyncio
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/block_meta.py b/autogpt_platform/backend/backend/copilot/capabilities/block_meta.py
new file mode 100644
index 0000000000..ab3174091a
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/capabilities/block_meta.py
@@ -0,0 +1,63 @@
+"""Block facts the registry and the copilot tools share.
+
+Lives below both ``backend.copilot.tools`` and the registry sources so that
+importing the registry never imports the tools package (which imports the
+registry tools, which import the registry: a cycle otherwise).
+"""
+
+from functools import cache
+
+from backend.blocks._base import AnyBlockSchema, BlockSchemaInput, BlockType
+from backend.integrations.providers import ProviderName
+
+# Block types that only work within graphs and cannot run standalone in CoPilot.
+COPILOT_EXCLUDED_BLOCK_TYPES = {
+ BlockType.INPUT, # Graph interface definition - data enters via chat, not graph inputs
+ BlockType.OUTPUT, # Graph interface definition - data exits via chat, not graph outputs
+ BlockType.WEBHOOK, # Wait for external events - would hang forever in CoPilot
+ BlockType.WEBHOOK_MANUAL, # Same as WEBHOOK
+ BlockType.NOTE, # Visual annotation only - no runtime behavior
+ BlockType.HUMAN_IN_THE_LOOP, # Pauses for human approval - CoPilot IS human-in-the-loop
+ BlockType.AGENT, # AgentExecutorBlock requires execution_context - use run_agent tool
+ BlockType.MCP_TOOL, # MCP servers are capabilities of their own with discovery + auth
+}
+
+# Specific block IDs excluded from CoPilot (STANDARD type but still require graph context)
+COPILOT_EXCLUDED_BLOCK_IDS = {
+ # OrchestratorBlock - dynamically discovers downstream blocks via graph topology;
+ # usable in agent graphs (guide hardcodes its ID) but cannot run standalone.
+ "3b191d9f-356f-482d-8238-ba04b6d18381",
+ # AutoPilotBlock - has dedicated run_sub_session tool with async start +
+ # poll lifecycle. Running it as a capability would block the parent stream
+ # for the sub-Otto's entire runtime (15-45+ min typical).
+ "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6",
+}
+
+
+def is_graph_only_block(block: AnyBlockSchema) -> bool:
+ return (
+ block.block_type in COPILOT_EXCLUDED_BLOCK_TYPES
+ or block.id in COPILOT_EXCLUDED_BLOCK_IDS
+ )
+
+
+def get_block_provider(block: AnyBlockSchema) -> str | None:
+ """Sole integration provider slug for a block, or None when the block
+ uses zero or multiple providers."""
+ try:
+ return _get_input_schema_provider(block.input_schema)
+ except Exception:
+ return None
+
+
+@cache
+def _get_input_schema_provider(input_schema: type[BlockSchemaInput]) -> str | None:
+ infos = input_schema.get_credentials_fields_info()
+ providers = {
+ ProviderName(provider).value
+ for info in infos.values()
+ for provider in info.provider
+ }
+ if len(providers) != 1:
+ return None
+ return next(iter(providers))
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py b/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py
new file mode 100644
index 0000000000..7b84518ba3
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py
@@ -0,0 +1,110 @@
+"""Human review for MCP calls made through ``run_capability``.
+
+MCP tool annotations are untrusted and, on the servers we see today, mostly
+absent, so the gate is conservative: a call to a server that is not in the
+official catalog pauses for review when the tool looks like a write. Catalog
+servers run without a pause; their tools go through the same review record
+once the per-user tool cache carries ``destructiveHint``.
+
+Records reuse the block review table with a synthetic node id so the
+existing approval UI, the pending-review feed and ``resume_capability`` all
+work unchanged.
+"""
+
+import re
+import uuid
+from typing import Any
+
+from pydantic import BaseModel
+
+from backend.copilot.constants import (
+ COPILOT_NODE_EXEC_ID_SEPARATOR,
+ COPILOT_SESSION_PREFIX,
+ COPILOT_SYNTHETIC_ID_PREFIX,
+)
+from backend.data.db_accessors import review_db
+
+COPILOT_MCP_NODE_PREFIX = f"{COPILOT_SYNTHETIC_ID_PREFIX}mcp-"
+
+_WRITE_VERBS = re.compile(
+ r"(^|[_\-.\s])(create|update|delete|remove|send|post|write|set|add|upload|"
+ r"publish|archive|merge|close|assign|move|rename|execute|run|trigger|"
+ r"cancel|approve|reject|pay|transfer|invite|grant|revoke|reset)([_\-.\s]|$)",
+ re.I,
+)
+_READ_VERBS = re.compile(
+ r"(^|[_\-.\s])(get|list|search|find|read|fetch|query|describe|show|"
+ r"lookup|check|count|view)([_\-.\s]|$)",
+ re.I,
+)
+
+
+class MCPReviewPayload(BaseModel):
+ """What ``resume_capability`` needs to replay an approved MCP call."""
+
+ server_url: str
+ tool: str
+ arguments: dict[str, Any]
+
+
+def looks_like_write(tool_name: str) -> bool:
+ if _READ_VERBS.search(tool_name) and not _WRITE_VERBS.search(tool_name):
+ return False
+ return bool(_WRITE_VERBS.search(tool_name)) or not _READ_VERBS.search(tool_name)
+
+
+def needs_review(tool_name: str, *, catalog_server: bool) -> bool:
+ return not catalog_server and looks_like_write(tool_name)
+
+
+def is_mcp_review_id(review_id: str) -> bool:
+ return review_id.startswith(COPILOT_MCP_NODE_PREFIX)
+
+
+def mcp_review_node_id(host: str) -> str:
+ return f"{COPILOT_MCP_NODE_PREFIX}{host}"
+
+
+async def open_mcp_review(
+ *,
+ user_id: str,
+ session_id: str,
+ host: str,
+ payload: MCPReviewPayload,
+ organization_id: str | None,
+ team_id: str | None,
+) -> str:
+ """Store a WAITING review for the call and return its review id.
+
+ An identical pending call (same server, tool and arguments) reuses its
+ review so a retried ``run_capability`` does not stack approvals.
+ """
+ graph_exec_id = f"{COPILOT_SESSION_PREFIX}{session_id}"
+ node_id = mcp_review_node_id(host)
+ data = payload.model_dump()
+ for review in await review_db().get_pending_reviews_for_execution(
+ graph_exec_id, user_id
+ ):
+ if (
+ review.node_id == node_id
+ and review.status.value == "WAITING"
+ and review.payload == data
+ ):
+ return review.node_exec_id
+ review_id = f"{node_id}{COPILOT_NODE_EXEC_ID_SEPARATOR}{uuid.uuid4().hex[:8]}"
+ await review_db().get_or_create_human_review(
+ user_id=user_id,
+ node_exec_id=review_id,
+ graph_exec_id=graph_exec_id,
+ graph_id=graph_exec_id,
+ graph_version=1,
+ input_data=data,
+ message=(
+ f"Run MCP tool '{payload.tool}' on {host} with the shown arguments? "
+ "This server is not in the official catalog."
+ ),
+ editable=True,
+ organization_id=organization_id,
+ team_id=team_id,
+ )
+ return review_id
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/ranking.py b/autogpt_platform/backend/backend/copilot/capabilities/ranking.py
index 0cce27c03b..f990ff7fcc 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/ranking.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/ranking.py
@@ -41,8 +41,8 @@ def resolve_connected(
if connection.key_type == "provider":
return connection.key in state.providers
if connection.key_type == "server_url":
- return _normalize_url(connection.key) in {
- _normalize_url(url) for url in state.server_urls
+ return normalize_server_url(connection.key) in {
+ normalize_server_url(url) for url in state.server_urls
}
return None
@@ -68,5 +68,11 @@ def class_weight(entry: CapabilityEntry, connected: bool | None) -> float:
}[tier(entry, connected)]
-def _normalize_url(url: str) -> str:
+def normalize_server_url(url: str) -> str:
+ """Compare MCP server URLs the way the catalog and the user write them.
+
+ Catalog keys are stored both ways (``https://mcp.miro.com/`` alongside
+ ``https://mcp.linear.app/mcp``), so a raw ``==`` against whatever the
+ model passes decides "is this a catalog server" on a trailing slash.
+ """
return url.strip().lower().rstrip("/")
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/registry.py b/autogpt_platform/backend/backend/copilot/capabilities/registry.py
index ad112c00b1..7f1bc87cee 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/registry.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/registry.py
@@ -4,11 +4,17 @@ The platform-wide index (tools + blocks + MCP catalog) is static for the
life of the process, so it is built once and reused. Per-user entries (MCP
servers the user has registered) are layered on top per request by a later
change; nothing here depends on the user.
+
+``backend.copilot.tools`` imports the registry tools, which import this
+package, so the tools package hands over its registry with
+:func:`configure_tools` once it has built it instead of this module
+importing it.
"""
import logging
import threading
from collections.abc import Mapping
+from typing import TYPE_CHECKING
from backend.copilot.capabilities.index import CapabilityIndex
from backend.copilot.capabilities.models import CapabilityEntry
@@ -17,7 +23,9 @@ from backend.copilot.capabilities.sources import (
mcp_catalog_entries,
tool_entries,
)
-from backend.copilot.tools.base import BaseTool
+
+if TYPE_CHECKING:
+ from backend.copilot.tools.base import BaseTool
logger = logging.getLogger(__name__)
@@ -30,22 +38,34 @@ MERGED_IMPLEMENTATIONS: dict[str, str] = {
_lock = threading.Lock()
_registry: CapabilityIndex | None = None
+_tools: "Mapping[str, BaseTool] | None" = None
+_groups: Mapping[str, str] = {}
+
+
+def configure_tools(tools: "Mapping[str, BaseTool]", groups: Mapping[str, str]) -> None:
+ """Hand the platform tool registry to this package (called once by
+ ``backend.copilot.tools`` after ``TOOL_REGISTRY`` exists)."""
+ global _tools, _groups
+ with _lock:
+ _tools, _groups = tools, groups
+
+def configured_tool(name: str) -> "BaseTool | None":
+ """The platform tool behind a ``tool:`` entry, or None."""
+ return None if _tools is None else _tools.get(name)
-def get_registry(
- tools: Mapping[str, BaseTool], groups: Mapping[str, str]
-) -> CapabilityIndex:
- """The process-wide platform index, built on first use.
- *tools*/*groups* are ``TOOL_REGISTRY``/``TOOL_GROUPS``; the caller passes
- them because the tools package imports this one. They only matter on
- the first call.
- """
+def get_registry() -> CapabilityIndex:
+ """The process-wide platform index, built on first use."""
global _registry
if _registry is None:
with _lock:
if _registry is None:
- _registry = CapabilityIndex(build_entries(tools, groups))
+ if _tools is None:
+ raise RuntimeError(
+ "Capability registry used before configure_tools()"
+ )
+ _registry = CapabilityIndex(build_entries(_tools, _groups))
logger.info(f"Capability registry built: {len(_registry)} entries")
return _registry
@@ -58,7 +78,7 @@ def reset_registry() -> None:
def build_entries(
- tools: Mapping[str, BaseTool],
+ tools: "Mapping[str, BaseTool]",
groups: Mapping[str, str],
*,
include_blocks: bool = True,
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/registry_test.py b/autogpt_platform/backend/backend/copilot/capabilities/registry_test.py
index 443c2e09f0..fcaeefa810 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/registry_test.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/registry_test.py
@@ -9,7 +9,9 @@ from backend.integrations.mcp_catalog import get_mcp_catalog
from .index import CapabilityIndex
from .registry import MERGED_IMPLEMENTATIONS, build_entries
+from .resolve import resolve_entry
from .sources import RETIRED_TOOLS
+from .sources.mcp_catalog import setup_hint
EXPLICIT_PRIMITIVES = {
"ExecuteCodeBlock",
@@ -87,6 +89,36 @@ def test_every_catalog_preset_survives_as_an_entry(index):
assert len(mcp_ids) == len(presets)
assert len(set(mcp_ids)) == len(mcp_ids)
assert {"mcp:atlassian", "mcp:atlassian_forge"} <= set(mcp_ids)
+ v2 = resolve_entry(index, "https://mcp.atlassian.com/v2/mcp")
+ forge = resolve_entry(index, "https://mcp.atlassian.com/v1/forge/mcp")
+ assert v2 is not None and forge is not None and v2.id != forge.id
+
+
+def test_custom_presets_carry_no_url_in_ref(index):
+ """A ``custom`` preset has no shared endpoint. Putting its catalog name
+ in the implementation ref sent it downstream as a hostname, where it
+ failed validation as "Hostname 'mcp_amplitude' has unsupported
+ characters" instead of telling the user to supply their own URL."""
+ custom = [
+ entry
+ for entry in index.entries
+ if entry.kind == "mcp_server" and not entry.implementations[0].ref
+ ]
+ assert custom, "expected catalog presets with no server_url"
+ assert all(not entry.connection.key for entry in custom)
+ assert "mcp:amplitude" in {entry.id for entry in custom}
+ for entry in custom:
+ hint = setup_hint(entry.schema_ref or entry.id)
+ assert "Settings" in hint and entry.name in hint
+
+
+def test_hosted_presets_keep_their_url(index):
+ hosted = [
+ entry
+ for entry in index.entries
+ if entry.kind == "mcp_server" and entry.implementations[0].ref
+ ]
+ assert all(entry.implementations[0].ref.startswith("https://") for entry in hosted)
def test_listing_stays_compact(index):
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/resolve.py b/autogpt_platform/backend/backend/copilot/capabilities/resolve.py
new file mode 100644
index 0000000000..be95a11304
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/capabilities/resolve.py
@@ -0,0 +1,95 @@
+"""Turn what the model hands us into a registry entry, and load the
+connection state that decides how entries rank for this user."""
+
+import logging
+from urllib.parse import urlsplit
+
+from backend.copilot.capabilities.index import CapabilityIndex
+from backend.copilot.capabilities.models import CapabilityEntry
+from backend.copilot.capabilities.ranking import ConnectionState, normalize_server_url
+from backend.copilot.capabilities.text import normalize_name
+from backend.data.model import Credentials, HostScopedCredentials, OAuth2Credentials
+from backend.integrations.credentials_store import canonical_provider
+from backend.integrations.creds_manager import IntegrationCredentialsManager
+from backend.integrations.providers import ProviderName
+
+logger = logging.getLogger(__name__)
+
+
+def resolve_entry(index: CapabilityIndex, capability_id: str) -> CapabilityEntry | None:
+ """Accept an entry id, a bare block uuid or tool name, a block class name,
+ an MCP host, or an MCP server URL."""
+ key = (capability_id or "").strip()
+ if not key:
+ return None
+ entry = index.get(key) or index.get(key.lower())
+ if entry is not None:
+ return entry
+ if "://" in key:
+ host = urlsplit(key).hostname
+ by_host = index.get(f"mcp:{host}") if host else None
+ if by_host is not None:
+ return by_host
+ # Two catalog presets can share a host, so those entries are keyed by
+ # slug; match the full server URL instead. Normalised on both sides:
+ # failing to match here does not say "unknown id", it says "not a
+ # catalog server", which sends trusted writes to human review.
+ wanted_url = normalize_server_url(key)
+ return next(
+ (
+ e
+ for e in index.entries
+ if e.connection.key
+ and normalize_server_url(e.connection.key) == wanted_url
+ ),
+ None,
+ )
+ if not key.startswith(("tool:", "block:", "mcp:")):
+ entry = index.get(f"mcp:{key.lower()}")
+ if entry is not None:
+ return entry
+ wanted = normalize_name(key.split(":", 1)[-1])
+ return next(
+ (e for e in index.entries if normalize_name(e.name) == wanted),
+ None,
+ )
+
+
+async def load_connection_state(user_id: str) -> ConnectionState:
+ """Providers, MCP server URLs and hosts the user holds credentials for.
+
+ One store read per call; the credentials manager already caches, so a
+ ``find_capability`` turn costs no extra round-trips.
+ """
+ try:
+ credentials = await IntegrationCredentialsManager().store.get_all_creds(user_id)
+ except Exception:
+ logger.warning("Could not load credentials for ranking", exc_info=True)
+ return ConnectionState()
+ return connection_state_from(credentials)
+
+
+def connection_state_from(credentials: list[Credentials]) -> ConnectionState:
+ providers: set[str] = set()
+ server_urls: set[str] = set()
+ hosts: set[str] = set()
+ for credential in credentials:
+ # Credentials stored under Python 3.13 carry ``"ProviderName.MCP"``
+ # where they mean ``"mcp"``; ranking compares against the canonical
+ # value, so an un-normalised one reads as a service the user never
+ # connected.
+ provider = canonical_provider(credential.provider)
+ providers.add(provider)
+ if isinstance(credential, HostScopedCredentials):
+ hosts.add(credential.host.lower())
+ if provider == ProviderName.MCP.value and isinstance(
+ credential, OAuth2Credentials
+ ):
+ url = (credential.metadata or {}).get("mcp_server_url")
+ if isinstance(url, str) and url:
+ server_urls.add(url)
+ return ConnectionState(
+ providers=frozenset(providers),
+ server_urls=frozenset(server_urls),
+ hosts=frozenset(hosts),
+ )
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/resolve_test.py b/autogpt_platform/backend/backend/copilot/capabilities/resolve_test.py
new file mode 100644
index 0000000000..e474475be8
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/capabilities/resolve_test.py
@@ -0,0 +1,122 @@
+"""Connection state feeds ranking, so a credential that reads as absent
+quietly demotes every capability the user actually connected — and a
+catalog URL that fails to resolve sends trusted writes to human review."""
+
+from pydantic import SecretStr
+
+from backend.data.model import APIKeyCredentials, OAuth2Credentials
+
+from .index import CapabilityIndex
+from .models import CapabilityEntry, Connection, Implementation
+from .resolve import connection_state_from, resolve_entry
+
+
+def _oauth(provider: str, url: str | None = None) -> OAuth2Credentials:
+ return OAuth2Credentials(
+ id="cred-1",
+ provider=provider,
+ title="Linear",
+ username=None,
+ access_token=SecretStr("at"),
+ refresh_token=None,
+ access_token_expires_at=None,
+ refresh_token_expires_at=None,
+ scopes=[],
+ metadata={"mcp_server_url": url} if url else {},
+ )
+
+
+def test_a_legacy_provider_string_still_counts_as_connected():
+ """Credentials written under Python 3.13 carry ``"ProviderName.MCP"``.
+
+ Ranking asks for the canonical ``"mcp"``, so without normalising here the
+ user's own connected server ranks as one they have never signed into.
+ """
+ state = connection_state_from(
+ [_oauth("ProviderName.MCP", "https://mcp.linear.app/mcp")]
+ )
+ assert "mcp" in state.providers
+ assert "https://mcp.linear.app/mcp" in state.server_urls
+
+
+def test_a_canonical_provider_is_left_alone():
+ state = connection_state_from([_oauth("mcp", "https://mcp.linear.app/mcp")])
+ assert state.providers == frozenset({"mcp"})
+ assert state.server_urls == frozenset({"https://mcp.linear.app/mcp"})
+
+
+def test_an_unknown_legacy_member_survives_as_itself():
+ """A provider we have since retired must not vanish from the set."""
+ state = connection_state_from([_oauth("ProviderName.NOT_A_PROVIDER")])
+ assert state.providers == frozenset({"ProviderName.NOT_A_PROVIDER"})
+
+
+def test_a_non_mcp_credential_contributes_no_server_url():
+ state = connection_state_from(
+ [
+ APIKeyCredentials(
+ id="cred-2",
+ provider="openai",
+ title="OpenAI",
+ api_key=SecretStr("sk"),
+ expires_at=None,
+ )
+ ]
+ )
+ assert state.providers == frozenset({"openai"})
+ assert state.server_urls == frozenset()
+
+
+def test_no_credentials_is_an_empty_state():
+ state = connection_state_from([])
+ assert not state.providers and not state.server_urls and not state.hosts
+
+
+def _mcp_entry(slug: str, server_url: str) -> CapabilityEntry:
+ return CapabilityEntry(
+ id=f"mcp:{slug}",
+ kind="mcp_server",
+ name=slug,
+ purpose=f"{slug} server",
+ implementations=[Implementation(kind="mcp_server", ref=server_url)],
+ connection=Connection(required=True, key_type="server_url", key=server_url),
+ )
+
+
+def _index(*entries: CapabilityEntry) -> CapabilityIndex:
+ return CapabilityIndex(list(entries))
+
+
+def test_a_shared_host_resolves_however_the_url_is_written():
+ """Two presets on one host fall through to a full-URL match.
+
+ Missing there does not read as "unknown id" — it reads as "not a catalog
+ server", which sends a trusted write to human review and drops the
+ catalog's own setup hints.
+ """
+ index = _index(
+ _mcp_entry("atlassian-jira", "https://mcp.atlassian.com/v1/sse"),
+ _mcp_entry("atlassian-conf", "https://mcp.atlassian.com/v1/confluence"),
+ )
+ for written in (
+ "https://mcp.atlassian.com/v1/sse",
+ "https://mcp.atlassian.com/v1/sse/",
+ " https://MCP.Atlassian.com/v1/SSE ",
+ ):
+ entry = resolve_entry(index, written)
+ assert entry is not None and entry.id == "mcp:atlassian-jira", written
+
+
+def test_a_catalog_key_stored_with_a_slash_matches_a_url_without_one():
+ """Catalog keys are stored both ways, so normalise both sides."""
+ index = _index(
+ _mcp_entry("miro-a", "https://mcp.miro.com/"),
+ _mcp_entry("miro-b", "https://mcp.miro.com/other"),
+ )
+ entry = resolve_entry(index, "https://mcp.miro.com")
+ assert entry is not None and entry.id == "mcp:miro-a"
+
+
+def test_a_url_on_no_catalog_host_still_resolves_to_nothing():
+ index = _index(_mcp_entry("miro-a", "https://mcp.miro.com/"))
+ assert resolve_entry(index, "https://mcp.example.com/mcp") is None
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/schema_trim.py b/autogpt_platform/backend/backend/copilot/capabilities/schema_trim.py
new file mode 100644
index 0000000000..1117679b7f
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/capabilities/schema_trim.py
@@ -0,0 +1,29 @@
+"""Schema trimming for ``describe_capability``: large enums are the single
+biggest schema cost (the LLM ``model`` enum alone is ~110 values), so they
+are collapsed to a sample unless the model asks to ``expand``."""
+
+from typing import Any
+
+ENUM_COLLAPSE_LIMIT = 12
+ENUM_SAMPLE = 8
+
+
+def collapse_large_enums(node: Any, limit: int = ENUM_COLLAPSE_LIMIT) -> Any:
+ """Return *node* with every ``enum`` longer than *limit* replaced by its
+ first ``ENUM_SAMPLE`` values plus a note carrying the full count."""
+ if isinstance(node, list):
+ return [collapse_large_enums(item, limit) for item in node]
+ if not isinstance(node, dict):
+ return node
+ cleaned: dict[str, Any] = {}
+ for key, value in node.items():
+ if key == "enum" and isinstance(value, list) and len(value) > limit:
+ cleaned["enum_sample"] = value[:ENUM_SAMPLE]
+ cleaned["enum_count"] = len(value)
+ cleaned["enum_note"] = (
+ f"{len(value)} allowed values; {ENUM_SAMPLE} shown. "
+ "Call describe_capability with expand=true for all of them."
+ )
+ continue
+ cleaned[key] = collapse_large_enums(value, limit)
+ return cleaned
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/sources/blocks.py b/autogpt_platform/backend/backend/copilot/capabilities/sources/blocks.py
index 864487c422..ce5d4e6183 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/sources/blocks.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/sources/blocks.py
@@ -10,6 +10,10 @@ import logging
from backend.blocks import get_blocks
from backend.blocks._base import AnyBlockSchema
+from backend.copilot.capabilities.block_meta import (
+ get_block_provider,
+ is_graph_only_block,
+)
from backend.copilot.capabilities.models import (
CapabilityEntry,
Connection,
@@ -17,11 +21,6 @@ from backend.copilot.capabilities.models import (
clip_purpose,
)
from backend.copilot.capabilities.text import tokenize
-from backend.copilot.tools.find_block import (
- COPILOT_EXCLUDED_BLOCK_IDS,
- COPILOT_EXCLUDED_BLOCK_TYPES,
-)
-from backend.copilot.tools.helpers import get_block_provider
from backend.data.model import CredentialsFieldInfo
logger = logging.getLogger(__name__)
@@ -53,10 +52,7 @@ def block_entries(*, include_disabled: bool = False) -> list[CapabilityEntry]:
def _block_entry(block: AnyBlockSchema) -> CapabilityEntry:
- graph_only = (
- block.block_type in COPILOT_EXCLUDED_BLOCK_TYPES
- or block.id in COPILOT_EXCLUDED_BLOCK_IDS
- )
+ graph_only = is_graph_only_block(block)
provider = get_block_provider(block)
# Credentials may sit inside a nested input (the Google Sheets picker),
# which ``get_credentials_fields`` does not see; the info view does.
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/sources/mcp_catalog.py b/autogpt_platform/backend/backend/copilot/capabilities/sources/mcp_catalog.py
index c7e0fe7c59..2ba7f41ca5 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/sources/mcp_catalog.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/sources/mcp_catalog.py
@@ -6,6 +6,7 @@ so a catalog entry is the "connect to Linear" capability itself.
"""
from collections import Counter
+from functools import cache
from urllib.parse import urlsplit
from backend.copilot.capabilities.models import (
@@ -43,6 +44,9 @@ def _catalog_entry(preset: MCPCatalogEntry, keyed_by_host: bool) -> CapabilityEn
# Service names come last so ``index._service_tags`` can read them back:
# the slug, the host, and the display name when it is a single word.
tags += ["mcp", slug]
+ brand = _brand(slug)
+ if brand:
+ tags.append(brand)
if host:
tags.append(host)
if " " not in preset.display_name.strip():
@@ -56,9 +60,13 @@ def _catalog_entry(preset: MCPCatalogEntry, keyed_by_host: bool) -> CapabilityEn
tags=tags,
context="direct",
implementations=[
+ # A ``custom`` preset ships no URL: the user supplies their own
+ # tenant endpoint. Leaving the ref empty keeps the preset name
+ # out of URL position, where it used to be parsed as a hostname
+ # ("Blocked server URL: Hostname 'mcp_amplitude' ...").
Implementation(
kind="mcp_server",
- ref=server.server_url or preset.name,
+ ref=server.server_url or "",
name=preset.display_name,
)
],
@@ -67,3 +75,46 @@ def _catalog_entry(preset: MCPCatalogEntry, keyed_by_host: bool) -> CapabilityEn
),
schema_ref=f"mcp:{preset.name}",
)
+
+
+# Suffixes that are part of a company's domain rather than its name, so
+# "apollo_io" is the service "apollo" and a query for "apollo" must reach it.
+_BRAND_SUFFIXES = frozenset({"io", "com", "dev", "ai", "co", "app", "so", "to", "sh"})
+
+
+def _brand(slug: str) -> str | None:
+ """The brand inside a domain-shaped slug, e.g. ``apollo_io`` -> ``apollo``."""
+ head, _, tail = slug.rpartition("_")
+ if head and tail in _BRAND_SUFFIXES and "_" not in head:
+ return head
+ return None
+
+
+def setup_hint(schema_ref: str) -> str:
+ """How to reach a catalog server that ships no URL of its own."""
+ preset = _presets_by_schema_ref().get(schema_ref)
+ if preset is None:
+ return (
+ "This MCP server needs a server URL. The user adds it under "
+ "Settings -> Integrations, then call run_capability with that "
+ "https:// URL as the id."
+ )
+ options = ", ".join(
+ f"{option.label} ({option.url})"
+ for option in preset.mcp_server.server_url_options
+ )
+ lines = [
+ f"{preset.display_name} has no shared endpoint: it runs at a URL "
+ "specific to the user's account, so the platform cannot call it until "
+ "they add one under Settings -> Integrations.",
+ preset.mcp_server.setup_instructions,
+ f"Known endpoints: {options}." if options else "",
+ "Once the user has added their URL, call run_capability with that "
+ "https:// URL as the id.",
+ ]
+ return " ".join(line for line in lines if line)
+
+
+@cache
+def _presets_by_schema_ref() -> dict[str, MCPCatalogEntry]:
+ return {f"mcp:{preset.name}": preset for preset in get_mcp_catalog()}
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 8232dbc5c9..1d93eceed0 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/sources/static_tools.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/sources/static_tools.py
@@ -6,6 +6,7 @@ hands its registry over at call time instead of at import time.
"""
from collections.abc import Mapping
+from typing import TYPE_CHECKING
from backend.copilot.capabilities.models import (
CapabilityEntry,
@@ -13,7 +14,9 @@ from backend.copilot.capabilities.models import (
clip_purpose,
)
from backend.copilot.capabilities.text import tokenize
-from backend.copilot.tools.base import BaseTool
+
+if TYPE_CHECKING:
+ from backend.copilot.tools.base import BaseTool
# Tools that stay in the model's tool list. Everything else in the registry
# is reached through find/describe/run_capability. The registry tools are
@@ -36,6 +39,11 @@ EAGER_CORE: frozenset[str] = frozenset(
"delegate_to_expert",
"handoff_to_expert",
"TodoWrite",
+ # ``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
+ # ``run_capability`` that would reach it.
+ "expert_onboarding",
}
)
@@ -47,7 +55,7 @@ RETIRED_TOOLS: frozenset[str] = frozenset(
def tool_entries(
- tools: Mapping[str, BaseTool], groups: Mapping[str, str]
+ tools: "Mapping[str, BaseTool]", groups: Mapping[str, str]
) -> list[CapabilityEntry]:
"""One entry per available tool, skipping the retired discovery tools."""
return [
@@ -57,7 +65,7 @@ def tool_entries(
]
-def _tool_entry(name: str, tool: BaseTool, group: str | None) -> CapabilityEntry:
+def _tool_entry(name: str, tool: "BaseTool", group: str | None) -> CapabilityEntry:
properties = (tool.parameters or {}).get("properties") or {}
tags = sorted(set(tokenize(name)))
if group:
diff --git a/autogpt_platform/backend/backend/copilot/context.py b/autogpt_platform/backend/backend/copilot/context.py
index 8d8f1beda3..a20ab19d75 100644
--- a/autogpt_platform/backend/backend/copilot/context.py
+++ b/autogpt_platform/backend/backend/copilot/context.py
@@ -129,6 +129,12 @@ _current_permissions: "ContextVar[CopilotPermissions | None]" = ContextVar(
_current_envelope: "ContextVar[TurnEnvelope | None]" = ContextVar(
"_current_envelope", default=None
)
+# Short tool names this turn hid from the model (permission-denied, group-
+# disabled, kickoff-narrowed). ``run_capability`` refuses to reach them, so
+# hiding stays an enforcement boundary once tools are reachable by id.
+_current_hidden_tools: ContextVar[frozenset[str]] = ContextVar(
+ "_current_hidden_tools", default=frozenset()
+)
def encode_cwd_for_cli(cwd: str) -> str:
@@ -152,6 +158,7 @@ def set_execution_context(
sdk_cwd: str | None = None,
permissions: "CopilotPermissions | None" = None,
envelope: "TurnEnvelope | None" = None,
+ hidden_tools: frozenset[str] = frozenset(),
) -> None:
"""Set per-turn context variables used by file-resolution tool handlers."""
_current_user_id.set(user_id)
@@ -161,6 +168,7 @@ def set_execution_context(
_current_project_dir.set(_encode_cwd_for_cli(sdk_cwd) if sdk_cwd else "")
_current_permissions.set(permissions)
_current_envelope.set(envelope)
+ _current_hidden_tools.set(hidden_tools)
reset_consult_budget()
@@ -179,6 +187,11 @@ def get_current_envelope() -> "TurnEnvelope | None":
return _current_envelope.get()
+def get_current_hidden_tools() -> frozenset[str]:
+ """Short tool names hidden from the model this turn."""
+ return _current_hidden_tools.get()
+
+
def get_current_sandbox() -> "AsyncSandbox | None":
"""Return the E2B sandbox for the current session, or None if not active."""
return _current_sandbox.get()
diff --git a/autogpt_platform/backend/backend/copilot/eval/style/generation.py b/autogpt_platform/backend/backend/copilot/eval/style/generation.py
index 01ca1f381b..e5438c8570 100644
--- a/autogpt_platform/backend/backend/copilot/eval/style/generation.py
+++ b/autogpt_platform/backend/backend/copilot/eval/style/generation.py
@@ -25,8 +25,15 @@ from backend.copilot.baseline.service import (
_mark_tools_with_cache_control,
_supports_prompt_cache_markers,
)
+from backend.copilot.capabilities.registry import get_registry
from backend.copilot.config import ChatConfig
-from backend.copilot.tools import expert_tool_disabled_groups, get_available_tools
+from backend.copilot.tools import (
+ ToolGroup,
+ expert_tool_disabled_groups,
+ get_available_tools,
+ get_tool,
+ reachable_tool_names,
+)
from backend.copilot.tools.list_agent_triggers import AgentTriggerListResponse
from backend.copilot.tools.manage_presets import PresetListResponse
from backend.copilot.tools.manage_schedules import ScheduleListResponse
@@ -34,6 +41,8 @@ from backend.copilot.tools.models import (
AgentInfo,
AgentOutputResponse,
AgentsFoundResponse,
+ CapabilityDetailsResponse,
+ CapabilityListResponse,
ErrorResponse,
ExecutionStartedResponse,
MemorySearchResponse,
@@ -62,6 +71,11 @@ TERMINAL_TOOL = "ask_question"
LIBRARY_SEARCH_TOOLS = ("find_library_agent", "find_agent")
DELEGATION_TOOLS = ("delegate_to_expert", "run_sub_session")
HANDOFF_TOOL = "handoff_to_expert"
+FIND_TOOL = "find_capability"
+DESCRIBE_TOOL = "describe_capability"
+RUN_TOOL = "run_capability"
+# The wrappers that name their target in ``id`` instead of being the target.
+CAPABILITY_WRAPPERS = (RUN_TOOL, DESCRIBE_TOOL)
WEB_TOOLS = ("web_search", "web_fetch")
STUB_EXECUTION_ID = "style-eval-execution"
STUB_GRAPH_ID = "style-eval-graph"
@@ -91,13 +105,25 @@ def chat_client(config: ChatConfig) -> openai.AsyncOpenAI:
return openai.AsyncOpenAI(api_key=api_key or "", base_url=base_url)
+def _expert_disabled_groups(expert: Expert | None) -> list[ToolGroup]:
+ return expert_tool_disabled_groups(
+ experts_enabled=DELEGATION_ENABLED, expert_id=expert.id if expert else None
+ )
+
+
def expert_tools(expert: Expert | None) -> list[ChatCompletionToolParam]:
"""Production's tool surface for the session (hire-experts on, memory on):
an expert loses the staffing tools, plain Otto the expert-only ones."""
- disabled = expert_tool_disabled_groups(
- experts_enabled=DELEGATION_ENABLED, expert_id=expert.id if expert else None
- )
- return get_available_tools(disabled_groups=disabled)
+ return get_available_tools(disabled_groups=_expert_disabled_groups(expert))
+
+
+def expert_reachable_tools(expert: Expert | None) -> frozenset[str]:
+ """Everything the session can run, declared or reached by id.
+
+ The schema list above is the eager core; the rest of the surface is a
+ ``run_capability`` call away, under the same group gate.
+ """
+ return reachable_tool_names(disabled_groups=_expert_disabled_groups(expert))
async def generate_turn(
@@ -148,7 +174,9 @@ async def generate_turn(
]
if not tool_calls:
break
- turn.tool_calls += [tc.function.name for tc in tool_calls]
+ turn.tool_calls += [
+ called_name(tc.function.name, tc.function.arguments) for tc in tool_calls
+ ]
asked = [tc for tc in tool_calls if tc.function.name == TERMINAL_TOOL]
if asked:
texts += [question_text(tc.function.arguments) for tc in asked]
@@ -185,6 +213,17 @@ def stub_tool_result(
An ad-hoc "no results" blob instead kept the model retrying the same tools
until the round cap, on 6 of 90 prompts."""
args = _arguments(arguments)
+ if name == FIND_TOOL:
+ return _capability_search(str(args.get("query") or ""))
+ if name == DESCRIBE_TOOL:
+ return _capability_details(called_name(name, arguments))
+ if name == RUN_TOOL:
+ # Since the swap the model reaches all but the eager core through
+ # run_capability, so the table below would answer almost nothing if
+ # it kept dispatching on the wrapper's name and arguments.
+ name = called_name(name, arguments)
+ nested = args.get("input")
+ args = dict(nested) if isinstance(nested, dict) else {}
workflow = _workflow(expert, args)
if name in LIBRARY_SEARCH_TOOLS:
return _dump(_library_result(expert))
@@ -275,6 +314,67 @@ def stub_tool_result(
return _dump(NoResultsResponse(message=f"Nothing to return from {name}."))
+def called_name(name: str, arguments: str) -> str:
+ """The tool the model actually asked for.
+
+ ``run_capability(id="tool:memory_search")`` is a call to ``memory_search``
+ as far as this eval is concerned; recording the wrapper instead would
+ collapse every per-tool measurement onto one name.
+ """
+ if name not in CAPABILITY_WRAPPERS:
+ return name
+ target = str(_arguments(arguments).get("id") or "").strip()
+ for prefix in ("tool:", "block:", "mcp:"):
+ if target.startswith(prefix):
+ return target[len(prefix) :]
+ return target or name
+
+
+def _capability_details(capability_id: str) -> str:
+ """What ``describe_capability`` answers: the entry and its input shape.
+
+ Only platform tools are described here — a block or MCP schema needs the
+ account the eval does not have, and no stub below answers one anyway.
+ """
+ entry = get_registry().get(capability_id)
+ tool = get_tool(capability_id) if entry else None
+ if entry is None or tool is None:
+ return _dump(
+ NoResultsResponse(message=f"No capability with id {capability_id!r}.")
+ )
+ return _dump(
+ CapabilityDetailsResponse(
+ message=f"{tool.description} Run it with run_capability(id='{entry.id}').",
+ capability=entry.listing(),
+ parameters=tool.parameters,
+ )
+ )
+
+
+def _capability_search(query: str) -> str:
+ """The real index, so a search here ranks what production ranks.
+
+ The registry is built in-process from the block and tool registries, the
+ same way the retrieval benchmark builds it, so this needs no database.
+ """
+ result = get_registry().search(query)
+ hits = list(result.hits)
+ if not hits and not result.fallback:
+ return _dump(
+ NoResultsResponse(message=f"Nothing on the platform matches {query!r}.")
+ )
+ return _dump(
+ CapabilityListResponse(
+ message=f"Found {len(hits)} capabilities.",
+ query=query,
+ capabilities=[hit.entry.listing() for hit in hits],
+ count=len(hits),
+ fallback=[hit.entry.listing() for hit in result.fallback],
+ service=result.service,
+ )
+ )
+
+
def _library_result(expert: Expert | None) -> ToolResponseBase:
"""A library search from a fresh hire: exactly its installed workflows.
An empty library made the model doubt the user's own run report."""
diff --git a/autogpt_platform/backend/backend/copilot/eval/style/generation_test.py b/autogpt_platform/backend/backend/copilot/eval/style/generation_test.py
index d03c0c0374..472321a2ce 100644
--- a/autogpt_platform/backend/backend/copilot/eval/style/generation_test.py
+++ b/autogpt_platform/backend/backend/copilot/eval/style/generation_test.py
@@ -14,7 +14,7 @@ from .assembly import attach_workflows, load_fixtures, roster_experts
from .generation import (
MAX_TOOL_ROUNDS,
add_usage,
- expert_tools,
+ expert_reachable_tools,
generate_turn,
question_text,
stub_tool_result,
@@ -225,11 +225,16 @@ def test_question_text_renders_questions_and_tolerates_bad_json():
def test_stubbed_tools_stay_within_the_sessions_tool_surface():
- """Every tool the stub table answers by name is one the model is given;
- a stub for a tool that is not offered would never fire."""
+ """Every tool the stub table answers by name is one the session can reach;
+ a stub for a tool that is out of reach would never fire.
+
+ Most of these are deferred now — the model calls them through
+ ``run_capability``, which ``stub_tool_result`` unwraps — so the question
+ is reachability, not whether they appear in the schema list.
+ """
from .generation import DELEGATION_TOOLS, HANDOFF_TOOL, LIBRARY_SEARCH_TOOLS
- offered = {t["function"]["name"] for t in expert_tools(roster_experts(["Max"])[0])}
+ reachable = expert_reachable_tools(roster_experts(["Max"])[0])
named = {
*LIBRARY_SEARCH_TOOLS,
*DELEGATION_TOOLS,
@@ -243,14 +248,39 @@ def test_stubbed_tools_stay_within_the_sessions_tool_surface():
"list_agent_triggers",
"list_workspace_files",
}
- assert named <= offered
+ assert named <= reachable
+
+
+def test_the_stub_table_is_reached_through_run_capability():
+ """The unwrap is what keeps every stub above firing after the swap."""
+ from .generation import called_name, stub_tool_result
+
+ assert called_name("run_capability", '{"id": "tool:memory_search"}') == (
+ "memory_search"
+ )
+ assert called_name("memory_search", "{}") == "memory_search"
+ answered = stub_tool_result(
+ "run_capability", '{"id": "tool:list_schedules", "input": {}}', None, []
+ )
+ assert "No schedules yet." in answered
+
+
+def test_a_malformed_call_still_gets_an_answer():
+ """A stub that raises ends the eval run; one that answers scores the turn.
+
+ The model writes these arguments, so `input` is not necessarily an object.
+ """
+ from .generation import stub_tool_result
+
+ for arguments in ('{"id": "tool:list_schedules", "input": "oops"}', "not json"):
+ assert stub_tool_result("run_capability", arguments, None, [])
def test_expert_session_loses_staffing_tools_and_keeps_memory():
- names = {t["function"]["name"] for t in expert_tools(roster_experts(["Max"])[0])}
+ names = expert_reachable_tools(roster_experts(["Max"])[0])
assert "memory_search" in names
assert "hire_expert" not in names
assert "update_expert_soul" in names
- plain = {t["function"]["name"] for t in expert_tools(None)}
+ plain = expert_reachable_tools(None)
assert "hire_expert" in plain
assert "update_expert_soul" not in plain
diff --git a/autogpt_platform/backend/backend/copilot/expert_context.py b/autogpt_platform/backend/backend/copilot/expert_context.py
index 69aaf4ec29..4ee997bd3e 100644
--- a/autogpt_platform/backend/backend/copilot/expert_context.py
+++ b/autogpt_platform/backend/backend/copilot/expert_context.py
@@ -418,7 +418,8 @@ def _team_rule(*, delegation_enabled: bool, exclude_expert_id: str | None) -> st
"Never impersonate a teammate or guess at their domain yourself. "
"Before anything that commits this company (money, dates, "
"guarantees, policy) leaves the conversation, have one of them "
- "check it with `consult_teammate`."
+ "check it with "
+ '`run_capability(id="tool:consult_teammate", input={...})`.'
)
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index db38221b91..f756a3995a 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -5,18 +5,25 @@
- ``AutoPilotBlock`` reads four block-input fields and builds one instance.
- ``stream_chat_completion_sdk`` applies it when constructing
``ClaudeAgentOptions.allowed_tools`` / ``disallowed_tools``.
-- ``run_block`` reads it from the contextvar to gate block execution.
+- ``run_capability`` reads it from the contextvar to gate block execution.
- Recursive (sub-agent) invocations merge parent and child so children
can only be *more* restrictive, never more permissive.
Tool names
----------
Users specify the **short name** as it appears in ``TOOL_REGISTRY`` (e.g.
-``run_block``, ``web_fetch``) or as an SDK built-in (e.g. ``Read``,
+``run_capability``, ``web_fetch``) or as an SDK built-in (e.g. ``Read``,
``Task``, ``WebSearch``). Internally these are mapped to the full SDK
-format (``mcp__copilot__run_block``, ``Read``, …) by
+format (``mcp__copilot__run_capability``, ``Read``, …) by
:func:`apply_tool_permissions`.
+Two names are **capability gates** rather than tools: ``run_block`` and
+``run_mcp_tool`` no longer exist as tools (blocks and MCP servers run through
+``run_capability``), but denying them still denies that whole kind of
+capability, so saved graphs keep their meaning. Retired discovery names
+(``find_block``, ``get_mcp_guide``, ``continue_run_block``) are accepted for
+saved graphs and mapped to their registry equivalents.
+
Block identifiers
-----------------
Each entry in ``blocks`` may be one of:
@@ -40,9 +47,11 @@ are allowed.
``blocks_exclude`` follows the same pattern for ``blocks``.
Denying a capability denies the tools that extend it (see
-``_IMPLIED_DENIALS``). A blacklist is written against the tools that exist
-when it is written, so a later tool that reaches the same resource would
-otherwise be silently regained by every existing blacklist.
+``_IMPLIED_DENIALS``); allowing a capability gate allows the tool that now
+performs it (see ``_IMPLIED_GRANTS``). Either list is written against the
+tools that exist when it is written, so a later tool that reaches the same
+resource would otherwise be silently regained by every existing blacklist,
+and a renamed one silently lost by every existing whitelist.
Recursion inheritance
---------------------
@@ -85,7 +94,6 @@ ToolName = Literal[
"confirm_expert_soul_update",
"connect_integration",
"consult_teammate",
- "continue_run_block",
"create_agent",
"create_feature_request",
"create_folder",
@@ -97,18 +105,18 @@ ToolName = Literal[
"delete_schedule",
"delete_skill",
"delete_workspace_file",
+ "describe_capability",
"edit_agent",
"edit_chat_platform_message",
"enter_agent_building_mode",
"expert_onboarding",
"find_agent",
- "find_block",
+ "find_capability",
"find_library_agent",
"find_session",
"fix_agent_graph",
"get_agent_building_guide",
"get_doc_page",
- "get_mcp_guide",
"get_platform_info",
"get_sub_session_result",
"grant_expert_credential",
@@ -141,11 +149,11 @@ ToolName = Literal[
"read_workspace_file",
"remove_expert_workflow",
"request_credential_grant",
+ "resume_capability",
"resume_schedule",
"revoke_expert_credential",
"run_agent",
- "run_block",
- "run_mcp_tool",
+ "run_capability",
"run_sub_session",
"schedule_followup",
"search_docs",
@@ -162,6 +170,9 @@ ToolName = Literal[
"web_fetch",
"web_search",
"write_workspace_file",
+ # Capability gates (not tools): deny to withhold a whole kind of capability
+ "run_block",
+ "run_mcp_tool",
# SDK built-ins
"Agent",
"Edit",
@@ -177,7 +188,21 @@ ToolName = Literal[
# Frozen set of all valid tool names — derived from the Literal.
ALL_TOOL_NAMES: frozenset[str] = frozenset(get_args(ToolName))
-DISABLED_LEGACY_TOOL_NAMES: frozenset[str] = frozenset()
+# Capability gates: names a permission list may deny to withhold every block
+# (``run_block``) or every MCP server (``run_mcp_tool``) from ``run_capability``.
+BLOCK_GATE = "run_block"
+MCP_GATE = "run_mcp_tool"
+CAPABILITY_GATE_NAMES: frozenset[str] = frozenset({BLOCK_GATE, MCP_GATE})
+
+# Retired tool names -> the registry tool that replaced them. Accepted in
+# saved ``AutoPilotBlock`` permission lists and translated on evaluation.
+LEGACY_TOOL_ALIASES: dict[str, str] = {
+ "find_block": "find_capability",
+ "get_mcp_guide": "find_capability",
+ "continue_run_block": "resume_capability",
+}
+
+DISABLED_LEGACY_TOOL_NAMES: frozenset[str] = frozenset(LEGACY_TOOL_ALIASES)
"""Tool names accepted only for backwards compatibility with saved graphs.
These names are intentionally absent from ``ToolName`` and
@@ -198,8 +223,10 @@ SDK_BUILTIN_TOOL_NAMES: frozenset[str] = frozenset(
{"Agent", "Edit", "Glob", "Grep", "Read", "Task", "WebSearch", "Write"}
)
-# Platform tool names — everything that isn't an SDK built-in.
-PLATFORM_TOOL_NAMES: frozenset[str] = ALL_TOOL_NAMES - SDK_BUILTIN_TOOL_NAMES
+# Platform tool names — everything that isn't an SDK built-in or a gate.
+PLATFORM_TOOL_NAMES: frozenset[str] = (
+ ALL_TOOL_NAMES - SDK_BUILTIN_TOOL_NAMES - CAPABILITY_GATE_NAMES
+)
# Compiled regex patterns for block identifier classification.
_FULL_UUID_RE = re.compile(
@@ -228,6 +255,27 @@ def _with_implied_denials(denied: frozenset[str]) -> frozenset[str]:
)
+# Tools that a whitelist entry must allow alongside the capability named.
+#
+# The mirror of the above: a whitelist is also written against the tools that
+# existed when it was written, and the gates are the one case where the tool
+# that does the work was renamed out from under it. A saved list naming
+# ``run_block`` meant "you may run blocks", which now happens through
+# ``run_capability`` -- a name no existing list can contain. Without this the
+# gate stays open and the tool that opens it is never handed to the model.
+_IMPLIED_GRANTS: dict[str, tuple[str, ...]] = {
+ BLOCK_GATE: ("run_capability",),
+ MCP_GATE: ("run_capability",),
+}
+
+
+def _with_implied_grants(allowed: frozenset[str]) -> frozenset[str]:
+ """Expand an allow set with the tools its entries imply."""
+ return allowed.union(
+ implied for name in allowed for implied in _IMPLIED_GRANTS.get(name, ())
+ )
+
+
# ---------------------------------------------------------------------------
# Helper — block identifier matching
# ---------------------------------------------------------------------------
@@ -258,7 +306,7 @@ class CopilotPermissions(BaseModel):
"""Capability filter for a single copilot execution.
Attributes:
- tools: Tool names to filter (short names, e.g. ``run_block``).
+ tools: Tool names to filter (short names, e.g. ``run_capability``).
tools_exclude: When True (default) ``tools`` is a blacklist;
when False it is a whitelist. Ignored when *tools* is empty.
blocks: Block identifiers (name, full UUID, or 8-char partial UUID).
@@ -289,10 +337,10 @@ class CopilotPermissions(BaseModel):
"""
if not self.tools:
return frozenset(all_tools)
- tool_set = frozenset(self.tools)
+ tool_set = frozenset(LEGACY_TOOL_ALIASES.get(t, t) for t in self.tools)
if self.tools_exclude:
return all_tools - _with_implied_denials(tool_set)
- return all_tools & tool_set
+ return all_tools & _with_implied_grants(tool_set)
# ------------------------------------------------------------------
# Block helpers
@@ -391,6 +439,14 @@ def validate_tool_names(tools: list[str]) -> list[str]:
_tool_names_checked = False
+def denied_tool_names(permissions: CopilotPermissions | None) -> frozenset[str]:
+ """Short names *permissions* withholds from the turn (empty when none)."""
+ if permissions is None or permissions.is_empty():
+ return frozenset()
+ all_tools = all_known_tool_names()
+ return all_tools - permissions.effective_allowed_tools(all_tools)
+
+
def _assert_tool_names_consistent() -> None:
"""Verify that ``PLATFORM_TOOL_NAMES`` matches ``TOOL_REGISTRY`` keys.
diff --git a/autogpt_platform/backend/backend/copilot/permissions_aliases_test.py b/autogpt_platform/backend/backend/copilot/permissions_aliases_test.py
new file mode 100644
index 0000000000..f6d48828f3
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/permissions_aliases_test.py
@@ -0,0 +1,68 @@
+"""Legacy tool names in saved permission lists keep their meaning: retired
+discovery names alias to the registry tools, and ``run_block`` /
+``run_mcp_tool`` survive as capability gates."""
+
+from backend.copilot.permissions import (
+ ALL_TOOL_NAMES,
+ BLOCK_GATE,
+ CAPABILITY_GATE_NAMES,
+ MCP_GATE,
+ PLATFORM_TOOL_NAMES,
+ CopilotPermissions,
+ denied_tool_names,
+ validate_tool_names,
+)
+from backend.copilot.tools import TOOL_REGISTRY
+
+
+def test_gates_are_permission_names_but_not_tools():
+ assert CAPABILITY_GATE_NAMES <= ALL_TOOL_NAMES
+ assert CAPABILITY_GATE_NAMES.isdisjoint(PLATFORM_TOOL_NAMES)
+ assert BLOCK_GATE not in TOOL_REGISTRY and MCP_GATE not in TOOL_REGISTRY
+ assert PLATFORM_TOOL_NAMES == frozenset(TOOL_REGISTRY)
+
+
+def test_legacy_whitelist_maps_to_registry_tools():
+ perms = CopilotPermissions(
+ tools=["find_block", "run_block", "continue_run_block"], tools_exclude=False
+ )
+ allowed = perms.effective_allowed_tools(ALL_TOOL_NAMES)
+ assert {"find_capability", "resume_capability", BLOCK_GATE} <= allowed
+
+
+def test_allowing_a_gate_allows_the_tool_that_runs_it():
+ """A saved whitelist says what the agent may do, not what we named it.
+
+ ``run_block`` meant "you may run blocks"; the tool that runs them is now
+ ``run_capability``, which no list written before the rename can contain.
+ Keep the gate open but withhold the tool and the agent can search and is
+ permitted to run, with nothing to run it with.
+ """
+ for gate in (BLOCK_GATE, MCP_GATE):
+ allowed = CopilotPermissions(
+ tools=[gate], tools_exclude=False
+ ).effective_allowed_tools(ALL_TOOL_NAMES)
+ assert {gate, "run_capability"} <= allowed
+ # The grant is implied by the gate, not handed out to every whitelist.
+ assert "run_capability" not in CopilotPermissions(
+ tools=["find_block"], tools_exclude=False
+ ).effective_allowed_tools(ALL_TOOL_NAMES)
+
+
+def test_legacy_blacklist_denies_the_gate():
+ perms = CopilotPermissions(tools=["run_block"])
+ allowed = perms.effective_allowed_tools(ALL_TOOL_NAMES)
+ assert BLOCK_GATE not in allowed and "run_capability" in allowed
+ assert denied_tool_names(perms) == frozenset({BLOCK_GATE})
+
+
+def test_legacy_names_validate():
+ assert (
+ validate_tool_names(["find_block", "get_mcp_guide", "continue_run_block"]) == []
+ )
+ assert validate_tool_names(["not_a_tool"]) == ["not_a_tool"]
+
+
+def test_denied_tool_names_empty_without_filter():
+ assert denied_tool_names(None) == frozenset()
+ assert denied_tool_names(CopilotPermissions()) == frozenset()
diff --git a/autogpt_platform/backend/backend/copilot/permissions_test.py b/autogpt_platform/backend/backend/copilot/permissions_test.py
index c3bab4af4b..c5a063c2fd 100644
--- a/autogpt_platform/backend/backend/copilot/permissions_test.py
+++ b/autogpt_platform/backend/backend/copilot/permissions_test.py
@@ -6,6 +6,7 @@ import pytest
from backend.copilot.permissions import (
ALL_TOOL_NAMES,
+ CAPABILITY_GATE_NAMES,
DREAM_PERMISSIONS,
PLATFORM_TOOL_NAMES,
SDK_BUILTIN_TOOL_NAMES,
@@ -365,7 +366,11 @@ class TestApplyToolPermissions:
def test_empty_permissions_returns_base_unchanged(self, mocker):
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
- return_value=["mcp__copilot__run_block", "mcp__copilot__web_fetch", "Task"],
+ return_value=[
+ "mcp__copilot__run_capability",
+ "mcp__copilot__web_fetch",
+ "Task",
+ ],
)
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",
@@ -373,18 +378,18 @@ class TestApplyToolPermissions:
)
mocker.patch(
"backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
- {"run_block": object(), "web_fetch": object()},
+ {"run_capability": object(), "web_fetch": object()},
)
perms = CopilotPermissions()
allowed, disallowed = apply_tool_permissions(perms, use_e2b=False)
- assert "mcp__copilot__run_block" in allowed
+ assert "mcp__copilot__run_capability" in allowed
assert "mcp__copilot__web_fetch" in allowed
def test_blacklist_removes_tool(self, mocker):
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
- "mcp__copilot__run_block",
+ "mcp__copilot__run_capability",
"mcp__copilot__web_fetch",
"mcp__copilot__bash_exec",
"Task",
@@ -397,25 +402,27 @@ class TestApplyToolPermissions:
mocker.patch(
"backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
{
- "run_block": object(),
+ "run_capability": object(),
"web_fetch": object(),
"bash_exec": object(),
},
)
mocker.patch(
"backend.copilot.permissions.all_known_tool_names",
- return_value=frozenset(["run_block", "web_fetch", "bash_exec", "Task"]),
+ return_value=frozenset(
+ ["run_capability", "web_fetch", "bash_exec", "Task"]
+ ),
)
perms = CopilotPermissions(tools=["bash_exec"], tools_exclude=True)
allowed, _ = apply_tool_permissions(perms, use_e2b=False)
assert "mcp__copilot__bash_exec" not in allowed
- assert "mcp__copilot__run_block" in allowed
+ assert "mcp__copilot__run_capability" in allowed
def test_whitelist_keeps_only_listed(self, mocker):
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
- "mcp__copilot__run_block",
+ "mcp__copilot__run_capability",
"mcp__copilot__web_fetch",
"Task",
"WebSearch",
@@ -427,15 +434,17 @@ class TestApplyToolPermissions:
)
mocker.patch(
"backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
- {"run_block": object(), "web_fetch": object()},
+ {"run_capability": object(), "web_fetch": object()},
)
mocker.patch(
"backend.copilot.permissions.all_known_tool_names",
- return_value=frozenset(["run_block", "web_fetch", "Task", "WebSearch"]),
+ return_value=frozenset(
+ ["run_capability", "web_fetch", "Task", "WebSearch"]
+ ),
)
- perms = CopilotPermissions(tools=["run_block"], tools_exclude=False)
+ perms = CopilotPermissions(tools=["run_capability"], tools_exclude=False)
allowed, _ = apply_tool_permissions(perms, use_e2b=False)
- assert "mcp__copilot__run_block" in allowed
+ assert "mcp__copilot__run_capability" in allowed
assert "mcp__copilot__web_fetch" not in allowed
assert "Task" not in allowed
@@ -444,7 +453,7 @@ class TestApplyToolPermissions:
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
- "mcp__copilot__run_block",
+ "mcp__copilot__run_capability",
"mcp__copilot__read_tool_result",
"Task",
],
@@ -455,11 +464,11 @@ class TestApplyToolPermissions:
)
mocker.patch(
"backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
- {"run_block": object()},
+ {"run_capability": object()},
)
mocker.patch(
"backend.copilot.permissions.all_known_tool_names",
- return_value=frozenset(["run_block", "Read", "Task"]),
+ return_value=frozenset(["run_capability", "Read", "Task"]),
)
# Explicitly blacklist Read
perms = CopilotPermissions(tools=["Read"], tools_exclude=True)
@@ -467,7 +476,7 @@ class TestApplyToolPermissions:
assert (
"mcp__copilot__read_tool_result" in allowed
) # always preserved for SDK internals
- assert "mcp__copilot__run_block" in allowed
+ assert "mcp__copilot__run_capability" in allowed
assert "Task" in allowed
def test_read_tool_always_included_with_narrow_whitelist(self, mocker):
@@ -475,7 +484,7 @@ class TestApplyToolPermissions:
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
- "mcp__copilot__run_block",
+ "mcp__copilot__run_capability",
"mcp__copilot__read_tool_result",
"Task",
],
@@ -486,26 +495,26 @@ class TestApplyToolPermissions:
)
mocker.patch(
"backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
- {"run_block": object()},
+ {"run_capability": object()},
)
mocker.patch(
"backend.copilot.permissions.all_known_tool_names",
- return_value=frozenset(["run_block", "Read", "Task"]),
+ return_value=frozenset(["run_capability", "Read", "Task"]),
)
- # Whitelist only run_block — Read not listed
- perms = CopilotPermissions(tools=["run_block"], tools_exclude=False)
+ # Whitelist only run_capability — Read not listed
+ perms = CopilotPermissions(tools=["run_capability"], tools_exclude=False)
allowed, _ = apply_tool_permissions(perms, use_e2b=False)
assert (
"mcp__copilot__read_tool_result" in allowed
) # always preserved for SDK internals
- assert "mcp__copilot__run_block" in allowed
+ assert "mcp__copilot__run_capability" in allowed
def test_e2b_file_tools_included_when_sdk_builtin_whitelisted(self, mocker):
"""In E2B mode, whitelisting 'Read' must include mcp__copilot__read_file."""
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
- "mcp__copilot__run_block",
+ "mcp__copilot__run_capability",
"mcp__copilot__read_tool_result",
"mcp__copilot__read_file",
"mcp__copilot__write_file",
@@ -518,21 +527,23 @@ class TestApplyToolPermissions:
)
mocker.patch(
"backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
- {"run_block": object()},
+ {"run_capability": object()},
)
mocker.patch(
"backend.copilot.permissions.all_known_tool_names",
- return_value=frozenset(["run_block", "Read", "Write", "Task"]),
+ return_value=frozenset(["run_capability", "Read", "Write", "Task"]),
)
mocker.patch(
"backend.copilot.sdk.e2b_file_tools.E2B_FILE_TOOL_NAMES",
["read_file", "write_file", "edit_file", "glob", "grep"],
)
- # Whitelist Read and run_block — E2B read_file should be included
- perms = CopilotPermissions(tools=["Read", "run_block"], tools_exclude=False)
+ # Whitelist Read and run_capability — E2B read_file should be included
+ perms = CopilotPermissions(
+ tools=["Read", "run_capability"], tools_exclude=False
+ )
allowed, _ = apply_tool_permissions(perms, use_e2b=True)
assert "mcp__copilot__read_file" in allowed
- assert "mcp__copilot__run_block" in allowed
+ assert "mcp__copilot__run_capability" in allowed
# Write not whitelisted — write_file should NOT be included
assert "mcp__copilot__write_file" not in allowed
@@ -541,7 +552,7 @@ class TestApplyToolPermissions:
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
- "mcp__copilot__run_block",
+ "mcp__copilot__run_capability",
"mcp__copilot__Write",
"mcp__copilot__Edit",
"mcp__copilot__read_file",
@@ -555,17 +566,19 @@ class TestApplyToolPermissions:
)
mocker.patch(
"backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
- {"run_block": object()},
+ {"run_capability": object()},
)
mocker.patch(
"backend.copilot.permissions.all_known_tool_names",
- return_value=frozenset(["run_block", "Read", "Write", "Edit", "Task"]),
+ return_value=frozenset(["run_capability", "Read", "Write", "Edit", "Task"]),
+ )
+ # Whitelist Write and run_capability — mcp__copilot__Write should be included
+ perms = CopilotPermissions(
+ tools=["Write", "run_capability"], tools_exclude=False
)
- # Whitelist Write and run_block — mcp__copilot__Write should be included
- perms = CopilotPermissions(tools=["Write", "run_block"], tools_exclude=False)
allowed, _ = apply_tool_permissions(perms, use_e2b=False)
assert "mcp__copilot__Write" in allowed
- assert "mcp__copilot__run_block" in allowed
+ assert "mcp__copilot__run_capability" in allowed
# Edit not whitelisted — should NOT be included
assert "mcp__copilot__Edit" not in allowed
# read_tool_result always preserved for SDK internals
@@ -576,7 +589,7 @@ class TestApplyToolPermissions:
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
- "mcp__copilot__run_block",
+ "mcp__copilot__run_capability",
"mcp__copilot__read_tool_result",
"mcp__copilot__read_file",
"Task",
@@ -588,11 +601,11 @@ class TestApplyToolPermissions:
)
mocker.patch(
"backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
- {"run_block": object()},
+ {"run_capability": object()},
)
mocker.patch(
"backend.copilot.permissions.all_known_tool_names",
- return_value=frozenset(["run_block", "Read", "Task"]),
+ return_value=frozenset(["run_capability", "Read", "Task"]),
)
mocker.patch(
"backend.copilot.sdk.e2b_file_tools.E2B_FILE_TOOL_NAMES",
@@ -602,7 +615,7 @@ class TestApplyToolPermissions:
perms = CopilotPermissions(tools=["Read"], tools_exclude=True)
allowed, _ = apply_tool_permissions(perms, use_e2b=True)
assert "mcp__copilot__read_file" not in allowed
- assert "mcp__copilot__run_block" in allowed
+ assert "mcp__copilot__run_capability" in allowed
# mcp__copilot__read_tool_result is always preserved for SDK internals
assert "mcp__copilot__read_tool_result" in allowed
@@ -643,7 +656,10 @@ class TestSdkBuiltinToolNames:
def test_all_tool_names_is_union(self):
"""ALL_TOOL_NAMES must equal PLATFORM_TOOL_NAMES | SDK_BUILTIN_TOOL_NAMES."""
- assert ALL_TOOL_NAMES == PLATFORM_TOOL_NAMES | SDK_BUILTIN_TOOL_NAMES
+ assert (
+ ALL_TOOL_NAMES
+ == PLATFORM_TOOL_NAMES | SDK_BUILTIN_TOOL_NAMES | CAPABILITY_GATE_NAMES
+ )
def test_no_overlap_between_platform_and_sdk(self):
"""Platform and SDK built-in names must not overlap."""
diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.py
index b36c227048..27b7574ceb 100644
--- a/autogpt_platform/backend/backend/copilot/prompting.py
+++ b/autogpt_platform/backend/backend/copilot/prompting.py
@@ -131,88 +131,50 @@ After building the file, reference it with `@@agptfile:` in other tools:
non-overlapping scope to avoid redundant searches.
-### Tool Discovery Priority — `find_block` is MANDATORY before any "no integration" reply
-
-When the user asks to interact with a service, integration, platform, or API,
-your **first action** in that turn MUST be a `find_block` call with the
-service name. This is non-negotiable. Your prior knowledge of which
-integrations exist is unreliable — the block registry changes constantly
-and is the only source of truth.
-
-Order of fallbacks (only after `find_block` returns nothing usable):
-
-1. **`find_block` first — ALWAYS.** Search platform blocks with the service
- name (e.g. `find_block(query="linkedin post")`,
- `find_block(query="shopify orders")`). Hundreds of built-in blocks exist
- (Google Sheets, Docs, Calendar, Gmail, Slack, GitHub, LinkedIn via Ayrshare,
- etc.). Most "obscure" integrations have a block.
-
-2. **`run_mcp_tool` — MANDATORY when `find_block` returns nothing.** Don't
- stop at "no integration exists" after one `find_block` miss. Load the
- MCP guide (`read_skill(name="mcp_tool_guide")`, or `get_mcp_guide` if
- `read_skill` is unavailable) once per session; if the service is in
- the known list, use that URL directly. Otherwise **web-search for the
- service's official MCP server URL** (e.g. "`<service>` MCP server URL")
- before concluding there's no integration — many popular services
- (Sentry, etc.) aren't in the hardcoded list but do host an MCP server.
-
- Before calling `run_mcp_tool` on a search-returned URL, **verify the
- server's hostname matches the service** (e.g. `mcp.sentry.dev` for
- Sentry, `mcp.<service>.com` / `mcp.<service>.dev` / vendor-owned
- domain). Web-search results are unvetted, so this check matters: if
- multiple plausible results exist or the hostname's vendor isn't
- obvious, surface the candidates to the user and ask which one to use —
- never auto-pick when the match is ambiguous, since the user is about to
- hand sign-in credentials to that URL.
-
- **For "just connect" intent** (user says "connect to X" / "sign in to
- X" with no action yet), call `run_mcp_tool(server_url,
- surface_connect_card=true)` — the tool returns only the sign-in card,
- skipping the network call. The card renders as "Connected to X —
- Reconnect" when creds already exist, or "Connect X" when not. Use this
- instead of discovery-only calls so the user always sees visible state.
-
- **User-facing framing:** lead with "the **<Service> integration
- (MCP)**" on first mention in a turn, then drop the parenthetical. Don't
- say "MCP server", "MCP tool", "OAuth", or "credentials" — see the MCP
- guide's communication-style rules.
-
-3. **`SendAuthenticatedWebRequestBlock`** — If no block AND no MCP server
- exists (after `find_block`, the known hosted list, AND a web search for
- an MCP server), use
- `SendAuthenticatedWebRequestBlock` with existing host-scoped
- credentials. Check available credentials via `connect_integration`.
-
-4. **Manual API call** — As a last resort, guide the user to set up
- credentials and use `SendAuthenticatedWebRequestBlock` with direct API
- calls.
+### Discovery — `find_capability` is MANDATORY before any "no integration" reply
+
+Everything beyond your eager tools lives in one registry: integrations
+(blocks), MCP servers and deferred platform tools. Your prior knowledge of
+what exists is unreliable; the registry is the source of truth.
+
+When the user asks to interact with a service, integration, platform or API,
+your **first action** in that turn is `find_capability(query="<service>
+<action>")`. Results are ranked and show `connected` for each service. Then:
+
+1. `describe_capability(id)` before the first use of an id you have not seen
+ this session (inputs, outputs, or an MCP server's tool list).
+2. `run_capability(id, input)` to act. Never guess or fabricate ids — take
+ them from `find_capability`. `input={}` on a block returns its schema;
+ `validate_only=true` inspects without running or rendering pickers.
+3. `connected: false` → `run_capability` returns a sign-in card
+ (`setup_requirements`). Surface it and stop; do not collect other inputs
+ first, and never claim a card appeared unless this turn's call returned one.
+4. `review_required` → tell the user; after they approve, call
+ `resume_capability(review_id)`.
+
+Entries of class `primitive` (HTTP request, SQL, code) are generic building
+blocks: prefer a matching `service` capability and use a primitive only when
+no service exists or the user asked for it. A service query also lists up to
+three primitives under `fallback`; `SendAuthenticatedWebRequestBlock` calls a
+vendor API directly with the user's host-scoped credentials when nothing else
+covers the service.
+
+If `find_capability` returns nothing for a named service, `web_search` for
+"<service> MCP server" and call `run_capability` with the server URL as `id`.
+Verify the hostname belongs to the vendor first; if several candidates exist,
+ask the user which to use — never auto-pick a URL the user is about to sign
+in to. Writes to servers outside the catalog pause for review.
+
+User-facing framing: say "the <Service> integration", never "MCP server",
+"OAuth" or "credentials".
### Anti-pattern: refusing without searching (CRITICAL)
-**Never** emit any variant of these without **both** a preceding
-`find_block` call AND, if `find_block` returned no usable match, a
-web-search for an MCP server in the current turn:
-
-- "We don't have a native X integration yet."
-- "X isn't supported on the platform."
-- "We can't do X / I can't access X."
-- "There's no block for X."
-- Any feature-request flow ("I'll flag this as a requested integration").
-
-Without **both** searches you do not yet know whether the service exists.
-Pivoting to a workaround before exhausting both is a known regression that
-overrides any worked example earlier in this prompt.
-
-Correct flow for *any* integration request:
-
-```
-1. find_block(query="<service> <action>")
-2. Matching block → use it (validate_only to inspect).
-3. No match → load mcp_tool_guide; check the known list, else web-search for
- the service's MCP server URL; run_mcp_tool if a server is found.
-4. Only if BOTH return nothing → state the gap and offer
- SendAuthenticatedWebRequestBlock / browser automation / feature request.
-```
+**Never** say "we don't have an X integration", "X isn't supported", "I can't
+access X", "there's no block for X", or open a feature request without a
+`find_capability` call for X in the current turn and, if it returned nothing,
+the MCP web search above. Pivoting to a workaround before both is a known
+regression that overrides any worked example earlier in this prompt.
### Asking the user questions — use `ask_question`
When your turn ends blocked on the user's input — a decision, a missing
@@ -244,7 +206,7 @@ copilot's) across all chats, not only the ones created here.
- Use `TodoWrite` to track the plan once the job has 3+ distinct steps.
- Delegate self-contained subtasks to `run_sub_session` to keep their
intermediate tool calls out of the parent context.
-- Do NOT invoke `AutoPilotBlock` via `run_block`; use `run_sub_session`
+- Do NOT invoke `AutoPilotBlock` via `run_capability`; use `run_sub_session`
instead.
- For multi-step build/edit work, maintain a `build_state.json` workspace
file recording the identifiers you will need again: library agent IDs +
@@ -287,8 +249,8 @@ guides + user-distilled know-how). Treat it as the canonical answer to
description or triggers, call `read_skill(name)` BEFORE planning the
work — the skill body usually contains the exact constraints, gotchas,
or block schemas you would otherwise rediscover the hard way.
-Built-in skills like `agent_building_guide` and `mcp_tool_guide`
-are loaded the same way as user-distilled ones.
+The built-in `agent_building_guide` skill is loaded the same way as
+user-distilled ones.
**Distill after succeeding — proactively, without being asked.** When
you finish a non-trivial multi-step procedure that is likely to recur
@@ -336,83 +298,53 @@ The index is a finite resource (~50 slots/user); you can `list_skills`
to inspect the current registry and `delete_skill` to remove stale
entries.
-### Picker-backed inputs via `run_block` (READ BEFORE CALLING)
+### Picker-backed inputs (READ BEFORE CALLING)
-Some block input fields are populated by a platform-rendered picker at
-run time — the user clicks a button, authenticates, and selects a
-resource in one step. **The picker is the ONLY source of the hidden
-credentials attached to the selected value.** A bare ID or URL will
-never authenticate. You can spot a picker field by a `format` hint or
-an `auto_credentials` entry in the schema returned by `find_block`.
+Some block inputs are filled by a platform-rendered picker: the user clicks,
+authenticates and selects a resource in one step, and **the picker is the
+only source of the hidden credentials attached to the value**. A bare ID or
+URL never authenticates. You can spot a picker field by a `format` hint or an
+`auto_credentials` entry in the schema from `describe_capability`.
-**The correct flow — just call `run_block` with the field set to
-`null` (or omit it for non-required fields); the platform handles the
-picker and credentials.**
+**The correct flow — call `run_capability` with the field set to `null` (or
+omit it when optional); the platform handles the picker and credentials.**
-✅ Correct — triggers the inline picker:
-```
-run_block(block_id="...", input_data={"<picker_field>": null, ...other inputs...})
-```
+✅ `run_capability(id="block:...", input={"<picker_field>": null, ...})`
-The tool returns a setup card with the picker in chat. The user picks
-the resource, and `run_block` is re-invoked automatically with the
-full picker payload (including the hidden credentials field) merged
-in. You do NOT need to collect URLs, IDs, or credentials from the
-user — just call the tool.
-
-❌ Do NOT:
-- Ask the user for a URL, ID, or any identifier for a picker-backed
- resource before calling `run_block`. The picker inside the setup
- card is the answer.
-- Hardcode an ID parsed from a URL the user happens to mention — a
- bare ID has no attached credentials and the block fails at auth.
-- Refuse the task ("I can't access private resources") — you can, via
- the picker. Call `run_block` first.
-
-**Chained calls**: if a prior tool already returned a full picker
-object (with its hidden credentials field attached), you MAY pass that
-object through as-is to a downstream `run_block`; do not strip or
-modify its fields.
+The tool returns a setup card with the picker in chat. The user picks the
+resource and `run_capability` is re-invoked automatically with the full
+picker payload merged in. Do NOT ask the user for a URL or ID, do NOT
+hardcode an ID parsed from a URL they mentioned, and do NOT refuse ("I can't
+access private resources") — call the tool first. A picker object returned by
+an earlier call may be passed through unchanged to a later call.
### Credentials & sign-in surfacing — CRITICAL
-When the user asks to run something that needs credentials (a block, an
-agent, an MCP server, or an authenticated web request) and the user may
-not have them yet, these rules apply:
-
-**1. Surface the sign-in card EAGERLY — in the same turn, before
-collecting other inputs.** Call `connect_integration(provider=...)`
-(or `run_agent` / `run_block`) immediately. Do not wait until you have
-the URL / resource ID / other parameters. The user can connect in
-parallel with answering follow-up questions. A frequent failure mode is
-asking "what URL should I use?" without ever emitting the card the user
-is supposed to click.
-
-**2. NEVER claim a card has appeared if you didn't just emit one.**
-Sentences like "a sign-in card has appeared in the chat", "I've added a
-connect button above", or "please connect it there" are CLAIMS about
-the actual UI state. You may only write such a sentence in the SAME
-turn that you have just called `connect_integration`, `run_agent`,
-`run_block`, or `run_mcp_tool` AND received a `setup_requirements`
-(or compatible) response. If you have not made that tool call yet, do
-not promise a card — call the tool first, then describe it.
-
-**3. Prefer the tool over verbal coaching.** If you would write
-"please connect your GitHub account", instead just call
-`connect_integration(provider="github")`. The card the tool surfaces
-does the job better than the sentence.
-
-**4. Connecting is not running.** When the user only asks to connect or
-sign in to a service, call `connect_integration(provider=...)` — never
-`run_block` or `run_agent`, which commit to an action the user has not
-asked for. Call those only when the user asks for the action itself.
-
-**5. The card asks for credentials, not inputs.** A setup card never
-renders a form for a block's or agent's inputs (the one exception is a
-picker-backed field, see above). Collect every other input in the chat:
-if you do not have a value, ask the user for it via `ask_question`, then
-call the tool with it once they connect. Do not tell the user to fill
-anything in on the card.
+When the user asks for something that needs credentials (a block, an agent,
+an MCP server, an authenticated web request) and may not have them yet:
+
+**1. Surface the sign-in card EAGERLY — in the same turn, before collecting
+other inputs.** Call `run_capability` (or `run_agent`) immediately; the
+`setup_requirements` response is the card. Do not wait for the URL / resource
+ID / other parameters — the user can connect while answering.
+
+**2. NEVER claim a card has appeared unless this turn's `run_capability`,
+`run_agent` or GitHub connect call returned `setup_requirements`.**
+
+**3. Prefer the tool over verbal coaching.** Instead of "please connect your
+Linear account", call the capability so the card does the job.
+
+**4. Connecting is not running.** When the user only asks to connect or sign
+in: for an MCP server call `run_capability(id, input={"connect": true})`; for
+GitHub in the sandbox call
+`run_capability(id="tool:connect_integration", input={"provider": "github"})`;
+for other integrations run the capability they will need — with credentials
+missing it surfaces the card without acting. Never run an action the user has
+not asked for.
+
+**5. The card asks for credentials, not inputs.** Collect every other input in
+chat (`ask_question` when you lack a value), then call the capability once
+they connect. Do not tell the user to fill anything in on the card.
**6. `rejection` on a `setup_requirements` response means the provider
refused a credential the user already has.** Name it only if
@@ -438,19 +370,16 @@ turn or an earlier turn you can still see:
### Pre-flight with `validate_only`
-`run_block(id, {})` is NOT always a safe probe — for blocks with no
-required inputs, it executes immediately. When you need to inspect
-what a block does or what it needs without side effects, pass
-`validate_only: true`:
+`run_capability(id, {})` is NOT always a safe probe — a block with no
+required inputs executes immediately. To inspect what a capability does or
+needs without side effects, pass `validate_only: true`:
```
-run_block(block_id="...", input_data={...}, validate_only=true)
+run_capability(id="block:...", input={...}, validate_only=true)
```
-This returns the block's input/output schema and a list of missing
-required fields — never executes, never renders picker cards, never
-charges credits. Use it when you're unsure whether a block has
-required inputs, or to plan multi-step work without committing.
+This returns the schema and the missing required fields — never executes,
+never renders picker cards, never charges credits.
"""
@@ -463,24 +392,24 @@ sandbox so `bash_exec` can access it for further processing.
The exact sandbox path is shown in the `[Sandbox copy available at ...]` note.
### GitHub CLI (`gh`) and git
-- To check if the user has their GitHub account already connected, run `gh auth status`. Always check this before running `connect_integration(provider="github")` which will ask the user to connect their GitHub regardless if it's already connected.
+- To check if the user has their GitHub account already connected, run `gh auth status`. Always check this before running `run_capability(id="tool:connect_integration", input={"provider": "github"})` which will ask the user to connect their GitHub regardless if it's already connected.
- If the user has connected their GitHub account, both `gh` and `git` are
pre-authenticated — use them directly without any manual login step.
`git` HTTPS operations (clone, push, pull) work automatically.
- If the token changes mid-session (e.g. user reconnects with a new token),
run `gh auth setup-git` to re-register the credential helper.
- **MANDATORY:** You MUST run `gh auth status` before EVER calling
- `connect_integration(provider="github")`. If it shows `Logged in`,
+ `run_capability(id="tool:connect_integration", input={"provider": "github"})`. If it shows `Logged in`,
proceed directly — no integration connection needed. Never skip this check.
- If `gh auth status` shows NOT logged in, or `gh`/`git` fails with an
authentication error (e.g. "authentication required", "could not read
Username", or exit code 128), THEN call
- `connect_integration(provider="github")` to surface the GitHub credentials
+ `run_capability(id="tool:connect_integration", input={"provider": "github"})` to surface the GitHub credentials
setup card so the user can connect their account. Once connected, retry
the operation.
- For operations that need broader access (e.g. private org repos, GitHub
Actions), pass the required scopes: e.g.
- `connect_integration(provider="github", scopes=["repo", "read:org"])`.
+ `run_capability(id="tool:connect_integration", input={"provider": "github", "scopes": ["repo", "read:org"]})`.
"""
@@ -729,8 +658,8 @@ def get_delegation_supplement() -> str:
- **Delegated work is yours to land.** When the user asked for an outcome,
a delegation that returns partial, blocked, or still-running is your
next step, not your final answer:
- - Still running / timed out → keep polling `get_sub_session_result`
- until it resolves.
+ - Still running / timed out → keep polling
+ `run_capability(id="tool:get_sub_session_result")` until it resolves.
- Completed but the outcome is not met → re-delegate into the SAME
`delegated_session_id`, naming exactly what remains.
- The expert asks something this conversation already answers (stack,
@@ -745,7 +674,8 @@ def get_delegation_supplement() -> str:
- Before anything that **commits the user's company** leaves this
conversation — a refund, credit, discount, price, payment, delivery or
fix date, guarantee, SLA, policy exception, or a claim that something
- is already done — run it past a teammate with `consult_teammate`.
+ is already done — run it past a teammate with
+ `run_capability(id="tool:consult_teammate", input={...})`.
- You must state the `authority` for every commitment: what the user
actually approved, in their words, or what a system confirmed. If you
cannot name the authority, that is the finding — do not send it, and
diff --git a/autogpt_platform/backend/backend/copilot/prompting_test.py b/autogpt_platform/backend/backend/copilot/prompting_test.py
index 27b5854122..7cb0e78182 100644
--- a/autogpt_platform/backend/backend/copilot/prompting_test.py
+++ b/autogpt_platform/backend/backend/copilot/prompting_test.py
@@ -62,31 +62,34 @@ class TestCredentialsSurfacingGuardrails:
class TestToolDiscoveryPriorityAntiPattern:
- """The Tool Discovery Priority section must forbid claiming a capability
- gap without calling ``find_block`` first — this is the regression the
+ """The Discovery section must forbid claiming a capability gap without
+ calling ``find_capability`` first — this is the regression the
LinkedIn-skip incident on dev (May 2026) exposed.
"""
- def test_supplement_contains_find_block_mandatory_language(self):
+ def test_supplement_contains_find_capability_mandatory_language(self):
result = prompting.get_sdk_supplement(use_e2b=False)
- # The header must signal that find_block is mandatory before any
- # "no integration" reply.
- assert "find_block` is MANDATORY" in result
+ # The header must signal that find_capability is mandatory before
+ # any "no integration" reply.
+ assert "find_capability` is MANDATORY" in result
def test_supplement_lists_the_forbidden_phrases(self):
result = prompting.get_sdk_supplement(use_e2b=False)
# The anti-pattern section must explicitly enumerate the
# phrases the model emitted in the regression so the model
# can pattern-match on its own draft and reject it.
- assert "We don't have a native X integration yet." in result
- assert "There's no block for X." in result
+ assert "we don't have an X integration" in result
+ assert "there's no block for X" in result
- def test_supplement_includes_correct_flow_template(self):
+ def test_supplement_includes_the_flow_and_no_legacy_names(self):
result = prompting.get_sdk_supplement(use_e2b=False)
- # The 3-step correct-flow block must be present so the model
- # has a concrete template to follow, not just a prohibition.
- assert "Correct flow" in result
- assert 'find_block(query="<service> <action>")' in result
+ # The numbered flow gives the model a concrete template to follow,
+ # not just a prohibition; the retired tools must not be named.
+ assert 'find_capability(query="<service>' in result
+ assert "describe_capability(id)" in result
+ assert "resume_capability(review_id)" in result
+ for legacy in ("find_block", "run_block", "run_mcp_tool", "get_mcp_guide"):
+ assert legacy not in result, legacy
class TestGraphitiMemoryScope:
diff --git a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
index bf1d570cef..a414f88e59 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
+++ b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
@@ -9,14 +9,14 @@ Use `ask_question` whenever the user's intent is ambiguous — before
starting or mid-workflow. Typical gaps: output format, delivery channel,
data source, trigger, or a choice between candidate blocks.
-Discover the platform's real options first (e.g. `find_block`), then
+Discover the platform's real options first (e.g. `find_capability`), then
call `ask_question` listing those options ("The platform supports
Gmail, Slack, and Google Docs — which for delivery?") and **wait for
the answer**.
**Skip** when the goal already specifies every dimension (e.g. "scrape
prices from Amazon and email me daily"). Data-shape questions are usually
-better answered by sampling (`run_block`, workflow step 2) than by asking
+better answered by sampling (`run_capability`, workflow step 2) than by asking
the user.
### Workflow for Creating/Editing Agents
@@ -39,7 +39,7 @@ sampling (step 2), not by deliberation.
2. **Sample real data BEFORE designing (data-driven agents)**: when the
agent will consume external data (a database, API, mailbox, feed), fetch
- a real sample **before** planning the graph: `run_block` the reader block
+ a real sample **before** planning the graph: `run_capability` the reader block
with the user's actual source. Two benefits: you design against the real
field names/types instead of guesses, and missing credentials surface
immediately as a connect card the user can complete while you continue.
@@ -65,14 +65,14 @@ sampling (step 2), not by deliberation.
always inspect the current graph first so you know exactly what to change.
Avoid using `include_graph=true` with broad keyword searches, as fetching
multiple graphs at once is expensive and consumes LLM context budget.
-5. **Discover blocks**: Call `find_block(query, for_agent_generation=true)` to
+5. **Discover blocks**: Call `find_capability(query, context="graph")` to
search for relevant blocks. This returns block IDs, names, descriptions,
and categories; to see a block's full input/output schema, call
- `run_block` with the block's id and no inputs. The `for_agent_generation=true` flag is
+ `run_capability` with the block's id and no inputs. The `context="graph"` argument is
required to surface graph-only blocks such as AgentInputBlock,
AgentDropdownInputBlock, AgentOutputBlock, OrchestratorBlock,
and WebhookBlock and MCPToolBlock. (When running MCP tools interactively
- in CoPilot outside agent generation, use `run_mcp_tool` instead.)
+ in CoPilot outside agent generation, use `run_capability` on the MCP server entry instead.)
6. **Find library agents for sub-agent composition**: Call `find_library_agent`
(default mode, no `for_creation` flag) to discover reusable agents that
can be composed as sub-agents via `AgentExecutorBlock`. This is distinct
@@ -132,7 +132,7 @@ agents call this one via `AgentExecutorBlock`, update their pinned
"nodes": [
{
"id": "<UUID v4>",
- "block_id": "<block UUID from find_block>",
+ "block_id": "<block UUID from find_capability>",
"input_default": {
"field_name": "design-time value"
},
@@ -200,7 +200,7 @@ this requirement on their own — do NOT add a throwaway base
`AgentInputBlock` alongside a specialized one. Each subclass carries its
own usage guidance (when it is required, how to configure it, how to
wire it to consumers, concrete link shape) in its block and field
-descriptions; read and follow those when `find_block` surfaces a match.
+descriptions; read and follow those when `find_capability` surfaces a match.
### Key Rules
@@ -223,7 +223,7 @@ descriptions; read and follow those when `find_block` surfaces a match.
do NOT redirect to the Builder. Credentials are set up inline as part
of the run flow: `run_agent` surfaces the setup card automatically
when credentials are missing or invalid, then proceeds to execute once
- connected. Use `connect_integration` only for a standalone provider
+ connected. Use `run_capability(id="tool:connect_integration", ...)` only for a standalone provider
setup not tied to a specific run.
- **Node spacing**: Position nodes with at least 800 X-units between them.
- **Nested properties**: Use `parentField_#_childField` notation in link
@@ -277,7 +277,7 @@ To compose agents using other agents as sub-agents:
> **Agent graph vs CoPilot direct execution**: This section covers embedding MCP
> tools as persistent nodes in an agent graph. When running MCP tools directly in
-> CoPilot (outside agent generation), use `run_mcp_tool` instead — it handles
+> CoPilot (outside agent generation), use `run_capability` on the MCP server entry instead — it handles
> server discovery and authentication interactively. Use `MCPToolBlock` here only
> when the user wants the MCP call baked into a reusable agent graph.
@@ -452,7 +452,7 @@ A minimal agent with input, processing, and output:
A **webhook trigger** runs an agent automatically when an external HTTP event
arrives. The agent must contain a webhook trigger block (surfaced by
-`find_block(..., for_agent_generation=true)`); such an agent can only be
+`find_capability(..., context="graph")`); such an agent can only be
triggered, not run manually.
**To set up a webhook trigger:** call `setup_agent_webhook_trigger` with the
@@ -480,7 +480,7 @@ Call `setup_agent_webhook_trigger` without `credentials` first: it returns a
setup card listing the available accounts per credential field. Ask the user
which to use, then call again with `credentials={<field_name>: <credential_id>}`.
If a field has no connected account, that **same card lets the user connect
-one** — do NOT also call `connect_integration` (that just shows a second,
+one** — do NOT also call `run_capability(id="tool:connect_integration", ...)` (that just shows a second,
duplicate card).
**Trigger config must come from the user, not a guess.** If the tool returns
diff --git a/autogpt_platform/backend/backend/copilot/sdk/mcp_tool_guide.md b/autogpt_platform/backend/backend/copilot/sdk/mcp_tool_guide.md
deleted file mode 100644
index dfc7a55314..0000000000
--- a/autogpt_platform/backend/backend/copilot/sdk/mcp_tool_guide.md
+++ /dev/null
@@ -1,104 +0,0 @@
-## MCP Tool Guide
-
-### Workflow
-
-`run_mcp_tool` follows a two-step pattern:
-
-1. **Discover** — call with only `server_url` to list available tools on the
- server. The response contains each tool's name, description, and a compact
- `params` summary (argument names, required ones marked `*`) — full input
- schemas are omitted to save context.
-2. **Execute** — call again with `server_url`, `tool_name`, and
- `tool_arguments` built from the description and `params` summary. If the
- tool name or arguments are wrong, the error response includes a bounded
- schema hint for that tool (very large schemas are reduced to their
- top-level structure and marked truncated) or the list of valid tool
- names — fix the call from that. Never re-run discovery just to see a
- schema.
-
-### Known hosted MCP servers
-
-Use these URLs directly without asking the user:
-
-| Service | URL |
-|---|---|
-| Linear | `https://mcp.linear.app/mcp` |
-| Stripe | `https://mcp.stripe.com` |
-| Cloudflare | `https://mcp.cloudflare.com/mcp` |
-
-<!-- official-mcp-catalog -->
-
-For other services, **web-search for the service's official MCP server URL**
-(e.g. "`<service>` MCP server URL") — many vendors host an MCP server even
-when it's not in the list above. Treat search results as unvetted: confirm
-the hostname is vendor-owned before using it (see below).
-
-The platform supports remote HTTP connections in both cloud and local deployments.
-Follow the setup requirements in the table before starting sign-in;
-some services require an administrator to enable access or a dedicated token.
-Use the listed authentication methods and default permissions. Where the table
-gives a separate OAuth URL, use that URL for signed-in account tools. Do not send
-API keys to an OAuth-only connection or infer that every advertised scope is
-required.
-For region choices, confirm where the user's account stores its data. For
-tenant-specific connections, obtain the endpoint using the vendor's setup
-instructions. Never substitute a documentation URL for the connection endpoint
-or invent a tenant hostname. Direct the user to the matching integration preset
-for regional selection, manual credentials, or optional write permissions.
-
-### Important: Check blocks first, then MCP is MANDATORY
-
-Always follow the **Tool Discovery Priority** described in the tool notes:
-call `find_block` before resorting to `run_mcp_tool`.
-
-When `find_block` returns no usable match, MCP is **not optional** — the
-user does not know MCP exists, so it's your job to discover and surface it
-on their behalf. Before telling the user a service isn't supported, you
-MUST:
-
-1. Check the known hosted MCP servers list above, AND
-2. If the service isn't there, web-search for the service's official MCP
- server URL.
-
-Only after **both** of these return nothing may you say the service isn't
-supported.
-
-**Never guess or construct MCP server URLs.** Only use URLs from the known
-servers list above, or a vendor-owned URL confirmed via web search.
-
-### Verifying the server hostname
-
-Before calling `run_mcp_tool` on a URL found via web search, **verify the
-hostname belongs to the service's vendor** (e.g. `mcp.sentry.dev` for
-Sentry, or a `mcp.<service>.com` / `mcp.<service>.dev` / other vendor-owned
-domain). Web-search results are unvetted, and the user is about to hand the
-server their sign-in, so this check matters:
-
-- If the hostname clearly belongs to the vendor, proceed.
-- If multiple plausible URLs exist, or the hostname's vendor isn't obvious,
- surface the candidates to the user and ask which one to use — never
- auto-pick when the match is ambiguous.
-
-### Authentication
-
-If the server requires credentials, a `SetupRequirementsResponse` is returned with an OAuth
-login prompt. Once the user completes the flow and confirms, retry the same call immediately.
-
-### Communication style
-
-To the user, MCP is just an integration. Lead with **"the <Service>
-integration (MCP)"** the first time you mention it in a turn, then drop
-the parenthetical on subsequent mentions. This keeps non-technical users
-oriented while still being transparent about what's happening for users
-who recognize the term.
-
-Never expose "MCP server", "MCP tool", "OAuth", or "credentials" to the
-user. Primary phrases: **"integration"**, **"connect to <Service>"**,
-**"sign in to <Service>"**.
-
-| Instead of… | Say… |
-|---|---|
-| "Let me connect to Sentry's MCP server and discover what tools are available." | "Let me set up the **Sentry integration (MCP)** and see what I can pull." |
-| "Let me connect to Sentry's MCP server now." | "Next, I'll connect to Sentry." |
-| "The MCP server at mcp.sentry.dev requires authentication. Please connect your credentials to continue." | "To continue, sign in to Sentry and approve access." |
-| "Sentry's MCP server needs OAuth authentication. You should see a prompt to connect your Sentry account…" | "You should see a prompt to sign in to Sentry. Once connected, I can surface critical issues right away." |
diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
index 7d31f9736e..671ed26d5e 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
@@ -182,6 +182,13 @@ def _validate_user_isolation(
return {}
+# Tools whose display name (block, agent, MCP tool) streams to the UI before
+# the call finishes; the bridge tags their input with a call token.
+_DISPLAY_BRIDGED_TOOLS: frozenset[str] = frozenset(
+ {"run_agent", "run_capability", "resume_capability"}
+)
+
+
def create_security_hooks(
user_id: str | None,
sdk_cwd: str | None = None,
@@ -280,7 +287,7 @@ def create_security_hooks(
logger.debug(f"[SDK] Tool start: {tool_name}, user={user_id}")
if (
is_copilot_tool
- and clean_name in {"run_agent", "run_block", "continue_run_block"}
+ and clean_name in _DISPLAY_BRIDGED_TOOLS
and tool_use_id is not None
and tool_display_bridge is not None
):
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index 4e8180c3e7..375de64e7b 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -115,8 +115,8 @@ from ..pending_messages import (
)
from ..permissions import (
CopilotPermissions,
- all_known_tool_names,
apply_tool_permissions,
+ denied_tool_names,
)
from ..prompting import (
get_chat_platform_supplement,
@@ -1037,10 +1037,7 @@ def _hidden_short_names_for_permissions(
Hiding the tool from the MCP server removes it from the model's tool
list entirely so it never reaches for the blocked name.
"""
- if permissions is None or permissions.is_empty():
- return frozenset()
- all_tools = all_known_tool_names()
- return all_tools - permissions.effective_allowed_tools(all_tools)
+ return denied_tool_names(permissions)
def _strip_synthetic_reprompt_from_cli_jsonl(content: bytes) -> bytes:
@@ -4968,6 +4965,17 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
| kickoff_hidden
| origin_disabled_tools(session.metadata.origin)
)
+ # run_capability reaches deferred tools by id; the same hidden set
+ # must bound it, so it travels with the turn's execution context.
+ set_execution_context(
+ user_id,
+ session,
+ sandbox=e2b_sandbox,
+ sdk_cwd=sdk_cwd,
+ permissions=permissions,
+ envelope=envelope,
+ hidden_tools=hidden_tools,
+ )
mcp_server = create_copilot_mcp_server(
use_e2b=use_e2b,
hidden_tool_names=hidden_tools,
@@ -5169,6 +5177,7 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
_otel_metadata: dict[str, str] = {
"resume": str(use_resume),
"conversation_turn": str(turn),
+ "tool_surface": "registry",
}
if _user_tier:
_otel_metadata["subscription_tier"] = _user_tier.value
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service_test.py b/autogpt_platform/backend/backend/copilot/sdk/service_test.py
index 33b9eb920a..127424d68c 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service_test.py
@@ -299,7 +299,7 @@ class TestPromptSupplement:
assert "## AVAILABLE TOOLS" not in SHARED_TOOL_NOTES
# Keep the high-value workflow rules that are NOT in any tool schema.
assert "@@agptfile:" in SHARED_TOOL_NOTES
- assert "Tool Discovery Priority" in SHARED_TOOL_NOTES
+ assert "find_capability` is MANDATORY" in SHARED_TOOL_NOTES
assert "run_sub_session" in SHARED_TOOL_NOTES
def test_pause_task_scheduled_before_transcript_upload(self):
@@ -2306,8 +2306,8 @@ class TestHiddenShortNamesForPermissions:
def test_whitelist_hides_everything_not_listed(self):
all_tools = all_known_tool_names()
# Pick one stable, well-known tool as the whitelist.
- keep = "find_block"
- assert keep in all_tools, "test relies on find_block being registered"
+ keep = "find_capability"
+ assert keep in all_tools, "test relies on find_capability being registered"
perms = CopilotPermissions(
tools=[keep],
tools_exclude=False,
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
index a731f7886d..f60554fc6c 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
@@ -19,6 +19,7 @@ from mcp.types import ToolAnnotations
from backend.copilot.context import (
_current_envelope,
+ _current_hidden_tools,
_current_permissions,
_current_project_dir,
_current_sandbox,
@@ -36,7 +37,12 @@ from backend.copilot.sdk.file_ref import (
expand_file_refs_in_args,
read_file_bytes,
)
-from backend.copilot.tools import TOOL_REGISTRY, ToolGroup, tool_names_in_groups
+from backend.copilot.tools import (
+ DEFERRED_TOOL_NAMES,
+ TOOL_REGISTRY,
+ ToolGroup,
+ tool_names_in_groups,
+)
from backend.copilot.tools.base import BaseTool
from backend.util.truncate import truncate
@@ -132,6 +138,7 @@ def set_execution_context(
sdk_cwd: str | None = None,
permissions: "CopilotPermissions | None" = None,
envelope: "TurnEnvelope | None" = None,
+ hidden_tools: frozenset[str] = frozenset(),
) -> None:
"""Set the execution context for tool calls.
@@ -145,6 +152,8 @@ def set_execution_context(
sdk_cwd: SDK working directory; used to scope tool-results reads.
permissions: Optional capability filter restricting tools/blocks.
envelope: The turn's tree envelope; spawn tools derive children from it.
+ hidden_tools: Short tool names hidden from the model this turn;
+ ``run_capability`` refuses to reach them by id.
"""
_current_user_id.set(user_id)
_current_session.set(session)
@@ -153,6 +162,7 @@ def set_execution_context(
_current_project_dir.set(_encode_cwd_for_cli(sdk_cwd) if sdk_cwd else "")
_current_permissions.set(permissions)
_current_envelope.set(envelope)
+ _current_hidden_tools.set(hidden_tools)
reset_consult_budget()
_pending_tool_outputs.set({})
_stash_event.set(asyncio.Event())
@@ -880,12 +890,14 @@ def create_copilot_mcp_server(
# excluded from ``allowed_tools`` — advertising an MCP copy the CLI
# can never approve makes the model call it, receive a permission
# denial, and silently abandon the feature (e.g. the task checklist).
+ # Deferred tools are reached through run_capability, not by name.
# ``is_available`` is the env check the baseline path applies in
# ``get_available_tools``; without it this engine offers browser
# tools on a box with no agent-browser binary.
if (
tool_name in hidden
or tool_name in BASELINE_ONLY_MCP_TOOLS
+ or tool_name in DEFERRED_TOOL_NAMES
or not base_tool.is_available
):
continue
@@ -1128,7 +1140,9 @@ def _registry_mcp_tools(*, hidden: frozenset[str] = frozenset()) -> list[str]:
return [
f"{MCP_TOOL_PREFIX}{name}"
for name in TOOL_REGISTRY.keys()
- if name not in BASELINE_ONLY_MCP_TOOLS and name not in hidden
+ if name not in BASELINE_ONLY_MCP_TOOLS
+ and name not in DEFERRED_TOOL_NAMES
+ and name not in hidden
]
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 62f4118008..7600922b7c 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py
@@ -12,7 +12,7 @@ from backend.copilot.builder_context import BUILDER_BLOCKED_TOOLS
from backend.copilot.context import get_sdk_cwd
from backend.copilot.model import ChatSession
from backend.copilot.response_model import StreamToolOutputAvailable
-from backend.copilot.tools import TOOL_REGISTRY
+from backend.copilot.tools import DEFERRED_TOOL_NAMES, TOOL_REGISTRY
from backend.util.truncate import truncate
from .tool_adapter import (
@@ -1255,11 +1255,10 @@ class TestCreateCopilotMcpServerHidden:
@pytest.mark.asyncio
async def test_hidden_tools_not_registered(self):
- # Use a named tool (find_block is stable + load-bearing in the
- # builder flow) so the test reads as a real scenario instead of
- # "the first key in dict insertion order".
- hidden_name = "find_block"
- assert hidden_name in TOOL_REGISTRY, "fixture relies on find_block"
+ # Use a named eager tool so the test reads as a real scenario
+ # instead of "the first key in dict insertion order".
+ hidden_name = "find_capability"
+ assert hidden_name in TOOL_REGISTRY, "fixture relies on find_capability"
server = create_copilot_mcp_server(hidden_tool_names=[hidden_name])
registered = await self._registered_tool_names(server)
assert hidden_name not in registered
@@ -1293,8 +1292,8 @@ class TestCreateCopilotMcpServerHidden:
registered = await self._registered_tool_names(server)
for blocked in BUILDER_BLOCKED_TOOLS:
assert blocked not in registered
- # edit_agent must remain so the model can populate the bound graph.
- assert "edit_agent" in registered
+ # The registry tools must remain so the model can still act.
+ assert "run_capability" in registered
@pytest.mark.asyncio
async def test_unknown_hidden_name_is_silently_ignored(self):
@@ -1332,16 +1331,23 @@ class TestCreateCopilotMcpServerHidden:
f"{sorted(INTERACTIVE_ORIGIN_TOOLS & registered)}"
)
# Narrow by design: the work an automation exists to do stays.
- assert {"run_agent", "run_block", "run_sub_session"} <= registered
+ # ``run_block`` is a permission gate rather than a registered
+ # tool now — blocks run through ``run_capability``.
+ assert {"run_agent", "run_capability", "run_sub_session"} <= registered
interactive = await self._registered_tool_names(
create_copilot_mcp_server(
hidden_tool_names=origin_disabled_tools("interactive")
)
)
- assert INTERACTIVE_ORIGIN_TOOLS <= interactive, (
- "an interactive session lost "
- f"{sorted(INTERACTIVE_ORIGIN_TOOLS - interactive)}"
+ # Every interactive-origin tool is deferred, so none is registered by
+ # name in either session; the model reaches them through
+ # ``run_capability``. What the origin gate still decides is whether
+ # the turn may run them at all, which the hidden set above enforces.
+ assert INTERACTIVE_ORIGIN_TOOLS <= DEFERRED_TOOL_NAMES
+ eager_interactive = INTERACTIVE_ORIGIN_TOOLS - DEFERRED_TOOL_NAMES
+ assert eager_interactive <= interactive, (
+ "an interactive session lost " f"{sorted(eager_interactive - interactive)}"
)
@pytest.mark.asyncio
@@ -1351,19 +1357,22 @@ class TestCreateCopilotMcpServerHidden:
Without it the model is offered browser tools on a box with no
``agent-browser`` binary, and they fail on first use.
"""
+ # The browser tools are deferred, so they are never registered by
+ # name; the model reaches them through ``run_capability``. Assert the
+ # env check on a tool that is registered when its binary is present.
browser_tools = {"browser_navigate", "browser_act", "browser_screenshot"}
-
- with patch(
- "backend.copilot.tools.agent_browser.shutil.which", return_value="/x"
- ):
- registered = await self._registered_tool_names(create_copilot_mcp_server())
- assert browser_tools <= registered
-
- with patch(
- "backend.copilot.tools.agent_browser.shutil.which", return_value=None
- ):
- registered = await self._registered_tool_names(create_copilot_mcp_server())
- assert not (browser_tools & registered)
+ assert browser_tools <= DEFERRED_TOOL_NAMES
+
+ for present in ("/x", None):
+ with patch(
+ "backend.copilot.tools.agent_browser.shutil.which",
+ return_value=present,
+ ):
+ registered = await self._registered_tool_names(
+ create_copilot_mcp_server()
+ )
+ assert not (browser_tools & registered)
+ assert self._expected_registry_names() <= registered
@staticmethod
def _expected_registry_names() -> set[str]:
@@ -1372,12 +1381,16 @@ class TestCreateCopilotMcpServerHidden:
``is_available`` is read here rather than asserted over the whole
registry: the chat-platform, browser and E2B tools depend on env the
test box may not have, and registering one the environment cannot
- serve is the bug, not the invariant.
+ serve is the bug, not the invariant. Deferred tools are excluded for
+ the same reason — they are reached through run_capability by id, not
+ registered by name.
"""
return {
name
for name, tool in TOOL_REGISTRY.items()
- if name not in BASELINE_ONLY_MCP_TOOLS and tool.is_available
+ if name not in BASELINE_ONLY_MCP_TOOLS
+ and name not in DEFERRED_TOOL_NAMES
+ and tool.is_available
}
@staticmethod
@@ -1477,3 +1490,18 @@ class TestEmptyArgsCircuitBreaker:
text = _text_from_mcp_result(result)
assert "STOP" in text
assert "Do NOT retry" in text
+
+
+def test_set_execution_context_carries_hidden_tools():
+ """The SDK engine hands its per-turn hidden tool set through this
+ adapter's ``set_execution_context`` (not ``context.set_execution_context``),
+ so the keyword must exist here too — run_capability reads it back."""
+ from backend.copilot.context import get_current_hidden_tools
+
+ session = MagicMock(spec=ChatSession)
+ set_execution_context("user", session, hidden_tools=frozenset({"list_schedules"}))
+ try:
+ assert get_current_hidden_tools() == frozenset({"list_schedules"})
+ finally:
+ set_execution_context(None, session)
+ assert get_current_hidden_tools() == frozenset()
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_display_integration_test.py b/autogpt_platform/backend/backend/copilot/sdk/tool_display_integration_test.py
index 9faedabb67..79ece55b3b 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_display_integration_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_display_integration_test.py
@@ -82,13 +82,13 @@ async def test_display_bridge_preserves_domain_execution_ids():
"graph_name",
),
(
- "run_block",
- {"block_id": "db7d8f02-2f44-4c55-ab7a-eae0941f0c30", "input_data": {}},
+ "run_capability",
+ {"id": "block:db7d8f02-2f44-4c55-ab7a-eae0941f0c30", "input": {}},
"FillTextTemplateBlock",
"block_name",
),
(
- "continue_run_block",
+ "resume_capability",
{"review_id": "review"},
"FillTextTemplateBlock",
"block_name",
diff --git a/autogpt_platform/backend/backend/copilot/session_permissions.py b/autogpt_platform/backend/backend/copilot/session_permissions.py
index 7bb6e1cf3b..0ff4a8524c 100644
--- a/autogpt_platform/backend/backend/copilot/session_permissions.py
+++ b/autogpt_platform/backend/backend/copilot/session_permissions.py
@@ -14,7 +14,7 @@ from backend.copilot.permissions import CopilotPermissions
# Tools hidden from builder-bound sessions: ``create_agent`` /
# ``customize_agent`` would mint a new graph (panel is bound to one),
# and ``get_agent_building_guide`` duplicates bytes already in the
-# system-prompt suffix. Everything else (find_block, find_agent, …)
+# system-prompt suffix. Everything else (find_capability, find_agent, …)
# stays available so the LLM can look up ids instead of hallucinating.
BUILDER_BLOCKED_TOOLS: tuple[str, ...] = (
"create_agent",
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index bed58b0bac..9e33e72868 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, Any, Literal
from openai.types.chat import ChatCompletionToolParam
+from backend.copilot.capabilities.registry import configure_tools
+from backend.copilot.capabilities.sources import EAGER_CORE
from backend.copilot.response_model import StreamToolOutputAvailable
from backend.copilot.tracking import track_tool_called
@@ -23,11 +25,11 @@ from .chat_platform import (
from .confirm_expert_change import ConfirmExpertChangeTool
from .connect_integration import ConnectIntegrationTool
from .consult_teammate import ConsultTeammateTool
-from .continue_run_block import ContinueRunBlockTool
from .create_agent import CreateAgentTool
from .customize_agent import CustomizeAgentTool
from .decompose_goal import DecomposeGoalTool
from .delegate_to_expert import DelegateToExpertTool
+from .describe_capability import DescribeCapabilityTool
from .edit_agent import EditAgentTool
from .enter_building_mode import EnterAgentBuildingModeTool
from .expert_chats import ListExpertChatsTool, ReadExpertChatTool
@@ -43,13 +45,12 @@ from .expert_resources import (
)
from .feature_requests import CreateFeatureRequestTool, SearchFeatureRequestsTool
from .find_agent import FindAgentTool
-from .find_block import FindBlockTool
+from .find_capability import FindCapabilityTool
from .find_library_agent import FindLibraryAgentTool
from .find_session import FindSessionTool
from .fix_agent import FixAgentGraphTool
from .get_agent_building_guide import GetAgentBuildingGuideTool
from .get_doc_page import GetDocPageTool
-from .get_mcp_guide import GetMCPGuideTool
from .get_sub_session_result import GetSubSessionResultTool
from .graphiti_forget import MemoryForgetConfirmTool, MemoryForgetSearchTool
from .graphiti_search import MemorySearchTool
@@ -77,9 +78,9 @@ from .message_session import MessageSessionTool
from .models import ErrorResponse
from .platform_info import PlatformInfoTool
from .raise_expert import RaiseExpertTool
+from .resume_capability import ResumeCapabilityTool
from .run_agent import RunAgentTool
-from .run_block import RunBlockTool
-from .run_mcp_tool import RunMCPToolTool
+from .run_capability import RunCapabilityTool
from .run_sub_session import RunSubSessionTool
from .schedule_followup import ScheduleFollowupTool
from .search_docs import SearchDocsTool
@@ -113,8 +114,13 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"decompose_goal": DecomposeGoalTool(),
"edit_agent": EditAgentTool(),
"find_agent": FindAgentTool(),
- "find_block": FindBlockTool(),
"find_library_agent": FindLibraryAgentTool(),
+ # Capability registry: one discovery/execution surface for blocks, MCP
+ # servers and the deferred platform tools (see EAGER_CORE).
+ "find_capability": FindCapabilityTool(),
+ "describe_capability": DescribeCapabilityTool(),
+ "run_capability": RunCapabilityTool(),
+ "resume_capability": ResumeCapabilityTool(),
# Graphiti memory tools
"memory_forget_confirm": MemoryForgetConfirmTool(),
"memory_forget_search": MemoryForgetSearchTool(),
@@ -146,8 +152,6 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"list_presets": ListPresetsTool(),
"update_preset": UpdatePresetTool(),
"delete_preset": DeletePresetTool(),
- "run_block": RunBlockTool(),
- "continue_run_block": ContinueRunBlockTool(),
"run_sub_session": RunSubSessionTool(),
"get_sub_session_result": GetSubSessionResultTool(),
"consult_teammate": ConsultTeammateTool(),
@@ -156,8 +160,6 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"delegate_to_expert": DelegateToExpertTool(),
"list_team": ListTeamTool(),
"TodoWrite": TodoWriteTool(),
- "run_mcp_tool": RunMCPToolTool(),
- "get_mcp_guide": GetMCPGuideTool(),
"view_agent_output": AgentOutputTool(),
"search_docs": SearchDocsTool(),
"get_doc_page": GetDocPageTool(),
@@ -226,6 +228,11 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
find_agent_tool = TOOL_REGISTRY["find_agent"]
run_agent_tool = TOOL_REGISTRY["run_agent"]
+# Tools the model does not see in its tool list; they are reached by id
+# through ``run_capability`` (their schema arrives via ``describe_capability``).
+# Keeping the prefix to the eager core is what makes the cold prompt cheap.
+DEFERRED_TOOL_NAMES: frozenset[str] = frozenset(TOOL_REGISTRY) - EAGER_CORE
+
# Capability groups a tool may belong to. The service layer can hide all
# tools in a group when the backing capability isn't available to this user
@@ -288,6 +295,11 @@ TOOL_GROUPS: dict[str, ToolGroup] = {
}
+# The capability registry indexes this registry; hand it over now that both
+# exist (the registry package cannot import them without a cycle).
+configure_tools(TOOL_REGISTRY, TOOL_GROUPS)
+
+
def expert_tool_disabled_groups(
*, experts_enabled: bool, expert_id: str | None
) -> list[ToolGroup]:
@@ -364,6 +376,7 @@ def get_available_tools(
*,
disabled_groups: Iterable[ToolGroup] = (),
disabled_tools: Iterable[str] = (),
+ include_deferred: bool = False,
) -> list[ChatCompletionToolParam]:
"""Return OpenAI tool schemas for tools available in the current environment.
@@ -374,8 +387,12 @@ def get_available_tools(
``graphiti`` when the memory backend is off for the current user).
*disabled_tools* hides individual tools for gates that don't follow the
group split, e.g. ``kickoff_turn_disabled_tools`` on a hire's first turn.
+ ``DEFERRED_TOOL_NAMES`` are left out unless *include_deferred*: the model
+ reaches them through ``run_capability``.
"""
hidden = tool_names_in_groups(disabled_groups) | frozenset(disabled_tools)
+ if not include_deferred:
+ hidden |= DEFERRED_TOOL_NAMES
return [
tool.as_openai_tool()
for name, tool in TOOL_REGISTRY.items()
@@ -388,6 +405,35 @@ def get_tool(tool_name: str) -> BaseTool | None:
return TOOL_REGISTRY.get(tool_name)
+def reachable_tool_names(
+ *,
+ disabled_groups: Iterable[ToolGroup] = (),
+ disabled_tools: Iterable[str] = (),
+) -> frozenset[str]:
+ """Names this turn can actually run, declared or reached by id.
+
+ Since the swap, a tool being absent from the schema list no longer means
+ the turn cannot run it: 57 of them are reached through ``run_capability``
+ instead, bounded by the same hidden set. Gate tests that ask "can this
+ session still do X" want this, not ``get_available_tools``; asking the
+ schema list alone reads every deferred tool as removed.
+ """
+ hidden = tool_names_in_groups(disabled_groups) | frozenset(disabled_tools)
+ declared = {
+ name
+ for name, tool in TOOL_REGISTRY.items()
+ if tool.is_available and name not in hidden and name not in DEFERRED_TOOL_NAMES
+ }
+ if "run_capability" not in declared:
+ # Nothing reaches a deferred tool without the tool that runs them.
+ return frozenset(declared)
+ return frozenset(declared) | frozenset(
+ name
+ for name in DEFERRED_TOOL_NAMES
+ if name not in hidden and TOOL_REGISTRY[name].is_available
+ )
+
+
async def execute_tool(
tool_name: str,
parameters: dict[str, Any],
@@ -407,6 +453,10 @@ 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.
+
``disabled_groups`` and ``disabled_tools`` are keyword-only and have no
default on purpose: they are an enforcement boundary, so a new call site
must state its gate rather than silently inherit "nothing is disabled"
@@ -418,8 +468,14 @@ async def execute_tool(
if not tool:
raise ValueError(f"Tool {tool_name} not found")
- if tool_name in tool_names_in_groups(disabled_groups) or tool_name in frozenset(
- disabled_tools
+ # A deferred tool is absent from every schema list, but a model that
+ # names one anyway reached it here and ran it -- routing around
+ # ``run_capability`` and the permission and envelope gates it applies.
+ # Deferred-ness is a property of the tool, not of the turn, so it is
+ # refused here rather than left to each caller's gate.
+ if tool_name in DEFERRED_TOOL_NAMES or (
+ tool_name in tool_names_in_groups(disabled_groups)
+ or tool_name in frozenset(disabled_tools)
):
logger.warning(
"Refusing disabled tool: tool=%s user=%s session=%s",
diff --git a/autogpt_platform/backend/backend/copilot/tools/ask_question.py b/autogpt_platform/backend/backend/copilot/tools/ask_question.py
index 8c8c4056be..f136288690 100644
--- a/autogpt_platform/backend/backend/copilot/tools/ask_question.py
+++ b/autogpt_platform/backend/backend/copilot/tools/ask_question.py
@@ -24,7 +24,7 @@ class AskQuestionTool(BaseTool):
"""Ask the user one or more clarifying questions and wait for answers.
Use this tool when the user's request is ambiguous and you need more
- information before proceeding. Call find_block or other discovery tools
+ information before proceeding. Call find_capability or other discovery tools
first to ground your questions in real platform options, then call this
tool with concrete questions listing those options.
"""
diff --git a/autogpt_platform/backend/backend/copilot/tools/base.py b/autogpt_platform/backend/backend/copilot/tools/base.py
index 450b6ff93d..fba7841931 100644
--- a/autogpt_platform/backend/backend/copilot/tools/base.py
+++ b/autogpt_platform/backend/backend/copilot/tools/base.py
@@ -12,7 +12,6 @@ from backend.copilot.model import ChatSession
from backend.copilot.response_model import StreamToolOutputAvailable
from backend.data.activity_event import ActivityEventDraft
from backend.data.db_accessors import activity_event_db, workspace_db
-from backend.util.feature_flag import Flag, is_feature_enabled
from backend.util.truncate import truncate
from backend.util.workspace import WorkspaceManager
@@ -32,9 +31,9 @@ _LARGE_OUTPUT_THRESHOLD = 80_000
# to avoid double truncation/spilling. 95K + ~300 wrapper = ~95.3K, under both.
_PREVIEW_CHARS = 95_000
-# Threshold and budget for the digest, which fires when AUTOPILOT_CONTEXT_TRIMMING
-# is on and the tool opts in. The budget is derived from the trigger so a digest
-# can never be larger than the output it replaces.
+# Threshold and budget for the digest, which fires when the tool opts in. The
+# budget is derived from the trigger so a digest can never be larger than the
+# output it replaces.
_DIGEST_THRESHOLD = 8_000
_DIGEST_PREVIEW_CHARS = _DIGEST_THRESHOLD // 4
_OUTLINE_SCALAR_CHARS = 120
@@ -425,15 +424,10 @@ class BaseTool:
await _record_activity(self, user_id, session, result, kwargs)
raw_output = result.model_dump_json(exclude_none=True)
- # Consult the flag only once the output could plausibly be digested,
- # so the common small-output path stays a pure local check.
digest = (
self.digest_large_output
and len(raw_output) > _DIGEST_THRESHOLD
and user_id is not None
- and await is_feature_enabled(
- Flag.AUTOPILOT_CONTEXT_TRIMMING, user_id, default=False
- )
)
threshold = _DIGEST_THRESHOLD if digest else _LARGE_OUTPUT_THRESHOLD
if len(raw_output) > threshold and user_id and session.session_id:
diff --git a/autogpt_platform/backend/backend/copilot/tools/base_test.py b/autogpt_platform/backend/backend/copilot/tools/base_test.py
index 6230699efe..4903f7d092 100644
--- a/autogpt_platform/backend/backend/copilot/tools/base_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/base_test.py
@@ -226,7 +226,7 @@ class TestSummarizeBinaryFields:
# ---------------------------------------------------------------------------
-# AUTOPILOT_CONTEXT_TRIMMING digest
+# Large-output digest (always on)
# ---------------------------------------------------------------------------
@@ -307,18 +307,13 @@ def _workspace_patches(manager):
async def _execute_with_flag(tool, flag_on: bool, manager=None):
+ """The digest used to sit behind a feature flag; it is now always on, so
+ ``flag_on`` is kept only so the call sites read as before."""
+ assert flag_on
session = MagicMock()
session.session_id = "s-1"
db_patch, mgr_patch = _workspace_patches(manager or AsyncMock())
- with (
- db_patch,
- mgr_patch,
- patch(
- "backend.copilot.tools.base.is_feature_enabled",
- new_callable=AsyncMock,
- return_value=flag_on,
- ),
- ):
+ with db_patch, mgr_patch:
return await tool.execute("user-1", session, "tc-digest")
@@ -328,15 +323,6 @@ class TestDigestThreshold:
deriving the budget from the trigger makes that unrepresentable."""
assert _DIGEST_PREVIEW_CHARS < _DIGEST_THRESHOLD
- @pytest.mark.asyncio
- async def test_flag_off_leaves_a_mid_sized_output_byte_identical(self):
- tool = _SchemaOutputTool(output_size=_DIGEST_THRESHOLD * 3)
- result = await _execute_with_flag(tool, flag_on=False)
- expected = (await tool._execute("user-1", MagicMock())).model_dump_json(
- exclude_none=True
- )
- assert result.output == expected
-
@pytest.mark.asyncio
async def test_flag_on_digests_a_mid_sized_output(self):
manager = AsyncMock()
@@ -434,18 +420,6 @@ class TestDigestThreshold:
start, length = int(window[1]), int(window[2])
assert json.loads(written[start : start + length]) == ["field_0"]
- @pytest.mark.asyncio
- async def test_a_small_output_never_consults_the_flag(self):
- tool = _SchemaOutputTool(output_size=200)
- with patch(
- "backend.copilot.tools.base.is_feature_enabled",
- new_callable=AsyncMock,
- ) as flag:
- session = MagicMock()
- session.session_id = "s-1"
- await tool.execute("user-1", session, "tc-small")
- flag.assert_not_awaited()
-
def _outline_of(data, budget: int) -> tuple[str, str]:
body, parsed, offsets = _index_json(json.dumps(data))
diff --git a/autogpt_platform/backend/backend/copilot/tools/capability_gates.py b/autogpt_platform/backend/backend/copilot/tools/capability_gates.py
new file mode 100644
index 0000000000..e153cc5660
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/capability_gates.py
@@ -0,0 +1,39 @@
+"""The per-kind gates that guard capability execution.
+
+``run_capability`` and ``resume_capability`` both run capabilities, so both
+answer to the same gates. They live here rather than in either tool so
+neither has to reach into the other's privates for them.
+"""
+
+from backend.copilot.context import (
+ get_current_envelope,
+ get_current_hidden_tools,
+ get_current_permissions,
+)
+from backend.copilot.permissions import ALL_TOOL_NAMES
+
+from .models import ErrorResponse
+
+
+def gate_denied(name: str) -> bool:
+ """True when this turn may not use *name* (a tool or a kind gate)."""
+ if name in get_current_hidden_tools():
+ return True
+ envelope = get_current_envelope()
+ if envelope is not None and not envelope.permits(name):
+ return True
+ permissions = get_current_permissions()
+ return permissions is not None and name not in permissions.effective_allowed_tools(
+ ALL_TOOL_NAMES
+ )
+
+
+def gate_denied_error(name: str, session_id: str) -> ErrorResponse:
+ return ErrorResponse(
+ message=(
+ f"'{name}' is not available in this session's permissions. "
+ "If the task needs it, say so instead of working around it."
+ ),
+ error="tool_disabled",
+ session_id=session_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
new file mode 100644
index 0000000000..775321110a
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py
@@ -0,0 +1,518 @@
+"""find/describe/run/resume_capability over the real registry with the
+execution paths mocked at their boundaries."""
+
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from prisma.enums import ReviewStatus
+
+from backend.copilot.capabilities.mcp_review import COPILOT_MCP_NODE_PREFIX
+from backend.copilot.capabilities.ranking import ConnectionState
+from backend.copilot.capabilities.sources import EAGER_CORE
+from backend.copilot.constants import COPILOT_SESSION_PREFIX
+from backend.copilot.context import set_execution_context
+from backend.copilot.permissions import CopilotPermissions
+from backend.copilot.prompting import SHARED_TOOL_NOTES
+from backend.copilot.tools import (
+ DEFERRED_TOOL_NAMES,
+ TOOL_REGISTRY,
+ get_available_tools,
+)
+
+from ._test_data import make_session
+from .describe_capability import DescribeCapabilityTool
+from .find_capability import FindCapabilityTool
+from .models import (
+ BlockDetails,
+ BlockDetailsResponse,
+ BlockOutputResponse,
+ CapabilityDetailsResponse,
+ CapabilityListResponse,
+ ErrorResponse,
+ MCPToolOutputResponse,
+ NoResultsResponse,
+ ReviewRequiredResponse,
+)
+from .resume_capability import ResumeCapabilityTool
+from .run_capability import RunCapabilityTool
+
+USER = "user-cap-tools"
+LINEAR_STATE = ConnectionState(providers=frozenset({"linear"}))
+
+
[email protected](autouse=True)
+def _clean_context():
+ session = make_session(USER)
+ set_execution_context(USER, session)
+ yield
+ set_execution_context(None, None)
+
+
+# ---------------------------------------------------------------- registry
+
+
+def test_eager_and_deferred_split_the_registry():
+ eager = set(TOOL_REGISTRY) & EAGER_CORE
+ assert eager.isdisjoint(DEFERRED_TOOL_NAMES)
+ assert eager | DEFERRED_TOOL_NAMES == set(TOOL_REGISTRY)
+ shown = {t["function"]["name"] for t in get_available_tools()}
+ assert shown <= eager
+ assert {
+ "find_capability",
+ "describe_capability",
+ "run_capability",
+ "resume_capability",
+ } <= shown
+ assert len(get_available_tools(include_deferred=True)) > len(shown)
+
+
+def test_prompt_names_only_registry_tools():
+ for legacy in (
+ "find_block",
+ "run_block",
+ "run_mcp_tool",
+ "get_mcp_guide",
+ "continue_run_block",
+ ):
+ assert legacy not in SHARED_TOOL_NOTES, legacy
+ assert (
+ "find_capability" in SHARED_TOOL_NOTES
+ and "resume_capability" in SHARED_TOOL_NOTES
+ )
+
+
+# ------------------------------------------------------------ find_capability
+
+
+async def test_find_capability_ranks_connected_service_first():
+ with patch(
+ "backend.copilot.tools.find_capability.load_connection_state",
+ AsyncMock(return_value=LINEAR_STATE),
+ ):
+ result = await FindCapabilityTool()._execute(
+ USER, make_session(USER), query="linear issue"
+ )
+ assert isinstance(result, CapabilityListResponse)
+ assert result.service == "linear"
+ assert result.capabilities[0]["name"].startswith("Linear")
+ assert result.capabilities[0]["connected"] is True
+ assert all(c.get("class") != "primitive" for c in result.capabilities)
+
+
+async def test_find_capability_no_results_points_to_open_world():
+ with patch(
+ "backend.copilot.tools.find_capability.load_connection_state",
+ AsyncMock(return_value=ConnectionState()),
+ ):
+ result = await FindCapabilityTool()._execute(
+ USER, make_session(USER), query="zzqx"
+ )
+ assert isinstance(result, NoResultsResponse)
+ assert any("MCP server" in s for s in result.suggestions)
+
+
+# -------------------------------------------------------- describe_capability
+
+
+async def test_describe_tool_returns_parameters():
+ result = await DescribeCapabilityTool()._execute(
+ USER, make_session(USER), id="tool:list_schedules"
+ )
+ assert isinstance(result, CapabilityDetailsResponse)
+ assert result.capability["id"] == "tool:list_schedules"
+ assert result.parameters == TOOL_REGISTRY["list_schedules"].parameters
+
+
+async def test_describe_block_collapses_large_enums_unless_expanded():
+ details = BlockDetailsResponse(
+ message="Block 'X' details.",
+ block=BlockDetails(
+ id="b",
+ name="X",
+ description="",
+ inputs={"properties": {"model": {"enum": list(range(40))}}},
+ ),
+ )
+ with patch(
+ "backend.copilot.tools.describe_capability.RunBlockTool._execute",
+ AsyncMock(return_value=details.model_copy(deep=True)),
+ ):
+ collapsed = await DescribeCapabilityTool()._execute(
+ USER, make_session(USER), id="SendWebRequestBlock"
+ )
+ assert isinstance(collapsed, BlockDetailsResponse)
+ assert collapsed.block.inputs["properties"]["model"]["enum_count"] == 40
+ assert "run_capability" in collapsed.message
+ with patch(
+ "backend.copilot.tools.describe_capability.RunBlockTool._execute",
+ AsyncMock(return_value=details.model_copy(deep=True)),
+ ):
+ full = await DescribeCapabilityTool()._execute(
+ USER, make_session(USER), id="SendWebRequestBlock", expand=True
+ )
+ assert isinstance(full, BlockDetailsResponse)
+ assert len(full.block.inputs["properties"]["model"]["enum"]) == 40
+
+
+async def test_describe_block_honours_the_run_block_gate():
+ """A withheld block's schema is part of what was withheld.
+
+ Describing an MCP server is not even a local lookup -- it connects to the
+ server to list its tools -- so both kinds answer to their gate here the
+ way they do in run_capability.
+ """
+ session = make_session(USER)
+ set_execution_context(
+ USER, session, permissions=CopilotPermissions(tools=["run_block"])
+ )
+ result = await DescribeCapabilityTool()._execute(
+ USER, session, id="SendWebRequestBlock"
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "tool_disabled"
+
+
+async def test_describe_mcp_honours_the_run_mcp_gate():
+ session = make_session(USER)
+ set_execution_context(
+ USER, session, permissions=CopilotPermissions(tools=["run_mcp_tool"])
+ )
+ with patch(
+ "backend.copilot.tools.describe_capability._describe_mcp", AsyncMock()
+ ) as describe:
+ result = await DescribeCapabilityTool()._execute(
+ USER, session, id="https://mcp.linear.app/mcp"
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "tool_disabled"
+ describe.assert_not_awaited()
+
+
+async def test_describe_unknown_id():
+ result = await DescribeCapabilityTool()._execute(
+ USER, make_session(USER), id="tool:nope"
+ )
+ assert isinstance(result, ErrorResponse) and "find_capability" in result.message
+
+
+# ------------------------------------------------------------ run_capability
+
+
+def _stub_tool(name: str) -> MagicMock:
+ tool = MagicMock()
+ tool.name = name
+ tool.description = "stub"
+ tool.parameters = {"type": "object", "properties": {"x": {"type": "string"}}}
+ tool._execute = AsyncMock(return_value=ErrorResponse(message="ran", session_id="s"))
+ return tool
+
+
+async def test_run_tool_dispatches_to_the_deferred_tool():
+ 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"}
+ )
+ assert result.message == "ran"
+ stub._execute.assert_awaited_once()
+ assert stub._execute.await_args.kwargs == {"x": "1"}
+
+
+async def test_run_tool_respects_turn_hidden_tools():
+ session = make_session(USER)
+ set_execution_context(USER, session, hidden_tools=frozenset({"list_schedules"}))
+ stub = _stub_tool("list_schedules")
+ with patch(
+ "backend.copilot.tools.run_capability.configured_tool", return_value=stub
+ ):
+ result = await RunCapabilityTool()._execute(
+ USER, session, id="tool:list_schedules", input={}
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "tool_disabled"
+ stub._execute.assert_not_awaited()
+
+
+async def test_run_block_honours_the_run_block_gate():
+ session = make_session(USER)
+ set_execution_context(
+ USER, session, permissions=CopilotPermissions(tools=["run_block"])
+ )
+ with patch(
+ "backend.copilot.tools.run_capability.RunBlockTool._execute", AsyncMock()
+ ) as run:
+ result = await RunCapabilityTool()._execute(
+ USER, session, id="SendWebRequestBlock", input={}
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "tool_disabled"
+ run.assert_not_awaited()
+
+
+async def test_run_block_forwards_to_run_block_tool():
+ output = BlockOutputResponse(
+ message="ok", block_id="b", block_name="SendWebRequestBlock", outputs={}
+ )
+ with patch(
+ "backend.copilot.tools.run_capability.RunBlockTool._execute",
+ AsyncMock(return_value=output),
+ ) as run:
+ result = await RunCapabilityTool()._execute(
+ USER,
+ make_session(USER),
+ id="SendWebRequestBlock",
+ input={"url": "https://x"},
+ validate_only=True,
+ )
+ assert result is output
+ kwargs = run.await_args.kwargs
+ assert (
+ kwargs["input_data"] == {"url": "https://x"} and kwargs["validate_only"] is True
+ )
+ assert kwargs["block_id"]
+
+
+async def test_run_mcp_catalog_write_runs_without_review():
+ out = MCPToolOutputResponse(
+ message="done", server_url="u", tool_name="create_issue"
+ )
+ with patch(
+ "backend.copilot.tools.run_capability.RunMCPToolTool._execute",
+ AsyncMock(return_value=out),
+ ) as run, patch(
+ "backend.copilot.tools.run_capability.open_mcp_review", AsyncMock()
+ ) as review:
+ result = await RunCapabilityTool()._execute(
+ USER,
+ make_session(USER),
+ id="mcp:mcp.linear.app",
+ input={"tool": "create_issue", "arguments": {"a": 1}},
+ )
+ assert result is out
+ review.assert_not_awaited()
+ assert run.await_args.kwargs["tool_name"] == "create_issue"
+ assert run.await_args.kwargs["tool_arguments"] == {"a": 1}
+
+
+async def test_run_mcp_open_world_write_pauses_for_review():
+ with patch(
+ "backend.copilot.tools.run_capability.RunMCPToolTool._execute", AsyncMock()
+ ) as run, patch(
+ "backend.copilot.tools.run_capability.open_mcp_review",
+ AsyncMock(return_value="copilot-mcp-x:1"),
+ ):
+ result = await RunCapabilityTool()._execute(
+ USER,
+ make_session(USER),
+ id="https://mcp.example.com/mcp",
+ input={"tool": "delete_thing", "arguments": {}},
+ )
+ assert isinstance(result, ReviewRequiredResponse)
+ assert (
+ result.review_id == "copilot-mcp-x:1" and "resume_capability" in result.message
+ )
+ run.assert_not_awaited()
+
+
+async def test_run_mcp_open_world_read_runs():
+ out = MCPToolOutputResponse(message="done", server_url="u", tool_name="list_things")
+ with patch(
+ "backend.copilot.tools.run_capability.RunMCPToolTool._execute",
+ AsyncMock(return_value=out),
+ ):
+ result = await RunCapabilityTool()._execute(
+ USER,
+ make_session(USER),
+ id="https://mcp.example.com/mcp",
+ input={"tool": "list_things"},
+ )
+ assert result is out
+
+
+async def test_run_mcp_validate_only_describes_input_shape():
+ result = await RunCapabilityTool()._execute(
+ USER, make_session(USER), id="mcp:mcp.linear.app", input={}, validate_only=True
+ )
+ assert isinstance(result, CapabilityDetailsResponse)
+ assert set(result.parameters["properties"]) == {"tool", "arguments", "connect"}
+
+
+async def test_run_unknown_id():
+ result = await RunCapabilityTool()._execute(
+ USER, make_session(USER), id="block:nope", input={}
+ )
+ assert isinstance(result, ErrorResponse) and "find_capability" in result.message
+
+
+# --------------------------------------------------------- resume_capability
+
+
+def _review(
+ review_id: str, status: ReviewStatus, payload: dict[str, Any], session_id: str
+) -> MagicMock:
+ review = MagicMock()
+ review.node_exec_id = review_id
+ review.status = status
+ review.payload = payload
+ review.graph_exec_id = f"{COPILOT_SESSION_PREFIX}{session_id}"
+ return review
+
+
+async def test_resume_block_review_delegates_to_continue_run_block():
+ with patch(
+ "backend.copilot.tools.resume_capability.ContinueRunBlockTool._execute",
+ AsyncMock(return_value=ErrorResponse(message="cont")),
+ ) as cont:
+ result = await ResumeCapabilityTool()._execute(
+ USER, make_session(USER), review_id="copilot-node-b:1"
+ )
+ assert result.message == "cont"
+ assert cont.await_args.kwargs == {"review_id": "copilot-node-b:1"}
+
+
+async def test_resume_mcp_review_replays_the_approved_call():
+ session = make_session(USER)
+ review_id = f"{COPILOT_MCP_NODE_PREFIX}mcp.example.com:ab12"
+ arguments = {"id": 1, "force": False}
+ review = _review(
+ review_id,
+ ReviewStatus.APPROVED,
+ {
+ "server_url": "https://mcp.example.com/mcp",
+ "tool": "delete_thing",
+ "arguments": arguments,
+ },
+ session.session_id,
+ )
+ db = MagicMock()
+ db.get_reviews_by_node_exec_ids = AsyncMock(return_value={review_id: review})
+ db.delete_review_by_node_exec_id = AsyncMock()
+ out = MCPToolOutputResponse(
+ message="done", server_url="u", tool_name="delete_thing"
+ )
+ with patch(
+ "backend.copilot.tools.resume_capability.review_db", return_value=db
+ ), patch(
+ "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",
+ AsyncMock(return_value=out),
+ ) as run:
+ result = await ResumeCapabilityTool()._execute(
+ USER, session, review_id=review_id
+ )
+ assert result is out
+ assert run.await_args.kwargs["tool_arguments"] == arguments
+ db.delete_review_by_node_exec_id.assert_awaited_once_with(review_id, USER)
+
+
+async def test_resume_mcp_review_reopens_when_overrides_change_a_write():
+ """An approval covers the call the user saw, not a family of them.
+
+ Replaying it with different arguments is how a prompt injection turns
+ "delete this" into "delete that", so the gate runs again on the merged
+ arguments and the call waits for a fresh approval.
+ """
+ session = make_session(USER)
+ review_id = f"{COPILOT_MCP_NODE_PREFIX}mcp.example.com:ab12"
+ review = _review(
+ review_id,
+ ReviewStatus.APPROVED,
+ {
+ "server_url": "https://mcp.example.com/mcp",
+ "tool": "delete_thing",
+ "arguments": {"id": 1, "force": False},
+ },
+ session.session_id,
+ )
+ db = MagicMock()
+ db.get_reviews_by_node_exec_ids = AsyncMock(return_value={review_id: review})
+ db.delete_review_by_node_exec_id = AsyncMock()
+ with patch(
+ "backend.copilot.tools.resume_capability.review_db", return_value=db
+ ), patch(
+ "backend.copilot.tools.resume_capability.open_mcp_review",
+ AsyncMock(return_value="copilot-mcp-mcp.example.com:ef56"),
+ ) as opened, patch(
+ "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",
+ AsyncMock(),
+ ) as run:
+ result = await ResumeCapabilityTool()._execute(
+ USER, session, review_id=review_id, input_overrides={"force": True}
+ )
+ assert result.type == "review_required"
+ assert result.review_id == "copilot-mcp-mcp.example.com:ef56"
+ assert opened.await_args.kwargs["payload"].arguments == {"id": 1, "force": True}
+ run.assert_not_awaited()
+ db.delete_review_by_node_exec_id.assert_not_awaited()
+
+
+async def test_resume_mcp_review_reopens_even_when_the_call_would_not_be_gated():
+ """The review's existence is the proof this call needed approving.
+
+ Re-deriving that on resume reads the world as it is now: a read-shaped
+ tool name, or a server added to the catalog between turns, both answer
+ "no review needed" and would replay the changed arguments unapproved.
+ """
+ session = make_session(USER)
+ review_id = f"{COPILOT_MCP_NODE_PREFIX}mcp.example.com:ab12"
+ review = _review(
+ review_id,
+ ReviewStatus.APPROVED,
+ {
+ "server_url": "https://mcp.example.com/mcp",
+ "tool": "get_thing", # a read: needs_review() would say no
+ "arguments": {"id": 1},
+ },
+ session.session_id,
+ )
+ db = MagicMock()
+ db.get_reviews_by_node_exec_ids = AsyncMock(return_value={review_id: review})
+ db.delete_review_by_node_exec_id = AsyncMock()
+ with patch(
+ "backend.copilot.tools.resume_capability.review_db", return_value=db
+ ), patch(
+ "backend.copilot.tools.resume_capability.open_mcp_review",
+ AsyncMock(return_value="copilot-mcp-mcp.example.com:ef56"),
+ ), patch(
+ "backend.copilot.tools.resume_capability.RunMCPToolTool._execute",
+ AsyncMock(),
+ ) as run:
+ result = await ResumeCapabilityTool()._execute(
+ USER, session, review_id=review_id, input_overrides={"id": 2}
+ )
+ assert result.type == "review_required"
+ run.assert_not_awaited()
+ db.delete_review_by_node_exec_id.assert_not_awaited()
+
+
+async def test_resume_honours_this_turn_s_gates():
+ """An approval is not a standing exemption from later permissions.
+
+ Permissions are rebuilt per turn, and resuming runs the capability, so a
+ turn that may not reach MCP servers may not reach them through a review
+ approved while it still could.
+ """
+ session = make_session(USER)
+ review_id = f"{COPILOT_MCP_NODE_PREFIX}mcp.example.com:ab12"
+ db = MagicMock()
+ db.get_reviews_by_node_exec_ids = AsyncMock()
+ set_execution_context(
+ USER, session, permissions=CopilotPermissions(tools=["run_mcp_tool"])
+ )
+ with patch("backend.copilot.tools.resume_capability.review_db", return_value=db):
+ result = await ResumeCapabilityTool()._execute(
+ USER, session, review_id=review_id
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "tool_disabled"
+ db.get_reviews_by_node_exec_ids.assert_not_awaited()
+
+
+async def test_resume_mcp_review_waits_for_approval():
+ session = make_session(USER)
+ review_id = f"{COPILOT_MCP_NODE_PREFIX}mcp.example.com:cd34"
+ review = _review(review_id, ReviewStatus.WAITING, {}, session.session_id)
+ db = MagicMock()
+ db.get_reviews_by_node_exec_ids = AsyncMock(return_value={review_id: review})
+ with patch("backend.copilot.tools.resume_capability.review_db", return_value=db):
+ result = await ResumeCapabilityTool()._execute(
+ USER, session, review_id=review_id
+ )
+ assert isinstance(result, ErrorResponse) and "not been approved" in result.message
diff --git a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
index fa80a772b4..a054c0ffec 100644
--- a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
@@ -25,7 +25,7 @@ logger = logging.getLogger(__name__)
class ContinueRunBlockTool(BaseTool):
"""Tool for continuing a block execution after human review approval."""
- # Returns execute_block's result, same as run_block.
+ # Returns execute_block's result, same as run_capability.
digest_large_output = True
@property
@@ -34,7 +34,7 @@ class ContinueRunBlockTool(BaseTool):
@property
def description(self) -> str:
- return "Resume block execution after a run_block call returned review_required. Pass the review_id."
+ return "Resume block execution after a run_capability call returned review_required. Pass the review_id."
@property
def parameters(self) -> dict[str, Any]:
@@ -81,7 +81,7 @@ class ContinueRunBlockTool(BaseTool):
return ErrorResponse(
message=(
f"Review '{review_id}' not found or already executed. "
- "It may have been consumed by a previous continue_run_block call."
+ "It may have been consumed by a previous resume_capability call."
),
session_id=session_id,
)
@@ -140,8 +140,8 @@ class ContinueRunBlockTool(BaseTool):
session_id=session_id,
)
- # dry_run=False is safe here: run_block's dry-run fast-path (line ~241)
- # skips HITL entirely, so continue_run_block is never called during a
+ # dry_run=False is safe here: run_capability's dry-run fast-path skips
+ # HITL entirely, so resume_capability is never called during a
# dry run — only real executions reach the human review gate.
result = await execute_block(
block=block,
diff --git a/autogpt_platform/backend/backend/copilot/tools/create_agent.py b/autogpt_platform/backend/backend/copilot/tools/create_agent.py
index bb74f806c8..406c37dfea 100644
--- a/autogpt_platform/backend/backend/copilot/tools/create_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/create_agent.py
@@ -120,7 +120,7 @@ class CreateAgentTool(BaseTool):
"Please provide agent_json with the complete agent graph "
'(inline or as an "@@agptfile:<path>" string), or '
"agent_json_ref pointing at the workspace agent file. "
- "Use find_block to discover blocks, then generate the JSON."
+ 'Use find_capability(context="graph") to discover blocks, then generate the JSON.'
),
)
if resolve_error is not None:
diff --git a/autogpt_platform/backend/backend/copilot/tools/describe_capability.py b/autogpt_platform/backend/backend/copilot/tools/describe_capability.py
new file mode 100644
index 0000000000..8612f08e98
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/describe_capability.py
@@ -0,0 +1,185 @@
+"""Full input/output schema for one capability, fetched on demand so the
+search index never carries schemas."""
+
+import logging
+from typing import Any
+
+from backend.copilot.capabilities.models import CapabilityEntry
+from backend.copilot.capabilities.registry import configured_tool, get_registry
+from backend.copilot.capabilities.resolve import resolve_entry
+from backend.copilot.capabilities.schema_trim import collapse_large_enums
+from backend.copilot.capabilities.sources.mcp_catalog import setup_hint
+from backend.copilot.model import ChatSession
+from backend.copilot.permissions import BLOCK_GATE, MCP_GATE
+
+from .base import BaseTool
+from .capability_gates import gate_denied, gate_denied_error
+from .models import (
+ BlockDetailsResponse,
+ CapabilityDetailsResponse,
+ ErrorResponse,
+ MCPToolsDiscoveredResponse,
+ ToolResponseBase,
+)
+from .run_block import RunBlockTool
+from .run_mcp_tool import RunMCPToolTool
+
+logger = logging.getLogger(__name__)
+
+UNKNOWN_ID_HINT = (
+ "Unknown capability id. Use the exact 'id' from a find_capability result "
+ "(tool:<name>, block:<uuid>, mcp:<host>)."
+)
+
+# Input shape for run_capability on an MCP server entry.
+MCP_RUN_PARAMETERS: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "tool": {"type": "string", "description": "Tool name from the server's list."},
+ "arguments": {"type": "object", "description": "Arguments for that tool."},
+ "connect": {
+ "type": "boolean",
+ "description": (
+ "Only surface the sign-in card for this server (no call). Use "
+ "for 'connect to X' with no action."
+ ),
+ },
+ },
+}
+
+
+class DescribeCapabilityTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "describe_capability"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Inputs and outputs of one capability by id, before its first use. "
+ "Blocks return their schema; MCP servers list their tools; platform "
+ "tools return their parameters. Large enums are sampled unless "
+ "expand=true."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Capability id from find_capability.",
+ },
+ "expand": {
+ "type": "boolean",
+ "description": "Return every enum value instead of a sample.",
+ "default": False,
+ },
+ },
+ "required": ["id"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ id: str = "",
+ expand: bool = False,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+ entry = resolve_entry(get_registry(), id)
+ if entry is None:
+ return ErrorResponse(message=UNKNOWN_ID_HINT, session_id=session_id)
+ # Describing answers to the gate that running does. An MCP
+ # description is not a local lookup -- it connects to the server to
+ # list its tools -- and a block's schema is what a withheld block
+ # was withheld from revealing.
+ if entry.kind == "block":
+ if gate_denied(BLOCK_GATE):
+ return gate_denied_error("blocks", session_id)
+ return await _describe_block(entry, user_id, session, expand)
+ if entry.kind == "tool":
+ name = entry.implementations[0].ref
+ if gate_denied(name):
+ return gate_denied_error(name, session_id)
+ return _describe_tool(entry, session_id, expand)
+ if entry.kind == "mcp_server":
+ if gate_denied(MCP_GATE):
+ return gate_denied_error("MCP servers", session_id)
+ return await _describe_mcp(entry, user_id, session)
+ return ErrorResponse(
+ message=f"Capabilities of kind '{entry.kind}' cannot be described yet.",
+ session_id=session_id,
+ )
+
+
+async def _describe_block(
+ entry: CapabilityEntry, user_id: str, session: ChatSession, expand: bool
+) -> ToolResponseBase:
+ block_id = _block_ref(entry) or ""
+ result = await RunBlockTool()._execute(
+ user_id, session, block_id=block_id, input_data={}, validate_only=True
+ )
+ if isinstance(result, BlockDetailsResponse):
+ result.message = (
+ f"{result.message} Run it with run_capability(id='{entry.id}', "
+ "input={...}); credentials are resolved by the platform."
+ )
+ if not expand:
+ result.block.inputs = collapse_large_enums(result.block.inputs)
+ result.block.outputs = collapse_large_enums(result.block.outputs)
+ return result
+
+
+def _describe_tool(
+ entry: CapabilityEntry, session_id: str, expand: bool
+) -> ToolResponseBase:
+ tool = configured_tool(entry.implementations[0].ref)
+ if tool is None:
+ return ErrorResponse(message=UNKNOWN_ID_HINT, session_id=session_id)
+ parameters = tool.parameters if expand else collapse_large_enums(tool.parameters)
+ return CapabilityDetailsResponse(
+ message=(
+ f"{tool.description} Run it with run_capability(id='{entry.id}', "
+ "input={...}) where input matches these parameters."
+ ),
+ capability=entry.listing(),
+ parameters=parameters,
+ session_id=session_id,
+ )
+
+
+async def _describe_mcp(
+ entry: CapabilityEntry, user_id: str, session: ChatSession
+) -> ToolResponseBase:
+ server_url = entry.implementations[0].ref
+ if not server_url:
+ return ErrorResponse(
+ message=setup_hint(entry.schema_ref or entry.id),
+ session_id=session.session_id,
+ )
+ result = await RunMCPToolTool()._execute(user_id, session, server_url=server_url)
+ if isinstance(result, MCPToolsDiscoveredResponse):
+ result.message = (
+ f"{entry.name} exposes {len(result.tools)} tool(s); `params` lists each "
+ "tool's arguments with required ones marked *. Run one with "
+ f"run_capability(id='{entry.id}', input={{'tool': <name>, 'arguments': "
+ "{...}}). An argument error returns that tool's schema; do not re-list."
+ )
+ return result
+
+
+def _block_ref(entry: CapabilityEntry) -> str | None:
+ return next(
+ (impl.ref for impl in entry.implementations if impl.kind == "block"), None
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_chats_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_chats_test.py
index 045eaeef7e..ff57160dca 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_chats_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_chats_test.py
@@ -26,8 +26,8 @@ from backend.copilot.model import ChatMessage, ChatSessionInfo, ChatSessionMetad
from backend.copilot.tools import (
TOOL_GROUPS,
execute_tool,
- get_available_tools,
get_tool,
+ reachable_tool_names,
)
from .expert_chats import _MAX_PAGE_CHARS, ListExpertChatsTool, ReadExpertChatTool
@@ -169,16 +169,16 @@ class TestGating:
assert TOOL_GROUPS["list_expert_chats"] == "expert_admin"
assert TOOL_GROUPS["read_expert_chat"] == "expert_admin"
- def test_an_autopilot_session_is_offered_them_and_an_expert_session_is_not(
+ def test_an_autopilot_session_can_reach_them_and_an_expert_session_cannot(
self,
) -> None:
- autopilot = {t["function"]["name"] for t in get_available_tools()}
+ # Both tools are deferred, so ask what the session can reach through
+ # run_capability, not what it declares — the schema list leaves them
+ # out of both sides and would pass whether the group gate works or not.
+ autopilot = reachable_tool_names()
# What survives the filter, NOT what it hid — naming this `hidden`
# invites "fixing" the assertion below into its own inverse.
- expert = {
- t["function"]["name"]
- for t in get_available_tools(disabled_groups=["expert_admin"])
- }
+ expert = reachable_tool_names(disabled_groups=["expert_admin"])
assert {"list_expert_chats", "read_expert_chat"} <= autopilot
assert not {"list_expert_chats", "read_expert_chat"} & expert
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_block.py b/autogpt_platform/backend/backend/copilot/tools/find_block.py
index 856fa3b279..883767754d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_block.py
@@ -6,6 +6,10 @@ from prisma.enums import ContentType
from backend.blocks import get_block, get_blocks
from backend.blocks._base import BlockType
+from backend.copilot.capabilities.block_meta import (
+ COPILOT_EXCLUDED_BLOCK_IDS,
+ COPILOT_EXCLUDED_BLOCK_TYPES,
+)
from backend.copilot.context import get_current_permissions
from backend.copilot.model import ChatSession
from backend.data.db_accessors import search
@@ -29,29 +33,6 @@ _OVERFETCH_PAGE_SIZE = 40
# Cap on registry hits for queries that name a block class directly.
_MAX_EXACT_NAME_MATCHES = 3
-# Block types that only work within graphs and cannot run standalone in CoPilot.
-COPILOT_EXCLUDED_BLOCK_TYPES = {
- BlockType.INPUT, # Graph interface definition - data enters via chat, not graph inputs
- BlockType.OUTPUT, # Graph interface definition - data exits via chat, not graph outputs
- BlockType.WEBHOOK, # Wait for external events - would hang forever in CoPilot
- BlockType.WEBHOOK_MANUAL, # Same as WEBHOOK
- BlockType.NOTE, # Visual annotation only - no runtime behavior
- BlockType.HUMAN_IN_THE_LOOP, # Pauses for human approval - CoPilot IS human-in-the-loop
- BlockType.AGENT, # AgentExecutorBlock requires execution_context - use run_agent tool
- BlockType.MCP_TOOL, # Has dedicated run_mcp_tool tool with discovery + auth flow
-}
-
-# Specific block IDs excluded from CoPilot (STANDARD type but still require graph context)
-COPILOT_EXCLUDED_BLOCK_IDS = {
- # OrchestratorBlock - dynamically discovers downstream blocks via graph topology;
- # usable in agent graphs (guide hardcodes its ID) but cannot run standalone.
- "3b191d9f-356f-482d-8238-ba04b6d18381",
- # AutoPilotBlock - has dedicated run_sub_session tool with async start +
- # poll lifecycle. Calling it via run_block would block the parent stream
- # for the sub-Otto's entire runtime (15-45+ min typical).
- "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6",
-}
-
class FindBlockTool(BaseTool):
"""Tool for searching available blocks."""
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_capability.py b/autogpt_platform/backend/backend/copilot/tools/find_capability.py
new file mode 100644
index 0000000000..2669458776
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/find_capability.py
@@ -0,0 +1,159 @@
+"""Search the capability registry: integrations, blocks, MCP servers and
+platform tools behind one query."""
+
+import logging
+from typing import Any
+
+from backend.copilot.capabilities.index import SearchHit
+from backend.copilot.capabilities.models import CapabilityKindName
+from backend.copilot.capabilities.registry import get_registry
+from backend.copilot.capabilities.resolve import load_connection_state
+from backend.copilot.context import get_current_permissions
+from backend.copilot.model import ChatSession
+
+from .base import BaseTool
+from .models import (
+ CapabilityListResponse,
+ ErrorResponse,
+ NoResultsResponse,
+ ToolResponseBase,
+)
+
+logger = logging.getLogger(__name__)
+
+CONTEXTS = ("direct", "graph")
+KINDS = ("tool", "block", "mcp_server")
+_KIND_ARG: dict[str, CapabilityKindName] = {
+ "tool": "tool",
+ "block": "block",
+ "mcp_server": "mcp_server",
+}
+
+
+class FindCapabilityTool(BaseTool):
+ """Ranked capability search with connection state."""
+
+ @property
+ def name(self) -> str:
+ return "find_capability"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Search everything the platform can do: integrations, blocks, MCP "
+ "servers and platform tools, by service name or action. Results are "
+ "ranked and show whether the user has connected each one. Call this "
+ "before saying something is not possible. Then describe_capability(id) "
+ "to see inputs, and run_capability(id, input) to act."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": (
+ "Service, action or name, e.g. 'linear issue', "
+ "'send email', 'http request', 'sentry'."
+ ),
+ },
+ "context": {
+ "type": "string",
+ "enum": list(CONTEXTS),
+ "description": (
+ "'direct' (default) for things to run now; 'graph' when "
+ "choosing blocks for an agent graph (includes graph-only "
+ "blocks such as inputs and outputs)."
+ ),
+ "default": "direct",
+ },
+ "kind": {
+ "type": "string",
+ "enum": list(KINDS),
+ "description": "Restrict to one kind of capability.",
+ },
+ },
+ "required": ["query"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ query: str = "",
+ context: str = "direct",
+ kind: str | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ query = (query or "").strip()
+ session_id = session.session_id
+ if not query:
+ return ErrorResponse(
+ message="Please provide a query", session_id=session_id
+ )
+ if context not in CONTEXTS:
+ context = "direct"
+ if kind is not None and kind not in KINDS:
+ return ErrorResponse(
+ message=f"kind must be one of {', '.join(KINDS)}",
+ session_id=session_id,
+ )
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+
+ connections = await load_connection_state(user_id)
+ result = get_registry().search(
+ query,
+ context="graph" if context == "graph" else "direct",
+ kind=_KIND_ARG.get(kind or ""),
+ connections=connections,
+ permissions=get_current_permissions(),
+ )
+ if not result.hits and not result.fallback:
+ return NoResultsResponse(
+ message=f"No capability found for '{query}'",
+ suggestions=[
+ "Try the service name alone, or a broader action ('email', 'sheet', 'http')",
+ "For a service with no result, web_search '<service> MCP server' and "
+ "call run_capability with the server URL as the id",
+ ],
+ session_id=session_id,
+ )
+ return CapabilityListResponse(
+ message=_message(result.service, len(result.hits), len(result.fallback)),
+ query=query,
+ capabilities=[_listing(hit) for hit in result.hits],
+ count=len(result.hits),
+ fallback=[_listing(hit) for hit in result.fallback],
+ service=result.service,
+ session_id=session_id,
+ )
+
+
+def _listing(hit: SearchHit) -> dict[str, Any]:
+ listing = hit.entry.listing()
+ if hit.entry.connection.required:
+ listing["connected"] = hit.connected
+ return listing
+
+
+def _message(service: str | None, hits: int, fallback: int) -> str:
+ parts = [f"Found {hits} capabilit{'y' if hits == 1 else 'ies'}"]
+ if service:
+ parts.append(f"for {service}")
+ text = " ".join(parts) + "."
+ if fallback:
+ text += f" {fallback} generic fallback(s) listed separately."
+ return (
+ f"{text} Call describe_capability(id) before first use, then "
+ "run_capability(id, input). connected=false means the user must sign in "
+ "first: run_capability returns the sign-in card."
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide_test.py b/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide_test.py
index 950486771f..3c98dd90a6 100644
--- a/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide_test.py
@@ -199,12 +199,13 @@ async def test_enter_building_mode_noop_when_already_active():
def test_enter_building_mode_available_on_baseline():
- """enter_agent_building_mode is offered on the baseline path too — it
+ """enter_agent_building_mode is reachable on the baseline path too — it
branches per path (SDK restart / engine switch / inline guide on
- SDK-less deployments)."""
- from backend.copilot.tools import get_available_tools
+ SDK-less deployments). Both tools are deferred, so the model reaches
+ them by id through run_capability rather than from the schema list."""
+ from backend.copilot.tools import reachable_tool_names
- names = {t["function"]["name"] for t in get_available_tools()}
+ names = reachable_tool_names()
assert "enter_agent_building_mode" in names
assert "get_agent_building_guide" in names
diff --git a/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py b/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py
deleted file mode 100644
index 9166789ebf..0000000000
--- a/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py
+++ /dev/null
@@ -1,76 +0,0 @@
-"""GetMCPGuideTool - Returns the MCP tool usage guide."""
-
-import logging
-from pathlib import Path
-from typing import Any
-
-from backend.copilot.model import ChatSession
-from backend.integrations.mcp_guide import render_mcp_guide
-
-from .base import BaseTool
-from .models import ErrorResponse, ResponseType, ToolResponseBase
-
-logger = logging.getLogger(__name__)
-
-_GUIDE_CACHE: str | None = None
-
-
-def _load_guide() -> str:
- global _GUIDE_CACHE
- if _GUIDE_CACHE is None:
- guide_path = Path(__file__).parent.parent / "sdk" / "mcp_tool_guide.md"
- _GUIDE_CACHE = render_mcp_guide(guide_path.read_text(encoding="utf-8"))
- return _GUIDE_CACHE
-
-
-class MCPGuideResponse(ToolResponseBase):
- """Response containing the MCP tool guide."""
-
- type: ResponseType = ResponseType.MCP_GUIDE
- content: str
-
-
-class GetMCPGuideTool(BaseTool):
- """Returns the MCP tool usage guide with known server URLs and auth details."""
-
- @property
- def name(self) -> str:
- return "get_mcp_guide"
-
- @property
- def description(self) -> str:
- return "Get MCP server URLs and auth guide. Call before run_mcp_tool if you need a server URL or auth info."
-
- @property
- def parameters(self) -> dict[str, Any]:
- return {
- "type": "object",
- "properties": {},
- "required": [],
- }
-
- @property
- def requires_auth(self) -> bool:
- return False
-
- async def _execute(
- self,
- user_id: str | None,
- session: ChatSession,
- **kwargs, # no tool-specific params; accepts kwargs for forward-compat
- ) -> ToolResponseBase:
- session_id = session.session_id if session else None
- try:
- content = _load_guide()
- return MCPGuideResponse(
- message="MCP guide loaded.",
- content=content,
- session_id=session_id,
- )
- except Exception as e:
- logger.error("Failed to load MCP guide: %s", e)
- return ErrorResponse(
- message="Failed to load MCP guide.",
- error=str(e),
- session_id=session_id,
- )
diff --git a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py
index 9deaf100cf..4cbf2a159d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py
@@ -719,26 +719,31 @@ class TestExecuteToolEnforcesDisabledGroups:
handed to the model — a presentation filter. ``execute_tool`` is the
actual enforcement boundary: a model that names a hidden tool anyway
must be refused BEFORE ``tool.execute`` runs, not just told about it
- afterwards."""
+ afterwards.
+
+ Both cases use an eager tool on purpose. A deferred one is refused here
+ whatever its group, so it cannot tell a working group gate from a broken
+ one — and it can never dispatch, which is the point of the second test.
+ """
@pytest.mark.asyncio
async def test_a_tool_in_a_disabled_group_is_refused_without_dispatching(
self,
) -> None:
session = _session()
- tool = get_tool("hire_expert")
+ tool = get_tool("handoff_to_expert")
assert tool is not None
with patch.object(
tool, "execute", new=AsyncMock(return_value="should never run")
) as execute_mock:
result = await execute_tool(
- tool_name="hire_expert",
+ tool_name="handoff_to_expert",
parameters={},
user_id="alice",
session=session,
tool_call_id="call-1",
- disabled_groups=["expert_admin"],
+ disabled_groups=["experts"],
disabled_tools=(),
)
@@ -750,14 +755,14 @@ class TestExecuteToolEnforcesDisabledGroups:
@pytest.mark.asyncio
async def test_a_tool_outside_any_disabled_group_still_dispatches(self) -> None:
session = _session()
- tool = get_tool("hire_expert")
+ tool = get_tool("handoff_to_expert")
assert tool is not None
with patch.object(
tool, "execute", new=AsyncMock(return_value="it ran")
) as execute_mock:
result = await execute_tool(
- tool_name="hire_expert",
+ tool_name="handoff_to_expert",
parameters={},
user_id="alice",
session=session,
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index b1f6f0f2b5..e617f30d9e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -6,13 +6,13 @@ import logging
import uuid
from collections import defaultdict
from dataclasses import dataclass
-from functools import cache
from typing import Any
from pydantic_core import PydanticUndefined
from backend.blocks import BlockType, get_block
-from backend.blocks._base import AnyBlockSchema, BlockSchemaInput
+from backend.blocks._base import AnyBlockSchema
+from backend.copilot.capabilities.block_meta import get_block_provider
from backend.copilot.constants import (
COPILOT_NODE_EXEC_ID_SEPARATOR,
COPILOT_NODE_PREFIX,
@@ -220,33 +220,6 @@ async def _charge_block_credits(
# BILLING_LEAK log above is the signal for reconciliation.
-def get_block_provider(block: AnyBlockSchema) -> str | None:
- """Sole integration provider slug for a block, or None when the block
- uses zero or multiple providers."""
- try:
- return _get_input_schema_provider(block.input_schema)
- except Exception:
- logger.debug(
- "Unable to determine integration provider for block input schema %r",
- block.input_schema,
- exc_info=True,
- )
- return None
-
-
-@cache
-def _get_input_schema_provider(input_schema: type[BlockSchemaInput]) -> str | None:
- infos = input_schema.get_credentials_fields_info()
- providers = {
- ProviderName(provider).value
- for info in infos.values()
- for provider in info.provider
- }
- if len(providers) != 1:
- return None
- return next(iter(providers))
-
-
async def execute_block(
*,
block: AnyBlockSchema,
@@ -267,8 +240,8 @@ async def execute_block(
``expert_id`` is the session's expert; it attributes the run so
``workspace://`` inputs resolve inside that expert's file scope.
- This is the shared execution path used by both ``run_block`` (after review
- check) and ``continue_run_block`` (after approval).
+ This is the shared execution path used by both ``run_capability`` (after
+ review check) and ``resume_capability`` (after approval).
Returns:
BlockOutputResponse on success, ErrorResponse on failure.
@@ -540,7 +513,7 @@ async def execute_block(
# keep hitting the cap — candidates for prompt tuning or
# escalation to the async start+poll pattern.
logger.warning(
- "copilot_tool_timeout tool=run_block block=%s block_id=%s "
+ "copilot_tool_timeout tool=run_capability block=%s block_id=%s "
"input_keys=%s user=%s session=%s cap_s=%d",
block.name,
block_id,
@@ -791,7 +764,7 @@ async def prepare_block_for_execution(
input schema generation, file-ref expansion, missing-credentials check, and
unrecognized-field validation.
- Does NOT check for missing required fields (tools differ: run_block shows a
+ Does NOT check for missing required fields (tools differ: run_capability shows a
schema preview) and does NOT run the HITL review check (use check_hitl_review
separately).
@@ -827,7 +800,7 @@ async def prepare_block_for_execution(
):
if block.block_type == BlockType.MCP_TOOL:
hint = (
- " Use the `run_mcp_tool` tool instead — it handles "
+ " Use run_capability on the MCP server entry from find_capability instead — it handles "
"MCP server discovery, authentication, and execution."
)
elif block.block_type == BlockType.AGENT:
@@ -1019,7 +992,7 @@ async def check_hitl_review(
return ReviewRequiredResponse(
message=(
f"Block '{block.name}' requires human review. "
- f"After the user approves, call continue_run_block with "
+ f"After the user approves, call resume_capability with "
f"review_id='{existing_review.node_exec_id}' to execute."
),
session_id=session_id,
@@ -1060,7 +1033,7 @@ async def check_hitl_review(
return ReviewRequiredResponse(
message=(
f"Block '{block.name}' requires human review. "
- f"After the user approves, call continue_run_block with "
+ f"After the user approves, call resume_capability with "
f"review_id='{synthetic_node_exec_id}' to execute."
),
session_id=session_id,
@@ -1102,7 +1075,7 @@ async def check_spend_approval(
return ReviewRequiredResponse(
message=(
f"{needed.headline}. Tell the user, and after they approve "
- "call run_block again with the same input."
+ "call run_capability again with the same input."
),
session_id=session.session_id,
block_id=prep.block_id,
diff --git a/autogpt_platform/backend/backend/copilot/tools/mcp_catalog_guide_test.py b/autogpt_platform/backend/backend/copilot/tools/mcp_catalog_guide_test.py
deleted file mode 100644
index 3f6314ee33..0000000000
--- a/autogpt_platform/backend/backend/copilot/tools/mcp_catalog_guide_test.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from unittest.mock import patch
-
-from backend.copilot.tools.get_mcp_guide import _load_guide
-from backend.copilot.tools.skills import get_default_skill_with_body
-from backend.integrations.mcp_guide import MCP_CATALOG_MARKER
-
-
-def test_both_guide_loaders_render_the_catalogue():
- with patch("backend.copilot.tools.get_mcp_guide._GUIDE_CACHE", None):
- legacy = _load_guide()
- skill = get_default_skill_with_body("mcp_tool_guide")
-
- assert skill is not None
- assert legacy == skill.body
- assert MCP_CATALOG_MARKER not in legacy
- assert "Additional official connections" in legacy
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index b504394208..e2c3488da0 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -46,6 +46,10 @@ class ResponseType(str, Enum):
BLOCK_OUTPUT = "block_output"
REVIEW_REQUIRED = "review_required"
+ # Capability registry (find/describe/run_capability)
+ CAPABILITY_LIST = "capability_list"
+ CAPABILITY_DETAILS = "capability_details"
+
# Schedules
SCHEDULE_LIST = "schedule_list"
SCHEDULE_DELETED = "schedule_deleted"
@@ -919,18 +923,41 @@ class BlockInfoSummary(BaseModel):
class BlockListResponse(ToolResponseBase):
- """Response for find_block tool."""
+ """Response for a block search (find_capability / legacy find_block)."""
type: ResponseType = ResponseType.BLOCK_LIST
blocks: list[BlockInfoSummary]
count: int
query: str
usage_hint: str = Field(
- default="To execute a block, call run_block with block_id set to the block's "
- "'id' field and input_data containing the fields listed in required_inputs."
+ default="To execute a block, call run_capability with id set to the block's "
+ "'id' field and input containing the fields listed in required_inputs."
)
+class CapabilityListResponse(ToolResponseBase):
+ """Ranked capabilities for a ``find_capability`` query. Each entry is a
+ compact listing (id, name, purpose, kind, class, connected)."""
+
+ type: ResponseType = ResponseType.CAPABILITY_LIST
+ query: str
+ capabilities: list[dict[str, Any]]
+ count: int
+ # Generic primitives offered when the query named a service.
+ fallback: list[dict[str, Any]] = Field(default_factory=list)
+ service: str | None = None
+
+
+class CapabilityDetailsResponse(ToolResponseBase):
+ """Schema for one capability whose implementation is a platform tool.
+ Blocks and MCP servers describe themselves with their existing
+ ``block_details`` / ``mcp_tools_discovered`` responses."""
+
+ type: ResponseType = ResponseType.CAPABILITY_DETAILS
+ capability: dict[str, Any]
+ parameters: dict[str, Any] = Field(default_factory=dict)
+
+
class BlockDetails(BaseModel):
"""Detailed block information."""
@@ -943,7 +970,7 @@ class BlockDetails(BaseModel):
class BlockDetailsResponse(ToolResponseBase):
- """Response for block details (first run_block attempt)."""
+ """Response for block details (describe_capability / first run attempt)."""
type: ResponseType = ResponseType.BLOCK_DETAILS
block: BlockDetails
@@ -951,7 +978,7 @@ class BlockDetailsResponse(ToolResponseBase):
class BlockOutputResponse(ToolResponseBase):
- """Response for run_block tool."""
+ """Response for a block run via run_capability."""
type: ResponseType = ResponseType.BLOCK_OUTPUT
block_id: str
diff --git a/autogpt_platform/backend/backend/copilot/tools/resume_capability.py b/autogpt_platform/backend/backend/copilot/tools/resume_capability.py
new file mode 100644
index 0000000000..17366d9953
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/resume_capability.py
@@ -0,0 +1,241 @@
+"""Resume a ``run_capability`` call that paused for human review.
+
+Block reviews replay through the existing ``ContinueRunBlockTool`` path; MCP
+reviews (synthetic ``copilot-mcp-`` node ids) replay the stored call. With
+``input_overrides`` the call is re-issued as a fresh run with the merged
+input, so every gate (credentials, review, spend) is evaluated again rather
+than trusting the stored approval for different data.
+"""
+
+import logging
+from typing import Any
+
+from prisma.enums import ReviewStatus
+
+from backend.blocks.mcp.helpers import server_host
+from backend.copilot.capabilities.mcp_review import (
+ MCPReviewPayload,
+ is_mcp_review_id,
+ open_mcp_review,
+)
+from backend.copilot.constants import (
+ COPILOT_NODE_PREFIX,
+ COPILOT_SESSION_PREFIX,
+ SPEND_REVIEW_MARKER,
+ parse_node_id_from_exec_id,
+)
+from backend.copilot.model import ChatSession
+from backend.copilot.permissions import BLOCK_GATE, MCP_GATE
+from backend.data.db_accessors import review_db
+
+from .base import BaseTool
+from .capability_gates import gate_denied, gate_denied_error
+from .continue_run_block import ContinueRunBlockTool
+from .models import ErrorResponse, ReviewRequiredResponse, ToolResponseBase
+from .run_block import RunBlockTool
+from .run_mcp_tool import RunMCPToolTool
+
+logger = logging.getLogger(__name__)
+
+
+class ResumeCapabilityTool(BaseTool):
+ digest_large_output = True
+
+ @property
+ def name(self) -> str:
+ return "resume_capability"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Resume a run_capability call that returned review_required, after the "
+ "user approved it. Pass the review_id. input_overrides re-runs the call "
+ "with changed input instead (it may ask for approval again)."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "review_id": {
+ "type": "string",
+ "description": "review_id from the review_required response.",
+ },
+ "input_overrides": {
+ "type": "object",
+ "description": "Fields to change before re-running.",
+ },
+ },
+ "required": ["review_id"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ review_id: str = "",
+ input_overrides: dict[str, Any] | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ review_id = (review_id or "").strip()
+ session_id = session.session_id
+ if not review_id:
+ return ErrorResponse(
+ message="Please provide a review_id", session_id=session_id
+ )
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+ if input_overrides is not None and not isinstance(input_overrides, dict):
+ return ErrorResponse(
+ message="input_overrides must be an object", session_id=session_id
+ )
+ if SPEND_REVIEW_MARKER in review_id:
+ # A spend approval releases an expert's budget; there is no block
+ # behind it to re-run, and parsing one out of the id fails.
+ return ErrorResponse(
+ message=(
+ "That review is a spend approval, not a paused capability. "
+ "It releases an expert's budget once the user approves it, "
+ "and there is nothing here to resume."
+ ),
+ session_id=session.session_id,
+ )
+ # Resuming runs the capability, so it answers to the gate the run
+ # would have. Permissions, hidden tools and the turn envelope are all
+ # rebuilt per turn, and an approval from an earlier turn is not a
+ # standing exemption from the permissions of this one.
+ if is_mcp_review_id(review_id):
+ if gate_denied(MCP_GATE):
+ return gate_denied_error("MCP servers", session_id)
+ return await _resume_mcp(review_id, user_id, session, input_overrides)
+ if gate_denied(BLOCK_GATE):
+ return gate_denied_error("blocks", session_id)
+ if input_overrides:
+ return await _rerun_block(review_id, user_id, session, input_overrides)
+ return await ContinueRunBlockTool()._execute(
+ user_id, session, review_id=review_id
+ )
+
+
+async def _load_approved_review(
+ review_id: str, user_id: str, session: ChatSession
+) -> Any | ErrorResponse:
+ session_id = session.session_id
+ reviews = await review_db().get_reviews_by_node_exec_ids([review_id], user_id)
+ review = reviews.get(review_id)
+ if not review:
+ return ErrorResponse(
+ message=(
+ f"Review '{review_id}' not found or already executed. It may have "
+ "been consumed by an earlier resume_capability call."
+ ),
+ session_id=session_id,
+ )
+ if review.graph_exec_id != f"{COPILOT_SESSION_PREFIX}{session_id}":
+ return ErrorResponse(
+ message="Review does not belong to this session.", session_id=session_id
+ )
+ if review.status == ReviewStatus.WAITING:
+ return ErrorResponse(
+ message="Review has not been approved yet. Wait for the user to approve it.",
+ session_id=session_id,
+ )
+ if review.status == ReviewStatus.REJECTED:
+ return ErrorResponse(
+ message="Review was rejected. The capability will not run.",
+ session_id=session_id,
+ )
+ return review
+
+
+async def _resume_mcp(
+ review_id: str,
+ user_id: str,
+ session: ChatSession,
+ input_overrides: dict[str, Any] | None,
+) -> ToolResponseBase:
+ review = await _load_approved_review(review_id, user_id, session)
+ if isinstance(review, ErrorResponse):
+ return review
+ stored = review.payload if isinstance(review.payload, dict) else {}
+ try:
+ payload = MCPReviewPayload.model_validate(stored)
+ except ValueError:
+ return ErrorResponse(
+ message="Stored review payload is not an MCP call.",
+ session_id=session.session_id,
+ )
+ arguments = {**payload.arguments, **(input_overrides or {})}
+ if arguments != payload.arguments:
+ # The user approved one call, not a family of them. This review only
+ # exists because the original call needed approving, so the changed
+ # call needs approving too. Re-deriving that from the live catalog
+ # instead would mean a server added to it since approval turns the
+ # replay -- which a prompt injection can steer -- into an unreviewed
+ # call on arguments nobody ever saw.
+ host = server_host(payload.server_url)
+ fresh = MCPReviewPayload(
+ server_url=payload.server_url, tool=payload.tool, arguments=arguments
+ )
+ new_id = await open_mcp_review(
+ user_id=user_id,
+ session_id=session.session_id,
+ host=host,
+ payload=fresh,
+ organization_id=session.organization_id,
+ team_id=session.team_id,
+ )
+ return ReviewRequiredResponse(
+ message=(
+ f"The arguments changed since the user approved "
+ f"'{payload.tool}' on {host}, so it needs approving again. "
+ f"Tell the user what changed; after they approve, call "
+ f"resume_capability(review_id='{new_id}')."
+ ),
+ session_id=session.session_id,
+ block_id=payload.server_url,
+ block_name=f"{host}/{payload.tool}",
+ review_id=new_id,
+ graph_exec_id=f"{COPILOT_SESSION_PREFIX}{session.session_id}",
+ input_data=fresh.model_dump(),
+ )
+ result = await RunMCPToolTool()._execute(
+ user_id,
+ session,
+ server_url=payload.server_url,
+ tool_name=payload.tool,
+ tool_arguments=arguments,
+ )
+ # A sign-in card or a fresh review means the call has not run, so the
+ # approval must survive for the retry that follows.
+ if result.type not in ("error", "setup_requirements", "review_required"):
+ await review_db().delete_review_by_node_exec_id(review_id, user_id)
+ return result
+
+
+async def _rerun_block(
+ review_id: str,
+ user_id: str,
+ session: ChatSession,
+ input_overrides: dict[str, Any],
+) -> ToolResponseBase:
+ review = await _load_approved_review(review_id, user_id, session)
+ if isinstance(review, ErrorResponse):
+ return review
+ block_id = parse_node_id_from_exec_id(review_id).removeprefix(COPILOT_NODE_PREFIX)
+ stored = review.payload if isinstance(review.payload, dict) else {}
+ result = await RunBlockTool()._execute(
+ user_id, session, block_id=block_id, input_data={**stored, **input_overrides}
+ )
+ # Delete only once the run has actually happened: dropping the review
+ # first left a failed run with nothing to retry from.
+ if result.type not in ("error", "setup_requirements", "review_required"):
+ await review_db().delete_review_by_node_exec_id(review_id, user_id)
+ return result
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.py
index cf09a86f1a..8bf3fed157 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py
@@ -9,7 +9,6 @@ from backend.copilot.constants import COPILOT_NODE_EXEC_ID_SEPARATOR
from backend.copilot.context import get_current_permissions
from backend.copilot.model import ChatSession
from backend.data.activity_event import ActivityEventDraft
-from backend.util.feature_flag import Flag, is_feature_enabled
from .base import BaseTool
from .helpers import (
@@ -42,12 +41,12 @@ class RunBlockTool(BaseTool):
@property
def description(self) -> str:
return (
- "Execute a block. IMPORTANT: Always get block_id from find_block first "
+ "Execute a block. IMPORTANT: Always get block_id from find_capability first "
"— do NOT guess or fabricate IDs. "
"Call with empty input_data to see schema, then with data to execute. "
"Pass `validate_only: true` to inspect a block without running it "
"(safe pre-flight — returns schema + detected missing inputs). "
- "If review_required, use continue_run_block."
+ "If review_required, use resume_capability."
)
@property
@@ -57,7 +56,7 @@ class RunBlockTool(BaseTool):
"properties": {
"block_id": {
"type": "string",
- "description": "Block ID from find_block results.",
+ "description": "Block ID from find_capability results.",
},
"input_data": {
"type": "object",
@@ -186,7 +185,7 @@ class RunBlockTool(BaseTool):
message=(
f"Block '{prep.block.name}' ({block_id}) is not permitted "
f"by the current execution permissions. {available_hint}"
- "Use find_block to discover blocks that are allowed."
+ "Use find_capability to discover blocks that are allowed."
),
session_id=session_id,
)
@@ -246,11 +245,8 @@ class RunBlockTool(BaseTool):
llm_input_schema = _strip_credentials_from_schema(
prep.input_schema, prep.credentials_fields
)
- if await is_feature_enabled(
- Flag.AUTOPILOT_CONTEXT_TRIMMING, user_id, default=False
- ):
- llm_input_schema = _strip_presentation_annotations(llm_input_schema)
- output_schema = _strip_presentation_annotations(output_schema)
+ llm_input_schema = _strip_presentation_annotations(llm_input_schema)
+ output_schema = _strip_presentation_annotations(output_schema)
if validate_only and not missing:
detail_msg = (
f"Block '{prep.block.name}' — all required inputs "
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
index 1eb76820c6..d378630da8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
@@ -832,7 +832,7 @@ class TestRunBlockSensitiveAction:
assert isinstance(response, ReviewRequiredResponse)
assert "requires human review" in response.message
- assert "continue_run_block" in response.message
+ assert "resume_capability" in response.message
assert response.block_name == "Delete Branch"
@pytest.mark.asyncio(loop_scope="session")
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_capability.py b/autogpt_platform/backend/backend/copilot/tools/run_capability.py
new file mode 100644
index 0000000000..99a5e15114
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/run_capability.py
@@ -0,0 +1,273 @@
+"""Run one capability by id: a block, a platform tool or an MCP server.
+
+Dispatches to the existing implementations (``RunBlockTool``,
+``RunMCPToolTool``, the tool's own ``_execute``) so credential resolution,
+pickers, human review, spend approval, dry-run and error hints all keep
+working; this module only adds the id resolution and the per-kind gates.
+"""
+
+import logging
+from typing import Any
+from urllib.parse import urlsplit
+
+from backend.copilot.capabilities.mcp_review import (
+ MCPReviewPayload,
+ needs_review,
+ open_mcp_review,
+)
+from backend.copilot.capabilities.models import CapabilityEntry
+from backend.copilot.capabilities.registry import configured_tool, get_registry
+from backend.copilot.capabilities.resolve import resolve_entry
+from backend.copilot.capabilities.sources.mcp_catalog import setup_hint
+from backend.copilot.constants import COPILOT_SESSION_PREFIX
+from backend.copilot.model import ChatSession
+from backend.copilot.permissions import BLOCK_GATE, MCP_GATE
+from backend.copilot.tool_display import emit_tool_display_name
+from backend.data.activity_event import ActivityEventDraft
+
+from .base import BaseTool
+from .capability_gates import gate_denied, gate_denied_error
+from .describe_capability import MCP_RUN_PARAMETERS, UNKNOWN_ID_HINT
+from .models import (
+ CapabilityDetailsResponse,
+ ErrorResponse,
+ ReviewRequiredResponse,
+ ToolResponseBase,
+)
+from .run_block import RunBlockTool
+from .run_mcp_tool import RunMCPToolTool
+
+logger = logging.getLogger(__name__)
+
+
+class RunCapabilityTool(BaseTool):
+ digest_large_output = True
+
+ @property
+ def name(self) -> str:
+ return "run_capability"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Run a capability by id with its input (blocks: the block's inputs; "
+ "MCP servers: {tool, arguments}; platform tools: their parameters). "
+ "Never guess ids: take them from find_capability. An unconnected "
+ "capability returns a sign-in card: show it and stop. review_required "
+ "means wait for approval, then resume_capability(review_id). "
+ "validate_only=true inspects without running."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Capability id from find_capability, or an MCP server URL.",
+ },
+ "input": {
+ "type": "object",
+ "description": "Input for the capability; {} to see what it needs.",
+ },
+ "validate_only": {
+ "type": "boolean",
+ "description": "Describe what the call would need without running it.",
+ "default": False,
+ },
+ },
+ "required": ["id", "input"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ def activity_event(
+ self, session: ChatSession, result: ToolResponseBase, **kwargs
+ ) -> ActivityEventDraft | None:
+ entry = resolve_entry(get_registry(), str(kwargs.get("id", "")))
+ if entry is None:
+ return None
+ if entry.kind == "block":
+ return RunBlockTool().activity_event(session, result)
+ if entry.kind == "tool":
+ tool = configured_tool(entry.implementations[0].ref)
+ payload = kwargs.get("input") or {}
+ return tool.activity_event(session, result, **payload) if tool else None
+ return None
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ id: str = "",
+ input: dict[str, Any] | None = None,
+ validate_only: bool = False,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+ if input is not None and not isinstance(input, dict):
+ return ErrorResponse(
+ message="input must be an object", session_id=session_id
+ )
+ payload: dict[str, Any] = dict(input or {})
+ entry = resolve_entry(get_registry(), id)
+ if entry is None and id.strip().lower().startswith("https://"):
+ # Open world: a server URL the catalog does not know. The MCP
+ # path validates the host; writes pause for review.
+ return await _run_mcp(
+ None, id.strip(), user_id, session, payload, validate_only
+ )
+ if entry is None and id.strip().lower().startswith("http://"):
+ # Saying "unknown capability" here sent the model looking for a
+ # typo in an id that was simply the wrong scheme.
+ return ErrorResponse(
+ message=(
+ "MCP servers must be reached over https. Retry with the "
+ "https:// form of that URL, or ask the user for the "
+ "server's secure endpoint."
+ ),
+ session_id=session_id,
+ )
+ if entry is None:
+ return ErrorResponse(message=UNKNOWN_ID_HINT, session_id=session_id)
+ 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)
+ if entry.kind == "mcp_server":
+ server_url = entry.implementations[0].ref
+ if not server_url:
+ return ErrorResponse(
+ message=setup_hint(entry.schema_ref or entry.id),
+ session_id=session_id,
+ )
+ return await _run_mcp(
+ entry, server_url, user_id, session, payload, validate_only
+ )
+ return ErrorResponse(
+ message=f"Capabilities of kind '{entry.kind}' cannot run yet.",
+ session_id=session_id,
+ )
+
+
+async def _run_block(
+ entry: CapabilityEntry,
+ user_id: str,
+ session: ChatSession,
+ payload: dict[str, Any],
+ validate_only: bool,
+) -> ToolResponseBase:
+ if gate_denied(BLOCK_GATE):
+ return gate_denied_error("blocks", session.session_id)
+ block_id = next(
+ (impl.ref for impl in entry.implementations if impl.kind == "block"), ""
+ )
+ return await RunBlockTool()._execute(
+ user_id,
+ session,
+ block_id=block_id,
+ input_data=payload,
+ validate_only=validate_only,
+ )
+
+
+async def _run_tool(
+ entry: CapabilityEntry,
+ user_id: str,
+ session: ChatSession,
+ payload: dict[str, Any],
+ validate_only: bool,
+) -> ToolResponseBase:
+ 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)
+
+
+async def _run_mcp(
+ entry: CapabilityEntry | None,
+ server_url: str,
+ user_id: str,
+ session: ChatSession,
+ payload: dict[str, Any],
+ validate_only: bool,
+) -> ToolResponseBase:
+ if gate_denied(MCP_GATE):
+ return gate_denied_error("MCP servers", session.session_id)
+ tool_name = str(payload.get("tool") or "").strip()
+ arguments = payload.get("arguments")
+ if arguments is not None and not isinstance(arguments, dict):
+ return ErrorResponse(
+ message="input.arguments must be an object", session_id=session.session_id
+ )
+ connect = bool(payload.get("connect", False))
+ if validate_only:
+ return CapabilityDetailsResponse(
+ message=(
+ "MCP server input shape. Call without validate_only and without a "
+ "tool to list the server's tools."
+ ),
+ capability=(
+ entry.listing() if entry else {"id": server_url, "kind": "mcp_server"}
+ ),
+ parameters=MCP_RUN_PARAMETERS,
+ session_id=session.session_id,
+ )
+ host = urlsplit(server_url).hostname or server_url
+ if (
+ tool_name
+ and not session.dry_run
+ and needs_review(tool_name, catalog_server=entry is not None)
+ ):
+ review = MCPReviewPayload(
+ server_url=server_url, tool=tool_name, arguments=dict(arguments or {})
+ )
+ review_id = await open_mcp_review(
+ user_id=user_id,
+ session_id=session.session_id,
+ host=host,
+ payload=review,
+ organization_id=session.organization_id,
+ team_id=session.team_id,
+ )
+ return ReviewRequiredResponse(
+ message=(
+ f"'{tool_name}' on {host} looks like a write to a server outside the "
+ "official catalog, so it needs the user's approval. Tell the user; "
+ f"after they approve, call resume_capability(review_id='{review_id}')."
+ ),
+ session_id=session.session_id,
+ block_id=entry.id if entry else server_url,
+ block_name=f"{host}/{tool_name}",
+ review_id=review_id,
+ graph_exec_id=f"{COPILOT_SESSION_PREFIX}{session.session_id}",
+ input_data=review.model_dump(),
+ )
+ if tool_name:
+ emit_tool_display_name(f"{host}: {tool_name}")
+ return await RunMCPToolTool()._execute(
+ user_id,
+ session,
+ server_url=server_url,
+ tool_name=tool_name,
+ tool_arguments=dict(arguments or {}),
+ surface_connect_card=connect,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
index 4b7a4ce85e..92743708d8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
@@ -101,7 +101,7 @@ class RunMCPToolTool(BaseTool):
return (
"Discover and execute MCP server tools. "
"Call with server_url only to list tools, then with tool_name + tool_arguments to execute. "
- "Call get_mcp_guide first for server URLs and auth."
+ "Reached through run_capability on an MCP server entry."
)
@property
@@ -374,10 +374,28 @@ class RunMCPToolTool(BaseTool):
# not a rejection, so it stores, returns 2xx and greens the
# pill — and the next call 403s again. Reporting it as
# connected breaks that loop.
+ kept_credential = creds is not None and not credential_rejected
+ if kept_credential and tool_name:
+ # ...but on a *named tool call* the connected card reads as
+ # success and says nothing about the refusal, so the caller
+ # retries the same tool forever. Report the refusal.
+ host = server_host(server_url)
+ return ErrorResponse(
+ message=(
+ f"{_service_name(host)} refused '{tool_name}' with HTTP "
+ f"{e.status_code}. The sign-in is still valid, so this is "
+ "a permission or scope limit on that tool, not a missing "
+ "credential. Call run_capability without a tool to list "
+ "what this server actually exposes, or tell the user which "
+ "permission the account is missing."
+ ),
+ session_id=session_id,
+ error=f"HTTP {e.status_code}: {str(e)[:300]}",
+ )
return await self._build_setup_requirements(
server_url,
session_id,
- connected=creds is not None and not credential_rejected,
+ connected=kept_credential,
rejection=rejected,
user_id=user_id,
expert_id=session.expert_id,
@@ -419,7 +437,7 @@ class RunMCPToolTool(BaseTool):
) -> MCPToolsDiscoveredResponse:
"""List available tools from an already-initialized MCPClient.
- Called when the agent invokes run_mcp_tool with only server_url (no
+ Called when run_capability targets an MCP server with no tool (no
tool_name). Returns MCPToolsDiscoveredResponse so the agent can
inspect tool schemas and choose one to execute in a follow-up call.
"""
@@ -453,7 +471,7 @@ class RunMCPToolTool(BaseTool):
f"{truncation_note} Full input "
"schemas are omitted to save context — `params` lists each "
"tool's argument names with required ones marked `*`. Call "
- "run_mcp_tool again with tool_name and tool_arguments to "
+ "run_capability again with input {tool, arguments} to "
"execute one; if the arguments are wrong, the error response "
"includes a schema hint for that tool. Do NOT re-run "
"discovery after an argument error."
@@ -651,9 +669,18 @@ class RunMCPToolTool(BaseTool):
status = (
f" (HTTP {rejection.status_code})" if rejection.status_code else ""
)
+ # The provider usually says why, and it is often something no
+ # amount of signing in again will fix — Brevo answers "API Key
+ # is not enabled" for a key created without the MCP option, and
+ # names its IP allow-list for a call from an unrecognised
+ # address. Dropping that left the card telling the user to retry
+ # the one thing that cannot work.
+ reason = (rejection.detail or "").strip()
message = (
- f"{service} rejected the saved credential{status}. "
- "Sign in again to continue."
+ f"{service} rejected the saved credential{status}."
+ + (f" {reason[:400]}" if reason else "")
+ + " Sign in again if the credential is simply stale; "
+ "otherwise fix what the service reported first."
)
elif connected:
message = (
@@ -690,7 +717,10 @@ class RunMCPToolTool(BaseTool):
def _rejection(creds: OAuth2Credentials, error: HTTPClientError) -> CredentialRejection:
return CredentialRejection(
provider=ProviderName.MCP.value,
- detail=sanitize_provider_message(str(error)),
+ # Providers put the fix at the end of the sentence — Brevo's 401 names
+ # its IP allow-list page, and the default 200-character cap truncated
+ # that link away, leaving the user the complaint without the remedy.
+ detail=sanitize_provider_message(str(error), max_chars=400),
status_code=error.status_code,
credential_id=creds.id,
credential_title=creds.title,
diff --git a/autogpt_platform/backend/backend/copilot/tools/skills.py b/autogpt_platform/backend/backend/copilot/tools/skills.py
index a7a5c9273f..0b5b5fddc2 100644
--- a/autogpt_platform/backend/backend/copilot/tools/skills.py
+++ b/autogpt_platform/backend/backend/copilot/tools/skills.py
@@ -48,7 +48,6 @@ from backend.data.workspace_scope import (
expert_skills_folder,
)
from backend.executor.cluster_lock import AsyncClusterLock
-from backend.integrations.mcp_guide import render_mcp_guide
from backend.util.exceptions import ConflictError
from backend.util.feature_flag import Flag, is_feature_enabled
from backend.util.workspace import WorkspaceManager
@@ -153,8 +152,8 @@ _NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9_-]{0,62}[a-z0-9])?$")
# ---------------------------------------------------------------------------
-# Default skills — migrated from the legacy ``get_agent_building_guide`` /
-# ``get_mcp_guide`` tools so users get a uniform discovery surface. These
+# Default skills — migrated from the legacy ``get_agent_building_guide``
+# tool so users get a uniform discovery surface. These
# are *read-only* — store_skill / delete_skill refuse to touch them. Body
# is loaded from disk lazily so adding more defaults is a drop-in.
# ---------------------------------------------------------------------------
@@ -185,15 +184,6 @@ DEFAULT_SKILLS: tuple[_DefaultSkill, ...] = (
"fix_agent_graph",
),
),
- _DefaultSkill(
- name="mcp_tool_guide",
- description=(
- "MCP server URLs and auth setup — load before calling "
- "run_mcp_tool when you need server URLs or auth details."
- ),
- body_path=_SDK_DIR / "mcp_tool_guide.md",
- triggers=("run_mcp_tool",),
- ),
)
_DEFAULT_SKILLS_BY_NAME: dict[str, _DefaultSkill] = {s.name: s for s in DEFAULT_SKILLS}
@@ -374,7 +364,7 @@ def _load_default_body(skill: _DefaultSkill) -> str:
"""Read a default skill's body from disk (cached at module level
via :func:`functools.lru_cache` would re-read on test reloads, so
we hit the disk each call — these files are small)."""
- return render_mcp_guide(skill.body_path.read_text(encoding="utf-8"))
+ return skill.body_path.read_text(encoding="utf-8")
def get_default_skill_with_body(name: str) -> ParsedSkill | None:
diff --git a/autogpt_platform/backend/backend/copilot/tools/skills_test.py b/autogpt_platform/backend/backend/copilot/tools/skills_test.py
index 280a45c416..14f0e35712 100644
--- a/autogpt_platform/backend/backend/copilot/tools/skills_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/skills_test.py
@@ -168,7 +168,6 @@ def test_default_skills_load_from_disk():
defaults = get_default_skills()
names = {s.name for s in defaults}
assert "agent_building_guide" in names
- assert "mcp_tool_guide" in names
# Bodies must be non-trivial — a zero-byte file silently kills the
# whole feature for end users.
for skill in defaults:
@@ -824,7 +823,6 @@ async def test_list_skills_anon_returns_defaults_only():
assert isinstance(result, ListSkillsResponse)
names = {s["name"] for s in result.skills}
assert "agent_building_guide" in names
- assert "mcp_tool_guide" in names
# All anon results must be flagged as default.
assert all(s["is_default"] for s in result.skills)
@@ -1152,10 +1150,11 @@ async def test_skills_update_notice_names_removed_skill():
async def test_skills_update_notice_truncates_long_added_lists():
"""Beyond _MAX_UPDATE_NAMES the notice falls back to a remainder count
instead of inlining the whole registry — it is a nudge, not the index."""
- from backend.copilot.tools.skills import _MAX_UPDATE_NAMES
+ from backend.copilot.tools.skills import _MAX_UPDATE_NAMES, get_default_skills
+ extra = 3
fake_manager = _FakeWorkspaceManager()
- for i in range(_MAX_UPDATE_NAMES + 3):
+ for i in range(_MAX_UPDATE_NAMES + extra):
slug = f"skill-{i:02d}"
fake_manager.files[f"/skills/{slug}/SKILL.md"] = render_skill_markdown(
ParsedSkill(name=slug, description=f"skill {i}", body="x")
@@ -1167,8 +1166,13 @@ async def test_skills_update_notice_truncates_long_added_lists():
_history_with_index("- name: agent_building_guide — guide")
],
)
+ # Derived, not spelled out: the defaults are part of the added set, so a
+ # default skill added or retired elsewhere should not fail this test.
+ unseen_defaults = sum(
+ 1 for s in get_default_skills() if s.name != "agent_building_guide"
+ )
assert "<skills_update>" in notice
- assert "and 4 more" in notice
+ assert f"and {extra + unseen_defaults} more" in notice
assert "list_skills" in notice
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_run_block_details.py b/autogpt_platform/backend/backend/copilot/tools/test_run_block_details.py
index d4fbc19155..a00433ab60 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_run_block_details.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_run_block_details.py
@@ -189,11 +189,6 @@ async def _details_for(block, flag_on: bool) -> BlockDetailsResponse:
new_callable=AsyncMock,
return_value=({}, []),
),
- patch(
- "backend.copilot.tools.run_block.is_feature_enabled",
- new_callable=AsyncMock,
- return_value=flag_on,
- ),
):
response = await RunBlockTool()._execute(
user_id=_TEST_USER_ID,
@@ -206,14 +201,6 @@ async def _details_for(block, flag_on: bool) -> BlockDetailsResponse:
return response
[email protected](loop_scope="session")
-async def test_flag_off_leaves_the_schema_byte_identical():
- block = make_annotated_block()
- response = await _details_for(block, flag_on=False)
- assert response.block.inputs == block.input_schema.jsonschema.return_value
- assert response.block.outputs == block.output_schema.jsonschema.return_value
-
-
@pytest.mark.asyncio(loop_scope="session")
async def test_flag_on_strips_presentation_annotations_from_both_schemas():
block = make_annotated_block()
diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
index 71025456b0..42a31f92bd 100644
--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
@@ -14,6 +14,8 @@ import pytest
from backend.copilot.tools import TOOL_REGISTRY
+from ._test_data import make_session
+
# Character budget (~4 chars/token heuristic, targeting ~8000 tokens).
# Bumped 32000 -> 32500 on PR #12699 to fit two pieces of load-bearing
# guidance: the wait_for_result dispatch-mode docs on run_agent
@@ -446,19 +448,24 @@ def test_get_available_tools_hides_graphiti_when_disabled() -> None:
"memory_forget_confirm",
}
- default = {t["function"]["name"] for t in get_available_tools()}
+ default = {
+ t["function"]["name"] for t in get_available_tools(include_deferred=True)
+ }
assert memory_tool_names.issubset(
default
), "sanity: memory_* tools should be present when no groups disabled"
filtered = {
- t["function"]["name"] for t in get_available_tools(disabled_groups=["graphiti"])
+ t["function"]["name"]
+ for t in get_available_tools(
+ include_deferred=True, disabled_groups=["graphiti"]
+ )
}
assert not (
memory_tool_names & filtered
), f"graphiti disabled but memory_* still present: {memory_tool_names & filtered}"
# Non-graphiti tools stay visible.
- assert "find_block" in filtered
+ assert "find_capability" in filtered
assert "TodoWrite" in filtered
@@ -473,8 +480,10 @@ def test_get_copilot_tool_names_hides_graphiti_when_disabled() -> None:
f"{MCP_TOOL_PREFIX}memory_forget_confirm",
}
+ # Memory tools are deferred: never in the schema list, reached through
+ # run_capability instead. Disabling the group must not resurrect them.
default = set(get_copilot_tool_names())
- assert memory_mcp_names.issubset(default)
+ assert not memory_mcp_names & default
filtered = set(get_copilot_tool_names(disabled_groups=["graphiti"]))
assert not (
@@ -500,53 +509,90 @@ def test_automation_origin_declares_no_interactive_origin_tools() -> None:
"""
from backend.copilot.tools import (
INTERACTIVE_ORIGIN_TOOLS,
- get_available_tools,
origin_disabled_tools,
+ reachable_tool_names,
)
for origin in ("automation", None):
hidden = origin_disabled_tools(origin)
assert hidden == INTERACTIVE_ORIGIN_TOOLS
- declared = {
- t["function"]["name"] for t in get_available_tools(disabled_tools=hidden)
- }
- assert not (INTERACTIVE_ORIGIN_TOOLS & declared), (
- f"origin={origin!r} still declares "
- f"{sorted(INTERACTIVE_ORIGIN_TOOLS & declared)}"
+ # Reachable, not declared: most of these are deferred now, so the
+ # schema list would read every one of them as gated whether the gate
+ # works or not. ``run_capability`` answers to the same hidden set.
+ reachable = reachable_tool_names(disabled_tools=hidden)
+ assert not (INTERACTIVE_ORIGIN_TOOLS & reachable), (
+ f"origin={origin!r} can still reach "
+ f"{sorted(INTERACTIVE_ORIGIN_TOOLS & reachable)}"
)
# The gate is narrow on purpose: an automation still does its work,
# still reports through a chat platform, still wakes itself up.
assert {
"run_agent",
- "run_block",
+ "run_capability",
"run_sub_session",
"schedule_followup",
"ask_question",
- } <= declared
+ } <= reachable
-def test_interactive_origin_declares_every_tool_it_did_before() -> None:
- """An interactive session declares exactly what it declared before.
+async def test_a_deferred_tool_named_directly_is_refused() -> None:
+ """The schema list is a presentation filter; this is the boundary.
+
+ Deferred tools are absent from every schema list, but a model that names
+ one anyway (replayed transcript, prompt injection) used to reach it here
+ and run it — routing around ``run_capability`` and the permission and
+ envelope gates it applies.
+ """
+ from unittest.mock import AsyncMock, patch
+
+ from backend.copilot.tools import DEFERRED_TOOL_NAMES, execute_tool, get_tool
+ from backend.copilot.tools.models import ErrorResponse
+
+ name = "memory_search"
+ assert name in DEFERRED_TOOL_NAMES, "test relies on this tool being deferred"
+ tool = get_tool(name)
+ assert tool is not None
+
+ with patch.object(
+ tool, "execute", new=AsyncMock(return_value="should never run")
+ ) as ran:
+ result = await execute_tool(
+ tool_name=name,
+ parameters={},
+ user_id="user-1",
+ session=make_session("user-1"),
+ tool_call_id="call-1",
+ # Nothing else gates it: the refusal has to come from deferral.
+ disabled_groups=[],
+ disabled_tools=(),
+ )
+
+ ran.assert_not_awaited()
+ assert result.success is False
+ assert ErrorResponse.model_validate_json(result.output).error == "tool_disabled"
+
+
+def test_interactive_origin_reaches_every_tool_it_did_before() -> None:
+ """An interactive session reaches exactly what it reached before.
The counterpart to the test above, and what fails if the gate ever widens
past ``origin`` into the sessions a person really is driving.
"""
from backend.copilot.tools import (
INTERACTIVE_ORIGIN_TOOLS,
- get_available_tools,
origin_disabled_tools,
+ reachable_tool_names,
)
hidden = origin_disabled_tools("interactive")
assert hidden == frozenset()
- declared = {
- t["function"]["name"] for t in get_available_tools(disabled_tools=hidden)
- }
+ reachable = reachable_tool_names(disabled_tools=hidden)
assert (
- INTERACTIVE_ORIGIN_TOOLS <= declared
- ), f"interactive session lost {sorted(INTERACTIVE_ORIGIN_TOOLS - declared)}"
+ INTERACTIVE_ORIGIN_TOOLS <= reachable
+ ), f"interactive session lost {sorted(INTERACTIVE_ORIGIN_TOOLS - reachable)}"
def test_set_matches_the_tools_that_call_the_origin_guard() -> None:
diff --git a/autogpt_platform/backend/backend/copilot/tree.py b/autogpt_platform/backend/backend/copilot/tree.py
index 43089f91a7..70d19a13cf 100644
--- a/autogpt_platform/backend/backend/copilot/tree.py
+++ b/autogpt_platform/backend/backend/copilot/tree.py
@@ -97,6 +97,7 @@ ISOLATE_DENIED_TOOLS: frozenset[str] = frozenset(
{
"post_to_chat_platform",
"schedule_followup",
+ # Capability gate: withholds every MCP server from run_capability.
"run_mcp_tool",
"store_skill",
"memory_store",
diff --git a/autogpt_platform/backend/backend/data/human_review.py b/autogpt_platform/backend/backend/data/human_review.py
index f15808341a..281a77bcab 100644
--- a/autogpt_platform/backend/backend/data/human_review.py
+++ b/autogpt_platform/backend/backend/data/human_review.py
@@ -425,9 +425,9 @@ async def _enrich_pending_reviews(
rather than one round-trip per row:
- ``node_id``, from the node executions
- expert attribution (from the graph execution, or from the chat
- session for CoPilot run_block reviews)
+ session for CoPilot run_capability reviews)
- the requesting agent's display name and library agent id
- - the chat session id, for CoPilot run_block reviews
+ - the chat session id, for CoPilot run_capability reviews
Mutates and returns the given models in place.
"""
@@ -756,7 +756,7 @@ async def cancel_pending_reviews_for_execution(graph_exec_id: str, user_id: str)
async def delete_review_by_node_exec_id(node_exec_id: str, user_id: str) -> int:
"""Delete a review record by node execution ID after it has been consumed.
- Used by CoPilot's continue_run_block to clean up one-time-use review records
+ Used by CoPilot's resume_capability to clean up one-time-use review records
after successful execution.
Args:
diff --git a/autogpt_platform/backend/backend/executor/auto_credentials.py b/autogpt_platform/backend/backend/executor/auto_credentials.py
index 5a6fc1b426..2926671f32 100644
--- a/autogpt_platform/backend/backend/executor/auto_credentials.py
+++ b/autogpt_platform/backend/backend/executor/auto_credentials.py
@@ -22,7 +22,7 @@ class MissingAutoCredentialsError(ValueError):
"""Raised when a picker-style field lacks a usable ``_credentials_id``.
Distinct from generic ``ValueError`` so callers (e.g. the CoPilot
- run_block path) can branch on "needs picker interaction" and return a
+ run_capability path) can branch on "needs picker interaction" and return a
structured response instead of a bare error.
"""
@@ -112,7 +112,7 @@ async def acquire_auto_credentials(
f"Authentication missing for '{file_name}' in field "
f"'{field_name}'. The CoPilot chat will render the "
f"{provider.capitalize()} picker inline — pick the "
- f"file there; re-invoking `run_block` with a bare "
+ f"file there; re-invoking `run_capability` with a bare "
f"id/URL will not authenticate."
)
elif field_data is None and field_name not in input_data:
@@ -122,7 +122,7 @@ async def acquire_auto_credentials(
raise MissingAutoCredentialsError(
f"No file selected for '{field_name}'. The CoPilot chat "
f"will render the {provider.capitalize()} picker inline "
- f"— pick the file there; `run_block` will re-run "
+ f"— pick the file there; `run_capability` will re-run "
f"automatically with the populated value."
)
else:
diff --git a/autogpt_platform/backend/backend/integrations/credentials_store.py b/autogpt_platform/backend/backend/integrations/credentials_store.py
index 64e99a9253..8285c8d32d 100644
--- a/autogpt_platform/backend/backend/integrations/credentials_store.py
+++ b/autogpt_platform/backend/backend/integrations/credentials_store.py
@@ -26,24 +26,31 @@ settings = Settings()
logger = logging.getLogger(__name__)
+def canonical_provider(stored: str) -> str:
+ """The canonical provider value for a possibly-legacy stored string.
+
+ On Python 3.13, ``str(ProviderName.MCP)`` returns ``"ProviderName.MCP"``
+ instead of ``"mcp"``, and credentials persisted then still carry it.
+ Anything already canonical, or naming a member we no longer have, comes
+ back unchanged.
+ """
+ if not stored.startswith("ProviderName."):
+ return stored
+ from backend.integrations.providers import ProviderName
+
+ try:
+ return ProviderName[stored.removeprefix("ProviderName.")].value
+ except KeyError:
+ return stored
+
+
def provider_matches(stored: str, expected: str) -> bool:
"""Compare provider strings, handling Python 3.13 ``str(StrEnum)`` bug.
- On Python 3.13, ``str(ProviderName.MCP)`` returns ``"ProviderName.MCP"``
- instead of ``"mcp"``. OAuth states persisted with the buggy format need
- to match when ``expected`` is the canonical value (e.g. ``"mcp"``).
+ OAuth states persisted with the buggy format need to match when
+ ``expected`` is the canonical value (e.g. ``"mcp"``).
"""
- if stored == expected:
- return True
- if stored.startswith("ProviderName."):
- member = stored.removeprefix("ProviderName.")
- from backend.integrations.providers import ProviderName
-
- try:
- return ProviderName[member].value == expected
- except KeyError:
- pass
- return False
+ return stored == expected or canonical_provider(stored) == expected
# This is an overrride since ollama doesn't actually require an API key, but the creddential system enforces one be attached
diff --git a/autogpt_platform/backend/backend/integrations/mcp_catalog.json b/autogpt_platform/backend/backend/integrations/mcp_catalog.json
index 8cb7e8e1c1..cd6ca5abf1 100644
--- a/autogpt_platform/backend/backend/integrations/mcp_catalog.json
+++ b/autogpt_platform/backend/backend/integrations/mcp_catalog.json
@@ -43,7 +43,8 @@
"icon_id": "agent_mail",
"auth_methods": [
"oauth"
- ]
+ ],
+ "provider": "agent_mail"
}
},
{
@@ -70,7 +71,8 @@
"data.records:write",
"schema.bases:write",
"data.recordComments:write"
- ]
+ ],
+ "provider": "airtable"
}
},
{
@@ -197,7 +199,8 @@
"oauth_write_scopes": [
"contact_write",
"contact_update"
- ]
+ ],
+ "provider": "apollo"
}
},
{
@@ -578,7 +581,8 @@
"auth_methods": [
"bearer"
],
- "icon_id": "github"
+ "icon_id": "github",
+ "provider": "github"
}
},
{
@@ -736,7 +740,8 @@
"oauth_write_scopes": [
"write"
],
- "icon_id": "linear"
+ "icon_id": "linear",
+ "provider": "linear"
}
},
{
@@ -807,7 +812,8 @@
],
"oauth_scopes": [
"default"
- ]
+ ],
+ "provider": "notion"
}
},
{
@@ -924,7 +930,8 @@
"oauth",
"bearer"
],
- "icon_id": "stripe"
+ "icon_id": "stripe",
+ "provider": "stripe"
}
},
{
@@ -992,7 +999,8 @@
"auth_methods": [
"oauth"
],
- "icon_id": "tavily"
+ "icon_id": "tavily",
+ "provider": "tavily"
}
},
{
@@ -1010,7 +1018,8 @@
"oauth_scopes": [
"data:read_write"
],
- "icon_id": "todoist"
+ "icon_id": "todoist",
+ "provider": "todoist"
}
},
{
diff --git a/autogpt_platform/backend/backend/integrations/mcp_catalog.py b/autogpt_platform/backend/backend/integrations/mcp_catalog.py
index 260e855f3f..aad462bb6b 100644
--- a/autogpt_platform/backend/backend/integrations/mcp_catalog.py
+++ b/autogpt_platform/backend/backend/integrations/mcp_catalog.py
@@ -36,6 +36,13 @@ class MCPServerMetadata(BaseModel):
oauth_scopes: list[str] | None = None
oauth_write_scopes: list[str] = Field(default_factory=list)
icon_id: str | None = Field(default=None, pattern=r"^[a-z0-9_-]+$")
+ provider: str | None = Field(
+ default=None,
+ pattern=r"^[a-z0-9_]+$",
+ description="Block provider this server belongs to, when the platform "
+ "also ships blocks for it. Lets the UI file an MCP connection under the "
+ "same service as its API-key credential instead of a generic MCP group.",
+ )
@field_validator("server_url", "documentation_url", "oauth_server_url")
@classmethod
diff --git a/autogpt_platform/backend/backend/integrations/mcp_guide.py b/autogpt_platform/backend/backend/integrations/mcp_guide.py
deleted file mode 100644
index 93d94db687..0000000000
--- a/autogpt_platform/backend/backend/integrations/mcp_guide.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from backend.integrations.mcp_catalog import MCPCatalogEntry, get_mcp_catalog
-
-MCP_CATALOG_MARKER = "<!-- official-mcp-catalog -->"
-
-
-def render_mcp_guide(content: str) -> str:
- if MCP_CATALOG_MARKER not in content:
- return content
- table = "\n".join(
- [
- "Additional official connections from the integration catalog:",
- "",
- "Respect each entry's purpose. Public documentation servers do not "
- "provide private account access. For regional or tenant-specific servers, "
- "confirm the user's region or obtain their endpoint before connecting.",
- "",
- "| Service | URL | Authentication | Purpose | Setup requirements |",
- "|---|---|---|---|---|",
- *(_render_entry(entry) for entry in get_mcp_catalog()),
- ]
- )
- return content.replace(MCP_CATALOG_MARKER, table)
-
-
-def _render_entry(entry: MCPCatalogEntry) -> str:
- cells = [
- entry.display_name,
- _server_location(entry),
- _authentication(entry),
- entry.description,
- entry.mcp_server.setup_instructions,
- ]
- return "| " + " | ".join(cell.replace("|", r"\|") for cell in cells) + " |"
-
-
-def _server_location(entry: MCPCatalogEntry) -> str:
- server = entry.mcp_server
- if server.server_url_options:
- options = "; ".join(
- f"{option.label}: `{option.url}`" for option in server.server_url_options
- )
- return f"Choose the account region: {options}"
- if server.server_url:
- return f"`{server.server_url}`"
- return f"User-provided endpoint; [setup instructions]({server.documentation_url})"
-
-
-def _authentication(entry: MCPCatalogEntry) -> str:
- server = entry.mcp_server
- methods = " / ".join(server.auth_methods)
- if server.oauth_server_url:
- methods += f"; OAuth uses `{server.oauth_server_url}`"
- if server.oauth_scopes is not None:
- methods += "; default OAuth scopes: " + (
- ", ".join(server.oauth_scopes) or "none"
- )
- if server.oauth_write_scopes:
- methods += "; optional grants require explicit selection in Integrations"
- return methods
diff --git a/autogpt_platform/backend/backend/integrations/mcp_guide_test.py b/autogpt_platform/backend/backend/integrations/mcp_guide_test.py
deleted file mode 100644
index 6a3dcb2d3b..0000000000
--- a/autogpt_platform/backend/backend/integrations/mcp_guide_test.py
+++ /dev/null
@@ -1,48 +0,0 @@
-from unittest.mock import patch
-
-from backend.integrations.mcp_catalog import (
- MCPCatalogEntry,
- MCPServerMetadata,
- get_mcp_catalog,
-)
-from backend.integrations.mcp_guide import MCP_CATALOG_MARKER, render_mcp_guide
-
-
-def test_guide_distinguishes_oauth_url_and_optional_permissions():
- entry = MCPCatalogEntry(
- name="mcp_vendor",
- display_name="Vendor",
- description="Search public and private content.",
- mcp_server=MCPServerMetadata(
- server_url="https://mcp.vendor.com/mcp",
- oauth_server_url="https://mcp.vendor.com/mcp/oauth",
- documentation_url="https://docs.vendor.com/mcp",
- setup_instructions="Select your workspace.",
- connection_mode="hosted",
- auth_methods=["none", "oauth", "bearer"],
- oauth_scopes=["read"],
- oauth_write_scopes=["write"],
- ),
- )
- with patch("backend.integrations.mcp_guide.get_mcp_catalog", return_value=(entry,)):
- guide = render_mcp_guide(MCP_CATALOG_MARKER)
-
- assert "none / oauth / bearer" in guide
- assert "OAuth uses `https://mcp.vendor.com/mcp/oauth`" in guide
- assert "default OAuth scopes: read" in guide
- assert "optional grants require explicit selection" in guide
-
-
-def test_guide_includes_connections_and_endpoint_choices():
- guide = render_mcp_guide(MCP_CATALOG_MARKER)
-
- for entry in get_mcp_catalog():
- assert entry.display_name in guide
- assert entry.mcp_server.setup_instructions in guide
- server = entry.mcp_server
- if server.server_url:
- assert f"`{server.server_url}`" in guide
- elif not server.server_url_options:
- assert f"[setup instructions]({server.documentation_url})" in guide
- for option in server.server_url_options:
- assert f"{option.label}: `{option.url}`" in guide
diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.py
index 5058d5a348..7779a59810 100644
--- a/autogpt_platform/backend/backend/util/feature_flag.py
+++ b/autogpt_platform/backend/backend/util/feature_flag.py
@@ -199,7 +199,6 @@ class Flag(str, Enum):
# Shrinks what Otto reads: strips builder-UI annotations from the
# block schemas, and digests oversized tool results to the workspace.
- AUTOPILOT_CONTEXT_TRIMMING = "autopilot-context-trimming"
def is_configured() -> bool:
diff --git a/autogpt_platform/backend/test/copilot/dry_run_loop_test.py b/autogpt_platform/backend/test/copilot/dry_run_loop_test.py
index 9a5d6e546d..11af32bd7e 100644
--- a/autogpt_platform/backend/test/copilot/dry_run_loop_test.py
+++ b/autogpt_platform/backend/test/copilot/dry_run_loop_test.py
@@ -48,6 +48,7 @@ from backend.copilot.prompting import get_sdk_supplement
from backend.copilot.service import CACHEABLE_SYSTEM_PROMPT as DEFAULT_SYSTEM_PROMPT
from backend.copilot.tools import TOOL_REGISTRY
from backend.copilot.tools.run_agent import RunAgentInput
+from backend.copilot.tools.run_block import RunBlockTool
# Resolved once for the whole module so individual tests stay fast.
_SDK_SUPPLEMENT = get_sdk_supplement(use_e2b=False)
@@ -96,8 +97,8 @@ class TestToolDescriptionsDryRunLoop:
)
def test_run_block_dry_run_not_in_llm_schema(self):
- """dry_run must NOT be in the run_block LLM schema — it is session-level."""
- schema = TOOL_REGISTRY["run_block"].as_openai_tool()
+ """dry_run must NOT be in the block-run LLM schema — it is session-level."""
+ schema = RunBlockTool().as_openai_tool()
params = cast(dict[str, Any], schema["function"].get("parameters", {}))
assert "dry_run" not in params.get("properties", {}), (
"dry_run must not be exposed in the run_block LLM schema; "
@@ -113,10 +114,10 @@ class TestPromptingSupplementContent:
"""
def test_includes_tool_discovery_priority(self):
- assert "Tool Discovery Priority" in _SDK_SUPPLEMENT
+ assert "Discovery" in _SDK_SUPPLEMENT and "MANDATORY" in _SDK_SUPPLEMENT
- def test_includes_find_block_first(self):
- assert "find_block first" in _SDK_SUPPLEMENT or "find_block" in _SDK_SUPPLEMENT
+ def test_includes_find_capability_first(self):
+ assert "find_capability" in _SDK_SUPPLEMENT
def test_includes_send_authenticated_web_request(self):
assert "SendAuthenticatedWebRequestBlock" in _SDK_SUPPLEMENT
@@ -214,7 +215,7 @@ class TestRunBlockToolSchema:
@pytest.fixture
def schema(self) -> ChatCompletionToolParam:
- return TOOL_REGISTRY["run_block"].as_openai_tool()
+ return RunBlockTool().as_openai_tool()
def test_schema_is_valid_openai_tool(self, schema: ChatCompletionToolParam):
assert schema["type"] == "function"
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
index 1257fc91ad..69f02b82e4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
@@ -16,9 +16,11 @@ import {
import { FindAgentsTool } from "../../../tools/FindAgents/FindAgents";
import { FolderTool } from "../../../tools/FolderTool/FolderTool";
import { FindBlocksTool } from "../../../tools/FindBlocks/FindBlocks";
+import { FindCapabilitiesTool } from "../../../tools/FindCapabilities/FindCapabilities";
import { GenericTool } from "../../../tools/GenericTool/GenericTool";
import { RunAgentTool } from "../../../tools/RunAgent/RunAgent";
import { RunBlockTool } from "../../../tools/RunBlock/RunBlock";
+import { RunCapabilityTool } from "../../../tools/RunCapability/RunCapability";
import { RunMCPToolComponent } from "../../../tools/RunMCPTool/RunMCPTool";
import { SearchDocsTool } from "../../../tools/SearchDocs/SearchDocs";
import { SetupTriggerTool } from "../../../tools/SetupTrigger/SetupTrigger";
@@ -237,6 +239,12 @@ export function MessagePartRenderer({
return <ExpertOnboardingCard key={key} part={part as ToolUIPart} />;
case "tool-find_block":
return <FindBlocksTool key={key} part={part as ToolUIPart} />;
+ case "tool-find_capability":
+ return <FindCapabilitiesTool key={key} part={part as ToolUIPart} />;
+ case "tool-describe_capability":
+ case "tool-run_capability":
+ case "tool-resume_capability":
+ return <RunCapabilityTool key={key} part={part as ToolUIPart} />;
case "tool-find_agent":
case "tool-find_library_agent":
return <FindAgentsTool key={key} part={part as ToolUIPart} />;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx
index 1b16970704..132bee7ccf 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx
@@ -13,7 +13,7 @@ interface Props {
/**
* Renders a single consolidated PendingReviewsList for all pending copilot
* reviews in a session — mirrors the non-copilot review page behavior.
- * Works for both run_block (synthetic copilot-session-*) and run_agent (real graph exec) reviews.
+ * Works for both run_capability (synthetic copilot-session-*) and run_agent (real graph exec) reviews.
*/
export function CopilotPendingReviews({ graphExecId }: Props) {
const { onSend } = useCopilotChatActions();
@@ -22,7 +22,7 @@ export function CopilotPendingReviews({ graphExecId }: Props) {
{ enabled: !!graphExecId, refetchInterval: 2000 },
);
- // Graph executions auto-resume after approval; block reviews need continue_run_block.
+ // Graph executions auto-resume after approval; capability reviews need resume_capability.
const isGraphExecution = !graphExecId.startsWith("copilot-session-");
const handleReviewComplete = useCallback(async () => {
@@ -42,7 +42,7 @@ export function CopilotPendingReviews({ graphExecId }: Props) {
} else {
onSend(
`All pending reviews have been processed. ` +
- `For any approved reviews, call continue_run_block with the corresponding review_id to execute them. ` +
+ `For any approved reviews, call resume_capability with the corresponding review_id to execute them. ` +
`For rejected reviews, no further action is needed.`,
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/useWorkDoneCounters.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/useWorkDoneCounters.ts
index d13b9d4811..c3adf296a4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/useWorkDoneCounters.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/useWorkDoneCounters.ts
@@ -6,6 +6,7 @@ const TOOL_TO_CATEGORY: Record<string, string> = {
find_library_agent: "search",
run_agent: "agent run",
run_block: "action",
+ run_capability: "action",
create_agent: "agent created",
edit_agent: "agent edited",
schedule_agent: "agent scheduled",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx
index d6c4c92a5f..bded7c59ee 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx
@@ -150,16 +150,50 @@ function chipStrings(value: unknown, key: string): string[] | null {
return labels.length > 0 ? labels : null;
}
+const CAPABILITY_RUN_TOOLS = new Set([
+ "run_capability",
+ "resume_capability",
+ "describe_capability",
+]);
+
+function isMcpCapabilityRow(
+ row: ChainRow,
+ output: Record<string, unknown>,
+): boolean {
+ if (!row.tool || !CAPABILITY_RUN_TOOLS.has(row.tool)) return false;
+ const input = asObject(row.input);
+ const id = (input && str(input, "id")) ?? "";
+ return (
+ id.startsWith("mcp:") || id.startsWith("https://") || "server_url" in output
+ );
+}
+
+function capabilityAsBlockItem(
+ item: Record<string, unknown>,
+): Record<string, unknown> {
+ return {
+ ...item,
+ description: item.purpose,
+ categories: [
+ item.kind === "mcp_server"
+ ? "integration"
+ : item.class === "primitive"
+ ? "building block"
+ : String(item.kind ?? ""),
+ ],
+ };
+}
+
function setupRequirementsCard(row: ChainRow, output: Record<string, unknown>) {
const setupInfo = asObject(output.setup_info);
if (!setupInfo) return null;
const setupOutput = output as unknown as SetupRequirementsResponse;
- if (row.tool === "run_mcp_tool") {
+ if (row.tool === "run_mcp_tool" || isMcpCapabilityRow(row, output)) {
return (
<MCPSetupCard
output={setupOutput}
- retryInstruction="I've connected the MCP server credentials. Please retry run_mcp_tool with the same server URL and arguments."
+ retryInstruction="I've connected the integration. Please retry the same call."
/>
);
}
@@ -294,13 +328,23 @@ function toolCard(
const blocks = output && asItems(output.blocks);
return blocks ? <BlockListCard blocks={blocks} /> : null;
}
+ case "find_capability": {
+ const items = output && asItems(output.capabilities);
+ return items ? (
+ <BlockListCard blocks={items.map(capabilityAsBlockItem)} />
+ ) : null;
+ }
case "run_block":
- case "continue_run_block": {
+ case "continue_run_block":
+ case "describe_capability":
+ case "run_capability":
+ case "resume_capability": {
if (!output) return null;
const block = asObject(output.block);
if (block) return <BlockListCard blocks={[block]} />;
if (str(output, "block_name", "block_id"))
return <BlockOutputCard output={output} />;
+ if ("result" in output) return <KeyValueList value={output.result} />;
return null;
}
case "connect_integration":
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/toolCatalog.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/toolCatalog.test.ts
index 6b4ecd5c75..d56c12c644 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/toolCatalog.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/toolCatalog.test.ts
@@ -272,4 +272,36 @@ describe("getCatalogLabel", () => {
)?.text,
).toBe('Messaged a session: "the numbers are in"');
});
+
+ it("labels the capability tools by what they act on", () => {
+ expect(
+ getCatalogLabel("find_capability", { query: "linear issue" }, "running")
+ ?.text,
+ ).toBe('Searching capabilities for "linear issue"…');
+ expect(
+ getCatalogLabel("describe_capability", { id: "block:abc" }, "done")?.text,
+ ).toBe('Read capability "block:abc"');
+ });
+
+ it("names a run by its block, falling back to the capability id", () => {
+ // The display name only arrives once the run reports back, so the id
+ // has to carry the label until then.
+ expect(
+ getCatalogLabel(
+ "run_capability",
+ { id: "tool:list_schedules" },
+ "running",
+ )?.text,
+ ).toBe('Running "tool:list_schedules"…');
+ expect(
+ getCatalogLabel("run_capability", { id: "block:abc" }, "done", {
+ displayName: "Send Web Request",
+ })?.text,
+ ).toBe('Ran "Send Web Request"');
+ expect(
+ getCatalogLabel("resume_capability", { review_id: "r" }, "done", {
+ displayName: "Send Web Request",
+ })?.text,
+ ).toBe('Resumed "Send Web Request"');
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
index d07fbb2979..cf36d353a6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
@@ -87,6 +87,13 @@ const ACTION_RESPONSE_TYPES = new Set([
"suggested_goal",
]);
+const BLOCK_ACTION_TOOLS = new Set([
+ "run_block",
+ "continue_run_block",
+ "run_capability",
+ "resume_capability",
+]);
+
function actionLabel(toolName: string, tool: ToolUIPart): string | null {
const output = tool.output;
const data = asObject(output);
@@ -94,7 +101,7 @@ function actionLabel(toolName: string, tool: ToolUIPart): string | null {
if (typeof data.type !== "string" || !ACTION_RESPONSE_TYPES.has(data.type)) {
return null;
}
- const isBlock = toolName === "run_block" || toolName === "continue_run_block";
+ const isBlock = BLOCK_ACTION_TOOLS.has(toolName);
if (data.type === "setup_requirements") {
const setup =
data.setup_info && typeof data.setup_info === "object"
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.platform.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.platform.ts
index 788796e126..59a2409aa6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.platform.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.platform.ts
@@ -136,6 +136,35 @@ export const PLATFORM_TOOL_CATALOG: Record<string, ToolMeta> = {
subject: (_input, context) =>
quotedName(getBlockDisplayName(context.displayName, context.output)),
},
+ find_capability: {
+ category: "block",
+ running: "Searching capabilities for",
+ done: "Searched capabilities for",
+ subject: (input) => quoted(input, "query"),
+ },
+ describe_capability: {
+ category: "block",
+ running: "Reading capability",
+ done: "Read capability",
+ subject: (input) => quotedName(strField(input, "id")),
+ },
+ run_capability: {
+ category: "block",
+ running: "Running",
+ done: "Ran",
+ subject: (input, context) =>
+ quotedName(
+ getBlockDisplayName(context.displayName, context.output) ??
+ strField(input, "id"),
+ ),
+ },
+ resume_capability: {
+ category: "block",
+ running: "Resuming",
+ done: "Resumed",
+ subject: (_input, context) =>
+ quotedName(getBlockDisplayName(context.displayName, context.output)),
+ },
schedule_agent: {
category: "agent",
running: "Scheduling agent",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/FindCapabilities.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/FindCapabilities.tsx
new file mode 100644
index 0000000000..9a90ccdbb1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/FindCapabilities.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { HorizontalScroll } from "@/app/(platform)/build/components/NewControlPanel/NewBlockMenu/HorizontalScroll";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import {
+ ContentCard,
+ ContentCardDescription,
+ ContentCardTitle,
+} from "../../components/ToolAccordion/AccordionContent";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import { AccordionIcon, ToolIcon } from "../FindBlocks/helpers";
+import {
+ type CapabilityListing,
+ type FindCapabilityToolPart,
+ getAnimationText,
+ kindLabel,
+ parseOutput,
+ queryOf,
+} from "./helpers";
+
+interface Props {
+ part: FindCapabilityToolPart;
+}
+
+function CapabilityCard({ item }: { item: CapabilityListing }) {
+ const connected = item.connected;
+ return (
+ <ContentCard className="w-52 shrink-0">
+ <div className="flex items-start justify-between gap-2">
+ <ContentCardTitle className="truncate">{item.name}</ContentCardTitle>
+ {connected !== undefined && connected !== null && (
+ <span
+ className={
+ "shrink-0 rounded-full px-2 py-0.5 text-[11px] " +
+ (connected
+ ? "bg-green-100 text-green-800"
+ : "bg-zinc-100 text-zinc-500")
+ }
+ >
+ {connected ? "connected" : "sign in"}
+ </span>
+ )}
+ </div>
+ <ContentCardDescription className="mt-1 line-clamp-2">
+ {item.purpose}
+ </ContentCardDescription>
+ <p className="mt-1 text-[11px] text-zinc-500">{kindLabel(item)}</p>
+ </ContentCard>
+ );
+}
+
+export function FindCapabilitiesTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+ const isError = part.state === "output-error";
+ const parsed =
+ part.state === "output-available" ? parseOutput(part.output) : null;
+ const items = parsed
+ ? [...parsed.capabilities, ...(parsed.fallback ?? [])]
+ : [];
+ const query = queryOf(part);
+ const description = parsed
+ ? `${parsed.count} result${parsed.count === 1 ? "" : "s"}${query ? ` for "${query}"` : ""}`
+ : undefined;
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {items.length > 0 && (
+ <ToolAccordion
+ icon={<AccordionIcon />}
+ title="Results"
+ description={description}
+ >
+ <HorizontalScroll dependencyList={[items.length]}>
+ {items.map((item) => (
+ <CapabilityCard key={item.id} item={item} />
+ ))}
+ </HorizontalScroll>
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/FindCapabilities.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/FindCapabilities.test.tsx
new file mode 100644
index 0000000000..d9a966b62b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/FindCapabilities.test.tsx
@@ -0,0 +1,106 @@
+import { render, screen } from "@/tests/integrations/test-utils";
+import { cleanup, fireEvent } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { FindCapabilitiesTool } from "../FindCapabilities";
+import type { CapabilityListOutput, FindCapabilityToolPart } from "../helpers";
+
+const OUTPUT: CapabilityListOutput = {
+ type: "capability_list",
+ query: "linear issue",
+ count: 2,
+ capabilities: [
+ {
+ id: "mcp:mcp.linear.app",
+ name: "Linear",
+ purpose: "Issues, projects and cycles",
+ kind: "mcp_server",
+ connected: true,
+ },
+ {
+ id: "block:abc-123",
+ name: "Send Web Request",
+ purpose: "Call an HTTP endpoint",
+ kind: "block",
+ connected: false,
+ },
+ ],
+ fallback: [
+ {
+ id: "block:def-456",
+ name: "HTTP Request",
+ purpose: "A lower-level request",
+ kind: "block",
+ },
+ ],
+};
+
+function part(overrides: Partial<FindCapabilityToolPart>) {
+ return {
+ type: "tool-find_capability",
+ toolCallId: "call-1",
+ state: "output-available",
+ input: { query: "linear issue" },
+ ...overrides,
+ } as FindCapabilityToolPart;
+}
+
+describe("FindCapabilitiesTool", () => {
+ afterEach(cleanup);
+
+ it("shows results and fallbacks together, counting only the hits", () => {
+ render(<FindCapabilitiesTool part={part({ output: OUTPUT })} />);
+ fireEvent.click(screen.getByText("Results"));
+
+ expect(screen.getByText("Linear")).toBeDefined();
+ expect(screen.getByText("Send Web Request")).toBeDefined();
+ // The fallback rides along in the same row — it is still something the
+ // model can call, just not what the query asked for.
+ expect(screen.getByText("HTTP Request")).toBeDefined();
+ expect(screen.getByText('2 results for "linear issue"')).toBeDefined();
+ });
+
+ it("marks connection state only where the capability needs one", () => {
+ render(<FindCapabilitiesTool part={part({ output: OUTPUT })} />);
+ fireEvent.click(screen.getByText("Results"));
+
+ expect(screen.getByText("connected")).toBeDefined();
+ expect(screen.getByText("sign in")).toBeDefined();
+ // The fallback reports no connection field, so it gets no badge: three
+ // cards, two badges.
+ expect(screen.queryAllByText(/^(connected|sign in)$/)).toHaveLength(2);
+ });
+
+ it("singularises a lone result", () => {
+ const single = {
+ ...OUTPUT,
+ count: 1,
+ capabilities: [OUTPUT.capabilities[0]],
+ };
+ render(<FindCapabilitiesTool part={part({ output: single })} />);
+
+ expect(screen.getByText('1 result for "linear issue"')).toBeDefined();
+ });
+
+ it("announces the search while it streams and shows no results row", () => {
+ render(<FindCapabilitiesTool part={part({ state: "input-streaming" })} />);
+
+ expect(
+ screen.getByText('Searching capabilities for "linear issue"'),
+ ).toBeDefined();
+ expect(screen.queryByText("Results")).toBeNull();
+ });
+
+ it("reports a failed search without pretending it returned nothing", () => {
+ render(<FindCapabilitiesTool part={part({ state: "output-error" })} />);
+
+ expect(screen.getByText('Search failed for "linear issue"')).toBeDefined();
+ });
+
+ it("survives an output that is not a capability list", () => {
+ render(
+ <FindCapabilitiesTool part={part({ output: { type: "block_list" } })} />,
+ );
+
+ expect(screen.queryByText("Results")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..35eee6119b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/__tests__/helpers.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import { getAnimationText, kindLabel, parseOutput } from "../helpers";
+
+const OUTPUT = {
+ type: "capability_list",
+ query: "linear issue",
+ count: 2,
+ service: "linear",
+ capabilities: [
+ {
+ id: "block:1",
+ name: "LinearCreateIssueBlock",
+ purpose: "Create an issue.",
+ kind: "block",
+ connected: true,
+ },
+ {
+ id: "mcp:mcp.linear.app",
+ name: "Linear",
+ purpose: "Linear MCP server.",
+ kind: "mcp_server",
+ connected: false,
+ },
+ ],
+ fallback: [
+ {
+ id: "block:2",
+ name: "SendWebRequestBlock",
+ purpose: "HTTP.",
+ kind: "block",
+ class: "primitive",
+ },
+ ],
+};
+
+describe("find_capability helpers", () => {
+ it("parses capability_list outputs as string or object", () => {
+ expect(parseOutput(JSON.stringify(OUTPUT))?.count).toBe(2);
+ expect(parseOutput(OUTPUT)?.capabilities).toHaveLength(2);
+ expect(parseOutput({ type: "block_list", blocks: [] })).toBeNull();
+ expect(parseOutput("")).toBeNull();
+ });
+
+ it("labels kinds for the card footer", () => {
+ expect(kindLabel(OUTPUT.capabilities[0])).toBe("action");
+ expect(kindLabel(OUTPUT.capabilities[1])).toBe("integration");
+ expect(kindLabel(OUTPUT.fallback[0])).toBe("building block");
+ });
+
+ it("animates the search state with the query", () => {
+ const base = {
+ type: "tool-find_capability",
+ toolCallId: "c",
+ input: { query: "linear issue" },
+ };
+ expect(getAnimationText({ ...base, state: "input-available" })).toBe(
+ 'Searching capabilities for "linear issue"',
+ );
+ expect(
+ getAnimationText({ ...base, state: "output-available", output: OUTPUT }),
+ ).toBe('Found 2 capabilities for "linear issue"');
+ expect(getAnimationText({ ...base, state: "output-error" })).toBe(
+ 'Search failed for "linear issue"',
+ );
+ });
+
+ it("survives a query that is not a string yet", () => {
+ const base = { type: "tool-find_capability", toolCallId: "c" };
+ for (const input of [
+ { query: 1 },
+ { query: null },
+ "not an object",
+ null,
+ ]) {
+ expect(
+ getAnimationText({ ...base, state: "input-streaming", input }),
+ ).toBe("Searching capabilities");
+ }
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/helpers.ts
new file mode 100644
index 0000000000..463fd1d8f4
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindCapabilities/helpers.ts
@@ -0,0 +1,91 @@
+export interface CapabilityListing {
+ id: string;
+ name: string;
+ purpose: string;
+ kind: string;
+ class?: string;
+ connected?: boolean | null;
+ eager?: boolean;
+}
+
+export interface CapabilityListOutput {
+ type: "capability_list";
+ query: string;
+ capabilities: CapabilityListing[];
+ count: number;
+ fallback?: CapabilityListing[];
+ service?: string | null;
+ message?: string;
+}
+
+export interface FindCapabilityInput {
+ query?: string;
+ context?: string;
+ kind?: string;
+}
+
+export interface FindCapabilityToolPart {
+ type: string;
+ toolCallId: string;
+ state: string;
+ input?: unknown;
+ output?: unknown;
+}
+
+export function parseOutput(output: unknown): CapabilityListOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const candidate = output as { type?: unknown; capabilities?: unknown };
+ if (
+ candidate.type === "capability_list" &&
+ Array.isArray(candidate.capabilities)
+ ) {
+ return output as CapabilityListOutput;
+ }
+ }
+ return null;
+}
+
+export function queryOf(part: FindCapabilityToolPart): string | undefined {
+ // `input` is whatever the model streamed, so `query` is not necessarily a
+ // string -- and this runs while the call is still streaming.
+ const query = (part.input as FindCapabilityInput | undefined)?.query;
+ return typeof query === "string" ? query.trim() : undefined;
+}
+
+export function getAnimationText(part: FindCapabilityToolPart): string {
+ const query = queryOf(part);
+ const queryText = query ? ` for "${query}"` : "";
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return `Searching capabilities${queryText}`;
+ case "output-available": {
+ const parsed = parseOutput(part.output);
+ if (parsed) {
+ return `Found ${parsed.count} capabilit${parsed.count === 1 ? "y" : "ies"}${queryText}`;
+ }
+ return `Searched capabilities${queryText}`;
+ }
+ case "output-error":
+ return `Search failed${queryText}`;
+ default:
+ return "Searching capabilities";
+ }
+}
+
+export function kindLabel(item: CapabilityListing): string {
+ if (item.kind === "mcp_server") return "integration";
+ if (item.class === "primitive") return "building block";
+ if (item.kind === "tool") return "tool";
+ return "action";
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/helpers.ts
index d61959d828..bcd04ce092 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/helpers.ts
@@ -31,6 +31,10 @@ const TOOL_DISPLAY_NAMES: Record<string, string> = {
view_agent_output: "Agent output",
run_block: "Action",
run_mcp_tool: "MCP tool",
+ find_capability: "Capability search",
+ describe_capability: "Capability details",
+ run_capability: "Action",
+ resume_capability: "Resumed action",
get_agent_building_guide: "Agent building guide",
};
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/RunCapability.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/RunCapability.tsx
new file mode 100644
index 0000000000..0cbb11c0e2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/RunCapability.tsx
@@ -0,0 +1,33 @@
+"use client";
+
+import type { ToolUIPart } from "ai";
+import { GenericTool } from "../GenericTool/GenericTool";
+import { RunBlockTool } from "../RunBlock/RunBlock";
+import { RunMCPToolComponent } from "../RunMCPTool/RunMCPTool";
+import {
+ asBlockPart,
+ asMcpPart,
+ capabilityId,
+ isCapabilityDetails,
+ isMcpCapability,
+ parseOutputObject,
+} from "./helpers";
+
+interface Props {
+ part: ToolUIPart;
+}
+
+/** run_capability / resume_capability / describe_capability render through
+ * the block or MCP renderer their target belongs to, chosen from the
+ * capability id and the response shape. */
+export function RunCapabilityTool({ part }: Props) {
+ const output = parseOutputObject(part.output);
+ const id = capabilityId(part.input);
+ if (isCapabilityDetails(output) || id.startsWith("tool:")) {
+ return <GenericTool part={part} />;
+ }
+ if (isMcpCapability(id, output)) {
+ return <RunMCPToolComponent part={asMcpPart(part, output)} />;
+ }
+ return <RunBlockTool part={asBlockPart(part)} />;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/__tests__/RunCapability.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/__tests__/RunCapability.test.tsx
new file mode 100644
index 0000000000..6e18490845
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/__tests__/RunCapability.test.tsx
@@ -0,0 +1,104 @@
+import type { ToolUIPart } from "ai";
+import { render, screen } from "@/tests/integrations/test-utils";
+import { cleanup } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { RunCapabilityTool } from "../RunCapability";
+
+// The three renderers this component routes between, stubbed down to the
+// part they receive: what is under test is the routing and the re-shaping,
+// not what a block or MCP card looks like.
+vi.mock("../../GenericTool/GenericTool", () => ({
+ GenericTool: () => <div data-testid="generic" />,
+}));
+vi.mock("../../RunBlock/RunBlock", () => ({
+ RunBlockTool: ({ part }: { part: ToolUIPart }) => (
+ <div data-testid="block">{JSON.stringify(part.input)}</div>
+ ),
+}));
+vi.mock("../../RunMCPTool/RunMCPTool", () => ({
+ RunMCPToolComponent: ({ part }: { part: ToolUIPart }) => (
+ <div data-testid="mcp">{JSON.stringify(part.input)}</div>
+ ),
+}));
+
+function part(input: unknown, output?: unknown): ToolUIPart {
+ return {
+ type: "tool-run_capability",
+ toolCallId: "call-1",
+ state: "output-available",
+ input,
+ output,
+ } as ToolUIPart;
+}
+
+describe("RunCapabilityTool", () => {
+ afterEach(cleanup);
+
+ it("sends a block id to the block renderer, unprefixed", () => {
+ render(
+ <RunCapabilityTool
+ part={part({ id: "block:abc-123", input: { url: "https://x" } })}
+ />,
+ );
+
+ expect(JSON.parse(screen.getByTestId("block").textContent ?? "")).toEqual({
+ block_id: "abc-123",
+ input_data: { url: "https://x" },
+ validate_only: false,
+ });
+ });
+
+ it("sends an MCP call to the MCP renderer, flattened", () => {
+ render(
+ <RunCapabilityTool
+ part={part(
+ {
+ id: "mcp:mcp.linear.app",
+ input: { tool: "create_issue", arguments: { title: "t" } },
+ },
+ { type: "mcp_tool_output", server_url: "https://mcp.linear.app/mcp" },
+ )}
+ />,
+ );
+
+ expect(
+ JSON.parse(screen.getByTestId("mcp").textContent ?? ""),
+ ).toMatchObject({
+ server_url: "https://mcp.linear.app/mcp",
+ tool_name: "create_issue",
+ tool_arguments: { title: "t" },
+ });
+ });
+
+ it("renders a platform tool generically", () => {
+ render(<RunCapabilityTool part={part({ id: "tool:list_schedules" })} />);
+
+ expect(screen.getByTestId("generic")).toBeDefined();
+ });
+
+ it("renders a describe_capability answer generically, whatever the target", () => {
+ render(
+ <RunCapabilityTool
+ part={part({ id: "block:abc-123" }, { type: "capability_details" })}
+ />,
+ );
+
+ expect(screen.getByTestId("generic")).toBeDefined();
+ });
+
+ it("routes a resumed MCP call by its review id, before any output", () => {
+ render(
+ <RunCapabilityTool
+ part={part({ review_id: "copilot-mcp-mcp.linear.app:ab12" })}
+ />,
+ );
+
+ expect(screen.getByTestId("mcp")).toBeDefined();
+ });
+
+ it("falls back to the block renderer when nothing names the target", () => {
+ render(<RunCapabilityTool part={part({})} />);
+
+ expect(screen.getByTestId("block")).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..3ea14d6b22
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/__tests__/helpers.test.ts
@@ -0,0 +1,101 @@
+import type { ToolUIPart } from "ai";
+import { describe, expect, it } from "vitest";
+import {
+ asBlockPart,
+ asMcpPart,
+ capabilityId,
+ isCapabilityDetails,
+ isMcpCapability,
+ parseOutputObject,
+} from "../helpers";
+
+function part(input: unknown, output?: unknown): ToolUIPart {
+ return {
+ type: "tool-run_capability",
+ toolCallId: "call-1",
+ state: "output-available",
+ input,
+ output,
+ } as ToolUIPart;
+}
+
+describe("run_capability helpers", () => {
+ it("parses string and object outputs", () => {
+ expect(parseOutputObject('{"type":"block_output"}')).toEqual({
+ type: "block_output",
+ });
+ expect(parseOutputObject({ type: "x" })).toEqual({ type: "x" });
+ expect(parseOutputObject("not json")).toBeNull();
+ expect(parseOutputObject(undefined)).toBeNull();
+ });
+
+ it("recognises MCP targets from the id or the response", () => {
+ expect(isMcpCapability("mcp:mcp.linear.app", null)).toBe(true);
+ expect(isMcpCapability("https://mcp.example.com/mcp", null)).toBe(true);
+ expect(isMcpCapability("block:abc", { type: "mcp_tool_output" })).toBe(
+ true,
+ );
+ expect(isMcpCapability("block:abc", { type: "block_output" })).toBe(false);
+ expect(isCapabilityDetails({ type: "capability_details" })).toBe(true);
+ });
+
+ it("re-shapes a block call into the run_block part shape", () => {
+ const shaped = asBlockPart(
+ part({ id: "block:abc-123", input: { url: "https://x" } }),
+ );
+ expect(shaped.type).toBe("tool-run_block");
+ expect(shaped.input).toEqual({
+ block_id: "abc-123",
+ input_data: { url: "https://x" },
+ validate_only: false,
+ });
+ expect(capabilityId({ id: " block:abc " })).toBe("block:abc");
+ });
+
+ it("re-shapes an MCP call into the run_mcp_tool part shape", () => {
+ const shaped = asMcpPart(
+ part(
+ {
+ id: "mcp:mcp.linear.app",
+ input: { tool: "create_issue", arguments: { title: "t" } },
+ },
+ { type: "mcp_tool_output", server_url: "https://mcp.linear.app/mcp" },
+ ),
+ { type: "mcp_tool_output", server_url: "https://mcp.linear.app/mcp" },
+ );
+ expect(shaped.type).toBe("tool-run_mcp_tool");
+ expect(shaped.input).toEqual({
+ server_url: "https://mcp.linear.app/mcp",
+ tool_name: "create_issue",
+ tool_arguments: { title: "t" },
+ surface_connect_card: false,
+ });
+ });
+
+ it("reads a resumed call's target out of its review id", () => {
+ expect(capabilityId({ review_id: "copilot-mcp-mcp.linear.app:ab12" })).toBe(
+ "mcp:mcp.linear.app",
+ );
+ expect(capabilityId({ review_id: "copilot-node-abc-123:ab12" })).toBe(
+ "block:abc-123",
+ );
+ expect(capabilityId({ review_id: "something-else:ab12" })).toBe("");
+ expect(capabilityId({ review_id: "copilot-mcp-no-suffix" })).toBe("");
+ });
+
+ it("routes a resumed MCP call to the MCP renderer before its output lands", () => {
+ const id = capabilityId({ review_id: "copilot-mcp-mcp.linear.app:ab12" });
+ expect(isMcpCapability(id, null)).toBe(true);
+ });
+
+ it("uses a bare server URL id when the response has none", () => {
+ const shaped = asMcpPart(
+ part({ id: "https://mcp.example.com/mcp", input: { connect: true } }),
+ null,
+ );
+ expect(shaped.input).toMatchObject({
+ server_url: "https://mcp.example.com/mcp",
+ surface_connect_card: true,
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/helpers.ts
new file mode 100644
index 0000000000..49c3a507cb
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunCapability/helpers.ts
@@ -0,0 +1,119 @@
+import type { ToolUIPart } from "ai";
+
+export interface RunCapabilityInput {
+ id?: string;
+ review_id?: string;
+ input?: Record<string, unknown>;
+ validate_only?: boolean;
+ expand?: boolean;
+}
+
+const MCP_OUTPUT_TYPES = new Set(["mcp_tools_discovered", "mcp_tool_output"]);
+
+// Review ids are "<prefix><target>:<random hex>", and the prefix says which
+// renderer the paused call belongs to.
+const MCP_REVIEW_PREFIX = "copilot-mcp-";
+const BLOCK_REVIEW_PREFIX = "copilot-node-";
+
+export function parseOutputObject(
+ output: unknown,
+): Record<string, unknown> | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ try {
+ return parseOutputObject(JSON.parse(output) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ return typeof output === "object"
+ ? (output as Record<string, unknown>)
+ : null;
+}
+
+/** `resume_capability` names its target by `review_id`, not `id`. Reading the
+ * target back out of the review id is what keeps a resumed MCP call from
+ * rendering as a nameless block for the seconds before its output lands. */
+export function capabilityId(input: unknown): string {
+ const call = input as RunCapabilityInput | undefined;
+ const id = typeof call?.id === "string" ? call.id.trim() : "";
+ if (id) return id;
+ const reviewId =
+ typeof call?.review_id === "string" ? call.review_id.trim() : "";
+ const separator = reviewId.lastIndexOf(":");
+ if (separator < 0) return "";
+ const target = reviewId.slice(0, separator);
+ for (const [prefix, kind] of [
+ [MCP_REVIEW_PREFIX, "mcp"],
+ [BLOCK_REVIEW_PREFIX, "block"],
+ ] as const) {
+ if (!target.startsWith(prefix)) continue;
+ const name = target.slice(prefix.length);
+ return name ? `${kind}:${name}` : "";
+ }
+ return "";
+}
+
+export function isMcpCapability(
+ id: string,
+ output: Record<string, unknown> | null,
+): boolean {
+ if (id.startsWith("mcp:") || id.startsWith("https://")) return true;
+ if (!output) return false;
+ const type = output.type;
+ return (
+ (typeof type === "string" && MCP_OUTPUT_TYPES.has(type)) ||
+ "server_url" in output
+ );
+}
+
+export function isCapabilityDetails(
+ output: Record<string, unknown> | null,
+): boolean {
+ return output?.type === "capability_details";
+}
+
+function stripPrefix(id: string, prefix: string): string {
+ return id.startsWith(prefix) ? id.slice(prefix.length) : id;
+}
+
+/** Re-shape a run_capability part into the legacy run_block part shape so
+ * the block renderer (details, output, review, setup card) is reused. */
+export function asBlockPart(part: ToolUIPart): ToolUIPart {
+ const input = (part.input ?? {}) as RunCapabilityInput;
+ return {
+ ...part,
+ type: "tool-run_block",
+ input: {
+ block_id: stripPrefix(capabilityId(input), "block:"),
+ input_data: input.input ?? {},
+ validate_only: input.validate_only ?? false,
+ },
+ } as ToolUIPart;
+}
+
+/** Re-shape a run_capability part into the legacy run_mcp_tool part shape. */
+export function asMcpPart(
+ part: ToolUIPart,
+ output: Record<string, unknown> | null,
+): ToolUIPart {
+ const input = (part.input ?? {}) as RunCapabilityInput;
+ const id = capabilityId(input);
+ const serverUrl =
+ typeof output?.server_url === "string"
+ ? output.server_url
+ : id.startsWith("https://")
+ ? id
+ : "";
+ const inner = input.input ?? {};
+ return {
+ ...part,
+ type: "tool-run_mcp_tool",
+ input: {
+ server_url: serverUrl,
+ tool_name: typeof inner.tool === "string" ? inner.tool : undefined,
+ tool_arguments: inner.arguments,
+ surface_connect_card: inner.connect === true,
+ },
+ } as ToolUIPart;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx
index e53fedeeae..54fe7ccb34 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx
@@ -99,7 +99,7 @@ export function RunMCPToolComponent({ part }: Props) {
{setupRequirementsOutput && (
<MCPSetupCard
output={setupRequirementsOutput}
- retryInstruction="I've connected the MCP server credentials. Please retry run_mcp_tool with the same server_url and arguments."
+ retryInstruction="I've connected the integration. Please retry the same call."
/>
)}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 63105890c8..10769a78dd 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -4049,7 +4049,7 @@
"post": {
"tags": ["v2", "chat", "chat"],
"summary": "Create Session",
- "description": "Create (or get-or-create) a chat session.\n\nTwo modes, selected by the request body:\n\n- Default: create a fresh session for the user. ``dry_run=True`` forces\n run_block and run_agent calls to use dry-run simulation.\n- Builder-bound: when ``builder_graph_id`` is set, get-or-create keyed\n on ``(user_id, builder_graph_id)``. Returns the existing session for\n that graph or creates one locked to it. Graph ownership is validated\n inside :func:`get_or_create_builder_session`; raises 404 on\n unauthorized access. Write-side scope is enforced per-tool\n (``edit_agent`` / ``run_agent`` reject any ``agent_id`` other than\n the bound graph) and a small blacklist hides tools that conflict\n with the panel's scope (see :data:`BUILDER_BLOCKED_TOOLS`).\n- Expert kickoff: atomically create or adopt the canonical first session\n for ``(user_id, expert_id)``.\n\nArgs:\n user_id: The authenticated user ID parsed from the JWT (required).\n request: Optional request body with ``dry_run``,\n ``builder_graph_id`` and/or ``expert_id``.\n\nReturns:\n CreateSessionResponse: Details of the resulting session.",
+ "description": "Create (or get-or-create) a chat session.\n\nTwo modes, selected by the request body:\n\n- Default: create a fresh session for the user. ``dry_run=True`` forces\n run_capability and run_agent calls to use dry-run simulation.\n- Builder-bound: when ``builder_graph_id`` is set, get-or-create keyed\n on ``(user_id, builder_graph_id)``. Returns the existing session for\n that graph or creates one locked to it. Graph ownership is validated\n inside :func:`get_or_create_builder_session`; raises 404 on\n unauthorized access. Write-side scope is enforced per-tool\n (``edit_agent`` / ``run_agent`` reject any ``agent_id`` other than\n the bound graph) and a small blacklist hides tools that conflict\n with the panel's scope (see :data:`BUILDER_BLOCKED_TOOLS`).\n- Expert kickoff: atomically create or adopt the canonical first session\n for ``(user_id, expert_id)``.\n\nArgs:\n user_id: The authenticated user ID parsed from the JWT (required).\n request: Optional request body with ``dry_run``,\n ``builder_graph_id`` and/or ``expert_id``.\n\nReturns:\n CreateSessionResponse: Details of the resulting session.",
"operationId": "postV2CreateSession",
"security": [{ "HTTPBearerJWT": [] }],
"requestBody": {
@@ -17873,7 +17873,7 @@
"type": "object",
"required": ["message", "block"],
"title": "BlockDetailsResponse",
- "description": "Response for block details (first run_block attempt)."
+ "description": "Response for block details (describe_capability / first run attempt)."
},
"BlockInfo": {
"properties": {
@@ -18013,13 +18013,13 @@
"usage_hint": {
"type": "string",
"title": "Usage Hint",
- "default": "To execute a block, call run_block with block_id set to the block's 'id' field and input_data containing the fields listed in required_inputs."
+ "default": "To execute a block, call run_capability with id set to the block's 'id' field and input containing the fields listed in required_inputs."
}
},
"type": "object",
"required": ["message", "blocks", "count", "query"],
"title": "BlockListResponse",
- "description": "Response for find_block tool."
+ "description": "Response for a block search (find_capability / legacy find_block)."
},
"BlockOutputResponse": {
"properties": {
@@ -18052,7 +18052,7 @@
"type": "object",
"required": ["message", "block_id", "block_name", "outputs"],
"title": "BlockOutputResponse",
- "description": "Response for run_block tool."
+ "description": "Response for a block run via run_capability."
},
"BlockResponse": {
"properties": {
@@ -19867,7 +19867,7 @@
"additionalProperties": false,
"type": "object",
"title": "CreateSessionRequest",
- "description": "Request model for creating (or get-or-creating) a chat session.\n\nTwo modes, selected by the body:\n\n- Default: create a fresh session. ``dry_run`` is a **top-level**\n field — do not nest it inside ``metadata``.\n- Builder-bound: when ``builder_graph_id`` is set, the endpoint\n switches to **get-or-create** keyed on\n ``(user_id, builder_graph_id)``. The builder panel calls this on\n mount so the chat persists across refreshes. Graph ownership is\n validated inside :func:`get_or_create_builder_session`. Write-side\n scope is enforced per-tool (``edit_agent`` / ``run_agent`` reject\n any ``agent_id`` other than the bound graph) and a small blacklist\n hides tools that conflict with the panel's scope\n (``create_agent`` / ``customize_agent`` / ``get_agent_building_guide``\n — see :data:`BUILDER_BLOCKED_TOOLS`). Read-side lookups\n (``find_block``, ``find_agent``, ``search_docs``, …) stay open.\n\n``expert_id`` scopes the session to a hired expert. It must reference\nan expert owned by the caller that is neither a template nor archived,\notherwise the request is rejected with 404. It is mutually exclusive\nwith ``builder_graph_id`` (422) — builder-bound sessions are never\nexpert-scoped.\n\n``expert_kickoff`` switches expert creation to an atomic create-or-adopt\nmode keyed by the authenticated user and expert. It is invalid without\n``expert_id``.\n\nExtra/unknown fields are rejected (422) to prevent silent mis-use."
+ "description": "Request model for creating (or get-or-creating) a chat session.\n\nTwo modes, selected by the body:\n\n- Default: create a fresh session. ``dry_run`` is a **top-level**\n field — do not nest it inside ``metadata``.\n- Builder-bound: when ``builder_graph_id`` is set, the endpoint\n switches to **get-or-create** keyed on\n ``(user_id, builder_graph_id)``. The builder panel calls this on\n mount so the chat persists across refreshes. Graph ownership is\n validated inside :func:`get_or_create_builder_session`. Write-side\n scope is enforced per-tool (``edit_agent`` / ``run_agent`` reject\n any ``agent_id`` other than the bound graph) and a small blacklist\n hides tools that conflict with the panel's scope\n (``create_agent`` / ``customize_agent`` / ``get_agent_building_guide``\n — see :data:`BUILDER_BLOCKED_TOOLS`). Read-side lookups\n (``find_capability``, ``find_agent``, ``search_docs``, …) stay open.\n\n``expert_id`` scopes the session to a hired expert. It must reference\nan expert owned by the caller that is neither a template nor archived,\notherwise the request is rejected with 404. It is mutually exclusive\nwith ``builder_graph_id`` (422) — builder-bound sessions are never\nexpert-scoped.\n\n``expert_kickoff`` switches expert creation to an atomic create-or-adopt\nmode keyed by the authenticated user and expert. It is invalid without\n``expert_id``.\n\nExtra/unknown fields are rejected (422) to prevent silent mis-use."
},
"CreateSessionResponse": {
"properties": {
@@ -25042,6 +25042,14 @@
{ "type": "null" }
],
"title": "Icon Id"
+ },
+ "provider": {
+ "anyOf": [
+ { "type": "string", "pattern": "^[a-z0-9_]+$" },
+ { "type": "null" }
+ ],
+ "title": "Provider",
+ "description": "Block provider this server belongs to, when the platform also ships blocks for it. Lets the UI file an MCP connection under the same service as its API-key credential instead of a generic MCP group."
}
},
"additionalProperties": false,
@@ -26431,7 +26439,7 @@
"session_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Session Id",
- "description": "Chat session id for copilot run_block reviews"
+ "description": "Chat session id for copilot run_capability reviews"
},
"was_edited": {
"anyOf": [{ "type": "boolean" }, { "type": "null" }],
@@ -27918,6 +27926,8 @@
"block_details",
"block_output",
"review_required",
+ "capability_list",
+ "capability_details",
"schedule_list",
"schedule_deleted",
"schedule_toggled",
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MCPServerURLField.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MCPServerURLField.tsx
index aa8450063e..ea7ac58c63 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MCPServerURLField.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MCPServerURLField.tsx
@@ -1,6 +1,7 @@
import { useState } from "react";
import { Input } from "@/components/atoms/Input/Input";
import { Select } from "@/components/atoms/Select/Select";
+import { noPasswordManager } from "./helpers";
interface Props {
serverURL: string;
@@ -60,6 +61,7 @@ export function MCPServerURLField({
disabled={disabled}
readOnly={readOnly || Boolean(matched && !customSelected)}
autoFocus={!readOnly && options.length === 0}
+ {...noPasswordManager}
/>
</>
);
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx
index c76af379a2..4f2a27e775 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx
@@ -14,6 +14,7 @@ import { useMCPConnectPanel } from "./useMCPConnectPanel";
import type { MCPAuthScheme } from "@/lib/mcp-auth";
import { MCPServerURLField } from "./MCPServerURLField";
import { MultiToggle } from "@/components/molecules/MultiToggle/MultiToggle";
+import { noPasswordManager } from "./helpers";
interface Props {
onSuccess: (credential?: CredentialsMetaResponse) => void;
@@ -95,6 +96,8 @@ export function McpConnectPanel({
onChange={(e) => state.handleTokenChange(e.target.value)}
disabled={state.isSubmitting}
hint={mcpAuthTokenHint(state.authScheme)}
+ {...noPasswordManager}
+ autoComplete="new-password"
/>
</>
)}
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/helpers.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/helpers.ts
index 9c92d788e3..4d10fb69b8 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/helpers.ts
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/helpers.ts
@@ -74,3 +74,14 @@ export function chatgptModelsSentence(
if (named.length === 1) return named[0];
return `${named.slice(0, -1).join(", ")} and ${named[named.length - 1]}`;
}
+
+// A server URL sitting next to a secret reads as a login form, so password
+// managers offer the saved site credential for both fields. Each vendor
+// honours its own opt-out attribute, so all of them are set.
+export const noPasswordManager = {
+ autoComplete: "off",
+ "data-1p-ignore": true,
+ "data-lpignore": "true",
+ "data-bwignore": true,
+ "data-form-type": "other",
+} as const;
diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.md
index 875d296b41..50af54d1ba 100644
--- a/docs/integrations/block-integrations/misc.md
+++ b/docs/integrations/block-integrations/misc.md
@@ -96,11 +96,11 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run
| transport | Run on platform credits, or on your connected ChatGPT subscription if supported by your plan. | "platform" \| "codex_app_server" | No |
| session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No |
| max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |
-| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_change" \| "confirm_expert_soul_update" \| "connect_integration" \| "consult_teammate" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delegate_to_expert" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "edit_chat_platform_message" \| "enter_agent_building_mode" \| "expert_onboarding" \| "find_agent" \| "find_block" \| "find_library_agent" \| "find_session" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "grant_expert_credential" \| "handoff_to_expert" \| "hire_expert" \| "install_expert_workflow" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_expert_chats" \| "list_expert_credentials" \| "list_expert_workflows" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_team" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "message_session" \| "move_agents_to_folder" \| "move_folder" \| "pause_schedule" \| "post_to_chat_platform" \| "raise_expert" \| "read_expert_chat" \| "read_skill" \| "read_workspace_file" \| "remove_expert_workflow" \| "request_credential_grant" \| "resume_schedule" \| "revoke_expert_credential" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "start_desktop" \| "store_skill" \| "update_expert" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_change" \| "confirm_expert_soul_update" \| "connect_integration" \| "consult_teammate" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delegate_to_expert" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "describe_capability" \| "edit_agent" \| "edit_chat_platform_message" \| "enter_agent_building_mode" \| "expert_onboarding" \| "find_agent" \| "find_capability" \| "find_library_agent" \| "find_session" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_platform_info" \| "get_sub_session_result" \| "grant_expert_credential" \| "handoff_to_expert" \| "hire_expert" \| "install_expert_workflow" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_expert_chats" \| "list_expert_credentials" \| "list_expert_workflows" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_team" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "message_session" \| "move_agents_to_folder" \| "move_folder" \| "pause_schedule" \| "post_to_chat_platform" \| "raise_expert" \| "read_expert_chat" \| "read_skill" \| "read_workspace_file" \| "remove_expert_workflow" \| "request_credential_grant" \| "resume_capability" \| "resume_schedule" \| "revoke_expert_credential" \| "run_agent" \| "run_capability" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "start_desktop" \| "store_skill" \| "update_expert" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "run_block" \| "run_mcp_tool" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
| tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No |
-| blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No |
+| blocks | Block identifiers to filter when the copilot runs blocks via run_capability. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No |
| blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |
-| dry_run | When enabled, run_block and run_agent tool calls in this autopilot session are forced to use dry-run simulation mode. No real API calls, side effects, or credits are consumed by those tools. Useful for testing agent wiring and previewing outputs. Only applies when creating a new session (session_id is empty). When reusing an existing session_id, the session's original dry_run setting is preserved. | bool | No |
+| dry_run | When enabled, run_capability and run_agent tool calls in this autopilot session are forced to use dry-run simulation mode. No real API calls, side effects, or credits are consumed by those tools. Useful for testing agent wiring and previewing outputs. Only applies when creating a new session (session_id is empty). When reusing an existing session_id, the session's original dry_run setting is preserved. | bool | No |
### Outputs