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): AutoPilot decides MCP calls on each server's effect map and asks on first use of any other tool (#14839)

Reinier van der Leer045af59b3577
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 5b176ec445..22ebe6afd3 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
@@ -2,7 +2,7 @@ import json
import re
from datetime import datetime
from functools import cache
-from typing import TYPE_CHECKING, Any, Dict, List, Union
+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Union
from prisma.enums import ReviewStatus
from pydantic import BaseModel, Field, field_validator, model_validator
@@ -158,6 +158,14 @@ class ReviewItem(BaseModel):
"block (node) will be automatically approved. This only affects approved reviews."
),
)
+ chat_rule: Literal["allow", "judge"] | None = Field(
+ default=None,
+ description=(
+ "AutoPilot cards naming a subject only: once approved, the subject "
+ "runs ('allow') or goes to the supervisor ('judge') for the rest of "
+ "the chat instead of asking."
+ ),
+ )
@field_validator("reviewed_data")
@classmethod
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/model_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/model_test.py
index ef8806fcc0..434fd8992c 100644
--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/model_test.py
+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/model_test.py
@@ -3,8 +3,9 @@ from datetime import datetime, timezone
import pytest
from prisma.enums import ReviewStatus
from prisma.models import PendingHumanReview
+from pydantic import ValidationError
-from .model import PendingHumanReviewModel
+from .model import PendingHumanReviewModel, ReviewItem
def _row(instructions: str) -> PendingHumanReview:
@@ -43,3 +44,10 @@ def test_a_block_review_carries_its_block_and_action(instructions, block_id, act
assert review.block_id == block_id
assert review.action == action
+
+
[email protected]("rule", ["ask", "bogus"])
+def test_an_answer_can_only_allow_or_judge_for_the_chat(rule):
+ """Reject is the ask; nothing else may ride on an approval."""
+ with pytest.raises(ValidationError):
+ ReviewItem(node_exec_id="n", approved=True, chat_rule=rule)
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py
index c3365d8a24..0942e8bbec 100644
--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py
@@ -9,6 +9,7 @@ from prisma.enums import ReviewStatus
from pytest_snapshot.plugin import Snapshot
from backend.api.rest_api import app
+from backend.copilot.gate.held import HeldCall
from backend.data.execution import (
ExecutionContext,
ExecutionStatus,
@@ -1419,3 +1420,59 @@ async def test_an_answer_on_a_chat_card_wakes_that_chat(
assert [r.node_exec_id for r in wake.await_args.args[2]] == ["test_node_123"]
else:
wake.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_an_approved_chat_card_sets_the_rule_it_asked_for(
+ client: httpx.AsyncClient,
+ mocker: pytest_mock.MockerFixture,
+ sample_pending_review: PendingHumanReviewModel,
+) -> None:
+ """The rule lands on the subject the gate stored with the held call."""
+ review = sample_pending_review.model_copy(
+ update={"graph_exec_id": None, "session_id": "s1"}
+ )
+ held_call = HeldCall(
+ review_id="test_node_123",
+ tool_name="run_capability",
+ tool_call_id="c",
+ args={},
+ rule_key="mcp:h/t",
+ )
+ # The turn the answer wakes claims the held call, so it is gone afterwards.
+ held_calls = {"test_node_123": held_call}
+ mocker.patch(
+ "backend.copilot.gate.held._held", side_effect=lambda _: dict(held_calls)
+ )
+ routes = "backend.api.features.graph_executions.review.routes"
+ mocker.patch(
+ f"{routes}.get_reviews_by_node_exec_ids",
+ return_value={"test_node_123": review},
+ )
+ approved = review.model_copy(update={"status": ReviewStatus.APPROVED})
+
+ async def process_and_claim(**_):
+ held_calls.clear()
+ return {"test_node_123": approved}
+
+ mocker.patch(
+ f"{routes}.process_all_reviews_for_execution", side_effect=process_and_claim
+ )
+ mocker.patch(f"{routes}.wake_for_held_calls")
+ set_rule = mocker.patch("backend.copilot.gate.chat_rules.set_rule")
+
+ response = await client.post(
+ "/api/review/action",
+ json={
+ "reviews": [
+ {
+ "node_exec_id": "test_node_123",
+ "approved": True,
+ "chat_rule": "allow",
+ }
+ ]
+ },
+ )
+
+ assert response.status_code == 200
+ set_rule.assert_awaited_once_with("s1", "mcp:h/t", "allow")
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py
index ae3fd8a51a..5a9ae0597b 100644
--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py
+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py
@@ -7,6 +7,8 @@ from fastapi import APIRouter, HTTPException, Query, Security, status
from prisma.enums import ReviewStatus
from backend.copilot.constants import legacy_chat_session_id, parse_node_id_from_exec_id
+from backend.copilot.gate.chat_rules import set_answer_rules as set_chat_rules
+from backend.copilot.gate.held import subject_keys as held_subject_keys
from backend.copilot.gate.held import wake as wake_for_held_calls
from backend.data.execution import (
ExecutionContext,
@@ -260,6 +262,15 @@ async def process_review_action(
)
auto_approve_requests[review.node_exec_id] = review.auto_approve_future
+ # Read before the answer lands: a turn it wakes claims the held calls.
+ chat_rule_keys = (
+ await held_subject_keys(
+ chat_session_id, [r.node_exec_id for r in request.reviews if r.chat_rule]
+ )
+ if chat_session_id is not None
+ else {}
+ )
+
# Process all reviews
updated_reviews = await process_all_reviews_for_execution(
user_id=user_id,
@@ -345,6 +356,14 @@ async def process_review_action(
if review.status == ReviewStatus.REJECTED
)
+ if chat_session_id is not None and chat_rule_keys:
+ await set_chat_rules(
+ chat_session_id,
+ updated_reviews,
+ {review.node_exec_id: review.chat_rule for review in request.reviews},
+ chat_rule_keys,
+ )
+
# A held call finishes on its own: the answer starts the chat's next turn.
if chat_session_id is not None and updated_reviews:
await wake_for_held_calls(user_id, chat_session_id, updated_reviews.values())
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py b/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py
index 55c4638b34..6d91d3c506 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py
@@ -1,10 +1,10 @@
"""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``.
+With the auto-mode gate off, MCP tool annotations are untrusted and mostly
+absent, so 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.
+With the gate on, none of this runs: the server's effect map decides, or the
+tool asks on first use (``gate/subject.py``).
Records reuse the block review table with a synthetic node id so the
existing approval UI, the pending-review feed and ``resume_capability`` all
diff --git a/autogpt_platform/backend/backend/copilot/gate/__init__.py b/autogpt_platform/backend/backend/copilot/gate/__init__.py
index 364902b543..a9c477f7f0 100644
--- a/autogpt_platform/backend/backend/copilot/gate/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/gate/__init__.py
@@ -4,10 +4,10 @@ Ordering is the design, cheapest and most certain first:
1. gate inactive -> ALLOW (today's behaviour)
2. an approval for exactly these args -> ALLOW, consumed single-use
-3. the user rejected this tool in chat -> ASK, in every mode
-4. what the call acts on: a block or workflow's own effect, or the tool's;
- a call that runs nothing never asks
-5. the mode's verdict for that effect: run, ask, or the supervisor
+3. what the call acts on: a block, workflow or MCP tool's own effect, or
+ the tool's; a call that runs nothing never asks
+4. the user's rule on that subject in this chat -> allow, judge or ask
+5. otherwise the mode's verdict for that effect: run, ask, or the supervisor
The supervisor is last because it is the least trusted step: it can only turn
a run into a question, never the reverse.
@@ -54,6 +54,13 @@ _UNRECORDABLE = (
_ASK_FIRST = "Ask First is on for this chat, so this action needs your approval."
_OUTWARD = "This action reaches outside the platform, so it needs your approval."
_PARKABLE = frozenset({Effect.SHELL, Effect.PLATFORM, Effect.EXTERNAL})
+# The user's own word on the subject in this chat outranks the mode's rule.
+_RULE_VERDICTS = {
+ "allow": Verdict.RUN,
+ "judge": Verdict.JUDGE,
+ "ask": Verdict.ASK,
+ "unreadable": Verdict.ASK,
+}
class Decision(BaseModel):
@@ -136,14 +143,17 @@ async def check_action(
return ALLOW
rule_key = subject.key if subject is not None else tool_name
mode = resolve_mode(session)
- verdict = verdict_for_effect(mode, effect)
+ # Only a subject that can be parked can carry a rule, so reads and
+ # workspace work skip the Redis round trip.
+ rule = (
+ await chat_rules.rule_for(session_id, rule_key) if effect in _PARKABLE else None
+ )
+ # A judge rule covers irreversible subjects too: the user chose the supervisor.
+ verdict = _RULE_VERDICTS[rule] if rule else verdict_for_effect(mode, effect)
reason_kind: review_store.ReasonKind
- # A block or workflow that only reads can never have been parked, though
- # the tool calling it can, so it skips the Redis round trip too.
- if effect in _PARKABLE and (
- rule_reason := await chat_rules.ask_reason(session_id, rule_key)
- ):
- reason, reason_kind = rule_reason, "rule"
+ if rule in ("ask", "unreadable"):
+ reason = chat_rules.DECLINED if rule == "ask" else chat_rules.UNREADABLE
+ reason_kind = "rule"
elif verdict is Verdict.RUN:
return ALLOW
elif verdict is Verdict.ASK and subject is not None and subject.reason:
diff --git a/autogpt_platform/backend/backend/copilot/gate/chat_rules.py b/autogpt_platform/backend/backend/copilot/gate/chat_rules.py
index 7eb8076aec..e7832bade3 100644
--- a/autogpt_platform/backend/backend/copilot/gate/chat_rules.py
+++ b/autogpt_platform/backend/backend/copilot/gate/chat_rules.py
@@ -1,11 +1,22 @@
-"""Chat-scoped ask rules: a subject the user rejected asks for the rest of the chat."""
+"""Chat-scoped rules: the user's own word on a subject for the rest of the chat.
+
+A rejection sets ``ask``; a card answered with a rule sets ``allow`` or
+``judge``. A subject holds one rule at a time and the latest answer replaces it.
+"""
import logging
+from typing import Literal, Mapping, get_args
+
+from prisma.enums import ReviewStatus
+from backend.api.features.graph_executions.review.model import PendingHumanReviewModel
from backend.data.redis_client import get_redis_async
logger = logging.getLogger(__name__)
+ChatRule = Literal["allow", "judge", "ask"]
+_RULES: dict[str, ChatRule] = {rule: rule for rule in get_args(ChatRule)}
+
# Outlives any chat anyone is still in; dead chats expire out of Redis.
_TTL_SECONDS = 90 * 24 * 60 * 60
_ASK_KEY = "copilot:gate:ask:"
@@ -18,35 +29,63 @@ UNREADABLE = (
)
-async def set_ask(session_id: str, tool_name: str) -> None:
- """Monotone: there is no un-ask, so re-proposing the call with a space
- added to its arguments cannot buy a fresh verdict."""
+async def set_ask(session_id: str, rule_key: str) -> None:
+ """Only the user's answer on a card replaces an ask, so re-proposing the
+ call with a space added to its arguments cannot buy a fresh verdict."""
+ await set_rule(session_id, rule_key, "ask")
+
+
+async def set_rule(session_id: str, rule_key: str, rule: ChatRule) -> None:
try:
redis = await get_redis_async()
- await redis.setex(_key(session_id, tool_name), _TTL_SECONDS, "1")
+ await redis.setex(_key(session_id, rule_key), _TTL_SECONDS, rule)
except Exception:
logger.warning(
- f"Gate could not persist an ask rule for session {session_id}",
+ f"Gate could not persist a {rule} rule for session {session_id}",
exc_info=True,
)
-async def ask_reason(session_id: str, tool_name: str) -> str | None:
- """Why this tool must ask in this chat, or None when no rule applies."""
+async def set_answer_rules(
+ session_id: str,
+ answered: Mapping[str, PendingHumanReviewModel],
+ rules: Mapping[str, ChatRule | None],
+ subject_keys: Mapping[str, str],
+) -> None:
+ """The rule each approved card asked for, on the subject it named.
+
+ ``subject_keys`` come from the held calls the gate stored, so a click can
+ only ever rule on a subject the server put on a card.
+ """
+ for review_id, rule in rules.items():
+ row = answered.get(review_id)
+ key = subject_keys.get(review_id)
+ if rule and key and row is not None and row.status == ReviewStatus.APPROVED:
+ await set_rule(session_id, key, rule)
+
+
+async def rule_for(
+ session_id: str, rule_key: str
+) -> ChatRule | Literal["unreadable"] | None:
+ """``unreadable`` asks like ``ask`` but must not claim the user said no."""
try:
redis = await get_redis_async()
- declined = await redis.get(_key(session_id, tool_name)) is not None
+ raw = await redis.get(_key(session_id, rule_key))
except Exception:
logger.warning(
- f"Gate could not read ask rules for session {session_id}; "
+ f"Gate could not read chat rules for session {session_id}; "
"assuming the subject asks",
exc_info=True,
)
- return UNREADABLE
- return DECLINED if declined else None
+ return "unreadable"
+ if raw is None:
+ return None
+ value = raw.decode() if isinstance(raw, bytes) else str(raw)
+ # Rows written before rules had decisions hold "1", which meant ask.
+ return _RULES.get(value, "ask")
-def _key(session_id: str, tool_name: str) -> str:
- # A flag per (session, tool): the cluster client's set operations are not
- # typed as awaitable.
- return f"{_ASK_KEY}{session_id}:{tool_name}"
+def _key(session_id: str, rule_key: str) -> str:
+ # A flag per (session, subject): the cluster client's set operations are
+ # not typed as awaitable.
+ return f"{_ASK_KEY}{session_id}:{rule_key}"
diff --git a/autogpt_platform/backend/backend/copilot/gate/chat_rules_test.py b/autogpt_platform/backend/backend/copilot/gate/chat_rules_test.py
new file mode 100644
index 0000000000..7c36e44573
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/gate/chat_rules_test.py
@@ -0,0 +1,100 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.enums import ReviewStatus
+
+from backend.copilot.gate import chat_rules, held
+
+
+class _Redis:
+ def __init__(self, data: dict[str, str] | None = None) -> None:
+ self.data = data or {}
+
+ async def setex(self, key: str, ttl: int, value: str) -> None:
+ self.data[key] = value
+
+ async def get(self, key: str) -> str | None:
+ return self.data.get(key)
+
+
+def redis():
+ store = _Redis()
+ with patch.object(chat_rules, "get_redis_async", AsyncMock(return_value=store)):
+ yield store
+
+
+def _row(status: ReviewStatus) -> SimpleNamespace:
+ return SimpleNamespace(status=status)
+
+
+async def test_an_approved_card_rules_on_the_subject_it_named(redis):
+ await chat_rules.set_answer_rules(
+ "s", {"a": _row(ReviewStatus.APPROVED)}, {"a": "allow"}, {"a": "mcp:h/t"}
+ )
+ assert await chat_rules.rule_for("s", "mcp:h/t") == "allow"
+ assert await chat_rules.rule_for("s", "mcp:h/other") is None
+
+
+ "status, keys",
+ [
+ (ReviewStatus.REJECTED, {"a": "mcp:h/t"}),
+ (ReviewStatus.WAITING, {"a": "mcp:h/t"}),
+ # A bare tool or a held read names no subject, so a click cannot rule on it.
+ (ReviewStatus.APPROVED, {}),
+ ],
+)
+async def test_only_an_approved_subject_card_sets_a_rule(redis, status, keys):
+ await chat_rules.set_answer_rules("s", {"a": _row(status)}, {"a": "allow"}, keys)
+ assert redis.data == {}
+
+
+async def test_a_later_answer_replaces_the_rule(redis):
+ await chat_rules.set_ask("s", "mcp:h/t")
+ await chat_rules.set_rule("s", "mcp:h/t", "judge")
+ assert await chat_rules.rule_for("s", "mcp:h/t") == "judge"
+
+
+async def test_a_rule_written_before_decisions_existed_still_asks():
+ store = _Redis({"copilot:gate:ask:s:bash_exec": "1"})
+ with patch.object(chat_rules, "get_redis_async", AsyncMock(return_value=store)):
+ assert await chat_rules.rule_for("s", "bash_exec") == "ask"
+
+
+async def test_an_unreadable_store_asks():
+ with patch.object(
+ chat_rules, "get_redis_async", AsyncMock(side_effect=ConnectionError)
+ ):
+ assert await chat_rules.rule_for("s", "mcp:h/t") == "unreadable"
+
+
+async def test_only_a_held_call_with_a_subject_offers_a_key():
+ calls = {
+ "mcp": held.HeldCall(
+ review_id="mcp",
+ tool_name="run_capability",
+ tool_call_id="c",
+ args={},
+ rule_key="mcp:h/t",
+ ),
+ "tool": held.HeldCall(
+ review_id="tool",
+ tool_name="bash_exec",
+ tool_call_id="c",
+ args={},
+ rule_key="bash_exec",
+ ),
+ "read": held.HeldCall(
+ review_id="read", tool_name="web_fetch", tool_call_id="c", args={}
+ ),
+ }
+ with patch.object(held, "_held", AsyncMock(return_value=calls)):
+ keys = await held.subject_keys("s", ["mcp", "tool", "read", "gone"])
+ assert keys == {"mcp": "mcp:h/t"}
+
+
+async def test_an_unreadable_store_approves_without_a_rule():
+ with patch.object(held, "_held", AsyncMock(side_effect=ConnectionError)):
+ assert await held.subject_keys("s", ["mcp"]) == {}
diff --git a/autogpt_platform/backend/backend/copilot/gate/gate_test.py b/autogpt_platform/backend/backend/copilot/gate/gate_test.py
index 616efcb9ec..fff2bd5270 100644
--- a/autogpt_platform/backend/backend/copilot/gate/gate_test.py
+++ b/autogpt_platform/backend/backend/copilot/gate/gate_test.py
@@ -23,7 +23,7 @@ from backend.copilot.model import (
_GATE = "backend.copilot.gate"
# The fixtures stub the rule lookup; the outage tests need the real one.
-_REAL_ASK_REASON = chat_rules.ask_reason
+_REAL_RULE_FOR = chat_rules.rule_for
_MODES: tuple[AutopilotMode, ...] = ("ask_first", "auto", "unsupervised")
@@ -60,7 +60,7 @@ def clean_session_state():
patch(f"{_GATE}.held.remember", AsyncMock(return_value=True)),
patch(f"{_GATE}.held._held", AsyncMock(return_value={})),
patch(f"{_GATE}.review_store.open_review", AsyncMock(return_value=True)),
- patch(f"{_GATE}.chat_rules.ask_reason", AsyncMock(return_value=None)),
+ patch(f"{_GATE}.chat_rules.rule_for", AsyncMock(return_value=None)),
patch(f"{_GATE}.chat_rules.set_ask", AsyncMock()),
):
yield
@@ -216,7 +216,7 @@ async def test_a_rejection_makes_the_tool_ask_for_the_rest_of_the_chat(
async def test_a_chat_ask_rule_holds_in_every_mode(gate_on, clean_session_state, mode):
supervisor = AsyncMock(return_value=(True, "fine"))
with (
- patch(f"{_GATE}.chat_rules.ask_reason", AsyncMock(return_value="declined")),
+ patch(f"{_GATE}.chat_rules.rule_for", AsyncMock(return_value="ask")),
patch(f"{_GATE}.classify", supervisor),
):
decision = await check_action("delete_folder", {"id": "f"}, "u", _session(mode))
@@ -228,7 +228,7 @@ async def test_a_chat_ask_rule_holds_in_every_mode(gate_on, clean_session_state,
async def test_reads_never_look_up_ask_rules(gate_on, clean_session_state):
"""A Redis outage reads as 'asks', which must not turn every search into a card."""
asks = AsyncMock(return_value="unreadable")
- with patch(f"{_GATE}.chat_rules.ask_reason", asks):
+ with patch(f"{_GATE}.chat_rules.rule_for", asks):
decision = await check_action("web_search", {"query": "x"}, "u", _session())
assert decision.allowed
asks.assert_not_awaited()
@@ -283,7 +283,7 @@ async def test_an_unreadable_ask_rule_asks_without_claiming_a_decline(
f"{_GATE}.chat_rules.get_redis_async",
AsyncMock(side_effect=ConnectionError("redis down")),
),
- patch(f"{_GATE}.chat_rules.ask_reason", _REAL_ASK_REASON),
+ patch(f"{_GATE}.chat_rules.rule_for", _REAL_RULE_FOR),
patch(f"{_GATE}.classify", AsyncMock(return_value=(True, "fine"))),
):
decision = await check_action("delete_folder", {"id": "f"}, "u", _session(mode))
@@ -291,8 +291,7 @@ async def test_an_unreadable_ask_rule_asks_without_claiming_a_decline(
assert decision.reason == chat_rules.UNREADABLE
-async def test_a_rejected_tool_says_the_user_declined_it():
- redis = AsyncMock()
- redis.get = AsyncMock(return_value="1")
- with patch(f"{_GATE}.chat_rules.get_redis_async", AsyncMock(return_value=redis)):
- assert await chat_rules.ask_reason("s", "bash_exec") == chat_rules.DECLINED
+async def test_a_rejected_tool_says_the_user_declined_it(gate_on, clean_session_state):
+ with patch(f"{_GATE}.chat_rules.rule_for", AsyncMock(return_value="ask")):
+ decision = await check_action("delete_folder", {"id": "f"}, "u", _session())
+ assert decision.reason == chat_rules.DECLINED
diff --git a/autogpt_platform/backend/backend/copilot/gate/held.py b/autogpt_platform/backend/backend/copilot/gate/held.py
index d1b63e2ac5..a0bd54ad28 100644
--- a/autogpt_platform/backend/backend/copilot/gate/held.py
+++ b/autogpt_platform/backend/backend/copilot/gate/held.py
@@ -100,6 +100,28 @@ async def rule_key(session_id: str, review_id: str, tool_name: str) -> str:
return (call.rule_key if call else None) or tool_name
+async def subject_keys(session_id: str, review_ids: list[str]) -> dict[str, str]:
+ """The subject each held card named; a bare tool or a held read names none."""
+ if not review_ids:
+ return {}
+ try:
+ held = await _held(session_id)
+ except Exception:
+ # The approval still lands; only the rule is lost.
+ logger.warning(
+ f"Held calls unreadable for session {session_id}; approving without a rule",
+ exc_info=True,
+ )
+ return {}
+ return {
+ review_id: call.rule_key
+ for review_id in review_ids
+ if (call := held.get(review_id))
+ and call.rule_key
+ and call.rule_key != call.tool_name
+ }
+
+
async def forget(session_id: str, review_id: str) -> None:
"""Drop a call whose card was never opened; nothing can answer it."""
await _claim(session_id, review_id)
diff --git a/autogpt_platform/backend/backend/copilot/gate/held_db_test.py b/autogpt_platform/backend/backend/copilot/gate/held_db_test.py
index a37c26f21c..d4a0b7b506 100644
--- a/autogpt_platform/backend/backend/copilot/gate/held_db_test.py
+++ b/autogpt_platform/backend/backend/copilot/gate/held_db_test.py
@@ -414,7 +414,7 @@ async def test_a_rejection_never_runs_and_the_tool_asks_from_then_on(
assert post_tool.runs == []
assert "declined" in delivered[0].content
assert delivered[0].metadata["held_call"]["outcome"] == "rejected"
- assert await chat_rules.ask_reason(session.session_id, _TOOL) == chat_rules.DECLINED
+ assert await chat_rules.rule_for(session.session_id, _TOOL) == "ask"
@pytest.mark.asyncio(loop_scope="session")
diff --git a/autogpt_platform/backend/backend/copilot/gate/review.py b/autogpt_platform/backend/backend/copilot/gate/review.py
index 2a495d1bca..9e7f8e44d7 100644
--- a/autogpt_platform/backend/backend/copilot/gate/review.py
+++ b/autogpt_platform/backend/backend/copilot/gate/review.py
@@ -73,7 +73,7 @@ class GateReviewPayload(BaseModel):
subject: Subject
reason: str = ""
reason_kind: ReasonKind = "mode"
- # The gate records no chat-scoped rule yet, so none is offered.
+ # Only a card naming a subject can set a rule on it.
chat_rules_allowed: list[Literal["allow", "judge"]] = []
headline: Headline
@@ -138,6 +138,7 @@ def review_payload(
subject=_payload_subject(tool_name, args, subject),
reason=" ".join(reason.split())[:300],
reason_kind=reason_kind,
+ chat_rules_allowed=["allow", "judge"] if subject is not None else [],
headline=(
Headline(ask="Run", object=subject.name)
if subject is not None
diff --git a/autogpt_platform/backend/backend/copilot/gate/review_test.py b/autogpt_platform/backend/backend/copilot/gate/review_test.py
index f33147d738..dab669f40a 100644
--- a/autogpt_platform/backend/backend/copilot/gate/review_test.py
+++ b/autogpt_platform/backend/backend/copilot/gate/review_test.py
@@ -16,7 +16,7 @@ from backend.copilot.gate.review import (
review_id_for,
review_payload,
)
-from backend.copilot.gate.subject import block_subject
+from backend.copilot.gate.subject import block_subject, mcp_subject
def test_the_same_call_is_the_same_approval():
@@ -166,8 +166,11 @@ def test_a_bare_tool_is_its_own_subject():
assert payload["mode"] == "auto"
-def test_no_rule_is_offered_before_the_gate_records_one():
+def test_a_bare_tool_offers_no_rule_and_a_named_subject_offers_both():
assert review_payload("create_folder", {})["chat_rules_allowed"] == []
+ subject = mcp_subject("https://mcp.example.com/mcp", "create_issue")
+ payload = review_payload("run_capability", {}, subject)
+ assert payload["chat_rules_allowed"] == ["allow", "judge"]
@pytest.mark.parametrize(
diff --git a/autogpt_platform/backend/backend/copilot/gate/subject.py b/autogpt_platform/backend/backend/copilot/gate/subject.py
index fa716d4cdf..af6249b063 100644
--- a/autogpt_platform/backend/backend/copilot/gate/subject.py
+++ b/autogpt_platform/backend/backend/copilot/gate/subject.py
@@ -1,16 +1,18 @@
"""What a call acts on, when the tool's name alone does not say.
-``run_capability`` and ``run_agent`` run a block or a workflow; the gate
+``run_capability`` and ``run_agent`` run a block, a workflow or an MCP tool; the gate
decides on that subject's effect, and the card's headline names it.
"""
import re
from typing import TYPE_CHECKING, Any
+from urllib.parse import urlsplit
from pydantic import BaseModel, ConfigDict
from backend.blocks._base import Block, BlockEffect
from backend.copilot.constants import AUTOPILOT_NAME
+from backend.integrations.mcp_catalog import mcp_tool_effect
from .effects import JUDGED_BLOCKS, block_effect, graph_effect
from .policy import Effect
@@ -22,22 +24,21 @@ if TYPE_CHECKING:
class Subject(BaseModel):
model_config = ConfigDict(frozen=True)
- # What a chat rule names: ``block:<id>`` or ``workflow:<graph id>``.
+ # What a chat rule names: ``block:<id>``, ``workflow:<graph id>`` or
+ # ``mcp:<host><path>::<tool>``.
key: str
name: str
effect: Effect
# The line the card shows under the name; empty where nothing asks.
reason: str = ""
- # A judge rule still asks: the supervisor may not wave through what
- # cannot be taken back.
+ # Shows "Can't be undone" and keeps the card out of approve-all; a judge
+ # rule still covers it.
irreversible: bool = False
# A schema lookup, ``validate_only``, a dry run, or a trigger workflow's details:
# nothing runs, so nothing asks, whatever the mode.
NO_OP = Subject(key="", name="", effect=Effect.UNGATED)
-# An MCP call keeps its own review until MCP servers carry effect maps.
-OWN_REVIEW = Subject(key="", name="", effect=Effect.UNGATED)
def block_subject(block: Block, inputs: dict[str, Any]) -> Subject:
@@ -102,6 +103,32 @@ def workflow_subject(
return subject
+def mcp_subject(server_url: str, tool: str) -> Subject:
+ """Keyed on the server (host and path, since one host can serve many) and
+ the tool, so a rule on one tool leaves every other asking. Only the
+ server's effect map decides; a tool's name is no evidence of what it does."""
+ url = urlsplit(server_url)
+ host = url.hostname or server_url
+ port = f":{url.port}" if url.port not in (None, 443) else ""
+ mapped = mcp_tool_effect(server_url, tool)
+ name = f"{tool} on {host}"
+ if mapped is None:
+ effect = Effect.EXTERNAL
+ reason = f"{AUTOPILOT_NAME} does not know what {name} does, so he asks."
+ elif mapped == "read":
+ effect, reason = Effect.READ, ""
+ else:
+ effect = Effect.EXTERNAL
+ reason = f"Runs {name}, which reaches outside the platform."
+ return Subject(
+ key=f"mcp:{host}{port}{url.path.rstrip('/')}::{tool}",
+ name=name,
+ effect=effect,
+ reason=reason,
+ irreversible=mapped == "irreversible",
+ )
+
+
def display_name(block: Block) -> str:
"""``GmailSendBlock`` -> ``Gmail Send``; the card drops any headline
containing "Block", so the suffix must go."""
diff --git a/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py b/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py
new file mode 100644
index 0000000000..66746b38ee
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py
@@ -0,0 +1,264 @@
+"""The gate decides an MCP call on the server's effect map, and asks on first
+use of any tool the map does not name.
+
+Driven through ``BaseTool.execute`` so the subject hook, the gate, the chat
+rules and the MCP path are the ones the engines call.
+"""
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.enums import ReviewStatus
+
+from backend.copilot.gate import chat_rules
+from backend.copilot.gate.review import payload_headline, review_payload
+from backend.copilot.model import AutopilotMode, ChatSession, ChatSessionMetadata
+from backend.copilot.tools.models import MCPToolOutputResponse
+from backend.copilot.tools.run_capability import RunCapabilityTool
+
+_GATE = "backend.copilot.gate"
+_CAP = "backend.copilot.tools.run_capability"
+_GITHUB = "mcp:api.githubcopilot.com"
+_OPEN_WORLD = "https://mcp.example.com/mcp"
+
+
+def _session(mode: AutopilotMode = "auto") -> ChatSession:
+ return ChatSession(
+ session_id="session-1",
+ user_id="user-1",
+ usage=[],
+ started_at=datetime.now(UTC),
+ updated_at=datetime.now(UTC),
+ metadata=ChatSessionMetadata(origin="interactive", autopilot_mode=mode),
+ messages=[],
+ )
+
+
+class _Redis:
+ """Chat rules are plain keys; the real module builds and reads them."""
+
+ def __init__(self) -> None:
+ self.data: dict[str, str] = {}
+
+ async def setex(self, key: str, ttl: int, value: str) -> None:
+ self.data[key] = value
+
+ async def get(self, key: str) -> str | None:
+ return self.data.get(key)
+
+
+def gate():
+ """The gate on, no approval on record, chat rules on a fresh store."""
+ store = SimpleNamespace(
+ find_review=AsyncMock(return_value=None),
+ open_review=AsyncMock(return_value=True),
+ consume=AsyncMock(return_value=True),
+ own_review=AsyncMock(return_value="copilot-mcp-x:1"),
+ classify=AsyncMock(return_value=(True, "")),
+ )
+ with (
+ patch(f"{_GATE}.is_feature_enabled", AsyncMock(return_value=True)),
+ patch(f"{_GATE}.review_store.find_review", store.find_review),
+ patch(f"{_GATE}.review_store.open_review", store.open_review),
+ patch(f"{_GATE}.review_store.consume", store.consume),
+ patch(f"{_GATE}.held.remember", AsyncMock(return_value=True)),
+ patch(f"{_GATE}.classify", store.classify),
+ patch(f"{_GATE}.reads.release_held_read", AsyncMock(return_value=None)),
+ patch(f"{_GATE}.reads.screen_read", AsyncMock(return_value=None)),
+ patch(f"{_CAP}.open_mcp_review", store.own_review),
+ patch(
+ "backend.copilot.gate.chat_rules.get_redis_async",
+ AsyncMock(return_value=_Redis()),
+ ),
+ ):
+ yield store
+
+
+def ran():
+ """What reached the MCP server, if anything did."""
+ run = AsyncMock(
+ return_value=MCPToolOutputResponse(
+ message="ran", server_url="u", tool_name="t", session_id="session-1"
+ )
+ )
+ with patch(f"{_CAP}.RunMCPToolTool._execute", run):
+ yield run
+
+
+async def _call(
+ session: ChatSession,
+ server: str,
+ tool: str,
+ arguments: dict[str, Any] | None = None,
+):
+ return await RunCapabilityTool().execute(
+ "user-1",
+ session,
+ "call-1",
+ id=server,
+ input={"tool": tool, "arguments": arguments or {}},
+ )
+
+
+def _is_held(result) -> bool:
+ return "approval_required" in str(result.output)
+
+
+def _headline(gate) -> str:
+ _, _, _, tool_name, args, reason, subject = gate.open_review.await_args.args
+ card = payload_headline(review_payload(tool_name, args, subject))
+ assert card == f"Run “{subject.name}”"
+ return f"{subject.name} — {reason}"
+
+
[email protected]("mode", ["ask_first", "auto"])
+async def test_a_mapped_read_runs_and_a_mapped_write_asks(gate, ran, mode):
+ read = await _call(_session(mode), _GITHUB, "issue_read", {"issue_number": 1})
+ assert not _is_held(read)
+ ran.assert_awaited_once()
+
+ write = await _call(_session(mode), _GITHUB, "create_branch", {"branch": "x"})
+ assert _is_held(write)
+ ran.assert_awaited_once()
+ assert _headline(gate) == (
+ "create_branch on api.githubcopilot.com — Runs create_branch on "
+ "api.githubcopilot.com, which reaches outside the platform."
+ )
+
+
+async def test_an_unmapped_tool_asks_naming_the_host_and_the_tool(gate, ran):
+ result = await _call(_session(), _GITHUB, "brand_new_tool")
+ assert _is_held(result)
+ ran.assert_not_awaited()
+ assert _headline(gate) == (
+ "brand_new_tool on api.githubcopilot.com — Otto does not know what "
+ "brand_new_tool on api.githubcopilot.com does, so he asks."
+ )
+
+
[email protected]("mode", ["ask_first", "auto"])
+async def test_a_read_shaped_name_on_an_unknown_server_still_asks(gate, ran, mode):
+ """A tool's name is no evidence: the verb heuristic never runs under the flag."""
+ result = await _call(_session(mode), _OPEN_WORLD, "get_things")
+ assert _is_held(result)
+ ran.assert_not_awaited()
+ assert "get_things on mcp.example.com" in _headline(gate)
+
+
+async def test_a_chat_allow_covers_that_tool_and_no_other_on_the_host(gate, ran):
+ session = _session()
+ assert _is_held(await _call(session, _OPEN_WORLD, "do_thing", {"n": 1}))
+ await _answer_with_rule(gate, "allow")
+
+ assert not _is_held(await _call(session, _OPEN_WORLD, "do_thing", {"n": 2}))
+ ran.assert_awaited_once()
+ assert _is_held(await _call(session, _OPEN_WORLD, "other_thing"))
+ ran.assert_awaited_once()
+
+
+async def test_a_chat_judge_sends_the_next_call_to_the_supervisor(gate, ran):
+ session = _session("ask_first")
+ assert _is_held(await _call(session, _OPEN_WORLD, "do_thing", {"n": 1}))
+ gate.classify.assert_not_awaited()
+ await _answer_with_rule(gate, "judge")
+
+ assert not _is_held(await _call(session, _OPEN_WORLD, "do_thing", {"n": 2}))
+ gate.classify.assert_awaited_once()
+ ran.assert_awaited_once()
+
+
+async def test_a_chat_allow_does_not_reach_another_server_on_the_host(gate, ran):
+ session = _session()
+ server_a, server_b = (
+ "https://tools.example.com/a/mcp",
+ "https://tools.example.com/b/mcp",
+ )
+ assert _is_held(await _call(session, server_a, "search", {"q": 1}))
+ await _answer_with_rule(gate, "allow")
+
+ assert not _is_held(await _call(session, server_a, "search", {"q": 2}))
+ assert _is_held(await _call(session, server_b, "search", {"q": 2}))
+ ran.assert_awaited_once()
+
+
+async def test_a_chat_judge_covers_an_irreversible_tool_too(gate, ran):
+ """Judging means the supervisor decides next time, irreversible or not."""
+ session = _session()
+ assert _is_held(await _call(session, _GITHUB, "merge_pull_request", {"n": 1}))
+ await _answer_with_rule(gate, "judge")
+
+ assert not _is_held(await _call(session, _GITHUB, "merge_pull_request", {"n": 2}))
+ gate.classify.assert_awaited_once()
+ ran.assert_awaited_once()
+
+
+async def test_an_irreversible_tool_asks_once_on_the_gate_row_only(gate, ran):
+ result = await _call(_session(), _GITHUB, "merge_pull_request", {"n": 7})
+ assert _is_held(result)
+ subject = gate.open_review.await_args.args[6]
+ assert subject.irreversible
+ gate.open_review.assert_awaited_once()
+
+ gate.find_review.return_value = SimpleNamespace(status=ReviewStatus.APPROVED)
+ approved = await _call(_session(), _GITHUB, "merge_pull_request", {"n": 7})
+ assert not _is_held(approved)
+ ran.assert_awaited_once()
+ gate.own_review.assert_not_awaited()
+
+
+async def test_an_approved_first_use_runs_without_a_second_card(gate, ran):
+ """The server-side review would ask again for an uncatalogued server."""
+ gate.find_review.return_value = SimpleNamespace(status=ReviewStatus.APPROVED)
+ result = await _call(_session(), _OPEN_WORLD, "do_thing")
+ assert not _is_held(result)
+ ran.assert_awaited_once()
+ gate.own_review.assert_not_awaited()
+
+
+async def test_unsupervised_runs_a_first_use_without_asking(gate, ran):
+ result = await _call(_session("unsupervised"), _OPEN_WORLD, "do_thing")
+ assert not _is_held(result)
+ ran.assert_awaited_once()
+
+
+async def test_listing_a_servers_tools_never_asks(gate, ran):
+ result = await RunCapabilityTool().execute(
+ "user-1", _session("ask_first"), "call-1", id=_OPEN_WORLD, input={}
+ )
+ assert not _is_held(result)
+ gate.open_review.assert_not_awaited()
+
+
+async def _answer_with_rule(gate, rule: chat_rules.ChatRule) -> None:
+ """What the approve endpoint does for the card the gate just opened."""
+ subject = gate.open_review.await_args.args[6]
+ row = SimpleNamespace(status=ReviewStatus.APPROVED)
+ await chat_rules.set_answer_rules(
+ "session-1", {"r": row}, {"r": rule}, {"r": subject.key}
+ )
+
+
+ "server, tool, pauses",
+ [
+ (_OPEN_WORLD, "get_things", False),
+ (_OPEN_WORLD, "delete_things", True),
+ # Catalogued servers run, mapped write or not.
+ (_GITHUB, "create_branch", False),
+ ],
+)
+async def test_flag_off_the_verb_heuristic_decides_as_before(ran, server, tool, pauses):
+ own_review = AsyncMock(return_value="copilot-mcp-x:1")
+ with (
+ patch(f"{_GATE}.is_feature_enabled", AsyncMock(return_value=False)),
+ patch(f"{_CAP}.open_mcp_review", own_review),
+ patch(f"{_GATE}.reads.screen_read", AsyncMock(return_value=None)),
+ ):
+ await _call(_session(), server, tool)
+ assert own_review.await_count == int(pauses)
+ assert ran.await_count == int(not pauses)
diff --git a/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py b/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py
index ad4f51b837..a1d11f4246 100644
--- a/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py
@@ -67,7 +67,7 @@ def gate():
patch(f"{_GATE}.review_store.open_review", store.open_review),
patch(f"{_GATE}.review_store.consume", store.consume),
patch(f"{_GATE}.held.remember", AsyncMock(return_value=True)),
- patch(f"{_GATE}.chat_rules.ask_reason", AsyncMock(return_value=None)),
+ patch(f"{_GATE}.chat_rules.rule_for", AsyncMock(return_value=None)),
patch(f"{_GATE}.chat_rules.set_ask", AsyncMock()),
patch(f"{_GATE}.reads.release_held_read", AsyncMock(return_value=None)),
patch(f"{_GATE}.reads.screen_read", AsyncMock(return_value=None)),
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_capability.py b/autogpt_platform/backend/backend/copilot/tools/run_capability.py
index b17d4d1890..61637eb405 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_capability.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_capability.py
@@ -23,7 +23,8 @@ from backend.copilot.capabilities.registry import configured_tool, get_registry
from backend.copilot.capabilities.resolve import resolve_entry
from backend.copilot.capabilities.sources import skill_name
from backend.copilot.capabilities.sources.mcp_catalog import setup_hint
-from backend.copilot.gate.subject import NO_OP, OWN_REVIEW, Subject, block_subject
+from backend.copilot.gate import gate_active
+from backend.copilot.gate.subject import NO_OP, Subject, block_subject, mcp_subject
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
@@ -96,7 +97,7 @@ class RunCapabilityTool(BaseTool):
async def gate_subject(
self, user_id: str, session: ChatSession, args: dict[str, Any]
) -> Subject | None:
- """The block this call runs, or NO_OP where nothing would run."""
+ """The block or MCP tool this call runs, or NO_OP where nothing would run."""
capability_id = str(args.get("id") or "")
payload = args.get("input")
if args.get("validate_only") or session.dry_run:
@@ -105,11 +106,11 @@ class RunCapabilityTool(BaseTool):
return NO_OP
entry = await resolve_session_entry(user_id, session, capability_id)
if entry is None and capability_id.strip().lower().startswith("https://"):
- return OWN_REVIEW
+ return _mcp_subject(capability_id.strip(), payload or {})
if entry is None:
return NO_OP
if entry.kind == "mcp_server":
- return OWN_REVIEW
+ return _mcp_subject(entry.implementations[0].ref, payload or {})
if entry.kind != "block":
return NO_OP
block_id = next(
@@ -223,6 +224,15 @@ async def _run_block(
)
+def _mcp_subject(server_url: str, payload: dict[str, Any]) -> Subject:
+ """Listing a server's tools runs none of them, and a catalogued server
+ that needs its URL answers with setup help."""
+ tool = str(payload.get("tool") or "").strip()
+ if not tool or not server_url:
+ return NO_OP
+ return mcp_subject(server_url, tool)
+
+
async def _describe_tool(
entry: CapabilityEntry, session: ChatSession
) -> ToolResponseBase:
@@ -294,10 +304,13 @@ async def _run_mcp(
session_id=session.session_id,
)
host = urlsplit(server_url).hostname or server_url
+ # With the gate on it has already decided this call on the server's
+ # effect map; the verb heuristic is the flag-off path only.
if (
tool_name
and not session.dry_run
and needs_review(tool_name, catalog_server=entry is not None)
+ and not await gate_active(user_id, session)
):
review = MCPReviewPayload(
server_url=server_url, tool=tool_name, arguments=dict(arguments or {})
diff --git a/autogpt_platform/backend/backend/integrations/mcp_catalog.py b/autogpt_platform/backend/backend/integrations/mcp_catalog.py
index aad462bb6b..75dfa7481f 100644
--- a/autogpt_platform/backend/backend/integrations/mcp_catalog.py
+++ b/autogpt_platform/backend/backend/integrations/mcp_catalog.py
@@ -165,3 +165,56 @@ def parse_mcp_catalog(content: str) -> tuple[MCPCatalogEntry, ...]:
if len({entry.name for entry in entries}) != len(entries):
raise ValueError("MCP catalog provider names must be unique")
return tuple(entries)
+
+
+MCPToolEffect = Literal["read", "external", "irreversible"]
+
+
+class MCPEffectMap(BaseModel):
+ """A catalogued server's tools by effect, written from its published list.
+
+ A tool the map does not name has no known effect, so it asks on first use.
+ """
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ source: str = Field(min_length=1)
+ read: list[str] = Field(default_factory=list)
+ external: list[str] = Field(default_factory=list)
+ # External writes that cannot be taken back.
+ irreversible: list[str] = Field(default_factory=list)
+
+ @model_validator(mode="after")
+ def validate_disjoint(self) -> "MCPEffectMap":
+ tools = [*self.read, *self.external, *self.irreversible]
+ if len(set(tools)) != len(tools):
+ raise ValueError("A tool appears in more than one effect list")
+ return self
+
+ def effect_of(self, tool: str) -> MCPToolEffect | None:
+ if tool in self.irreversible:
+ return "irreversible"
+ if tool in self.external:
+ return "external"
+ return "read" if tool in self.read else None
+
+
+def mcp_tool_effect(server_url: str, tool: str) -> MCPToolEffect | None:
+ """None: the server is not catalogued, or its map does not name the tool."""
+ entry = get_mcp_catalog_entry_for_url(server_url)
+ effects = get_mcp_effect_maps().get(entry.name) if entry else None
+ return effects.effect_of(tool) if effects else None
+
+
+@cache
+def get_mcp_effect_maps() -> dict[str, MCPEffectMap]:
+ content = Path(__file__).with_name("mcp_effects.json").read_text(encoding="utf-8")
+ return parse_mcp_effect_maps(content)
+
+
+def parse_mcp_effect_maps(content: str) -> dict[str, MCPEffectMap]:
+ maps = TypeAdapter(dict[str, MCPEffectMap]).validate_json(content)
+ unknown = set(maps) - {entry.name for entry in get_mcp_catalog()}
+ if unknown:
+ raise ValueError(f"Effect maps for servers not in the catalog: {unknown}")
+ return maps
diff --git a/autogpt_platform/backend/backend/integrations/mcp_catalog_test.py b/autogpt_platform/backend/backend/integrations/mcp_catalog_test.py
index 2938165df8..68ef4be0ad 100644
--- a/autogpt_platform/backend/backend/integrations/mcp_catalog_test.py
+++ b/autogpt_platform/backend/backend/integrations/mcp_catalog_test.py
@@ -9,7 +9,10 @@ from backend.integrations.mcp_catalog import (
MCPServerMetadata,
get_mcp_catalog,
get_mcp_catalog_entry_for_url,
+ get_mcp_effect_maps,
+ mcp_tool_effect,
parse_mcp_catalog,
+ parse_mcp_effect_maps,
)
@@ -191,3 +194,38 @@ def test_catalog_matches_only_complete_known_urls(url, matched):
result = get_mcp_catalog_entry_for_url(url)
assert result == (entry if matched else None)
+
+
+def test_effect_maps_load_for_catalogued_servers_only():
+ maps = get_mcp_effect_maps()
+ assert {"mcp_github", "mcp_stripe", "mcp_atlassian"} <= set(maps)
+ with pytest.raises(ValueError, match="not in the catalog"):
+ parse_mcp_effect_maps(json.dumps({"mcp_nowhere": {"source": "x"}}))
+
+
+def test_a_tool_cannot_carry_two_effects():
+ with pytest.raises(ValidationError, match="more than one"):
+ parse_mcp_effect_maps(
+ json.dumps(
+ {"mcp_github": {"source": "x", "read": ["t"], "irreversible": ["t"]}}
+ )
+ )
+
+
+ "url, tool, effect",
+ [
+ ("https://api.githubcopilot.com/mcp/readonly", "issue_read", "read"),
+ ("https://api.githubcopilot.com/mcp/readonly", "create_branch", "external"),
+ ("https://api.githubcopilot.com/mcp/readonly", "issue_write", "irreversible"),
+ (
+ "https://api.githubcopilot.com/mcp/readonly",
+ "merge_pull_request",
+ "irreversible",
+ ),
+ ("https://api.githubcopilot.com/mcp/readonly", "not_published", None),
+ ("https://mcp.example.com/mcp", "get_things", None),
+ ],
+)
+def test_a_tool_takes_its_effect_from_its_servers_map(url, tool, effect):
+ assert mcp_tool_effect(url, tool) == effect
diff --git a/autogpt_platform/backend/backend/integrations/mcp_effects.json b/autogpt_platform/backend/backend/integrations/mcp_effects.json
new file mode 100644
index 0000000000..b4c4d8fbe7
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/mcp_effects.json
@@ -0,0 +1,535 @@
+{
+ "mcp_github": {
+ "source": "https://github.com/github/github-mcp-server/blob/main/README.md",
+ "read": [
+ "actions_get",
+ "actions_list",
+ "custom_properties_read",
+ "get_code_quality_finding",
+ "get_code_scanning_alert",
+ "get_commit",
+ "get_copilot_space",
+ "get_dependabot_alert",
+ "get_discussion",
+ "get_discussion_comments",
+ "get_file_contents",
+ "get_gist",
+ "get_global_security_advisory",
+ "get_job_logs",
+ "get_label",
+ "get_latest_release",
+ "get_me",
+ "get_notification_details",
+ "get_release_by_tag",
+ "get_repository_tree",
+ "get_secret_scanning_alert",
+ "get_tag",
+ "get_team_members",
+ "get_teams",
+ "github_support_docs_search",
+ "issue_read",
+ "list_branches",
+ "list_code_scanning_alerts",
+ "list_commits",
+ "list_copilot_spaces",
+ "list_dependabot_alerts",
+ "list_discussion_categories",
+ "list_discussions",
+ "list_gists",
+ "list_global_security_advisories",
+ "list_issue_fields",
+ "list_issue_types",
+ "list_issues",
+ "list_label",
+ "list_notifications",
+ "list_org_repository_security_advisories",
+ "list_pull_requests",
+ "list_releases",
+ "list_repository_collaborators",
+ "list_repository_security_advisories",
+ "list_secret_scanning_alerts",
+ "list_starred_repositories",
+ "list_tags",
+ "projects_get",
+ "projects_list",
+ "pull_request_read",
+ "repository_ruleset_read",
+ "search_code",
+ "search_commits",
+ "search_issues",
+ "search_orgs",
+ "search_pull_requests",
+ "search_repositories",
+ "search_users"
+ ],
+ "external": [
+ "actions_run_trigger",
+ "add_comment_to_pending_review",
+ "add_reply_to_pull_request_comment",
+ "assign_copilot_to_issue",
+ "assign_copilot_to_issue_with_intent",
+ "create_branch",
+ "create_gist",
+ "create_or_update_file",
+ "create_pull_request",
+ "create_pull_request_with_copilot",
+ "create_repository",
+ "create_repository_ruleset",
+ "custom_properties_write",
+ "delete_file",
+ "discussion_comment_write",
+ "dismiss_notification",
+ "fork_repository",
+ "label_write",
+ "manage_notification_subscription",
+ "manage_repository_notification_subscription",
+ "mark_all_notifications_read",
+ "projects_write",
+ "push_files",
+ "request_copilot_review",
+ "star_repository",
+ "sub_issue_write",
+ "unstar_repository",
+ "update_gist",
+ "update_issue_comment",
+ "update_pull_request",
+ "update_pull_request_branch"
+ ],
+ "irreversible": [
+ "add_issue_comment",
+ "delete_repository",
+ "issue_write",
+ "merge_pull_request",
+ "pull_request_review_write"
+ ]
+ },
+ "mcp_linear": {
+ "source": "https://linear.app/docs/mcp"
+ },
+ "mcp_notion": {
+ "source": "https://developers.notion.com/docs/mcp-supported-tools",
+ "read": [
+ "notion-ai-search",
+ "notion-download-attachment",
+ "notion-download-skill",
+ "notion-fetch",
+ "notion-get-async-task",
+ "notion-get-comments",
+ "notion-get-session-status",
+ "notion-get-teams",
+ "notion-get-tool-access",
+ "notion-get-users",
+ "notion-list-agents",
+ "notion-list-session-events",
+ "notion-query-data-sources",
+ "notion-query-meeting-notes",
+ "notion-query-sessions",
+ "notion-read-session-event",
+ "notion-search",
+ "notion-search-agents",
+ "notion-search-sessions",
+ "notion-search-skills",
+ "notion-wait-session"
+ ],
+ "external": [
+ "notion-convert-page-to-skill",
+ "notion-create-attachment",
+ "notion-create-comment",
+ "notion-create-database",
+ "notion-create-file-upload",
+ "notion-create-folder",
+ "notion-create-pages",
+ "notion-create-view",
+ "notion-duplicate-page",
+ "notion-move-pages",
+ "notion-send-message-to-session",
+ "notion-spawn-session",
+ "notion-stop-session",
+ "notion-update-data-source",
+ "notion-update-page",
+ "notion-update-view"
+ ]
+ },
+ "mcp_stripe": {
+ "source": "https://docs.stripe.com/mcp",
+ "read": [
+ "get_balance_summary",
+ "get_stripe_account_info",
+ "search_stripe_documentation",
+ "stripe_analytics",
+ "stripe_api_details",
+ "stripe_api_read",
+ "stripe_api_search",
+ "stripe_implementation_planner"
+ ],
+ "external": [
+ "send_stripe_feedback"
+ ],
+ "irreversible": [
+ "stripe_api_write"
+ ]
+ },
+ "mcp_todoist": {
+ "source": "https://github.com/Doist/todoist-mcp/blob/main/src/utils/tool-names.ts",
+ "read": [
+ "export-project-template",
+ "fetch",
+ "fetch-object",
+ "find-activity",
+ "find-comments",
+ "find-completed-tasks",
+ "find-filters",
+ "find-labels",
+ "find-project-collaborators",
+ "find-projects",
+ "find-reminders",
+ "find-sections",
+ "find-tasks",
+ "find-tasks-by-date",
+ "get-overview",
+ "get-productivity-stats",
+ "get-project-activity-stats",
+ "get-project-health",
+ "get-workspace-insights",
+ "list-workspaces",
+ "search",
+ "user-info",
+ "view-attachment"
+ ],
+ "external": [
+ "add-comments",
+ "add-filters",
+ "add-labels",
+ "add-projects",
+ "add-reminders",
+ "add-sections",
+ "add-tasks",
+ "analyze-project-health",
+ "complete-tasks",
+ "import-project-template",
+ "manage-assignments",
+ "project-management",
+ "project-move",
+ "reorder-objects",
+ "reschedule-tasks",
+ "uncomplete-tasks",
+ "update-comments",
+ "update-filters",
+ "update-labels",
+ "update-projects",
+ "update-reminders",
+ "update-sections",
+ "update-tasks"
+ ],
+ "irreversible": [
+ "delete-object"
+ ]
+ },
+ "mcp_atlassian": {
+ "source": "https://developer.atlassian.com/cloud/rovo-mcp/guides/supported-tools/",
+ "read": [
+ "atlassianUserInfo",
+ "diffCodeSymbols",
+ "diffConfluenceContentVersions",
+ "discover",
+ "downloadConfluenceAttachment",
+ "downloadJiraIssueAttachment",
+ "executeRead",
+ "exportConfluenceContent",
+ "getAccessibleAtlassianResources",
+ "getBitbucketRepoBranch",
+ "getBitbucketRepoCommit",
+ "getBitbucketRepoCommitReport",
+ "getBitbucketRepoCommitReportAnnotations",
+ "getBitbucketRepoDefaultReviewers",
+ "getBitbucketRepoDeployment",
+ "getBitbucketRepoEnvironment",
+ "getBitbucketRepoFileContent",
+ "getBitbucketRepoPipeline",
+ "getBitbucketRepoPipelineStep",
+ "getBitbucketRepoPipelineStepLog",
+ "getBitbucketRepoPullRequest",
+ "getBitbucketRepoPullRequestDiff",
+ "getBitbucketRepository",
+ "getBitbucketWorkspace",
+ "getCodeFile",
+ "getCodeSymbol",
+ "getConfluenceAttachment",
+ "getConfluenceComment",
+ "getConfluenceContent",
+ "getConfluenceContentPermissions",
+ "getConfluenceContentRestrictionState",
+ "getConfluenceContentVersion",
+ "getConfluenceMauiApp",
+ "getConfluencePersonalSpace",
+ "getConfluencePublicLinkStatus",
+ "getConfluenceReactions",
+ "getConfluenceSpace",
+ "getConfluenceSpaceInstructions",
+ "getConfluenceTask",
+ "getConfluenceTemplate",
+ "getContentFormatGuide",
+ "getFocusArea",
+ "getFocusAreaTypes",
+ "getGoal",
+ "getGoalTypes",
+ "getGoalUpdate",
+ "getJiraBoardConfig",
+ "getJiraBoardIssueData",
+ "getJiraBoardSprintData",
+ "getJiraCurrentUser",
+ "getJiraEntityProperty",
+ "getJiraIssue",
+ "getJiraIssueTypeMetaWithFields",
+ "getJiraProjectVersionRelatedWork",
+ "getJiraProjectVersions",
+ "getJiraUser",
+ "getJsmOpsAlerts",
+ "getJsmOpsScheduleInfo",
+ "getJsmOpsTeamInfo",
+ "getLoomMeetingActionItems",
+ "getLoomVideo",
+ "getLoomVideoComments",
+ "getLoomVideoDownloadUrl",
+ "getProject",
+ "getProjectUpdate",
+ "getTalentFields",
+ "getTalentGroupMetrics",
+ "getTalentPosition",
+ "getTalentPositionsByEntity",
+ "getTalentUser",
+ "getTeam",
+ "getTeamworkGraphContext",
+ "getTeamworkGraphObject",
+ "listBitbucketRepoCommitReports",
+ "listBitbucketRepoDeployments",
+ "listBitbucketRepoEnvironments",
+ "listBitbucketRepoPipelineSteps",
+ "listBitbucketRepoPipelines",
+ "listBitbucketRepoPullRequestComments",
+ "listBitbucketRepoPullRequestTasks",
+ "listBitbucketRepoPullRequests",
+ "listBitbucketRepositories",
+ "listBitbucketWorkspaces",
+ "listCodeDirectory",
+ "listConfluenceAttachments",
+ "listConfluenceComments",
+ "listConfluenceContent",
+ "listConfluenceContentVersions",
+ "listConfluenceSpaces",
+ "listConfluenceTasks",
+ "listConfluenceTemplates",
+ "listJiraBoardSprints",
+ "listJiraBoards",
+ "listJiraDashboards",
+ "listJiraFilters",
+ "listJiraIssueAssignableUsers",
+ "listJiraIssueChangelogs",
+ "listJiraIssueComments",
+ "listJiraIssueLinkTypes",
+ "listJiraIssueRemoteIssueLinks",
+ "listJiraIssueTransitions",
+ "listJiraIssueWorklogs",
+ "listJiraProjectComponents",
+ "listJiraProjectIssueTypesMetadata",
+ "listJiraProjects",
+ "listJiraStatuses",
+ "listLoomFolders",
+ "listLoomVideos",
+ "listLoomVideosSharedWithMe",
+ "lookupJiraAccountId",
+ "resolveConfluenceContentMacros",
+ "scanCodeRepo",
+ "search",
+ "searchCode",
+ "searchConfluence",
+ "searchFocusAreas",
+ "searchGoals",
+ "searchJiraIssuesUsingJql",
+ "searchProjects",
+ "searchTalentPositions",
+ "searchTeams"
+ ],
+ "external": [
+ "addBitbucketRepoPullRequestComment",
+ "addConfluenceReaction",
+ "addConnectionsToGoals",
+ "addConnectionsToProjects",
+ "addLabelsToConfluenceContent",
+ "addOrEditJiraIssueComment",
+ "addOrEditJiraIssueWorklog",
+ "addTeamworkGraphContext",
+ "approveBitbucketRepoPullRequest",
+ "archiveConfluenceContent",
+ "completeConfluenceTask",
+ "convertConfluenceContentMode",
+ "copyConfluenceContent",
+ "createBitbucketRepoBranch",
+ "createBitbucketRepoCommit",
+ "createBitbucketRepoPullRequest",
+ "createBitbucketRepoPullRequestTask",
+ "createConfluenceAttachment",
+ "createConfluenceComment",
+ "createConfluenceContent",
+ "createConfluenceInfographicForPage",
+ "createConfluenceMauiApp",
+ "createConfluenceSpace",
+ "createFocusArea",
+ "createFocusAreaStatusUpdate",
+ "createGoal",
+ "createGoalUpdate",
+ "createJiraBoard",
+ "createJiraIssue",
+ "createJiraIssueLink",
+ "createJiraProject",
+ "createLoomFolder",
+ "createLoomVideoComment",
+ "createLoomVideoReaction",
+ "createLoomVideoUpload",
+ "createProject",
+ "createProjectUpdate",
+ "createTalentSkill",
+ "createTeam",
+ "disableConfluencePublicLink",
+ "editConfluenceInfographicForPage",
+ "editConfluenceMauiApp",
+ "editJiraEntityProperty",
+ "editJiraIssue",
+ "enableConfluencePublicLink",
+ "executeWrite",
+ "linkToFocusArea",
+ "manageJiraProjectVersion",
+ "manageJiraProjectVersionRelatedWork",
+ "manageJiraSprint",
+ "moveConfluenceContent",
+ "moveLoomVideoToFolder",
+ "recoverLoomVideo",
+ "removeConfluenceContentPermissions",
+ "reopenBitbucketRepoPullRequestComment",
+ "reopenConfluenceTask",
+ "requestChangesOnBitbucketRepoPullRequest",
+ "resolveBitbucketRepoPullRequestComment",
+ "restoreConfluenceContentVersion",
+ "runBitbucketRepoPipeline",
+ "setBitbucketRepoPullRequestTaskState",
+ "setConfluenceContentRestrictionState",
+ "setConfluenceContentStatus",
+ "setConfluenceSpaceInstructions",
+ "starConfluenceContent",
+ "starConfluenceSpace",
+ "transitionJiraIssue",
+ "unarchiveConfluenceContent",
+ "unstarConfluenceContent",
+ "unstarConfluenceSpace",
+ "unwatchConfluenceContent",
+ "unwatchConfluenceLabel",
+ "unwatchConfluenceSpace",
+ "updateBitbucketRepoPullRequest",
+ "updateConfluenceComment",
+ "updateConfluenceCommentResolution",
+ "updateConfluenceContent",
+ "updateFocusArea",
+ "updateJiraProject",
+ "updateLoomVideoPermissions",
+ "updateLoomVideoTitle",
+ "updateTalentPositionFocusAreaMappings",
+ "updateTalentWorkerSkillMappings",
+ "updateTeam",
+ "uploadAttachmentToJiraIssue",
+ "watchConfluenceContent",
+ "watchConfluenceLabel",
+ "watchConfluenceSpace",
+ "watchJiraIssue"
+ ],
+ "irreversible": [
+ "addConfluenceContentPermissions",
+ "deleteJiraComment",
+ "deleteJiraIssue",
+ "deleteJiraIssueAttachment",
+ "executeDestructive",
+ "mergeBitbucketRepoPullRequest",
+ "publishLoomVideo",
+ "replaceConfluenceContentPermissions",
+ "shareLoomVideo",
+ "updateJsmOpsAlert"
+ ]
+ },
+ "mcp_sentry": {
+ "source": "https://github.com/getsentry/sentry-mcp/blob/main/packages/mcp-core/src/toolDefinitions.json",
+ "read": [
+ "find_alert_rules",
+ "find_dashboards",
+ "find_dsns",
+ "find_monitors",
+ "find_organizations",
+ "find_projects",
+ "find_releases",
+ "find_teams",
+ "find_uptime_monitors",
+ "get_agent_conversation_details",
+ "get_ai_conversation_details",
+ "get_alert_rule",
+ "get_dashboard_details",
+ "get_doc",
+ "get_event_attachment",
+ "get_event_stacktrace",
+ "get_issue_activity",
+ "get_issue_breadcrumbs",
+ "get_issue_details",
+ "get_issue_tag_values",
+ "get_issue_user_reports",
+ "get_latest_base_snapshot",
+ "get_monitor_details",
+ "get_profile",
+ "get_profile_details",
+ "get_release_details",
+ "get_replay_details",
+ "get_sentry_mcp_info",
+ "get_sentry_resource",
+ "get_snapshot",
+ "get_snapshot_image",
+ "get_span_details",
+ "get_trace_details",
+ "get_uptime_monitor_details",
+ "search_agent_conversations",
+ "search_ai_conversations",
+ "search_docs",
+ "search_events",
+ "search_issue_events",
+ "search_issues",
+ "search_sentry_tools",
+ "whoami"
+ ],
+ "external": [
+ "add_issue_note",
+ "add_team_to_project",
+ "analyze_issue_with_seer",
+ "create_dsn",
+ "create_project",
+ "create_team",
+ "create_uptime_monitor",
+ "execute_sentry_tool",
+ "onboarding_status_update",
+ "remove_team_from_project",
+ "update_dsn",
+ "update_issue",
+ "update_project",
+ "update_uptime_monitor"
+ ],
+ "irreversible": [
+ "delete_uptime_monitor"
+ ]
+ },
+ "mcp_airtable": {
+ "source": "https://support.airtable.com/docs/using-the-airtable-mcp-server",
+ "read": [
+ "get_record_for_page",
+ "list_pages_for_base",
+ "list_records_for_page",
+ "list_workspaces"
+ ],
+ "external": [
+ "create_base"
+ ]
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx
index 3939314187..42c212f12d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx
@@ -16,6 +16,7 @@ import {
heldRead,
heldReview,
mail,
+ mcpTool,
realCardSchemaHandler,
realCards,
shell,
@@ -94,6 +95,9 @@ export const BlockCard: Story = {
export const WorkflowRun: Story = { args: queueOf([workflow()]) };
+// The Approve menu: the chat rules the server allows on this subject.
+export const RuleMenu: Story = { args: queueOf([mcpTool()]) };
+
export const BlockChainRow: StoryObj = {
render: () => {
const part = {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/chatRule.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/chatRule.test.tsx
new file mode 100644
index 0000000000..8a93f81830
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/chatRule.test.tsx
@@ -0,0 +1,73 @@
+import userEvent from "@testing-library/user-event";
+import { http, HttpResponse } from "msw";
+import { expect, test, vi } from "vitest";
+import { server } from "@/mocks/mock-server";
+import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";
+import { CopilotPendingReviews } from "../../CopilotPendingReviews/CopilotPendingReviews";
+import { mail, mcpTool, CHAT_SESSION } from "./fixtures";
+
+function serve(
+ review: ReturnType<typeof mail> = mail("m1", ["allow", "judge"]),
+) {
+ const sent: { reviews: Record<string, unknown>[] }[] = [];
+ server.use(
+ http.get(`*/api/review/session/${CHAT_SESSION}`, () =>
+ HttpResponse.json([review]),
+ ),
+ http.post("*/api/review/action", async ({ request }) => {
+ sent.push(
+ (await request.json()) as { reviews: Record<string, unknown>[] },
+ );
+ return HttpResponse.json({
+ approved_count: 1,
+ rejected_count: 0,
+ failed_count: 0,
+ });
+ }),
+ );
+ return sent;
+}
+
+function renderQueue() {
+ render(
+ <CopilotChatActionsProvider onSend={vi.fn()} onBackendTurn={vi.fn()}>
+ <CopilotPendingReviews chatSessionId={CHAT_SESSION} />
+ </CopilotChatActionsProvider>,
+ );
+}
+
+test.each([
+ ["Approve for this chat", "allow", "a block", mail("m1")],
+ ["Let Otto judge from now on", "judge", "a block", mail("m1")],
+ ["Approve for this chat", "allow", "an MCP tool", mcpTool("m1")],
+ ["Let Otto judge from now on", "judge", "an MCP tool", mcpTool("m1")],
+])(
+ "choosing %s approves the call and sets the %s rule on %s",
+ async (item, rule, _subject, review) => {
+ const sent = serve(review);
+ renderQueue();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "More ways to approve" }),
+ );
+ await userEvent.click(await screen.findByText(item));
+
+ await waitFor(() => expect(sent).toHaveLength(1));
+ expect(sent[0].reviews).toEqual([
+ expect.objectContaining({ approved: true, chat_rule: rule }),
+ ]);
+ },
+);
+
+test("a plain approve sets no rule", async () => {
+ const sent = serve();
+ renderQueue();
+
+ await userEvent.click(await screen.findByRole("button", { name: "Approve" }));
+
+ await waitFor(() => expect(sent).toHaveLength(1));
+ expect(sent[0].reviews).toEqual([
+ expect.objectContaining({ approved: true, chat_rule: null }),
+ ]);
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/fixtures.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/fixtures.ts
index 2884808517..16ca453965 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/fixtures.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/fixtures.ts
@@ -184,6 +184,29 @@ export function heldRead(id: string, url: string) {
return { ...review, node_id: node, node_exec_id: `${node}:${id}` };
}
+// An MCP tool on a server the effect map names.
+export function mcpTool(id = "mcp") {
+ const name = "create_issue on mcp.linear.app";
+ return heldReview({
+ id,
+ tool: "run_capability",
+ mode: "auto",
+ reason: `Runs ${name}, which reaches outside the platform.`,
+ reasonKind: "subject",
+ subject: {
+ kind: "mcp",
+ key: "mcp:mcp.linear.app/mcp::create_issue",
+ name,
+ effect: "external",
+ irreversible: false,
+ block_id: null,
+ },
+ chatRules: ["allow", "judge"],
+ args: { title: "Q3 invoices missing PO numbers", team: "Finance" },
+ headline: { ask: "Run", object: name },
+ });
+}
+
export interface RealCard {
story: string;
review: PendingHumanReviewModel;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/realCards.json b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/realCards.json
index dc2a1aff60..87e3f151f2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/realCards.json
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/realCards.json
@@ -49,7 +49,7 @@
},
"reason": "Runs Gmail Send, which reaches outside the platform.",
"reason_kind": "subject",
- "chat_rules_allowed": [],
+ "chat_rules_allowed": ["allow", "judge"],
"headline": {
"ask": "Run",
"object": "Gmail Send",
@@ -231,7 +231,7 @@
},
"reason": "Otto does not know what Google Sheets Update Row does, so he asks.",
"reason_kind": "subject",
- "chat_rules_allowed": [],
+ "chat_rules_allowed": ["allow", "judge"],
"headline": {
"ask": "Run",
"object": "Google Sheets Update Row",
@@ -447,7 +447,7 @@
},
"reason": "it reads a local file of invoices and prints what it finds.",
"reason_kind": "supervisor",
- "chat_rules_allowed": [],
+ "chat_rules_allowed": ["allow", "judge"],
"headline": {
"ask": "Run",
"object": "Execute Code Step",
@@ -592,7 +592,7 @@
},
"reason": "Runs Send Web Request, which reaches outside the platform.",
"reason_kind": "subject",
- "chat_rules_allowed": [],
+ "chat_rules_allowed": ["allow", "judge"],
"headline": {
"ask": "Run",
"object": "Send Web Request",
@@ -731,7 +731,7 @@
},
"reason": "Runs Post To X, which reaches outside the platform.",
"reason_kind": "subject",
- "chat_rules_allowed": [],
+ "chat_rules_allowed": ["allow", "judge"],
"headline": {
"ask": "Run",
"object": "Post To X",
@@ -1070,7 +1070,7 @@
},
"reason": "Runs Morning digest; its step Gmail Send reaches outside the platform.",
"reason_kind": "subject",
- "chat_rules_allowed": [],
+ "chat_rules_allowed": ["allow", "judge"],
"headline": {
"ask": "Run",
"object": "Morning digest",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts
index e00f59bc3b..5343d45e8a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts
@@ -61,9 +61,7 @@ export function useApprovalQueue({ items, onAnswered }: Args) {
batch.map((item) => ({
node_exec_id: item.reviewId,
approved,
- // The chat-scoped rule rides the approval; the gate reads it once it records rules.
- auto_approve_future: approved && !!rule,
- message: rule,
+ chat_rule: approved ? (rule ?? null) : null,
})),
batch.map((item) => item.scope),
);
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 2084d774cd..d12809e6a6 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -28645,6 +28645,14 @@
"title": "Auto Approve Future",
"description": "If true and this review is approved, future executions of this same block (node) will be automatically approved. This only affects approved reviews.",
"default": false
+ },
+ "chat_rule": {
+ "anyOf": [
+ { "type": "string", "enum": ["allow", "judge"] },
+ { "type": "null" }
+ ],
+ "title": "Chat Rule",
+ "description": "AutoPilot cards naming a subject only: once approved, the subject runs ('allow') or goes to the supervisor ('judge') for the rest of the chat instead of asking."
}
},
"type": "object",