Repository navigation
fix(mcp): pool startup resilience & spawn-cycle protection - #2
Merged
Merged
Conversation
Hermes (and any MCP host) restarted code-executor in a tight loop because
the upstream stdio handshake was answered only AFTER connecting to every
downstream server. A single slow/unreachable server (notably HTTP ones)
blocked startup past the host timeout, so the host killed and respawned the
process repeatedly — each spawn leaking ~15 child MCP processes.
Root cause + amplifiers fixed:
1. Background pool init (index.ts): connect the upstream stdio transport
FIRST, then initialize the downstream pool in the background. The host
handshake now returns instantly regardless of downstream health. Tool
handlers await `poolReady` before executing (bounded by per-server
timeouts). Total downstream failure no longer crashes the server.
2. Per-server connect timeout (client-pool.ts): each connect races against
POOL_CONNECT_TIMEOUT_MS (default 15s, Zod-validated). A hung server is
marked failed instead of blocking the pool. On timeout the spawned child
is killed explicitly by PID (SIGKILL) in addition to transport.close(),
since AbortController-based kill is unreliable under the Bun runtime.
3. Process-leak hardening (client-pool.ts, index.ts): track in-flight
transports in `pendingStdioTransports` so children spawned during a
mid-init teardown are still reaped; add a synchronous `process.on('exit')`
backstop (killChildrenSync) that SIGKILLs all spawned children even on a
hard exit.
Partial availability: a failed/timed-out server is never added to
clients/toolCache, so its tools are neither discoverable nor callable — the
remaining servers stay fully available and startup continues without it.
Startup status report: initialize() now logs one line per configured server
(✓/✗ with duration and failure reason) plus an N/M summary, so it is always
clear which servers came up and which did not.
Verified on the bun --compile binary: transport connects before pool init,
per-server timeout fires and kills the hung child, no orphans remain after
shutdown, and the server keeps running when all downstream servers fail.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Live diagnosis: the fork bomb was NOT direct self-inclusion (code-executor is correctly excluded from its own pool by name). It was a CYCLIC MCP topology — the host (an agent gateway) lists code-executor as a server, and code-executor's config lists that same host (its `mcp serve`) as a downstream server. The two spawn each other indefinitely (code-executor → host → code-executor → ...), producing dozens of processes per minute. Name-based self-exclusion can't catch this: the intermediary is a different program. Guard: at startup, walk the parent-PID chain; if any ancestor process is itself a code-executor (argv0 basename = code-executor-mcp), run in LEAF MODE — connect to no downstream servers and return immediately, terminating the cycle. Design notes: - PID ancestry, not an inherited env marker: the observed intermediary (`hermes mcp serve`) does NOT forward our environment to the code-executor it spawns, so a marker never arrives. Parent PIDs are always readable. - The whole chain, not just the direct parent: in the cyclic case the direct parent is the host, and the code-executor ancestor is one hop further up. - argv0 basename match, not the full command line: avoids a false positive where a shell wrapper (`sh -c "... /path/code-executor-mcp ..."`) is mistaken for a code-executor — which wrongly put a top-level instance into leaf mode. - Escape hatch: CODE_EXECUTOR_ALLOW_NESTED=1 disables the guard. - Best-effort: if `ps` is unavailable (e.g. Windows) the guard does not engage. Verified on the bun --compile binary, simulating a host that strips the environment: the top-level instance runs full and connects downstream, while the instance it transitively spawns detects the code-executor ancestor, logs LEAF MODE, and spawns nothing — bounding the chain. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…stream) Complements the name-based self-exclusion (which only matches the conventional "code-executor" config key) and the ancestry guard. At pool init, any downstream STDIO server whose command is code-executor itself — basename "code-executor-mcp" or an exact match of process.execPath — is skipped regardless of its config key name, with a logged reason. This catches "wired self in under a different name", the original suspected cause. Note: this does NOT remove a downstream that loops back indirectly through a different host program (e.g. an agent gateway), because that command is not the code-executor binary; the parent-PID ancestry guard handles that case, and breaking the config cycle is the way to drop the (harmless, leaf-mode) extra process entirely. Verified on the bun --compile binary: code-executor configured as a downstream under a non-"code-executor" key is skipped at startup. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ilience - tests/recursion-guard.test.ts: path-based self-exclusion (self wired under any key name, and exact process.execPath match) and the parent-PID ancestry leaf guard, including the CODE_EXECUTOR_ALLOW_NESTED override. - tests/pool-config-validation.test.ts: connectTimeoutMs default (15000) and POOL_CONNECT_TIMEOUT_MS parsing. - CHANGELOG.md: [Unreleased] entry summarizing the startup-resilience and spawn-cycle fixes. - docs/mcp-pool-startup-resilience.md: full diagnosis, fixes, and the rationale for each design decision (incl. why ancestry beats an env marker, why argv0 matching, why leaf mode not exit). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Hardens code-executor startup against two production failure modes seen when running behind an MCP host (the Hermes agent gateway):
hermes mcp serve) as a downstream server, so the two spawn each other indefinitely. (Not direct self-inclusion — that is correctly excluded by name.)Full diagnosis and design rationale:
docs/mcp-pool-startup-resilience.md.What changed
src/index.ts): connect the upstream stdio transport first, initialize the downstream pool in the background (poolReady); tool handlers await readiness. Total downstream failure no longer crashes the server.POOL_CONNECT_TIMEOUT_MS, default 15 s): a hung server is marked failed instead of blocking the pool; its child is killed by PID on timeout (AbortController kill is unreliable on Bun).hermes mcp servedoes, so the earlier env-marker approach failed live. Override:CODE_EXECUTOR_ALLOW_NESTED=1.process.execPath), regardless of config key name.process.on('exit')SIGKILL backstop.Tests
tests/recursion-guard.test.ts(new): self-exclusion, leaf-mode guard,CODE_EXECUTOR_ALLOW_NESTEDoverride.tests/pool-config-validation.test.ts:connectTimeoutMsdefault + parsing.psancestry) verified manually on thebun --compilebinary; see the docs note's Verification section.Notes
bun --compilebinary;bin/code-executor-mcpis gitignored, rebuild withnpm run build:binary.🤖 Generated with Claude Code