process-tree.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import { execFile } from "node:child_process";
  2. import type { ExecFileOptionsWithStringEncoding } from "node:child_process";
  3. const PROCESS_LOOKUP_TIMEOUT_MS = 1_000;
  4. const POSIX_PROCESS_TREE_GRACE_MS = 250;
  5. const POSIX_PROCESS_TREE_FORCE_MS = 750;
  6. const POSIX_PROCESS_TREE_VERIFY_MS = 250;
  7. const POSIX_PROCESS_TREE_POLL_MS = 25;
  8. const WINDOWS_TASKKILL_TIMEOUT_MS = 2_000;
  9. interface CommandResult {
  10. error?: unknown;
  11. status: number | null;
  12. stderr: string;
  13. stdout: string;
  14. }
  15. type KillFn = typeof process.kill;
  16. type ExecFileFn = (
  17. file: string,
  18. args: readonly string[],
  19. options: ExecFileOptionsWithStringEncoding,
  20. ) => Promise<CommandResult>;
  21. export interface McpStdioProcessTreeTerminatorOptions {
  22. execFile?: ExecFileFn;
  23. kill?: KillFn;
  24. now?: () => number;
  25. platform?: NodeJS.Platform;
  26. sleep?: (ms: number) => Promise<void>;
  27. }
  28. export async function terminateMcpStdioProcessTree(
  29. pid: number,
  30. options: McpStdioProcessTreeTerminatorOptions = {},
  31. ): Promise<void> {
  32. const platform = getPlatform(options);
  33. if (platform === "win32") {
  34. await terminateWindowsProcessTree(pid, options);
  35. return;
  36. }
  37. await terminatePosixProcessTree(pid, options);
  38. }
  39. function isProcessAlive(pid: number, options: McpStdioProcessTreeTerminatorOptions): boolean {
  40. const kill = options.kill ?? process.kill;
  41. try {
  42. kill(pid, 0);
  43. return true;
  44. } catch (error) {
  45. return isPermissionDenied(error);
  46. }
  47. }
  48. function isPermissionDenied(error: unknown): boolean {
  49. return (
  50. typeof error === "object" &&
  51. error !== null &&
  52. "code" in error &&
  53. (error as { code?: unknown }).code === "EPERM"
  54. );
  55. }
  56. function getPlatform(options: McpStdioProcessTreeTerminatorOptions): NodeJS.Platform {
  57. return options.platform ?? process.platform;
  58. }
  59. function defaultSleep(ms: number): Promise<void> {
  60. return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
  61. }
  62. function parsePidList(stdout: string): number[] {
  63. return stdout
  64. .split(/\s+/)
  65. .map((value) => Number(value))
  66. .filter((pid) => Number.isInteger(pid) && pid > 0);
  67. }
  68. function getPosixProcessListArgs(platform: NodeJS.Platform): string[] {
  69. return platform === "darwin" ? ["-axo", "pid=,ppid="] : ["-eo", "pid=,ppid="];
  70. }
  71. function parseChildPidsFromProcessList(stdout: string, parentPid: number): number[] {
  72. const children: number[] = [];
  73. for (const line of stdout.split(/\r?\n/)) {
  74. const [pidText, ppidText] = line.trim().split(/\s+/);
  75. const pid = Number(pidText);
  76. const ppid = Number(ppidText);
  77. if (Number.isInteger(pid) && pid > 0 && ppid === parentPid) {
  78. children.push(pid);
  79. }
  80. }
  81. return children;
  82. }
  83. async function collectChildPids(
  84. pid: number,
  85. options: McpStdioProcessTreeTerminatorOptions,
  86. ): Promise<number[]> {
  87. const pgrepResult = await runCommand(
  88. "pgrep",
  89. ["-P", String(pid)],
  90. {
  91. encoding: "utf8",
  92. timeout: PROCESS_LOOKUP_TIMEOUT_MS,
  93. },
  94. options,
  95. );
  96. if (!pgrepResult.error && pgrepResult.status === 0 && pgrepResult.stdout) {
  97. return parsePidList(String(pgrepResult.stdout));
  98. }
  99. const psResult = await runCommand(
  100. "ps",
  101. getPosixProcessListArgs(getPlatform(options)),
  102. {
  103. encoding: "utf8",
  104. timeout: PROCESS_LOOKUP_TIMEOUT_MS,
  105. },
  106. options,
  107. );
  108. if (psResult.error || psResult.status !== 0 || !psResult.stdout) return [];
  109. return parseChildPidsFromProcessList(String(psResult.stdout), pid);
  110. }
  111. async function collectDescendantPids(
  112. pid: number,
  113. options: McpStdioProcessTreeTerminatorOptions,
  114. seen = new Set<number>(),
  115. ): Promise<number[]> {
  116. if (seen.has(pid)) return [];
  117. seen.add(pid);
  118. const descendants: number[] = [];
  119. for (const childPid of await collectChildPids(pid, options)) {
  120. descendants.push(childPid, ...(await collectDescendantPids(childPid, options, seen)));
  121. }
  122. return descendants;
  123. }
  124. function uniquePids(pids: number[]): number[] {
  125. return [...new Set(pids.filter((pid) => pid > 0))];
  126. }
  127. function killPid(
  128. pid: number,
  129. signal: NodeJS.Signals,
  130. options: McpStdioProcessTreeTerminatorOptions,
  131. ): void {
  132. const kill = options.kill ?? process.kill;
  133. try {
  134. kill(pid, signal);
  135. } catch {
  136. // 进程可能已经被 SDK close 或前一轮信号回收;关闭路径要求幂等。
  137. }
  138. }
  139. function killProcessGroup(
  140. pid: number,
  141. signal: NodeJS.Signals,
  142. options: McpStdioProcessTreeTerminatorOptions,
  143. ): void {
  144. const kill = options.kill ?? process.kill;
  145. try {
  146. kill(-pid, signal);
  147. } catch {
  148. // SDK 当前没有 detached spawn,进程组可能不存在;保留兼容未来 launcher 的能力。
  149. }
  150. }
  151. async function terminateWindowsProcessTree(
  152. pid: number,
  153. options: McpStdioProcessTreeTerminatorOptions,
  154. ): Promise<void> {
  155. if (!isProcessAlive(pid, options)) return;
  156. const result = await runCommand(
  157. "taskkill",
  158. ["/PID", String(pid), "/T", "/F"],
  159. {
  160. encoding: "utf8",
  161. timeout: WINDOWS_TASKKILL_TIMEOUT_MS,
  162. windowsHide: true,
  163. },
  164. options,
  165. );
  166. if (didTerminationFail(result) && isProcessAlive(pid, options)) {
  167. throw new Error(
  168. `taskkill failed for MCP stdio process tree pid=${pid} status=${result.status ?? "unknown"}`,
  169. );
  170. }
  171. }
  172. async function terminatePosixProcessTree(
  173. pid: number,
  174. options: McpStdioProcessTreeTerminatorOptions,
  175. ): Promise<void> {
  176. if (!isProcessAlive(pid, options)) return;
  177. const descendants = uniquePids(await collectDescendantPids(pid, options)).reverse();
  178. const treePids = uniquePids([...descendants, pid]);
  179. killProcessGroup(pid, "SIGINT", options);
  180. for (const treePid of treePids) killPid(treePid, "SIGINT", options);
  181. await waitUntilAllExited(treePids, POSIX_PROCESS_TREE_GRACE_MS, options);
  182. if (!treePids.some((treePid) => isProcessAlive(treePid, options))) return;
  183. killProcessGroup(pid, "SIGTERM", options);
  184. for (const treePid of treePids) killPid(treePid, "SIGTERM", options);
  185. await waitUntilAllExited(treePids, POSIX_PROCESS_TREE_FORCE_MS, options);
  186. if (!treePids.some((treePid) => isProcessAlive(treePid, options))) return;
  187. const latestDescendants = uniquePids(await collectDescendantPids(pid, options)).reverse();
  188. const finalPids = uniquePids([...latestDescendants, ...treePids]);
  189. for (const treePid of finalPids) {
  190. if (isProcessAlive(treePid, options)) killPid(treePid, "SIGKILL", options);
  191. }
  192. killProcessGroup(pid, "SIGKILL", options);
  193. await waitUntilAllExited(finalPids, POSIX_PROCESS_TREE_VERIFY_MS, options);
  194. const remainingPids = finalPids.filter((treePid) => isProcessAlive(treePid, options));
  195. if (remainingPids.length > 0) {
  196. throw new Error(
  197. `SIGKILL failed for MCP stdio process tree pid=${pid} remaining=${remainingPids.join(",")}`,
  198. );
  199. }
  200. }
  201. async function waitUntilAllExited(
  202. pids: number[],
  203. timeoutMs: number,
  204. options: McpStdioProcessTreeTerminatorOptions,
  205. ): Promise<void> {
  206. const sleep = options.sleep ?? defaultSleep;
  207. const now = options.now ?? Date.now;
  208. const startedAt = now();
  209. while (now() - startedAt < timeoutMs) {
  210. if (!pids.some((pid) => isProcessAlive(pid, options))) return;
  211. await sleep(POSIX_PROCESS_TREE_POLL_MS);
  212. }
  213. }
  214. function runCommand(
  215. file: string,
  216. args: readonly string[],
  217. options: ExecFileOptionsWithStringEncoding,
  218. terminatorOptions: McpStdioProcessTreeTerminatorOptions,
  219. ): Promise<CommandResult> {
  220. const execFileFn = terminatorOptions.execFile ?? defaultExecFile;
  221. return execFileFn(file, args, options);
  222. }
  223. function defaultExecFile(
  224. file: string,
  225. args: readonly string[],
  226. options: ExecFileOptionsWithStringEncoding,
  227. ): Promise<CommandResult> {
  228. return new Promise((resolveCommand) => {
  229. execFile(file, [...args], options, (error, stdout, stderr) => {
  230. resolveCommand({
  231. error,
  232. status: getExitStatus(error),
  233. stderr,
  234. stdout,
  235. });
  236. });
  237. });
  238. }
  239. function getExitStatus(error: unknown): number | null {
  240. if (!error || typeof error !== "object" || !("code" in error)) return 0;
  241. const code = (error as { code?: unknown }).code;
  242. return typeof code === "number" ? code : null;
  243. }
  244. function didTerminationFail(result: CommandResult): boolean {
  245. return Boolean(result.error) || (result.status !== null && result.status !== 0);
  246. }