Skip to content

fix(mcp): tool results are duplicated when a server mirrors structuredContent as compact JSON - #169180

Merged
RomneyDa merged 1 commit into
openclaw:mainfrom
xilopaint:fix/mcp-structured-mirror-proof
Oct 11, 2026
Merged

RomneyDa merged 1 commit into
openclaw:mainfrom
xilopaint:fix/mcp-structured-mirror-proof

Conversation

@xilopaint

Copy link
Copy Markdown
Contributor

Closes #169121
Related: #169135

What Problem This Solves

Fixes: an MCP tool result is sent to the model twice when the server mirrors structuredContent as compact (or differently ordered) JSON instead of the exact pretty-printed form.

User Impact

User impact: tool results from such MCP servers no longer double context usage or get spilled to files just because of the duplicate. Recovery text and JSON for a different value are still kept.

Why This Change Was Made

This carries #169135 forward with the real-behavior proof ClawSweeper requested there. The code is @jipeng6036-del's commit, unchanged and with its authorship kept, rebased on current main. I reported #169121 and had prepared an equivalent fix when #169135 appeared. That PR is blocked only on proof, and this is the author's first PR here, so I'm adding the proof in a PR body that I can update. If you'd rather land #169135 once its author copies the evidence below, please close this one.

The change itself: both mirror filters (agent projection in src/agents/mcp-content.ts and node-host bounding in src/node-host/invoke-mcp-result.ts) only dropped a text block that was byte-identical to JSON.stringify(structuredContent, null, 2). They now share a matcher that keeps that fast path and otherwise treats a text block as the mirror only when it parses as complete JSON with the same stable-stringified value. Parse failures keep the block.

Evidence

Real behavior through the shipped Gateway and node-host flows. I used a disposable Gateway and a paired headless node (openclaw node run) on loopback. The model was a local OpenAI-compatible mock that calls the MCP tool and logs the exact tool-result text the agent sends back to it. The MCP server is a stdio fixture that returns:

  • structuredContent: {"answer":42,"items":[1,2],"query":"proof"}
  • text blocks: a compact mirror, a reordered mirror, distinct JSON {"answer":41}, and the guidance text authentication expired; run login

The same tool was configured on both paths: Gateway mcp.servers.mirror, reached as mirror__lookup, and node nodeHost.mcp.servers.nodemirror, reached as nodemirror_lookup through mcp.tools.call.v1. The turns ran with openclaw agent --agent main --message "Call the lookup tool." --json.

Runtime used and its limit. The runtime was the official [email protected] npm package. "Before" is that package unmodified. "After" applies this PR's change to the two compiled chunks: mcp-content-*.mjs for the agent projection, and the chunk with boundMcpToolResultPayload for node-host bounding. I could not build main here, because tsdown needs about 4.7 GB of RAM and this host runs production agents. Between v2026.10.1 and this PR's base, src/agents/mcp-content.ts is identical. src/node-host/invoke-mcp-result.ts differs only in unrelated byte-limit checks.

Tool result received by the model (\n shown as line breaks):

Gateway MCP (mirror__lookup)

Before (2026.10.1):

structuredContent:
{
  "answer": 42,
  "items": [
    1,
    2
  ],
  "query": "proof"
}
{"answer":42,"items":[1,2],"query":"proof"}
{"query":"proof","items":[1,2],"answer":42}
{"answer":41}
authentication expired; run login

After (with this change):

structuredContent:
{
  "answer": 42,
  "items": [
    1,
    2
  ],
  "query": "proof"
}
{"answer":41}
authentication expired; run login
Node-hosted MCP (nodemirror_lookup via node.invoke)

Before (2026.10.1, node and Gateway unmodified): same as Gateway before, with both mirrors present.

Node-host change only (Gateway projection still unmodified): both mirrors are gone. This isolates boundMcpToolResultPayload.

structuredContent:
{
  "answer": 42,
  "items": [
    1,
    2
  ],
  "query": "proof"
}
{"answer":41}
authentication expired; run login

After (full change on node and Gateway): identical to the output above.

On both paths, the compact and reordered mirrors are removed, and the distinct JSON and recovery guidance remain.

Tests on this branch: pnpm exec vitest run src/agents/mcp-content.test.ts src/node-host/invoke-mcp-result.test.ts src/node-host/invoke.mcp.test.ts passes 3 files and 15 tests.

This PR body and the proof harness were prepared with an AI coding agent.

@clawsweeper

clawsweeper Bot commented Oct 11, 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 Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR removes compact and reordered JSON mirrors of structured MCP results while preserving distinct JSON and recovery guidance.

Example: An MCP server returns structuredContent {"answer":42}, text '{"answer":42}', and 'authentication expired; run login'.

  • Before: The model receives the structured result, its compact duplicate, and the guidance.
  • After: The model receives one structured result and the guidance.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with relevant shipped-flow traces and no actionable finding; proof qualifies modified release chunks rather than a full build of this head.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): Supplied model-input traces exercise configured Gateway MCP and paired-node calls through the shipped agent CLI, showing compact and reordered mirrors removed while distinct JSON and login guidance remain; the node-only run isolates producer filtering. Proof uses modified compiled chunks of official 2026.10.1 rather than a full build of the reviewed head, with relevant release-to-base source equivalence verified.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Some MCP servers send duplicate tool payloads to the model, wasting context and pushing otherwise inline results across downstream size thresholds.
Reason: Every production hunk serves the source-confirmed duplication defect without changing configuration, public APIs, or independent result content.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it fixes a current MCP duplication bug with a focused shared matcher, and no actionable defect was found.

Priority: P2
Reviewed head: c75580d93bf50f7a61aac317d2653dccd5271473

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway MCP projection converts server results into model content, while node-host bounding removes redundant content before applying transport limits; both boundaries now share the JSON mirror matcher.

flowchart TD
  A[MCP server result] --> B[Gateway MCP execution]
  A --> C[Node host payload bounding]
  C --> D[Node invoke response]
  D --> E[Shared result projection]
  B --> E
  F[JSON mirror matcher] --> C
  F --> E
  E --> G[Model tool result]
Loading

Technical review

Best possible solution:

Land the shared complete-JSON comparison at both existing boundaries while preserving independent content, payload priorities, and the original contributor's credit.

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

Current-main source deterministically retains compact JSON beside structured output, and the reporter supplies official-release before/after traces; no target code was executed during this review.

Is this the best way to solve the issue?

The shared matcher fixes the cause at both existing boundaries, compares complete JSON values, and preserves overlapping text that may contain recovery guidance.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Verified PR introduction: The pinned introduction replaces both exact pretty-JSON comparisons with one matcher that parses complete JSON and compares deterministic values; different values and parse failures remain. (src/agents/mcp-structured-mirror.ts:15, c75580d93bf5)
  • Current main retains the defect: Current main removes only text byte-identical to pretty JSON, retaining compact and reordered mirrors alongside canonical structured output; neither affected production owner changed between the merge base and fetched main. (src/agents/mcp-content.ts:128, 4e3818bab0fe)
  • Node transport priorities preserved: Mirror suppression still precedes aggregate text truncation and occurs only when structuredContent survives payload bounding; error status, limits, and truncation markers remain intact. (src/node-host/invoke-mcp-result.ts:44, c75580d93bf5)
  • Supplied shipped-flow proof: The full PR body records configured Gateway and paired-node calls through the shipped agent CLI, capturing model input before and after the change; the node-only modification separately isolates producer filtering. (c75580d93bf5)
  • Release proof context verified: Proof uses official 2026.10.1 with modified compiled chunks. Release-to-base comparison confirms identical agent projection and only two unrelated byte-limit check simplifications in node bounding. (src/node-host/invoke-mcp-result.ts:36, 8ab6ad102827)
  • Original recovery-text contract: Merged fix(mcp): preserve recovery text with structured results #125914 established preservation of independent text, media, error status, and structured-result priority; this PR explains extending recognition to complete equivalent JSON. (src/agents/mcp-content.ts, d33ba0015dcc)

Likely related people:

  • Peter Steinberger: Raw commit 407c8cd adds src/node-host/invoke-mcp-result.ts:14 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 407c8cdb3440; files: src/node-host/invoke-mcp-result.ts)
  • wangmiao0668000666: Raw commit 452c808 adds src/agents/mcp-content.ts:113 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 +33, Tests +55. Total +88 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 40 7 +33
Tests 2 55 0 +55
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 95 7 +88

Review metrics

Metric Value Why it matters
Production versus tests Production +33 net lines; tests +55 lines. The production growth centralizes comparison used by two existing boundaries; focused tests protect semantic deduplication and preservation of independent content.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #169121
Summary: The canonical issue describes the exact byte-equality defect; both open PRs carry its repair, and this PR adds shipped-flow evidence.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Affected MCP servers waste model context and can trigger unnecessary large-result handling, without evidence of a core outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-11T15:17:22.002Z sha e23785826e55070d35c9e4fc751cc33dbd25b3ae :: needs maintainer review before merge. :: none

Reviewed October 11, 2026, 3:28 PM ET / 19:28 UTC (Revision 2).

MCP servers that mirror structuredContent as compact JSON (or with a
different key order) had that text block sent to the model next to the
structuredContent block, doubling the payload. Treat a text block as the
mirror when it is complete JSON for the same value, in both the agent
projection and the node-host bounding. Other text, including JSON for a
different value, is still kept.

Fixes openclaw#169121
@RomneyDa
RomneyDa force-pushed the fix/mcp-structured-mirror-proof branch from e237858 to c75580d Compare October 11, 2026 19:22
@RomneyDa
RomneyDa merged commit 5270b03 into openclaw:main Oct 11, 2026
116 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…openclaw#169180)

MCP servers that mirror structuredContent as compact JSON (or with a
different key order) had that text block sent to the model next to the
structuredContent block, doubling the payload. Treat a text block as the
mirror when it is complete JSON for the same value, in both the agent
projection and the node-host bounding. Other text, including JSON for a
different value, is still kept.

Fixes openclaw#169121

Co-authored-by: jipeng6036-del <[email protected]>
hilsbos pushed a commit to hilsbos/openclaw that referenced this pull request Oct 22, 2026
…openclaw#169180)

MCP servers that mirror structuredContent as compact JSON (or with a
different key order) had that text block sent to the model next to the
structuredContent block, doubling the payload. Treat a text block as the
mirror when it is complete JSON for the same value, in both the agent
projection and the node-host bounding. Other text, including JSON for a
different value, is still kept.

Fixes openclaw#169121

Co-authored-by: jipeng6036-del <[email protected]>
(cherry picked from commit 5270b03)
Co-authored-by: RomneyDa <[email protected]>
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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

[Bug]: MCP structuredContent projection duplicates payload when server's text mirror is compact JSON

3 participants