preinstalled-tool-environment.test.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { delimiter, join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createMcpAdapter } from "@zcode/adapters/mcp";
  6. import { NodeExecutionAdapter } from "@zcode/adapters/exec";
  7. import { createConfiguredHookRunner } from "@zcode/core";
  8. import { HookEventName, createSessionId, createTraceId, createTurnId } from "@zcode/contracts";
  9. const TIMEOUT_MS = 10000;
  10. describe("preinstalled entries in long-lived Agent child environments", () => {
  11. it.skipIf(process.platform === "win32")(
  12. "MCP stdio and hooks see entry publication, removal and restoration without reconnecting",
  13. async () => {
  14. const root = await mkdtemp(join(tmpdir(), "zcode-preinstalled-children-"));
  15. const home = join(root, "中文 空格");
  16. const bin = join(home, "bin");
  17. const system = join(home, "system-bin");
  18. await mkdir(bin, { recursive: true });
  19. await mkdir(system);
  20. await writeFile(join(system, "qpdf"), "#!/bin/sh\nprintf 'system\\n'\n", { mode: 0o755 });
  21. const env = {
  22. ...process.env,
  23. HOME: home,
  24. PATH: [bin, system, process.env.PATH].join(delimiter),
  25. ZCODE_PREINSTALLED_TOOLS_AVAILABLE: "1",
  26. };
  27. const mcp = createMcpAdapter({ env });
  28. const execution = new NodeExecutionAdapter({
  29. processEnv: env,
  30. outputRootDir: join(root, "exec"),
  31. });
  32. const server = join(root, "server.mjs");
  33. const hook = join(root, "hook.mjs");
  34. await writeFile(
  35. server,
  36. [
  37. `import { McpServer } from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/server"))};`,
  38. `import { serveStdio } from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/server/stdio"))};`,
  39. "import { execFile } from 'node:child_process'; import { promisify } from 'node:util';",
  40. "serveStdio(() => { const server = new McpServer({name:'preinstalled-child-test',version:'1.0.0'});",
  41. "server.registerTool('resolve',{description:'resolve current entry',inputSchema:{}},async()=>{ const result=await promisify(execFile)('qpdf',[]); return {content:[{type:'text',text:JSON.stringify({pid:process.pid,value:result.stdout.trim()})}]}; }); return server; });",
  42. ].join("\n"),
  43. );
  44. await writeFile(
  45. hook,
  46. [
  47. "import { execFile } from 'node:child_process'; import { promisify } from 'node:util';",
  48. "const result=await promisify(execFile)('qpdf',[]);",
  49. "console.log(JSON.stringify({hookSpecificOutput:{hookEventName:'UserPromptSubmit',additionalContext:result.stdout.trim()}}));",
  50. ].join("\n"),
  51. );
  52. const runner = createConfiguredHookRunner({
  53. config: {
  54. enabled: true,
  55. timeoutMs: TIMEOUT_MS,
  56. maxOutputBytes: 4096,
  57. events: {
  58. UserPromptSubmit: [
  59. { hooks: [{ type: "process", command: process.execPath, args: [hook] }] },
  60. ],
  61. },
  62. },
  63. executionPort: execution,
  64. getWorkingDirectory: () => home,
  65. });
  66. try {
  67. await mcp.connectServer("inherited", {
  68. type: "stdio",
  69. command: process.execPath,
  70. args: [server],
  71. timeoutMs: TIMEOUT_MS,
  72. });
  73. let pid: number | undefined;
  74. const observe = async (expected: string) => {
  75. const output = await mcp.callTool({ serverName: "inherited", toolName: "resolve" });
  76. const text = output.content.find((item) => item.type === "text");
  77. if (!text || text.type !== "text") throw new Error("Missing MCP text result");
  78. const observed = JSON.parse(text.text);
  79. expect(observed.value).toBe(expected);
  80. if (pid) expect(observed.pid).toBe(pid);
  81. pid = observed.pid;
  82. const hookResult = await runner!.run({
  83. cwd: home,
  84. hookEventName: HookEventName.UserPromptSubmit,
  85. mode: "build",
  86. prompt: "read entry",
  87. sessionId: createSessionId("preinstalled-children"),
  88. timestamp: new Date().toISOString(),
  89. traceId: createTraceId(),
  90. turnId: createTurnId(`turn-${expected}`),
  91. });
  92. expect(hookResult.additionalContexts).toContain(expected);
  93. };
  94. await observe("system");
  95. const entry = join(bin, "qpdf");
  96. await writeFile(entry, "#!/bin/sh\nprintf 'managed\\n'\n", { mode: 0o755 });
  97. await observe("managed");
  98. await rm(entry);
  99. await observe("system");
  100. await writeFile(entry, "#!/bin/sh\nprintf 'managed\\n'\n", { mode: 0o755 });
  101. await observe("managed");
  102. await mcp.connectServer("explicit-path", {
  103. type: "stdio",
  104. command: process.execPath,
  105. args: [server],
  106. env: { PATH: [system, process.env.PATH].join(delimiter) },
  107. timeoutMs: TIMEOUT_MS,
  108. });
  109. const overridden = await mcp.callTool({ serverName: "explicit-path", toolName: "resolve" });
  110. expect(JSON.stringify(overridden.content)).toContain("system");
  111. } finally {
  112. await mcp.close();
  113. await execution.close();
  114. await rm(root, { recursive: true, force: true });
  115. }
  116. },
  117. 60000,
  118. );
  119. });