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(copilot): unified MCP file tools (Read/Write/Edit) to prevent truncation data loss (#12750)

Zamil Majdya3846e1e74b9
diff --git a/autogpt_platform/backend/backend/copilot/context.py b/autogpt_platform/backend/backend/copilot/context.py
index 446fed589c..895aa6c4a1 100644
--- a/autogpt_platform/backend/backend/copilot/context.py
+++ b/autogpt_platform/backend/backend/copilot/context.py
@@ -116,6 +116,47 @@ def is_within_allowed_dirs(path: str) -> bool:
return False
+def is_sdk_tool_path(path: str) -> bool:
+ """Return True if *path* is an SDK-internal tool-results or tool-outputs path.
+
+ These paths exist on the host filesystem (not in the E2B sandbox) and are
+ created by the Claude Agent SDK itself. In E2B mode, only these paths should
+ be read from the host; all other paths should be read from the sandbox.
+
+ This is a strict subset of ``is_allowed_local_path`` — it intentionally
+ excludes ``sdk_cwd`` paths because those are the agent's working directory,
+ which in E2B mode is the sandbox, not the host.
+ """
+ if not path:
+ return False
+
+ if path.startswith("~"):
+ resolved = os.path.realpath(os.path.expanduser(path))
+ elif not os.path.isabs(path):
+ # Relative paths cannot resolve to an absolute SDK-internal path
+ return False
+ else:
+ resolved = os.path.realpath(path)
+
+ encoded = _current_project_dir.get("")
+ if not encoded:
+ return False
+
+ project_dir = os.path.realpath(os.path.join(SDK_PROJECTS_DIR, encoded))
+ if not project_dir.startswith(SDK_PROJECTS_DIR + os.sep):
+ return False
+ if not resolved.startswith(project_dir + os.sep):
+ return False
+
+ relative = resolved[len(project_dir) + 1 :]
+ parts = relative.split(os.sep)
+ return (
+ len(parts) >= 3
+ and _UUID_RE.match(parts[0]) is not None
+ and parts[1] in ("tool-results", "tool-outputs")
+ )
+
+
def resolve_sandbox_path(path: str) -> str:
"""Normalise *path* to an absolute sandbox path under an allowed directory.
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index b201840cc9..cc01a124c4 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -389,21 +389,26 @@ def apply_tool_permissions(
all_tools = all_known_tool_names()
effective = permissions.effective_allowed_tools(all_tools)
- # In E2B mode, SDK built-in file tools (Read, Write, Edit, Glob, Grep)
- # are replaced by MCP equivalents (read_file, write_file, ...).
- # Map each SDK built-in name to its E2B MCP name so users can use the
- # familiar names in their permissions and the E2B tools are included.
- _SDK_TO_E2B: dict[str, str] = {}
+ # SDK built-in file tools are replaced by MCP equivalents in both modes.
+ # Map each SDK built-in name to its MCP tool name so users can use the
+ # familiar names in their permissions and the correct tools are included.
+ _SDK_TO_MCP: dict[str, str] = {}
if use_e2b:
from backend.copilot.sdk.e2b_file_tools import E2B_FILE_TOOL_NAMES
- _SDK_TO_E2B = dict(
+ _SDK_TO_MCP = dict(
zip(
["Read", "Write", "Edit", "Glob", "Grep"],
E2B_FILE_TOOL_NAMES,
strict=False,
)
)
+ else:
+ from backend.copilot.sdk.e2b_file_tools import EDIT_TOOL_NAME as _EDIT
+ from backend.copilot.sdk.e2b_file_tools import READ_TOOL_NAME as _READ
+ from backend.copilot.sdk.e2b_file_tools import WRITE_TOOL_NAME as _WRITE
+
+ _SDK_TO_MCP = {"Read": _READ, "Write": _WRITE, "Edit": _EDIT}
# Build an updated allowed list by mapping short names → SDK names and
# keeping only those present in the original base_allowed list.
@@ -411,9 +416,9 @@ def apply_tool_permissions(
names: list[str] = []
if short in TOOL_REGISTRY:
names.append(f"{MCP_TOOL_PREFIX}{short}")
- elif short in _SDK_TO_E2B:
- # E2B mode: map SDK built-in file tool to its MCP equivalent.
- names.append(f"{MCP_TOOL_PREFIX}{_SDK_TO_E2B[short]}")
+ elif short in _SDK_TO_MCP:
+ # Map SDK built-in file tool to its MCP equivalent.
+ names.append(f"{MCP_TOOL_PREFIX}{_SDK_TO_MCP[short]}")
else:
names.append(short) # SDK built-in — used as-is
return names
@@ -422,7 +427,7 @@ def apply_tool_permissions(
permitted_sdk: set[str] = set()
for s in effective:
permitted_sdk.update(to_sdk_names(s))
- # Always include the internal Read tool (used by SDK for large/truncated outputs)
+ # Always include the internal read_tool_result tool (used by SDK for large/truncated outputs)
permitted_sdk.add(f"{MCP_TOOL_PREFIX}{_READ_TOOL_NAME}")
filtered_allowed = [t for t in base_allowed if t in permitted_sdk]
diff --git a/autogpt_platform/backend/backend/copilot/permissions_test.py b/autogpt_platform/backend/backend/copilot/permissions_test.py
index 2aaec60843..5289ea8d22 100644
--- a/autogpt_platform/backend/backend/copilot/permissions_test.py
+++ b/autogpt_platform/backend/backend/copilot/permissions_test.py
@@ -408,12 +408,12 @@ class TestApplyToolPermissions:
assert "Task" not in allowed
def test_read_tool_always_included_even_when_blacklisted(self, mocker):
- """mcp__copilot__Read must stay in allowed even if Read is explicitly blacklisted."""
+ """mcp__copilot__read_tool_result must stay in allowed even if Read is explicitly blacklisted."""
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
"mcp__copilot__run_block",
- "mcp__copilot__Read",
+ "mcp__copilot__read_tool_result",
"Task",
],
)
@@ -432,17 +432,19 @@ class TestApplyToolPermissions:
# Explicitly blacklist Read
perms = CopilotPermissions(tools=["Read"], tools_exclude=True)
allowed, _ = apply_tool_permissions(perms, use_e2b=False)
- assert "mcp__copilot__Read" in allowed # always preserved for SDK internals
+ assert (
+ "mcp__copilot__read_tool_result" in allowed
+ ) # always preserved for SDK internals
assert "mcp__copilot__run_block" in allowed
assert "Task" in allowed
def test_read_tool_always_included_with_narrow_whitelist(self, mocker):
- """mcp__copilot__Read must stay in allowed even when not in a whitelist."""
+ """mcp__copilot__read_tool_result must stay in allowed even when not in a whitelist."""
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
"mcp__copilot__run_block",
- "mcp__copilot__Read",
+ "mcp__copilot__read_tool_result",
"Task",
],
)
@@ -461,7 +463,9 @@ class TestApplyToolPermissions:
# Whitelist only run_block — Read not listed
perms = CopilotPermissions(tools=["run_block"], tools_exclude=False)
allowed, _ = apply_tool_permissions(perms, use_e2b=False)
- assert "mcp__copilot__Read" in allowed # always preserved for SDK internals
+ assert (
+ "mcp__copilot__read_tool_result" in allowed
+ ) # always preserved for SDK internals
assert "mcp__copilot__run_block" in allowed
def test_e2b_file_tools_included_when_sdk_builtin_whitelisted(self, mocker):
@@ -470,7 +474,7 @@ class TestApplyToolPermissions:
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
"mcp__copilot__run_block",
- "mcp__copilot__Read",
+ "mcp__copilot__read_tool_result",
"mcp__copilot__read_file",
"mcp__copilot__write_file",
"Task",
@@ -500,13 +504,48 @@ class TestApplyToolPermissions:
# Write not whitelisted — write_file should NOT be included
assert "mcp__copilot__write_file" not in allowed
+ def test_non_e2b_file_tools_included_when_sdk_builtin_whitelisted(self, mocker):
+ """In non-E2B mode, whitelisting 'Write' must include mcp__copilot__Write."""
+ mocker.patch(
+ "backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
+ return_value=[
+ "mcp__copilot__run_block",
+ "mcp__copilot__Write",
+ "mcp__copilot__Edit",
+ "mcp__copilot__read_file",
+ "mcp__copilot__read_tool_result",
+ "Task",
+ ],
+ )
+ mocker.patch(
+ "backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",
+ return_value=["Bash"],
+ )
+ mocker.patch(
+ "backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",
+ {"run_block": object()},
+ )
+ mocker.patch(
+ "backend.copilot.permissions.all_known_tool_names",
+ return_value=frozenset(["run_block", "Read", "Write", "Edit", "Task"]),
+ )
+ # Whitelist Write and run_block — mcp__copilot__Write should be included
+ perms = CopilotPermissions(tools=["Write", "run_block"], tools_exclude=False)
+ allowed, _ = apply_tool_permissions(perms, use_e2b=False)
+ assert "mcp__copilot__Write" in allowed
+ assert "mcp__copilot__run_block" in allowed
+ # Edit not whitelisted — should NOT be included
+ assert "mcp__copilot__Edit" not in allowed
+ # read_tool_result always preserved for SDK internals
+ assert "mcp__copilot__read_tool_result" in allowed
+
def test_e2b_file_tools_excluded_when_sdk_builtin_blacklisted(self, mocker):
"""In E2B mode, blacklisting 'Read' must also remove mcp__copilot__read_file."""
mocker.patch(
"backend.copilot.sdk.tool_adapter.get_copilot_tool_names",
return_value=[
"mcp__copilot__run_block",
- "mcp__copilot__Read",
+ "mcp__copilot__read_tool_result",
"mcp__copilot__read_file",
"Task",
],
@@ -532,8 +571,8 @@ class TestApplyToolPermissions:
allowed, _ = apply_tool_permissions(perms, use_e2b=True)
assert "mcp__copilot__read_file" not in allowed
assert "mcp__copilot__run_block" in allowed
- # mcp__copilot__Read is always preserved for SDK internals
- assert "mcp__copilot__Read" in allowed
+ # mcp__copilot__read_tool_result is always preserved for SDK internals
+ assert "mcp__copilot__read_tool_result" in allowed
# ---------------------------------------------------------------------------
diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.py
index c620833345..c500a2b865 100644
--- a/autogpt_platform/backend/backend/copilot/prompting.py
+++ b/autogpt_platform/backend/backend/copilot/prompting.py
@@ -75,11 +75,12 @@ Example — committing an image file to GitHub:
}}
```
-### Writing large files — CRITICAL
-**Never write an entire large document in a single tool call.** When the
-content you want to write exceeds ~2000 words the tool call's output token
-limit will silently truncate the arguments, producing an empty `{{}}` input
-that fails repeatedly.
+### Writing large files — CRITICAL (causes production failures)
+**NEVER write an entire large document in a single tool call.** When the
+content you want to write exceeds ~2000 words the API output-token limit
+will silently truncate the tool call arguments mid-JSON, losing all content
+and producing an opaque error. This is unrecoverable — the user's work is
+lost and retrying with the same approach fails in an infinite loop.
**Preferred: compose from file references.** If the data is already in
files (tool outputs, workspace files), compose the report in one call
diff --git a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py
index a8669a301c..4661d32513 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py
@@ -1,8 +1,12 @@
-"""MCP file-tool handlers that route to the E2B cloud sandbox.
+"""Unified MCP file-tool handlers for both E2B (sandbox) and non-E2B (local) modes.
-When E2B is active, these tools replace the SDK built-in Read/Write/Edit/
-Glob/Grep so that all file operations share the same ``/home/user``
-and ``/tmp`` filesystems as ``bash_exec``.
+When E2B is active, Read/Write/Edit/Glob/Grep route to the sandbox so that
+all file operations share the same ``/home/user`` and ``/tmp`` filesystems
+as ``bash_exec``.
+
+In non-E2B mode (no sandbox), Read/Write/Edit operate on the SDK working
+directory (``/tmp/copilot-<session>/``), providing the same truncation
+detection and path-validation guarantees.
SDK-internal paths (``~/.claude/projects/…/tool-results/``) are handled
by the separate ``Read`` MCP tool registered in ``tool_adapter.py``.
@@ -10,6 +14,7 @@ by the separate ``Read`` MCP tool registered in ``tool_adapter.py``.
import asyncio
import base64
+import collections
import hashlib
import itertools
import json
@@ -25,6 +30,7 @@ from backend.copilot.context import (
get_current_sandbox,
get_sdk_cwd,
is_allowed_local_path,
+ is_sdk_tool_path,
is_within_allowed_dirs,
resolve_sandbox_path,
)
@@ -37,6 +43,121 @@ logger = logging.getLogger(__name__)
# bridge copy is worthwhile).
_DEFAULT_READ_LIMIT = 2000
+# Per-path lock for edit operations to prevent parallel lost updates.
+# When MCP tools are dispatched in parallel (readOnlyHint=True annotation),
+# two Edit calls on the same file could race through read-modify-write
+# and silently drop one change. Keyed by resolved absolute path.
+# Bounded to _EDIT_LOCKS_MAX entries (LRU eviction) to prevent unbounded
+# memory growth across long-running server processes.
+_EDIT_LOCKS_MAX = 1_000
+_edit_locks: collections.OrderedDict[str, asyncio.Lock] = collections.OrderedDict()
+
+# Inline content above this threshold triggers a warning — it survived this
+# time but is dangerously close to the API output-token truncation limit.
+_LARGE_CONTENT_WARN_CHARS = 50_000
+
+_READ_BINARY_EXTENSIONS = frozenset(
+ {
+ ".png",
+ ".jpg",
+ ".jpeg",
+ ".gif",
+ ".bmp",
+ ".ico",
+ ".webp",
+ ".pdf",
+ ".zip",
+ ".gz",
+ ".tar",
+ ".bz2",
+ ".xz",
+ ".7z",
+ ".exe",
+ ".dll",
+ ".so",
+ ".dylib",
+ ".bin",
+ ".o",
+ ".a",
+ ".pyc",
+ ".pyo",
+ ".class",
+ ".wasm",
+ ".mp3",
+ ".mp4",
+ ".avi",
+ ".mov",
+ ".mkv",
+ ".wav",
+ ".flac",
+ ".sqlite",
+ ".db",
+ }
+)
+
+
+def _is_likely_binary(path: str) -> bool:
+ """Heuristic check for binary files by extension."""
+ _, ext = os.path.splitext(path)
+ return ext.lower() in _READ_BINARY_EXTENSIONS
+
+
+_PARTIAL_TRUNCATION_MSG = (
+ "Your Write call was truncated (file_path missing but content "
+ "was present). The content was too large for a single tool call. "
+ "Write in chunks: use bash_exec with "
+ "'cat > file << \"EOF\"\\n...\\nEOF' for the first section, "
+ "'cat >> file << \"EOF\"\\n...\\nEOF' to append subsequent "
+ "sections, then reference the file with "
+ "@@agptfile:/path/to/file if needed."
+)
+
+_COMPLETE_TRUNCATION_MSG = (
+ "Your Write call had empty arguments — this means your previous "
+ "response was too long and the tool call was truncated by the API. "
+ "Break your work into smaller steps. For large content, write "
+ "section-by-section using bash_exec with "
+ "'cat > file << \"EOF\"\\n...\\nEOF' and "
+ "'cat >> file << \"EOF\"\\n...\\nEOF'."
+)
+
+_EDIT_PARTIAL_TRUNCATION_MSG = (
+ "Your Edit call was truncated (file_path missing but old_string/new_string "
+ "were present). The arguments were too large for a single tool call. "
+ "Break your edit into smaller replacements, or use bash_exec with "
+ "'sed' for large-scale find-and-replace."
+)
+
+
+def _check_truncation(file_path: str, content: str) -> dict[str, Any] | None:
+ """Return an error response if the args look truncated, else ``None``."""
+ if not file_path:
+ if content:
+ return _mcp(_PARTIAL_TRUNCATION_MSG, error=True)
+ return _mcp(_COMPLETE_TRUNCATION_MSG, error=True)
+ return None
+
+
+def _resolve_and_validate(
+ file_path: str, sdk_cwd: str
+) -> tuple[str, None] | tuple[None, dict[str, Any]]:
+ """Resolve *file_path* against *sdk_cwd* and validate it stays within bounds.
+
+ Returns ``(resolved_path, None)`` on success, or ``(None, error_response)``
+ on failure.
+ """
+ if not os.path.isabs(file_path):
+ resolved = os.path.realpath(os.path.join(sdk_cwd, file_path))
+ else:
+ resolved = os.path.realpath(file_path)
+
+ if not is_allowed_local_path(resolved, sdk_cwd):
+ return None, _mcp(
+ f"Path must be within the working directory: {os.path.basename(file_path)}",
+ error=True,
+ )
+ return resolved, None
+
async def _check_sandbox_symlink_escape(
sandbox: Any,
@@ -137,18 +258,44 @@ async def _sandbox_write(sandbox: Any, path: str, content: str | bytes) -> None:
async def _handle_read_file(args: dict[str, Any]) -> dict[str, Any]:
- """Read lines from a sandbox file, falling back to the local host for SDK-internal paths."""
+ """Read lines from a file — E2B sandbox, local SDK working dir, or SDK-internal paths."""
+ if not args:
+ return _mcp(
+ "Your read_file call had empty arguments \u2014 this means your previous "
+ "response was too long and the tool call was truncated by the API. "
+ "Break your work into smaller steps.",
+ error=True,
+ )
file_path: str = args.get("file_path", "")
- offset: int = max(0, int(args.get("offset", 0)))
- limit: int = max(1, int(args.get("limit", _DEFAULT_READ_LIMIT)))
+ try:
+ offset: int = max(0, int(args.get("offset", 0)))
+ limit: int = max(1, int(args.get("limit", _DEFAULT_READ_LIMIT)))
+ except (ValueError, TypeError):
+ return _mcp("Invalid offset/limit \u2014 must be integers.", error=True)
if not file_path:
+ if "offset" in args or "limit" in args:
+ return _mcp(
+ "Your read_file call was truncated (file_path missing but "
+ "offset/limit were present). Resend with the full file_path.",
+ error=True,
+ )
return _mcp("file_path is required", error=True)
- # SDK-internal paths (tool-results/tool-outputs, ephemeral working dir)
- # stay on the host. When E2B is active, also copy the file into the
- # sandbox so bash_exec can access it for further processing.
- if _is_allowed_local(file_path):
+ # SDK-internal tool-results/tool-outputs paths are on the host filesystem in
+ # both E2B and non-E2B mode — always read them locally.
+ # When E2B is active, also copy the file into the sandbox so bash_exec can
+ # process it further.
+ # NOTE: when E2B is active we intentionally use `is_sdk_tool_path` (not
+ # `_is_allowed_local`) so that sdk_cwd-relative paths (e.g. "output.txt")
+ # are NOT captured here. In E2B mode the agent's working directory is the
+ # sandbox, not sdk_cwd on the host, so relative paths should be read from
+ # the sandbox below.
+ sandbox_active = _get_sandbox() is not None
+ local_check = (
+ is_sdk_tool_path(file_path) if sandbox_active else _is_allowed_local(file_path)
+ )
+ if local_check:
result = _read_local(file_path, offset, limit)
if not result.get("isError"):
sandbox = _get_sandbox()
@@ -160,19 +307,54 @@ async def _handle_read_file(args: dict[str, Any]) -> dict[str, Any]:
result["content"][0]["text"] += annotation
return result
- result = _get_sandbox_and_path(file_path)
- if isinstance(result, dict):
- return result
- sandbox, remote = result
+ sandbox = _get_sandbox()
+ if sandbox is not None:
+ # E2B path — read from sandbox filesystem
+ result = _get_sandbox_and_path(file_path)
+ if isinstance(result, dict):
+ return result
+ sandbox, remote = result
+
+ try:
+ raw: bytes = await sandbox.files.read(remote, format="bytes")
+ content = raw.decode("utf-8", errors="replace")
+ except Exception as exc:
+ return _mcp(f"Failed to read {os.path.basename(remote)}: {exc}", error=True)
+
+ lines = content.splitlines(keepends=True)
+ selected = list(itertools.islice(lines, offset, offset + limit))
+ numbered = "".join(
+ f"{i + offset + 1:>6}\t{line}" for i, line in enumerate(selected)
+ )
+ return _mcp(numbered)
+
+ # Non-E2B path — read from SDK working directory
+ sdk_cwd = get_sdk_cwd()
+ if not sdk_cwd:
+ return _mcp("No SDK working directory available", error=True)
+
+ resolved, err = _resolve_and_validate(file_path, sdk_cwd)
+ if err is not None:
+ return err
+ assert resolved is not None
+
+ if _is_likely_binary(resolved):
+ return _mcp(
+ f"Cannot read binary file: {os.path.basename(resolved)}. "
+ "Use bash_exec with 'xxd' or 'file' to inspect binary files.",
+ error=True,
+ )
try:
- raw: bytes = await sandbox.files.read(remote, format="bytes")
- content = raw.decode("utf-8", errors="replace")
+ with open(resolved, encoding="utf-8", errors="replace") as f:
+ selected = list(itertools.islice(f, offset, offset + limit))
+ except FileNotFoundError:
+ return _mcp(f"File not found: {file_path}", error=True)
+ except PermissionError:
+ return _mcp(f"Permission denied: {file_path}", error=True)
except Exception as exc:
- return _mcp(f"Failed to read {remote}: {exc}", error=True)
+ return _mcp(f"Failed to read {file_path}: {exc}", error=True)
- lines = content.splitlines(keepends=True)
- selected = list(itertools.islice(lines, offset, offset + limit))
numbered = "".join(
f"{i + offset + 1:>6}\t{line}" for i, line in enumerate(selected)
)
@@ -180,93 +362,243 @@ async def _handle_read_file(args: dict[str, Any]) -> dict[str, Any]:
async def _handle_write_file(args: dict[str, Any]) -> dict[str, Any]:
- """Write content to a sandbox file, creating parent directories as needed."""
+ """Write content to a file — E2B sandbox or local SDK working directory."""
+ if not args:
+ return _mcp(_COMPLETE_TRUNCATION_MSG, error=True)
file_path: str = args.get("file_path", "")
content: str = args.get("content", "")
- if not file_path:
- return _mcp("file_path is required", error=True)
+ truncation_err = _check_truncation(file_path, content)
+ if truncation_err is not None:
+ return truncation_err
- result = _get_sandbox_and_path(file_path)
- if isinstance(result, dict):
- return result
- sandbox, remote = result
+ sandbox = _get_sandbox()
+ if sandbox is not None:
+ # E2B path — write to sandbox filesystem
+ try:
+ remote = resolve_sandbox_path(file_path)
+ except ValueError as exc:
+ return _mcp(str(exc), error=True)
- try:
- parent = os.path.dirname(remote)
- if parent and parent not in E2B_ALLOWED_DIRS:
- await sandbox.files.make_dir(parent)
- canonical_parent = await _check_sandbox_symlink_escape(sandbox, parent)
- if canonical_parent is None:
+ try:
+ parent = os.path.dirname(remote)
+ if parent and parent not in E2B_ALLOWED_DIRS:
+ await sandbox.files.make_dir(parent)
+ canonical_parent = await _check_sandbox_symlink_escape(sandbox, parent)
+ if canonical_parent is None:
+ return _mcp(
+ f"Path must be within {E2B_ALLOWED_DIRS_STR}: {os.path.basename(parent)}",
+ error=True,
+ )
+ remote = os.path.join(canonical_parent, os.path.basename(remote))
+ await _sandbox_write(sandbox, remote, content)
+ except Exception as exc:
return _mcp(
- f"Path must be within {E2B_ALLOWED_DIRS_STR}: {os.path.basename(parent)}",
- error=True,
+ f"Failed to write {os.path.basename(remote)}: {exc}", error=True
)
- remote = os.path.join(canonical_parent, os.path.basename(remote))
- await _sandbox_write(sandbox, remote, content)
+
+ msg = f"Successfully wrote to {file_path}"
+ if len(content) > _LARGE_CONTENT_WARN_CHARS:
+ logger.warning(
+ "[Write] large inline content (%d chars) for %s",
+ len(content),
+ remote,
+ )
+ msg += (
+ f"\n\nWARNING: The content was very large ({len(content)} chars). "
+ "Next time, write large files in sections using bash_exec with "
+ "'cat > file << EOF ... EOF' and 'cat >> file << EOF ... EOF' "
+ "to avoid output-token truncation."
+ )
+ return _mcp(msg)
+
+ # Non-E2B path — write to SDK working directory
+ sdk_cwd = get_sdk_cwd()
+ if not sdk_cwd:
+ return _mcp("No SDK working directory available", error=True)
+
+ resolved, err = _resolve_and_validate(file_path, sdk_cwd)
+ if err is not None:
+ return err
+ assert resolved is not None
+
+ try:
+ parent = os.path.dirname(resolved)
+ if parent:
+ os.makedirs(parent, exist_ok=True)
+ with open(resolved, "w", encoding="utf-8") as f:
+ f.write(content)
except Exception as exc:
- return _mcp(f"Failed to write {remote}: {exc}", error=True)
+ logger.error("Write failed for %s: %s", resolved, exc, exc_info=True)
+ return _mcp(
+ f"Failed to write {os.path.basename(resolved)}: {type(exc).__name__}",
+ error=True,
+ )
- return _mcp(f"Successfully wrote to {remote}")
+ msg = f"Successfully wrote to {file_path}"
+ if len(content) > _LARGE_CONTENT_WARN_CHARS:
+ logger.warning(
+ "[Write] large inline content (%d chars) for %s",
+ len(content),
+ resolved,
+ )
+ msg += (
+ f"\n\nWARNING: The content was very large ({len(content)} chars). "
+ "Next time, write large files in sections using bash_exec with "
+ "'cat > file << EOF ... EOF' and 'cat >> file << EOF ... EOF' "
+ "to avoid output-token truncation."
+ )
+ return _mcp(msg)
async def _handle_edit_file(args: dict[str, Any]) -> dict[str, Any]:
- """Replace a substring in a sandbox file, with optional replace-all support."""
+ """Replace a substring in a file — E2B sandbox or local SDK working directory."""
+ if not args:
+ return _mcp(
+ "Your Edit call had empty arguments \u2014 this means your previous "
+ "response was too long and the tool call was truncated by the API. "
+ "Break your work into smaller steps.",
+ error=True,
+ )
file_path: str = args.get("file_path", "")
old_string: str = args.get("old_string", "")
new_string: str = args.get("new_string", "")
replace_all: bool = args.get("replace_all", False)
+ # Partial truncation: file_path missing but edit strings present
if not file_path:
- return _mcp("file_path is required", error=True)
+ if old_string or new_string:
+ return _mcp(_EDIT_PARTIAL_TRUNCATION_MSG, error=True)
+ return _mcp(
+ "Your Edit call had empty arguments \u2014 this means your previous "
+ "response was too long and the tool call was truncated by the API. "
+ "Break your work into smaller steps.",
+ error=True,
+ )
+
if not old_string:
return _mcp("old_string is required", error=True)
- result = _get_sandbox_and_path(file_path)
- if isinstance(result, dict):
- return result
- sandbox, remote = result
+ sandbox = _get_sandbox()
+ if sandbox is not None:
+ # E2B path — edit in sandbox filesystem
+ try:
+ remote = resolve_sandbox_path(file_path)
+ except ValueError as exc:
+ return _mcp(str(exc), error=True)
+
+ parent = os.path.dirname(remote)
+ canonical_parent = await _check_sandbox_symlink_escape(sandbox, parent)
+ if canonical_parent is None:
+ return _mcp(
+ f"Path must be within {E2B_ALLOWED_DIRS_STR}: {os.path.basename(parent)}",
+ error=True,
+ )
+ remote = os.path.join(canonical_parent, os.path.basename(remote))
+
+ try:
+ raw = bytes(await sandbox.files.read(remote, format="bytes"))
+ content = raw.decode("utf-8", errors="replace")
+ except Exception as exc:
+ return _mcp(f"Failed to read {os.path.basename(remote)}: {exc}", error=True)
+
+ count = content.count(old_string)
+ if count == 0:
+ return _mcp(f"old_string not found in {file_path}", error=True)
+ if count > 1 and not replace_all:
+ return _mcp(
+ f"old_string appears {count} times in {file_path}. "
+ "Use replace_all=true or provide a more unique string.",
+ error=True,
+ )
+
+ updated = (
+ content.replace(old_string, new_string)
+ if replace_all
+ else content.replace(old_string, new_string, 1)
+ )
+ try:
+ await _sandbox_write(sandbox, remote, updated)
+ except Exception as exc:
+ return _mcp(
+ f"Failed to write {os.path.basename(remote)}: {exc}", error=True
+ )
- parent = os.path.dirname(remote)
- canonical_parent = await _check_sandbox_symlink_escape(sandbox, parent)
- if canonical_parent is None:
return _mcp(
- f"Path must be within {E2B_ALLOWED_DIRS_STR}: {os.path.basename(parent)}",
- error=True,
+ f"Edited {file_path} ({count} replacement{'s' if count > 1 else ''})"
)
- remote = os.path.join(canonical_parent, os.path.basename(remote))
- try:
- raw: bytes = await sandbox.files.read(remote, format="bytes")
- content = raw.decode("utf-8", errors="replace")
- except Exception as exc:
- return _mcp(f"Failed to read {remote}: {exc}", error=True)
+ # Non-E2B path — edit in SDK working directory
+ sdk_cwd = get_sdk_cwd()
+ if not sdk_cwd:
+ return _mcp("No SDK working directory available", error=True)
+
+ resolved, err = _resolve_and_validate(file_path, sdk_cwd)
+ if err is not None:
+ return err
+ assert resolved is not None
+
+ # Per-path lock prevents parallel edits from racing through
+ # the read-modify-write cycle and silently dropping changes.
+ # LRU-bounded: evict the oldest entry when the dict is full so that
+ # _edit_locks does not grow unboundedly in long-running server processes.
+ if resolved not in _edit_locks:
+ if len(_edit_locks) >= _EDIT_LOCKS_MAX:
+ _edit_locks.popitem(last=False)
+ _edit_locks[resolved] = asyncio.Lock()
+ else:
+ _edit_locks.move_to_end(resolved)
+ lock = _edit_locks[resolved]
+ async with lock:
+ try:
+ with open(resolved, encoding="utf-8") as f:
+ content = f.read()
+ except FileNotFoundError:
+ return _mcp(f"File not found: {file_path}", error=True)
+ except PermissionError:
+ return _mcp(f"Permission denied: {file_path}", error=True)
+ except Exception as exc:
+ return _mcp(f"Failed to read {file_path}: {exc}", error=True)
+
+ count = content.count(old_string)
+ if count == 0:
+ return _mcp(f"old_string not found in {file_path}", error=True)
+ if count > 1 and not replace_all:
+ return _mcp(
+ f"old_string appears {count} times in {file_path}. "
+ "Use replace_all=true or provide a more unique string.",
+ error=True,
+ )
- count = content.count(old_string)
- if count == 0:
- return _mcp(f"old_string not found in {file_path}", error=True)
- if count > 1 and not replace_all:
- return _mcp(
- f"old_string appears {count} times in {file_path}. "
- "Use replace_all=true or provide a more unique string.",
- error=True,
+ updated = (
+ content.replace(old_string, new_string)
+ if replace_all
+ else content.replace(old_string, new_string, 1)
)
- updated = (
- content.replace(old_string, new_string)
- if replace_all
- else content.replace(old_string, new_string, 1)
- )
- try:
- await _sandbox_write(sandbox, remote, updated)
- except Exception as exc:
- return _mcp(f"Failed to write {remote}: {exc}", error=True)
+ # Yield to the event loop between the read and write phases so other
+ # coroutines waiting on this lock can be scheduled. The lock above
+ # ensures they cannot enter the critical section until we release it.
+ await asyncio.sleep(0)
- return _mcp(f"Edited {remote} ({count} replacement{'s' if count > 1 else ''})")
+ try:
+ with open(resolved, "w", encoding="utf-8") as f:
+ f.write(updated)
+ except Exception as exc:
+ return _mcp(f"Failed to write {file_path}: {exc}", error=True)
+
+ return _mcp(f"Edited {file_path} ({count} replacement{'s' if count > 1 else ''})")
async def _handle_glob(args: dict[str, Any]) -> dict[str, Any]:
"""Find files matching a name pattern inside the sandbox using ``find``."""
+ if not args:
+ return _mcp(
+ "Your glob call had empty arguments \u2014 this means your previous "
+ "response was too long and the tool call was truncated by the API. "
+ "Break your work into smaller steps.",
+ error=True,
+ )
pattern: str = args.get("pattern", "")
path: str = args.get("path", "")
@@ -294,6 +626,13 @@ async def _handle_glob(args: dict[str, Any]) -> dict[str, Any]:
async def _handle_grep(args: dict[str, Any]) -> dict[str, Any]:
"""Search file contents by regex inside the sandbox using ``grep -rn``."""
+ if not args:
+ return _mcp(
+ "Your grep call had empty arguments \u2014 this means your previous "
+ "response was too long and the tool call was truncated by the API. "
+ "Break your work into smaller steps.",
+ error=True,
+ )
pattern: str = args.get("pattern", "")
path: str = args.get("path", "")
include: str = args.get("include", "")
@@ -466,7 +805,6 @@ E2B_FILE_TOOLS: list[tuple[str, str, dict[str, Any], Callable[..., Any]]] = [
"description": "Number of lines to read. Default: 2000.",
},
},
- "required": ["file_path"],
},
_handle_read_file,
),
@@ -485,7 +823,6 @@ E2B_FILE_TOOLS: list[tuple[str, str, dict[str, Any], Callable[..., Any]]] = [
},
"content": {"type": "string", "description": "Content to write."},
},
- "required": ["file_path", "content"],
},
_handle_write_file,
),
@@ -507,7 +844,6 @@ E2B_FILE_TOOLS: list[tuple[str, str, dict[str, Any], Callable[..., Any]]] = [
"description": "Replace all occurrences (default: false).",
},
},
- "required": ["file_path", "old_string", "new_string"],
},
_handle_edit_file,
),
@@ -526,7 +862,6 @@ E2B_FILE_TOOLS: list[tuple[str, str, dict[str, Any], Callable[..., Any]]] = [
"description": "Directory to search. Default: /home/user.",
},
},
- "required": ["pattern"],
},
_handle_glob,
),
@@ -546,10 +881,114 @@ E2B_FILE_TOOLS: list[tuple[str, str, dict[str, Any], Callable[..., Any]]] = [
"description": "Glob to filter files (e.g. *.py).",
},
},
- "required": ["pattern"],
},
_handle_grep,
),
]
E2B_FILE_TOOL_NAMES: list[str] = [name for name, *_ in E2B_FILE_TOOLS]
+
+
+# ---------------------------------------------------------------------------
+# Unified tool descriptors — used by tool_adapter.py in both E2B and non-E2B modes
+# ---------------------------------------------------------------------------
+
+WRITE_TOOL_NAME = "Write"
+WRITE_TOOL_DESCRIPTION = (
+ "Write or create a file. Parent directories are created automatically. "
+ "For large content (>2000 words), prefer writing in sections using "
+ "bash_exec with 'cat > file' and 'cat >> file' instead."
+)
+WRITE_TOOL_SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": (
+ "The path to the file to write. "
+ "Relative paths are resolved against the working directory."
+ ),
+ },
+ "content": {
+ "type": "string",
+ "description": "The content to write to the file.",
+ },
+ },
+}
+
+READ_TOOL_NAME = "read_file"
+READ_TOOL_DESCRIPTION = (
+ "Read a file from the working directory. Returns content with line numbers "
+ "(cat -n format). Use offset and limit to read specific ranges for large files."
+)
+READ_TOOL_SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": (
+ "The path to the file to read. "
+ "Relative paths are resolved against the working directory."
+ ),
+ },
+ "offset": {
+ "type": "integer",
+ "description": (
+ "Line number to start reading from (0-indexed). Default: 0."
+ ),
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Number of lines to read. Default: 2000.",
+ },
+ },
+}
+
+EDIT_TOOL_NAME = "Edit"
+EDIT_TOOL_DESCRIPTION = (
+ "Make targeted text replacements in a file. Finds old_string in the file "
+ "and replaces it with new_string. For replacing all occurrences, set "
+ "replace_all=true."
+)
+EDIT_TOOL_SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": (
+ "The path to the file to edit. "
+ "Relative paths are resolved against the working directory."
+ ),
+ },
+ "old_string": {
+ "type": "string",
+ "description": "The text to find in the file.",
+ },
+ "new_string": {
+ "type": "string",
+ "description": "The replacement text.",
+ },
+ "replace_all": {
+ "type": "boolean",
+ "description": (
+ "Replace all occurrences of old_string (default: false). "
+ "When false, old_string must appear exactly once."
+ ),
+ },
+ },
+}
+
+
+def get_write_tool_handler() -> Callable[..., Any]:
+ """Return the Write handler for non-E2B mode."""
+ return _handle_write_file
+
+
+def get_read_tool_handler() -> Callable[..., Any]:
+ """Return the Read handler for non-E2B mode."""
+ return _handle_read_file
+
+
+def get_edit_tool_handler() -> Callable[..., Any]:
+ """Return the Edit handler for non-E2B mode."""
+ return _handle_edit_file
diff --git a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools_test.py b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools_test.py
index f4d690f335..cc85215675 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools_test.py
@@ -1,4 +1,5 @@
-"""Tests for E2B file-tool path validation and local read safety.
+"""Tests for unified file-tool handlers (E2B + non-E2B), path validation,
+local read safety, truncation detection, and per-path edit locking.
Pure unit tests with no external dependencies (no E2B, no sandbox).
"""
@@ -12,12 +13,24 @@ from unittest.mock import AsyncMock
import pytest
from backend.copilot.context import E2B_WORKDIR, SDK_PROJECTS_DIR, _current_project_dir
+from backend.copilot.sdk.tool_adapter import SDK_DISALLOWED_TOOLS
from .e2b_file_tools import (
_BRIDGE_SHELL_MAX_BYTES,
_BRIDGE_SKIP_BYTES,
_DEFAULT_READ_LIMIT,
+ _LARGE_CONTENT_WARN_CHARS,
+ EDIT_TOOL_NAME,
+ EDIT_TOOL_SCHEMA,
+ READ_TOOL_NAME,
+ READ_TOOL_SCHEMA,
+ WRITE_TOOL_NAME,
+ WRITE_TOOL_SCHEMA,
_check_sandbox_symlink_escape,
+ _edit_locks,
+ _handle_edit_file,
+ _handle_read_file,
+ _handle_write_file,
_read_local,
_sandbox_write,
bridge_and_annotate,
@@ -26,6 +39,14 @@ from .e2b_file_tools import (
)
[email protected](autouse=True)
+def _clear_edit_locks():
+ """Clear the module-level _edit_locks dict between tests to prevent bleed."""
+ _edit_locks.clear()
+ yield
+ _edit_locks.clear()
+
+
def _expected_bridge_path(file_path: str, prefix: str = "/tmp") -> str:
"""Compute the expected sandbox path for a bridged file."""
expanded = os.path.realpath(os.path.expanduser(file_path))
@@ -565,3 +586,739 @@ class TestBridgeAndAnnotate:
)
assert annotation is None
+
+
+# ===========================================================================
+# Non-E2B (local SDK working dir) tests — ported from file_tools_test.py
+# ===========================================================================
+
+
+def sdk_cwd(tmp_path, monkeypatch):
+ """Provide a temporary SDK working directory with no sandbox."""
+ cwd = str(tmp_path / "copilot-test-session")
+ os.makedirs(cwd, exist_ok=True)
+ monkeypatch.setattr("backend.copilot.sdk.e2b_file_tools.get_sdk_cwd", lambda: cwd)
+ # Ensure no sandbox is returned (non-E2B mode)
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.get_current_sandbox", lambda: None
+ )
+ monkeypatch.setattr("backend.copilot.sdk.e2b_file_tools._get_sandbox", lambda: None)
+
+ def _patched_is_allowed(path: str, cwd_arg: str | None = None) -> bool:
+ resolved = os.path.realpath(path)
+ norm_cwd = os.path.realpath(cwd)
+ return resolved == norm_cwd or resolved.startswith(norm_cwd + os.sep)
+
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.is_allowed_local_path",
+ _patched_is_allowed,
+ )
+ return cwd
+
+
+# ---------------------------------------------------------------------------
+# Schema validation
+# ---------------------------------------------------------------------------
+
+
+class TestWriteToolSchema:
+ def test_file_path_is_first_property(self):
+ """file_path should be listed first in schema so truncation preserves it."""
+ props = list(WRITE_TOOL_SCHEMA["properties"].keys())
+ assert props[0] == "file_path"
+
+ def test_no_required_in_schema(self):
+ """required is omitted so MCP SDK does not reject truncated calls."""
+ assert "required" not in WRITE_TOOL_SCHEMA
+
+
+# ---------------------------------------------------------------------------
+# Normal write (non-E2B)
+# ---------------------------------------------------------------------------
+
+
+class TestNormalWrite:
+ @pytest.mark.asyncio
+ async def test_write_creates_file(self, sdk_cwd):
+ result = await _handle_write_file(
+ {"file_path": "hello.txt", "content": "Hello, world!"}
+ )
+ assert not result["isError"]
+ written = open(os.path.join(sdk_cwd, "hello.txt")).read()
+ assert written == "Hello, world!"
+
+ @pytest.mark.asyncio
+ async def test_write_creates_parent_dirs(self, sdk_cwd):
+ result = await _handle_write_file(
+ {"file_path": "sub/dir/file.py", "content": "print('hi')"}
+ )
+ assert not result["isError"]
+ assert os.path.isfile(os.path.join(sdk_cwd, "sub", "dir", "file.py"))
+
+ @pytest.mark.asyncio
+ async def test_write_absolute_path_within_cwd(self, sdk_cwd):
+ abs_path = os.path.join(sdk_cwd, "abs.txt")
+ result = await _handle_write_file(
+ {"file_path": abs_path, "content": "absolute"}
+ )
+ assert not result["isError"]
+ assert open(abs_path).read() == "absolute"
+
+ @pytest.mark.asyncio
+ async def test_success_message_contains_path(self, sdk_cwd):
+ result = await _handle_write_file({"file_path": "msg.txt", "content": "ok"})
+ text = result["content"][0]["text"]
+ assert "Successfully wrote" in text
+ assert "msg.txt" in text
+
+
+# ---------------------------------------------------------------------------
+# Large content warning
+# ---------------------------------------------------------------------------
+
+
+class TestLargeContentWarning:
+ @pytest.mark.asyncio
+ async def test_large_content_warns(self, sdk_cwd):
+ big_content = "x" * (_LARGE_CONTENT_WARN_CHARS + 1)
+ result = await _handle_write_file(
+ {"file_path": "big.txt", "content": big_content}
+ )
+ assert not result["isError"]
+ text = result["content"][0]["text"]
+ assert "WARNING" in text
+ assert "large" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_normal_content_no_warning(self, sdk_cwd):
+ result = await _handle_write_file(
+ {"file_path": "small.txt", "content": "small"}
+ )
+ text = result["content"][0]["text"]
+ assert "WARNING" not in text
+
+
+# ---------------------------------------------------------------------------
+# Truncation detection
+# ---------------------------------------------------------------------------
+
+
+class TestWriteTruncationDetection:
+ @pytest.mark.asyncio
+ async def test_partial_truncation_content_no_path(self, sdk_cwd):
+ """Simulates API truncating file_path but preserving content."""
+ result = await _handle_write_file({"content": "some content here"})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "truncated" in text.lower()
+ assert "file_path" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_complete_truncation_empty_args(self, sdk_cwd):
+ """Simulates API truncating to empty args {}."""
+ result = await _handle_write_file({})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "truncated" in text.lower()
+ assert "smaller steps" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_empty_file_path_string(self, sdk_cwd):
+ """Empty string file_path should trigger truncation error."""
+ result = await _handle_write_file({"file_path": "", "content": "data"})
+ assert result["isError"]
+
+
+# ---------------------------------------------------------------------------
+# Path validation (write)
+# ---------------------------------------------------------------------------
+
+
+class TestWritePathValidation:
+ @pytest.mark.asyncio
+ async def test_path_traversal_blocked(self, sdk_cwd):
+ result = await _handle_write_file(
+ {"file_path": "../../etc/passwd", "content": "evil"}
+ )
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "must be within" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_absolute_outside_cwd_blocked(self, sdk_cwd):
+ result = await _handle_write_file(
+ {"file_path": "/etc/passwd", "content": "evil"}
+ )
+ assert result["isError"]
+
+ @pytest.mark.asyncio
+ async def test_no_sdk_cwd_returns_error(self, monkeypatch):
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.get_sdk_cwd", lambda: ""
+ )
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools._get_sandbox", lambda: None
+ )
+ result = await _handle_write_file({"file_path": "test.txt", "content": "hi"})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "working directory" in text.lower()
+
+
+# ---------------------------------------------------------------------------
+# CLI built-in disallowed
+# ---------------------------------------------------------------------------
+
+
+class TestCliBuiltinDisallowed:
+ def test_write_in_disallowed_tools(self):
+ assert "Write" in SDK_DISALLOWED_TOOLS
+
+ def test_tool_name_is_write(self):
+ assert WRITE_TOOL_NAME == "Write"
+
+ def test_edit_in_disallowed_tools(self):
+ assert "Edit" in SDK_DISALLOWED_TOOLS
+
+
+# ===========================================================================
+# Read tool tests (non-E2B)
+# ===========================================================================
+
+
+class TestReadToolSchema:
+ def test_file_path_is_first_property(self):
+ props = list(READ_TOOL_SCHEMA["properties"].keys())
+ assert props[0] == "file_path"
+
+ def test_no_required_in_schema(self):
+ """required is omitted so MCP SDK does not reject truncated calls."""
+ assert "required" not in READ_TOOL_SCHEMA
+
+ def test_tool_name_is_read_file(self):
+ assert READ_TOOL_NAME == "read_file"
+
+
+class TestNormalRead:
+ @pytest.mark.asyncio
+ async def test_read_file(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "hello.txt")
+ with open(path, "w") as f:
+ f.write("line1\nline2\nline3\n")
+ result = await _handle_read_file({"file_path": "hello.txt"})
+ assert not result["isError"]
+ text = result["content"][0]["text"]
+ assert "line1" in text
+ assert "line2" in text
+ assert "line3" in text
+
+ @pytest.mark.asyncio
+ async def test_read_with_line_numbers(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "numbered.txt")
+ with open(path, "w") as f:
+ f.write("alpha\nbeta\ngamma\n")
+ result = await _handle_read_file({"file_path": "numbered.txt"})
+ text = result["content"][0]["text"]
+ assert "1\t" in text
+ assert "2\t" in text
+ assert "3\t" in text
+
+ @pytest.mark.asyncio
+ async def test_read_absolute_path_within_cwd(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "abs.txt")
+ with open(path, "w") as f:
+ f.write("absolute content")
+ result = await _handle_read_file({"file_path": path})
+ assert not result["isError"]
+ assert "absolute content" in result["content"][0]["text"]
+
+
+class TestReadOffsetLimit:
+ @pytest.mark.asyncio
+ async def test_read_with_offset(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "lines.txt")
+ with open(path, "w") as f:
+ for i in range(10):
+ f.write(f"line{i}\n")
+ result = await _handle_read_file(
+ {"file_path": "lines.txt", "offset": 5, "limit": 3}
+ )
+ text = result["content"][0]["text"]
+ assert "line5" in text
+ assert "line6" in text
+ assert "line7" in text
+ assert "line4" not in text
+ assert "line8" not in text
+
+ @pytest.mark.asyncio
+ async def test_read_with_limit(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "many.txt")
+ with open(path, "w") as f:
+ for i in range(100):
+ f.write(f"line{i}\n")
+ result = await _handle_read_file({"file_path": "many.txt", "limit": 2})
+ text = result["content"][0]["text"]
+ assert "line0" in text
+ assert "line1" in text
+ assert "line2" not in text
+
+ @pytest.mark.asyncio
+ async def test_offset_line_numbers_are_correct(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "offset_nums.txt")
+ with open(path, "w") as f:
+ for i in range(10):
+ f.write(f"line{i}\n")
+ result = await _handle_read_file(
+ {"file_path": "offset_nums.txt", "offset": 3, "limit": 2}
+ )
+ text = result["content"][0]["text"]
+ assert "4\t" in text
+ assert "5\t" in text
+
+
+class TestReadInvalidOffsetLimit:
+ @pytest.mark.asyncio
+ async def test_non_integer_offset(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "valid.txt")
+ with open(path, "w") as f:
+ f.write("content\n")
+ result = await _handle_read_file({"file_path": "valid.txt", "offset": "abc"})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "invalid" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_non_integer_limit(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "valid.txt")
+ with open(path, "w") as f:
+ f.write("content\n")
+ result = await _handle_read_file({"file_path": "valid.txt", "limit": "xyz"})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "invalid" in text.lower()
+
+
+class TestReadFileNotFound:
+ @pytest.mark.asyncio
+ async def test_file_not_found(self, sdk_cwd):
+ result = await _handle_read_file({"file_path": "nonexistent.txt"})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "not found" in text.lower()
+
+
+class TestReadPathTraversal:
+ @pytest.mark.asyncio
+ async def test_path_traversal_blocked(self, sdk_cwd):
+ result = await _handle_read_file({"file_path": "../../etc/passwd"})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "must be within" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_absolute_outside_cwd_blocked(self, sdk_cwd):
+ result = await _handle_read_file({"file_path": "/etc/passwd"})
+ assert result["isError"]
+
+
+class TestReadBinaryFile:
+ @pytest.mark.asyncio
+ async def test_binary_file_rejected(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "image.png")
+ with open(path, "wb") as f:
+ f.write(b"\x89PNG\r\n\x1a\n")
+ result = await _handle_read_file({"file_path": "image.png"})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "binary" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_text_file_not_rejected_as_binary(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "code.py")
+ with open(path, "w") as f:
+ f.write("print('hello')\n")
+ result = await _handle_read_file({"file_path": "code.py"})
+ assert not result["isError"]
+
+
+class TestReadTruncationDetection:
+ @pytest.mark.asyncio
+ async def test_truncation_offset_without_file_path(self, sdk_cwd):
+ """offset present but file_path missing — truncated call."""
+ result = await _handle_read_file({"offset": 5})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "truncated" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_truncation_limit_without_file_path(self, sdk_cwd):
+ """limit present but file_path missing — truncated call."""
+ result = await _handle_read_file({"limit": 100})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "truncated" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_no_truncation_plain_empty(self, sdk_cwd):
+ """Empty args — treated as complete truncation."""
+ result = await _handle_read_file({})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "truncated" in text.lower() or "empty arguments" in text.lower()
+
+
+class TestReadEmptyFilePath:
+ @pytest.mark.asyncio
+ async def test_empty_file_path(self, sdk_cwd):
+ result = await _handle_read_file({"file_path": ""})
+ assert result["isError"]
+
+ @pytest.mark.asyncio
+ async def test_no_sdk_cwd(self, monkeypatch):
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.get_sdk_cwd", lambda: ""
+ )
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools._get_sandbox", lambda: None
+ )
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools._is_allowed_local",
+ lambda p: False,
+ )
+ result = await _handle_read_file({"file_path": "test.txt"})
+ assert result["isError"]
+ assert "working directory" in result["content"][0]["text"].lower()
+
+
+# ===========================================================================
+# Edit tool tests (non-E2B)
+# ===========================================================================
+
+
+class TestEditToolSchema:
+ def test_file_path_is_first_property(self):
+ props = list(EDIT_TOOL_SCHEMA["properties"].keys())
+ assert props[0] == "file_path"
+
+ def test_no_required_in_schema(self):
+ """required is omitted so MCP SDK does not reject truncated calls."""
+ assert "required" not in EDIT_TOOL_SCHEMA
+
+ def test_tool_name_is_edit(self):
+ assert EDIT_TOOL_NAME == "Edit"
+
+
+class TestNormalEdit:
+ @pytest.mark.asyncio
+ async def test_simple_replacement(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "edit_me.txt")
+ with open(path, "w") as f:
+ f.write("Hello World\n")
+ result = await _handle_edit_file(
+ {"file_path": "edit_me.txt", "old_string": "World", "new_string": "Earth"}
+ )
+ assert not result["isError"]
+ content = open(path).read()
+ assert content == "Hello Earth\n"
+
+ @pytest.mark.asyncio
+ async def test_edit_reports_replacement_count(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "count.txt")
+ with open(path, "w") as f:
+ f.write("one two three\n")
+ result = await _handle_edit_file(
+ {"file_path": "count.txt", "old_string": "two", "new_string": "2"}
+ )
+ text = result["content"][0]["text"]
+ assert "1 replacement" in text
+
+ @pytest.mark.asyncio
+ async def test_edit_absolute_path(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "abs_edit.txt")
+ with open(path, "w") as f:
+ f.write("before\n")
+ result = await _handle_edit_file(
+ {"file_path": path, "old_string": "before", "new_string": "after"}
+ )
+ assert not result["isError"]
+ assert open(path).read() == "after\n"
+
+
+class TestEditOldStringNotFound:
+ @pytest.mark.asyncio
+ async def test_old_string_not_found(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "nope.txt")
+ with open(path, "w") as f:
+ f.write("Hello World\n")
+ result = await _handle_edit_file(
+ {"file_path": "nope.txt", "old_string": "MISSING", "new_string": "x"}
+ )
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "not found" in text.lower()
+
+
+class TestEditOldStringNotUnique:
+ @pytest.mark.asyncio
+ async def test_not_unique_without_replace_all(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "dup.txt")
+ with open(path, "w") as f:
+ f.write("foo bar foo baz\n")
+ result = await _handle_edit_file(
+ {"file_path": "dup.txt", "old_string": "foo", "new_string": "qux"}
+ )
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "2 times" in text
+ assert open(path).read() == "foo bar foo baz\n"
+
+
+class TestEditReplaceAll:
+ @pytest.mark.asyncio
+ async def test_replace_all(self, sdk_cwd):
+ path = os.path.join(sdk_cwd, "all.txt")
+ with open(path, "w") as f:
+ f.write("foo bar foo baz foo\n")
+ result = await _handle_edit_file(
+ {
+ "file_path": "all.txt",
+ "old_string": "foo",
+ "new_string": "qux",
+ "replace_all": True,
+ }
+ )
+ assert not result["isError"]
+ content = open(path).read()
+ assert content == "qux bar qux baz qux\n"
+ text = result["content"][0]["text"]
+ assert "3 replacement" in text
+
+
+class TestEditPartialTruncation:
+ @pytest.mark.asyncio
+ async def test_partial_truncation(self, sdk_cwd):
+ """file_path missing but old_string/new_string present."""
+ result = await _handle_edit_file(
+ {"old_string": "something", "new_string": "else"}
+ )
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "truncated" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_complete_truncation(self, sdk_cwd):
+ result = await _handle_edit_file({})
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "truncated" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_empty_file_path_with_content(self, sdk_cwd):
+ result = await _handle_edit_file(
+ {"file_path": "", "old_string": "x", "new_string": "y"}
+ )
+ assert result["isError"]
+
+
+class TestEditPathTraversal:
+ @pytest.mark.asyncio
+ async def test_path_traversal_blocked(self, sdk_cwd):
+ result = await _handle_edit_file(
+ {
+ "file_path": "../../etc/passwd",
+ "old_string": "root",
+ "new_string": "evil",
+ }
+ )
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "must be within" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_absolute_outside_cwd_blocked(self, sdk_cwd):
+ result = await _handle_edit_file(
+ {
+ "file_path": "/etc/passwd",
+ "old_string": "root",
+ "new_string": "evil",
+ }
+ )
+ assert result["isError"]
+
+
+class TestEditFileNotFound:
+ @pytest.mark.asyncio
+ async def test_file_not_found(self, sdk_cwd):
+ result = await _handle_edit_file(
+ {
+ "file_path": "nonexistent.txt",
+ "old_string": "x",
+ "new_string": "y",
+ }
+ )
+ assert result["isError"]
+ text = result["content"][0]["text"]
+ assert "not found" in text.lower()
+
+ @pytest.mark.asyncio
+ async def test_no_sdk_cwd(self, monkeypatch):
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.get_sdk_cwd", lambda: ""
+ )
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools._get_sandbox", lambda: None
+ )
+ result = await _handle_edit_file(
+ {"file_path": "test.txt", "old_string": "x", "new_string": "y"}
+ )
+ assert result["isError"]
+ assert "working directory" in result["content"][0]["text"].lower()
+
+
+# ---------------------------------------------------------------------------
+# Concurrent edit locking
+# ---------------------------------------------------------------------------
+
+
+class TestConcurrentEditLocking:
+ @pytest.mark.asyncio
+ async def test_concurrent_edits_are_serialised(self, sdk_cwd):
+ """Two parallel Edit calls on the same file must not race.
+
+ Each edit appends a unique line by replacing a sentinel. Without the
+ per-path lock one update would silently overwrite the other; with the
+ lock both replacements must be present in the final file.
+
+ The handler yields via ``asyncio.sleep(0)`` between the read and write
+ phases, allowing the event loop to schedule the second coroutine. The
+ per-path lock ensures the second edit cannot proceed until the first
+ completes — without it, the test would fail because edit_b would read
+ a stale file and overwrite edit_a's change.
+ """
+ import asyncio as _asyncio
+
+ path = os.path.join(sdk_cwd, "concurrent.txt")
+ with open(path, "w") as f:
+ f.write("line1\nline2\n")
+
+ # Two coroutines both replace a *different* substring — they must not
+ # race through the read-modify-write cycle.
+ async def edit_a():
+ return await _handle_edit_file(
+ {
+ "file_path": "concurrent.txt",
+ "old_string": "line1",
+ "new_string": "EDITED_A",
+ }
+ )
+
+ async def edit_b():
+ return await _handle_edit_file(
+ {
+ "file_path": "concurrent.txt",
+ "old_string": "line2",
+ "new_string": "EDITED_B",
+ }
+ )
+
+ results = await _asyncio.gather(edit_a(), edit_b())
+ for r in results:
+ assert not r["isError"], r["content"][0]["text"]
+
+ final = open(path).read()
+ assert "EDITED_A" in final
+ assert "EDITED_B" in final
+
+
+# ---------------------------------------------------------------------------
+# E2B mode: relative paths are routed to the sandbox, not the host
+# ---------------------------------------------------------------------------
+
+
+class TestReadFileE2BRouting:
+ """Verify that _handle_read_file routes correctly in E2B mode.
+
+ When E2B is active, relative paths (e.g. "output.txt") resolve against
+ sdk_cwd on the host via _is_allowed_local — but those files were written to
+ the sandbox, not to sdk_cwd. The fix: when E2B is active, only SDK-internal
+ tool-results/tool-outputs paths are read from the host; everything else is
+ routed to the sandbox.
+ """
+
+ @pytest.mark.asyncio
+ async def test_relative_path_in_e2b_mode_goes_to_sandbox(
+ self, monkeypatch, tmp_path
+ ):
+ """A plain relative path in E2B mode must be read from the sandbox, not the host."""
+ cwd = str(tmp_path / "copilot-session")
+ os.makedirs(cwd)
+
+ # Set up sdk_cwd so _is_allowed_local would return True for "output.txt"
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.get_sdk_cwd", lambda: cwd
+ )
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.is_allowed_local_path",
+ lambda path, cwd_arg=None: os.path.realpath(
+ os.path.join(cwd, path) if not os.path.isabs(path) else path
+ ).startswith(os.path.realpath(cwd)),
+ )
+
+ # Create a sandbox mock that returns "sandbox content"
+ sandbox = SimpleNamespace(
+ files=SimpleNamespace(
+ read=AsyncMock(return_value=b"sandbox content\n"),
+ make_dir=AsyncMock(),
+ ),
+ commands=SimpleNamespace(run=AsyncMock()),
+ )
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools._get_sandbox", lambda: sandbox
+ )
+
+ result = await _handle_read_file({"file_path": "output.txt"})
+
+ # Should NOT be an error (file was read from sandbox)
+ assert not result.get("isError"), result["content"][0]["text"]
+ assert "sandbox content" in result["content"][0]["text"]
+ # The sandbox files.read must have been called
+ sandbox.files.read.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_absolute_tmp_path_in_e2b_goes_to_sandbox(self, monkeypatch):
+ """An absolute /tmp path (sdk_cwd-relative) in E2B mode is routed to the sandbox.
+
+ sdk_cwd is always under /tmp in production (e.g. /tmp/copilot-<session>/).
+ An absolute path like /tmp/copilot-xxx/result.txt must be read from the
+ sandbox rather than the host even though _is_allowed_local would return True
+ for it.
+ """
+ cwd = "/tmp/copilot-test-session-xyz"
+ absolute_path = "/tmp/copilot-test-session-xyz/result.txt"
+
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.get_sdk_cwd", lambda: cwd
+ )
+ # Simulate _is_allowed_local returning True for the path (as it would in prod)
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools.is_allowed_local_path",
+ lambda path, cwd_arg=None: path.startswith(cwd),
+ )
+
+ sandbox = SimpleNamespace(
+ files=SimpleNamespace(
+ read=AsyncMock(return_value=b"sandbox result\n"),
+ make_dir=AsyncMock(),
+ ),
+ commands=SimpleNamespace(run=AsyncMock()),
+ )
+ monkeypatch.setattr(
+ "backend.copilot.sdk.e2b_file_tools._get_sandbox", lambda: sandbox
+ )
+
+ result = await _handle_read_file({"file_path": absolute_path})
+
+ assert not result.get("isError"), result["content"][0]["text"]
+ assert "sandbox result" in result["content"][0]["text"]
+ sandbox.files.read.assert_called_once()
diff --git a/autogpt_platform/backend/backend/copilot/sdk/file_ref_integration_test.py b/autogpt_platform/backend/backend/copilot/sdk/file_ref_integration_test.py
index 4e41a19da6..117dcfc02d 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/file_ref_integration_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/file_ref_integration_test.py
@@ -375,7 +375,12 @@ async def test_bare_ref_toml_returns_parsed_dict():
@pytest.mark.asyncio
async def test_read_file_handler_local_file():
- """_read_file_handler reads a local file when it's within sdk_cwd."""
+ """_read_file_handler rejects files in sdk_cwd (use read_file MCP tool for those).
+
+ read_tool_result is restricted to SDK-internal tool-results/tool-outputs paths
+ via is_sdk_tool_path(). sdk_cwd files should be read via the read_file (e2b_file_tools)
+ handler, not via read_tool_result.
+ """
with tempfile.TemporaryDirectory() as sdk_cwd:
test_file = os.path.join(sdk_cwd, "read_test.txt")
lines = [f"L{i}\n" for i in range(1, 6)]
@@ -389,16 +394,16 @@ async def test_read_file_handler_local_file():
return_value=("user-1", _make_session()),
):
mock_cwd_var.get.return_value = sdk_cwd
+ # No project_dir set — so is_sdk_tool_path returns False for sdk_cwd paths
mock_proj_var.get.return_value = ""
result = await _read_file_handler(
{"file_path": test_file, "offset": 0, "limit": 5}
)
- assert not result["isError"]
- text = result["content"][0]["text"]
- assert "L1" in text
- assert "L5" in text
+ # sdk_cwd paths are NOT allowed via read_tool_result (use read_file instead)
+ assert result["isError"]
+ assert "not allowed" in result["content"][0]["text"].lower()
@pytest.mark.asyncio
diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
index 1e33bca2d8..e5ba184f4f 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py
@@ -10,7 +10,7 @@ import re
from collections.abc import Callable
from typing import Any, cast
-from backend.copilot.context import is_allowed_local_path
+from backend.copilot.context import is_allowed_local_path, is_sdk_tool_path
from .tool_adapter import (
BLOCKED_TOOLS,
@@ -71,16 +71,32 @@ def _validate_workspace_path(
) -> dict[str, Any]:
"""Validate that a workspace-scoped tool only accesses allowed paths.
- Delegates to :func:`is_allowed_local_path` which permits:
- - The SDK working directory (``/tmp/copilot-<session>/``)
- - The current session's tool-results directory
- (``~/.claude/projects/<encoded-cwd>/<uuid>/tool-results/``)
+ 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.
"""
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 {}
@@ -101,6 +117,13 @@ def _validate_tool_access(
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}")
@@ -110,10 +133,6 @@ def _validate_tool_access(
"Use the CoPilot-specific MCP tools instead."
)
- # Workspace-scoped tools: allowed only within the SDK workspace directory
- 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 ""
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 ac13217036..033bcf1494 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py
@@ -56,25 +56,36 @@ def test_unknown_tool_allowed():
# -- Workspace-scoped tools --------------------------------------------------
-def test_read_within_workspace_allowed():
+def test_read_within_workspace_blocked():
+ """Read of workspace files is denied — workspace reads must use the read_file MCP tool."""
result = _validate_tool_access(
"Read", {"file_path": f"{SDK_CWD}/file.txt"}, sdk_cwd=SDK_CWD
)
- assert result == {}
+ assert _is_denied(result)
-def test_write_within_workspace_allowed():
+def test_read_outside_workspace_blocked():
+ """Read outside the workspace is denied."""
+ result = _validate_tool_access(
+ "Read", {"file_path": "/etc/passwd"}, sdk_cwd=SDK_CWD
+ )
+ assert _is_denied(result)
+
+
+def test_write_builtin_blocked():
+ """SDK built-in Write is blocked — all writes go through MCP Write tool."""
result = _validate_tool_access(
"Write", {"file_path": f"{SDK_CWD}/output.json"}, sdk_cwd=SDK_CWD
)
- assert result == {}
+ assert _is_denied(result)
-def test_edit_within_workspace_allowed():
+def test_edit_builtin_blocked():
+ """SDK built-in Edit is blocked — all edits go through MCP Edit tool."""
result = _validate_tool_access(
"Edit", {"file_path": f"{SDK_CWD}/src/main.py"}, sdk_cwd=SDK_CWD
)
- assert result == {}
+ assert _is_denied(result)
def test_glob_within_workspace_allowed():
@@ -161,6 +172,26 @@ def test_read_claude_projects_settings_json_denied():
_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)
+
+
# -- Built-in Bash is blocked (use bash_exec MCP tool instead) ---------------
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
index 9c963f6863..2a64c84d64 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
@@ -25,8 +25,7 @@ from backend.copilot.context import (
_current_user_id,
_encode_cwd_for_cli,
get_execution_context,
- get_sdk_cwd,
- is_allowed_local_path,
+ is_sdk_tool_path,
)
from backend.copilot.model import ChatSession
from backend.copilot.sdk.file_ref import (
@@ -38,7 +37,23 @@ from backend.copilot.tools import TOOL_REGISTRY
from backend.copilot.tools.base import BaseTool
from backend.util.truncate import truncate
-from .e2b_file_tools import E2B_FILE_TOOL_NAMES, E2B_FILE_TOOLS, bridge_and_annotate
+from .e2b_file_tools import (
+ E2B_FILE_TOOL_NAMES,
+ E2B_FILE_TOOLS,
+ EDIT_TOOL_DESCRIPTION,
+ EDIT_TOOL_NAME,
+ EDIT_TOOL_SCHEMA,
+ READ_TOOL_DESCRIPTION,
+ READ_TOOL_NAME,
+ READ_TOOL_SCHEMA,
+ WRITE_TOOL_DESCRIPTION,
+ WRITE_TOOL_NAME,
+ WRITE_TOOL_SCHEMA,
+ bridge_and_annotate,
+ get_edit_tool_handler,
+ get_read_tool_handler,
+ get_write_tool_handler,
+)
if TYPE_CHECKING:
from e2b import AsyncSandbox
@@ -349,11 +364,18 @@ def create_tool_handler(base_tool: BaseTool):
def _build_input_schema(base_tool: BaseTool) -> dict[str, Any]:
- """Build a JSON Schema input schema for a tool."""
+ """Build a JSON Schema input schema for a tool.
+
+ ``required`` is intentionally omitted from the schema sent to the MCP SDK.
+ The SDK validates ``required`` fields BEFORE calling the Python handler \u2014
+ when the LLM's output tokens are truncated the tool call arrives as ``{}``
+ and the SDK rejects it with an opaque ``'X' is a required property`` error.
+ By omitting ``required`` the empty-args case reaches our Python handler
+ where ``_make_truncating_wrapper`` returns actionable chunking guidance.
+ """
return {
"type": "object",
"properties": base_tool.parameters.get("properties", {}),
- "required": base_tool.parameters.get("required", []),
}
@@ -363,9 +385,6 @@ async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:
Supports ``workspace://`` URIs (delegated to the workspace manager) and
local paths within the session's allowed directories (sdk_cwd + tool-results).
"""
- file_path = args.get("file_path", "")
- offset = max(0, int(args.get("offset", 0)))
- limit = max(1, int(args.get("limit", 2000)))
def _mcp_err(text: str) -> dict[str, Any]:
return {"content": [{"type": "text", "text": text}], "isError": True}
@@ -373,6 +392,28 @@ async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:
def _mcp_ok(text: str) -> dict[str, Any]:
return {"content": [{"type": "text", "text": text}], "isError": False}
+ if not args:
+ return _mcp_err(
+ "Your Read call had empty arguments \u2014 this means your previous "
+ "response was too long and the tool call was truncated by the API. "
+ "Break your work into smaller steps."
+ )
+
+ file_path = args.get("file_path", "")
+ try:
+ offset = max(0, int(args.get("offset", 0)))
+ limit = max(1, int(args.get("limit", 2000)))
+ except (ValueError, TypeError):
+ return _mcp_err("Invalid offset/limit \u2014 must be integers.")
+
+ if not file_path:
+ if "offset" in args or "limit" in args:
+ return _mcp_err(
+ "Your Read call was truncated (file_path missing but "
+ "offset/limit were present). Resend with the full file_path."
+ )
+ return _mcp_err("file_path is required")
+
if file_path.startswith("workspace://"):
user_id, session = get_execution_context()
if session is None:
@@ -388,8 +429,13 @@ async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:
)
return _mcp_ok(numbered)
- if not is_allowed_local_path(file_path, get_sdk_cwd()):
- return _mcp_err(f"Path not allowed: {file_path}")
+ # Use is_sdk_tool_path (not is_allowed_local_path) to restrict this tool
+ # to only SDK-internal tool-results/tool-outputs paths. is_sdk_tool_path
+ # validates session membership via _current_project_dir, preventing
+ # cross-session reads. sdk_cwd files (workspace outputs) are NOT allowed
+ # here — they are served by the e2b_file_tools Read handler instead.
+ if not is_sdk_tool_path(file_path):
+ return _mcp_err(f"Path not allowed: {os.path.basename(file_path)}")
resolved = os.path.realpath(os.path.expanduser(file_path))
try:
@@ -413,9 +459,12 @@ async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:
return _mcp_err(f"Error reading file: {e}")
-_READ_TOOL_NAME = "Read"
+_READ_TOOL_NAME = "read_tool_result"
_READ_TOOL_DESCRIPTION = (
- "Read a file from the local filesystem. "
+ "Read an SDK-internal tool-result file or a workspace:// URI. "
+ "Use this tool only for paths under ~/.claude/projects/.../tool-results/ "
+ "or tool-outputs/, and for workspace:// URIs returned by other tools. "
+ "For files in the working directory use read_file instead. "
"Use offset and limit to read specific line ranges for large files."
)
_READ_TOOL_SCHEMA = {
@@ -434,7 +483,6 @@ _READ_TOOL_SCHEMA = {
"description": "Number of lines to read. Default: 2000",
},
},
- "required": ["file_path"],
}
@@ -456,6 +504,7 @@ def _text_from_mcp_result(result: dict[str, Any]) -> str:
_PARALLEL_ANNOTATION = ToolAnnotations(readOnlyHint=True)
+_MUTATING_ANNOTATION = ToolAnnotations(readOnlyHint=False)
def _strip_llm_fields(result: dict[str, Any]) -> dict[str, Any]:
@@ -512,7 +561,13 @@ def _make_truncating_wrapper(
"""
async def wrapper(args: dict[str, Any]) -> dict[str, Any]:
- if not args and input_schema and input_schema.get("required"):
+ # Detect empty-args truncation: args is empty AND the schema declares
+ # at least one property (so a non-empty call was expected).
+ # NOTE: _build_input_schema intentionally omits "required" to avoid
+ # SDK-side validation rejecting truncated calls before reaching this
+ # handler. We detect truncation via "properties" instead.
+ schema_has_params = bool(input_schema and input_schema.get("properties"))
+ if not args and schema_has_params:
logger.warning(
"[MCP] %s called with empty args (likely output "
"token truncation) — returning guidance",
@@ -612,16 +667,67 @@ def create_copilot_mcp_server(*, use_e2b: bool = False):
sdk_tools.append(decorated)
# E2B file tools replace SDK built-in Read/Write/Edit/Glob/Grep.
+ _MUTATING_E2B_TOOLS = {"write_file", "edit_file"}
if use_e2b:
for name, desc, schema, handler in E2B_FILE_TOOLS:
+ ann = (
+ _MUTATING_ANNOTATION
+ if name in _MUTATING_E2B_TOOLS
+ else _PARALLEL_ANNOTATION
+ )
decorated = tool(
name,
desc,
schema,
- annotations=_PARALLEL_ANNOTATION,
+ annotations=ann,
)(_make_truncating_wrapper(handler, name))
sdk_tools.append(decorated)
+ # Unified Write/Read/Edit tools — replace the CLI's built-in versions
+ # which have no defence against output-token truncation.
+ # Skip in E2B mode: E2B_FILE_TOOLS already registers "write_file",
+ # "read_file", and "edit_file". Registering both would give the LLM
+ # duplicate tools per operation.
+ if not use_e2b:
+ write_handler = get_write_tool_handler()
+ write_tool = tool(
+ WRITE_TOOL_NAME,
+ WRITE_TOOL_DESCRIPTION,
+ WRITE_TOOL_SCHEMA,
+ annotations=_MUTATING_ANNOTATION,
+ )(
+ _make_truncating_wrapper(
+ write_handler, WRITE_TOOL_NAME, input_schema=WRITE_TOOL_SCHEMA
+ )
+ )
+ sdk_tools.append(write_tool)
+
+ read_file_handler = get_read_tool_handler()
+ read_file_tool = tool(
+ READ_TOOL_NAME,
+ READ_TOOL_DESCRIPTION,
+ READ_TOOL_SCHEMA,
+ annotations=_PARALLEL_ANNOTATION,
+ )(
+ _make_truncating_wrapper(
+ read_file_handler, READ_TOOL_NAME, input_schema=READ_TOOL_SCHEMA
+ )
+ )
+ sdk_tools.append(read_file_tool)
+
+ edit_handler = get_edit_tool_handler()
+ edit_tool = tool(
+ EDIT_TOOL_NAME,
+ EDIT_TOOL_DESCRIPTION,
+ EDIT_TOOL_SCHEMA,
+ annotations=_MUTATING_ANNOTATION,
+ )(
+ _make_truncating_wrapper(
+ edit_handler, EDIT_TOOL_NAME, input_schema=EDIT_TOOL_SCHEMA
+ )
+ )
+ sdk_tools.append(edit_tool)
+
# Read tool for SDK-truncated tool results (always needed, read-only).
read_tool = tool(
_READ_TOOL_NAME,
@@ -658,10 +764,27 @@ _SDK_BUILTIN_TOOLS = [*_SDK_BUILTIN_FILE_TOOLS, *_SDK_BUILTIN_ALWAYS]
# WebFetch: SSRF risk — can reach internal network (localhost, 10.x, etc.).
# Agent uses the SSRF-protected mcp__copilot__web_fetch tool instead.
# AskUserQuestion: interactive CLI tool — no terminal in copilot context.
+# Write: the CLI's built-in Write tool has no defence against output-token
+# truncation. When the LLM generates a very large `content` argument the
+# API truncates the response mid-JSON and Ajv rejects it with the opaque
+# "'file_path' is a required property" error, losing the user's work.
+# All writes go through our MCP Write tool (e2b_file_tools.py) where we
+# control validation and return actionable guidance.
+# Edit: same truncation risk as Write — the CLI's built-in Edit has no
+# defence against output-token truncation. All edits go through our
+# MCP Edit tool (e2b_file_tools.py).
+# Read: already disallowed in E2B mode (prod/dev) via
+# _SDK_BUILTIN_FILE_TOOLS. Disallow in non-E2B too for consistency
+# — our MCP read_file handles tool-results paths via
+# is_allowed_local_path() and has been the only Read available in
+# prod without issues.
SDK_DISALLOWED_TOOLS = [
"Bash",
"WebFetch",
"AskUserQuestion",
+ "Write",
+ "Edit",
+ "Read",
]
# Tools that are blocked entirely in security hooks (defence-in-depth).
@@ -678,7 +801,13 @@ BLOCKED_TOOLS = {
# 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.
-WORKSPACE_SCOPED_TOOLS = {"Read", "Write", "Edit", "Glob", "Grep"}
+# 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"}
# Dangerous patterns in tool inputs
DANGEROUS_PATTERNS = [
@@ -700,6 +829,9 @@ DANGEROUS_PATTERNS = [
# Static tool name list for the non-E2B case (backward compatibility).
COPILOT_TOOL_NAMES = [
*[f"{MCP_TOOL_PREFIX}{name}" for name in TOOL_REGISTRY.keys()],
+ f"{MCP_TOOL_PREFIX}{WRITE_TOOL_NAME}",
+ f"{MCP_TOOL_PREFIX}{READ_TOOL_NAME}",
+ f"{MCP_TOOL_PREFIX}{EDIT_TOOL_NAME}",
f"{MCP_TOOL_PREFIX}{_READ_TOOL_NAME}",
*_SDK_BUILTIN_TOOLS,
]
@@ -714,6 +846,9 @@ def get_copilot_tool_names(*, use_e2b: bool = False) -> list[str]:
if not use_e2b:
return list(COPILOT_TOOL_NAMES)
+ # In E2B mode, Write/Edit are NOT registered (E2B uses write_file/edit_file
+ # from E2B_FILE_TOOLS instead), so don't include them here.
+ # _READ_TOOL_NAME is still needed for SDK tool-result reads.
return [
*[f"{MCP_TOOL_PREFIX}{name}" for name in TOOL_REGISTRY.keys()],
f"{MCP_TOOL_PREFIX}{_READ_TOOL_NAME}",
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py
index 4cd398f451..6629363c2f 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py
@@ -653,8 +653,8 @@ class TestReadFileHandlerBridge:
test_file.write_text('{"ok": true}\n')
monkeypatch.setattr(
- "backend.copilot.sdk.tool_adapter.is_allowed_local_path",
- lambda path, cwd: True,
+ "backend.copilot.sdk.tool_adapter.is_sdk_tool_path",
+ lambda path: True,
)
fake_sandbox = object()
@@ -692,8 +692,8 @@ class TestReadFileHandlerBridge:
test_file.write_text('{"ok": true}\n')
monkeypatch.setattr(
- "backend.copilot.sdk.tool_adapter.is_allowed_local_path",
- lambda path, cwd: True,
+ "backend.copilot.sdk.tool_adapter.is_sdk_tool_path",
+ lambda path: True,
)
bridge_calls: list[tuple] = []