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
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
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';
Expand Down Expand Up @@ -718,6 +719,19 @@
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
Expand Down Expand Up @@ -936,7 +950,7 @@
await server.start();
} catch (error) {
console.error('Fatal error:', error);
process.exit(1);

Check failure on line 953 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:953: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.
}
})();
}
46 changes: 46 additions & 0 deletions src/mcp/stdin-watcher.ts
Original file line number Diff line number Diff line change
@@ -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'));
}
62 changes: 62 additions & 0 deletions tests/stdin-watcher.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading