Skip to content

fix(agent-runtime): prevent MCP stdio servers from polluting Claude's inherited stdout (#630 follow-up) #640

Closed

Description

@dolho

Summary

Follow-up to #630 / #639. The defensive fix in #639 (per-line reader isolation + result-metadata recovery from raw_messages) covers the case where a stream-json line is parsed but processing is interrupted mid-loop. It does not address the underlying root cause flagged in #630: stdio MCP server children inherit Claude Code's stdout file descriptor and concurrent writes from Claude + the MCP child interleave on the wire, producing invalid JSON that json.loads silently skips.

When the result line itself is the casualty of interleaving, recovery cannot help — the line never lands in raw_messages because the JSON parse failed.

Root cause

When agent-server launches Claude Code via subprocess.Popen(stdout=PIPE), Claude inherits fd 1 = the pipe write-end going back to agent-server. When Claude then spawns an stdio MCP server (e.g. npx -y some-mcp-package):

  1. Claude opens a new pipe for the MCP-protocol channel
  2. dup2s the new pipe onto the MCP child's fd 0/1
  3. Anything the MCP child (or its npm bootstrap) writes to fd 1 goes through the protocol channel, not to agent-server

So fd 1 inheritance is not the direct path. The actual leak is one of:

  • The MCP child has Claude's original stdout fd inherited as some fd > 2 (no close_fds / FD_CLOEXEC), and the package writes to it via /proc/self/fd/N or similar
  • The MCP child's stderr is dup2'd from Claude's stderr (which is also a pipe to agent-server), and a noisy package writes to stderr — but stderr is a separate reader, that goes into the stderr buffer, not stdout
  • Claude itself buffers and flushes the result line in a way that interleaves with concurrent assistant-message streaming when an MCP server is producing stderr-on-stdout via npm wrapper

Need bisect to confirm which mechanism. The reporter in #630 saw consistent corruption with npx-launched MCP servers; reproduction with a known-pollutant MCP server is the first task.

Acceptance criteria

  • Reliable reproduction: a minimal agent template + chat task that triggers "Failed to parse line as JSON" + missing cost_usd consistently (≥3/5 runs)
  • Root cause confirmed via fd inspection in the MCP child process (/proc/{pid}/fd) or strace
  • Fix prevents corruption at source. Candidates (in order of preference):
    • Wrap each .mcp.json command so the spawned binary never inherits Claude's stdout/stderr — e.g. rewrite command to setsid bash -c 'exec "$0" "$@" 1>&3 2>&4 3>&- 4>&-' with appropriate fd plumbing for the MCP protocol
    • Patch the agent's CLAUDE.md / .mcp.json template so all MCP servers are launched via a wrapper script the agent ships
    • If Claude Code supports close_fds-style options for MCP launch, enable them
  • Existing chat / task / scheduling paths continue to work (no MCP regression)
  • Test that asserts: with a deliberately-noisy stdio MCP server installed, a 50+ turn chat completes with metadata.cost_usd != None

Related

Why split from #639

#639 ships a defensive layer that's safe and unit-testable today and improves the failure UX (publish exceptions no longer silently kill the reader). The wire-corruption work needs:

  • Reliable reproduction harness (more investigation than coding)
  • Possibly cross-cutting changes to agent template defaults / .mcp.json shape
  • Coordination with the agent-base-image build + rollout

That's a separate effort that shouldn't block #639.

