Skip to content

fix(mcp): guard stdio stdout frame parsing against oversized-buffer crash - #119379

Merged
Takhoffman merged 1 commit into
openclaw:mainfrom
yetval:fix/mcp-stdout-oversized-frame-crash
Aug 5, 2026
Merged

Takhoffman merged 1 commit into
openclaw:mainfrom
yetval:fix/mcp-stdout-oversized-frame-crash

Conversation

@yetval

@yetval yetval commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Summary

An MCP stdio server whose stdout frame exceeds the SDK ReadBuffer 10 MiB cap crashes the whole OpenClaw host process, taking down every concurrent session with it. The frame is emitted by the server subprocess, but its size is driven by tool-result payload data (file contents, a fetched page, a database row) that a lower-privileged message sender can influence, not by the operator who chose which server to run.

Root cause

src/agents/mcp-stdio-transport.ts handles child stdout with an unguarded synchronous call into the SDK read buffer:

// before
child.stdout?.on("data", (chunk: Buffer) => {
  this.readBuffer.append(chunk);
  this.processReadBuffer();
});

ReadBuffer.append throws ReadBuffer exceeded maximum size of 10485760 bytes synchronously once the accumulated buffer passes STDIO_DEFAULT_MAX_BUFFER_SIZE (10 MiB). processReadBuffer has its own inner try/catch around readMessage, but append is called outside it. The throw runs inside the Node stream data callback, on a different stack from the per-server isolation the MCP runtime builds, so nothing catches it. It escapes as an uncaughtException and terminates the host process. There is no MCP server quarantine that survives the exit (serverBackoff is an in-memory map that dies with the process), so this is a deterministic, remotely influenced gateway kill.

Fix

Wrap the two calls in the same guard the upstream SDK StdioClientTransport uses for this exact code:

// after
child.stdout?.on("data", (chunk: Buffer) => {
  try {
    this.readBuffer.append(chunk);
    this.processReadBuffer();
  } catch (error) {
    this.onerror?.(error instanceof Error ? error : new Error(String(error)));
    void this.close();
  }
});

The oversized frame is now reported through onerror and the transport closes, which the MCP runtime already handles as a normal server disconnect. The host stays up.

Why this is the right boundary

