mcp-process-lifecycle.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { tmpdir } from "node:os";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { createMcpAdapter } from "../src/mcp/index.js";
  6. import { terminateMcpStdioProcessTree } from "../src/mcp/process-tree.js";
  7. import { createMcpTelemetryTracker } from "../src/mcp/telemetry.js";
  8. describe("MCP stdio process lifecycle", () => {
  9. const cleanupPids = new Set<number>();
  10. afterEach(() => {
  11. for (const pid of cleanupPids) {
  12. forceKillPid(pid);
  13. }
  14. cleanupPids.clear();
  15. });
  16. it("uses taskkill to terminate stdio MCP process trees on Windows", async () => {
  17. const execFileMock = vi.fn(async () => createCommandResult({ status: 0 }));
  18. const killMock = vi.fn((pid: number, signal?: NodeJS.Signals | 0) => {
  19. if (signal === 0 && pid === 1234) return true;
  20. return true;
  21. }) as unknown as typeof process.kill;
  22. await terminateMcpStdioProcessTree(1234, {
  23. execFile: execFileMock,
  24. kill: killMock,
  25. platform: "win32",
  26. });
  27. expect(execFileMock).toHaveBeenCalledWith(
  28. "taskkill",
  29. ["/PID", "1234", "/T", "/F"],
  30. expect.objectContaining({
  31. windowsHide: true,
  32. }),
  33. );
  34. });
  35. it("reports Windows taskkill failures when the stdio MCP process is still alive", async () => {
  36. const execFileMock = vi.fn(async () =>
  37. createCommandResult({ error: new Error("taskkill failed"), status: 1 }),
  38. );
  39. const killMock = vi.fn((pid: number, signal?: NodeJS.Signals | 0) => {
  40. if (signal === 0 && pid === 4321) return true;
  41. return true;
  42. }) as unknown as typeof process.kill;
  43. await expect(
  44. terminateMcpStdioProcessTree(4321, {
  45. execFile: execFileMock,
  46. kill: killMock,
  47. platform: "win32",
  48. }),
  49. ).rejects.toThrow("taskkill failed");
  50. });
  51. it("treats Windows EPERM process probes as alive before taskkill", async () => {
  52. const execFileMock = vi.fn(async () => createCommandResult({ status: 0 }));
  53. const killMock = vi.fn((pid: number, signal?: NodeJS.Signals | 0) => {
  54. if (signal === 0 && pid === 9876) {
  55. throw Object.assign(new Error("permission denied"), { code: "EPERM" });
  56. }
  57. return true;
  58. }) as unknown as typeof process.kill;
  59. await terminateMcpStdioProcessTree(9876, {
  60. execFile: execFileMock,
  61. kill: killMock,
  62. platform: "win32",
  63. });
  64. expect(execFileMock).toHaveBeenCalledWith(
  65. "taskkill",
  66. ["/PID", "9876", "/T", "/F"],
  67. expect.objectContaining({
  68. windowsHide: true,
  69. }),
  70. );
  71. });
  72. it("signals known POSIX descendants before force killing stale stdio MCP processes", async () => {
  73. const alive = new Set([1000, 1001, 1002]);
  74. let now = 0;
  75. const killCalls: Array<{ pid: number; signal: NodeJS.Signals | 0 | undefined }> = [];
  76. const killMock = vi.fn((pid: number, signal?: NodeJS.Signals | 0) => {
  77. killCalls.push({ pid, signal });
  78. if (signal === 0) {
  79. if (alive.has(pid)) return true;
  80. throw Object.assign(new Error("missing"), { code: "ESRCH" });
  81. }
  82. if (signal === "SIGKILL" && pid > 0) {
  83. alive.delete(pid);
  84. }
  85. return true;
  86. }) as unknown as typeof process.kill;
  87. const execFileMock = vi.fn(async (command: string, args?: readonly string[]) => {
  88. if (command === "ps") return createCommandResult({ stdout: "" });
  89. expect(command).toBe("pgrep");
  90. const parentPid = args?.[1];
  91. if (parentPid === "1000") return createCommandResult({ stdout: "1001\n" });
  92. if (parentPid === "1001") return createCommandResult({ stdout: "1002\n" });
  93. return createCommandResult({ error: new Error("no children"), status: 1 });
  94. });
  95. await terminateMcpStdioProcessTree(1000, {
  96. execFile: execFileMock,
  97. kill: killMock,
  98. now: () => now,
  99. platform: "darwin",
  100. sleep: async (ms) => {
  101. now += ms;
  102. },
  103. });
  104. expect(killCalls).toEqual(
  105. expect.arrayContaining([
  106. { pid: -1000, signal: "SIGINT" },
  107. { pid: 1002, signal: "SIGINT" },
  108. { pid: 1001, signal: "SIGINT" },
  109. { pid: 1000, signal: "SIGINT" },
  110. { pid: -1000, signal: "SIGTERM" },
  111. { pid: 1002, signal: "SIGTERM" },
  112. { pid: 1001, signal: "SIGTERM" },
  113. { pid: 1000, signal: "SIGTERM" },
  114. { pid: 1002, signal: "SIGKILL" },
  115. { pid: 1001, signal: "SIGKILL" },
  116. { pid: 1000, signal: "SIGKILL" },
  117. ]),
  118. );
  119. });
  120. it("does not escalate POSIX cleanup after stdio MCP processes exit on SIGINT", async () => {
  121. const alive = new Set([2000, 2001]);
  122. let now = 0;
  123. const killCalls: Array<{ pid: number; signal: NodeJS.Signals | 0 | undefined }> = [];
  124. const killMock = vi.fn((pid: number, signal?: NodeJS.Signals | 0) => {
  125. killCalls.push({ pid, signal });
  126. if (signal === 0) {
  127. if (alive.has(pid)) return true;
  128. throw Object.assign(new Error("missing"), { code: "ESRCH" });
  129. }
  130. if (signal === "SIGINT" && pid > 0) {
  131. alive.delete(pid);
  132. }
  133. return true;
  134. }) as unknown as typeof process.kill;
  135. const execFileMock = vi.fn(async (_command: string, args?: readonly string[]) => {
  136. if (_command === "ps") return createCommandResult({ stdout: "" });
  137. return args?.[1] === "2000"
  138. ? createCommandResult({ stdout: "2001\n" })
  139. : createCommandResult({ error: new Error("no children"), status: 1 });
  140. });
  141. await terminateMcpStdioProcessTree(2000, {
  142. execFile: execFileMock,
  143. kill: killMock,
  144. now: () => now,
  145. platform: "linux",
  146. sleep: async (ms) => {
  147. now += ms;
  148. },
  149. });
  150. expect(killCalls).toEqual(
  151. expect.arrayContaining([
  152. { pid: -2000, signal: "SIGINT" },
  153. { pid: 2001, signal: "SIGINT" },
  154. { pid: 2000, signal: "SIGINT" },
  155. ]),
  156. );
  157. expect(killCalls).not.toEqual(
  158. expect.arrayContaining([
  159. { pid: 2001, signal: "SIGTERM" },
  160. { pid: 2000, signal: "SIGTERM" },
  161. { pid: 2001, signal: "SIGKILL" },
  162. { pid: 2000, signal: "SIGKILL" },
  163. ]),
  164. );
  165. });
  166. it("falls back to ps when pgrep cannot list POSIX descendants", async () => {
  167. const alive = new Set([3000, 3001, 3002]);
  168. let now = 0;
  169. const killCalls: Array<{ pid: number; signal: NodeJS.Signals | 0 | undefined }> = [];
  170. const killMock = vi.fn((pid: number, signal?: NodeJS.Signals | 0) => {
  171. killCalls.push({ pid, signal });
  172. if (signal === 0) {
  173. if (alive.has(pid)) return true;
  174. throw Object.assign(new Error("missing"), { code: "ESRCH" });
  175. }
  176. if (signal === "SIGKILL" && pid > 0) {
  177. alive.delete(pid);
  178. }
  179. return true;
  180. }) as unknown as typeof process.kill;
  181. const execFileMock = vi.fn(async (command: string) => {
  182. if (command === "pgrep") {
  183. return createCommandResult({
  184. error: Object.assign(new Error("pgrep missing"), { code: "ENOENT" }),
  185. status: null,
  186. });
  187. }
  188. expect(command).toBe("ps");
  189. return createCommandResult({
  190. stdout: ["3000 1", "3001 3000", "3002 3001"].join("\n"),
  191. });
  192. });
  193. await terminateMcpStdioProcessTree(3000, {
  194. execFile: execFileMock,
  195. kill: killMock,
  196. now: () => now,
  197. platform: "linux",
  198. sleep: async (ms) => {
  199. now += ms;
  200. },
  201. });
  202. expect(execFileMock).toHaveBeenCalledWith("ps", ["-eo", "pid=,ppid="], expect.anything());
  203. expect(killCalls).toEqual(
  204. expect.arrayContaining([
  205. { pid: 3002, signal: "SIGKILL" },
  206. { pid: 3001, signal: "SIGKILL" },
  207. { pid: 3000, signal: "SIGKILL" },
  208. ]),
  209. );
  210. });
  211. it("reports POSIX cleanup failures when stale stdio MCP processes survive SIGKILL", async () => {
  212. let now = 0;
  213. const killMock = vi.fn((pid: number, signal?: NodeJS.Signals | 0) => {
  214. if (signal === 0 && pid === 4000) return true;
  215. return true;
  216. }) as unknown as typeof process.kill;
  217. const execFileMock = vi.fn(async (command: string) => {
  218. if (command === "pgrep") {
  219. return createCommandResult({ error: new Error("no children"), status: 1 });
  220. }
  221. return createCommandResult({ stdout: "4000 1\n" });
  222. });
  223. await expect(
  224. terminateMcpStdioProcessTree(4000, {
  225. execFile: execFileMock,
  226. kill: killMock,
  227. now: () => now,
  228. platform: "darwin",
  229. sleep: async (ms) => {
  230. now += ms;
  231. },
  232. }),
  233. ).rejects.toThrow("SIGKILL failed");
  234. });
  235. it.runIf(process.platform !== "win32")(
  236. "terminates a connected stdio MCP server and its child process on adapter close",
  237. async () => {
  238. const fixture = await createMcpProcessFixture();
  239. const adapter = createMcpAdapter();
  240. await expect(
  241. adapter.connectServer("tree", {
  242. args: [fixture.serverPath],
  243. command: process.execPath,
  244. env: fixture.env,
  245. timeoutMs: 5_000,
  246. type: "stdio",
  247. }),
  248. ).resolves.toMatchObject({
  249. status: "connected",
  250. });
  251. const serverPid = await readPidFile(fixture.serverPidFile);
  252. const childPid = await readPidFile(fixture.childPidFile);
  253. cleanupPids.add(serverPid);
  254. cleanupPids.add(childPid);
  255. expect(isPidAlive(serverPid)).toBe(true);
  256. expect(isPidAlive(childPid)).toBe(true);
  257. await adapter.close();
  258. await waitForPidExit(serverPid);
  259. await waitForPidExit(childPid);
  260. cleanupPids.delete(serverPid);
  261. cleanupPids.delete(childPid);
  262. await rm(fixture.root, { force: true, recursive: true });
  263. },
  264. );
  265. it.runIf(process.platform !== "win32")(
  266. "cleans up stdio MCP server children when connection times out",
  267. async () => {
  268. const fixture = await createMcpProcessFixture({ hangDuringInitialize: true });
  269. const adapter = createMcpAdapter();
  270. const connect = adapter.connectServer("hanging", {
  271. args: [fixture.serverPath],
  272. command: process.execPath,
  273. env: fixture.env,
  274. timeoutMs: 1_000,
  275. type: "stdio",
  276. });
  277. const serverPid = await readPidFile(fixture.serverPidFile);
  278. const childPid = await readPidFile(fixture.childPidFile);
  279. cleanupPids.add(serverPid);
  280. cleanupPids.add(childPid);
  281. await expect(connect).resolves.toMatchObject({
  282. failureKind: "connection_timeout",
  283. status: "failed",
  284. });
  285. await waitForPidExit(serverPid);
  286. await waitForPidExit(childPid);
  287. cleanupPids.delete(serverPid);
  288. cleanupPids.delete(childPid);
  289. await rm(fixture.root, { force: true, recursive: true });
  290. },
  291. );
  292. it.runIf(process.platform !== "win32")(
  293. "reports one start and crash for the final stdio process with its exit code",
  294. async () => {
  295. const fixture = await createMcpProcessFixture({ crashAfterConnectedMs: 100 });
  296. const events: Array<{ exitCode?: number | null; kind: string; mcpInstanceId?: string }> = [];
  297. const telemetry = createMcpTelemetryTracker({
  298. idSalt: "device-a",
  299. onEvent: (event) => events.push(event),
  300. randomId: () => "mcp-instance-1",
  301. });
  302. telemetry.registerConnection({
  303. connectionId: "connection-1",
  304. isolation: "session",
  305. serverName: "crashing-server",
  306. });
  307. telemetry.acquireOwner({
  308. connectionId: "connection-1",
  309. ownerId: "lease-1",
  310. sessionId: "session-1",
  311. });
  312. const adapter = createMcpAdapter({
  313. connectionContext: {
  314. mcpConnectionId: "connection-1",
  315. mcpIsolation: "session",
  316. sessionId: "session-1",
  317. },
  318. telemetry,
  319. });
  320. await expect(
  321. adapter.connectServer("crashing-server", {
  322. args: [fixture.serverPath],
  323. command: process.execPath,
  324. env: fixture.env,
  325. timeoutMs: 5_000,
  326. type: "stdio",
  327. }),
  328. ).resolves.toMatchObject({ status: "connected" });
  329. const serverPid = await readPidFile(fixture.serverPidFile);
  330. const childPid = await readPidFile(fixture.childPidFile);
  331. cleanupPids.add(serverPid);
  332. cleanupPids.add(childPid);
  333. await waitFor(() =>
  334. events.some((event) => event.kind === "process_crash") ? true : undefined,
  335. );
  336. expect(events).toEqual([
  337. expect.objectContaining({
  338. kind: "process_start",
  339. mcpInstanceId: "mcp-instance-1",
  340. }),
  341. expect.objectContaining({
  342. exitCode: 23,
  343. kind: "process_crash",
  344. mcpInstanceId: "mcp-instance-1",
  345. }),
  346. ]);
  347. await adapter.close();
  348. forceKillPid(childPid);
  349. cleanupPids.delete(serverPid);
  350. cleanupPids.delete(childPid);
  351. await rm(fixture.root, { force: true, recursive: true });
  352. },
  353. );
  354. });
  355. function createCommandResult(input: {
  356. error?: Error;
  357. status?: number | null;
  358. stdout?: string;
  359. stderr?: string;
  360. }) {
  361. return {
  362. error: input.error,
  363. status: input.status ?? 0,
  364. stderr: input.stderr ?? "",
  365. stdout: input.stdout ?? "",
  366. };
  367. }
  368. async function createMcpProcessFixture(
  369. options: { crashAfterConnectedMs?: number; hangDuringInitialize?: boolean } = {},
  370. ) {
  371. const root = await mkdtemp(join(tmpdir(), "zcode-mcp-process-"));
  372. const childPath = join(root, "child.mjs");
  373. const serverPath = join(root, "server.mjs");
  374. const serverPidFile = join(root, "server.pid");
  375. const childPidFile = join(root, "child.pid");
  376. const mcpServerModule = import.meta.resolve("@modelcontextprotocol/server");
  377. const stdioServerTransportModule = import.meta.resolve("@modelcontextprotocol/server/stdio");
  378. await writeFile(
  379. childPath,
  380. [
  381. "process.on('SIGINT', () => {});",
  382. "process.on('SIGTERM', () => {});",
  383. "setInterval(() => {}, 1000);",
  384. ].join("\n"),
  385. );
  386. await writeFile(
  387. serverPath,
  388. [
  389. "import { spawn } from 'node:child_process';",
  390. "import { writeFileSync } from 'node:fs';",
  391. `import { McpServer } from ${JSON.stringify(mcpServerModule)};`,
  392. `import { StdioServerTransport } from ${JSON.stringify(stdioServerTransportModule)};`,
  393. "writeFileSync(process.env.SERVER_PID_FILE, String(process.pid));",
  394. "const child = spawn(process.execPath, [process.env.CHILD_SCRIPT], { stdio: 'ignore' });",
  395. "writeFileSync(process.env.CHILD_PID_FILE, String(child.pid));",
  396. "process.on('SIGINT', () => {});",
  397. "process.on('SIGTERM', () => {});",
  398. options.hangDuringInitialize
  399. ? "setInterval(() => {}, 1000);"
  400. : [
  401. "const server = new McpServer({ name: 'process-tree-test', version: '1.0.0' });",
  402. "server.registerTool('ping', { description: 'ping', inputSchema: {} }, async () => ({ content: [{ type: 'text', text: 'pong' }] }));",
  403. "await server.connect(new StdioServerTransport());",
  404. ...(options.crashAfterConnectedMs
  405. ? [`setTimeout(() => process.exit(23), ${options.crashAfterConnectedMs});`]
  406. : []),
  407. ].join("\n"),
  408. ].join("\n"),
  409. );
  410. return {
  411. childPidFile,
  412. env: {
  413. CHILD_PID_FILE: childPidFile,
  414. CHILD_SCRIPT: childPath,
  415. SERVER_PID_FILE: serverPidFile,
  416. },
  417. root,
  418. serverPath,
  419. serverPidFile,
  420. };
  421. }
  422. async function readPidFile(path: string): Promise<number> {
  423. await waitFor(async () => {
  424. try {
  425. const value = Number(await readFile(path, "utf8"));
  426. return Number.isInteger(value) && value > 0 ? value : undefined;
  427. } catch {
  428. return undefined;
  429. }
  430. });
  431. return Number(await readFile(path, "utf8"));
  432. }
  433. async function waitForPidExit(pid: number): Promise<void> {
  434. await waitFor(() => (!isPidAlive(pid) ? true : undefined), 5_000);
  435. }
  436. async function waitFor<T>(
  437. callback: () => T | undefined | Promise<T | undefined>,
  438. timeoutMs = 2_000,
  439. ): Promise<T> {
  440. const startedAt = Date.now();
  441. while (Date.now() - startedAt < timeoutMs) {
  442. const value = await callback();
  443. if (value !== undefined) return value;
  444. await new Promise((resolveWait) => setTimeout(resolveWait, 25));
  445. }
  446. throw new Error(`Timed out after ${timeoutMs}ms`);
  447. }
  448. function isPidAlive(pid: number): boolean {
  449. try {
  450. process.kill(pid, 0);
  451. return true;
  452. } catch {
  453. return false;
  454. }
  455. }
  456. function forceKillPid(pid: number): void {
  457. try {
  458. process.kill(pid, "SIGKILL");
  459. } catch {
  460. // best effort cleanup
  461. }
  462. }