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
30 changes: 29 additions & 1 deletion docs/mcp-pool-startup-resilience.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,17 +137,45 @@ AbortController-based kill in the MCP SDK's stdio transport is not reliable unde
Bun. The ancestry walk uses `ps`; on platforms without it (Windows) the guard is
best-effort and simply does not engage.

## Parent-liveness watchdog and graceful child cleanup

`stdin` EOF (see `src/mcp/stdin-watcher.ts`) is the primary signal that the MCP
host is gone, but it is not always delivered: the host can be SIGKILLed, or a
launcher/wrapper (or a child that inherited fd 0) can hold the write end of our
stdin pipe open, so the EOF never arrives. Without a second signal the server β€”
and every downstream MCP child it spawned β€” orphans forever.

- **Active parent poll** (`src/mcp/parent-watcher.ts`): on POSIX a process whose
parent dies is reparented to PID 1, so a change in `process.ppid` away from its
startup value is a reliable, pipe-independent "parent is gone" signal. The poll
is wired in `start()` and stopped in `shutdown()`; it is a no-op on Windows and
when launched directly by init (`ppid <= 1`), to avoid false positives.
- **SIGHUP** (controlling terminal / session leader gone) is treated as a
graceful shutdown rather than the default terminate.
- **Bounded graceful child kill** (`src/mcp/process-killer.ts`): `disconnect()`
sends SIGTERM, polls for exit, and SIGKILLs only once a configurable grace
window elapses (a child that honors SIGTERM is not delayed). `client.close()` /
`transport.close()` are bounded so a wedged child cannot stall the kill
sequence before it runs.

## 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. |
| `CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS` | `2000` | Cadence of the parent-liveness poll (500–60000). |
| `CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS` | `30000` | SIGTERMβ†’SIGKILL grace per downstream child (1000–300000). |
| `CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS` | `2000` | Per-client `close()` timeout during shutdown (250–30000). |

## Verification

Unit tests: `tests/recursion-guard.test.ts` (self-exclusion + leaf mode +
override), `tests/pool-config-validation.test.ts` (`connectTimeoutMs`).
override), `tests/pool-config-validation.test.ts` (`connectTimeoutMs`),
`tests/parent-watcher.test.ts` (ppid reparent detection),
`tests/process-killer.test.ts` (graceful β†’ force kill), `tests/shutdown-config.test.ts`
(clamped shutdown env knobs), `tests/integration/orphan-cleanup.test.ts`
(real-binary stdin-close and parent-death child reaping).

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
Expand Down
87 changes: 87 additions & 0 deletions src/config/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,3 +460,90 @@ export function getDockerContainer(): string | undefined {
// (will be removed in v2.0)
export const DEFAULT_TIMEOUT_MS = 30000;
export const MAX_TIMEOUT_MS = 300000;

/**
* Lifecycle / shutdown timeout knobs.
*
* These govern graceful self-shutdown and downstream child cleanup:
* - CHILD_SHUTDOWN: SIGTERM→SIGKILL grace per spawned child (default 30s).
* - PARENT_POLL: cadence of the parent-liveness poll (default 2s).
* - CLIENT_CLOSE: per-client close() timeout so a wedged child cannot stall
* shutdown before the kill sequence runs (default 2s).
*/
export const DEFAULT_CHILD_SHUTDOWN_TIMEOUT_MS = 30_000;
const MIN_CHILD_SHUTDOWN_TIMEOUT_MS = 1_000;
const MAX_CHILD_SHUTDOWN_TIMEOUT_MS = 300_000; // 5 min ceiling

export const DEFAULT_PARENT_POLL_INTERVAL_MS = 2_000;
const MIN_PARENT_POLL_INTERVAL_MS = 500;
const MAX_PARENT_POLL_INTERVAL_MS = 60_000;

export const DEFAULT_CLIENT_CLOSE_TIMEOUT_MS = 2_000;
const MIN_CLIENT_CLOSE_TIMEOUT_MS = 250;
const MAX_CLIENT_CLOSE_TIMEOUT_MS = 30_000;

/**
* Read a bounded integer env var for the shutdown path.
*
* **WHY clamp instead of throw:** unlike {@link getCharacterLimit} (read on the
* execution/output path, where fail-fast is fine), these knobs are read while
* SHUTTING DOWN. A throw here would abort the very cleanup the value configures
* and re-create the orphan it is meant to prevent. So a non-numeric value falls
* back to the default and an out-of-range value is clamped β€” shutdown never
* throws on a misconfigured timeout.
*/
function getBoundedEnvMs(
value: string | undefined,
defaultMs: number,
minMs: number,
maxMs: number
): number {
if (!value) return defaultMs;
const parsed = parseInt(value, 10);
if (isNaN(parsed)) return defaultMs;
if (parsed < minMs) return minMs;
if (parsed > maxMs) return maxMs;
return parsed;
}

/**
* Grace period (ms) a spawned child gets after SIGTERM before it is SIGKILLed.
*
* Exit is polled, so a child that honors SIGTERM exits well within this window
* and is not delayed; the timeout only bounds a misbehaving/wedged child.
* Overridable via CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS (1s..5min).
*/
export function getChildShutdownTimeoutMs(): number {
return getBoundedEnvMs(
process.env.CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS,
DEFAULT_CHILD_SHUTDOWN_TIMEOUT_MS,
MIN_CHILD_SHUTDOWN_TIMEOUT_MS,
MAX_CHILD_SHUTDOWN_TIMEOUT_MS
);
}

/**
* Cadence (ms) of the active parent-liveness poll.
* Overridable via CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS (0.5s..60s).
*/
export function getParentPollIntervalMs(): number {
return getBoundedEnvMs(
process.env.CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS,
DEFAULT_PARENT_POLL_INTERVAL_MS,
MIN_PARENT_POLL_INTERVAL_MS,
MAX_PARENT_POLL_INTERVAL_MS
);
}

/**
* Per-client close() timeout (ms) during shutdown.
* Overridable via CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS (0.25s..30s).
*/
export function getClientCloseTimeoutMs(): number {
return getBoundedEnvMs(
process.env.CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS,
DEFAULT_CLIENT_CLOSE_TIMEOUT_MS,
MIN_CLIENT_CLOSE_TIMEOUT_MS,
MAX_CLIENT_CLOSE_TIMEOUT_MS
);
}
35 changes: 34 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import { initConfig, isPythonEnabled, isRateLimitEnabled, getRateLimitConfig, shouldSkipDangerousPatternCheck } from './config/loader.js';
import { initConfig, isPythonEnabled, isRateLimitEnabled, getRateLimitConfig, shouldSkipDangerousPatternCheck, getParentPollIntervalMs } from './config/loader.js';
import { ExecuteTypescriptInputSchema, ExecutePythonInputSchema, ExecutionResultSchema } from './config/schemas.js';
import { MCPClientPool } from './mcp/client-pool.js';
import { watchClientDisconnect } from './mcp/stdin-watcher.js';
import { watchParentExit } from './mcp/parent-watcher.js';
import { redirectConsoleLogToStderr } from './utils/stdio-guard.js';
import { SecurityValidator } from './validation/security-validator.js';
import { ConnectionPool } from './mcp/connection-pool.js';
Expand Down Expand Up @@ -73,6 +74,8 @@ class CodeExecutorServer {
// 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();
// Halts the active parent-liveness poll (see start()). Null until start() wires it.
private stopParentWatch: (() => void) | null = null;

constructor() {
// Initialize MCP server
Expand Down Expand Up @@ -737,6 +740,26 @@ Returns:
});
});

