Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion orchestrator/mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,36 @@ def get_logger(name: str, **kwargs) -> logging.Logger:
except ImportError:
_SLICE_ID_PATTERN = re.compile(r"^slice-[0-9]+$")

try:
from egg_tool_output import cap_result_dict
except ImportError: # pragma: no cover - shared path always present in prod

def cap_result_dict(result, **_kwargs): # type: ignore[no-redef]
return result


# Per-tool "how to narrow this call" hints, surfaced in the truncation
# marker when a result exceeds the tool-output cap (#2805). These tools'
# output scales with cluster/repo state rather than the caller's params, so
# they are the at-risk set; anything not listed gets a generic hint and, in
# practice, never trips the cap because its output is bounded by design.
_TOOL_NARROW_HINTS: dict[str, str] = {
"get_service_logs": (
"lower `lines` or set a smaller `since_seconds` window, or fetch a single service at a time"
),
"get_container_logs": (
"lower `lines` or set a smaller `since_seconds` window, or target a single container"
),
"list_containers": (
"request a single pipeline/phase if the API supports it; otherwise "
"this result is proportional to the running container count"
),
"list_tasks": "use `limit` (and any status/phase filter) to page results",
"list_checkpoints": "use `limit` + `cursor` pagination or add filters",
"search_checkpoints": "use `limit` + `cursor` pagination or a narrower query",
"list_agent_local_commits": "target a single agent/branch or use `limit`",
}


logger = get_logger("orchestrator.mcp_tools")

