From 3087c7719b800c831b8840f8b8405a5ddddbd539 Mon Sep 17 00:00:00 2001 From: Jack Arturo Date: Wed, 29 Jul 2026 11:05:50 +0200 Subject: [PATCH 1/4] fix: exit orphaned stdio MCP servers on parent death Clients can abandon sessions while a wrapper keeps stdin open, so EOF never arrives and leaked servers thrash swap. Exit on stdin close and add a parent-liveness watchdog (same approach as mcp-automem). --- __tests__/unit/lifecycle.test.ts | 34 ++++++++++ node_modules | 1 + src/index.ts | 9 +++ src/lifecycle.ts | 109 +++++++++++++++++++++++++++++++ 4 files changed, 153 insertions(+) create mode 100644 __tests__/unit/lifecycle.test.ts create mode 120000 node_modules create mode 100644 src/lifecycle.ts diff --git a/__tests__/unit/lifecycle.test.ts b/__tests__/unit/lifecycle.test.ts new file mode 100644 index 0000000..62c6537 --- /dev/null +++ b/__tests__/unit/lifecycle.test.ts @@ -0,0 +1,34 @@ +import { + DEFAULT_PARENT_WATCHDOG_MS, + parseWatchdogIntervalMs, + startParentWatchdog, +} from '../../src/lifecycle.js'; + +describe('parseWatchdogIntervalMs', () => { + it('defaults on unset/invalid/non-positive', () => { + expect(parseWatchdogIntervalMs(undefined)).toBe(DEFAULT_PARENT_WATCHDOG_MS); + expect(parseWatchdogIntervalMs('')).toBe(DEFAULT_PARENT_WATCHDOG_MS); + expect(parseWatchdogIntervalMs('nope')).toBe(DEFAULT_PARENT_WATCHDOG_MS); + expect(parseWatchdogIntervalMs('0')).toBe(DEFAULT_PARENT_WATCHDOG_MS); + expect(parseWatchdogIntervalMs('-1')).toBe(DEFAULT_PARENT_WATCHDOG_MS); + }); + + it('honours positive values floored at 100ms', () => { + expect(parseWatchdogIntervalMs('250')).toBe(250); + expect(parseWatchdogIntervalMs('50')).toBe(100); + }); +}); + +describe('startParentWatchdog', () => { + it('fires once when the probe reports parent gone', () => { + jest.useFakeTimers(); + const onDead = jest.fn(); + startParentWatchdog(1, 100, onDead, () => true); + expect(onDead).not.toHaveBeenCalled(); + jest.advanceTimersByTime(100); + expect(onDead).toHaveBeenCalledTimes(1); + jest.advanceTimersByTime(500); + expect(onDead).toHaveBeenCalledTimes(1); + jest.useRealTimers(); + }); +}); diff --git a/node_modules b/node_modules new file mode 120000 index 0000000..223a897 --- /dev/null +++ b/node_modules @@ -0,0 +1 @@ +/Users/jgarturo/Projects/OpenAI/mcp-servers/mcp-evernote/node_modules \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 389a96e..2f8be48 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ #!/usr/bin/env node import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { installStdioLifecycle } from "./lifecycle.js"; import { CallToolRequestSchema, ListToolsRequestSchema, @@ -2550,6 +2551,14 @@ async function main() { } const transport = new StdioServerTransport(); + installStdioLifecycle({ + transport, + onCloseAssignable: server, + envName: "EVERNOTE_PARENT_WATCHDOG_MS", + onShutdown: () => { + stopPolling(); + }, + }); await server.connect(transport); console.error("Evernote MCP server running on stdio"); diff --git a/src/lifecycle.ts b/src/lifecycle.ts new file mode 100644 index 0000000..02fd28b --- /dev/null +++ b/src/lifecycle.ts @@ -0,0 +1,109 @@ +/** + * Parent-liveness watchdog for the stdio MCP server. + * + * When an intermediate wrapper (npx → npm exec → node bin → server) keeps the + * server's stdin write-end open, a dead client never delivers EOF, so the leaf + * sits in the event loop forever and can thrash swap (multi-GB). stdin + * 'end'/'close', transport close, and signals all miss that orphan case. The + * watchdog catches it by noticing the original parent is gone. + * + * Kept side-effect-free on import so unit tests can cover it without spawning + * the full server. + */ + +export type ParentLivenessProbe = (parentPid: number) => boolean; + +/** Poll interval (ms) used when the env override is unset or invalid. */ +export const DEFAULT_PARENT_WATCHDOG_MS = 30_000; + +const MIN_PARENT_WATCHDOG_MS = 100; + +/** + * Parse EVERNOTE_PARENT_WATCHDOG_MS into a safe poll interval. + * + * Non-finite / zero / negative → default. No disable value: an unparseable + * knob must never silently turn orphan protection off. Floored at + * MIN_PARENT_WATCHDOG_MS so tiny inputs can't spin the CPU. + */ +export function parseWatchdogIntervalMs(raw: string | undefined): number { + const n = Number(raw); + if (!Number.isFinite(n) || n <= 0) return DEFAULT_PARENT_WATCHDOG_MS; + return Math.max(n, MIN_PARENT_WATCHDOG_MS); +} + +/** + * Default probe: the server has been reparented away from its original parent. + * POSIX only (Windows does not reparent orphans, so this is a no-op there). + */ +export function parentReparented(parentPid: number): boolean { + return process.ppid !== parentPid; +} + +/** + * Poll for the original parent's death and invoke `onDead` exactly once. + * Interval is unref'd so the watchdog alone never keeps the event loop alive. + */ +export function startParentWatchdog( + parentPid: number, + intervalMs: number, + onDead: () => void, + isParentGone: ParentLivenessProbe = parentReparented +): NodeJS.Timeout { + let fired = false; + const timer = setInterval(() => { + if (fired) return; + if (isParentGone(parentPid)) { + fired = true; + onDead(); + } + }, intervalMs); + timer.unref(); + return timer; +} + +/** + * Install stdin/transport/signal/parent-watchdog shutdown hooks. + * Call before `server.connect(transport)`. Captures `process.ppid` immediately. + */ +export function installStdioLifecycle(options: { + transport: { close?: () => unknown }; + onCloseAssignable?: { onclose?: (() => void) | null }; + envName?: string; + onShutdown?: () => void; +}): () => void { + const parentPid = process.ppid; + let shuttingDown = false; + const shutdown = (code = 0) => { + if (shuttingDown) return; + shuttingDown = true; + try { + options.onShutdown?.(); + } catch { + /* best effort */ + } + try { + void options.transport.close?.(); + } catch { + /* best effort */ + } + process.exit(code); + }; + + process.stdin.on('end', () => shutdown(0)); + process.stdin.on('close', () => shutdown(0)); + if (options.onCloseAssignable) { + options.onCloseAssignable.onclose = () => shutdown(0); + } + for (const sig of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) { + process.on(sig, () => shutdown(0)); + } + + const envName = options.envName ?? 'EVERNOTE_PARENT_WATCHDOG_MS'; + startParentWatchdog( + parentPid, + parseWatchdogIntervalMs(process.env[envName]), + () => shutdown(0) + ); + + return shutdown; +} From 05036262ca75b99fc458db6c4247dad52fb141e7 Mon Sep 17 00:00:00 2001 From: Jack Arturo Date: Wed, 29 Jul 2026 11:06:55 +0200 Subject: [PATCH 2/4] chore: remove accidental node_modules symlink from PR --- node_modules | 1 - 1 file changed, 1 deletion(-) delete mode 120000 node_modules diff --git a/node_modules b/node_modules deleted file mode 120000 index 223a897..0000000 --- a/node_modules +++ /dev/null @@ -1 +0,0 @@ -/Users/jgarturo/Projects/OpenAI/mcp-servers/mcp-evernote/node_modules \ No newline at end of file From c3b59dfa11eab9e41a7c579f541dd614a4e6821e Mon Sep 17 00:00:00 2001 From: Jack Arturo Date: Wed, 29 Jul 2026 13:35:33 +0200 Subject: [PATCH 3/4] fix: make soft stdin EOF a true no-op MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Do not transport.close() or process.exit on stdin end/close — that trips SDK onclose and breaks one-shot pipe flows. Hard exit only on parent watchdog reparent and SIGTERM/SIGINT/SIGHUP. Capture parentPid before any await; unit tests assert stdin EOF alone does not exit. --- __tests__/unit/lifecycle.test.ts | 26 ++++++++++++++++++++++++++ src/index.ts | 3 +++ src/lifecycle.ts | 28 +++++++++++++++++++++------- 3 files changed, 50 insertions(+), 7 deletions(-) diff --git a/__tests__/unit/lifecycle.test.ts b/__tests__/unit/lifecycle.test.ts index 62c6537..8dd95e9 100644 --- a/__tests__/unit/lifecycle.test.ts +++ b/__tests__/unit/lifecycle.test.ts @@ -1,5 +1,6 @@ import { DEFAULT_PARENT_WATCHDOG_MS, + installStdioLifecycle, parseWatchdogIntervalMs, startParentWatchdog, } from '../../src/lifecycle.js'; @@ -32,3 +33,28 @@ describe('startParentWatchdog', () => { jest.useRealTimers(); }); }); + +describe('installStdioLifecycle soft stdin EOF', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('does not close transport or exit on stdin end/close', () => { + const transport = { close: jest.fn() }; + const exitSpy = jest + .spyOn(process, 'exit') + .mockImplementation((() => undefined) as never); + + installStdioLifecycle({ + transport, + parentPid: process.ppid, + envName: 'EVERNOTE_PARENT_WATCHDOG_MS', + }); + + process.stdin.emit('end'); + process.stdin.emit('close'); + + expect(transport.close).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/src/index.ts b/src/index.ts index 2f8be48..8b08b32 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2541,6 +2541,8 @@ process.on("uncaughtException", (error: Error) => { // Start server async function main() { + // Capture before any await — process.ppid is dynamic. + const parentPid = process.ppid; console.error("Starting Evernote MCP server..."); console.error(`Environment: ${ENVIRONMENT}`); console.error( @@ -2555,6 +2557,7 @@ async function main() { transport, onCloseAssignable: server, envName: "EVERNOTE_PARENT_WATCHDOG_MS", + parentPid, onShutdown: () => { stopPolling(); }, diff --git a/src/lifecycle.ts b/src/lifecycle.ts index 02fd28b..ab42278 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -3,9 +3,14 @@ * * When an intermediate wrapper (npx → npm exec → node bin → server) keeps the * server's stdin write-end open, a dead client never delivers EOF, so the leaf - * sits in the event loop forever and can thrash swap (multi-GB). stdin - * 'end'/'close', transport close, and signals all miss that orphan case. The - * watchdog catches it by noticing the original parent is gone. + * sits in the event loop forever and can thrash swap (multi-GB). Soft stdin + * EOF alone is not enough to catch that orphan case. The watchdog catches it + * by noticing the original parent is gone. + * + * Soft stdin EOF is intentional: do NOT call `transport.close()` and do NOT + * `process.exit` on `end`/`close`. Closing the transport trips the MCP SDK + * `onclose` → hard exit and breaks one-shot `echo … | npm start` flows. + * Hard exit is reserved for parent-watchdog reparent + OS signals. * * Kept side-effect-free on import so unit tests can cover it without spawning * the full server. @@ -63,15 +68,21 @@ export function startParentWatchdog( /** * Install stdin/transport/signal/parent-watchdog shutdown hooks. - * Call before `server.connect(transport)`. Captures `process.ppid` immediately. + * Call before `server.connect(transport)`. + * + * If `main()` awaits anything before this call, pass `parentPid` captured + * synchronously at the top of `main()` — `process.ppid` is dynamic, and a + * late capture after reparent would make the watchdog a no-op (mcp-automem #137). */ export function installStdioLifecycle(options: { transport: { close?: () => unknown }; onCloseAssignable?: { onclose?: (() => void) | null }; envName?: string; onShutdown?: () => void; + /** Prefer a pid captured before any `await` in `main()`. */ + parentPid?: number; }): () => void { - const parentPid = process.ppid; + const parentPid = options.parentPid ?? process.ppid; let shuttingDown = false; const shutdown = (code = 0) => { if (shuttingDown) return; @@ -89,8 +100,11 @@ export function installStdioLifecycle(options: { process.exit(code); }; - process.stdin.on('end', () => shutdown(0)); - process.stdin.on('close', () => shutdown(0)); + // Soft stdin EOF → no-op. Do not transport.close() (SDK onclose → hard exit) + // and do not process.exit. One-shot pipes must drain in-flight handlers; + // orphans that keep stdin open are killed by the parent watchdog / signals. + process.stdin.on('end', () => {}); + process.stdin.on('close', () => {}); if (options.onCloseAssignable) { options.onCloseAssignable.onclose = () => shutdown(0); } From 097f1600eb85803e9241ecb94635f684e14eb21d Mon Sep 17 00:00:00 2001 From: Jack Arturo Date: Wed, 29 Jul 2026 17:40:46 +0200 Subject: [PATCH 4/4] docs: clarify parent watchdog is POSIX-only on Windows Match mcp-automem wording: win32 does not reparent orphans, so the ppid probe is a documented no-op there. --- src/lifecycle.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/lifecycle.ts b/src/lifecycle.ts index ab42278..eb81b3a 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -38,7 +38,12 @@ export function parseWatchdogIntervalMs(raw: string | undefined): number { /** * Default probe: the server has been reparented away from its original parent. - * POSIX only (Windows does not reparent orphans, so this is a no-op there). + * + * POSIX only: this relies on the kernel reparenting an orphan (to pid 1 or a + * subreaper) when its parent dies. Windows does not reparent orphans, so + * `process.ppid` never changes there and this probe never fires — the watchdog + * is a no-op on win32. Orphan mitigation on Windows would need a different + * mechanism (e.g. a job object or a stdin heartbeat). Matches mcp-automem. */ export function parentReparented(parentPid: number): boolean { return process.ppid !== parentPid;