// Belt-and-suspenders to the stdin watcher above: actively poll parent
// liveness. stdin EOF can fail to arrive (host SIGKILLed, or a wrapper/child
// holds our stdin pipe open), and then the poll is the only signal that the
// host is gone. On POSIX, parent death reparents us to PID 1; that is what we
// watch for. See parent-watcher.ts.
const initialPpid = process.ppid;
this.stopParentWatch = watchParentExit({
getPpid: () => process.ppid,
initialPpid,
intervalMs: getParentPollIntervalMs(),
isPosix: process.platform !== 'win32',
onParentExit: (reason) => {
console.error(`Parent process gone (${reason}) β€” initiating shutdown...`);
void this.shutdown().catch((error) => {
console.error('Error during parent-exit-triggered shutdown:', error);
process.exit(1);
});
},
});

console.error('Code Executor MCP Server started successfully (downstream MCP pool initializing in background)');

// Initialize MCP client pool in the background. Tool handlers await
Expand Down Expand Up @@ -809,6 +832,13 @@ Returns:
}
this.shutdownInProgress = true;

// Stop the parent-liveness poll β€” shutdown is underway (its internal guard
// also fires onParentExit at most once, so this is hygiene, not correctness).
if (this.stopParentWatch) {
this.stopParentWatch();
this.stopParentWatch = null;
}

const shutdownStart = Date.now();

