Skip to content

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

fix(backend/copilot): deny every tool outside the session's allowed set, and fail CI on an unclassified CLI built-in (#15123)

Reinier van der Leerb3f661d23b22
diff --git a/autogpt_platform/backend/backend/blocks/orchestrator.py b/autogpt_platform/backend/backend/blocks/orchestrator.py
index ebfacb22c8..e9195148ad 100644
--- a/autogpt_platform/backend/backend/blocks/orchestrator.py
+++ b/autogpt_platform/backend/backend/blocks/orchestrator.py
@@ -420,7 +420,7 @@ def sdk_disallowed_tools() -> list[str]:
# which every block load should not have to pay for.
from backend.copilot.sdk.tool_adapter import get_sdk_builtin_tools
- return [*get_sdk_builtin_tools(), "NotebookEdit"]
+ return get_sdk_builtin_tools()
class OrchestratorBlock(Block):
diff --git a/autogpt_platform/backend/backend/copilot/context_test.py b/autogpt_platform/backend/backend/copilot/context_test.py
index 9011156640..fbf82c113d 100644
--- a/autogpt_platform/backend/backend/copilot/context_test.py
+++ b/autogpt_platform/backend/backend/copilot/context_test.py
@@ -17,6 +17,7 @@ from backend.copilot.context import (
get_execution_context,
get_sdk_cwd,
is_allowed_local_path,
+ is_sdk_tool_path,
is_unattended_turn,
resolve_sandbox_path,
set_execution_context,
@@ -97,6 +98,23 @@ def test_get_sdk_cwd_returns_set_value():
# ---------------------------------------------------------------------------
+ "relative,expected",
+ [
+ ("test-encoded-dir/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-results/o", True),
+ ("test-encoded-dir/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-outputs/o", True),
+ ("other-session/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-results/o", False),
+ ("test-encoded-dir/settings.json", False),
+ ],
+)
+def test_is_sdk_tool_path_only_allows_current_session_results(relative, expected):
+ token = _current_project_dir.set("test-encoded-dir")
+ try:
+ assert is_sdk_tool_path(os.path.join(SDK_PROJECTS_DIR, relative)) is expected
+ finally:
+ _current_project_dir.reset(token)
+
+
def test_is_allowed_local_path_empty():
assert not is_allowed_local_path("")
diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.py
index a602599ded..7be0923ffa 100644
--- a/autogpt_platform/backend/backend/copilot/prompting.py
+++ b/autogpt_platform/backend/backend/copilot/prompting.py
@@ -607,7 +607,8 @@ Important files (code, configs, outputs) should be saved to workspace to ensure
### SDK tool-result files
When tool outputs are large, the SDK truncates them and saves the full output to
a local file under `~/.claude/projects/.../tool-results/` (or `tool-outputs/`).
-To read these files, use `Read` — it reads from the host filesystem.
+To read these files, use `read_tool_result` with the full path as `file_path`.
+It reads the session's SDK result files from the host filesystem.
### Large tool outputs saved to workspace
When a tool output contains `<tool-output-truncated workspace_path="...">`, the
diff --git a/autogpt_platform/backend/backend/copilot/prompting_test.py b/autogpt_platform/backend/backend/copilot/prompting_test.py
index e7be99f708..4c4ffdfa58 100644
--- a/autogpt_platform/backend/backend/copilot/prompting_test.py
+++ b/autogpt_platform/backend/backend/copilot/prompting_test.py
@@ -34,6 +34,15 @@ class TestGetSdkSupplementStaticPlaceholder:
result = prompting.get_sdk_supplement(use_e2b=True)
assert "<session-id>" not in result
+ @pytest.mark.parametrize("use_e2b", [False, True])
+ def test_sdk_results_use_the_mcp_read_handler(self, use_e2b):
+ result = prompting.get_sdk_supplement(use_e2b=use_e2b)
+ guidance = result.split("### SDK tool-result files\n", 1)[1].split("\n### ", 1)[
+ 0
+ ]
+ assert "`read_tool_result`" in guidance
+ assert "`Read`" not in guidance
+
class TestComputerNote:
"""A plain chat on E2B is told it has a screen; an expert session is told
diff --git a/autogpt_platform/backend/backend/copilot/sdk/cli_builtin_tools_test.py b/autogpt_platform/backend/backend/copilot/sdk/cli_builtin_tools_test.py
new file mode 100644
index 0000000000..b3aaa6f65b
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/sdk/cli_builtin_tools_test.py
@@ -0,0 +1,72 @@
+"""A claude-agent-sdk bump that ships a new CLI built-in fails here until it is classified."""
+
+import asyncio
+import os
+from pathlib import Path
+
+import pytest
+from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, SystemMessage
+
+from .env import build_sdk_env
+from .tool_adapter import (
+ create_copilot_mcp_server,
+ get_copilot_tool_names,
+ get_sdk_disallowed_tools,
+)
+
+
[email protected]("use_e2b", [False, True])
+async def test_cli_offers_only_allowed_tools(
+ use_e2b: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ # A run inside Claude Code inherits its CLAUDE_* flags, which change the tool set.
+ for key in [k for k in os.environ if k.startswith("CLAUDE")]:
+ monkeypatch.delenv(key)
+ allowed = get_copilot_tool_names(use_e2b=use_e2b)
+ offered = await asyncio.wait_for(
+ _cli_offered_tools(
+ allowed,
+ get_sdk_disallowed_tools(use_e2b=use_e2b),
+ tmp_path,
+ use_e2b=use_e2b,
+ ),
+ timeout=60,
+ )
+ assert {"Task", "TodoWrite", "mcp__copilot__bash_exec"} <= set(offered), offered
+ unclassified = sorted(set(offered) - set(allowed))
+ assert not unclassified, (
+ f"The bundled Claude CLI offers {unclassified}, which security_hooks "
+ "denies and nothing classifies. Add each to SDK_DISALLOWED_TOOLS in "
+ "sdk/tool_adapter.py, or to _SDK_BUILTIN_ALWAYS if the copilot should use it."
+ )
+
+
+async def _cli_offered_tools(
+ allowed: list[str], disallowed: list[str], tmp_path: Path, *, use_e2b: bool
+) -> list[str]:
+ """The tool list in the CLI's ``init`` message, which precedes any API call."""
+ sdk_cwd = tmp_path / "copilot-session"
+ sdk_cwd.mkdir()
+ # A closed loopback port: the CLI only ever retries, so no network or key is needed.
+ env = build_sdk_env(
+ sdk_cwd=str(sdk_cwd),
+ codex_gateway_url="http://127.0.0.1:9",
+ codex_gateway_token="unused",
+ )
+ env["HOME"] = str(tmp_path)
+ options = ClaudeAgentOptions(
+ setting_sources=[],
+ extra_args={"strict-mcp-config": None},
+ allowed_tools=allowed,
+ disallowed_tools=disallowed,
+ mcp_servers={"copilot": create_copilot_mcp_server(use_e2b=use_e2b)},
+ cwd=str(sdk_cwd),
+ env=env,
+ )
+ async with ClaudeSDKClient(options) as client:
+ await client.query("hi")
+ async for message in client.receive_messages():
+ if isinstance(message, SystemMessage) and message.subtype == "init":
+ return message.data["tools"]
+ raise AssertionError("The CLI ended without an init message")
diff --git a/autogpt_platform/backend/backend/copilot/sdk/env.py b/autogpt_platform/backend/backend/copilot/sdk/env.py
index bed12de8aa..2e37d14b62 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/env.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/env.py
@@ -181,6 +181,9 @@ def build_sdk_env(
# CLI has been closed, killing the sub-agent and losing its work. This
# also stops the CLI from moving long tool calls to the background.
env["CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"] = "1"
+ # Keep TodoWrite, the checklist the UI renders; the CLI otherwise swaps in
+ # its TaskCreate/TaskUpdate tools.
+ env["CLAUDE_CODE_ENABLE_TASKS"] = "0"
# Strip Anthropic-specific beta headers that OpenRouter rejects.
# NOTE: this disables ALL experimental betas including
# context-management-2025-06-27. This is intentional: OpenRouter
diff --git a/autogpt_platform/backend/backend/copilot/sdk/governor_test.py b/autogpt_platform/backend/backend/copilot/sdk/governor_test.py
index 96ab4b3529..f33eed8b85 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/governor_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/governor_test.py
@@ -10,10 +10,12 @@ from backend.copilot.turn_pause import TurnPause
from .governor import STEP_BACKSTOP_MARGIN, TurnGovernor
from .security_hooks import create_security_hooks
+from .transient_retry_test import _SVC, _reply, _Turn
from .usage_meter import UsageMeter, cli_price_ratio
RESETS = datetime(2026, 10, 15, tzinfo=UTC)
KIMI = "moonshotai/kimi-k2.6"
+ALLOWED = {"mcp__copilot__run_block", "Agent"}
class _Meter(UsageMeter):
@@ -212,7 +214,9 @@ def _deny_reason(result: dict) -> str | None:
@pytest.mark.asyncio
async def test_pre_tool_hook_refuses_every_tool_once_landing():
governor = _governor(meter=_Meter(spent=1.0))
- hooks = create_security_hooks(user_id="u1", sdk_cwd="/tmp/w", governor=governor)
+ hooks = create_security_hooks(
+ user_id="u1", sdk_cwd="/tmp/w", governor=governor, allowed_tools=ALLOWED
+ )
pre = hooks["PreToolUse"][0].hooks[0]
for tool in ("mcp__copilot__run_block", "Agent", "WebSearch"):
result = await pre(
@@ -227,7 +231,9 @@ async def test_pre_tool_hook_refuses_every_tool_once_landing():
@pytest.mark.asyncio
async def test_pre_tool_hook_lets_tools_run_below_the_limits():
governor = _governor(meter=_Meter(spent=0.1, last=0.01))
- hooks = create_security_hooks(user_id="u1", sdk_cwd="/tmp/w", governor=governor)
+ hooks = create_security_hooks(
+ user_id="u1", sdk_cwd="/tmp/w", governor=governor, allowed_tools=ALLOWED
+ )
pre = hooks["PreToolUse"][0].hooks[0]
result = await pre(
{"tool_name": "mcp__copilot__run_block", "tool_input": {}},
@@ -235,6 +241,28 @@ async def test_pre_tool_hook_lets_tools_run_below_the_limits():
context={},
)
assert _deny_reason(dict(result)) is None
+ unlisted = await pre(
+ {"tool_name": "TaskCreate", "tool_input": {}}, tool_use_id="tu-2", context={}
+ )
+ assert "not available in this session" in (_deny_reason(dict(unlisted)) or "")
+
+
+async def test_the_turns_hook_carries_its_governor_and_allowed_tools(
+ tmp_path, monkeypatch
+):
+ # Every other turn-level test mocks create_security_hooks, so a call site
+ # that drops either argument stays green there.
+ turn = _Turn(tmp_path, monkeypatch)
+ await turn.run([_reply("gen-ok")])
+
+ kwargs = turn._mocks[f"{_SVC}.create_security_hooks"].call_args.kwargs
+ assert isinstance(kwargs["governor"], TurnGovernor)
+ assert kwargs["allowed_tools"] == turn._mocks[f"{_SVC}.get_copilot_tool_names"]()
+ assert (
+ kwargs["builtin_tool_spans"]
+ == turn._mocks[f"{_SVC}.config"].posthog_builtin_tool_spans
+ )
def test_a_trial_limited_by_the_task_cap_gets_no_headroom():
diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
index d5409f6268..7574b41fd2 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
@@ -7,17 +7,13 @@ ensuring multi-user isolation and preventing unauthorized operations.
import json
import logging
import re
-from collections.abc import Callable
+from collections.abc import Callable, Collection, Iterable
from typing import Any, cast
from claude_agent_sdk.types import HookEvent, HookMatcher
from backend.copilot.ai_spans import ToolSpanTimer
-from backend.copilot.context import (
- get_execution_context,
- is_allowed_local_path,
- is_sdk_tool_path,
-)
+from backend.copilot.context import get_execution_context, is_allowed_local_path
from backend.copilot.pending_messages import drain_and_format_for_injection
from .governor import TurnGovernor
@@ -94,34 +90,12 @@ def _landing_refusal(governor: TurnGovernor | None) -> str | None:
def _validate_workspace_path(
tool_name: str, tool_input: dict[str, Any], sdk_cwd: str | None
) -> dict[str, Any]:
- """Validate that a workspace-scoped tool only accesses allowed paths.
-
- For ``Read``: only SDK artifact paths (tool-results/, tool-outputs/) are
- permitted. The workspace directory is served by the ``read_file`` MCP
- tool which enforces per-session isolation.
-
- For ``Glob`` / ``Grep``: the full workspace (sdk_cwd) is allowed in
- addition to SDK artifact paths.
- """
+ """Restrict Glob/Grep to the workspace and session's SDK artifact paths."""
path = tool_input.get("file_path") or tool_input.get("path") or ""
if not path:
# Glob/Grep without a path default to cwd which is already sandboxed
return {}
- if tool_name == "Read":
- # Narrow carve-out: only allow SDK artifact paths for the native Read tool.
- # ``is_sdk_tool_path`` validates session membership via _current_project_dir,
- # preventing cross-session access to another session's tool-results directory.
- # All other file reads must go through the read_file MCP tool.
- if is_sdk_tool_path(path):
- return {}
- logger.warning(f"Blocked Read outside SDK artifact paths: {path}")
- return _deny(
- "[SECURITY] The SDK 'Read' tool can only access tool-results/ or "
- "tool-outputs/ paths. Use the 'read_file' MCP tool to read workspace files. "
- "This is enforced by the platform and cannot be bypassed."
- )
-
if is_allowed_local_path(path, sdk_cwd):
return {}
@@ -135,20 +109,20 @@ def _validate_workspace_path(
def _validate_tool_access(
- tool_name: str, tool_input: dict[str, Any], sdk_cwd: str | None = None
+ tool_name: str,
+ tool_input: dict[str, Any],
+ sdk_cwd: str | None = None,
+ allowed_tools: Collection[str] = frozenset(),
) -> dict[str, Any]:
"""Validate that a tool call is allowed.
+ A tool outside *allowed_tools* is denied: ``allowed_tools`` on
+ ``ClaudeAgentOptions`` only pre-approves, so a CLI built-in that needs no
+ permission runs unless this hook refuses it.
+
Returns:
Empty dict to allow, or dict with hookSpecificOutput to deny
"""
- # Workspace-scoped tools: allowed only within the SDK workspace directory.
- # Check this BEFORE the blocked-tools list because Read is blocked in
- # general but must remain accessible for tool-results/tool-outputs paths
- # that the SDK uses internally for oversized result handling.
- if tool_name in WORKSPACE_SCOPED_TOOLS:
- return _validate_workspace_path(tool_name, tool_input, sdk_cwd)
-
# Block forbidden tools
if tool_name in BLOCKED_TOOLS:
logger.warning(f"Blocked tool access attempt: {tool_name}")
@@ -158,6 +132,12 @@ def _validate_tool_access(
"Use the CoPilot-specific MCP tools instead."
)
+ if tool_name not in allowed_tools:
+ return _deny_unlisted(tool_name)
+
+ if tool_name in WORKSPACE_SCOPED_TOOLS:
+ return _validate_workspace_path(tool_name, tool_input, sdk_cwd)
+
# Check for dangerous patterns in tool input
# Use json.dumps for predictable format (str() produces Python repr)
input_str = json.dumps(tool_input) if tool_input else ""
@@ -175,6 +155,14 @@ def _validate_tool_access(
return {}
+def _deny_unlisted(tool_name: str) -> dict[str, Any]:
+ logger.warning(f"Blocked tool outside the session's allowed set: {tool_name}")
+ return _deny(
+ f"[SECURITY] Tool '{tool_name}' is not available in this session. "
+ "This is enforced by the platform and cannot be bypassed."
+ )
+
+
def _validate_user_isolation(
tool_name: str, tool_input: dict[str, Any], user_id: str | None
) -> dict[str, Any]:
@@ -214,6 +202,8 @@ def create_security_hooks(
tool_display_bridge: SDKToolDisplayBridge | None = None,
governor: TurnGovernor | None = None,
builtin_tool_spans: bool = True,
+ *,
+ allowed_tools: Iterable[str],
) -> dict[HookEvent, list[HookMatcher]]:
"""Create the security hooks configuration for Claude Agent SDK.
@@ -236,10 +226,13 @@ def create_security_hooks(
is refused with a reason that asks for a checkpoint.
builtin_tool_spans: Send a PostHog span for each call of the CLI's
built-in tools (``ChatConfig.posthog_builtin_tool_spans``).
+ allowed_tools: The ``allowed_tools`` passed to ``ClaudeAgentOptions``;
+ every other tool is denied.
Returns:
Hooks configuration dict for ClaudeAgentOptions
"""
+ allowed = frozenset(allowed_tools)
try:
from claude_agent_sdk import HookMatcher
from claude_agent_sdk.types import HookContext, HookInput, SyncHookJSONOutput
@@ -311,12 +304,16 @@ def create_security_hooks(
is_copilot_tool = tool_name.startswith(MCP_TOOL_PREFIX)
clean_name = tool_name.removeprefix(MCP_TOOL_PREFIX)
- # Only block non-CoPilot tools; our MCP-registered tools
- # (including Read for oversized results) are already sandboxed.
+ # Our MCP tools sandbox themselves, so they skip the path and
+ # pattern checks — but not the allowed set.
if not is_copilot_tool:
- result = _validate_tool_access(clean_name, tool_input, sdk_cwd)
+ result = _validate_tool_access(
+ clean_name, tool_input, sdk_cwd, allowed_tools=allowed
+ )
if result:
return cast(SyncHookJSONOutput, result)
+ elif tool_name not in allowed:
+ return cast(SyncHookJSONOutput, _deny_unlisted(tool_name))
# Validate user isolation
result = _validate_user_isolation(clean_name, tool_input, user_id)
diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_allowlist_test.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_allowlist_test.py
new file mode 100644
index 0000000000..37315a4b34
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_allowlist_test.py
@@ -0,0 +1,52 @@
+import pytest
+
+from .security_hooks import create_security_hooks
+from .tool_adapter import get_copilot_tool_names
+
+
[email protected]("use_e2b", [False, True])
[email protected]("tool_name", ["Glob", "Grep"])
[email protected]("tool_input", [{}, {"path": "/tmp/copilot-test/src"}])
+async def test_workspace_tool_removed_from_allowed_set_is_denied(
+ tool_name, tool_input, use_e2b
+):
+ allowed = [
+ name for name in get_copilot_tool_names(use_e2b=use_e2b) if name != tool_name
+ ]
+ pre = create_security_hooks(
+ "u1", sdk_cwd="/tmp/copilot-test", allowed_tools=allowed
+ )["PreToolUse"][0].hooks[0]
+ result = await pre(
+ {"tool_name": tool_name, "tool_input": tool_input}, tool_use_id=None, context={}
+ )
+ output = result.get("hookSpecificOutput", {})
+ assert output.get("permissionDecision") == "deny"
+ assert "not available in this session" in output.get("permissionDecisionReason", "")
+
+
+async def test_blocked_read_stays_denied_even_when_allowed():
+ pre = create_security_hooks("u1", allowed_tools={"Read"})["PreToolUse"][0].hooks[0]
+ result = await pre(
+ {"tool_name": "Read", "tool_input": {}}, tool_use_id=None, context={}
+ )
+ output = result.get("hookSpecificOutput", {})
+ assert output.get("permissionDecision") == "deny"
+ assert "blocked for security" in output.get("permissionDecisionReason", "")
+
+
[email protected]("tool_name", ["Glob", "Grep"])
+async def test_allowed_workspace_tool_cannot_escape_workspace(tool_name, tmp_path):
+ pre = create_security_hooks("u1", sdk_cwd=str(tmp_path), allowed_tools={tool_name})[
+ "PreToolUse"
+ ][0].hooks[0]
+ result = await pre(
+ {"tool_name": tool_name, "tool_input": {"path": str(tmp_path.parent)}},
+ tool_use_id=None,
+ context={},
+ )
+ output = result.get("hookSpecificOutput", {})
+ assert output.get("permissionDecision") == "deny"
+ assert "within the workspace" in output.get("permissionDecisionReason", "")
diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py
index c04b744545..f0641a9213 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py
@@ -10,15 +10,19 @@ import os
import pytest
-from backend.copilot.context import _current_project_dir
-
from .security_hooks import (
_validate_tool_access,
_validate_user_isolation,
create_security_hooks,
)
+from .tool_adapter import (
+ get_copilot_tool_names,
+ get_sdk_builtin_tools,
+ get_sdk_disallowed_tools,
+)
SDK_CWD = "/tmp/copilot-abc123"
+ALLOWED = get_copilot_tool_names()
def _sdk_available() -> bool:
@@ -48,9 +52,61 @@ def test_blocked_tools_denied():
assert _is_denied(result), f"{tool} should be blocked"
-def test_unknown_tool_allowed():
- result = _validate_tool_access("SomeCustomTool", {})
- assert result == {}
[email protected](not _sdk_available(), reason="claude_agent_sdk not installed")
+ "tool_name", ["ListAgents2", "mcp__copilot__not_registered", "mcp__other__tool"]
+)
+async def test_tool_outside_allowed_set_denied(tool_name):
+ pre = create_security_hooks("u1", sdk_cwd=SDK_CWD, allowed_tools=ALLOWED)[
+ "PreToolUse"
+ ][0].hooks[0]
+ result = await pre(
+ {"tool_name": tool_name, "tool_input": {}}, tool_use_id=None, context={}
+ )
+ assert "not available in this session" in _reason(result)
+
+
[email protected](not _sdk_available(), reason="claude_agent_sdk not installed")
[email protected]("use_e2b", [False, True])
+async def test_every_allowed_tool_passes_the_hook(use_e2b):
+ allowed = get_copilot_tool_names(use_e2b=use_e2b)
+ pre = create_security_hooks("u1", sdk_cwd=SDK_CWD, allowed_tools=allowed)[
+ "PreToolUse"
+ ][0].hooks[0]
+ usable = set(allowed) - set(get_sdk_disallowed_tools(use_e2b=use_e2b))
+ denied = [
+ name
+ for name in sorted(usable)
+ if _is_denied(
+ await pre(
+ {"tool_name": name, "tool_input": {}}, tool_use_id=None, context={}
+ )
+ )
+ ]
+ assert denied == []
+
+
[email protected](not _sdk_available(), reason="claude_agent_sdk not installed")
[email protected]("use_e2b", [False, True])
+async def test_every_unusable_builtin_is_denied(use_e2b):
+ allowed = get_copilot_tool_names(use_e2b=use_e2b)
+ pre = create_security_hooks("u1", sdk_cwd=SDK_CWD, allowed_tools=allowed)[
+ "PreToolUse"
+ ][0].hooks[0]
+ usable = set(allowed) - set(get_sdk_disallowed_tools(use_e2b=use_e2b))
+ passed = [
+ name
+ for name in sorted(set(get_sdk_builtin_tools()) - usable)
+ if not _is_denied(
+ await pre(
+ {"tool_name": name, "tool_input": {}}, tool_use_id=None, context={}
+ )
+ )
+ ]
+ assert passed == []
# -- Workspace-scoped tools --------------------------------------------------
@@ -89,12 +145,16 @@ def test_edit_builtin_blocked():
def test_glob_within_workspace_allowed():
- result = _validate_tool_access("Glob", {"path": f"{SDK_CWD}/src"}, sdk_cwd=SDK_CWD)
+ result = _validate_tool_access(
+ "Glob", {"path": f"{SDK_CWD}/src"}, sdk_cwd=SDK_CWD, allowed_tools=ALLOWED
+ )
assert result == {}
def test_grep_within_workspace_allowed():
- result = _validate_tool_access("Grep", {"path": f"{SDK_CWD}/src"}, sdk_cwd=SDK_CWD)
+ result = _validate_tool_access(
+ "Grep", {"path": f"{SDK_CWD}/src"}, sdk_cwd=SDK_CWD, allowed_tools=ALLOWED
+ )
assert result == {}
@@ -123,7 +183,7 @@ def test_traversal_attack_denied():
def test_no_path_allowed():
"""Glob/Grep without a path argument defaults to cwd — should pass."""
- result = _validate_tool_access("Glob", {}, sdk_cwd=SDK_CWD)
+ result = _validate_tool_access("Glob", {}, sdk_cwd=SDK_CWD, allowed_tools=ALLOWED)
assert result == {}
@@ -136,60 +196,22 @@ def test_read_no_cwd_denies_absolute():
# -- Tool-results directory --------------------------------------------------
-def test_read_tool_results_allowed():
- home = os.path.expanduser("~")
- path = f"{home}/.claude/projects/-tmp-copilot-abc123/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-results/12345.txt"
- # is_allowed_local_path requires the session's encoded cwd to be set
- token = _current_project_dir.set("-tmp-copilot-abc123")
- try:
- result = _validate_tool_access("Read", {"file_path": path}, sdk_cwd=SDK_CWD)
- assert result == {}
- finally:
- _current_project_dir.reset(token)
-
-
-def test_read_tool_outputs_allowed():
- """tool-outputs/ paths should be allowed, same as tool-results/."""
- home = os.path.expanduser("~")
- path = f"{home}/.claude/projects/-tmp-copilot-abc123/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-outputs/12345.txt"
- token = _current_project_dir.set("-tmp-copilot-abc123")
- try:
- result = _validate_tool_access("Read", {"file_path": path}, sdk_cwd=SDK_CWD)
- assert result == {}
- finally:
- _current_project_dir.reset(token)
-
-
-def test_read_claude_projects_settings_json_denied():
- """SDK-internal artifacts like settings.json are NOT accessible — only tool-results/tool-outputs is."""
- home = os.path.expanduser("~")
- path = f"{home}/.claude/projects/-tmp-copilot-abc123/settings.json"
- token = _current_project_dir.set("-tmp-copilot-abc123")
- try:
- result = _validate_tool_access("Read", {"file_path": path}, sdk_cwd=SDK_CWD)
- assert _is_denied(result)
- finally:
- _current_project_dir.reset(token)
-
-
-def test_read_cross_session_tool_results_denied():
- """Cross-session reads are blocked: session A cannot read session B's tool-results."""
- home = os.path.expanduser("~")
- # session A: encoded cwd is "-tmp-copilot-abc123"
- # session B: encoded cwd is "-tmp-copilot-other999"
- other_session_path = (
- f"{home}/.claude/projects/-tmp-copilot-other999/"
- "a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-results/secret.txt"
- )
- # Current session is abc123, not other999 — so the path should be denied.
- token = _current_project_dir.set("-tmp-copilot-abc123")
- try:
- result = _validate_tool_access(
- "Read", {"file_path": other_session_path}, sdk_cwd=SDK_CWD
- )
- assert _is_denied(result)
- finally:
- _current_project_dir.reset(token)
+ "relative",
+ [
+ "-tmp-copilot-abc123/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-results/o",
+ "-tmp-copilot-abc123/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-outputs/o",
+ "-tmp-copilot-abc123/settings.json",
+ "-tmp-copilot-other999/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-results/o",
+ ],
+)
+def test_native_read_is_blocked_regardless_of_sdk_path(relative):
+ path = os.path.join(os.path.expanduser("~"), ".claude", "projects", relative)
+ result = _validate_tool_access(
+ "Read", {"file_path": path}, sdk_cwd=SDK_CWD, allowed_tools={"Read"}
+ )
+ assert _is_denied(result)
+ assert "blocked for security" in _reason(result)
# -- Built-in Bash is blocked (use bash_exec MCP tool instead) ---------------
@@ -205,12 +227,16 @@ def test_bash_builtin_always_blocked():
def test_dangerous_pattern_blocked():
- result = _validate_tool_access("SomeTool", {"cmd": "sudo rm -rf /"})
+ result = _validate_tool_access(
+ "SomeTool", {"cmd": "sudo rm -rf /"}, allowed_tools={"SomeTool"}
+ )
assert _is_denied(result)
def test_subprocess_pattern_blocked():
- result = _validate_tool_access("SomeTool", {"code": "subprocess.run(...)"})
+ result = _validate_tool_access(
+ "SomeTool", {"code": "subprocess.run(...)"}, allowed_tools={"SomeTool"}
+ )
assert _is_denied(result)
@@ -268,7 +294,9 @@ def test_bash_builtin_blocked_message_clarity():
@pytest.fixture()
def _hooks():
"""Create security hooks and return (pre, post, post_failure) handlers."""
- hooks = create_security_hooks(user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2)
+ hooks = create_security_hooks(
+ user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2, allowed_tools=ALLOWED
+ )
pre = hooks["PreToolUse"][0].hooks[0]
post = hooks["PostToolUse"][0].hooks[0]
post_failure = hooks["PostToolUseFailure"][0].hooks[0]
@@ -616,7 +644,9 @@ async def test_mixed_task_agent_share_slots(_hooks):
@pytest.fixture()
def _subagent_hooks():
"""Create hooks and return (subagent_start, subagent_stop) handlers."""
- hooks = create_security_hooks(user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2)
+ hooks = create_security_hooks(
+ user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2, allowed_tools=ALLOWED
+ )
start = hooks["SubagentStart"][0].hooks[0]
stop = hooks["SubagentStop"][0].hooks[0]
return start, stop
@@ -738,7 +768,9 @@ async def test_post_tool_use_injects_followup_additional_context(
"backend.copilot.pending_messages.stash_pending_for_persist", fake_stash
)
- hooks = create_security_hooks(user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2)
+ hooks = create_security_hooks(
+ user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2, allowed_tools=ALLOWED
+ )
post = hooks["PostToolUse"][0].hooks[0]
result = await post(
@@ -776,7 +808,9 @@ async def test_post_tool_use_no_pending_returns_empty(monkeypatch):
"backend.copilot.pending_messages.drain_pending_messages", fake_drain
)
- hooks = create_security_hooks(user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2)
+ hooks = create_security_hooks(
+ user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2, allowed_tools=ALLOWED
+ )
post = hooks["PostToolUse"][0].hooks[0]
result = await post(
@@ -810,7 +844,9 @@ async def test_post_tool_use_drain_failure_returns_empty(monkeypatch):
"backend.copilot.pending_messages.drain_pending_messages", failing_drain
)
- hooks = create_security_hooks(user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2)
+ hooks = create_security_hooks(
+ user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2, allowed_tools=ALLOWED
+ )
post = hooks["PostToolUse"][0].hooks[0]
result = await post(
@@ -845,7 +881,9 @@ async def test_post_tool_use_no_session_skips_drain(monkeypatch):
"backend.copilot.pending_messages.drain_pending_messages", fake_drain
)
- hooks = create_security_hooks(user_id=None, sdk_cwd=SDK_CWD, max_subtasks=2)
+ hooks = create_security_hooks(
+ user_id=None, sdk_cwd=SDK_CWD, max_subtasks=2, allowed_tools=ALLOWED
+ )
post = hooks["PostToolUse"][0].hooks[0]
result = await post(
@@ -982,7 +1020,11 @@ async def test_a_high_volume_builtin_tool_sends_no_span(_hooks, _spans):
@pytest.mark.asyncio
async def test_builtin_tool_spans_turned_off_send_none(_spans):
hooks = create_security_hooks(
- user_id="u1", sdk_cwd=SDK_CWD, max_subtasks=2, builtin_tool_spans=False
+ user_id="u1",
+ sdk_cwd=SDK_CWD,
+ max_subtasks=2,
+ builtin_tool_spans=False,
+ allowed_tools=ALLOWED,
)
pre = hooks["PreToolUse"][0].hooks[0]
post = hooks["PostToolUse"][0].hooks[0]
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index eae356dddd..4fce4e1f24 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -5338,16 +5338,6 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
step_checkin=config.sdk_step_checkin,
)
- security_hooks = create_security_hooks(
- user_id,
- sdk_cwd=sdk_cwd,
- max_subtasks=config.claude_agent_max_subtasks,
- on_compact=compaction.on_compact,
- tool_display_bridge=tool_display_bridge,
- governor=governor,
- builtin_tool_spans=config.posthog_builtin_tool_spans,
- )
-
if permissions is not None:
allowed, disallowed = apply_tool_permissions(
permissions, use_e2b=use_e2b, disabled_groups=disabled_tool_groups
@@ -5362,6 +5352,17 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
kickoff_hidden_mcp = {f"{MCP_TOOL_PREFIX}{n}" for n in kickoff_hidden}
allowed = [n for n in allowed if n not in kickoff_hidden_mcp]
+ security_hooks = create_security_hooks(
+ user_id,
+ sdk_cwd=sdk_cwd,
+ max_subtasks=config.claude_agent_max_subtasks,
+ on_compact=compaction.on_compact,
+ tool_display_bridge=tool_display_bridge,
+ governor=governor,
+ builtin_tool_spans=config.posthog_builtin_tool_spans,
+ allowed_tools=allowed,
+ )
+
def _on_stderr(line: str) -> None:
"""Log a stderr line emitted by the Claude CLI subprocess."""
nonlocal fallback_model_activated_per_attempt
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
index 950a793d6a..0475c612ac 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
@@ -1136,6 +1136,15 @@ _SDK_BUILTIN_TOOLS = [*_SDK_BUILTIN_FILE_TOOLS, *_SDK_BUILTIN_ALWAYS]
# sdk_cwd is a per-session /tmp dir that is never restored. Leaving them
# exposed lets the model promise unattended monitoring that silently never
# fires — `schedule_followup` is the primitive that actually persists.
+# ListAgents/SendMessage: reach other CLI sessions in the same pod.
+# NotebookEdit: writes files outside the MCP Write/Edit tools.
+# Skill: Claude Code's own skills; copilot skills go through read_skill.
+# Workflow: spawns multi-agent runs with no copilot budget or UI.
+# EnterWorktree/ExitWorktree/ReportFindings: Claude Code dev-loop tools.
+# TaskStop: unused here, and permissions cannot name it, so filtered sessions
+# would drop it anyway.
+# A built-in in neither this list nor _SDK_BUILTIN_* is denied by
+# security_hooks and fails cli_builtin_tools_test.py.
SDK_DISALLOWED_TOOLS = [
"Bash",
"WebFetch",
@@ -1150,6 +1159,13 @@ SDK_DISALLOWED_TOOLS = [
"CronDelete",
"ListAgents",
"SendMessage",
+ "NotebookEdit",
+ "Skill",
+ "Workflow",
+ "EnterWorktree",
+ "ExitWorktree",
+ "ReportFindings",
+ "TaskStop",
]
# Tools that are blocked entirely in security hooks (defence-in-depth).
@@ -1163,16 +1179,9 @@ BLOCKED_TOOLS = {
"command",
}
-# Tools allowed only when their path argument stays within the SDK workspace.
-# The SDK uses these to handle oversized tool results (writes to tool-results/
-# files, then reads them back) and for workspace file operations.
-# Read is included because the SDK reads back oversized tool results from
-# tool-results/ and tool-outputs/ directories. It is also in
-# SDK_DISALLOWED_TOOLS (which controls the SDK's disallowed_tools config),
-# but the security hooks check workspace scope BEFORE the blocked list
-# so that these internal reads are permitted.
-# Write and Edit are NOT included: they are fully replaced by MCP equivalents.
-WORKSPACE_SCOPED_TOOLS = {"Glob", "Grep", "Read"}
+# Allowed Glob/Grep calls must also stay within the session's local paths.
+# Native Read/Write/Edit stay blocked; MCP handlers provide file access.
+WORKSPACE_SCOPED_TOOLS = {"Glob", "Grep"}
# Dangerous patterns in tool inputs
DANGEROUS_PATTERNS = [
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 79ece55b3b..54e328369a 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
@@ -27,6 +27,7 @@ from backend.copilot.sdk.tool_adapter import (
_build_input_schema,
_execute_tool_sync,
_make_truncating_wrapper,
+ get_copilot_tool_names,
pop_pending_tool_output,
set_execution_context,
)
@@ -100,7 +101,9 @@ async def test_hook_to_mcp_handler_keeps_provider_identity_and_clean_stash(
tool_name, args, display_name, name_key
):
bridge = SDKToolDisplayBridge()
- hooks = create_security_hooks("user", tool_display_bridge=bridge)
+ hooks = create_security_hooks(
+ "user", tool_display_bridge=bridge, allowed_tools=get_copilot_tool_names()
+ )
pre_hook = hooks["PreToolUse"][0].hooks[0]
decision = await pre_hook(
{