diff --git a/CHANGELOG.md b/CHANGELOG.md index 63e8588..b111e26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,19 @@ topology. See `docs/mcp-pool-startup-resilience.md` for the full diagnosis. synchronous `process.on('exit')` backstop that SIGKILLs all spawned children. - **Files:** `src/mcp/client-pool.ts`, `src/index.ts` +- **Orphaned process tree on host disconnect** — when the MCP host (e.g. Claude + Code) exited, the code-executor it spawned kept running, taking its whole + downstream pool (Hermes + nested code-executor) with it. On macOS a child + receives no signal when its parent dies, and the SDK's `StdioServerTransport` + listens only for `'data'`/`'error'` on stdin — it never translates the EOF + from the closed pipe into a transport close. With nothing acting on the EOF, + the process never reached `exit`, so even the `process.on('exit')` reap + backstop never fired. Multiple host sessions accumulated whole orphan trees. + - **Fix:** watch `process.stdin` for `'end'`/`'close'` after the transport + connects and trigger the existing graceful `shutdown()` (which disconnects + the downstream pool, SIGTERM/SIGKILLs its children, then exits). + - **Files:** `src/mcp/stdin-watcher.ts` (new), `src/index.ts` + #### Added - **Per-server connect timeout** — each downstream connect is bounded by diff --git a/src/index.ts b/src/index.ts index c68635b..e64953a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,6 +16,7 @@ import { z } from 'zod'; import { initConfig, isPythonEnabled, isRateLimitEnabled, getRateLimitConfig, shouldSkipDangerousPatternCheck } 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 { SecurityValidator } from './validation/security-validator.js'; import { ConnectionPool } from './mcp/connection-pool.js'; import { RateLimiter } from './security/rate-limiter.js'; @@ -718,6 +719,19 @@ Returns: const transport = new StdioServerTransport(); await this.server.connect(transport); + // Shut down when the MCP host disconnects. The host's exit closes our stdin + // pipe (EOF); on macOS that is the only signal we get that the parent is + // gone (no death signal is delivered to children), and the SDK transport + // does not act on it. Without this the server and every downstream MCP + // child it spawned orphan after the host exits. See stdin-watcher.ts. + watchClientDisconnect(process.stdin, (reason) => { + console.error(`stdin ${reason} — MCP client disconnected, initiating shutdown...`); + void this.shutdown().catch((error) => { + console.error('Error during disconnect-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 diff --git a/src/mcp/stdin-watcher.ts b/src/mcp/stdin-watcher.ts new file mode 100644 index 0000000..89421b7 --- /dev/null +++ b/src/mcp/stdin-watcher.ts @@ -0,0 +1,46 @@ +/** + * Client-disconnect detection for the stdio MCP transport. + * + * WHY: When the MCP host (our parent process, e.g. Claude Code) exits, our + * stdin pipe receives EOF. On macOS a child process is NOT signalled when its + * parent dies (there is no `PR_SET_PDEATHSIG` equivalent), and the MCP SDK's + * StdioServerTransport listens only for 'data'/'error' on stdin — it never + * translates EOF into a transport close. So this stdin EOF is the only reliable + * signal that the client is gone. Without acting on it, the server (and every + * downstream MCP child it spawned) lingers forever as an orphan after the host + * exits. + * + * Kept as a standalone, side-effect-free module so it is unit-testable with a + * fake stream — importing the main server module would run its startup side + * effects (signal handlers, server.start()). + */ + +import type { EventEmitter } from 'node:events'; + +/** + * Invoke `onDisconnect` exactly once when `stdin` reaches EOF or closes. + * + * Both 'end' (no more data to read) and 'close' (stream fully closed) can fire + * for a single disconnect; the internal guard ensures `onDisconnect` runs at + * most once. + * + * @param stdin - The input stream to watch (typically `process.stdin`). + * @param onDisconnect - Called with the triggering event name ('end'/'close'). + */ +export function watchClientDisconnect( + stdin: EventEmitter, + onDisconnect: (reason: string) => void +): void { + let fired = false; + + const fire = (reason: string): void => { + if (fired) { + return; + } + fired = true; + onDisconnect(reason); + }; + + stdin.once('end', () => fire('end')); + stdin.once('close', () => fire('close')); +} diff --git a/tests/stdin-watcher.test.ts b/tests/stdin-watcher.test.ts new file mode 100644 index 0000000..e64edf8 --- /dev/null +++ b/tests/stdin-watcher.test.ts @@ -0,0 +1,62 @@ +/** + * Tests for the stdio client-disconnect watcher. + * + * When the MCP host (parent process) exits, our stdin pipe receives EOF. On + * macOS no death signal reaches the child and the SDK transport never acts on + * the EOF, so without watching stdin the server — and every downstream MCP + * child it spawned — orphans forever. watchClientDisconnect() converts that + * EOF/close into a single shutdown trigger. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { EventEmitter } from 'node:events'; +import { watchClientDisconnect } from '../src/mcp/stdin-watcher.js'; + +describe('watchClientDisconnect', () => { + it('should_invokeOnDisconnect_when_stdinEmitsEnd', () => { + const stdin = new EventEmitter(); + const onDisconnect = vi.fn(); + + watchClientDisconnect(stdin, onDisconnect); + stdin.emit('end'); + + expect(onDisconnect).toHaveBeenCalledTimes(1); + expect(onDisconnect).toHaveBeenCalledWith('end'); + }); + + it('should_invokeOnDisconnect_when_stdinEmitsClose', () => { + const stdin = new EventEmitter(); + const onDisconnect = vi.fn(); + + watchClientDisconnect(stdin, onDisconnect); + stdin.emit('close'); + + expect(onDisconnect).toHaveBeenCalledTimes(1); + expect(onDisconnect).toHaveBeenCalledWith('close'); + }); + + it('should_invokeOnDisconnectOnce_when_bothEndAndCloseFire', () => { + // A real stdin pipe emits 'end' then 'close' for a single disconnect; + // shutdown must be triggered only once. + const stdin = new EventEmitter(); + const onDisconnect = vi.fn(); + + watchClientDisconnect(stdin, onDisconnect); + stdin.emit('end'); + stdin.emit('close'); + + expect(onDisconnect).toHaveBeenCalledTimes(1); + expect(onDisconnect).toHaveBeenCalledWith('end'); + }); + + it('should_notInvokeOnDisconnect_when_streamStillOpen', () => { + // 'data' (normal traffic) must never be mistaken for a disconnect. + const stdin = new EventEmitter(); + const onDisconnect = vi.fn(); + + watchClientDisconnect(stdin, onDisconnect); + stdin.emit('data', Buffer.from('{"jsonrpc":"2.0"}')); + + expect(onDisconnect).not.toHaveBeenCalled(); + }); +});