The transport owns the child stdio read path, and this file already guards its sibling surfaces at exactly this boundary: stdin write errors (#75438), the stdout error event, and stderr pipe errors (#99803). stdout data was the one path left unguarded. The fix mirrors the upstream SDK behavior byte-for-byte (onerror + close), so a correctly framed stream is unaffected and existing message delivery is unchanged. No sibling transport is left one-sided.

Verification

  • node scripts/run-vitest.mjs src/agents/mcp-stdio-transport.test.ts -> 10 passed, including the new reports an oversized stdout frame without an unhandled error crash case. The new case fails on pristine main (the frame throws out of the handler) and passes with the patch.
  • oxlint and oxfmt --check on both changed files -> clean.
  • run-tsgo.mjs -p tsconfig.core.json and -p test/tsconfig/tsconfig.core.test.json -> no errors.
  • SDK version exercised is @modelcontextprotocol/[email protected], the version pinned by the current lockfile (the 10 MiB cap exists there).

Real behavior proof

Behavior addressed: an MCP stdio server emitting a single stdout frame larger than 10 MiB kills the entire host process instead of failing just that server connection.
Real environment tested: the real OpenClawStdioClientTransport (no stub) spawns a real Node subprocess that writes one oversized line to stdout, parsed by the real @modelcontextprotocol/[email protected] ReadBuffer. Nothing is mocked: real child_process.spawn, real stdio pipes, real read buffer. Run on pristine main fb81d03 and on the patched tree with an identical subprocess and identical input.
Exact steps or command run after this patch: tsx host script instantiates OpenClawStdioClientTransport({ command: node, args: [oversized-server.mjs] }), registers a process.on("uncaughtException") recorder plus onerror/onclose handlers, calls start(), and reports whether the host survives.
Evidence after fix:

# BEFORE (pristine main fb81d03)
HOST started; awaiting oversized frame
HOST uncaughtException: ReadBuffer exceeded maximum size of 10485760 bytes
host exit=1

# AFTER (this patch, identical subprocess and input)
HOST started; awaiting oversized frame
HOST onerror: ReadBuffer exceeded maximum size of 10485760 bytes
HOST SURVIVED exit=0
host exit=0

Observed result after fix: the oversized frame is delivered to onerror and the host keeps running and exits cleanly, where before it escaped to the top level and terminated the host with a non-zero exit.
What was not tested: no live third-party MCP server was driven (a local subprocess stands in for the oversized emitter); the full production build was not run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Aug 4, 2026
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. labels Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 4, 2026, 11:15 PM ET / August 5, 2026, 03:15 UTC.

ClawSweeper review

What this changes

The PR catches oversized MCP stdio stdout frames, reports a transport error, and closes that MCP server connection instead of allowing the OpenClaw host to crash.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open: this is a necessary, narrow repair with no actionable patch defect found. Current main still lets the stdout buffer append escape its stream callback; the PR contains a focused guard and real subprocess before/after proof, while exact-head checks are still running.

Priority: P1
Reviewed head: 5dfb202e4fea8e9a31d0096e5599f68ebf1548d0

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-supported crash repair with convincing runtime proof; remaining merge readiness depends on the pending exact-head gates.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides a before/after real subprocess run through the actual transport and SDK buffer, showing the host survives after the patch.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides a before/after real subprocess run through the actual transport and SDK buffer, showing the host survives after the patch.
Evidence reviewed 7 items Current-main failure boundary: Current main invokes ReadBuffer.append inside the child stdout data callback outside processReadBuffer's catch, so a synchronous append failure can escape that callback.
Patch owns the correct boundary: The exact PR head wraps both stdout buffer append and parsing, forwards an Error through the established callback, and starts the existing close lifecycle.
Runtime handles a transport close as server recovery: The MCP runtime marks the closed client disconnected and schedules catalog retry for an established current session, rather than terminating the host.
Findings None None.
Security None None.

How this fits together

OpenClaw launches configured MCP servers as subprocesses and parses their stdout into protocol messages for agent tools. The stdio transport mediates parser failures before the MCP runtime marks a server disconnected and schedules recovery.

flowchart LR
  A[Configured MCP server] --> B[Child process stdout]
  B --> C[OpenClaw stdio transport]
  C --> D[Frame buffer and parser]
  D --> E{Frame accepted?}
  E -->|yes| F[Agent MCP runtime]
  E -->|oversized or invalid| G[Transport error and close]
  G --> F
  F --> H[Server reconnect on next request]
Loading

Before merge

  • Resolve merge risk (P1) - GitHub reports the branch cleanly mergeable but behind main, and required exact-head checks are still in progress; merge only after those gates complete on the reviewed head or its verified merge result.
  • Complete next step (P2) - No repair is needed; wait for the exact-head required checks and normal merge gate.
Agent review details

Security

None.

PR surface

Source +5, Tests +19. Total +24 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 7 2 +5
Tests 1 19 0 +19
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 26 2 +24

Review metrics

Metric Value Why it matters
Production vs. regression-test delta production +5 net (7 added, 2 removed); tests +19 The production growth is the required owner-boundary guard against an uncaught stream-callback exception, with focused regression coverage.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Land the narrow transport-boundary guard after exact-head CI completes, preserving the existing disconnect-and-reconnect lifecycle for only the misbehaving MCP server.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Land the narrow transport-boundary guard after exact-head CI completes, preserving the existing disconnect-and-reconnect lifecycle for only the misbehaving MCP server.

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

Yes, at source level: current main retains the unguarded stdout callback, and the PR supplies a real child-process before/after run using an oversized frame. This review did not rerun the untrusted branch locally.

Is this the best way to solve the issue?

Yes. The append call is outside the parser catch, so guarding it at the child stdout transport boundary and closing only that transport is the narrowest maintainable repair; the claimed upstream byte match was not independently inspected.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 1f3d45b76f51.

Labels

Label justifications:

  • P1: An oversized MCP server frame can currently terminate the host process and interrupt concurrent agent work.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides a before/after real subprocess run through the actual transport and SDK buffer, showing the host survives after the patch.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides a before/after real subprocess run through the actual transport and SDK buffer, showing the host survives after the patch.

Evidence

What I checked:

  • Current-main failure boundary: Current main invokes ReadBuffer.append inside the child stdout data callback outside processReadBuffer's catch, so a synchronous append failure can escape that callback. (src/agents/mcp-stdio-transport.ts:84, 1f3d45b76f51)
  • Patch owns the correct boundary: The exact PR head wraps both stdout buffer append and parsing, forwards an Error through the established callback, and starts the existing close lifecycle. (src/agents/mcp-stdio-transport.ts:84, 5dfb202e4fea)
  • Runtime handles a transport close as server recovery: The MCP runtime marks the closed client disconnected and schedules catalog retry for an established current session, rather than terminating the host. (src/agents/agent-bundle-mcp-runtime.ts:787, 1f3d45b76f51)
  • Current-line provenance: Blame attributes the current unguarded stdout callback to the current line history; this establishes area ownership, not fault attribution. (src/agents/mcp-stdio-transport.ts:84, aa07d55ec98f)
  • Adjacent error-path history: The merged stderr-pipe repair shows the same transport already treats child-stream failures as non-fatal transport errors. (src/agents/mcp-stdio-transport.ts:90, 1b84316a91dc)
  • Real behavior proof supplied: The PR body records the real transport with a real child subprocess: the baseline exits after an uncaught oversized-frame error, while the patched run reports onerror and exits cleanly. (5dfb202e4fea)

Likely related people:

  • Vincent Koc: Current stdout callback lines blame to this recent agents-area commit. (role: recent area contributor; confidence: high; commits: aa07d55ec98f; files: src/agents/mcp-stdio-transport.ts)
  • cxbAsDev: Merged the stderr-pipe transport error repair that established the neighboring failure-handling pattern. (role: adjacent error-path contributor; confidence: high; commits: 1b84316a91dc; files: src/agents/mcp-stdio-transport.ts, src/agents/mcp-stdio-transport.test.ts)
  • Peter Steinberger: Earlier MCP stdio process-tree teardown work is part of this transport's lifecycle history. (role: historical MCP transport contributor; confidence: medium; commits: 5f7b44045dc1; files: src/agents/mcp-stdio-transport.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-05T00:07:07.136Z sha 5baefb38cb93432d4d3245f930cc9c624d768fd9 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T02:04:39.061Z sha e5299b950262dc6e1cb5e265fbb8a43c906cd164 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T02:13:05.597Z sha e5299b950262dc6e1cb5e265fbb8a43c906cd164 :: needs maintainer review before merge. :: none

@Takhoffman Takhoffman self-assigned this Aug 5, 2026
@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord scripts Repository scripts commands Command implementations size: S and removed size: XS labels Aug 5, 2026
@Takhoffman

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Head moved: added Discord package doctorCapabilities metadata (from #119391) so unit-fast no longer loads the full Discord plugin graph during open-policy-allowfrom and times out under CI contention. Original MCP stdio oversized-frame guard is unchanged.

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Takhoffman
Takhoffman force-pushed the fix/mcp-stdout-oversized-frame-crash branch from cd4939c to 5baefb3 Compare August 5, 2026 01:54
@openclaw-barnacle openclaw-barnacle Bot added size: XS and removed channel: discord Channel integration: discord scripts Repository scripts commands Command implementations size: S labels Aug 5, 2026
@Takhoffman

Copy link
Copy Markdown
Contributor

Maintainer land decision for ClawSweeper re-review option:

ClawSweeper recommended splitting the Discord doctorCapabilities metadata to #119391. Exact-head CI for the MCP-only tip repeatedly failed on open-policy-allowfrom because Doctor loads the full Discord plugin graph without that metadata (same hang #119391 fixes).

Adopting this PR as the single vehicle (ClawSweeper alternate option): keep the Discord metadata commit here with co-author credit to Vincent Koc, land the MCP crash guard with green exact-head CI, then close #119391 as superseded once this merges.

@Takhoffman

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Head is MCP guard + Discord doctorCapabilities (same as #119391) after maintainer decision to adopt this PR as the single vehicle and supersede #119391. Please review exact head e5299b950262dc6e1cb5e265fbb8a43c906cd164.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord scripts Repository scripts commands Command implementations labels Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

…rash

An MCP server whose stdout frame exceeds the SDK ReadBuffer 10 MiB cap makes
ReadBuffer.append throw synchronously inside the child stdout data callback.
The handler had no try/catch, so the error escaped as an uncaughtException and
took down the host process, killing every concurrent session. The frame size is
driven by tool-result data a lower-privileged sender can influence, not by the
operator who chose the server.

Wrap append and processReadBuffer in the same try/catch the upstream SDK
transport uses: route the error to onerror and close the transport so the MCP
runtime handles it as a server disconnect. This matches the existing stdin
(openclaw#75438) and stderr (openclaw#99803) guards in this file; stdout was the missed path.
@Takhoffman
Takhoffman force-pushed the fix/mcp-stdout-oversized-frame-crash branch from e5299b9 to 5dfb202 Compare August 5, 2026 03:09
@Takhoffman

Copy link
Copy Markdown
Contributor

Rebased onto latest main.

@Takhoffman

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Rebased onto main. MCP-only tip 5dfb202e4fea8e9a31d0096e5599f68ebf1548d0 (Discord metadata already on main via #119391). Please review exact head.

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added size: XS and removed channel: discord Channel integration: discord scripts Repository scripts commands Command implementations size: S labels Aug 5, 2026
@Takhoffman
Takhoffman merged commit 3bda007 into openclaw:main Aug 5, 2026
124 of 128 checks passed
@Takhoffman

Copy link
Copy Markdown
Contributor

Merged via squash.

vincentkoc added a commit that referenced this pull request Aug 5, 2026
* origin/main:
  fix(channels): honor explicit preview streaming settings
  refactor(telegram): consolidate outbound contracts and targets (#119438)
  fix(qa): retry transport cleanup and always stop owned labs (#119442)
  fix(mcp): guard stdio stdout frame parsing against oversized-buffer crash (#119379)
  refactor(auto-reply): centralize delivery deduplication and routing (#119436)
  fix(qa): preserve scenario isolation in serial suites (#119439)
  perf(xai): lazy-load optional capability runtimes (#119374)
  refactor(browser): consolidate browser CLI and normalization helpers (#119432)
  fix(qa): require ready transport accounts (#119431)
  refactor(media): share image and video geometry normalization (#119416)
  fix(config): preserve plugin metadata for missing config (#119421)
  fix: retry delivery when outbound adapter is unavailable (#119371)
  fix(cli): retire invalid secret flags and prove doctor recovery (#118926)
  refactor(signal): share outbound and reaction transport (#119415)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 5, 2026
…rash (openclaw#119379)

…rash

An MCP server whose stdout frame exceeds the SDK ReadBuffer 10 MiB cap makes
ReadBuffer.append throw synchronously inside the child stdout data callback.
The handler had no try/catch, so the error escaped as an uncaughtException and
took down the host process, killing every concurrent session. The frame size is
driven by tool-result data a lower-privileged sender can influence, not by the
operator who chose the server.

Wrap append and processReadBuffer in the same try/catch the upstream SDK
transport uses: route the error to onerror and close the transport so the MCP
runtime handles it as a server disconnect. This matches the existing stdin
(openclaw#75438) and stderr (openclaw#99803) guards in this file; stdout was the missed path.

Co-authored-by: Tak Hoffman <[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 P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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.

2 participants