mcp-node-fallback.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import { execFile } from "node:child_process";
  2. import { existsSync } from "node:fs";
  3. import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join } from "node:path";
  6. import { promisify } from "node:util";
  7. import { afterEach, describe, expect, it, vi } from "vitest";
  8. import type { Logger } from "@zcode/contracts";
  9. import { createMcpAdapter } from "../src/mcp/index.js";
  10. import {
  11. applyMcpNodeFallbackEnv,
  12. createMcpNodeFallbackProvider,
  13. ensureNodeFallbackShimDir,
  14. NODE_FALLBACK_EXEC_PATH_ENV_KEY,
  15. NODE_FALLBACK_NPM_ROOT_ENV_KEY,
  16. renderNodeFallbackShims,
  17. resolveBundledNpmRoot,
  18. } from "../src/mcp/node-fallback.js";
  19. const execFileAsync = promisify(execFile);
  20. const isPosix = process.platform !== "win32";
  21. // 测试机没有 Electron:用当前 Node 冒充“Electron 可执行文件”。shim 只关心它能执行 JS,
  22. // ELECTRON_RUN_AS_NODE 对真实 Node 无副作用。
  23. const fakeElectronExecPath = process.execPath;
  24. // 模拟“用户机器没有装 Node”:PATH 只有一个不存在的目录。shim 只依赖绝对路径
  25. // (/bin/sh、/usr/bin/env),所以 Linux CI 上即便 /usr/bin/node 存在,用例也不会误绿。
  26. const POSIX_PATH_WITHOUT_NODE = join(tmpdir(), "zcode-node-fallback-empty-path");
  27. const runningNodeNpmRoot = resolveRunningNodeNpmRoot();
  28. const tempRoots: string[] = [];
  29. async function makeTempRoot(prefix: string): Promise<string> {
  30. const root = await mkdtemp(join(tmpdir(), prefix));
  31. tempRoots.push(root);
  32. return root;
  33. }
  34. afterEach(async () => {
  35. await Promise.all(tempRoots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  36. });
  37. function createLoggerSpy() {
  38. const info = vi.fn();
  39. const warn = vi.fn();
  40. const logger = {
  41. child: () => logger,
  42. debug: vi.fn(),
  43. error: vi.fn(),
  44. info,
  45. warn,
  46. } as unknown as Logger;
  47. return { info, logger, warn };
  48. }
  49. async function writeFakeNpmPackage(root: string): Promise<string> {
  50. const npmRoot = join(root, "npm");
  51. await mkdir(join(npmRoot, "bin"), { recursive: true });
  52. await writeFile(join(npmRoot, "bin", "npm-cli.js"), "console.log('fake npm');\n");
  53. await writeFile(join(npmRoot, "bin", "npx-cli.js"), "console.log('fake npx');\n");
  54. return npmRoot;
  55. }
  56. describe("renderNodeFallbackShims", () => {
  57. it("renders static POSIX shims that read the exec path and npm root from env", () => {
  58. const shims = renderNodeFallbackShims("darwin");
  59. expect(shims.map((shim) => shim.name)).toEqual(["node", "npm", "npx"]);
  60. for (const shim of shims) {
  61. expect(shim.executable).toBe(true);
  62. expect(shim.content.startsWith("#!/bin/sh\n")).toBe(true);
  63. expect(shim.content).toContain(NODE_FALLBACK_EXEC_PATH_ENV_KEY);
  64. expect(shim.content).toContain("ELECTRON_RUN_AS_NODE=1");
  65. expect(shim.content).toContain("exit 127");
  66. // 内容不能带机器路径,否则 AppImage 每次挂载点不同会生成新目录。
  67. expect(shim.content).not.toContain(fakeElectronExecPath);
  68. }
  69. const npx = shims.find((shim) => shim.name === "npx")!;
  70. expect(npx.content).toContain(NODE_FALLBACK_NPM_ROOT_ENV_KEY);
  71. expect(npx.content).toContain("/bin/npx-cli.js");
  72. expect(npx.content).toContain("npm_config_update_notifier");
  73. const node = shims.find((shim) => shim.name === "node")!;
  74. expect(node.content).not.toContain(NODE_FALLBACK_NPM_ROOT_ENV_KEY);
  75. });
  76. it("renders Windows batch shims with CRLF line endings", () => {
  77. const shims = renderNodeFallbackShims("win32");
  78. expect(shims.map((shim) => shim.name)).toEqual(["node.cmd", "npm.cmd", "npx.cmd"]);
  79. for (const shim of shims) {
  80. expect(shim.executable).toBe(false);
  81. expect(shim.content.startsWith("@echo off\r\n")).toBe(true);
  82. expect(shim.content.replaceAll("\r\n", "")).not.toContain("\n");
  83. expect(shim.content).toContain(`"%${NODE_FALLBACK_EXEC_PATH_ENV_KEY}%"`);
  84. expect(shim.content).toContain('set "ELECTRON_RUN_AS_NODE=1"');
  85. expect(shim.content).toContain("exit /b 127");
  86. }
  87. const npm = shims.find((shim) => shim.name === "npm.cmd")!;
  88. expect(npm.content).toContain(`"%${NODE_FALLBACK_NPM_ROOT_ENV_KEY}%\\bin\\npm-cli.js" %*`);
  89. });
  90. });
  91. describe("ensureNodeFallbackShimDir", () => {
  92. it("writes the shims once and leaves identical files untouched", async () => {
  93. const binDir = join(await makeTempRoot("zcode-node-fallback-"), "bin");
  94. await ensureNodeFallbackShimDir(binDir, process.platform);
  95. const shims = renderNodeFallbackShims(process.platform);
  96. const firstStats = await Promise.all(shims.map((shim) => stat(join(binDir, shim.name))));
  97. await ensureNodeFallbackShimDir(binDir, process.platform);
  98. const secondStats = await Promise.all(shims.map((shim) => stat(join(binDir, shim.name))));
  99. for (const [index, shim] of shims.entries()) {
  100. expect(await readFile(join(binDir, shim.name), "utf8")).toBe(shim.content);
  101. expect(secondStats[index]!.ino).toBe(firstStats[index]!.ino);
  102. expect(secondStats[index]!.mtimeMs).toBe(firstStats[index]!.mtimeMs);
  103. }
  104. });
  105. it("repairs changed content and lost exec bits", async () => {
  106. const binDir = join(await makeTempRoot("zcode-node-fallback-"), "bin");
  107. await ensureNodeFallbackShimDir(binDir, process.platform);
  108. const [firstShim] = renderNodeFallbackShims(process.platform);
  109. const shimPath = join(binDir, firstShim!.name);
  110. await writeFile(shimPath, "corrupted");
  111. if (isPosix) await chmod(shimPath, 0o644);
  112. await ensureNodeFallbackShimDir(binDir, process.platform);
  113. expect(await readFile(shimPath, "utf8")).toBe(firstShim!.content);
  114. if (isPosix) expect((await stat(shimPath)).mode & 0o111).toBe(0o111);
  115. });
  116. it("is safe when several agents prepare the same directory at once", async () => {
  117. const binDir = join(await makeTempRoot("zcode-node-fallback-"), "bin");
  118. await Promise.all(
  119. Array.from({ length: 8 }, () => ensureNodeFallbackShimDir(binDir, process.platform)),
  120. );
  121. for (const shim of renderNodeFallbackShims(process.platform)) {
  122. expect(await readFile(join(binDir, shim.name), "utf8")).toBe(shim.content);
  123. }
  124. });
  125. });
  126. describe("resolveBundledNpmRoot", () => {
  127. it("returns the first candidate that has both npm entry files", async () => {
  128. const root = await makeTempRoot("zcode-node-fallback-npm-");
  129. const incomplete = join(root, "incomplete");
  130. await mkdir(join(incomplete, "bin"), { recursive: true });
  131. await writeFile(join(incomplete, "bin", "npm-cli.js"), "");
  132. const complete = await writeFakeNpmPackage(join(root, "complete"));
  133. const later = await writeFakeNpmPackage(join(root, "later"));
  134. await expect(
  135. resolveBundledNpmRoot([join(root, "missing"), incomplete, complete, later]),
  136. ).resolves.toBe(complete);
  137. await expect(resolveBundledNpmRoot([join(root, "missing"), incomplete])).resolves.toBe(
  138. undefined,
  139. );
  140. });
  141. });
  142. describe("applyMcpNodeFallbackEnv", () => {
  143. const fallback = {
  144. binDir: "/storage/node-fallback/v1",
  145. env: {
  146. [NODE_FALLBACK_EXEC_PATH_ENV_KEY]: "/Applications/ZCode.app/Helper",
  147. [NODE_FALLBACK_NPM_ROOT_ENV_KEY]: "/Applications/ZCode.app/npm",
  148. },
  149. };
  150. it("appends the shim directory last so the user's commands win", () => {
  151. expect(applyMcpNodeFallbackEnv({ PATH: "/usr/bin:/bin" }, fallback, "darwin")).toEqual({
  152. PATH: "/usr/bin:/bin:/storage/node-fallback/v1",
  153. ...fallback.env,
  154. });
  155. });
  156. it("does not add the shim directory twice", () => {
  157. const env = { PATH: "/usr/bin:/storage/node-fallback/v1" };
  158. expect(applyMcpNodeFallbackEnv(env, fallback, "linux").PATH).toBe(env.PATH);
  159. });
  160. describe("on Windows", () => {
  161. const winFallback = { ...fallback, binDir: "C:\\Users\\dev\\.zcode\\node-fallback\\v1" };
  162. const hostPath = "C:\\Windows\\System32";
  163. // 复现真实链路:MCP SDK StdioClientTransport 以 `{ PATH: process.env.PATH, ...env }` spawn;
  164. // cross-spawn(path-key)按插入顺序取最后一个 PATH 键解析命令;Node 在 win32 上把 env 键排序后
  165. // 同名(大小写不敏感)只保留第一个传给子进程。两者都必须看到 shim 目录。
  166. function win32PathsSeenBySpawn(env: Record<string, string>) {
  167. const spawnEnv: Record<string, string> = { PATH: hostPath, ...env };
  168. const pathKeys = Object.keys(spawnEnv).filter((key) => key.toUpperCase() === "PATH");
  169. return {
  170. commandLookup: spawnEnv[pathKeys.at(-1)!],
  171. childProcess: spawnEnv[[...pathKeys].sort()[0]!],
  172. };
  173. }
  174. it("writes one PATH key so the SDK's default PATH cannot shadow the shim directory", () => {
  175. const env = applyMcpNodeFallbackEnv({ Path: hostPath }, winFallback, "win32");
  176. expect(env).toEqual({ PATH: `${hostPath};${winFallback.binDir}`, ...fallback.env });
  177. expect(win32PathsSeenBySpawn(env)).toEqual({
  178. childProcess: `${hostPath};${winFallback.binDir}`,
  179. commandLookup: `${hostPath};${winFallback.binDir}`,
  180. });
  181. });
  182. it("builds on the server's PATH when the host Path and a server PATH both exist", () => {
  183. const env = applyMcpNodeFallbackEnv(
  184. { Path: hostPath, PATH: "C:\\plugin\\bin" },
  185. winFallback,
  186. "win32",
  187. );
  188. expect(env).toEqual({ PATH: `C:\\plugin\\bin;${winFallback.binDir}`, ...fallback.env });
  189. expect(win32PathsSeenBySpawn(env).childProcess).toBe(`C:\\plugin\\bin;${winFallback.binDir}`);
  190. });
  191. it("compares entries case-insensitively", () => {
  192. expect(
  193. applyMcpNodeFallbackEnv(
  194. { Path: "c:\\users\\dev\\.zcode\\node-fallback\\v1\\" },
  195. winFallback,
  196. "win32",
  197. ),
  198. ).toEqual({ PATH: "c:\\users\\dev\\.zcode\\node-fallback\\v1\\", ...fallback.env });
  199. });
  200. });
  201. it("uses the shim directory as PATH when the env has none", () => {
  202. expect(applyMcpNodeFallbackEnv({}, fallback, "linux").PATH).toBe(fallback.binDir);
  203. });
  204. it("returns the env unchanged without a fallback", () => {
  205. const env = { PATH: "/usr/bin" };
  206. expect(applyMcpNodeFallbackEnv(env, undefined, "linux")).toBe(env);
  207. });
  208. });
  209. describe("node fallback preparation inside the connection budget", () => {
  210. const hungFallback = { resolve: () => new Promise<never>(() => undefined) };
  211. const stdioConfig = { args: ["server.js"], command: "node", type: "stdio" as const };
  212. it("fails the connection when preparation outlasts the connection timeout", async () => {
  213. const adapter = createMcpAdapter({ nodeFallback: hungFallback });
  214. try {
  215. await expect(
  216. adapter.connectServer("hung", { ...stdioConfig, timeoutMs: 50 }),
  217. ).resolves.toMatchObject({
  218. error: expect.stringContaining("node fallback preparation timed out"),
  219. status: "failed",
  220. });
  221. } finally {
  222. await adapter.close();
  223. }
  224. });
  225. it("fails the connection when the caller cancels during preparation", async () => {
  226. const adapter = createMcpAdapter({ nodeFallback: hungFallback });
  227. const controller = new AbortController();
  228. try {
  229. const connecting = adapter.connectServer(
  230. "hung",
  231. { ...stdioConfig, timeoutMs: 60_000 },
  232. { signal: controller.signal },
  233. );
  234. controller.abort(new Error("cancelled by caller"));
  235. await connecting;
  236. await vi.waitFor(async () => {
  237. expect((await adapter.status()).hung).toMatchObject({ status: "failed" });
  238. });
  239. } finally {
  240. await adapter.close();
  241. }
  242. });
  243. });
  244. describe("createMcpNodeFallbackProvider", () => {
  245. it("prepares the shim directory once and reports the bundled npm", async () => {
  246. const root = await makeTempRoot("zcode-node-fallback-provider-");
  247. const npmRoot = await writeFakeNpmPackage(root);
  248. const { info, logger, warn } = createLoggerSpy();
  249. const provider = createMcpNodeFallbackProvider({
  250. execPath: fakeElectronExecPath,
  251. logger,
  252. npmRootCandidates: [join(root, "missing"), npmRoot],
  253. storageRoot: join(root, "storage"),
  254. });
  255. const [first, second] = await Promise.all([provider.resolve(), provider.resolve()]);
  256. expect(second).toBe(first);
  257. expect(first).toEqual({
  258. binDir: join(root, "storage", "node-fallback", "v1"),
  259. env: {
  260. [NODE_FALLBACK_EXEC_PATH_ENV_KEY]: fakeElectronExecPath,
  261. [NODE_FALLBACK_NPM_ROOT_ENV_KEY]: npmRoot,
  262. },
  263. });
  264. expect(existsSync(join(first!.binDir, isPosix ? "node" : "node.cmd"))).toBe(true);
  265. expect(info).toHaveBeenCalledTimes(1);
  266. expect(info).toHaveBeenCalledWith(
  267. "MCP node fallback ready",
  268. expect.objectContaining({ event: "mcp.node_fallback.ready", hasNpm: true }),
  269. );
  270. expect(warn).not.toHaveBeenCalled();
  271. });
  272. it("omits the npm root when no bundled npm is found", async () => {
  273. const root = await makeTempRoot("zcode-node-fallback-provider-");
  274. const provider = createMcpNodeFallbackProvider({
  275. execPath: fakeElectronExecPath,
  276. npmRootCandidates: [join(root, "missing")],
  277. storageRoot: root,
  278. });
  279. await expect(provider.resolve()).resolves.toEqual({
  280. binDir: join(root, "node-fallback", "v1"),
  281. env: { [NODE_FALLBACK_EXEC_PATH_ENV_KEY]: fakeElectronExecPath },
  282. });
  283. });
  284. it("logs one warning and disables the fallback when the directory cannot be written", async () => {
  285. const root = await makeTempRoot("zcode-node-fallback-provider-");
  286. // storageRoot 是普通文件:mkdir 必然失败。
  287. const blockedStorageRoot = join(root, "file");
  288. await writeFile(blockedStorageRoot, "");
  289. const { logger, warn } = createLoggerSpy();
  290. const provider = createMcpNodeFallbackProvider({
  291. execPath: fakeElectronExecPath,
  292. logger,
  293. npmRootCandidates: [],
  294. storageRoot: blockedStorageRoot,
  295. });
  296. await expect(provider.resolve()).resolves.toBeUndefined();
  297. await expect(provider.resolve()).resolves.toBeUndefined();
  298. expect(warn).toHaveBeenCalledTimes(1);
  299. expect(warn).toHaveBeenCalledWith(
  300. "MCP node fallback unavailable",
  301. expect.objectContaining({ event: "mcp.node_fallback.unavailable" }),
  302. );
  303. });
  304. });
  305. describe.runIf(isPosix)("node fallback shims (real processes)", () => {
  306. async function prepareShims(npmRoot?: string) {
  307. const root = await makeTempRoot("zcode-node-fallback-run-");
  308. const fallback = await createMcpNodeFallbackProvider({
  309. execPath: fakeElectronExecPath,
  310. npmRootCandidates: npmRoot ? [npmRoot] : [],
  311. storageRoot: root,
  312. }).resolve();
  313. const env = applyMcpNodeFallbackEnv({ HOME: root, PATH: POSIX_PATH_WITHOUT_NODE }, fallback);
  314. return { env, root };
  315. }
  316. it("runs a node script through the shim when PATH has no node", async () => {
  317. const { env } = await prepareShims();
  318. const { stdout } = await execFileAsync(
  319. "node",
  320. ["-e", "process.stdout.write(process.env.ELECTRON_RUN_AS_NODE + ':' + process.argv[1])", "x"],
  321. { env },
  322. );
  323. expect(stdout).toBe("1:x");
  324. });
  325. it("resolves #!/usr/bin/env node scripts through the shim", async () => {
  326. const { env, root } = await prepareShims();
  327. const scriptPath = join(root, "tool.js");
  328. await writeFile(scriptPath, "#!/usr/bin/env node\nprocess.stdout.write('shebang-ok');\n");
  329. await chmod(scriptPath, 0o755);
  330. const { stdout } = await execFileAsync(scriptPath, [], { env });
  331. expect(stdout).toBe("shebang-ok");
  332. });
  333. it("propagates the script exit code", async () => {
  334. const { env } = await prepareShims();
  335. await expect(execFileAsync("node", ["-e", "process.exit(7)"], { env })).rejects.toMatchObject({
  336. code: 7,
  337. });
  338. });
  339. it("exits 127 with a clear message when the exec path variable is missing", async () => {
  340. const { env } = await prepareShims();
  341. delete env[NODE_FALLBACK_EXEC_PATH_ENV_KEY];
  342. await expect(execFileAsync("node", ["-v"], { env })).rejects.toMatchObject({
  343. code: 127,
  344. stderr: expect.stringContaining(NODE_FALLBACK_EXEC_PATH_ENV_KEY),
  345. });
  346. });
  347. it("fails npx with a clear message when no bundled npm exists", async () => {
  348. const { env } = await prepareShims();
  349. await expect(execFileAsync("npx", ["--version"], { env })).rejects.toMatchObject({
  350. code: 127,
  351. stderr: expect.stringContaining(NODE_FALLBACK_NPM_ROOT_ENV_KEY),
  352. });
  353. });
  354. it.runIf(runningNodeNpmRoot !== undefined)(
  355. "runs the real npm and npx packages through the shims",
  356. async () => {
  357. const { env } = await prepareShims(runningNodeNpmRoot);
  358. const npm = await execFileAsync("npm", ["--version"], { env });
  359. const npx = await execFileAsync("npx", ["--version"], { env });
  360. expect(npm.stdout.trim()).toMatch(/^\d+\.\d+\.\d+/);
  361. expect(npx.stdout.trim()).toBe(npm.stdout.trim());
  362. },
  363. );
  364. it("connects a stdio MCP server with command node through the fallback", async () => {
  365. const root = await makeTempRoot("zcode-node-fallback-mcp-");
  366. const serverPath = join(root, "server.mjs");
  367. const mcpServerModule = import.meta.resolve("@modelcontextprotocol/server");
  368. const stdioServerTransportModule = import.meta.resolve("@modelcontextprotocol/server/stdio");
  369. await writeFile(
  370. serverPath,
  371. [
  372. `import { McpServer } from ${JSON.stringify(mcpServerModule)};`,
  373. `import { StdioServerTransport } from ${JSON.stringify(stdioServerTransportModule)};`,
  374. "const server = new McpServer({ name: 'node-fallback-test', version: '1.0.0' });",
  375. "server.registerTool('ping', { description: 'ping', inputSchema: {} }, async () => ({ content: [{ type: 'text', text: 'pong' }] }));",
  376. "await server.connect(new StdioServerTransport());",
  377. ].join("\n"),
  378. );
  379. const adapter = createMcpAdapter({
  380. env: { HOME: root, PATH: POSIX_PATH_WITHOUT_NODE },
  381. nodeFallback: createMcpNodeFallbackProvider({
  382. execPath: fakeElectronExecPath,
  383. npmRootCandidates: [],
  384. storageRoot: root,
  385. }),
  386. });
  387. try {
  388. await expect(
  389. adapter.connectServer("fallback", {
  390. args: [serverPath],
  391. command: "node",
  392. timeoutMs: 10_000,
  393. type: "stdio",
  394. }),
  395. ).resolves.toMatchObject({ status: "connected" });
  396. } finally {
  397. await adapter.close();
  398. }
  399. });
  400. });
  401. /** 当前 Node 安装自带的 npm(nvm / mise / 官方安装包布局);没有时跳过真实 npm 用例。 */
  402. function resolveRunningNodeNpmRoot(): string | undefined {
  403. const nodeDir = dirname(process.execPath);
  404. const candidates = [
  405. join(nodeDir, "..", "lib", "node_modules", "npm"),
  406. join(nodeDir, "node_modules", "npm"),
  407. ];
  408. return candidates.find(
  409. (candidate) =>
  410. existsSync(join(candidate, "bin", "npm-cli.js")) &&
  411. existsSync(join(candidate, "bin", "npx-cli.js")),
  412. );
  413. }