mcp-config-source-lifecycle.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import { EventEmitter } from "node:events";
  2. import { expect, it, vi } from "vitest";
  3. import { createDynamicMcpConfigSource } from "../src/mcp/config-source.js";
  4. const state = vi.hoisted(() => ({
  5. config: "{}",
  6. entered: Promise.withResolvers<void>(),
  7. release: Promise.withResolvers<void>(),
  8. blocked: false,
  9. watchers: [] as EventEmitter[],
  10. files: new Map<string, string>(),
  11. reading: "",
  12. }));
  13. vi.mock("node:fs/promises", async (original) => ({
  14. ...(await original<typeof import("node:fs/promises")>()),
  15. stat: async () => ({ dev: 1, ino: 1, isDirectory: () => true }),
  16. // 虚拟配置文件系统也负责发布前的数据目录准备,不能落到真实 /workspace。
  17. mkdir: vi.fn(async () => undefined),
  18. readFile: async (path: string) => {
  19. if (state.files.has(path)) {
  20. const captured = state.files.get(path)!;
  21. if (state.reading === path) {
  22. state.entered.resolve();
  23. await state.release.promise;
  24. }
  25. return captured;
  26. }
  27. if (path === "/workspace/config.json") {
  28. if (state.blocked) {
  29. state.entered.resolve();
  30. await state.release.promise;
  31. }
  32. return state.config;
  33. }
  34. if (path === "/new-plugin/.zcode-plugin/plugin.json")
  35. return JSON.stringify({ name: "test", mcpServers: { service: { command: "node" } } });
  36. throw Object.assign(new Error("missing"), { code: "ENOENT" });
  37. },
  38. }));
  39. vi.mock("chokidar", () => ({
  40. watch: () => {
  41. const watcher = Object.assign(new EventEmitter(), { close: vi.fn(async () => {}) });
  42. state.watchers.push(watcher);
  43. queueMicrotask(() => watcher.emit("ready"));
  44. return watcher;
  45. },
  46. }));
  47. it("does not create watchers or publish a delayed configuration after close", async () => {
  48. const source = await createDynamicMcpConfigSource({
  49. configPaths: ["/workspace/config.json"],
  50. userConfigPath: "/workspace/config.json",
  51. pluginStorageRoot: "/workspace/plugins",
  52. pluginRoots: [],
  53. workingDirectory: "/workspace",
  54. });
  55. const published = vi.fn();
  56. source.subscribe(published);
  57. const watchers = state.watchers.length;
  58. state.blocked = true;
  59. state.config = JSON.stringify({ plugins: { dirs: ["/new-plugin"] } });
  60. state.watchers[0]!.emit("all", "change", "/workspace/config.json");
  61. await state.entered.promise;
  62. source.close();
  63. state.release.resolve();
  64. // 文件端口返回已解决的 Promise;一个事件循环边界排空本次读取链,无真实磁盘时序假设。
  65. await new Promise<void>((resolve) => setImmediate(resolve));
  66. expect(state.watchers).toHaveLength(watchers);
  67. expect(published).not.toHaveBeenCalled();
  68. expect(source.getSnapshot().servers).toEqual({});
  69. });
  70. it("rereads newly declared files under an existing watched directory after coverage changes", async () => {
  71. state.blocked = false;
  72. state.watchers = [];
  73. state.entered = Promise.withResolvers<void>();
  74. state.release = Promise.withResolvers<void>();
  75. state.config = JSON.stringify({ plugins: { dirs: ["/workspace/plugin"] } });
  76. const manifest = "/workspace/plugin/.zcode-plugin/plugin.json";
  77. const oldFile = "/workspace/plugin/old.json";
  78. const newFile = "/workspace/plugin/new.json";
  79. state.files.set(manifest, JSON.stringify({ name: "example", mcpServers: "old.json" }));
  80. state.files.set(oldFile, JSON.stringify({ mcpServers: { service: { command: "old" } } }));
  81. const source = await createDynamicMcpConfigSource({
  82. configPaths: ["/workspace/config.json"],
  83. userConfigPath: "/workspace/config.json",
  84. pluginStorageRoot: "/workspace/plugins",
  85. pluginRoots: [],
  86. workingDirectory: "/workspace",
  87. });
  88. try {
  89. const changed = Promise.withResolvers<void>();
  90. source.subscribe(() => changed.resolve());
  91. state.files.set(manifest, JSON.stringify({ name: "example", mcpServers: "new.json" }));
  92. state.files.set(newFile, JSON.stringify({ mcpServers: { service: { command: "stale" } } }));
  93. state.reading = newFile;
  94. state.watchers[0]!.emit("all", "change", manifest);
  95. await state.entered.promise;
  96. // 新文件尚未进入订阅集合,故此更新没有 watcher 事件;ready 后的重读必须捕获它。
  97. state.files.set(newFile, JSON.stringify({ mcpServers: { service: { command: "fresh" } } }));
  98. state.reading = "";
  99. state.release.resolve();
  100. await changed.promise;
  101. expect(Object.values(source.getSnapshot().servers)).toEqual([
  102. expect.objectContaining({ command: "fresh" }),
  103. ]);
  104. } finally {
  105. source.close();
  106. state.files.clear();
  107. }
  108. });
  109. it("publishes private workspace options on save and falls back to user options on removal", async () => {
  110. state.blocked = false;
  111. state.watchers = [];
  112. state.files.clear();
  113. state.config = JSON.stringify({
  114. plugins: { dirs: ["/workspace/plugin"], options: { "example@inline": { label: "user" } } },
  115. });
  116. const project = "/workspace/project/.zcode/config.json";
  117. const secrets = "/workspace/plugin-secrets.json";
  118. state.files.set(
  119. project,
  120. JSON.stringify({ plugins: { options: { "example@inline": { label: "repository" } } } }),
  121. );
  122. state.files.set(
  123. "/workspace/plugin/.zcode-plugin/plugin.json",
  124. JSON.stringify({
  125. name: "example",
  126. userConfig: { label: { type: "string" } },
  127. mcpServers: { service: { command: "node", env: { LABEL: "${user_config.label}" } } },
  128. }),
  129. );
  130. const source = await createDynamicMcpConfigSource({
  131. configPaths: [project, "/workspace/config.json"],
  132. userConfigPath: "/workspace/config.json",
  133. pluginStorageRoot: "/workspace/plugins",
  134. pluginRoots: [],
  135. workingDirectory: "/workspace/project",
  136. });
  137. const label = () => Object.values(source.getSnapshot().servers)[0]?.env?.LABEL;
  138. try {
  139. expect(label()).toBe("user");
  140. let changed = Promise.withResolvers<void>();
  141. source.subscribe(() => changed.resolve());
  142. state.files.set(
  143. secrets,
  144. JSON.stringify({
  145. version: 1,
  146. user: {},
  147. workspaces: {
  148. "/workspace/project": { "example@inline": { label: "private" } },
  149. },
  150. }),
  151. );
  152. for (const watcher of state.watchers) watcher.emit("all", "add", secrets);
  153. await changed.promise;
  154. expect(label()).toBe("private");
  155. changed = Promise.withResolvers<void>();
  156. state.files.delete(secrets);
  157. for (const watcher of state.watchers) watcher.emit("all", "unlink", secrets);
  158. await changed.promise;
  159. expect(label()).toBe("user");
  160. } finally {
  161. source.close();
  162. state.files.clear();
  163. }
  164. });