Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Reap orphaned ok mcp on host death to clear stale presence icons (#1599)

miles-kt-inkeepaaee937d37b5
diff --git a/.changeset/mcp-orphan-host-liveness.md b/.changeset/mcp-orphan-host-liveness.md
new file mode 100644
index 000000000..10f0731f5
--- /dev/null
+++ b/.changeset/mcp-orphan-host-liveness.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+fix(mcp): exit `ok mcp` when its launching host dies so stale agent-presence icons clear
+
+The `ok mcp` global stdio server opens a per-project keepalive WebSocket on the first tool call. That socket plus its reconnect timer keep the Node event loop alive, which silently disabled the only host-disconnect exit path the server had: the passive "stdin EOF then the event loop drains then the process exits" behavior never fires once a keepalive is open, and there was no active handler watching for the host going away.
+
+As a result, when the launching host process ended (for example a Claude Desktop per-turn agent harness finishing its run), the `ok mcp` process did not exit. It was reparented to launchd, kept its keepalive WebSocket open, and the server's presence heartbeat kept refreshing the entry past both the client 5s TTL and the server 20s eviction, so the agent's presence icon never cleared. Each new run spawned a fresh `ok mcp` process with its own id, so ghost icons accumulated one per run.
+
+`ok mcp` now exits promptly when its host is gone via two signals: an active `stdin` end handler (clean disconnect) and a parent-death watch that polls `process.ppid` and shuts down when the process is reparented (covers the case where a wrapper holds stdin open so no EOF arrives). Once the process exits, the existing keepalive-close to grace-timer to presence-clear path removes the entry. Live, idle agents are unaffected because their host process is still alive.
diff --git a/packages/cli/src/mcp/host-liveness.test.ts b/packages/cli/src/mcp/host-liveness.test.ts
new file mode 100644
index 000000000..9f5bef67f
--- /dev/null
+++ b/packages/cli/src/mcp/host-liveness.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, test } from 'bun:test';
+import { type HostLivenessScheduler, startHostLivenessWatch } from './host-liveness.ts';
+
+function manualScheduler(): {
+ scheduler: HostLivenessScheduler;
+ tick: () => void;
+ registered: () => boolean;
+ cleared: () => boolean;
+} {
+ let cb: (() => void) | null = null;
+ let active = false;
+ let everRegistered = false;
+ const token = Symbol('timer') as unknown as ReturnType<typeof globalThis.setInterval>;
+ return {
+ scheduler: {
+ setInterval: (fn) => {
+ cb = fn;
+ active = true;
+ everRegistered = true;
+ return token;
+ },
+ clearInterval: (handle) => {
+ if (handle === token) active = false;
+ },
+ },
+ tick: () => {
+ if (active) cb?.();
+ },
+ registered: () => everRegistered,
+ cleared: () => everRegistered && !active,
+ };
+}
+
+describe('startHostLivenessWatch', () => {
+ test('fires onHostGone once when ppid changes from boot, then clears the timer', () => {
+ const m = manualScheduler();
+ let ppid = 4242;
+ const reasons: string[] = [];
+ startHostLivenessWatch({
+ getPpid: () => ppid,
+ onHostGone: (r) => reasons.push(r),
+ scheduler: m.scheduler,
+ });
+
+ m.tick(); // parent still alive
+ expect(reasons).toHaveLength(0);
+
+ ppid = 1; // reparented to launchd
+ m.tick();
+ expect(reasons).toHaveLength(1);
+ expect(reasons[0]).toContain('4242');
+ expect(reasons[0]).toContain('1');
+ expect(m.cleared()).toBe(true);
+
+ m.tick(); // timer cleared → no further fires
+ expect(reasons).toHaveLength(1);
+ });
+
+ test('does not fire while the parent pid is unchanged', () => {
+ const m = manualScheduler();
+ let fired = 0;
+ startHostLivenessWatch({
+ getPpid: () => 999,
+ onHostGone: () => {
+ fired++;
+ },
+ scheduler: m.scheduler,
+ });
+ m.tick();
+ m.tick();
+ expect(fired).toBe(0);
+ });
+
+ test('no-op when there is no meaningful parent (bootPpid <= 1)', () => {
+ const m = manualScheduler();
+ let fired = 0;
+ const handle = startHostLivenessWatch({
+ getPpid: () => 1, // already orphaned / launched by init
+ onHostGone: () => {
+ fired++;
+ },
+ scheduler: m.scheduler,
+ });
+ expect(m.registered()).toBe(false); // never schedules a poll
+ handle.stop(); // safe to call
+ expect(fired).toBe(0);
+ });
+
+ test('stop() halts polling so onHostGone never fires afterward', () => {
+ const m = manualScheduler();
+ let ppid = 500;
+ let fired = 0;
+ const handle = startHostLivenessWatch({
+ getPpid: () => ppid,
+ onHostGone: () => {
+ fired++;
+ },
+ scheduler: m.scheduler,
+ });
+ handle.stop();
+ expect(m.cleared()).toBe(true);
+ ppid = 1; // host dies after we stopped watching
+ m.tick(); // no-op (timer cleared)
+ expect(fired).toBe(0);
+ });
+});
diff --git a/packages/cli/src/mcp/host-liveness.ts b/packages/cli/src/mcp/host-liveness.ts
new file mode 100644
index 000000000..aecdda7f6
--- /dev/null
+++ b/packages/cli/src/mcp/host-liveness.ts
@@ -0,0 +1,42 @@
+export interface HostLivenessScheduler {
+ setInterval: (cb: () => void, ms: number) => ReturnType<typeof globalThis.setInterval>;
+ clearInterval: (handle: ReturnType<typeof globalThis.setInterval>) => void;
+}
+
+export interface HostLivenessWatchOptions {
+ getPpid: () => number;
+ onHostGone: (reason: string) => void;
+ intervalMs?: number;
+ scheduler?: HostLivenessScheduler;
+}
+
+export interface HostLivenessWatchHandle {
+ stop: () => void;
+}
+
+const DEFAULT_INTERVAL_MS = 1000;
+
+export function startHostLivenessWatch(opts: HostLivenessWatchOptions): HostLivenessWatchHandle {
+ const scheduler: HostLivenessScheduler = opts.scheduler ?? {
+ setInterval: (cb, ms) => globalThis.setInterval(cb, ms),
+ clearInterval: (handle) => globalThis.clearInterval(handle),
+ };
+ const bootPpid = opts.getPpid();
+
+ if (bootPpid <= 1) return { stop: () => {} };
+
+ let fired = false;
+ const timer = scheduler.setInterval(() => {
+ if (fired) return;
+ const current = opts.getPpid();
+ if (current !== bootPpid) {
+ fired = true;
+ scheduler.clearInterval(timer);
+ opts.onHostGone(`host process exited (ppid ${bootPpid} -> ${current})`);
+ }
+ }, opts.intervalMs ?? DEFAULT_INTERVAL_MS);
+
+ (timer as { unref?: () => void }).unref?.();
+
+ return { stop: () => scheduler.clearInterval(timer) };
+}
diff --git a/packages/cli/src/mcp/keepalive-orphan-reaping.test.ts b/packages/cli/src/mcp/keepalive-orphan-reaping.test.ts
new file mode 100644
index 000000000..1318f507e
--- /dev/null
+++ b/packages/cli/src/mcp/keepalive-orphan-reaping.test.ts
@@ -0,0 +1,126 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync, spawn } from 'node:child_process';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { setTimeout as wait } from 'node:timers/promises';
+import { fileURLToPath } from 'node:url';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const CLI_ENTRY = join(HERE, '..', 'cli.ts');
+
+function isAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function killQuietly(pid: number | undefined): void {
+ if (pid === undefined) return;
+ try {
+ process.kill(pid, 'SIGKILL');
+ } catch {}
+}
+
+async function pollUntil(
+ predicate: () => boolean,
+ timeoutMs: number,
+ intervalMs = 200,
+): Promise<boolean> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return true;
+ await wait(intervalMs);
+ }
+ return predicate();
+}
+
+describe('ok mcp orphan reaping (PRD-6917)', () => {
+ const cleanups: Array<() => void> = [];
+
+ afterEach(() => {
+ for (const fn of cleanups.splice(0).reverse()) {
+ try {
+ fn();
+ } catch {}
+ }
+ });
+
+ test('ok mcp exits when its launching parent dies even if stdin never EOFs (no orphan to launchd)', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-orphan-reaping-'));
+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
+
+ const fifo = join(dir, 'mcp.stdin');
+ execFileSync('mkfifo', [fifo]);
+ const mcpErr = join(dir, 'mcp.err');
+ writeFileSync(mcpErr, '');
+
+ const keeperScript = join(dir, 'keeper.mjs');
+ writeFileSync(
+ keeperScript,
+ [
+ "import { openSync } from 'node:fs';",
+ 'openSync(process.argv[2], "a");',
+ 'setInterval(() => {}, 1 << 30);',
+ ].join('\n'),
+ 'utf-8',
+ );
+ const keeper = spawn(process.execPath, [keeperScript, fifo], {
+ detached: true,
+ stdio: 'ignore',
+ });
+ keeper.unref();
+ cleanups.push(() => killQuietly(keeper.pid));
+
+ const parentScript = join(dir, 'parent.mjs');
+ writeFileSync(
+ parentScript,
+ [
+ "import { spawn } from 'node:child_process';",
+ "import { openSync } from 'node:fs';",
+ 'const [cliEntry, fifoPath, errPath] = process.argv.slice(2);',
+ 'const rfd = openSync(fifoPath, "r");',
+ 'const efd = openSync(errPath, "a");',
+ 'const child = spawn(process.execPath, [cliEntry, "mcp"], {',
+ ' cwd: process.cwd(),',
+ ' stdio: [rfd, "ignore", efd],',
+ ' env: { ...process.env, OK_BUNDLE_PROXY: "0" },',
+ '});',
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: literal source emitted into the spawned child script, not a template string in this file
+ 'process.stdout.write(`CHILDPID:${child.pid}\\n`);',
+ 'setInterval(() => {}, 1 << 30);',
+ ].join('\n'),
+ 'utf-8',
+ );
+
+ const parent = spawn(process.execPath, [parentScript, CLI_ENTRY, fifo, mcpErr], {
+ cwd: dir,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: process.env,
+ });
+ cleanups.push(() => killQuietly(parent.pid));
+
+ let stdoutBuf = '';
+ parent.stdout.on('data', (chunk) => {
+ stdoutBuf += String(chunk);
+ });
+ const gotPid = await pollUntil(() => /CHILDPID:(\d+)/.test(stdoutBuf), 15_000, 100);
+ const match = stdoutBuf.match(/CHILDPID:(\d+)/);
+ expect(gotPid && match).toBeTruthy();
+ const childPid = Number(match?.[1]);
+ cleanups.push(() => killQuietly(childPid));
+
+ const cameUp = await pollUntil(() => isAlive(childPid), 6_000, 100);
+ expect(cameUp).toBe(true);
+ const diedWhileParented = await pollUntil(() => !isAlive(childPid), 3_000, 250);
+ expect(diedWhileParented).toBe(false);
+
+ killQuietly(parent.pid);
+
+ const exited = await pollUntil(() => !isAlive(childPid), 12_000, 250);
+ expect(exited).toBe(true);
+ }, 40_000);
+});
diff --git a/packages/cli/src/mcp/server.ts b/packages/cli/src/mcp/server.ts
index e01cc7c11..0499340d7 100644
--- a/packages/cli/src/mcp/server.ts
+++ b/packages/cli/src/mcp/server.ts
@@ -26,6 +26,7 @@ import {
detectBundleIdentity,
startBundleIdentityWatcher,
} from './bundle-identity.ts';
+import { type HostLivenessWatchHandle, startHostLivenessWatch } from './host-liveness.ts';
import { attachLifecycleLogging } from './lifecycle-logging.ts';
import { parseSpawnTimeoutEnv, resolveMcpHttpUrl, resolveMcpKeepaliveWsUrl } from './shim.ts';
@@ -202,11 +203,13 @@ export async function startGlobalMcpServer(
const transport = new StdioServerTransport();
let closed = false;
let bundleWatcher: BundleIdentityWatcherHandle | undefined;
+ let hostLiveness: HostLivenessWatchHandle | undefined;
const close = async (): Promise<void> => {
if (closed) return;
closed = true;
bundleWatcher?.stop();
+ hostLiveness?.stop();
for (const handle of keepalivesByProject.values()) {
try {
handle.close();
@@ -246,6 +249,24 @@ export async function startGlobalMcpServer(
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
+ process.stdin.on('end', () => {
+ stderr.write('[mcp] stdin end — host disconnected, shutting down\n');
+ shutdown();
+ });
+ process.stdin.on('error', (err) => {
+ stderr.write(
+ `[mcp] stdin error (${err instanceof Error ? err.message : String(err)}) — host disconnected, shutting down\n`,
+ );
+ shutdown();
+ });
+ hostLiveness = startHostLivenessWatch({
+ getPpid: () => process.ppid,
+ onHostGone: (reason) => {
+ stderr.write(`[mcp] ${reason} — shutting down\n`);
+ shutdown();
+ },
+ });
+
attachLifecycleLogging({
log: (m) => stderr.write(`${m}\n`),
transport,