Skip to content
Closed
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
87 changes: 87 additions & 0 deletions src/config/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,93 @@ export function getCharacterLimit(): number {
return override;
}

/**
* 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
);
}

/**
* Get allowed read paths
*/
Expand Down
53 changes: 47 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@
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, getChildShutdownTimeoutMs, 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 @@ -67,6 +68,7 @@
private denoAvailable: boolean = false;
private healthCheckServer: HealthCheckServer | null = null;
private shutdownInProgress = false; // P1: Prevent concurrent shutdown attempts
private stopParentWatch: (() => void) | null = null; // halts the parent-liveness poll
// 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
Expand Down Expand Up @@ -733,6 +735,25 @@
});
});

// Belt-and-suspenders to the stdin watcher above: actively poll parent
// liveness. stdin EOF can fail to arrive (host SIGKILLed, or a wrapper/an
// inherited fd holds our stdin pipe's write end open), in which case this
// 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.
this.stopParentWatch = watchParentExit({
getPpid: () => process.ppid,
initialPpid: process.ppid,
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 @@ -795,24 +816,41 @@
* 3. Clean up rate limiter
* 4. Disconnect MCP clients (with 2s SIGTERM grace period)
*
* @param timeoutMs - Maximum time for entire shutdown (default: 35s = 30s drain + 5s cleanup)
* @param timeoutMs - Maximum time for the entire shutdown. When omitted it is
* derived from config as drain + per-child grace + buffer, so the graceful
* child-kill window (CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS) is never
* pre-empted by this overall cap.
*/
async shutdown(timeoutMs: number = 35000): Promise<void> {
async shutdown(timeoutMs?: number): Promise<void> {
// P1: Prevent concurrent shutdown attempts (manual + signal handler races)
if (this.shutdownInProgress) {
console.error('Shutdown already in progress - ignoring duplicate call');
return;
}
this.shutdownInProgress = true;

// Stop the parent-liveness poll — shutdown is underway (hygiene; the guard
// above already makes a second trigger a no-op).
if (this.stopParentWatch) {
this.stopParentWatch();
this.stopParentWatch = null;
}

// Overall cap must outlast Phase-1 drain plus the Phase-4 per-child graceful
// kill window, otherwise the timeout race below would force process.exit(0)
// (and a synchronous SIGKILL via the 'exit' handler) before a legitimately
// graceful child shutdown could complete. +5s cleanup buffer.
const drainTimeoutMs = 30_000;
const effectiveTimeoutMs = timeoutMs ?? drainTimeoutMs + getChildShutdownTimeoutMs() + 5_000;

const shutdownStart = Date.now();

// Wrap entire shutdown in timeout protection
const shutdownPromise = (async () => {
// Phase 1: Drain connection pool (wait for active executions)
console.error('Phase 1: Draining connection pool...');
try {
await this.connectionPool.drain(30000); // 30s timeout for executions
await this.connectionPool.drain(drainTimeoutMs); // wait for active executions
} catch (error) {
console.error('Error draining connection pool:', error);
}
Expand Down Expand Up @@ -846,10 +884,10 @@
setTimeout(() => {
const elapsed = Date.now() - shutdownStart;
console.error(
`⚠️ Shutdown timeout after ${timeoutMs}ms (elapsed: ${elapsed}ms) - forcing exit`
`⚠️ Shutdown timeout after ${effectiveTimeoutMs}ms (elapsed: ${elapsed}ms) - forcing exit`
);
resolve();
}, timeoutMs);
}, effectiveTimeoutMs);
});

await Promise.race([shutdownPromise, timeoutPromise]);
Expand Down Expand Up @@ -881,6 +919,9 @@

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 Expand Up @@ -958,7 +999,7 @@
await server.start();
} catch (error) {
console.error('Fatal error:', error);
process.exit(1);

Check failure on line 1002 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:1002: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.
}
})();
}
133 changes: 66 additions & 67 deletions src/mcp/client-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ 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';
import { getPoolConfig, getChildShutdownTimeoutMs, getClientCloseTimeoutMs } from '../config/loader.js';
import { isValidMCPToolName, normalizeError } from '../utils/utils.js';
import { killProcessGracefully } from './process-killer.js';
import type { MCPConfig, MCPServerConfig, ToolInfo, ProcessInfo, StdioServerConfig, HttpServerConfig } from '../types.js';
import { isStdioConfig, isHttpConfig } from '../types.js';
import type { IToolSchemaProvider, CachedToolSchema } from '../types.js';
Expand Down Expand Up @@ -922,82 +923,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