Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(mcp): surface actionable stdio startup diagnostics instead of bare -32000 (#21110)

Arvin Xua26dbfd668bb
diff --git a/apps/desktop/src/main/libs/mcp/client.test.ts b/apps/desktop/src/main/libs/mcp/client.test.ts
new file mode 100644
index 00000000000..1d885adf968
--- /dev/null
+++ b/apps/desktop/src/main/libs/mcp/client.test.ts
@@ -0,0 +1,608 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildInitializeProbeMessage,
+ describeStdioSpawnFailure,
+ hasInitializeResponse,
+ isBareConnectionClosedError,
+ MCPClient,
+ MCPConnectionError,
+ PrecheckOutputStream,
+ selectDiagnosticOutputLines,
+} from './client';
+
+describe('describeStdioSpawnFailure', () => {
+ it('diagnoses ENOENT spawn errors with the command and install guidance', () => {
+ const message = describeStdioSpawnFailure({
+ command: 'kali-mcp',
+ spawnCode: 'ENOENT',
+ });
+
+ expect(message).toContain('kali-mcp');
+ expect(message).toContain('not found');
+ expect(message).toContain('npx`/`.cmd`');
+ });
+
+ it('maps Windows numeric errno -4058 (ENOENT) to the not-found diagnosis', () => {
+ // Windows spawn failures surface as a numeric errno without a symbolic code
+ const message = describeStdioSpawnFailure({
+ command: 'goatjg_mcp',
+ errno: -4058,
+ });
+
+ expect(message).toContain('goatjg_mcp');
+ expect(message).toContain('not found');
+ });
+
+ it('diagnoses permission errors', () => {
+ const message = describeStdioSpawnFailure({
+ command: '/usr/local/bin/kali-server',
+ spawnCode: 'EACCES',
+ });
+
+ expect(message).toContain('not executable');
+ expect(message).toContain('chmod +x');
+ });
+
+ it('detects the pt-BR "path not found" loader message from the real vent', () => {
+ // Real-world stderr from vent msg_PjF7YECkH0nA67ddyY (Windows, pt-BR locale)
+ const message = describeStdioSpawnFailure({
+ command: 'mcpkali_note',
+ exitCode: 1,
+ stderr: 'O sistema não pode encontrar o caminho especificado.',
+ });
+
+ expect(message).toContain('mcpkali_note');
+ expect(message).toContain('path not found');
+ expect(message).toContain('Reinstall');
+ });
+
+ it('detects the zh-CN loader message', () => {
+ const message = describeStdioSpawnFailure({
+ command: 'kali_mcp',
+ exitCode: 1,
+ stderr: '系统找不到指定的路径。',
+ });
+
+ expect(message).toContain('path not found');
+ });
+
+ it('falls back to the exit-code diagnosis for unrelated stderr', () => {
+ const message = describeStdioSpawnFailure({
+ command: 'broken-server',
+ exitCode: 127,
+ stderr: 'some unrelated crash output',
+ });
+
+ expect(message).toContain('exited immediately with code 127');
+ });
+
+ it('diagnoses a zero-code exit without MCP handshake as a startup failure', () => {
+ const message = describeStdioSpawnFailure({
+ command: 'one-shot-wrapper',
+ exitCode: 0,
+ stdout: 'starting up',
+ });
+
+ expect(message).toContain('exited (code 0)');
+ expect(message).toContain('without completing the MCP handshake');
+ });
+
+ it('diagnoses a zero-code exit with an error line printed on stdout', () => {
+ const message = describeStdioSpawnFailure({
+ command: 'kali-wrapper',
+ exitCode: 0,
+ stdout: 'Error: config file missing',
+ });
+
+ expect(message).toContain('exited (code 0)');
+ expect(message).toContain('kali-wrapper');
+ });
+
+ it('reports the crash signal for signal-only exits (exitCode null)', () => {
+ // Node sets exitCode === null and populates `signal` when killed by one
+ const message = describeStdioSpawnFailure({
+ command: 'segfaulting-server',
+ exitCode: null,
+ signal: 'SIGSEGV',
+ });
+
+ expect(message).toContain('segfaulting-server');
+ expect(message).toContain('terminated by signal SIGSEGV');
+ expect(message).not.toContain('not found');
+ });
+
+ it('reports a signal crash with no output distinctly', () => {
+ const message = describeStdioSpawnFailure({
+ command: 'aborting-server',
+ exitCode: null,
+ signal: 'SIGABRT',
+ });
+
+ expect(message).toContain('terminated by signal SIGABRT');
+ expect(message).toContain('no output');
+ });
+
+ it('detects the pt-BR "path not found" loader message printed on stdout', () => {
+ // Some launchers print the loader error on stdout instead of stderr
+ const message = describeStdioSpawnFailure({
+ command: 'mcpkali_note',
+ exitCode: 1,
+ stderr: '',
+ stdout: 'O sistema não pode encontrar o caminho especificado.',
+ });
+
+ expect(message).toContain('mcpkali_note');
+ expect(message).toContain('path not found');
+ expect(message).toContain('Reinstall');
+ });
+
+ it('falls back to the no-output diagnosis when nothing is captured', () => {
+ const message = describeStdioSpawnFailure({ command: 'silent-server' });
+
+ expect(message).toContain('produced no output');
+ expect(message).toContain('silent-server');
+ });
+});
+
+describe('isBareConnectionClosedError', () => {
+ it('matches the bare -32000 Connection closed transport failure', () => {
+ const error = Object.assign(new Error('MCP error -32000: Connection closed'), {
+ code: -32_000,
+ });
+
+ expect(isBareConnectionClosedError(error)).toBe(true);
+ });
+
+ it('rejects -32000 errors without the connection-closed message', () => {
+ const error = Object.assign(new Error('MCP error -32000: other transport failure'), {
+ code: -32_000,
+ });
+
+ expect(isBareConnectionClosedError(error)).toBe(false);
+ });
+
+ it('rejects protocol/configuration failures that are not -32000', () => {
+ const error = Object.assign(
+ new Error('MCP error -32602: Invalid params — incompatible protocol version'),
+ { code: -32_602 },
+ );
+
+ expect(isBareConnectionClosedError(error)).toBe(false);
+ });
+
+ it('rejects non-error values', () => {
+ expect(isBareConnectionClosedError(null)).toBe(false);
+ expect(isBareConnectionClosedError(undefined)).toBe(false);
+ expect(isBareConnectionClosedError('Connection closed')).toBe(false);
+ });
+});
+
+describe('MCPConnectionError', () => {
+ it('carries stderr logs and a stable name for the existing enhancer pipeline', () => {
+ const error = new MCPConnectionError('diagnosis text', ['line one', 'line two']);
+
+ expect(error.name).toBe('MCPConnectionError');
+ expect(error.message).toBe('diagnosis text');
+ expect(error.stderrLogs).toEqual(['line one', 'line two']);
+ });
+});
+
+describe('PrecheckOutputStream', () => {
+ const CAP = 64 * 1024;
+
+ it('accumulates small chunks without truncation', () => {
+ const stream = new PrecheckOutputStream('stdout');
+ stream.append(Buffer.from('hello '));
+ stream.append(Buffer.from('world'));
+
+ expect(stream.truncated).toBe(false);
+ expect(stream.toString()).toBe('hello world');
+ });
+
+ it('retains the actual tail when the cap is exceeded (P2 4306325895)', () => {
+ // A noisy launcher fills the cap with chatter, THEN prints the decisive
+ // error. The tail buffer must keep the later error, not the first 64 KiB.
+ const stream = new PrecheckOutputStream('stderr');
+ stream.append(Buffer.from('x'.repeat(CAP)));
+ stream.append(Buffer.from('\nnoise padding line\n'));
+ stream.append(Buffer.from('final error: path not found\n'));
+
+ const text = stream.toString();
+ expect(stream.truncated).toBe(true);
+ expect(text).toContain('final error: path not found');
+ });
+
+ it('decodes a multibyte character split across two chunks (P2 4306581051)', () => {
+ // pt-BR "não pode encontrar o caminho especificado" — the byte sequence
+ // of ã (0xC3 0xA3) must survive the chunk boundary. The pt-BR
+ // path-not-found matcher lowercases the combined output.
+ const stream = new PrecheckOutputStream('stderr');
+ stream.append(Buffer.from('O sistema n', 'utf8'));
+ stream.append(Buffer.from([0xc3, 0xa3])); // ã, split across the boundary
+ stream.append(Buffer.from('o pode encontrar o caminho especificado', 'utf8'));
+
+ const text = stream.toString();
+ expect(text).toContain('não pode encontrar o caminho especificado');
+ expect(text).not.toContain('\uFFFD');
+ expect(text.toLowerCase()).toContain('não pode encontrar o caminho especificado');
+ });
+
+ it('drops only the head beyond the cap, aligned to a UTF-8 sequence boundary', () => {
+ // 4-byte emoji per repetition guarantees a multibyte cut candidate.
+ const stream = new PrecheckOutputStream('stdout');
+ stream.append(Buffer.from('🎉'.repeat(30_000))); // ~120 KB, ~2x cap
+
+ const text = stream.toString();
+ expect(stream.truncated).toBe(true);
+ expect(Buffer.byteLength(text)).toBeLessThanOrEqual(CAP + 128);
+ expect(text).toContain('🎉');
+ expect(text).not.toContain('\uFFFD');
+ });
+
+ it('handles a single oversized chunk by keeping its last cap bytes', () => {
+ const stream = new PrecheckOutputStream('stdout');
+ stream.append(Buffer.from('a'.repeat(CAP + 500)));
+
+ const text = stream.toString();
+ expect(stream.truncated).toBe(true);
+ expect(text).toContain('a');
+ expect(text.length).toBeLessThanOrEqual(CAP + 128);
+ });
+
+ it('marks truncation once and keeps the marker stable across flushes', () => {
+ const stream = new PrecheckOutputStream('stderr');
+ stream.append(Buffer.from('x'.repeat(CAP)));
+ const first = stream.toString();
+ const second = stream.toString();
+
+ expect(first).toContain('truncated: pre-check output cap reached');
+ expect(second).toBe(first);
+ });
+});
+
+describe('buildInitializeProbeMessage', () => {
+ it('includes capabilities so spec-validating servers accept the probe', () => {
+ const message = buildInitializeProbeMessage();
+ const parsed = JSON.parse(message);
+
+ expect(parsed.params.capabilities).toEqual({});
+ expect(parsed.params.protocolVersion).toBe('2024-11-05');
+ expect(parsed.params.clientInfo.name).toBe('lobe-mcp-precheck');
+ expect(message.endsWith('\n')).toBe(true);
+ });
+});
+
+describe('selectDiagnosticOutputLines', () => {
+ const CAP = 64 * 1024;
+ const makeLines = (n: number, prefix: string) =>
+ Array.from({ length: n }, (_, i) => `${prefix} line ${i + 1}`).join('\n');
+
+ it('keeps the tail of each stream and caps at 10 lines per stream', () => {
+ const stdout = makeLines(15, 'out');
+ const stderr = makeLines(15, 'err');
+
+ const lines = selectDiagnosticOutputLines(stdout, stderr);
+
+ expect(lines).toHaveLength(20);
+ expect(lines[0]).toBe('out line 6');
+ expect(lines[9]).toBe('out line 15');
+ expect(lines[10]).toBe('err line 6');
+ expect(lines[19]).toBe('err line 15');
+ });
+
+ it('merges stdout then stderr preserving order', () => {
+ const lines = selectDiagnosticOutputLines('out-1\nout-2', 'err-1');
+
+ expect(lines).toEqual(['out-1', 'out-2', 'err-1']);
+ });
+
+ it('returns an empty array when both streams are empty', () => {
+ expect(selectDiagnosticOutputLines('', '')).toEqual([]);
+ });
+
+ it('preserves the truncation notice when the payload fills the tail window (P2 4307065883)', () => {
+ // Composed accumulator → selector: a capped stream whose retained payload
+ // has ≥ 10 non-empty lines. A bare slice(-10) silently drops the prepended
+ // notice, making the tail look complete even though the head was dropped.
+ const stream = new PrecheckOutputStream('stderr');
+ stream.append(Buffer.from('x'.repeat(CAP)));
+ stream.append(Buffer.from('\n' + makeLines(12, 'err') + '\n'));
+ stream.append(Buffer.from('final error: path not found\n'));
+
+ const lines = selectDiagnosticOutputLines(stream.toString(), '');
+
+ expect(lines[0]).toBe('[stderr truncated: pre-check output cap reached]');
+ expect(lines).toContain('final error: path not found');
+ expect(lines).toHaveLength(11);
+ });
+
+ it('keeps non-notice lines even when they merely look like a truncation notice', () => {
+ // A payload line that merely echoes notice wording must NOT be hoisted as
+ // the notice itself — only the exact marker line is hoisted. The payload
+ // copy uses near-identical but distinct wording, and since the real
+ // marker's stream is capped the payload copy is dropped with the head.
+ const stream = new PrecheckOutputStream('stdout');
+ stream.append(
+ Buffer.from('[stdout truncated: pre-check app reached]\nreal payload line\n'),
+ );
+ stream.append(Buffer.from('y'.repeat(CAP)));
+ stream.append(Buffer.from('\ndecisive error\n'));
+
+ const lines = selectDiagnosticOutputLines(stream.toString(), '');
+
+ expect(lines[0]).toBe('[stdout truncated: pre-check output cap reached]');
+ expect(lines).toContain('decisive error');
+ expect(lines).not.toContain('[stdout truncated: pre-check app reached]');
+ });
+});
+
+describe('hasInitializeResponse', () => {
+ it('detects a JSON-RPC response to the initialize probe (id 1)', () => {
+ const stdout = [
+ 'server starting…',
+ JSON.stringify({ id: 1, jsonrpc: '2.0', result: { protocolVersion: '2024-11-05' } }),
+ ].join('\n');
+
+ expect(hasInitializeResponse(stdout)).toBe(true);
+ });
+
+ it('returns false when stdout has chatter but no probe response', () => {
+ expect(hasInitializeResponse('booting\nready-ish\n')).toBe(false);
+ });
+
+ it('ignores notifications (no id) and other ids', () => {
+ const stdout = [
+ JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),
+ JSON.stringify({ id: 2, jsonrpc: '2.0', result: {} }),
+ ].join('\n');
+
+ expect(hasInitializeResponse(stdout)).toBe(false);
+ });
+});
+
+describe('preCheckStdioCommand', () => {
+ /**
+ * Call the private pre-check directly with a short timeout so long-running
+ * server cases do not stall the suite.
+ */
+ const runPreCheck = (
+ command: string,
+ args?: string[],
+ timeoutMs = 1200,
+ ): Promise<{ diagnosis: string; stderr: string; stdout: string; success: boolean }> =>
+ (
+ MCPClient.prototype as unknown as {
+ preCheckStdioCommand: (p: {
+ args?: string[];
+ command: string;
+ env?: Record<string, string>;
+ timeoutMs?: number;
+ }) => Promise<{ diagnosis: string; stderr: string; stdout: string; success: boolean }>;
+ }
+ ).preCheckStdioCommand.call({} as MCPClient, { args, command, env: {}, timeoutMs });
+
+ it(
+ 'classifies on close so buffered stdout is drained before the diagnosis (P2 4305387427)',
+ { timeout: 15_000 },
+ async () => {
+ // The child prints its error line and exits 0 immediately; Node may
+ // emit `exit` before the stdout chunk drains — classification must
+ // wait for `close` (or the bounded fallback) to see it.
+ const result = await runPreCheck('node', [
+ '-e',
+ 'process.stdout.write("final loader error\\n"); process.exit(0)',
+ ]);
+
+ expect(result.success).toBe(false);
+ expect(result.diagnosis).toContain('without completing the MCP handshake');
+ expect(result.stdout).toContain('final loader error');
+ },
+ );
+
+ it(
+ 'does not credit exit 0 without an initialize response (round-4 regression guard)',
+ { timeout: 15_000 },
+ async () => {
+ const result = await runPreCheck('node', ['-e', 'process.exit(0)']);
+
+ expect(result.success).toBe(false);
+ expect(result.diagnosis).toContain('without completing the MCP handshake');
+ },
+ );
+
+ it(
+ 'classifies zero-code exits even when close is delayed by inherited pipes (exit fallback)',
+ { timeout: 15_000 },
+ async () => {
+ // The child spawns a detached grandchild holding stdout open, then
+ // exits 0. `close` stays pending on the inherited pipe; the exit-armed
+ // fallback must classify with the real exit code before the 5s timeout
+ // would have misreported "healthy-enough".
+ const result = await runPreCheck('node', [
+ '-e',
+ [
+ 'const { spawn } = require("node:child_process");',
+ 'const g = spawn(process.execPath, ["-e", "setTimeout(() => {}, 3000)"], { stdio: ["ignore", "inherit", "inherit"], detached: false });',
+ 'g.unref();',
+ 'process.exit(0);',
+ ].join(' '),
+ ]);
+
+ expect(result.success).toBe(false);
+ expect(result.diagnosis).toContain('without completing the MCP handshake');
+ },
+ );
+
+ it(
+ 'treats a long-running silent server as healthy via the timeout path (success preserved)',
+ { timeout: 15_000 },
+ async () => {
+ const result = await runPreCheck(
+ 'node',
+ ['-e', 'setInterval(() => {}, 1000)'],
+ 800, // short pre-check window: the server outlives it
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.diagnosis).toBe('');
+ },
+ );
+
+ it(
+ 'terminates the whole process tree: the launcher-spawned descendant does not survive cleanup (P2 4305748076)',
+ { timeout: 20_000 },
+ async () => {
+ // The configured command is a launcher that starts a persistent worker
+ // (writes a heartbeat to a side file every 200ms) and stays alive via
+ // pipes. The pre-check must tear down BOTH processes: the worker file
+ // must stop growing after the pre-check window, proving no orphan.
+ const heartbeat = '/tmp/lobehub-precheck-p2-heartbeat';
+
+ const result = await runPreCheck('node', [
+ '-e',
+ [
+ `require("node:fs").rmSync("${heartbeat}", { force: true });`,
+ 'const { spawn } = require("node:child_process");',
+ `const w = spawn(process.execPath, ["-e", "const fs=require(\\"fs\\");const t=setInterval(()=>fs.appendFileSync(\\"${heartbeat}\\", String(Date.now())+\\"\\\\n\\"),200);process.on(\\"SIGTERM\\",()=>{clearInterval(t);process.exit(0);});"], { stdio: "ignore" });`,
+ 'w.unref();',
+ 'setInterval(() => {}, 1000);', // launcher itself stays alive → timeout path
+ ].join(' '),
+ ]);
+
+ expect(result.success).toBe(true); // still-running launcher → healthy-enough path
+ const settleWait = Date.now() + 5000;
+ let lines = 0;
+ // Give the teardown (SIGTERM → SIGKILL escalation) time to land.
+ while (Date.now() < settleWait) {
+ await new Promise((r) => setTimeout(r, 400));
+ lines = require('node:fs').existsSync(heartbeat)
+ ? require('node:fs').readFileSync(heartbeat, 'utf8').trim().split('\n').length
+ : 0;
+ if (lines >= 3) break; // worker was alive and writing
+ }
+ const stableAt = lines;
+
+ // After teardown the heartbeat must freeze: no orphaned worker.
+ await new Promise((r) => setTimeout(r, 1600));
+ const finalLines = require('node:fs').existsSync(heartbeat)
+ ? require('node:fs').readFileSync(heartbeat, 'utf8').trim().split('\n').length
+ : 0;
+
+ expect(stableAt).toBeGreaterThanOrEqual(3); // worker genuinely ran
+ expect(finalLines).toBe(stableAt); // …and was killed with the tree
+ },
+ );
+
+ it(
+ 'reaps worker descendants when the launcher exits on its own (zero-code path)',
+ { timeout: 20_000 },
+ async () => {
+ // Launcher starts a worker, lets it write a few heartbeat lines, then
+ // exits 0 without a handshake → zero-code classification. The worker
+ // must not survive the classification: reapOrphanedProcessGroup kills
+ // the group.
+ const heartbeat = '/tmp/lobehub-precheck-reap-heartbeat';
+
+ const result = await runPreCheck('node', [
+ '-e',
+ [
+ `require("node:fs").rmSync("${heartbeat}", { force: true });`,
+ 'const { spawn } = require("node:child_process");',
+ `const w = spawn(process.execPath, ["-e", "const fs=require(\\"fs\\");const t=setInterval(()=>fs.appendFileSync(\\"${heartbeat}\\", String(Date.now())+\\"\\\\n\\"),200);"], { stdio: "ignore" });`,
+ 'w.unref();',
+ 'setTimeout(() => process.exit(0), 700);', // worker writes ~3 lines first
+ ].join(' '),
+ ]);
+
+ expect(result.success).toBe(false);
+ expect(result.diagnosis).toContain('without completing the MCP handshake');
+
+ const settleWait = Date.now() + 5000;
+ let lines = 0;
+ while (Date.now() < settleWait) {
+ await new Promise((r) => setTimeout(r, 400));
+ lines = require('node:fs').existsSync(heartbeat)
+ ? require('node:fs').readFileSync(heartbeat, 'utf8').trim().split('\n').length
+ : 0;
+ if (lines >= 3) break;
+ }
+ const stableAt = lines;
+
+ await new Promise((r) => setTimeout(r, 1600));
+ const finalLines = require('node:fs').existsSync(heartbeat)
+ ? require('node:fs').readFileSync(heartbeat, 'utf8').trim().split('\n').length
+ : 0;
+
+ expect(stableAt).toBeGreaterThanOrEqual(3);
+ expect(finalLines).toBe(stableAt);
+ },
+ );
+
+ it('reports a nonzero exit with its code after streams drain', { timeout: 15_000 }, async () => {
+ const result = await runPreCheck('node', [
+ '-e',
+ 'process.stderr.write("boom\\n"); process.exit(3)',
+ ]);
+
+ expect(result.success).toBe(false);
+ expect(result.diagnosis).toContain('code 3');
+ });
+});
+
+describe('MCPClient.initialize respawn gating (P2 4306033474)', () => {
+ /**
+ * Drive `initialize()` against a stubbed SDK client to prove the
+ * diagnostic re-spawn only fires for the bare -32000 connection-closed
+ * failure it was built to diagnose.
+ */
+ const runInitialize = async (connectError: unknown): Promise<{ respawned: boolean }> => {
+ let respawned = false;
+ const probe = MCPClient.prototype as unknown as {
+ initialize: MCPClient['initialize'];
+ };
+
+ const instance = Object.create(MCPClient.prototype) as MCPClient;
+ // Stub the private fields initialize() reads.
+ Object.assign(instance, {
+ isStdio: true,
+ stderrLogs: [],
+ stdioParams: { args: [], command: 'irrelevant' },
+ mcp: {
+ connect: () => {
+ throw connectError;
+ },
+ },
+ // Instrument the private pre-check instead of spawning real processes.
+ preCheckStdioCommand: async () => {
+ respawned = true;
+ return { diagnosis: 'stubbed', stderr: '', stdout: '', success: false };
+ },
+ });
+
+ try {
+ await probe.initialize.call(instance, {});
+ } catch {
+ // initialize() is expected to throw — the call shape is not under test.
+ }
+ return { respawned };
+ };
+
+ it('re-spawns for the bare -32000 Connection closed failure', async () => {
+ const { respawned } = await runInitialize(
+ Object.assign(new Error('MCP error -32000: Connection closed'), { code: -32_000 }),
+ );
+
+ expect(respawned).toBe(true);
+ });
+
+ it('does not re-spawn for other handshake failures (protocol/config errors)', async () => {
+ const { respawned } = await runInitialize(
+ Object.assign(new Error('MCP error -32602: Invalid params — incompatible protocol version'), {
+ code: -32_602,
+ }),
+ );
+
+ expect(respawned).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/libs/mcp/client.ts b/apps/desktop/src/main/libs/mcp/client.ts
index 2a59616a7d9..a75957ad85f 100644
--- a/apps/desktop/src/main/libs/mcp/client.ts
+++ b/apps/desktop/src/main/libs/mcp/client.ts
@@ -1,3 +1,4 @@
+import { spawn } from 'node:child_process';
import type { Readable } from 'node:stream';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
@@ -11,8 +12,31 @@ import type { Progress } from '@modelcontextprotocol/sdk/types.js';
import { getDesktopEnv } from '@/env';
+import { reapOrphanedProcessGroup, terminatePrecheckProcess } from './process-tree';
import type { MCPClientParams, McpPrompt, McpResource, McpTool, ToolCallResult } from './types';
+// Process-tree teardown lives in ./process-tree; re-export so existing
+// importers of this module (and the focused test file) keep one import path.
+export {
+ reapOrphanedProcessGroup,
+ signalProcessTree,
+ terminatePrecheckProcess,
+} from './process-tree';
+
+/**
+ * The SDK surfaces a stdio process that died without completing the MCP
+ * handshake as a bare "Connection closed" (JSON-RPC error -32000). This is
+ * the only failure class the diagnostic re-spawn can improve: when the
+ * server rejected the handshake for a protocol/configuration reason instead,
+ * re-running the same command adds a five-second probe window and a
+ * temporary duplicate server process without producing new information.
+ */
+export function isBareConnectionClosedError(error: unknown): boolean {
+ if ((error as { code?: unknown })?.code !== -32_000) return false;
+ const message = error instanceof Error ? error.message : String(error);
+ return message.includes('Connection closed');
+}
+
/**
* Custom error class for MCP connection errors that includes STDIO logs
*/
@@ -26,6 +50,294 @@ export class MCPConnectionError extends Error {
}
}
+/**
+ * Known Windows loader error messages surfaced when a shim/script target path
+ * does not exist (reported in the user's locale, e.g. pt-BR
+ * "O sistema não pode encontrar o caminho especificado").
+ */
+const WINDOWS_PATH_NOT_FOUND_PATTERNS = [
+ '找不到指定的路径', // zh-CN
+ '找不到指定的文件', // zh-CN (file variant)
+ 'The system cannot find the path specified', // en-US
+ 'The system cannot find the file specified', // en-US (file variant)
+ 'não pode encontrar o caminho especificado', // pt-BR
+ 'no se puede encontrar la ruta especificada', // es-419
+ 'Das System kann den angegebenen Pfad nicht finden', // de-DE
+ '指定されたパスが見つかりません', // ja-JP
+ '지정된 경로를 찾을 수 없습니다', // ko-KR
+];
+
+export interface StdioSpawnFailureInput {
+ args?: string[];
+ command: string;
+ /** errno for spawn 'error' events (negative on Windows, e.g. -4058) */
+ errno?: number;
+ exitCode?: number | null;
+ message?: string;
+ /** Termination signal when the process was killed by one (e.g. SIGTERM) */
+ signal?: NodeJS.Signals | null;
+ spawnCode?: string | null;
+ stderr?: string;
+ /** Some launchers report the actual failure (e.g. loader errors) on stdout */
+ stdout?: string;
+}
+
+/** Per-stream cap for pre-check output so a noisy command cannot balloon the
+ * Electron main process heap while the 5s pre-check window runs. */
+const PRECHECK_OUTPUT_CAP_BYTES = 64 * 1024;
+
+/** Grace window between `exit` and `close` before the pre-check classifies
+ * on the data captured so far — a grandchild holding the stdio pipes can
+ * keep `close` pending indefinitely (see the `close`/`exit` handlers in
+ * `preCheckStdioCommand`). */
+const PRECHECK_CLOSE_GRACE_MS = 750;
+
+/**
+ * Find the first index at or after `start` that begins a complete UTF-8
+ * sequence, skipping the continuation bytes of a character split by the cut.
+ * Advances at most 3 bytes; returns `start` when it already lands on a
+ * sequence boundary.
+ */
+const utf8SequenceStart = (buf: Buffer, start: number): number => {
+ let index = start;
+ while (index < buf.byteLength && (buf[index] & 0b1100_0000) === 0b1000_0000) index += 1;
+ return index;
+};
+
+/**
+ * Per-stream pre-check output accumulator (bounded tail buffer).
+ *
+ * Keeps the most recent bytes under a hard per-stream cap so a noisy launcher
+ * cannot balloon the Electron main-process heap, while the stream's actual
+ * tail — where launchers print the decisive startup error — stays available
+ * for diagnosis. The previous prefix-accumulate-then-drop design kept only
+ * the first 64 KiB, so the tail-10 line selection saw the tail of that prefix
+ * and lost errors printed after the cap (P2 4306325895).
+ *
+ * Raw bytes are buffered and decoded as a whole on flush: stream chunks do
+ * not preserve character boundaries, and decoding each chunk independently
+ * turns a multibyte character split across two chunks into U+FFFD — which
+ * broke localized (e.g. pt-BR) path-not-found matchers (P2 4306581051).
+ */
+export class PrecheckOutputStream {
+ private readonly label: 'stdout' | 'stderr';
+ private tail: Buffer = Buffer.alloc(0);
+ private overflown = false;
+
+ constructor(label: 'stdout' | 'stderr') {
+ this.label = label;
+ }
+
+ /** Buffer a raw stdout/stderr chunk; retains only the most recent cap bytes. */
+ append(chunk: Buffer): void {
+ if (chunk.byteLength === 0) return;
+
+ if (chunk.byteLength >= PRECHECK_OUTPUT_CAP_BYTES) {
+ // Single oversized chunk: keep its last cap bytes on a sequence boundary.
+ this.tail = chunk.subarray(
+ utf8SequenceStart(chunk, chunk.byteLength - PRECHECK_OUTPUT_CAP_BYTES),
+ );
+ this.overflown = true;
+ return;
+ }
+
+ const merged = this.tail.byteLength === 0 ? chunk : Buffer.concat([this.tail, chunk]);
+ if (merged.byteLength > PRECHECK_OUTPUT_CAP_BYTES) {
+ this.tail = merged.subarray(
+ utf8SequenceStart(merged, merged.byteLength - PRECHECK_OUTPUT_CAP_BYTES),
+ );
+ this.overflown = true;
+ } else {
+ this.tail = merged;
+ }
+ }
+
+ /** Whether the stream ever exceeded the per-stream cap. */
+ get truncated(): boolean {
+ return this.overflown;
+ }
+
+ /**
+ * Decode the retained tail (pure — safe to call repeatedly). When the cap
+ * was hit, the truncation marker is prepended so downstream line selection
+ * keeps the decisive error while still disclosing the truncation.
+ */
+ toString(): string {
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(this.tail);
+ if (!this.overflown) return text;
+ return `[${this.label} truncated: pre-check output cap reached]\n${text}`;
+ }
+}
+
+/**
+ * Select diagnostic lines for the MCPConnectionError payload. Keeps the TAIL
+ * of each stream: launchers print startup chatter first and emit the decisive
+ * error last, so head-slicing keeps the noise and drops the lines that
+ * actually explain the failure. Both streams are capped upstream (64 KiB), so
+ * the result stays small.
+ *
+ * The truncation notice emitted by PrecheckOutputStream.toString() is
+ * prepended to the stream text BEFORE the payload, so it must be pulled out
+ * before tail-slicing — otherwise a stream with ≥ 10 retained lines silently
+ * drops the notice and the tail looks complete even though earlier output was
+ * discarded (P2 4307065883).
+ */
+const truncationNoticePattern = /^\[(?:stdout|stderr) truncated: pre-check output cap reached\]$/;
+
+export function selectDiagnosticOutputLines(stdout: string, stderr: string): string[] {
+ const tailLines = (text: string) => {
+ const lines = text
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+ const notices: string[] = [];
+ const payload: string[] = [];
+ for (const line of lines) {
+ if (truncationNoticePattern.test(line)) notices.push(line);
+ else payload.push(line);
+ }
+ return [...notices, ...payload.slice(-10)];
+ };
+ return [...tailLines(stdout), ...tailLines(stderr)];
+}
+
+/** Build the minimal JSON-RPC initialize probe sent to the pre-check child. */
+export function buildInitializeProbeMessage(): string {
+ return (
+ JSON.stringify({
+ id: 1,
+ jsonrpc: '2.0',
+ method: 'initialize',
+ params: {
+ capabilities: {},
+ clientInfo: { name: 'lobe-mcp-precheck', version: '1.0.0' },
+ protocolVersion: '2024-11-05',
+ },
+ }) + '\n'
+ );
+}
+
+/**
+ * Detect the JSON-RPC response to the initialize probe (id: 1) in captured
+ * pre-check stdout. Exit status 0 alone does not prove the MCP handshake
+ * progressed: one-shot executables and wrappers can start, print an error and
+ * exit 0 without ever completing the handshake. Without this check such
+ * servers pass the pre-check and the original bare "Connection closed" error
+ * surfaces unchanged.
+ */
+export function hasInitializeResponse(stdout: string): boolean {
+ return stdout.split('\n').some((line) => {
+ const trimmed = line.trim();
+ if (!trimmed.startsWith('{')) return false;
+ try {
+ const parsed = JSON.parse(trimmed) as { id?: unknown; result?: unknown };
+ return parsed.id === 1 && parsed.result !== undefined;
+ // Non-JSON lines are startup chatter, not handshake responses.
+ } catch {
+ return false;
+ }
+ });
+}
+
+/**
+ * Build a user-actionable diagnosis for a failed stdio MCP process spawn.
+ * Pure function (no I/O) so it can be unit-tested in isolation.
+ *
+ * Real-world shape (vent msg_PjF7YECkH0nA67ddyY): five Kali MCP connectors on a
+ * Windows host all fail with "MCP error -32000: Connection closed" plus the
+ * loader message "O sistema não pode encontrar o caminho especificado" — the
+ * SDK spawns with `shell: false`, so the configured command/its shim must
+ * resolve to a real executable; a broken install or a stale PATH surfaces as
+ * an immediate process exit with that stderr, and previously users only saw
+ * the bare -32000 with nothing actionable.
+ */
+export function describeStdioSpawnFailure(input: StdioSpawnFailureInput): string {
+ const { command } = input;
+ // Launchers may print the real error on stdout instead of stderr — scan both
+ const stderr = (input.stderr || '').trim();
+ const stdout = (input.stdout || '').trim();
+ const combinedOutput = `${stdout}\n${stderr}`.trim();
+ const spawnCode = input.spawnCode || null;
+ const errno = typeof input.errno === 'number' ? input.errno : undefined;
+
+ // Windows spawns can fail with a numeric errno and no symbolic code
+ const codeIsNotFound = spawnCode === 'ENOENT' || errno === -4058 || errno === 4058;
+ const codeIsPermission = spawnCode === 'EACCES' || spawnCode === 'EPERM';
+
+ if (codeIsNotFound) {
+ return (
+ `MCP server executable not found: "${command}". ` +
+ 'Verify the command exists on this machine (check the configured PATH) and install the package it needs ' +
+ '(e.g. `npm install -g <package>` or `pip install <package>`). ' +
+ 'On Windows, `npx`/`.cmd` shims cannot be spawned directly — configure the real executable instead ' +
+ '(e.g. `node <path>\\server.js` or `<path>\\python.exe -m <module>`).'
+ );
+ }
+
+ if (codeIsPermission) {
+ return (
+ `MCP server executable is not executable: "${command}". ` +
+ 'Check file permissions (on macOS/Linux: `chmod +x <file>`) or antivirus/security-software blocks.'
+ );
+ }
+
+ const windowsPathNotFound = WINDOWS_PATH_NOT_FOUND_PATTERNS.some((pattern) =>
+ combinedOutput.toLowerCase().includes(pattern.toLowerCase()),
+ );
+
+ if (windowsPathNotFound) {
+ return (
+ `MCP server "${command}" failed to start: the loader reported "path not found" (see the process output below). ` +
+ 'The configured command or one of its script/shim targets does not exist on this machine. ' +
+ 'Reinstall the MCP server package, or fix the configured command/args to point at an existing executable. ' +
+ 'On Windows, `npx`/`.cmd` shims require the target script to exist — prefer the real executable path.'
+ );
+ }
+
+ // Signal-only kills have exitCode === null in Node; surface the crash
+ // signal instead of the generic "check PATH / install" advice. Catch it
+ // before the exitCode branch, which the null code would skip.
+ if (input.signal) {
+ return (
+ `MCP server "${command}" crashed: terminated by signal ${input.signal}` +
+ `${combinedOutput ? ' (see the process output below)' : ' with no output'}. ` +
+ 'This usually indicates an unhandled native-level failure (e.g. missing shared library or corrupted binary); ' +
+ 'reinstall the MCP server package and verify it runs standalone.'
+ );
+ }
+
+ // Zero-code exits are only passed by the pre-check when the process
+ // terminated cleanly WITHOUT completing the MCP handshake — a persistent
+ // MCP server must stay alive and answer initialize requests. Catch before
+ // the exitCode branch, which skips code 0.
+ if (input.exitCode === 0) {
+ return (
+ `MCP server "${command}" exited (code 0) without completing the MCP handshake. ` +
+ 'A persistent MCP server must stay running and respond to initialize requests; ' +
+ 'the configured command may be a one-shot utility, or it may be exiting right ' +
+ 'after startup (see the process output below for any error it printed).'
+ );
+ }
+
+ if (input.exitCode !== undefined && input.exitCode !== null && input.exitCode !== 0) {
+ return (
+ `MCP server "${command}" exited immediately with code ${input.exitCode}` +
+ `${input.signal ? ` (signal ${input.signal})` : ''}` +
+ ". Check the process output below and the server's installation requirements."
+ );
+ }
+
+ if (stderr) {
+ return `MCP server "${command}" failed to start. Check the process output below.`;
+ }
+
+ return (
+ `MCP server "${command}" failed to start and produced no output. ` +
+ 'Verify the command exists on this machine (check the configured PATH) and install the package it needs ' +
+ '(e.g. `npm install -g <package>` or `pip install <package>`).'
+ );
+}
+
export class MCPClient {
/**
* Upper bound on retained stderr lines. Pooled clients can live for the
@@ -40,6 +352,12 @@ export class MCPClient {
private transport: Transport;
private stderrLogs: string[] = [];
private isStdio: boolean = false;
+ /**
+ * Kept for post-failure diagnostics: `StdioClientTransport` does not expose
+ * its server params, and re-spawning the command after a bare
+ * "Connection closed" is the only way to surface an actionable error.
+ */
+ private stdioParams?: { args?: string[]; command: string; env?: Record<string, string> };
constructor(params: MCPClientParams) {
this.mcp = new Client({ name: 'lobehub-desktop-mcp-client', version: '1.0.0' });
@@ -66,6 +384,11 @@ export class MCPClient {
case 'stdio': {
this.isStdio = true;
+ this.stdioParams = {
+ args: params.args,
+ command: params.command,
+ env: params.env,
+ };
const stdioTransport = new StdioClientTransport({
args: params.args,
command: params.command,
@@ -116,6 +439,226 @@ export class MCPClient {
return this.stderrLogs;
}
+ /**
+ * Re-run the stdio command out-of-band to capture the concrete startup
+ * failure. `StdioClientTransport.start()` rejects with the bare transport
+ * error ("Connection closed", SDK error -32000) and when the process dies
+ * instantly there is often no stderr flowing through the transport's pipe
+ * yet — leaving users with nothing actionable. Mirrors the web app's
+ * `preCheckStdioCommand` (src/libs/mcp/client.ts).
+ */
+ private preCheckStdioCommand(params: {
+ args?: string[];
+ command: string;
+ env?: Record<string, string>;
+ /** Test hook only — production always uses the default 5s window. */
+ timeoutMs?: number;
+ }): Promise<{ diagnosis: string; stderr: string; stdout: string; success: boolean }> {
+ return new Promise((resolve) => {
+ // Do NOT spread the full process.env here: only the SDK's safe defaults
+ // plus user-configured vars, matching the main StdioClientTransport.
+ const env = {
+ ...getDefaultEnvironment(),
+ ...params.env,
+ } as NodeJS.ProcessEnv;
+
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(params.command, params.args ?? [], {
+ // POSIX only: make the child a process-group leader so teardown
+ // can signal the whole tree (launchers that spawn persistent
+ // workers leave no orphans). On Windows `detached` means a new
+ // console window / DETACHED_PROCESS — not wanted here; tree
+ // teardown there is handled via `taskkill /T` (see
+ // `signalProcessTree`).
+ detached: process.platform !== 'win32',
+ env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ } catch (error) {
+ // spawn() can throw synchronously (e.g. invalid args) — normalize it
+ const err = error as NodeJS.ErrnoException;
+ resolve({
+ diagnosis: describeStdioSpawnFailure({
+ command: params.command,
+ errno: err.errno,
+ message: err.message,
+ spawnCode: err.code,
+ }),
+ stderr: '',
+ stdout: '',
+ success: false,
+ });
+ return;
+ }
+
+ const stdout = new PrecheckOutputStream('stdout');
+ const stderr = new PrecheckOutputStream('stderr');
+ let resolved = false;
+
+ const finish = (result: {
+ diagnosis: string;
+ stderr: string;
+ stdout: string;
+ success: boolean;
+ }) => {
+ if (!resolved) {
+ resolved = true;
+ clearTimeout(timeout);
+ resolve(result);
+ }
+ };
+
+ // Give the process a short window to either complete the MCP handshake
+ // (exit 0 in pre-check terms) or fail with a diagnosable error.
+ const timeout = setTimeout(() => {
+ if (resolved) return;
+ child.stdout?.pause();
+ child.stderr?.pause();
+ child.stdin?.end();
+ // Wait for the confirmed teardown (SIGTERM → SIGKILL escalation →
+ // exit event) before resolving; a server that ignores SIGTERM must
+ // not survive the pre-check with its pipe listeners attached.
+ terminatePrecheckProcess(child, () => {
+ // Still running after 5s: treat as healthy-enough; the original
+ // connection error is the real failure and should surface as-is.
+ finish({
+ diagnosis: '',
+ stderr: stderr.toString(),
+ stdout: stdout.toString(),
+ success: true,
+ });
+ });
+ }, params.timeoutMs ?? 5000);
+
+ // P1: the diagnostic child may die instantly (the exact scenario this
+ // pre-check targets) and `stdin.write` would emit an async EPIPE that
+ // the surrounding try/catch cannot catch — an uncaught exception in the
+ // Electron main process. Swallow it; 'error'/'exit' handlers own the
+ // failure diagnosis.
+ child.stdin?.on('error', () => {});
+
+ child.stdout?.on('data', (data: Buffer) => {
+ stdout.append(data);
+ });
+
+ child.stderr?.on('data', (data: Buffer) => {
+ stderr.append(data);
+ });
+
+ child.on('error', (error: NodeJS.ErrnoException) => {
+ finish({
+ diagnosis: describeStdioSpawnFailure({
+ command: params.command,
+ errno: error.errno,
+ message: error.message,
+ spawnCode: error.code,
+ }),
+ stderr: stderr.toString(),
+ stdout: stdout.toString(),
+ success: false,
+ });
+ });
+
+ // Classify on `close`, not `exit`: Node emits `exit` when the process
+ // terminates but stdio streams may still hold buffered data, so a final
+ // loader error — or the initialize response checked by
+ // `hasInitializeResponse()` — can arrive after `exit` and be missed,
+ // producing a generic or wrong diagnosis. `close` fires only after ALL
+ // stdio streams have closed and drained. The `error` handler above
+ // still owns spawn failures (error and close are mutually exclusive).
+ const classify = (code: number | null, signal: NodeJS.Signals | null) => {
+ // The direct child exited on its own. If it was a launcher, its
+ // worker descendants may still be alive in the process group —
+ // every failed reconnect would otherwise accumulate another
+ // orphaned MCP server. Background-reap the group (no-op when the
+ // tree already exited; setsid daemons that left the group are
+ // untouched). The timeout path instead goes through
+ // `terminatePrecheckProcess`, which signals the whole tree itself.
+ if (child.pid !== undefined) {
+ reapOrphanedProcessGroup(child.pid);
+ }
+
+ if (code === 0) {
+ // Exit 0 alone does not prove the MCP handshake completed: one-shot
+ // executables and wrappers can start, print an error and exit
+ // cleanly before responding to the initialize probe. Only credit
+ // the probe when an initialize response was actually received;
+ // otherwise diagnose the zero-code exit as a startup failure.
+ if (hasInitializeResponse(stdout.toString())) {
+ finish({
+ diagnosis: '',
+ stderr: stderr.toString(),
+ stdout: stdout.toString(),
+ success: true,
+ });
+ } else {
+ finish({
+ diagnosis: describeStdioSpawnFailure({
+ command: params.command,
+ exitCode: 0,
+ stderr: stderr.toString(),
+ stdout: stdout.toString(),
+ }),
+ stderr: stderr.toString(),
+ success: false,
+ stdout: stdout.toString(),
+ });
+ }
+ return;
+ }
+
+ finish({
+ diagnosis: describeStdioSpawnFailure({
+ command: params.command,
+ exitCode: code,
+ signal,
+ stderr: stderr.toString(),
+ stdout: stdout.toString(),
+ }),
+ stderr: stderr.toString(),
+ stdout: stdout.toString(),
+ success: false,
+ });
+ };
+
+ // A grandchild spawned by the server can inherit the stdio pipes and
+ // keep `close` pending long after the direct child exited. Arm a
+ // bounded fallback on `exit` (never before — a healthy long-running
+ // server has no exit yet) so a zero-code exit still gets classified
+ // with the direct child's real exit code instead of waiting for the
+ // 5s timeout and being misclassified as "healthy-enough" — which
+ // would regress the round-4 fix that diagnoses one-shot wrappers.
+ // When the pipes close in time the `close` handler wins and this
+ // timer is cleared.
+ let closeFallback: ReturnType<typeof setTimeout> | null = null;
+
+ child.on('close', (code, signal) => {
+ if (closeFallback) clearTimeout(closeFallback);
+ classify(code, signal);
+ });
+
+ child.on('exit', (code, signal) => {
+ if (resolved) return;
+ closeFallback = setTimeout(() => {
+ classify(code, signal);
+ }, PRECHECK_CLOSE_GRACE_MS);
+ });
+
+ // Send a minimal JSON-RPC initialize so servers that start fine but
+ // exit on EOF don't get killed as "failed" before they can boot.
+ // `capabilities: {}` is included per the MCP initialize spec so servers
+ // that validate params don't reject the probe for a probe-specific
+ // reason and mask the real startup failure.
+ try {
+ child.stdin?.write(buildInitializeProbeMessage());
+ child.stdin?.end();
+ } catch {
+ // stdin write failures are handled via 'error'/'close' events
+ }
+ });
+ }
+
private isMethodNotFoundError(error: unknown) {
const err = error as any;
if (!err) return false;
@@ -134,6 +677,37 @@ export class MCPClient {
const originalMessage = error instanceof Error ? error.message : String(error);
throw new MCPConnectionError(originalMessage, this.stderrLogs);
}
+
+ // When the process dies instantly there may be no stderr at all, leaving
+ // users with a bare "Connection closed" (-32000). Re-spawn once to
+ // capture a concrete, actionable diagnosis instead. Other failure
+ // classes (protocol/configuration errors with stderr already flowing
+ // through the transport) gain nothing from a re-spawn: the probe can
+ // only diagnose startup liveness, so gate it to the bare
+ // connection-closed failure (P2 4306033474).
+ if (this.isStdio && this.stdioParams?.command && isBareConnectionClosedError(error)) {
+ const preCheck = await this.preCheckStdioCommand({
+ args: this.stdioParams.args,
+ command: this.stdioParams.command,
+ env: this.stdioParams.env,
+ });
+
+ if (!preCheck.success) {
+ const originalMessage = error instanceof Error ? error.message : String(error);
+ // Bounded process output (stdout can carry the real launcher error
+ // when the process writes nothing to stderr). Merge both streams,
+ // keeping the tail of each — the decisive error is usually the last
+ // line, after startup chatter. selectDiagnosticOutputLines caps the
+ // result (10 lines per stream; both streams are capped at 64 KiB).
+ const outputLines = selectDiagnosticOutputLines(preCheck.stdout, preCheck.stderr);
+
+ throw new MCPConnectionError(
+ `${preCheck.diagnosis} (original error: ${originalMessage})`,
+ outputLines,
+ );
+ }
+ }
+
throw error;
}
}
diff --git a/apps/desktop/src/main/libs/mcp/process-tree.test.ts b/apps/desktop/src/main/libs/mcp/process-tree.test.ts
new file mode 100644
index 00000000000..95ad703c2bf
--- /dev/null
+++ b/apps/desktop/src/main/libs/mcp/process-tree.test.ts
@@ -0,0 +1,437 @@
+import { EventEmitter } from 'node:events';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ reapOrphanedProcessGroup,
+ signalProcessTree,
+ terminatePrecheckProcess,
+} from './process-tree';
+
+describe('terminatePrecheckProcess', () => {
+ const makeFakeChild = (pid?: number) => {
+ const listeners: Record<string, (() => void)[]> = {};
+ const child = new EventEmitter() as EventEmitter & {
+ kill: ReturnType<typeof vi.fn>;
+ once: (event: string, fn: () => void) => void;
+ pid?: number;
+ };
+ child.kill = vi.fn();
+ child.pid = pid;
+ (child as any).once = (event: string, fn: () => void) => {
+ listeners[event] = listeners[event] || [];
+ listeners[event].push(fn);
+ return child;
+ };
+ (child as any).__emit = (event: string) => {
+ for (const fn of listeners[event] || []) fn();
+ };
+ (child as any).__listeners = listeners;
+ return child;
+ };
+
+ it('sends SIGTERM via signalProcessTree and settles on the exit event', async () => {
+ vi.useFakeTimers();
+ try {
+ const child = makeFakeChild(4242);
+ const onSettled = vi.fn();
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation(((
+ pid: number,
+ sig?: NodeJS.Signals,
+ ) => {
+ if (pid === -4242) return true;
+ return process.kill(pid, sig);
+ }) as any);
+
+ terminatePrecheckProcess(child as any, onSettled);
+ // signalProcessTree awaits a 100ms delay before the direct-kill belt
+ await vi.advanceTimersByTimeAsync(150);
+
+ // -pid signals the whole POSIX process group (launcher + workers)
+ expect(groupKill).toHaveBeenCalledWith(-4242, 'SIGTERM');
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(onSettled).not.toHaveBeenCalled();
+
+ (child as any).__emit('exit');
+ expect(onSettled).toHaveBeenCalledTimes(1);
+ // The SIGKILL escalation survives the launcher's exit (P2 4306440127);
+ // only the hard fallback is cleared by settle. advanceTimersByTimeAsync
+ // flushes the promise chain inside signalProcessTree so the direct-kill
+ // belt (100ms after the group signal) lands before the assertion.
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(onSettled).toHaveBeenCalledTimes(1);
+ expect(groupKill).toHaveBeenCalledWith(-4242, 'SIGKILL');
+ expect(child.kill).toHaveBeenLastCalledWith('SIGKILL');
+ groupKill.mockRestore();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps the group SIGKILL escalation when the launcher exits early and a worker ignores SIGTERM (P2 4306440127)', async () => {
+ vi.useFakeTimers();
+ try {
+ const child = makeFakeChild(4242);
+ const onSettled = vi.fn();
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation((() => true) as any);
+
+ terminatePrecheckProcess(child as any, onSettled);
+ await vi.advanceTimersByTimeAsync(150);
+ // The launcher dies on the group SIGTERM before the grace period ends;
+ // a worker descendant ignored the signal and is still alive.
+ (child as any).__emit('exit');
+ expect(onSettled).toHaveBeenCalledTimes(1);
+
+ // The escalation must still fire after the grace period — settle no
+ // longer cancels it, otherwise the ignoring worker leaks.
+ await vi.advanceTimersByTimeAsync(600); // grace 500 + retry 100
+ expect(groupKill).toHaveBeenCalledWith(-4242, 'SIGKILL');
+ expect(child.kill).toHaveBeenLastCalledWith('SIGKILL');
+ expect(onSettled).toHaveBeenCalledTimes(1); // settled exactly once
+ groupKill.mockRestore();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('escalates to a SIGKILL group signal after the grace period', async () => {
+ vi.useFakeTimers();
+ try {
+ const child = makeFakeChild(4242);
+ const onSettled = vi.fn();
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation((() => true) as any);
+
+ terminatePrecheckProcess(child as any, onSettled);
+ await vi.advanceTimersByTimeAsync(600); // grace 500 + retry 100
+
+ expect(groupKill).toHaveBeenCalledWith(-4242, 'SIGKILL');
+ expect(child.kill).toHaveBeenLastCalledWith('SIGKILL');
+
+ // exit after escalation settles and clears the fallback timer
+ (child as any).__emit('exit');
+ expect(onSettled).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(2000);
+ expect(onSettled).toHaveBeenCalledTimes(1);
+ groupKill.mockRestore();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('falls back to a direct child kill when the process group is gone (ESRCH)', async () => {
+ const child = makeFakeChild(9999);
+ const onSettled = vi.fn();
+ // No group exists for -9999: process.kill(-pid) throws ESRCH
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation(((pid: number) => {
+ if (typeof pid === 'number' && pid < 0) {
+ const e = new Error('no such process') as NodeJS.ErrnoException;
+ e.code = 'ESRCH';
+ throw e;
+ }
+ return true;
+ }) as any);
+
+ await signalProcessTree(child as any, 'SIGTERM');
+
+ // group signal failed, but the direct child still got the signal
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(onSettled).not.toHaveBeenCalled();
+ groupKill.mockRestore();
+ });
+
+ it('uses the direct kill path for children without a pid (mocked children)', async () => {
+ const child = makeFakeChild(undefined);
+
+ await signalProcessTree(child as any, 'SIGTERM');
+
+ expect(child.kill).toHaveBeenCalledTimes(1);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ });
+
+ it('settles via the hard fallback even when no exit event ever fires', async () => {
+ vi.useFakeTimers();
+ try {
+ const child = makeFakeChild(4242);
+ const onSettled = vi.fn();
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation((() => true) as any);
+
+ terminatePrecheckProcess(child as any, onSettled);
+ await vi.advanceTimersByTimeAsync(1600); // SIGTERM round + SIGKILL round
+
+ expect(onSettled).toHaveBeenCalledTimes(1);
+ // SIGTERM (group+direct) + SIGKILL (group+direct)
+ expect(child.kill).toHaveBeenCalledTimes(2);
+ expect(groupKill).toHaveBeenCalledWith(-4242, 'SIGTERM');
+ expect(groupKill).toHaveBeenCalledWith(-4242, 'SIGKILL');
+ groupKill.mockRestore();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('settles only once across exit and fallback races', async () => {
+ vi.useFakeTimers();
+ try {
+ const child = makeFakeChild(4242);
+ const onSettled = vi.fn();
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation((() => true) as any);
+
+ terminatePrecheckProcess(child as any, onSettled);
+ await vi.advanceTimersByTimeAsync(150);
+ (child as any).__emit('exit');
+ vi.advanceTimersByTime(2000);
+
+ expect(onSettled).toHaveBeenCalledTimes(1);
+ groupKill.mockRestore();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('reapOrphanedProcessGroup', () => {
+ it('sends the initial group signal immediately and re-checks once', async () => {
+ vi.useFakeTimers();
+ try {
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation((() => true) as any);
+
+ reapOrphanedProcessGroup(5555);
+
+ expect(groupKill).toHaveBeenCalledWith(-5555, 'SIGKILL');
+
+ await vi.advanceTimersByTimeAsync(500);
+ expect(groupKill).toHaveBeenCalledTimes(2);
+ expect(groupKill).toHaveBeenLastCalledWith(-5555, 'SIGKILL');
+ groupKill.mockRestore();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not schedule a re-check when the group is already gone', async () => {
+ vi.useFakeTimers();
+ try {
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation(((pid: number) => {
+ if (typeof pid === 'number' && pid < 0) {
+ const e = new Error('no such process') as NodeJS.ErrnoException;
+ e.code = 'ESRCH';
+ throw e;
+ }
+ return true;
+ }) as any);
+
+ reapOrphanedProcessGroup(5555);
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(groupKill).toHaveBeenCalledTimes(1); // initial probe only
+ groupKill.mockRestore();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('logs and leaves alone a group it cannot signal (EPERM / setsid daemon)', async () => {
+ vi.useFakeTimers();
+ try {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation(((pid: number) => {
+ if (typeof pid === 'number' && pid < 0) {
+ const e = new Error('operation not permitted') as NodeJS.ErrnoException;
+ e.code = 'EPERM';
+ throw e;
+ }
+ return true;
+ }) as any);
+
+ reapOrphanedProcessGroup(6666);
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(groupKill).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('EPERM'));
+ groupKill.mockRestore();
+ warn.mockRestore();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('windows launcher pre-exit recovery (P2 4307489808)', () => {
+ // The Windows branches key off process.platform at call time; pin it to
+ // win32 (and restore) so the paths are covered on a POSIX dev machine.
+ const pinWindowsPlatform = () => {
+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
+ return () => Object.defineProperty(process, 'platform', descriptor);
+ };
+
+ // ./process-tree is statically imported at the top of this file; clear the
+ // module registry so vi.doMock applies to the dynamic re-import below.
+ const setupWindowsMocks = (plan: { taskkill: 'ok' | 'fail'; cim?: string }) => {
+ vi.resetModules();
+ const taskkillInvocations: string[][] = [];
+ let cimSnapshotCount = 0;
+ vi.doMock('node:child_process', async (importOriginal) => {
+ const actual = importOriginal<any>();
+ return {
+ ...actual,
+ execFile: (
+ file: string,
+ args: readonly string[],
+ optionsOrCallback:
+ | { timeout?: number }
+ | ((error: Error | null, stdout: string) => void),
+ maybeCallback?: (error: Error | null, stdout: string) => void,
+ ) => {
+ // Node arity: (file, args, callback) or (file, args, options, callback)
+ const callback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : maybeCallback;
+ if (typeof callback !== 'function') {
+ throw new TypeError('mock execFile: no callback provided');
+ }
+ if (file === 'taskkill') {
+ if (plan.taskkill === 'ok') callback(null, '');
+ else callback(new Error('The process not found.'), '');
+ return;
+ }
+ if (file === 'powershell' && typeof plan.cim === 'string') {
+ cimSnapshotCount += 1;
+ callback(null, plan.cim);
+ return;
+ }
+ callback(new Error(`unexpected invocation: ${file}`), '');
+ },
+ } as any;
+ });
+ vi.doMock('node:util', async (importOriginal) => {
+ const actual = importOriginal<any>();
+ return {
+ ...actual,
+ promisify:
+ (fn: (...args: any[]) => void) =>
+ (...args: any[]) =>
+ new Promise((resolve, reject) => {
+ (fn as any)(...args, (error: Error | null, stdout: string) => {
+ if (error) reject(error);
+ else resolve({ stdout });
+ });
+ if (args[0] === 'taskkill') {
+ taskkillInvocations.push([...(args[1] as readonly string[])]);
+ }
+ }),
+ } as any;
+ });
+ return {
+ taskkillInvocations,
+ cimSnapshotCount: () => cimSnapshotCount,
+ };
+ };
+
+ const restoreMocks = () => {
+ vi.doUnmock('node:child_process');
+ vi.doUnmock('node:util');
+ vi.resetModules();
+ };
+
+ it('directly force-kills surviving descendants when the root taskkill fails (terminate path)', async () => {
+ const restorePlatform = pinWindowsPlatform();
+ const { taskkillInvocations } = setupWindowsMocks({
+ taskkill: 'fail',
+ cim: JSON.stringify([
+ { ProcessId: 111, ParentProcessId: 4242 },
+ { ProcessId: 222, ParentProcessId: 111 },
+ { ProcessId: 333, ParentProcessId: 999 },
+ ]),
+ });
+
+ try {
+ const { signalProcessTree } = await import('./process-tree');
+ const child = new EventEmitter() as EventEmitter & { kill: any; pid?: number };
+ child.kill = vi.fn();
+ child.pid = 4242;
+
+ // EPERM → treat as alive; ESRCH → already gone
+ const aliveProbe = vi.spyOn(process, 'kill').mockImplementation(((pid: number) => {
+ if (pid === 111 || pid === 222) {
+ const e = new Error('operation not permitted') as NodeJS.ErrnoException;
+ e.code = 'EPERM';
+ throw e;
+ }
+ const e = new Error('no such process') as NodeJS.ErrnoException;
+ e.code = 'ESRCH';
+ throw e;
+ }) as any);
+
+ await signalProcessTree(child as any, 'SIGTERM');
+
+ // Root /T /F failed → one batched direct kill for the survivors
+ // (111 + 222; 333 is not a descendant of 4242)
+ expect(taskkillInvocations.length).toBe(2);
+ expect(taskkillInvocations[0]).toEqual(['/pid', '4242', '/T', '/F']);
+ expect(taskkillInvocations[1]).toEqual(['/pid', '111', '/pid', '222', '/F']);
+ aliveProbe.mockRestore();
+ } finally {
+ restorePlatform();
+ restoreMocks();
+ }
+ });
+
+ it('sweeps surviving descendants detached after the root kill in the reaper (zero-code path)', async () => {
+ const restorePlatform = pinWindowsPlatform();
+ const { taskkillInvocations } = setupWindowsMocks({
+ taskkill: 'fail',
+ cim: JSON.stringify([
+ { ProcessId: 777, ParentProcessId: 5555 },
+ { ProcessId: 888, ParentProcessId: 777 },
+ ]),
+ });
+
+ try {
+ const { reapOrphanedProcessGroup } = await import('./process-tree');
+ const aliveProbe = vi.spyOn(process, 'kill').mockImplementation(((pid: number) => {
+ if (pid === 777) return true; // survivor
+ const e = new Error('no such process') as NodeJS.ErrnoException;
+ e.code = 'ESRCH';
+ throw e;
+ }) as any);
+
+ reapOrphanedProcessGroup(5555);
+
+ // The sweep is detached (not awaited) — poll until the survivor batch lands.
+ await vi.waitFor(() => {
+ expect(taskkillInvocations.length).toBe(2);
+ });
+ expect(taskkillInvocations[0]).toEqual(['/pid', '5555', '/T', '/F']);
+ // 888 is a descendant but probes dead (ESRCH) → only 777 is swept.
+ expect(taskkillInvocations[1]).toEqual(['/pid', '777', '/F']);
+ aliveProbe.mockRestore();
+ } finally {
+ restorePlatform();
+ restoreMocks();
+ }
+ });
+
+ it('skips the survivor sweep when the root taskkill succeeds (terminate path)', async () => {
+ const restorePlatform = pinWindowsPlatform();
+ const { taskkillInvocations, cimSnapshotCount } = setupWindowsMocks({
+ taskkill: 'ok',
+ cim: '[]',
+ });
+
+ try {
+ const { signalProcessTree } = await import('./process-tree');
+ const child = new EventEmitter() as EventEmitter & { kill: any; pid?: number };
+ child.kill = vi.fn();
+ child.pid = 4242;
+
+ await signalProcessTree(child as any, 'SIGTERM');
+
+ // Root kill landed; no CIM snapshot round and no extra taskkill call.
+ expect(taskkillInvocations).toEqual([['/pid', '4242', '/T', '/F']]);
+ expect(cimSnapshotCount()).toBe(0);
+ } finally {
+ restorePlatform();
+ restoreMocks();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/libs/mcp/process-tree.ts b/apps/desktop/src/main/libs/mcp/process-tree.ts
new file mode 100644
index 00000000000..cd32cd521d6
--- /dev/null
+++ b/apps/desktop/src/main/libs/mcp/process-tree.ts
@@ -0,0 +1,279 @@
+import { type ChildProcess, execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+
+/** execFile with a narrowed promise shape (the (file, args[, options]) overload only). */
+const execFileAsync = promisify(execFile) as (
+ file: string,
+ args: readonly string[],
+ options?: { timeout?: number },
+) => Promise<{ stdout: string; stderr: string }>;
+
+/** Max descendant pids listed per direct taskkill invocation. */
+const TASKKILL_BATCH_SIZE = 20;
+
+/** One CIM snapshot query returns every process id with its parent id. */
+const WINDOWS_PROCESS_SNAPSHOT_ARGS = [
+ '-NoProfile',
+ '-NonInteractive',
+ '-Command',
+ 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId | ConvertTo-Json -Compress',
+];
+
+type WindowsProcessRow = { ProcessId: number; ParentProcessId: number };
+
+const isPidAlive = (pid: number): boolean => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ // EPERM: the process exists but we cannot probe it — treat as alive.
+ return (error as NodeJS.ErrnoException).code === 'EPERM';
+ }
+};
+
+/**
+ * Enumerate the descendant pids of `rootPid` from a single CIM snapshot
+ * (one PowerShell round trip) and a BFS over the parent→children map. The
+ * visited set keeps self-referencing rows from looping the walk. Returns []
+ * when the snapshot is unavailable (CIM service down, malformed output), so
+ * callers degrade to the pre-existing behavior instead of throwing.
+ */
+const collectWindowsDescendantPids = async (rootPid: number): Promise<number[]> => {
+ let rows: WindowsProcessRow[];
+ try {
+ const { stdout } = await execFileAsync('powershell', [...WINDOWS_PROCESS_SNAPSHOT_ARGS], {
+ timeout: 5_000,
+ });
+ const parsed = JSON.parse(stdout) as WindowsProcessRow | WindowsProcessRow[];
+ rows = Array.isArray(parsed) ? parsed : [parsed];
+ } catch {
+ return [];
+ }
+
+ const childrenOf = new Map<number, number[]>();
+ for (const row of rows) {
+ if (typeof row?.ProcessId !== 'number' || typeof row?.ParentProcessId !== 'number') continue;
+ const siblings = childrenOf.get(row.ParentProcessId);
+ if (siblings) siblings.push(row.ProcessId);
+ else childrenOf.set(row.ParentProcessId, [row.ProcessId]);
+ }
+
+ const descendants: number[] = [];
+ const visited = new Set<number>([rootPid]);
+ const queue = [rootPid];
+ while (queue.length > 0) {
+ const parent = queue.shift();
+ if (parent === undefined) break;
+ for (const child of childrenOf.get(parent) ?? []) {
+ if (visited.has(child)) continue;
+ visited.add(child);
+ descendants.push(child);
+ queue.push(child);
+ }
+ }
+ return descendants;
+};
+
+const killWindowsDescendants = async (descendantPids: number[]): Promise<void> => {
+ for (let i = 0; i < descendantPids.length; i += TASKKILL_BATCH_SIZE) {
+ const batch = descendantPids.slice(i, i + TASKKILL_BATCH_SIZE);
+ const args = batch.flatMap((pid) => ['/pid', String(pid)]);
+ args.push('/F');
+ try {
+ await execFileAsync('taskkill', args);
+ } catch {
+ // already exited between the snapshot and the kill
+ }
+ }
+};
+
+/**
+ * Windows fallback for the launcher pre-exit gap (P2 4307489808): `taskkill
+ * /T` walks the tree from the given pid, so it cannot recover descendants
+ * whose root (the launcher) has already exited — the swallowed failure
+ * would leak the worker across reconnects. Probe whether any descendant
+ * survived the failed root kill and force-terminate them directly.
+ */
+const killSurvivingWindowsDescendants = async (rootPid: number): Promise<void> => {
+ const descendants = await collectWindowsDescendantPids(rootPid);
+ const survivors = descendants.filter(isPidAlive);
+ if (survivors.length === 0) return;
+ await killWindowsDescendants(survivors);
+};
+
+/**
+ * Signal a pre-check child and its whole process tree.
+ *
+ * A configured command can be a launcher (`.cmd` shim, wrapper script,
+ * `npx`, ...) that spawns a persistent MCP worker as a separate process.
+ * Signaling only the direct child PID leaves that worker orphaned — the
+ * launcher exits, `settle` reports cleanup done, and every repeated failed
+ * connection accumulates another live MCP server. On POSIX the pre-check
+ * child is spawned `detached`, making it a process-group leader, so a
+ * negative PID signals the whole group in one call. Windows has no process
+ * groups, so `taskkill /T /F` walks and force-kills the tree instead. The
+ * direct-kill fallback keeps this correct for mocked children in tests and
+ * for detached=false callers.
+ */
+export async function signalProcessTree(
+ child: Pick<ChildProcess, 'kill' | 'pid'>,
+ signal: NodeJS.Signals,
+ options: { retryDelayMs?: number } = {},
+): Promise<void> {
+ const { retryDelayMs = 100 } = options;
+
+ if (child.pid === undefined) {
+ // Never spawned (or already reaped) — the direct kill keeps mocked
+ // children in unit tests working without a real pid.
+ try {
+ child.kill(signal);
+ } catch {
+ // already gone
+ }
+ return;
+ }
+
+ const pid = child.pid;
+
+ if (process.platform === 'win32') {
+ // Windows: /T walks the child tree, /F force-terminates. taskkill can
+ // exit nonzero when the tree already exited — not an error for us.
+ try {
+ await execFileAsync('taskkill', ['/pid', String(pid), '/T', '/F']);
+ return;
+ } catch {
+ // The tree may already be gone — but a launcher that exited BEFORE
+ // this call leaves /T nothing to walk (its descendants are no longer
+ // its children), so probe for surviving descendants directly
+ // (P2 4307489808) instead of swallowing the failure.
+ }
+ await killSurvivingWindowsDescendants(pid);
+ return;
+ }
+
+ // POSIX: the child is spawned detached → it leads its own process group,
+ // so -pid signals every member (launcher + worker descendants) atomically.
+ try {
+ process.kill(-pid, signal);
+ } catch {
+ // ESRCH: group already gone — fall through to the direct child kill.
+ }
+
+ // Belt-and-braces: if the group signal raced with an exit and the direct
+ // child somehow survived (group leader replaced / signal delivered between
+ // membership checks), ensure it gets the signal directly.
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
+ try {
+ child.kill(signal);
+ } catch {
+ // already dead
+ }
+}
+
+/**
+ * After the pre-check child exits on its own (launcher self-exit path),
+ * the launcher's descendants can still be alive in the process group —
+ * repeated failed connections would accumulate one orphaned MCP worker
+ * each time. Probe the group for survivors and SIGKILL them.
+ *
+ * Runs detached in the background (not awaited): the pre-check promise
+ * must not wait on cleanup, and a failed probe is a no-op. A daemonized
+ * (setsid) server deliberately leaves its group; killing it would be
+ * surprising behavior, so survivors there are logged and left alone.
+ */
+export function reapOrphanedProcessGroup(
+ pid: number,
+ signal: NodeJS.Signals = 'SIGKILL',
+ options: { recheckDelayMs?: number } = {},
+): void {
+ const { recheckDelayMs = 500 } = options;
+
+ if (process.platform === 'win32') {
+ // No POSIX process groups on Windows; the zero-code classification path
+ // here is best-effort cleanup. A launcher that exited before this call
+ // leaves /T nothing to walk (its descendants are no longer its children),
+ // so after the root kill, probe for surviving descendants directly
+ // (P2 4307489808). Detached best-effort sweep — this function is
+ // intentionally not awaited.
+ void (async () => {
+ try {
+ await execFileAsync('taskkill', ['/pid', String(pid), '/T', '/F']);
+ } catch {
+ // root already gone or tree already exited
+ }
+ await killSurvivingWindowsDescendants(pid);
+ })();
+ return;
+ }
+
+ const killGroup = (groupSignal: NodeJS.Signals): boolean => {
+ try {
+ process.kill(-pid, groupSignal);
+ return true;
+ } catch (error) {
+ const err = error as NodeJS.ErrnoException;
+ // EPERM means the group exists but we lack permission (e.g. a
+ // setsid daemon whose group we cannot signal) — report and leave.
+ // ESRCH means the group is already gone — normal case.
+ if (err.code === 'EPERM') {
+ console.warn(
+ `[mcp-precheck] orphaned process group -${pid} survives (EPERM, possibly setsid daemon); leaving it alone`,
+ );
+ }
+ return false;
+ }
+ };
+
+ if (!killGroup(signal)) return;
+
+ // Re-check after a grace period: a signal can be delivered while a
+ // descendant is between fork and signal-handler install. A second kill of
+ // the same group is a no-op if everything died.
+ setTimeout(() => {
+ killGroup(signal);
+ }, recheckDelayMs);
+}
+
+/**
+ * Tear down a pre-check child that outlived its 5s window. The whole
+ * process tree is signaled (see `signalProcessTree` — POSIX process-group
+ * signal or Windows `taskkill /T`), escalating from SIGTERM to SIGKILL
+ * after a short grace period, and settling once the exit event confirms
+ * the process is gone (with a hard fallback so the pre-check promise can
+ * never hang). The SIGKILL escalation is NOT cancelled by the launcher's
+ * exit (P2 4306440127): a launcher that dies on the group SIGTERM while a
+ * worker descendant ignores the signal would otherwise settle the teardown
+ * and leak that worker across repeated failed connections. When the group
+ * is already gone the escalation is a harmless ESRCH no-op. Without the
+ * exit confirmation a server that ignores SIGTERM would survive with its
+ * pipe listeners attached, leaking processes across repeated failed
+ * connections.
+ */
+export function terminatePrecheckProcess(
+ child: ChildProcess,
+ onSettled: () => void,
+ options: { fallbackMs?: number; graceMs?: number } = {},
+): void {
+ const { fallbackMs = 1500, graceMs = 500 } = options;
+
+ let settled = false;
+ const settle = () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(fallbackTimer);
+ onSettled();
+ };
+
+ // The SIGKILL escalation is intentionally NOT tracked/cancelled: settle()
+ // fires when the launcher exits, but a worker descendant may ignore the
+ // group SIGTERM — the escalation must still land to kill the group
+ // (P2 4306440127). When everything already exited it is an ESRCH no-op.
+ setTimeout(() => {
+ void signalProcessTree(child, 'SIGKILL');
+ }, graceMs);
+
+ const fallbackTimer = setTimeout(settle, fallbackMs);
+
+ child.once('exit', settle);
+ void signalProcessTree(child, 'SIGTERM');
+}