Expand Down Expand Up @@ -1147,10 +1177,21 @@ def handle_tool_call(self, tool_name: str, arguments: dict[str, Any]) -> dict[st
return {"error": f"Unknown tool: {tool_name}"}

try:
return handler(arguments)
result = handler(arguments)
except Exception as e:
logger.error("Tool call failed", tool=tool_name, error=str(e))
return {"error": str(e)}
# Bound the result before mcp_server.py serializes it across the
# operator's Agent SDK 1 MB reader buffer (#2805). Oversized output
# is replaced with a head-preview marker naming how to narrow the
# call; bounded tools never trip this.
if isinstance(result, dict):
return cap_result_dict(
result,
tool=tool_name,
narrow_hint=_TOOL_NARROW_HINTS.get(tool_name),
)
return result

def _make_request(
self,
Expand Down
34 changes: 34 additions & 0 deletions orchestrator/tests/test_mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -3043,3 +3043,37 @@ def test_rebuild_and_rollout_wait_default_false(self):
tools_by_name = {t["name"]: t for t in PIPELINE_TOOLS}
props = tools_by_name["rebuild_and_rollout"]["inputSchema"]["properties"]
assert props["wait"]["default"] is False


class TestToolOutputCap:
"""Output-size caps (#2805): handle_tool_call must bound any result
before mcp_server.py serializes it across the operator's 1 MB SDK
reader buffer."""

def test_oversized_result_truncated_to_marker(self, handler):
# A list_containers result proportional to a huge cluster.
huge = {"containers": [{"id": f"c{i}", "log": "x" * 200} for i in range(20000)]}
handler._handle_list_containers = lambda args: huge # type: ignore[assignment]

result = handler.handle_tool_call("list_containers", {})

assert result["_egg_truncated"] is True
assert result["tool"] == "list_containers"
assert len(json.dumps(result).encode("utf-8")) <= 200 * 1024
# The narrow-hint for this tool is surfaced in the marker note.
assert "container" in result["note"]

def test_small_result_passes_through(self, handler):
small = {"containers": [{"id": "c1"}]}
handler._handle_list_containers = lambda args: small # type: ignore[assignment]

result = handler.handle_tool_call("list_containers", {})
assert result == small

def test_error_dict_not_inflated(self, handler):
def boom(args):
raise RuntimeError("kaboom")

handler._handle_list_containers = boom # type: ignore[assignment]
result = handler.handle_tool_call("list_containers", {})
assert result == {"error": "kaboom"}
29 changes: 27 additions & 2 deletions sandbox/egg_agent_tools/tools/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
from collections.abc import Callable
from typing import Any

from egg_tool_output import cap_text, spill_to_file

from egg_agent_tools.handlers.errors import GatewayError, HandlerError

# Prefer the structured logger used by shared/egg_agent/client.py so
Expand Down Expand Up @@ -53,11 +55,16 @@ def _format_error(exc: BaseException) -> str:
return f"{type(exc).__name__}: {exc}"


def _success_payload(response: dict[str, Any]) -> dict[str, Any]:
def _success_payload(response: dict[str, Any], tool_name: str | None = None) -> dict[str, Any]:
try:
text = json.dumps(response, default=str)
except Exception:
text = str(response)
# Defense-in-depth (#2805): bound the payload before it crosses the
# Agent SDK's 1 MB JSON reader buffer. Oversized output is replaced with
# a structured head-preview marker telling the agent how to narrow the
# call. Bounded/paginated tools never trip this.
text = cap_text(text, tool=tool_name)
return {"content": [{"type": "text", "text": text}]}


Expand All @@ -71,13 +78,22 @@ def _error_payload(exc: BaseException) -> dict[str, Any]:
async def invoke_handler(
handler: Callable[[dict[str, Any]], dict[str, Any]],
args: dict[str, Any],
*,
tool_name: str | None = None,
spill: bool = False,
) -> dict[str, Any]:
"""Run ``handler(args)`` in a thread and wrap the result for the SDK.

The handler is expected to be synchronous (most of ours are thin
wrappers around urllib). If the handler raises, the error is
serialised into an ``is_error`` SDK tool-result rather than
propagated — a gateway flake must never crash the agent loop.

Output is bounded before it crosses the Agent SDK's 1 MB JSON reader
buffer (#2805). When ``spill`` is set (large, unpaginated content such
as a full checkpoint transcript), an oversized result is written to a
file the agent can re-``Read``/``grep`` and replaced with a small
preview descriptor; otherwise it is truncated to a head-preview marker.
"""
try:
response = await asyncio.to_thread(handler, args or {})
Expand All @@ -95,4 +111,13 @@ async def invoke_handler(
exc,
)
return _error_payload(exc)
return _success_payload(response)
name = tool_name or getattr(handler, "__name__", None)
if spill:
try:
text = json.dumps(response, default=str)
except Exception:
text = str(response)
descriptor = spill_to_file(text, tool=name or "tool")
if descriptor is not None:
return _success_payload(descriptor, name)
return _success_payload(response, name)
6 changes: 5 additions & 1 deletion sandbox/egg_agent_tools/tools/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ async def checkpoint_list(args: dict[str, Any]) -> dict[str, Any]:
_SHOW_SCHEMA,
)
async def checkpoint_show(args: dict[str, Any]) -> dict[str, Any]:
return await invoke_handler(handlers.checkpoint_show, args)
# A single checkpoint is a full agent transcript — unpaginated and often
# MB-scale, with the relevant detail anywhere in it. Spill an oversized
# result to a file the agent can Read/grep rather than truncating the
# tail away (#2805).
return await invoke_handler(handlers.checkpoint_show, args, spill=True)


@tool(
Expand Down
205 changes: 205 additions & 0 deletions shared/egg_tool_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
"""Tool-output size caps for egg-owned MCP tools (issue #2805).

The Claude Agent SDK message reader has a hard 1 MB JSON buffer; a tool
result that exceeds it kills the agent with exit 255 (#2804). #2810 made
that crash observable and terminal, but the *prevention* — never producing
an oversized payload in the first place — lives here.

This module is the shared helper referenced by #2805's "consistent across
tools" requirement. It is deliberately a flat, stdlib-only module (no
package ``__init__`` side effects, no ``claude_agent_sdk`` import) so both
sides of the boundary can import it once ``shared/`` is on ``sys.path``:

* the **orchestrator** MCP server (operator-facing tools in
``orchestrator/mcp_tools.py``), and
* the **sandbox** agent ``@tool`` wrappers
(``sandbox/egg_agent_tools/tools/_common.py``).

Two strategies are exposed:

* :func:`cap_result_dict` / :func:`cap_text` — *truncate + structured
marker*. The tail is replaced with a JSON object that names what was cut
and how to narrow the call. Simple; the right fit for paginated or
structured tools where a head preview plus a "narrow it" hint is enough.
* :func:`spill_to_file` — *write full result to disk + return a preview*.
Mirrors Claude Code's own ``Bash`` tool (inline preview, full output
spilled to a file the model can re-``Read`` / ``grep``). The right fit
for large, unpaginated raw content (e.g. a full checkpoint transcript)
where the tail matters and truncation would lose it. Only usable when
the caller and the reader share a filesystem (in-sandbox agent tools),
so the orchestrator MCP server uses truncation only.
"""

from __future__ import annotations

import json
import os
import tempfile
import uuid
from typing import Any

# Default cap, well under the SDK's 1 MB reader buffer so the serialized
# result still has headroom for the surrounding SDK/MCP framing. Override
# with ``EGG_TOOL_OUTPUT_CAP_BYTES`` (issue #2805 "configurable").
DEFAULT_CAP_BYTES = 100 * 1024

# Reserve for the non-preview marker fields so the assembled marker still
# fits under the cap; the preview is then shrunk to fit if needed.
_MARKER_RESERVE_BYTES = 2048

# Sentinel keys so callers/tests can recognize a capped payload.
TRUNCATION_KEY = "_egg_truncated"
SPILL_KEY = "_egg_output_spilled"


def cap_bytes_from_env(default: int = DEFAULT_CAP_BYTES) -> int:
"""Resolve the configured cap, falling back to ``default`` on bad input."""
raw = os.environ.get("EGG_TOOL_OUTPUT_CAP_BYTES")
if not raw:
return default
try:
value = int(raw)
except TypeError, ValueError:
return default
return value if value > 0 else default


def _utf8_len(text: str) -> int:
return len(text.encode("utf-8"))


def _truncation_marker(
text: str,
*,
cap_bytes: int,
tool: str | None,
narrow_hint: str | None,
) -> dict[str, Any]:
"""Build a structured marker dict that fits under ``cap_bytes`` serialized.

The preview is the head of ``text`` shrunk (by bytes, re-checking the
serialized size) until the whole marker fits — robust to JSON escape
expansion of the preview.
"""
original_bytes = _utf8_len(text)
hint = narrow_hint or (
"narrow the call (e.g. a smaller limit/lines window, a more "
"specific filter, or pagination) and retry"
)
note = (
f"Result was {original_bytes} bytes; it exceeded the {cap_bytes}-byte "
"tool-output cap and was truncated to avoid the Agent SDK 1 MB "
"message-buffer crash (#2804/#2805). Only the head is shown below — "
f"to see the rest, {hint}."
)
budget = max(cap_bytes - _MARKER_RESERVE_BYTES, 256)
preview = text.encode("utf-8")[:budget].decode("utf-8", errors="ignore")
marker: dict[str, Any] = {
TRUNCATION_KEY: True,
"tool": tool,
"original_bytes": original_bytes,
"cap_bytes": cap_bytes,
"note": note,
"preview": preview,
}
# Shrink the preview until the serialized marker fits. JSON-escaping can
# expand the preview past the byte budget, so check the real size.
while _utf8_len(json.dumps(marker, default=str)) > cap_bytes and preview:
preview = preview[: len(preview) // 2]
marker["preview"] = preview
return marker


def cap_text(
text: str,
*,
tool: str | None = None,
narrow_hint: str | None = None,
cap_bytes: int | None = None,
) -> str:
"""Cap an already-serialized text payload.

Returns ``text`` unchanged when it is within the cap, otherwise a JSON
string holding the truncation marker (head preview + how to narrow).
"""
limit = cap_bytes if cap_bytes is not None else cap_bytes_from_env()
if _utf8_len(text) <= limit:
return text
marker = _truncation_marker(text, cap_bytes=limit, tool=tool, narrow_hint=narrow_hint)
return json.dumps(marker, default=str)


def cap_result_dict(
result: dict[str, Any],
*,
tool: str | None = None,
narrow_hint: str | None = None,
cap_bytes: int | None = None,
) -> dict[str, Any]:
"""Cap a result *dict* by its serialized size.

Returns ``result`` unchanged when within the cap, otherwise the
truncation marker dict (a small, well-formed replacement). Used at the
orchestrator MCP chokepoint, where the result is re-serialized by the
server; the marker dict keeps that serialization small.
"""
limit = cap_bytes if cap_bytes is not None else cap_bytes_from_env()
try:
text = json.dumps(result, default=str)
except TypeError, ValueError:
text = str(result)
if _utf8_len(text) <= limit:
return result
return _truncation_marker(text, cap_bytes=limit, tool=tool, narrow_hint=narrow_hint)


def spill_to_file(
text: str,
*,
tool: str,
preview_lines: int = 50,
cap_bytes: int | None = None,
spill_dir: str | None = None,
) -> dict[str, Any] | None:
"""Spill an oversized payload to a file and return a preview descriptor.

Returns ``None`` when ``text`` is within the cap (caller should use the
payload as-is). Otherwise writes the full ``text`` to a file the agent
can re-read with ``Read`` (offset/limit) or ``grep`` via ``Bash``, and
returns ``{output_path, total_bytes, preview, ...}``.

Only appropriate when the caller and the agent share a filesystem
(in-sandbox tools). On any write failure, returns ``None`` so the
caller falls back to truncation rather than failing the tool call.
"""
limit = cap_bytes if cap_bytes is not None else cap_bytes_from_env()
total_bytes = _utf8_len(text)
if total_bytes <= limit:
return None

target_dir = spill_dir or tempfile.gettempdir()
path = os.path.join(target_dir, f"egg-tool-out-{tool}-{uuid.uuid4().hex}.txt")
try:
with open(path, "w", encoding="utf-8") as fh:
fh.write(text)
except OSError:
return None

preview = "\n".join(text.splitlines()[:preview_lines])
# Keep the preview itself under the cap (a single huge line can blow it).
preview = cap_text(preview, tool=tool, cap_bytes=limit)
return {
SPILL_KEY: True,
"tool": tool,
"output_path": path,
"total_bytes": total_bytes,
"cap_bytes": limit,
"note": (
f"Result was {total_bytes} bytes (over the {limit}-byte tool-output "
"cap), so the full output was written to `output_path` to avoid the "
"Agent SDK 1 MB buffer crash (#2804/#2805). Read it with the `Read` "
"tool (use `offset`/`limit`) or `grep` it via `Bash`. Only the first "
f"{preview_lines} lines are inlined below."
),
"preview": preview,
}
Loading
Loading