Activity

  1. added
    priority-p1
    type-bug
    status-in-progress
    on May 4, 2026
  2. self-assigned this
    on May 5, 2026
  3. added
    status-in-dev
    and removed
    status-in-progress
    on May 6, 2026
  4. added a commit that references this issue on May 7, 2026
  5. dolho commented on May 7, 2026

    @dolho
    ContributorAuthor

    Status update — synthetic-hypothesis investigation hit a wall

    PR #693 ships a deterministic repro harness (tests/harness/640/) and documents 6 falsified hypotheses from running it + statically inspecting @anthropic-ai/claude-code cli.js.

    Falsified

    1. Node spawn fd>2 leak — Node closes fd>2 by default; no MCP-spawn site in cli.js disables this. Confirmed via static read of every spawn(...) site.
    2. Claude internal stray stdout write in stream-json hot path — all 45 process.stdout.write sites in cli.js inspected. Real-code sites all gate on subcommands (mcp add, login, TUI) that don't fire under --print --output-format stream-json. Sites that look problematic (event.delta.text raw writes) are markdown documentation strings, not real code.
    3. Claude bridges MCP stderr → its own stdout — the SDK's stderr.on("data") handler appends to a 64MB in-memory ring (if($.length<67108864) $+=h.toString()); never re-emits.
    4. npm-bootstrap pre-protocol stdout boilerplate — 50-turn run with npm-wrapper variant, 0/50 null-cost. Claude tolerates pre-protocol garbage at handshake.
    5. setsid grandchild fd retention — 50-turn run with setsid-child variant. 53 grandchildren forked + escaped pgid (verified via sidecar log + broken-pipe events). Pollution lands on MCP-protocol pipe (claude-side), not on agent-server's claude-stdout pipe. Claude skips non-JSON frames silently.
    6. /proc/self/fd/N userspace bypass — smoke test returned ENXIO (No such device or address). Linux refuses to re-open a pipe via /proc/self/fd/*. Kernel-level isolation; this hypothesis is impossible to exercise from userspace.

    Why the harness can't reach the bug

    Every leak path the harness exercises lands on the MCP protocol pipe (Claude-side), not on the agent-server claude-stdout pipe where #640's wire corruption actually manifests. Claude+SDK isolate MCP child stdio correctly. No userspace synthetic variant from a child process can corrupt agent-server's read end of Claude's stdout.

    What's still open (real remaining hypothesis space)

    • Race in Claude's own stdout line buffering — concurrent emitter threads inside Claude. Untestable without LD_PRELOAD or claude-cli source patching.
    • Shell-wrapped MCP launch (bash -c "node x.js") where shell init writes to a fd we haven't simulated. Need a real cmdline from production.
    • Load-state dependent — bug body says ≥100 turns / 18 min; our runs were 50 turns / ~6 min. Possible accumulation effect we can't reach with synthetic prompts.
    • cli.js version drift — base image cli.js may differ from production version that hit Async chat_with_agent: long execution silently fails with null response (reader-thread) #678. Worth checking version pinning.

    Recommended path forward

    1. Land fix(agent-runtime): surface stdout parse failures + orphan identity for #640 debugging #662 — only practical way to ID the actual leaking package is real prod log evidence (parse_failures=N count + orphan cmdline).
    2. Redeploy dev cluster fixes (bug: drain_reader_threads t.join(30) deadlocks asyncio event loop permanently when reader thread is stuck #657, bug: drain_reader_threads post-kill timeout not enforced; leaked thread blocks capacity slot indefinitely #649, bug(agent-runtime): npx MCP server subprocesses outside claude pgid hold stdout pipe open — reader stuck after #531 grace period #618, bug: stdio MCP subprocess stdout inheritance causes 'Execution completed without a result message' #630, bug: drain_reader_threads closes stdout pipe before reader can drain backlog — silently loses final result line on long agentic tasks #531, bug: agent_server reports task as 'completed successfully' when claude exits 0 with no result message #520) on the host running the ability-website agent (Async chat_with_agent: long execution silently fails with null response (reader-thread) #678 victim). Reduces frequency of this failure mode.
    3. Wait for next prod failure with fix(agent-runtime): surface stdout parse failures + orphan identity for #640 debugging #662 instrumentation merged. Read the orphan cmdlines to identify which package actually leaks.
    4. Build a targeted variant from that real cmdline. Cheap once the real package is known; expensive otherwise (this investigation, ~$4 + ~3h).

    Cost recap

    • ~$4 of subscription compute (npm-wrapper + setsid-child runs at 50 turns each)
    • ~3 hours wall
    • 6 hypotheses falsified, harness committed as a future regression gate

    Issue stays open — root cause still unknown. This comment closes the synthetic-hypothesis-hunting angle.

  6. removed their assignment
    on May 7, 2026
  7. added a commit that references this issue on May 7, 2026
  8. vybe commented on Jun 1, 2026

    @vybe
    Contributor

    Shipped in v0.6.0 (released via #998).

  9. added
    complexity-low
    theme-reliability
    and removed
    status-in-dev
    on Jun 1, 2026
  10. added a commit that references this issue on Jun 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    complexity-lowpriority-p1theme-reliabilitytype-bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions