From 088189683c7441c6cbbe686cad59ee936980909c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=93=88=E5=9F=BA=E7=B1=B3?= <140241684+BlueX888@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:57:48 +0800 Subject: [PATCH] fix(mcp): redact inline base64 payloads from tool error messages (#8412) * fix(mcp): redact inline base64 payloads from tool error messages (#8326) * fix(mcp): redact base64url payloads and update the guide * fix(mcp): bound the data-URI params window The data: branch rescanned a comma-free run from every start position, so a crafted multi-MB error string cost quadratic CPU on the redaction path. Bound the params window to 200 characters (MIME types and parameters sit well below that) and cover the pathological input with a regression test. * docs(mcp): explain the bounded data-URI params window --- .../tool_error_handling_middleware.py | 23 +++- .../packages/harness/deerflow/mcp/AGENTS.md | 5 +- .../test_tool_error_handling_middleware.py | 126 ++++++++++++++++++ 3 files changed, 152 insertions(+), 2 deletions(-) diff --git a/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py index 28b8b27b76..169dc531ad 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py @@ -2,6 +2,7 @@ import asyncio import logging +import re import secrets from collections.abc import Awaitable, Callable, Iterable from typing import TYPE_CHECKING, override @@ -54,6 +55,26 @@ _TOOL_RESULT_CONTRACT = ( "These fields describe tool execution, not the truth of the data or completion of the task." ) +# langchain-mcp-adapters stringifies non-text error blocks for sse/http +# transports, so an MCP error's ToolException can carry an inline base64 or +# base64url payload: an image/file block's ``'base64': '...'`` field or a +# ``data:`` URI. +# Redact the payload before truncation, because the 500-character cap alone +# would leave a base64 prefix in the model-visible message and the checkpoint. +# Values below the threshold (a short diagnostic token) stay readable. +_INLINE_BASE64_MIN_CHARS = 64 +# Bound the params window: without it, a comma-free run with many `data:` starts rescans +# from every position and backtracks quadratically. MIME params sit far below 200. +_INLINE_BASE64_RE = re.compile( + rf"(?P(?:['\"]base64['\"]\s*:\s*['\"]|data:[^,\s]{{0,200}};base64,))[A-Za-z0-9+/=_-]{{{_INLINE_BASE64_MIN_CHARS},}}", + re.IGNORECASE, +) + + +def _redact_inline_base64(text: str) -> str: + """Replace inline base64 payloads in an exception string with ````.""" + return _INLINE_BASE64_RE.sub(r"\g", text) + def _stamp_task_exception_status(message: ToolMessage, *, tool_name: str, error: str) -> ToolMessage: """Stamp failed metadata on task exception wrappers produced here.""" @@ -143,7 +164,7 @@ class ToolErrorHandlingMiddleware(AgentMiddleware[AgentState]): def _build_error_message(self, request: ToolCallRequest, exc: Exception) -> ToolMessage: tool_name = str(request.tool_call.get("name") or "unknown_tool") tool_call_id = str(request.tool_call.get("id") or _MISSING_TOOL_CALL_ID) - detail = str(exc).strip() or exc.__class__.__name__ + detail = _redact_inline_base64(str(exc).strip() or exc.__class__.__name__) if len(detail) > 500: detail = detail[:497] + "..." diff --git a/backend/packages/harness/deerflow/mcp/AGENTS.md b/backend/packages/harness/deerflow/mcp/AGENTS.md index 295324641a..906c92ffde 100644 --- a/backend/packages/harness/deerflow/mcp/AGENTS.md +++ b/backend/packages/harness/deerflow/mcp/AGENTS.md @@ -61,7 +61,10 @@ make test-blocking-io - **Never put base64 payloads in text.** Unsupported content (inline audio) raises a recoverable tool error, and the stdio conversion reports an error result with no text block by content shape, never the payload. sse/http tools keep - `langchain-mcp-adapters`' conversion, which still stringifies that fallback. + `langchain-mcp-adapters`' conversion, which still stringifies that fallback; + `ToolErrorHandlingMiddleware` redacts inline `base64` fields and `data:` + payloads from tool error messages before truncation, so neither the + model-visible message nor the checkpoint carries the bytes. - **`ResourceLink` items do not become URL-sourced `file` blocks.** Chat Completions serialization rejects them, and a checkpointed block would break every later turn of the thread. diff --git a/backend/tests/test_tool_error_handling_middleware.py b/backend/tests/test_tool_error_handling_middleware.py index c5ba933721..04819d8e5e 100644 --- a/backend/tests/test_tool_error_handling_middleware.py +++ b/backend/tests/test_tool_error_handling_middleware.py @@ -1,3 +1,4 @@ +import base64 import posixpath import re import sys @@ -7,6 +8,7 @@ from types import ModuleType, SimpleNamespace import pytest from langchain.agents.middleware import AgentMiddleware from langchain_core.messages import ToolMessage +from langchain_core.tools import ToolException from langgraph.errors import GraphInterrupt from deerflow.agents.middlewares.tool_error_handling_middleware import ( @@ -696,6 +698,130 @@ def test_wrap_tool_call_uses_fallback_tool_call_id_when_missing(): assert result.status == "error" +def _adapter_image_error(payload: str) -> ToolException: + """The ToolException langchain-mcp-adapters raises for an image-only error. + + The ``sse``/``http`` path keeps the adapter's conversion, which falls back + to ``str(content)`` when an error result has no text block; that string + embeds the inline base64 payload. + """ + from langchain_mcp_adapters.tools import _convert_call_tool_result + from mcp.types import CallToolResult, ImageContent + + with pytest.raises(ToolException) as excinfo: + _convert_call_tool_result(CallToolResult(content=[ImageContent(type="image", data=payload, mimeType="image/png")], isError=True)) + return excinfo.value + + +def test_error_message_redacts_inline_base64_before_truncation(): + """A ~100 KB image-only MCP error becomes a short message without the payload.""" + payload = base64.b64encode(b"deerflow-inline-payload-" + bytes(range(256)) * 400).decode("ascii") + assert len(payload) > 100_000 + exc = _adapter_image_error(payload) + middleware = ToolErrorHandlingMiddleware() + req = _request(name="mcp_tool", tool_call_id="tc-img") + + def _boom(_req): + raise exc + + result = middleware.wrap_tool_call(req, _boom) + + assert "" in result.text + assert payload[:256] not in result.text + assert payload not in result.text + assert "image/png" in result.text + assert len(result.text) < 600 + + +# Encodes to "-_" in the URL-safe alphabet, so the payload only redacts once +# the pattern accepts base64url characters as well as standard base64. +_BASE64URL_PROBE = b"\xfb\xff" + + +@pytest.mark.parametrize("encode", [base64.b64encode, base64.urlsafe_b64encode], ids=["standard", "urlsafe"]) +@pytest.mark.parametrize("quote", ["'", '"']) +def test_error_message_redacts_python_and_json_base64_fields(quote, encode): + payload = encode(_BASE64URL_PROBE + b"field payload " * 20).decode("ascii") + detail = f"{{{quote}base64{quote}: {quote}{payload}{quote}}}" + middleware = ToolErrorHandlingMiddleware() + req = _request(name="mcp_tool", tool_call_id="tc-field") + + def _boom(_req): + raise ToolException(detail) + + result = middleware.wrap_tool_call(req, _boom) + + assert f"{quote}base64{quote}: {quote}{quote}" in result.text + assert payload[:64] not in result.text + + +@pytest.mark.parametrize("encode", [base64.b64encode, base64.urlsafe_b64encode], ids=["standard", "urlsafe"]) +def test_error_message_redacts_data_uri_payloads_case_insensitively(encode): + payload = encode(_BASE64URL_PROBE + b"svg payload " * 200).decode("ascii") + detail = f"render failed: DATA:IMAGE/SVG+XML;charset=utf-8;BASE64,{payload}" + middleware = ToolErrorHandlingMiddleware() + req = _request(name="web_fetch", tool_call_id="tc-data-uri") + + def _boom(_req): + raise ToolException(detail) + + result = middleware.wrap_tool_call(req, _boom) + + assert "DATA:IMAGE/SVG+XML;charset=utf-8;BASE64," in result.text + assert payload[:64] not in result.text + + +def test_error_message_does_not_backtrack_quadratically_on_comma_free_text(): + r"""The data-URI params window is bounded, so many `data:` starts stay linear. + + `[^,\s]*` rescanned to the end of one comma-free run for every start + position; 160K characters of crafted text took seconds before the bound. + """ + import time + + middleware = ToolErrorHandlingMiddleware() + req = _request(name="web_fetch", tool_call_id="tc-adversarial") + detail = "data:x;y" * 20_000 + + def _boom(_req): + raise ToolException(detail) + + started = time.perf_counter() + result = middleware.wrap_tool_call(req, _boom) + elapsed = time.perf_counter() - started + + assert elapsed < 2.0, f"redaction took {elapsed:.2f}s on a 160K comma-free string" + assert "data:x;y" in result.text + + +def test_error_message_leaves_plain_text_unchanged(): + middleware = ToolErrorHandlingMiddleware() + req = _request(name="web_search", tool_call_id="tc-plain") + + def _boom(_req): + raise ToolException("server refused: bad token") + + result = middleware.wrap_tool_call(req, _boom) + + assert result.content == "Error: Tool 'web_search' failed with ToolException: server refused: bad token. Continue with available context, or choose an alternative tool." + + +def test_error_message_keeps_base64_values_below_the_redaction_threshold(): + """Payloads shorter than 64 characters cannot be a meaningful inline image + or file, so short diagnostics that mention a small base64 value survive.""" + short_value = base64.b64encode(b"short").decode("ascii") + middleware = ToolErrorHandlingMiddleware() + req = _request(name="mcp_tool", tool_call_id="tc-short") + + def _boom(_req): + raise ToolException(f"{{'type': 'image', 'base64': '{short_value}'}}") + + result = middleware.wrap_tool_call(req, _boom) + + assert short_value in result.text + assert "" not in result.text + + def test_wrap_tool_call_reraises_graph_interrupt(): middleware = ToolErrorHandlingMiddleware() req = _request(name="ask_clarification", tool_call_id="tc-int")