Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
155 changes: 155 additions & 0 deletions docs/mcp-pool-startup-resilience.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion src/config/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export type RateLimitConfig = z.infer<typeof RateLimitConfigSchema>;
* - 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) */
Expand All @@ -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<typeof PoolConfigSchema>;
Expand Down
69 changes: 59 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@
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<void> = Promise.resolve();

constructor() {
// Initialize MCP server
Expand Down Expand Up @@ -281,6 +287,11 @@
};
}

// 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(
Expand Down Expand Up @@ -537,6 +548,10 @@
};
}

// 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.
Expand Down Expand Up @@ -695,12 +710,32 @@
}
}

// 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';
Expand All @@ -720,12 +755,14 @@
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();
}

/**
Expand Down Expand Up @@ -830,6 +867,18 @@
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];
Expand Down Expand Up @@ -887,7 +936,7 @@
await server.start();
} catch (error) {
console.error('Fatal error:', error);
process.exit(1);

Check failure on line 939 in src/index.ts

View workflow job for this annotation

GitHub Actions / Test & Lint

Unhandled error

Error: process.exit unexpectedly called with "1" ❯ src/index.ts:939:15 This error originated in "tests/security/sampling-attacks.test.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.
}
})();
}
Loading
Loading