Repository navigation
fix(mcp): stop sending wrapped MCP results to the model twice - #196243
Conversation
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
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis 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"}]'.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherMCP 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +8, Tests +82. Total +90 across 6 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 9, 2026, 3:55 PM ET / 20:55 UTC. |
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
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]>
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)
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
structuredContentto 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,structuredContentwas rendered with two-space indentation and thedispatch_actionenvelope indented it again inside an escaped JSON string.structuredContent, or, for a single-keystructuredContent, 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.structuredContent, as before: it is what a declaredoutputSchemadescribes, it is already whatdetails.structuredContentand 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.structuredContentis serialized as compact key-sorted JSON (still deterministic for prompt caching and loop-outcome digests), and thedispatch_actionenvelope 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_actionenvelope are compact, and any readable formatting should happen at display time.Checked dependents of the pretty form: no snapshots depend on it;
digestToolOutcomehashes 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 showstructuredContent:followed by one line of JSON, and thedispatch_actionenvelope 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) andtool_search/tool_describeoutput are unchanged.Evidence
Real CLI run on an AWS Crabbox, before vs. after. Provider
aws, leasecbx_fb8edff4dfb8(c7a.8xlarge, eu-west-1), runrun_336e0d1d8cb1f6442c7cb742b1e6cef6; lease released afterwards. On one box, OpenClaw was built from source twice: current maind3b571f8163c(before) and the same commit plus this PR's diff (after). Each build ranopenclaw agent --localagainst the real garrytan/g-harness-evals world MCP server (1c26ae409de0, trialt-prof, splitdev, fresh world per build), registered withopenclaw mcp set worldover streamable HTTP, using the harness's ownharnesses/openclaw/config/openclaw.json. The model side was a scripted Anthropic Messages endpoint that replays the same sequence for both builds (tool_search, thendispatch_actionforworld__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):world__list_channelsworld__read_channelworld__list_membersworld__list_filesworld__read_fileworld__clock_nowThe 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_actionresult forworld__list_channels(first 90 characters of each block):Complete
world__clock_nowenvelope 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, aftersha256:59d865d50987d2b8130941e370fbf889cd71368c28473f07beeb3148c9715a95. The world data is the harness's syntheticdevsplit.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), plussrc/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 throughdispatch_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-ratchetpasses 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-gategreen). That head merges current main (7554b069a703): an earlier run failedcheck-lint-core-2on ano-shadowerror inui/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 againstd3b571f8163c, P1 coverage): scoped-clean, no findings. Hosted ClawSweeper review of3c2b53e90eb5: 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