Skip to content

fix(mcp): stop sending wrapped MCP results to the model twice - #196243

Merged
roboclaw-bot merged 6 commits into
mainfrom
openclaw/mcp-result-dedupe-compact
Nov 9, 2026
Merged

roboclaw-bot merged 6 commits into
mainfrom
openclaw/mcp-result-dedupe-compact

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #184031, #125914, #194934

What Problem This Solves

Fixes: MCP tool results reach the model twice, pretty-printed and re-escaped, when a server returns an array or scalar (wrapped as structuredContent: {"items": [...]} or FastMCP's {"result": ...}) alongside the bare value as text.

User Impact

User impact: agents that call MCP tools returning lists (channels, messages, members, files and similar) send roughly half as many tool-result tokens to the model, and the Tool Search output cap truncates real data later. Object results, recovery text and non-JSON text are unchanged.

Why This Change Was Made

The MCP spec requires structuredContent to be an object, so servers wrap non-object values under one key while the text block carries the bare value. The mirror matcher only recognized text that was JSON for the whole object, so a bare array never matched and both copies reached the model. On top of that, structuredContent was rendered with two-space indentation and the dispatch_action envelope indented it again inside an escaped JSON string.

  • A text block is now the redundant mirror when it parses to a value equal to structuredContent, or, for a single-key structuredContent, equal to that key's only value (a plain-text block also matches when that value is the same string). The node-host bounding path uses the same matcher, so both call sites stay consistent.
  • The kept copy is structuredContent, as before: it is what a declared outputSchema describes, it is already what details.structuredContent and Code Mode guests receive, and existing tests and the recovery-text guarantee from fix(mcp): preserve recovery text with structured results #125914 already treat it as the canonical copy. Any text that is not an equal mirror (different JSON, non-JSON, multi-key wrappers) is still sent.
  • structuredContent is serialized as compact key-sorted JSON (still deterministic for prompt caching and loop-outcome digests), and the dispatch_action envelope is serialized compactly, the same way Code Mode control results already are. No information is dropped; only indentation is removed.

Formatting decision (agreed with @jalehman): pretty-printing belongs in the UI, not in model-facing or server-side serialization. Raw tool results are rarely displayed unless someone digs in, while every indentation byte is paid by the model on every turn and counts against the Tool Search output cap. So model-facing MCP results and the dispatch_action envelope are compact, and any readable formatting should happen at display time.

Checked dependents of the pretty form: no snapshots depend on it; digestToolOutcome hashes whatever is delivered and stays deterministic; Tool Search budget fitting measures the serialized text it delivers. The one surface that benefited from the indentation is the Control UI tool-output panel, which shows the raw captured text in a wrapping <pre> with Raw/Copy/Download and keeps non-exec output literal by design: direct (non-Tool-Search) MCP calls now show structuredContent: followed by one line of JSON, and the dispatch_action envelope loses its outer indentation (the MCP text inside the envelope was already a single escaped string before this change). Display-time JSON formatting for those tool outputs is left as a follow-up rather than kept as server-side indentation; this PR has no UI change. Tool Search catalog entries (compactToolSearchCatalogEntry) and tool_search/tool_describe output are unchanged.

Evidence

Real CLI run on an AWS Crabbox, before vs. after. Provider aws, lease cbx_fb8edff4dfb8 (c7a.8xlarge, eu-west-1), run run_336e0d1d8cb1f6442c7cb742b1e6cef6; lease released afterwards. On one box, OpenClaw was built from source twice: current main d3b571f8163c (before) and the same commit plus this PR's diff (after). Each build ran openclaw agent --local against the real garrytan/g-harness-evals world MCP server (1c26ae409de0, trial t-prof, split dev, fresh world per build), registered with openclaw mcp set world over streamable HTTP, using the harness's own harnesses/openclaw/config/openclaw.json. The model side was a scripted Anthropic Messages endpoint that replays the same sequence for both builds (tool_search, then dispatch_action for world__list_channels, world__read_channel, world__list_members, world__list_files, world__read_file, world__clock_now) and records every request body. Both agent runs exited 0 with 8 model requests each, and the world server returned byte-identical results to both builds.

Measured on the final recorded request (bytes of each model-visible tool_result; "copies" counts a payload value that occurs exactly once in the server's own text):

Tool Server text (B) Before: tool_result (B) Before: copies After: tool_result (B) After: copies Change
world__list_channels 2,242 6,408 2 2,534 1 −60.5%
world__read_channel 4,899 12,408 2 5,297 1 −57.3%
world__list_members 4,017 10,694 2 4,409 1 −58.8%
world__list_files 2,743 7,356 2 3,125 1 −57.5%
world__read_file 531 1,129 1 1,014 1 −10.2%
world__clock_now 188 760 1 650 1 −14.5%
6 world tools 14,620 38,755 17,029 −56.1%
Request bytes Before After Change
Final request (all 6 results in history) 111,156 84,908 −23.6%
All 8 model requests of the turn 706,550 589,369 −16.6%

The four array tools ({"items": [...]} wrappers) were sent twice before and once after; the two object tools were already deduplicated and only lose indentation. After the change, model-visible size is 1.16× the server's own text (the remaining overhead is the {tool, result} envelope, string escaping and the external-content boundary).

Excerpts from the recorded request bodies (final request of each build)

Content blocks inside the dispatch_action result for world__list_channels (first 90 characters of each block):

before (2 blocks):
"structuredContent:\n{\n  \"items\": [\n    {\n      \"id\": \"C3SPE8A5OO7\",\n      \"kind\": \"random\"," … (2808 chars)
"[\n {\n  \"id\": \"C3SPE8A5OO7\",\n  \"name\": \"#central-random\",\n  \"kind\": \"random\",\n  \"purpose\": " … (2242 chars)
after (1 block):
"structuredContent:\n{\"items\":[{\"id\":\"C3SPE8A5OO7\",\"kind\":\"random\",\"members\":[\"hollis.mbeki\"" … (1822 chars)

Complete world__clock_now envelope as sent to the model (inside the external-content boundary), before (453 chars):

{
  "tool": {
    "id": "mcp:world:world__clock_now",
    "name": "world__clock_now",
    "source": "mcp"
  },
  "result": {
    "content": [
      {
        "type": "text",
        "text": "structuredContent:\n{\n  \"advanced_seconds\": 0,\n  \"now\": \"2026-10-14T09:00:00-05:00\",\n  \"offset_minutes\": -300,\n  \"reference\": \"2026-10-14T09:00:00-05:00\",\n  \"time_zone\": \"America/Chicago\",\n  \"today\": \"2026-10-14\"\n}"
      }
    ]
  }
}

After (343 chars):

{"tool":{"id":"mcp:world:world__clock_now","name":"world__clock_now","source":"mcp"},"result":{"content":[{"type":"text","text":"structuredContent:\n{\"advanced_seconds\":0,\"now\":\"2026-10-14T09:00:00-05:00\",\"offset_minutes\":-300,\"reference\":\"2026-10-14T09:00:00-05:00\",\"time_zone\":\"America/Chicago\",\"today\":\"2026-10-14\"}"}]}}

Final request bodies: before sha256:e3a3db81b54607d3f66d10891553fa4b995632ddc0e1f822fb089c376c2d32e6, after sha256:59d865d50987d2b8130941e370fbf889cd71368c28473f07beeb3148c9715a95. The world data is the harness's synthetic dev split.

Focused tests (pnpm test <files> --maxWorkers=1): src/agents/mcp-content.test.ts, src/node-host/invoke-mcp-result.test.ts, src/agents/tool-search.mcp-error.test.ts (22 passed), plus src/agents/tool-search.test.ts, tool-search.agent-loop.test.ts, tool-search.metadata.test.ts, code-mode.result-budget.test.ts, src/node-host/invoke.mcp.test.ts (all passed). The cases are table-driven and cover {items}/{result} wrappers, pretty/compact/reordered mirrors, scalar and plain-string wrapped values, multi-key structuredContent (text kept), non-mirror recovery text (kept), text too deeply nested to compare (kept), the unchanged unprojectable-depth path, the node-host bounding path, and a materialized MCP tool called through dispatch_action (one copy, no indentation). With the production files reverted to main, 15 of the 22 fail.

Test-line budget: the new cases are folded into the existing mirror table; the remaining net growth (+37 lines of regression coverage for the behavior above) is recorded in config/test-lines-allocations/mcp-wrapped-structured-mirror.txt. check-test-lines-ratchet passes against current main with slack 0.

Checks: pnpm check:changed: typecheck (core + core tests), lint, format, line-cap, test-lines and other guards pass. The dead-export scan fails on two unrelated exports present on the base commit (src/config/skill-library-tool-split-migration.ts, ui/src/lib/config/config-saved-notice.ts).

CI: all checks pass on 255127804f52 (60 passed, 0 failed, openclaw/ci-gate green). That head merges current main (7554b069a703): an earlier run failed check-lint-core-2 on a no-shadow error in ui/src/e2e/sidebar-rail-alignment.e2e.test.ts, a file this PR does not touch; main fixed it after that run's merge ref was built, and the file lints clean on current main. The PR diff against main is unchanged (the same 7 files).

Review: local autoreview (Codex gpt-6.1-sol, branch mode against d3b571f8163c, P1 coverage): scoped-clean, no findings. Hosted ClawSweeper review of 3c2b53e90eb5: no findings, nothing required before merge. Later heads only consolidate tests, add the allocation record and merge main; production code is unchanged.

Not covered: no paid-model run (the scripted endpoint isolates request bytes from model behavior). Full raw request captures for both builds are retained with the proof kit on the team host; the excerpts above are taken from them.

Requested by @jalehman.

Work sessions

Linked for team reference; these sessions aren’t public.

Worked on by

roboclaw-bot and others added 2 commits November 9, 2026 20:19
MCP servers that return an array or scalar wrap it in a single-key
structuredContent object ({"items": [...]}, FastMCP's {"result": ...})
while the text block carries the bare value. The mirror matcher only
recognized text that was JSON for the whole object, so both copies
reached the model. Treat the bare wrapped value as the mirror too, and
serialize the kept structuredContent and the dispatch_action envelope
without indentation.

Co-authored-by: jalehman <[email protected]>
Co-authored-by: GrahamMcBain <[email protected]>
Worked on by:
- @jalehman
- @GrahamMcBain

Co-authored-by: jalehman <[email protected]>
Co-authored-by: GrahamMcBain <[email protected]>
OpenClaw-Publication: 373ac188-17fd-4598-b837-49b1e4605f13
@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Nov 9, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 9, 2026
@clawsweeper

clawsweeper Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR removes redundant text mirrors of single-key structured MCP results and compacts model-facing result serialization.

Example: An MCP tool returns structuredContent {"items":[{"id":"C1","name":"general"}]} alongside text '[{"id":"C1","name":"general"}]'.

  • Before: The model receives the channel data twice, with additional indentation.
  • After: The model receives one compact structured copy.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused, source-supported repair with no actionable defect found; direct behavior evidence is limited to the published run report and measurements.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored exemption applies; the body reports real CLI calls through the world MCP server and recorded model requests, while the private raw captures were not inspected.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Wrapped MCP lists and scalars appear twice in model context and reach output truncation sooner.
Reason: The source demonstrates redundant payloads, and the maintainer-authored direction explicitly accepts compact formatting.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: current main still duplicates wrapped MCP values, and the focused patch addresses that boundary without a concrete correctness finding; it remains a draft.

Priority: P2
Reviewed head: 3c2b53e90eb5516169c6cb1411870c5c96a74b12

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported CLI comparison includes request-size measurements, but its raw before/after request captures are not publicly attached for direct inspection.
Agent review details

How this fits together

MCP result projection converts server content into agent text and images; node-host bounding shares its mirror matcher, and Tool Search wraps the projected result for the model.

flowchart LR
  A[MCP server result] --> B[Shared mirror matcher]
  B --> C[Node payload bounding]
  B --> D[Agent result projection]
  C --> D
  D --> E[Tool Search envelope]
  E --> F[Model request]
Loading

Technical review

Best possible solution:

Extend the existing shared matcher while retaining canonical structured content, unequal recovery text, and the existing output-budget owner.

Do we have a high-confidence way to reproduce the issue?

The verified server returns bare-array text plus an items wrapper, and current-main matching retains both; no reproduction was run during this read-only review.

Is this the best way to solve the issue?

The patch repairs the shared comparison boundary and reuses existing compact serialization, preserving distinct content without new machinery.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d53921ac1424.

Provenance checked

  • Shared mirror matching keeps the original intent (5270b03: Recognize compact and reordered complete-object mirrors while preserving different JSON and recovery guidance.)
  • Structured-result rendering changes intended behavior with a stated reason (452c808: Handle deeply nested structured results without crashing projection; the patch retains that failure handling and explains removing indentation.)
  • Tool Search envelope formatting keeps the original intent (4cb9f12: Carry network-content provenance through control results; compact serialization leaves the same protection and provenance path intact.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit afd0f78 adds src/agents/mcp-content.ts:112 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: afd0f78383c0; files: src/agents/mcp-content.ts)
  • wangmiao0668000666: Raw commit 452c808 adds src/agents/mcp-content.ts:120 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 452c808d5b1b; files: src/agents/mcp-content.ts)

PR surface

Source +8, Tests +82. Total +90 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 25 17 +8
Tests 3 87 5 +82
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 112 22 +90

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: Duplicate MCP payloads waste model context and consume the Tool Search result cap, with limited subsystem scope.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Duplicate MCP payloads waste model context and consume the Tool Search result cap, with limited subsystem scope.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Attach sanitized before/after model-request excerpts showing the wrapped payload once after the fix.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 9, 2026, 3:55 PM ET / 20:55 UTC.

@roboclaw-bot
roboclaw-bot marked this pull request as ready for review November 9, 2026 21:01
roboclaw-bot and others added 4 commits November 9, 2026 21:18
Fold the new structuredContent mirror cases into the existing table and
record the remaining regression coverage in a test-lines allocation.

Co-authored-by: jalehman <[email protected]>
Co-authored-by: GrahamMcBain <[email protected]>
Worked on by:
- @jalehman
- @GrahamMcBain

Co-authored-by: jalehman <[email protected]>
Co-authored-by: GrahamMcBain <[email protected]>
OpenClaw-Publication: a0f70cc3-f8ce-410f-9cfb-11ef245cbcd5
Worked on by:
- @jalehman
- @GrahamMcBain

Co-authored-by: jalehman <[email protected]>
Co-authored-by: GrahamMcBain <[email protected]>
OpenClaw-Publication: 641a27f3-c557-4935-b391-fa0e02470d2f
@roboclaw-bot
roboclaw-bot merged commit bdce9c8 into main Nov 9, 2026
127 checks passed
@roboclaw-bot
roboclaw-bot deleted the openclaw/mcp-result-dedupe-compact branch November 9, 2026 22:45
RomneyDa added a commit that referenced this pull request Nov 10, 2026
Release adaptation: complete the #196243 fixture cutover by expecting compact structured JSON and omitting only an exact mirrored description. Preserve real stdio, non-text, node metadata and error assertions.

The two original failures were reproduced. Both repaired assertions pass; the broader local batch retains eight unrelated HTTP transport failures for separate diagnosis. Focused types, type-aware core lint, formatting and independent review passed.

Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 12, 2026
Backport source bdce9c8.
Keep distinct recovery text while compacting model-visible MCP results.

Co-authored-by: jalehman <[email protected]>
Co-authored-by: GrahamMcBain <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit e746f06b22b8849e056b80a494e06e985b176532)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant