mcp-config-source-registry.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import { EventEmitter } from "node:events";
  2. import { afterEach, beforeEach, expect, it, vi } from "vitest";
  3. import type { McpConfigurationSnapshot, McpServerConfig } from "@zcode/contracts";
  4. import { createMcpConfigurationLoader } from "../src/mcp/config-loader.js";
  5. import {
  6. MCP_CONFIG_EVENT_DEBOUNCE_MS,
  7. createDynamicMcpConfigSource,
  8. createMcpConfigSourceRegistry,
  9. } from "../src/mcp/config-source.js";
  10. // 进程内共享配置源:同一 key 只有一组 watcher,一次写入的事件突发只读一次盘。
  11. const CONFIG_PATH = "/workspace/config.json";
  12. const PLUGIN_MANIFEST = "/workspace/plugin/.zcode-plugin/plugin.json";
  13. const state = vi.hoisted(() => ({
  14. files: new Map<string, string>(),
  15. reads: new Map<string, number>(),
  16. watchers: [] as Array<EventEmitter & { close: ReturnType<typeof vi.fn> }>,
  17. }));
  18. vi.mock("node:fs/promises", async (original) => ({
  19. ...(await original<typeof import("node:fs/promises")>()),
  20. stat: async () => ({ dev: 1, ino: 1, isDirectory: () => true }),
  21. // 全部文件端口都是虚拟的:真实 IO 不受假定时器推进,读盘链会停在半途。
  22. access: async () => {
  23. throw Object.assign(new Error("missing"), { code: "ENOENT" });
  24. },
  25. mkdir: vi.fn(async () => undefined),
  26. readFile: async (path: string) => {
  27. state.reads.set(path, (state.reads.get(path) ?? 0) + 1);
  28. const content = state.files.get(path);
  29. if (content !== undefined) return content;
  30. throw Object.assign(new Error("missing"), { code: "ENOENT" });
  31. },
  32. }));
  33. vi.mock("../src/mcp/config-loader.js", async (original) => {
  34. const actual = await original<typeof import("../src/mcp/config-loader.js")>();
  35. return { ...actual, createMcpConfigurationLoader: vi.fn(actual.createMcpConfigurationLoader) };
  36. });
  37. vi.mock("chokidar", () => ({
  38. watch: () => {
  39. const watcher = Object.assign(new EventEmitter(), { close: vi.fn(async () => {}) });
  40. state.watchers.push(watcher);
  41. queueMicrotask(() => watcher.emit("ready"));
  42. return watcher;
  43. },
  44. }));
  45. function writeConfig(servers: Record<string, unknown>, extra: Record<string, unknown> = {}) {
  46. state.files.set(CONFIG_PATH, JSON.stringify({ mcp: { servers }, ...extra }));
  47. }
  48. function loads(): number {
  49. return state.reads.get(CONFIG_PATH) ?? 0;
  50. }
  51. function options(extra: { defaultEnabledPlugins?: ReadonlySet<string> } = {}) {
  52. return {
  53. configPaths: [CONFIG_PATH],
  54. userConfigPath: CONFIG_PATH,
  55. pluginStorageRoot: "/workspace/plugins",
  56. pluginRoots: [],
  57. workingDirectory: "/workspace",
  58. ...extra,
  59. };
  60. }
  61. /** 模拟一次保存:同一文件的 raw 与 all 事件交替到达。 */
  62. function emitWriteBurst(): void {
  63. for (const watcher of state.watchers) {
  64. watcher.emit("raw", "change", "config.json", { watchedPath: "/workspace" });
  65. watcher.emit("all", "change", CONFIG_PATH);
  66. watcher.emit("raw", "rename", "config.json", { watchedPath: "/workspace" });
  67. }
  68. }
  69. /** 推过去抖窗口并排空随后的读盘链。 */
  70. async function settle(): Promise<void> {
  71. await vi.advanceTimersByTimeAsync(MCP_CONFIG_EVENT_DEBOUNCE_MS);
  72. await vi.advanceTimersByTimeAsync(0);
  73. }
  74. beforeEach(() => {
  75. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  76. state.files.clear();
  77. state.reads.clear();
  78. state.watchers = [];
  79. writeConfig({ first: { command: "node" } });
  80. });
  81. afterEach(() => {
  82. vi.useRealTimers();
  83. });
  84. it("loads once for a burst of events from one write", async () => {
  85. const source = await createDynamicMcpConfigSource(options());
  86. try {
  87. const before = loads();
  88. writeConfig({ second: { command: "node" } });
  89. emitWriteBurst();
  90. await settle();
  91. // 修复前每个事件都把 drain 标脏:一次保存读 2 次以上,多个会话再各读一遍。
  92. expect(loads() - before).toBe(1);
  93. expect(Object.keys(source.getSnapshot().servers)).toEqual(["second"]);
  94. } finally {
  95. source.close();
  96. }
  97. });
  98. it("shares one watcher set for sessions with the same inputs", async () => {
  99. const registry = createMcpConfigSourceRegistry();
  100. const first = await registry.acquire(options());
  101. const watchers = state.watchers.length;
  102. const second = await registry.acquire(options());
  103. try {
  104. expect(watchers).toBeGreaterThan(0);
  105. expect(state.watchers).toHaveLength(watchers);
  106. } finally {
  107. first.close();
  108. second.close();
  109. registry.close();
  110. }
  111. });
  112. it("does not share a source between sessions admitted with different workspace plugin trust", async () => {
  113. // 修复前键里只有官方根目录:信任前创建的会话与信任后的新会话共用一个源,新会话拿不到插件 MCP。
  114. const root = (state: "pending" | "trusted") => ({
  115. rootPath: "/workspace/plugin",
  116. marketplace: "inline",
  117. source: "inline" as const,
  118. workspaceTrust: { state, pluginRoot: "plugin", declarationDigest: "a".repeat(64) },
  119. });
  120. const registry = createMcpConfigSourceRegistry();
  121. const pending = await registry.acquire({ ...options(), pluginRoots: [root("pending")] });
  122. const watchers = state.watchers.length;
  123. const trusted = await registry.acquire({ ...options(), pluginRoots: [root("trusted")] });
  124. try {
  125. expect(state.watchers.length).toBeGreaterThan(watchers);
  126. } finally {
  127. pending.close();
  128. trusted.close();
  129. registry.close();
  130. }
  131. });
  132. it("reads the latest files on acquire even without a watcher event", async () => {
  133. const registry = createMcpConfigSourceRegistry();
  134. const first = await registry.acquire(options());
  135. const firstNotified = vi.fn();
  136. first.subscribe(firstNotified);
  137. try {
  138. writeConfig({ fresh: { command: "node" } });
  139. const second = await registry.acquire(options());
  140. try {
  141. expect(Object.keys(second.getSnapshot().servers)).toEqual(["fresh"]);
  142. expect(Object.keys(first.getSnapshot().servers)).toEqual(["fresh"]);
  143. expect(firstNotified).toHaveBeenCalledOnce();
  144. } finally {
  145. second.close();
  146. }
  147. } finally {
  148. first.close();
  149. registry.close();
  150. }
  151. });
  152. it("skips a pending debounce timer when a new session acquires", async () => {
  153. const registry = createMcpConfigSourceRegistry();
  154. const first = await registry.acquire(options());
  155. try {
  156. writeConfig({ fresh: { command: "node" } });
  157. emitWriteBurst();
  158. expect(vi.getTimerCount()).toBe(1);
  159. const second = await registry.acquire(options());
  160. try {
  161. expect(Object.keys(second.getSnapshot().servers)).toEqual(["fresh"]);
  162. expect(vi.getTimerCount()).toBe(0);
  163. } finally {
  164. second.close();
  165. }
  166. } finally {
  167. first.close();
  168. registry.close();
  169. }
  170. });
  171. it("keeps other views updated after one view is closed twice", async () => {
  172. const registry = createMcpConfigSourceRegistry();
  173. const first = await registry.acquire(options());
  174. const second = await registry.acquire(options());
  175. const secondNotified = vi.fn();
  176. second.subscribe(secondNotified);
  177. try {
  178. // 一次 app 关闭会多次走 beginShutdown;view 释放必须幂等,引用计数只减一次。
  179. first.close();
  180. first.close();
  181. expect(state.watchers.every((watcher) => watcher.close.mock.calls.length === 0)).toBe(true);
  182. writeConfig({ later: { command: "node" } });
  183. emitWriteBurst();
  184. await settle();
  185. expect(secondNotified).toHaveBeenCalledOnce();
  186. expect(Object.keys(second.getSnapshot().servers)).toEqual(["later"]);
  187. } finally {
  188. second.close();
  189. registry.close();
  190. }
  191. });
  192. it("closes watchers and timers when the last view is released", async () => {
  193. const registry = createMcpConfigSourceRegistry();
  194. const first = await registry.acquire(options());
  195. const second = await registry.acquire(options());
  196. const notified = vi.fn();
  197. first.subscribe(notified);
  198. second.subscribe(notified);
  199. writeConfig({ late: { command: "node" } });
  200. emitWriteBurst();
  201. first.close();
  202. second.close();
  203. const before = loads();
  204. expect(state.watchers.every((watcher) => watcher.close.mock.calls.length === 1)).toBe(true);
  205. expect(vi.getTimerCount()).toBe(0);
  206. await settle();
  207. expect(loads()).toBe(before);
  208. expect(notified).not.toHaveBeenCalled();
  209. registry.close();
  210. });
  211. it("releases the entry when a view fails to prepare and retries on the next acquire", async () => {
  212. const registry = createMcpConfigSourceRegistry();
  213. await expect(
  214. registry.acquire({
  215. ...options(),
  216. prepare() {
  217. throw new Error("prepare failed");
  218. },
  219. }),
  220. ).rejects.toThrow("prepare failed");
  221. expect(state.watchers.every((watcher) => watcher.close.mock.calls.length === 1)).toBe(true);
  222. const watchers = state.watchers.length;
  223. const source = await registry.acquire(options());
  224. try {
  225. expect(state.watchers.length).toBeGreaterThan(watchers);
  226. expect(Object.keys(source.getSnapshot().servers)).toEqual(["first"]);
  227. } finally {
  228. source.close();
  229. registry.close();
  230. }
  231. });
  232. it("keeps per-session preparation isolated on a shared entry", async () => {
  233. const registry = createMcpConfigSourceRegistry();
  234. const withHost = (name: string) => ({
  235. ...options(),
  236. prepare: (servers: Record<string, McpServerConfig>, _plugins: unknown, enabled: boolean) => ({
  237. enabled,
  238. servers: { ...servers, [name]: { type: "stdio" as const, command: name } },
  239. }),
  240. });
  241. const first = await registry.acquire(withHost("alpha"));
  242. const second = await registry.acquire(withHost("beta"));
  243. try {
  244. writeConfig({ later: { command: "node" } });
  245. emitWriteBurst();
  246. await settle();
  247. expect(Object.keys(first.getSnapshot().servers).sort()).toEqual(["alpha", "later"]);
  248. expect(Object.keys(second.getSnapshot().servers).sort()).toEqual(["beta", "later"]);
  249. } finally {
  250. first.close();
  251. second.close();
  252. registry.close();
  253. }
  254. });
  255. it("separates entries whose default-enabled plugin sets differ", async () => {
  256. const registry = createMcpConfigSourceRegistry();
  257. // Set 直接参与 mcpConfigKey 会序列化成 "{}",不同集合必须得到不同的 key。
  258. const first = await registry.acquire(options({ defaultEnabledPlugins: new Set(["a@official"]) }));
  259. const watchers = state.watchers.length;
  260. const second = await registry.acquire(
  261. options({ defaultEnabledPlugins: new Set(["b@official"]) }),
  262. );
  263. try {
  264. expect(state.watchers.length).toBe(watchers * 2);
  265. } finally {
  266. first.close();
  267. second.close();
  268. registry.close();
  269. }
  270. });
  271. it("lets every view see plugin servers by identity on a shared entry", async () => {
  272. writeConfig({}, { plugins: { dirs: ["/workspace/plugin"] } });
  273. state.files.set(
  274. PLUGIN_MANIFEST,
  275. JSON.stringify({ name: "example", mcpServers: { service: { command: "node" } } }),
  276. );
  277. const registry = createMcpConfigSourceRegistry();
  278. // 官方 CUA 信任按对象身份判定;各 view 共用同一份原始结果,不能各自深拷贝。
  279. const trusted = {
  280. ...options(),
  281. prepare: (
  282. servers: Record<string, McpServerConfig>,
  283. pluginServers: Record<string, McpServerConfig>,
  284. enabled: boolean,
  285. ): McpConfigurationSnapshot => ({
  286. enabled,
  287. servers,
  288. trustedOfficialCuaServerNames: Object.keys(pluginServers).filter(
  289. (name) => servers[name] === pluginServers[name],
  290. ),
  291. }),
  292. };
  293. const first = await registry.acquire(trusted);
  294. const second = await registry.acquire(trusted);
  295. try {
  296. expect(first.getSnapshot().trustedOfficialCuaServerNames).toEqual(["plugin:example:service"]);
  297. expect(second.getSnapshot().trustedOfficialCuaServerNames).toEqual(["plugin:example:service"]);
  298. } finally {
  299. first.close();
  300. second.close();
  301. registry.close();
  302. }
  303. });
  304. it("does not keep the creating session's preparation in the shared entry", async () => {
  305. const registry = createMcpConfigSourceRegistry();
  306. const first = await registry.acquire({
  307. ...options(),
  308. prepare: (_servers, _plugins, enabled) => ({ enabled, servers: {} }),
  309. });
  310. try {
  311. // 修复前条目持有创建者的 options:prepare 闭包引用创建者的 app 作用域,该会话关闭后仍不能回收。
  312. expect(vi.mocked(createMcpConfigurationLoader).mock.lastCall?.[0]).not.toHaveProperty(
  313. "prepare",
  314. );
  315. } finally {
  316. first.close();
  317. registry.close();
  318. }
  319. });