// Wrap entire shutdown in timeout protection
Expand Down Expand Up @@ -885,6 +915,9 @@ const handleShutdownSignal = async (signal: string) => {

process.on('SIGINT', () => void handleShutdownSignal('SIGINT'));
process.on('SIGTERM', () => void handleShutdownSignal('SIGTERM'));
// SIGHUP: controlling terminal / session leader went away (a common parent-death
// signal). Treat it as a graceful shutdown rather than the default (terminate).
process.on('SIGHUP', () => void handleShutdownSignal('SIGHUP'));

// Synchronous last-resort cleanup. If the process exits without the async
// graceful path completing (e.g. host sends SIGKILL after a timeout, or an
Expand Down
131 changes: 65 additions & 66 deletions src/mcp/client-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ 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 { getPoolConfig, getChildShutdownTimeoutMs, getClientCloseTimeoutMs } from '../config/loader.js';
import { killProcessGracefully } from './process-killer.js';
import { isValidMCPToolName, normalizeError, isErrnoException } from '../utils/utils.js';
import type { MCPConfig, MCPServerConfig, ToolInfo, ProcessInfo, StdioServerConfig, HttpServerConfig } from '../types.js';
import { isStdioConfig, isHttpConfig } from '../types.js';
Expand Down Expand Up @@ -1037,82 +1038,80 @@ export class MCPClientPool implements IToolSchemaProvider {
}

/**
* Disconnect all clients and kill child processes
* Await `close()` but never let it hang shutdown.
*
* Graceful shutdown: SIGTERM β†’ wait 2s β†’ SIGKILL
* WHY: a wedged downstream child (e.g. basic-memory stuck on a lock) can make
* the SDK's `client.close()` / `transport.close()` block indefinitely. Before
* this bound, that hung the whole disconnect() BEFORE the SIGTERM→SIGKILL step
* ran, so the child orphaned anyway. We cap the close and then proceed to kill
* the underlying PID regardless.
*/
async disconnect(): Promise<void> {
// Close MCP clients
const disconnections = Array.from(this.clients.values()).map(
async (client) => {
try {
await client.close();
} catch (error) {
console.error('Error disconnecting client:', error);
}
private async closeWithTimeout(
close: () => Promise<void>,
timeoutMs: number,
label: string
): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<void>((resolve) => {
timer = setTimeout(() => {
console.error(`⚠️ ${label} did not close within ${timeoutMs}ms β€” proceeding to terminate`);
resolve();
}, timeoutMs);
});
try {
await Promise.race([
close().catch((error) => console.error(`Error closing ${label}:`, error)),
timeout,
]);
} finally {
if (timer) {
clearTimeout(timer);
}
);

await Promise.all(disconnections);
}
}

// Kill child processes (STDIO servers only)
const processCleanup = Array.from(this.processes.values()).map(
async (processInfo) => {
try {
const { pid, serverName } = processInfo;
/**
* Disconnect all clients and kill child processes.
*
* Graceful shutdown per child: SIGTERM β†’ poll for exit β†’ SIGKILL once the
* configured grace window (CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS, default
* 30s) elapses. `client.close()` is bounded (CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS)
* so a wedged child cannot stall the kill sequence.
*/
async disconnect(): Promise<void> {
const closeTimeoutMs = getClientCloseTimeoutMs();
const childTimeoutMs = getChildShutdownTimeoutMs();
const logToStderr = (message: string): void => console.error(message);

// Try graceful shutdown (SIGTERM)
try {
process.kill(pid, 'SIGTERM');
console.error(`βœ“ Sent SIGTERM to ${serverName} (PID ${pid})`);

// Wait 2 seconds for graceful shutdown
await new Promise((resolve) => setTimeout(resolve, 2000));

// Check if process still exists
try {
process.kill(pid, 0); // Signal 0 checks existence
// Process still alive, force kill
process.kill(pid, 'SIGKILL');
console.error(`⚠️ Force killed ${serverName} (PID ${pid}) with SIGKILL`);
} catch {
// Process already exited
console.error(`βœ“ ${serverName} (PID ${pid}) exited gracefully`);
}
} catch (error) {
// Process might already be dead, safe to ignore ESRCH (No such process)
// TYPE-001 fix: Use isErrnoException type guard instead of unsafe cast
if (!isErrnoException(error) || error.code !== 'ESRCH') {
console.error(`Error killing ${serverName} (PID ${pid}):`, error);
}
}
} catch (error) {
console.error('Error during process cleanup:', error);
}
}
// Close MCP clients β€” bounded, so a wedged client cannot stall the kill step.
const disconnections = Array.from(this.clients.values()).map((client) =>
this.closeWithTimeout(() => client.close(), closeTimeoutMs, 'MCP client')
);
await Promise.all(disconnections);

// Kill tracked STDIO child processes (graceful β†’ force after grace window).
const processCleanup = Array.from(this.processes.values()).map(({ pid, serverName }) =>
killProcessGracefully(pid, {
timeoutMs: childTimeoutMs,
logger: logToStderr,
serverName,
})
);
await Promise.all(processCleanup);

// Close any transports whose connect() is still in flight (mid-init shutdown).
// Close 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
}
}
const pendingCleanup = Array.from(this.pendingStdioTransports).map(async (transport) => {
const pid = transport.pid;
await this.closeWithTimeout(() => transport.close(), closeTimeoutMs, 'pending transport');
if (pid != null) {
await killProcessGracefully(pid, {
timeoutMs: childTimeoutMs,
logger: logToStderr,
serverName: 'pending-transport',
});
}
);
});
await Promise.all(pendingCleanup);
this.pendingStdioTransports.clear();

Expand Down
Loading
Loading