From b7152faff9036489f7324a40a5495ca647cd9627 Mon Sep 17 00:00:00 2001 From: SWSAmor Date: Sun, 31 May 2026 22:10:12 +0200 Subject: [PATCH 1/4] fix(mcp): decouple startup from downstream pool, prevent respawn loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/config/loader.ts | 3 +- src/config/types.ts | 4 + src/index.ts | 69 +++++++++++-- src/mcp/client-pool.ts | 217 +++++++++++++++++++++++++++++++++-------- 4 files changed, 241 insertions(+), 52 deletions(-) diff --git a/src/config/loader.ts b/src/config/loader.ts index fe9f1d1..a6f07b2 100644 --- a/src/config/loader.ts +++ b/src/config/loader.ts @@ -282,6 +282,7 @@ export function getPoolConfig(): PoolConfig { maxConcurrent: parseEnvInt(process.env.POOL_MAX_CONCURRENT, 'POOL_MAX_CONCURRENT'), queueSize: parseEnvInt(process.env.POOL_QUEUE_SIZE, 'POOL_QUEUE_SIZE'), queueTimeoutMs: parseEnvInt(process.env.POOL_QUEUE_TIMEOUT_MS, 'POOL_QUEUE_TIMEOUT_MS'), + connectTimeoutMs: parseEnvInt(process.env.POOL_CONNECT_TIMEOUT_MS, 'POOL_CONNECT_TIMEOUT_MS'), }); } catch (error) { // WHY: Wrap Zod errors with user-friendly messages @@ -291,7 +292,7 @@ export function getPoolConfig(): PoolConfig { const field = firstError?.path.join('.') || 'unknown'; throw new Error( `Invalid pool configuration: ${field} - ${firstError?.message}. ` + - `Check environment variables: POOL_MAX_CONCURRENT (1-1000), POOL_QUEUE_SIZE (1-1000), POOL_QUEUE_TIMEOUT_MS (1000-300000).` + `Check environment variables: POOL_MAX_CONCURRENT (1-1000), POOL_QUEUE_SIZE (1-1000), POOL_QUEUE_TIMEOUT_MS (1000-300000), POOL_CONNECT_TIMEOUT_MS (1000-120000).` ); } // Re-throw non-Zod errors (e.g., parseEnvInt errors) diff --git a/src/config/types.ts b/src/config/types.ts index 9a0badc..62b2671 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -28,6 +28,8 @@ export type RateLimitConfig = z.infer; * - maxConcurrent: 1-1000 balances throughput vs resource consumption * - queueSize: 1-1000 prevents memory exhaustion from unbounded queues * - queueTimeoutMs: 1s-5min ensures reasonable wait times + * - connectTimeoutMs: 1s-2min caps how long a single downstream MCP server may + * take to connect, so one slow/unreachable server cannot stall pool startup */ export const PoolConfigSchema = z.object({ /** Maximum concurrent requests (default: 100) */ @@ -36,6 +38,8 @@ export const PoolConfigSchema = z.object({ queueSize: z.number().int().min(1).max(1000).default(200), /** Queue timeout in milliseconds (default: 30000ms = 30s) */ queueTimeoutMs: z.number().int().min(1000).max(300000).default(30000), + /** Per-server connect timeout in milliseconds (default: 15000ms = 15s) */ + connectTimeoutMs: z.number().int().min(1000).max(120000).default(15000), }); export type PoolConfig = z.infer; diff --git a/src/index.ts b/src/index.ts index 03a6a63..c68635b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -65,6 +65,12 @@ class CodeExecutorServer { private denoAvailable: boolean = false; private healthCheckServer: HealthCheckServer | null = null; private shutdownInProgress = false; // P1: Prevent concurrent shutdown attempts + // Resolves when the downstream MCP client pool has finished initializing. + // The pool is initialized in the BACKGROUND (see start()) so the upstream MCP + // handshake is never blocked by slow/unreachable downstream servers. Tool + // handlers await this before executing so downstream tools are ready (or have + // been determined unavailable) by the time code runs. + private poolReady: Promise = Promise.resolve(); constructor() { // Initialize MCP server @@ -281,6 +287,11 @@ Example: }; } + // Ensure the downstream MCP pool has finished initializing (it is set + // up in the background at startup) so callMCPTool/discovery see the + // connected servers. Bounded by per-server connect timeouts. + await this.poolReady; + // Execute code with connection pooling const result = await this.connectionPool.execute(async () => { return await executeTypescriptInSandbox( @@ -537,6 +548,10 @@ Example: }; } + // Ensure the downstream MCP pool has finished initializing (background + // startup) before executing. Bounded by per-server connect timeouts. + await this.poolReady; + // Execute code with connection pooling // Use Pyodide (secure) when PYTHON_SANDBOX_READY, otherwise native (insecure) // Pyodide loaded lazily so its 13MB WASM stays out of compiled binaries that don't enable it. @@ -695,12 +710,32 @@ Returns: } } - // Initialize MCP client pool - console.error('Initializing MCP client pool...'); - await this.mcpClientPool.initialize(); + // Start stdio transport FIRST so the upstream MCP handshake (initialize + + // tools/list) is answered immediately. The downstream client pool is then + // initialized in the BACKGROUND. This decouples our own readiness from the + // health of downstream servers: a slow/unreachable server can no longer + // delay startup past the host's timeout and trigger a respawn loop. + const transport = new StdioServerTransport(); + await this.server.connect(transport); - const tools = this.mcpClientPool.listAllTools(); - console.error(`Connected to ${tools.length} MCP tools across multiple servers`); + console.error('Code Executor MCP Server started successfully (downstream MCP pool initializing in background)'); + + // Initialize MCP client pool in the background. Tool handlers await + // `poolReady` before executing (see registerTools). Failures are logged but + // never crash the server — code-executor keeps serving whatever connected. + console.error('Initializing MCP client pool...'); + this.poolReady = this.mcpClientPool + .initialize() + .then(() => { + const tools = this.mcpClientPool.listAllTools(); + console.error(`Connected to ${tools.length} MCP tools across multiple servers`); + }) + .catch((error) => { + const message = error instanceof Error ? error.message : String(error); + console.error( + `MCP client pool initialization failed — continuing without downstream tools: ${message}` + ); + }); // Initialize health check server (optional, enabled via env var) const enableHealthCheck = process.env.ENABLE_HEALTH_CHECK !== 'false'; @@ -720,12 +755,14 @@ Returns: this.healthCheckServer = null; } } + } - // Start stdio transport - const transport = new StdioServerTransport(); - await this.server.connect(transport); - - console.error('Code Executor MCP Server started successfully'); + /** + * Synchronously kill all spawned downstream child processes. + * Backstop for the process 'exit' handler (see bottom of file). + */ + killChildrenSync(): void { + this.mcpClientPool.killChildrenSync(); } /** @@ -830,6 +867,18 @@ const handleShutdownSignal = async (signal: string) => { process.on('SIGINT', () => void handleShutdownSignal('SIGINT')); process.on('SIGTERM', () => void handleShutdownSignal('SIGTERM')); +// Synchronous last-resort cleanup. If the process exits without the async +// graceful path completing (e.g. host sends SIGKILL after a timeout, or an +// unexpected exit), this guarantees spawned downstream MCP children are killed +// rather than left as orphans. Must be synchronous — no async work runs here. +process.on('exit', () => { + try { + server.killChildrenSync(); + } catch { + // Nothing actionable during exit. + } +}); + // Argument parsing: Handle CLI commands const args = process.argv.slice(2); const command = args[0]; diff --git a/src/mcp/client-pool.ts b/src/mcp/client-pool.ts index f5068a2..15a6915 100644 --- a/src/mcp/client-pool.ts +++ b/src/mcp/client-pool.ts @@ -46,6 +46,8 @@ export interface MCPClientPoolConfig { queueSize?: number; /** Queue timeout in milliseconds (default: 30000ms = 30s) */ queueTimeoutMs?: number; + /** Per-server connect timeout in milliseconds (default: 15000ms = 15s) */ + connectTimeoutMs?: number; } /** @@ -65,6 +67,17 @@ export class MCPClientPool implements IToolSchemaProvider { private processes: Map = new Map(); private initialized = false; + // Per-server connect timeout: a single slow/unreachable downstream server must + // never stall pool startup (which would delay the upstream MCP handshake and + // trigger a supervisor restart loop). See connectStdio/connectHttp. + private connectTimeoutMs: number; + + // STDIO transports that have spawned a child process but whose connect() has + // not yet resolved. Tracked here so a child can still be reaped if the whole + // pool is torn down (or the process exits) before connect() completes — + // otherwise these children leak as orphans on a mid-init shutdown/kill. + private pendingStdioTransports: Set = new Set(); + // US4: Concurrency limiting and overflow queue private maxConcurrent: number; private activeConcurrent = 0; @@ -91,6 +104,9 @@ export class MCPClientPool implements IToolSchemaProvider { // T053: Store queue timeout for waitForQueueSlot this.queueTimeoutMs = config?.queueTimeoutMs ?? poolConfig.queueTimeoutMs; + // Per-server connect timeout (Priority: explicit config > env-validated default) + this.connectTimeoutMs = config?.connectTimeoutMs ?? poolConfig.connectTimeoutMs; + // T053: Initialize connection queue this.connectionQueue = new ConnectionQueue({ maxSize: config?.queueSize ?? poolConfig.queueSize, @@ -210,57 +226,64 @@ export class MCPClientPool implements IToolSchemaProvider { } console.error(`🔌 Initializing MCP client pool (excluding self${userExclusions.length > 0 ? ` + ${userExclusions.length} excluded` : ''}, ${filteredServers.length} servers)`); - // Connect to each configured server with detailed error tracking + // Connect to each configured server. Each connection is independent and + // bounded by connectTimeoutMs (see connectToServer), so one slow/unreachable + // server can never block the others — failures degrade gracefully and the + // pool comes up with whatever connected. A failed server is NEVER added to + // `clients`/`toolCache`, so its tools are not discoverable or callable. const serverNames = filteredServers.map(([name]) => name); - const connections = filteredServers.map( - ([serverName, serverConfig]) => - this.connectToServer(serverName, serverConfig) + const outcomes = await Promise.all( + filteredServers.map(async ([serverName, serverConfig]) => { + const startedAt = Date.now(); + try { + await this.connectToServer(serverName, serverConfig); + return { serverName, ok: true as const, ms: Date.now() - startedAt }; + } catch (error) { + return { + serverName, + ok: false as const, + ms: Date.now() - startedAt, + error: error instanceof Error ? error.message : String(error), + }; + } + }) ); - const results = await Promise.allSettled(connections); + const failures = outcomes.filter(o => !o.ok); + const successes = outcomes.length - failures.length; - // Track failures - const failures = results.filter(r => r.status === 'rejected'); + // Per-server startup status report: one line per configured server (so a + // 9-server config produces 9 lines), with the failure reason when known. + // This is the authoritative record of what came up and what did not. + if (serverNames.length === 0) { + console.error('ℹ️ No other MCP servers configured (code-executor running standalone)'); + } else { + console.error(`📋 MCP server startup report (${successes}/${serverNames.length} connected):`); + for (const o of outcomes) { + if (o.ok) { + console.error(` ✓ ${o.serverName} (${o.ms}ms)`); + } else { + console.error(` ✗ ${o.serverName} (${o.ms}ms): ${o.error}`); + } + } + } - // If ALL servers failed (and there were servers to connect to), throw error - // Allow zero servers as valid configuration (code-executor can run standalone) + // If ALL servers failed (and there were servers to connect to), throw error. + // Allow zero servers as a valid configuration (code-executor runs standalone). if (serverNames.length > 0 && failures.length === serverNames.length) { - const errorMessages = results - .map((r, i) => { - if (r.status === 'rejected') { - return ` - ${serverNames[i]}: ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`; - } - return ''; - }) - .filter(Boolean) + const errorMessages = failures + .map(o => ` - ${o.serverName}: ${o.error}`) .join('\n'); - throw new Error( `All MCP server connections failed. Check .mcp.json configuration:\n${errorMessages}` ); } - // If zero servers configured, log info message - if (serverNames.length === 0) { - console.error('ℹ️ No other MCP servers configured (code-executor running standalone)'); - } - - // If some servers failed, warn but continue if (failures.length > 0) { - console.warn(`⚠️ ${failures.length}/${serverNames.length} MCP servers failed to connect`); - failures.forEach((f, i) => { - if (f.status === 'rejected') { - const serverName = serverNames[i]; - console.error(` ✗ ${serverName}: ${f.reason instanceof Error ? f.reason.message : String(f.reason)}`); - } - }); + console.warn(`⚠️ ${failures.length}/${serverNames.length} MCP servers failed to connect — continuing without them`); } - // Report successful connections - const successes = results.filter(r => r.status === 'fulfilled').length; - console.error(`✓ Connected to ${successes}/${serverNames.length} MCP servers`); - - // Cache tool listings + // Cache tool listings (only from successfully connected servers) await this.cacheToolListings(); this.initialized = true; @@ -282,6 +305,43 @@ export class MCPClientPool implements IToolSchemaProvider { } } + /** + * Race a client.connect() against connectTimeoutMs. + * + * On timeout (or connect rejection) the error is propagated to the caller, + * which owns transport/child teardown. The still-pending connect promise is + * detached with a no-op catch so a late rejection cannot surface as an + * unhandled rejection after we have moved on. + */ + private async connectWithTimeout( + client: Client, + transport: Parameters[0], + serverName: string + ): Promise { + let timer: ReturnType | undefined; + const connectPromise = client.connect(transport); + const timeoutPromise = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`connect timed out after ${this.connectTimeoutMs}ms`)), + this.connectTimeoutMs + ); + }); + + try { + await Promise.race([connectPromise, timeoutPromise]); + } catch (error) { + // Detach the losing connect promise so a late rejection is swallowed. + void connectPromise.catch(() => { /* superseded by timeout/failure */ }); + throw error instanceof Error + ? error + : new Error(`Failed to connect to ${serverName}: ${String(error)}`); + } finally { + if (timer) { + clearTimeout(timer); + } + } + } + /** * Connect to STDIO-based MCP server */ @@ -307,10 +367,35 @@ export class MCPClientPool implements IToolSchemaProvider { }, }); - // Connect to server - await client.connect(transport); + // Track the transport BEFORE connecting: connect() spawns the child process, + // so if connect hangs (or the pool is torn down mid-init) we must still be + // able to reap that child via this set. Removed once connect settles. + this.pendingStdioTransports.add(transport); - // Track process for cleanup + try { + await this.connectWithTimeout(client, transport, serverName); + } catch (error) { + // Capture the spawned child PID before close() clears it, then tear the + // child down explicitly (SIGKILL) so a slow/failed server leaves no orphan. + // Explicit kill-by-PID is used in addition to transport.close() because the + // AbortController-based kill is not reliable across runtimes (e.g. Bun). + const orphanPid = transport.pid; + this.pendingStdioTransports.delete(transport); + void transport.close().catch(() => { /* best effort */ }); + void client.close().catch(() => { /* best effort */ }); + if (orphanPid != null) { + try { + process.kill(orphanPid, 'SIGKILL'); + } catch { + // ESRCH (already gone) or not-permitted — nothing more to do. + } + } + throw error; + } + + this.pendingStdioTransports.delete(transport); + + // Track process for graceful cleanup on shutdown if (transport.pid) { this.processes.set(serverName, { pid: transport.pid, @@ -351,7 +436,7 @@ export class MCPClientPool implements IToolSchemaProvider { }, } ); - await client.connect(transport); + await this.connectWithTimeout(client, transport, serverName); connected = true; console.error(`✓ Connected to ${serverName} via StreamableHTTP`); } catch { @@ -368,7 +453,7 @@ export class MCPClientPool implements IToolSchemaProvider { }, } ); - await client.connect(transport); + await this.connectWithTimeout(client, transport, serverName); console.error(`✓ Connected to ${serverName} via SSE (fallback)`); } @@ -781,6 +866,28 @@ export class MCPClientPool implements IToolSchemaProvider { await Promise.all(processCleanup); + // Close any transports whose connect() is still in flight (mid-init shutdown). + // These are not yet in `processes`, so without this their children would leak. + const pendingCleanup = Array.from(this.pendingStdioTransports).map( + async (transport) => { + const pid = transport.pid; + try { + await transport.close(); + } catch { + // best effort + } + if (pid != null) { + try { + process.kill(pid, 'SIGKILL'); + } catch { + // already gone / not permitted + } + } + } + ); + await Promise.all(pendingCleanup); + this.pendingStdioTransports.clear(); + // Clear all state this.clients.clear(); this.toolCache.clear(); @@ -793,6 +900,34 @@ export class MCPClientPool implements IToolSchemaProvider { this.queueSlotEmitter.removeAllListeners(); } + /** + * Synchronously SIGKILL every child process this pool has spawned. + * + * Last-resort backstop for `process.on('exit')`, where only synchronous work + * runs: async disconnect() cannot complete there. Covers both fully-connected + * STDIO servers (`processes`) and connects still in flight (`pendingStdioTransports`), + * so a hard exit never leaves orphaned downstream MCP processes behind. + */ + killChildrenSync(): void { + const pids = new Set(); + for (const { pid } of this.processes.values()) { + pids.add(pid); + } + for (const transport of this.pendingStdioTransports) { + const pid = transport.pid; + if (pid != null) { + pids.add(pid); + } + } + for (const pid of pids) { + try { + process.kill(pid, 'SIGKILL'); + } catch { + // already gone / not permitted — nothing to do in a sync exit handler + } + } + } + /** * Alias for disconnect() - for backward compatibility with tests * From 5445e76b4459c19e60459adf36a981d2ae01f32c Mon Sep 17 00:00:00 2001 From: SWSAmor Date: Sun, 31 May 2026 23:56:16 +0200 Subject: [PATCH 2/4] fix(mcp): break code-executor spawn cycles via parent-PID ancestry guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/mcp/client-pool.ts | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/src/mcp/client-pool.ts b/src/mcp/client-pool.ts index 15a6915..f5632c7 100644 --- a/src/mcp/client-pool.ts +++ b/src/mcp/client-pool.ts @@ -10,6 +10,7 @@ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js' import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'; import { EventEmitter } from 'events'; +import { execFileSync } from 'child_process'; import * as fs from 'fs/promises'; import { getPoolConfig } from '../config/loader.js'; import { isValidMCPToolName, normalizeError, isErrnoException } from '../utils/utils.js'; @@ -78,6 +79,14 @@ export class MCPClientPool implements IToolSchemaProvider { // otherwise these children leak as orphans on a mid-init shutdown/kill. private pendingStdioTransports: Set = new Set(); + // Recursion guard. A code-executor wired (directly, or indirectly via another + // MCP host such as its own agent gateway) as a downstream server of another + // code-executor forms a spawn cycle that fork-bombs the machine. Name-based + // self-exclusion cannot catch the indirect case (the intermediary is a + // different program). Instead, at startup we walk the parent-PID chain and run + // in LEAF MODE (connect to no downstream servers) if any ancestor is itself a + // code-executor process. See hasCodeExecutorAncestor(). + // US4: Concurrency limiting and overflow queue private maxConcurrent: number; private activeConcurrent = 0; @@ -122,6 +131,63 @@ export class MCPClientPool implements IToolSchemaProvider { this.metricsExporter = metricsExporter; } + /** + * Walk this process's parent-PID chain and report whether any ancestor is + * itself a code-executor process. This is what breaks the cycle: a + * code-executor nested under another (directly, or via an intermediate MCP + * host) detects the ancestor and runs in leaf mode. + * + * Why walk the live process table instead of an inherited env marker: the + * intermediary (observed: an agent gateway's `mcp serve`) does NOT forward + * our environment to the children it spawns, so a marker never reaches the + * nested instance. Parent PIDs, by contrast, are always there to read. + * + * Why the whole chain, not just the direct parent: in the cyclic case the + * direct parent is the host (e.g. hermes), not a code-executor — the + * code-executor ancestor is one hop further up. + * + * Matching is on the ancestor's argv0 basename only (not the whole command + * line), so a shell wrapper like `sh -c "... /path/code-executor-mcp ..."` + * (whose argv0 is "sh") is not mistaken for a code-executor. + * + * Best-effort: returns false if `ps` is unavailable (e.g. Windows) or the + * query fails. + */ + private static hasCodeExecutorAncestor(): boolean { + const SELF_BINARY = 'code-executor-mcp'; + try { + let pid = process.ppid; + let hops = 0; + while (pid && pid > 1 && hops < 64) { + hops++; + const out = execFileSync('ps', ['-o', 'ppid=,command=', '-p', String(pid)], { + encoding: 'utf8', + timeout: 2000, + }).trim(); + if (!out) { + break; + } + const spaceIdx = out.indexOf(' '); + const ppidStr = spaceIdx === -1 ? out : out.slice(0, spaceIdx); + const command = spaceIdx === -1 ? '' : out.slice(spaceIdx + 1); + // argv0 = first whitespace-delimited token; compare its basename. + const argv0 = command.split(/\s+/)[0] ?? ''; + const argv0Base = argv0.split('/').pop() ?? ''; + if (argv0Base === SELF_BINARY) { + return true; + } + const nextPid = Number.parseInt(ppidStr, 10); + if (!Number.isFinite(nextPid) || nextPid === pid) { + break; + } + pid = nextPid; + } + } catch { + // ps unavailable / query failed — guard simply does not engage here. + } + return false; + } + /** * Initialize client pool by reading config and connecting to servers */ @@ -130,6 +196,22 @@ export class MCPClientPool implements IToolSchemaProvider { return; } + // Recursion guard: if this code-executor is itself nested under another + // code-executor — directly, or indirectly via an MCP host such as an agent + // gateway — do NOT connect to any downstream servers, to prevent a spawn + // cycle that would fork-bomb the machine. + const allowNested = process.env.CODE_EXECUTOR_ALLOW_NESTED === '1' + || process.env.CODE_EXECUTOR_ALLOW_NESTED === 'true'; + if (!allowNested && MCPClientPool.hasCodeExecutorAncestor()) { + console.error( + `🛑 Nested code-executor detected (a code-executor process is an ancestor — ` + + `cyclic MCP topology) — running in LEAF MODE: not connecting to any downstream ` + + `MCP servers, to prevent a spawn cycle. Set CODE_EXECUTOR_ALLOW_NESTED=1 to override.` + ); + this.initialized = true; + return; + } + try { let config: MCPConfig; From 01ee82ab0d61bcb9f34b16e8afc2c9ac2cfbb3d2 Mon Sep 17 00:00:00 2001 From: SWSAmor Date: Mon, 1 Jun 2026 10:09:01 +0200 Subject: [PATCH 3/4] fix(mcp): path-based self-exclusion (skip code-executor wired as downstream) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/mcp/client-pool.ts | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/mcp/client-pool.ts b/src/mcp/client-pool.ts index f5632c7..caba777 100644 --- a/src/mcp/client-pool.ts +++ b/src/mcp/client-pool.ts @@ -188,6 +188,21 @@ export class MCPClientPool implements IToolSchemaProvider { return false; } + /** + * Whether a downstream server config points at code-executor itself (so + * launching it would recurse). Matches the command's basename against our + * binary name, or exact equality with our own executable path — independent + * of the config key name. HTTP servers are never self. + */ + private static isSelfServer(config: MCPServerConfig): boolean { + if (!isStdioConfig(config)) { + return false; + } + const command = config.command ?? ''; + const base = command.split('/').pop() ?? ''; + return base === 'code-executor-mcp' || command === process.execPath; + } + /** * Initialize client pool by reading config and connecting to servers */ @@ -299,7 +314,23 @@ export class MCPClientPool implements IToolSchemaProvider { } const filteredServers = Object.entries(config.mcpServers).filter( - ([serverName]) => !excludeSet.has(serverName) + ([serverName, serverConfig]) => { + // Name-based exclusion (self under the conventional "code-executor" + // key, plus user/env exclusions). + if (excludeSet.has(serverName)) { + return false; + } + // Path-based self-exclusion: never launch a downstream server that is + // code-executor itself — regardless of the config key name. This + // catches the "wired self in under a different name" case that the + // name check above would miss. (Does not catch an indirect cycle via + // a different host program; the ancestry guard handles that.) + if (MCPClientPool.isSelfServer(serverConfig)) { + console.error(`🚫 Skipping downstream server '${serverName}': its command is code-executor itself (would recurse).`); + return false; + } + return true; + } ); const userExclusions = [...excludeSet].filter(n => n !== 'code-executor'); From be6b13cf1f25c7b71e321f4ecdde584119a44724 Mon Sep 17 00:00:00 2001 From: SWSAmor Date: Mon, 1 Jun 2026 10:17:30 +0200 Subject: [PATCH 4/4] test(mcp): cover recursion guards; docs(changelog): document pool resilience - 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 --- CHANGELOG.md | 58 ++++++++++ docs/mcp-pool-startup-resilience.md | 155 +++++++++++++++++++++++++ tests/pool-config-validation.test.ts | 4 + tests/recursion-guard.test.ts | 165 +++++++++++++++++++++++++++ 4 files changed, 382 insertions(+) create mode 100644 docs/mcp-pool-startup-resilience.md create mode 100644 tests/recursion-guard.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index b533f10..63e8588 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### 🛡️ MCP pool startup resilience & spawn-cycle protection + +Hardens code-executor startup against two failure modes observed when running +behind an MCP host (e.g. the Hermes agent gateway): a respawn loop driven by +slow/unreachable downstream servers, and a fork bomb caused by a cyclic MCP +topology. See `docs/mcp-pool-startup-resilience.md` for the full diagnosis. + +#### Fixed + +- **Startup respawn loop** — the upstream MCP handshake was answered only AFTER + connecting to every downstream server, so one slow/unreachable server delayed + startup past the host's timeout, causing the host to kill and respawn the + process repeatedly (each spawn leaking child MCP processes). + - **Fix:** connect the upstream stdio transport FIRST, then initialize the + downstream client pool in the background. Tool handlers await pool readiness + before executing. Total downstream failure no longer crashes the server. + - **Files:** `src/index.ts`, `src/mcp/client-pool.ts` + +- **Spawn cycle / fork bomb** — when the host lists code-executor as a server + AND code-executor's config lists that same host as a downstream server, the + two spawn each other indefinitely. Name-based self-exclusion cannot catch this + (the intermediary is a different program). + - **Fix:** at startup, walk the parent-PID chain (`ps`); if any ancestor is + itself a code-executor, run in LEAF MODE (connect to no downstream servers). + Reliable even when the host strips the environment of its children. + Overridable via `CODE_EXECUTOR_ALLOW_NESTED=1`. + - **Files:** `src/mcp/client-pool.ts` + +- **Orphaned child MCP processes** — children spawned during a connect that was + killed mid-init were not tracked, so they leaked as orphans. + - **Fix:** track in-flight transports and reap them on shutdown; add a + synchronous `process.on('exit')` backstop that SIGKILLs all spawned children. + - **Files:** `src/mcp/client-pool.ts`, `src/index.ts` + +#### Added + +- **Per-server connect timeout** — each downstream connect is bounded by + `POOL_CONNECT_TIMEOUT_MS` (default 15000, range 1000–120000); a hung server is + marked failed instead of blocking the whole pool. On timeout its spawned child + is killed explicitly by PID (AbortController-based kill is unreliable on Bun). + - **Files:** `src/config/types.ts`, `src/config/loader.ts`, `src/mcp/client-pool.ts` + +- **Path-based self-exclusion** — a downstream server whose command IS + code-executor itself (binary basename or exact `process.execPath`) is skipped + regardless of its config key name, catching "wired self in under a different + name" that the name-based exclusion misses. + - **Files:** `src/mcp/client-pool.ts` + +- **Per-server startup status report** — pool init logs one line per configured + server (✓/✗ with duration and failure reason) plus an N/M summary. + - **Files:** `src/mcp/client-pool.ts` + +#### Tests + +- `tests/recursion-guard.test.ts` — path-based self-exclusion and ancestry/leaf-mode + guard (including the `CODE_EXECUTOR_ALLOW_NESTED` override). +- `tests/pool-config-validation.test.ts` — `connectTimeoutMs` default and parsing. + ## [1.0.5] - 2025-11-23 ### 🚨 CRITICAL BUGFIX #4 diff --git a/docs/mcp-pool-startup-resilience.md b/docs/mcp-pool-startup-resilience.md new file mode 100644 index 0000000..2c17c44 --- /dev/null +++ b/docs/mcp-pool-startup-resilience.md @@ -0,0 +1,155 @@ +# MCP Pool Startup Resilience & Spawn-Cycle Protection + +Status: implemented (branch `fix/mcp-pool-startup-resilience`) + +This note documents two production failure modes observed when code-executor +runs behind an MCP host (the Hermes agent gateway), their root causes, the +fixes, and — importantly — *why* each fix is shaped the way it is. The +alternatives that were tried and rejected are recorded so the reasoning is not +lost. + +## Symptoms + +1. **Respawn storm** — hundreds of code-executor startups in the host log + (`~/.hermes/logs/mcp-stderr.log`), restarting roughly once per second; many + downstream MCP child processes left behind. +2. **Fork bomb** — dozens of `code-executor-mcp` *and* `hermes mcp serve` + processes, growing every ~2 seconds, in a clean alternating parent chain. + +## Root causes + +### A. Startup coupled to downstream pool init → respawn loop + +Original `start()` order: + +``` +await mcpClientPool.initialize(); // connect to ALL downstream servers (blocking) +await server.connect(transport); // only now answer the host's MCP handshake +``` + +`initialize()` used `Promise.allSettled` over all downstream connects with **no +per-server timeout**, so a single slow/unreachable server (HTTP servers were the +worst offenders) blocked the whole thing. The host's `initialize` request went +unanswered past its startup timeout → the host killed the process and respawned +it → loop. Each spawn had already begun launching child MCP servers, which were +then orphaned. + +### B. Cyclic MCP topology → fork bomb + +Not direct self-inclusion — code-executor is correctly excluded from its own +pool by the `code-executor` config key. The real cause was a **cycle through a +second program**: + +- the host's MCP config lists `code-executor` as a server; +- code-executor's merged config (`~/.mcp_ce.json`) lists the host + (`hermes mcp serve`) as a downstream server. + +So: `gateway → code-executor → hermes mcp serve → code-executor → hermes → …` +Name-based self-exclusion cannot catch this because the intermediary +(`hermes`) is a different program. + +## Fixes + +### 1. Decouple the upstream handshake from downstream pool init + +`start()` now connects the stdio transport to the host **first**, then runs +`mcpClientPool.initialize()` in the **background** (`this.poolReady`). The host +gets its `initialize`/`tools/list` answer immediately, independent of downstream +health. The `executeTypescript`/`executePython` handlers `await this.poolReady` +before running, so downstream tools are ready (or known-unavailable) by the time +user code executes. A total downstream failure is caught and logged — the server +stays up instead of crashing. + +### 2. Per-server connect timeout + graceful degradation + +Each connect races against `POOL_CONNECT_TIMEOUT_MS` (default 15 s). A hung +server is recorded as failed; the pool comes up with whatever connected. A +failed/timed-out server is **never** added to `clients`/`toolCache`, so its tools +are neither discoverable nor callable — partial availability "just works". +`initialize()` logs a per-server report (✓/✗ + duration + reason). + +### 3. Recursion guard via parent-PID ancestry (the key fix for B) + +At startup, walk the parent-PID chain with `ps`; 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. This bounds the cycle: + +``` +gateway → code-executor (full) → hermes mcp serve → code-executor (LEAF — stops) +``` + +Override with `CODE_EXECUTOR_ALLOW_NESTED=1`. + +### 4. Path-based self-exclusion + +A downstream server whose command IS code-executor itself (binary basename, or +exact `process.execPath`) is skipped regardless of its config key name — catches +"wired self in under a different name". + +### 5. Orphan reaping + +In-flight transports are tracked in `pendingStdioTransports` and reaped on +shutdown; a synchronous `process.on('exit')` handler SIGKILLs all spawned +children as a last-resort backstop (covers host SIGKILL after a timeout). + +## Design decisions & rejected alternatives + +- **Background pool init vs. just adding timeouts.** Timeouts alone still risk + exceeding an unknown host startup window. Answering the handshake first fully + decouples our readiness from downstream health — the robust fix. + +- **Process ancestry vs. an inherited env marker.** The first attempt stamped + spawned children with `CODE_EXECUTOR_DEPTH+1` and went leaf at a max depth. + **It failed in production:** `hermes mcp serve` does **not** forward our + environment to the code-executor it spawns, so the marker never arrived and + the fork bomb continued. Parent PIDs are always readable from the process + table, independent of what the intermediary does with the environment. The env + approach was removed. + +- **Why the whole chain, not just the direct parent.** In the cyclic case the + direct parent is the host (`hermes`), not a code-executor; the code-executor + ancestor is one hop further up. + +- **Why match `argv0` basename, not the full command line.** Matching the whole + command line produced a false positive: a top-level instance launched via a + shell wrapper (`sh -c "… /path/code-executor-mcp …"`) counted its own launcher + as an ancestor and wrongly went leaf. `argv0` of a shell wrapper is `sh`. + +- **Why LEAF MODE, not exit.** A nested instance that exits would make the host + see a failed MCP server and likely respawn it → back to a respawn loop. + Staying alive but inert answers the host's handshake and is stable. + +- **Why this cannot reach "exactly one" process for the cyclic config.** The + nested code-executor is spawned by the *host*, not by code-executor, so + code-executor cannot prevent its creation; it can only make it inert (leaf). + The host and the nested leaf instance are a stable, harmless pair. Reaching a + single process requires breaking the config cycle (remove the host entry from + code-executor's downstream config, or remove code-executor from the host's + config) — the cycle is fundamentally a configuration issue; the guards make it + *safe*, not invisible. + +## Runtime notes (Bun) + +The shipped artifact is a `bun --compile` single binary, so `process.execPath` +is the code-executor binary itself, signal/`process.kill` and `process.on('exit')` +behave as on Node, and child kill is done explicitly by PID because the +AbortController-based kill in the MCP SDK's stdio transport is not reliable under +Bun. The ancestry walk uses `ps`; on platforms without it (Windows) the guard is +best-effort and simply does not engage. + +## Configuration + +| Env var | Default | Purpose | +|---|---|---| +| `POOL_CONNECT_TIMEOUT_MS` | `15000` | Per-downstream-server connect timeout (1000–120000). | +| `CODE_EXECUTOR_ALLOW_NESTED` | unset | Set to `1`/`true` to disable the ancestry leaf-mode guard. | + +## Verification + +Unit tests: `tests/recursion-guard.test.ts` (self-exclusion + leaf mode + +override), `tests/pool-config-validation.test.ts` (`connectTimeoutMs`). + +Manual, on the compiled binary: confirmed the transport connects before pool +init; a hung server is timed out and its child killed; a top-level instance runs +full while an instance it transitively spawns (with the environment stripped, as +the host does) detects the ancestor and runs leaf, spawning nothing. diff --git a/tests/pool-config-validation.test.ts b/tests/pool-config-validation.test.ts index af2f03a..23b4a2d 100644 --- a/tests/pool-config-validation.test.ts +++ b/tests/pool-config-validation.test.ts @@ -20,6 +20,7 @@ describe('Pool Configuration Validation (SEC-002)', () => { delete process.env.POOL_MAX_CONCURRENT; delete process.env.POOL_QUEUE_SIZE; delete process.env.POOL_QUEUE_TIMEOUT_MS; + delete process.env.POOL_CONNECT_TIMEOUT_MS; }); afterEach(() => { @@ -34,6 +35,7 @@ describe('Pool Configuration Validation (SEC-002)', () => { expect(config.maxConcurrent).toBe(100); expect(config.queueSize).toBe(200); expect(config.queueTimeoutMs).toBe(30000); + expect(config.connectTimeoutMs).toBe(15000); }); }); @@ -42,12 +44,14 @@ describe('Pool Configuration Validation (SEC-002)', () => { process.env.POOL_MAX_CONCURRENT = '50'; process.env.POOL_QUEUE_SIZE = '100'; process.env.POOL_QUEUE_TIMEOUT_MS = '60000'; + process.env.POOL_CONNECT_TIMEOUT_MS = '8000'; const config = getPoolConfig(); expect(config.maxConcurrent).toBe(50); expect(config.queueSize).toBe(100); expect(config.queueTimeoutMs).toBe(60000); + expect(config.connectTimeoutMs).toBe(8000); }); it('should_acceptMinimumValues_when_atLowerBound', () => { diff --git a/tests/recursion-guard.test.ts b/tests/recursion-guard.test.ts new file mode 100644 index 0000000..a63f663 --- /dev/null +++ b/tests/recursion-guard.test.ts @@ -0,0 +1,165 @@ +/** + * Tests for the code-executor spawn-cycle guards. + * + * A code-executor wired (directly, or indirectly via another MCP host) as a + * downstream server of another code-executor forms a spawn cycle that + * fork-bombs the machine. These tests cover the two code-level defences: + * + * 1. Path-based self-exclusion — a downstream server whose command IS + * code-executor itself is skipped at pool init, regardless of its config + * key name (the name-based exclusion only catches the "code-executor" key). + * + * 2. Parent-PID ancestry guard — if any ancestor process is itself a + * code-executor, the pool runs in LEAF MODE (connects to nothing), + * breaking indirect cycles even when the intermediate host strips the + * environment. Overridable via CODE_EXECUTOR_ALLOW_NESTED. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +// Mock modules BEFORE imports +vi.mock('fs/promises'); +vi.mock('../src/config/loader.js'); + +import * as fs from 'fs/promises'; +import { MCPClientPool } from '../src/mcp/client-pool.js'; +import * as loader from '../src/config/loader.js'; + +describe('recursion guard', () => { + let pool: MCPClientPool; + let connectSpy: ReturnType; + let originalEnv: NodeJS.ProcessEnv; + + beforeEach(() => { + vi.resetAllMocks(); + originalEnv = { ...process.env }; + delete process.env.CODE_EXECUTOR_ALLOW_NESTED; + + vi.mocked(loader.getPoolConfig).mockReturnValue({ + maxConcurrent: 100, + queueSize: 200, + queueTimeoutMs: 30000, + connectTimeoutMs: 15000, + }); + + pool = new MCPClientPool(); + + // Prevent real connections and tool caching + connectSpy = vi.fn().mockResolvedValue(undefined); + vi.spyOn(pool as any, 'connectToServer').mockImplementation(connectSpy); + vi.spyOn(pool as any, 'cacheToolListings').mockResolvedValue(undefined); + + // Default: not nested (deterministic — avoids a real `ps` walk). + vi.spyOn(MCPClientPool as any, 'hasCodeExecutorAncestor').mockReturnValue(false); + }); + + afterEach(() => { + process.env = originalEnv; + vi.clearAllMocks(); + }); + + describe('path-based self-exclusion', () => { + it('should_skipDownstream_when_commandIsCodeExecutorBinary_underAnyName', async () => { + const config = JSON.stringify({ + mcpServers: { + // Wired self in under a NON-"code-executor" key — name check misses it. + 'my-nested-ce': { command: '/opt/tools/bin/code-executor-mcp', args: [] }, + zen: { command: 'zen-mcp', args: [] }, + }, + }); + vi.mocked(loader.getAllMCPConfigPaths).mockResolvedValue(['/config.json']); + vi.mocked(fs.readFile).mockResolvedValue(config as any); + + await pool.initialize(); + + expect(connectSpy).toHaveBeenCalledTimes(1); + expect(connectSpy).toHaveBeenCalledWith('zen', expect.any(Object)); + expect(connectSpy).not.toHaveBeenCalledWith('my-nested-ce', expect.any(Object)); + }); + + it('should_skipDownstream_when_commandEqualsOwnExecutablePath', async () => { + const config = JSON.stringify({ + mcpServers: { + self: { command: process.execPath, args: [] }, + zen: { command: 'zen-mcp', args: [] }, + }, + }); + vi.mocked(loader.getAllMCPConfigPaths).mockResolvedValue(['/config.json']); + vi.mocked(fs.readFile).mockResolvedValue(config as any); + + await pool.initialize(); + + expect(connectSpy).not.toHaveBeenCalledWith('self', expect.any(Object)); + expect(connectSpy).toHaveBeenCalledWith('zen', expect.any(Object)); + }); + + it('should_notSkipDownstream_when_commandIsUnrelatedBinary', async () => { + const config = JSON.stringify({ + mcpServers: { + // basename "code-executor-client" must NOT match "code-executor-mcp" + decoy: { command: '/usr/bin/code-executor-client', args: [] }, + }, + }); + vi.mocked(loader.getAllMCPConfigPaths).mockResolvedValue(['/config.json']); + vi.mocked(fs.readFile).mockResolvedValue(config as any); + + await pool.initialize(); + + expect(connectSpy).toHaveBeenCalledWith('decoy', expect.any(Object)); + }); + }); + + describe('parent-PID ancestry guard (leaf mode)', () => { + it('should_connectToNothing_when_codeExecutorAncestorPresent', async () => { + vi.spyOn(MCPClientPool as any, 'hasCodeExecutorAncestor').mockReturnValue(true); + + const config = JSON.stringify({ + mcpServers: { + zen: { command: 'zen-mcp', args: [] }, + other: { command: 'other-mcp', args: [] }, + }, + }); + vi.mocked(loader.getAllMCPConfigPaths).mockResolvedValue(['/config.json']); + vi.mocked(fs.readFile).mockResolvedValue(config as any); + + await pool.initialize(); + + // Leaf mode: returns before connecting to anything. + expect(connectSpy).not.toHaveBeenCalled(); + expect(pool.listAllTools()).toEqual([]); + }); + + it('should_connectNormally_when_noCodeExecutorAncestor', async () => { + // hasCodeExecutorAncestor already mocked to false in beforeEach. + const config = JSON.stringify({ + mcpServers: { + zen: { command: 'zen-mcp', args: [] }, + }, + }); + vi.mocked(loader.getAllMCPConfigPaths).mockResolvedValue(['/config.json']); + vi.mocked(fs.readFile).mockResolvedValue(config as any); + + await pool.initialize(); + + expect(connectSpy).toHaveBeenCalledWith('zen', expect.any(Object)); + }); + + it('should_ignoreAncestorGuard_when_allowNestedEnvSet', async () => { + process.env.CODE_EXECUTOR_ALLOW_NESTED = '1'; + vi.spyOn(MCPClientPool as any, 'hasCodeExecutorAncestor').mockReturnValue(true); + + const config = JSON.stringify({ + mcpServers: { + zen: { command: 'zen-mcp', args: [] }, + }, + }); + vi.mocked(loader.getAllMCPConfigPaths).mockResolvedValue(['/config.json']); + vi.mocked(fs.readFile).mockResolvedValue(config as any); + + await pool.initialize(); + + // Override in effect: connects despite the ancestor. + expect(connectSpy).toHaveBeenCalledWith('zen', expect.any(Object)); + }); + }); +});