dynamic-mcp-config.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { expect, it, vi } from "vitest";
  5. import type { ConfigResult } from "@zcode/adapters/config";
  6. import type { AgentRuntimeConfig } from "@zcode/core";
  7. import type { Logger, PluginLoadOutcome } from "@zcode/contracts";
  8. import { createConfig } from "@zcode/adapters/config";
  9. import { createMcpConfigSourceRegistry } from "@zcode/adapters/mcp";
  10. import { createAppMcpConfigurationSource } from "../src/app/dynamic-mcp-config.js";
  11. import { resolveStartupPlugins } from "../src/app/startup-marks.js";
  12. import { resolveEffectiveMcpConfiguration } from "../src/mcp-config.js";
  13. import { resolveAppRuntimeConfig } from "../src/app/runtime-config.js";
  14. it("workspace snapshots reload disk configuration while explicit maps and children stay scoped", async () => {
  15. const root = await mkdtemp(join(tmpdir(), "mcp-app-source-"));
  16. const workspace = join(root, "workspace");
  17. const user = join(root, "user.json");
  18. await mkdir(join(workspace, ".zcode"), { recursive: true });
  19. await writeFile(
  20. join(workspace, ".zcode", "config.json"),
  21. JSON.stringify({ mcp: { servers: { shared: { command: "project" } } } }),
  22. );
  23. await writeFile(
  24. user,
  25. JSON.stringify({ features: { mcp: false }, mcp: { servers: { shared: { command: "user" } } } }),
  26. );
  27. const base = {
  28. options: { pluginStorageRoot: join(root, "plugins") },
  29. configResult: { sources: { user: { path: user } } } as ConfigResult,
  30. runtimeFeatures: {} as AgentRuntimeConfig["runtimeFeatures"],
  31. pluginOutcome: { plugins: [] } as unknown as PluginLoadOutcome,
  32. builtInMcpServers: { host: { type: "stdio" as const, command: "host" } },
  33. cliStorageRoot: root,
  34. workingDirectory: workspace,
  35. logger: { warn: vi.fn(), debug: vi.fn() } as unknown as Logger,
  36. };
  37. const workspaceSource = await createAppMcpConfigurationSource({
  38. ...base,
  39. options: base.options,
  40. });
  41. const explicitSource = await createAppMcpConfigurationSource({
  42. ...base,
  43. options: {
  44. ...base.options,
  45. runtimeConfig: {
  46. mcp: { enabled: true, servers: { pinned: { type: "stdio", command: "pinned" } } },
  47. },
  48. },
  49. });
  50. try {
  51. expect(workspaceSource!.getSnapshot().enabled).toBe(false);
  52. expect(explicitSource!.getSnapshot().enabled).toBe(true);
  53. expect(workspaceSource!.getSnapshot().servers.shared).toMatchObject({ command: "user" });
  54. expect(Object.keys(explicitSource!.getSnapshot().servers).sort()).toEqual(["host", "pinned"]);
  55. const applied = Promise.withResolvers<void>();
  56. workspaceSource!.subscribe(() => {
  57. if (workspaceSource!.getSnapshot().servers.next) applied.resolve();
  58. });
  59. await writeFile(user, JSON.stringify({ mcp: { servers: { next: { command: "new" } } } }));
  60. await applied.promise;
  61. expect(workspaceSource!.getSnapshot().servers.shared).toMatchObject({
  62. command: "project",
  63. cwd: workspace,
  64. });
  65. expect(workspaceSource!.getSnapshot().servers.host).toEqual(base.builtInMcpServers.host);
  66. expect(Object.keys(explicitSource!.getSnapshot().servers).sort()).toEqual(["host", "pinned"]);
  67. expect(JSON.parse(await readFile(user, "utf8")).mcp.servers.host).toBeUndefined();
  68. const forkSource = await createAppMcpConfigurationSource({
  69. ...base,
  70. options: {
  71. ...base.options,
  72. runtimeConfig: { parentSessionId: "parent" } as AgentRuntimeConfig,
  73. },
  74. });
  75. try {
  76. expect(forkSource?.getSnapshot().servers.next).toMatchObject({ command: "new" });
  77. } finally {
  78. forkSource?.close();
  79. }
  80. } finally {
  81. workspaceSource?.close();
  82. explicitSource?.close();
  83. await rm(root, { recursive: true, force: true });
  84. }
  85. });
  86. it("produces the same first snapshot as the startup configuration path", async () => {
  87. const root = await mkdtemp(join(tmpdir(), "mcp-app-parity-"));
  88. const workspace = join(root, "workspace");
  89. const user = join(root, "user.json");
  90. const pluginStorageRoot = join(root, "plugins");
  91. const inline = join(root, "inline-plugin");
  92. const installed = join(root, "installed-plugin");
  93. try {
  94. await mkdir(join(workspace, ".zcode"), { recursive: true });
  95. await mkdir(pluginStorageRoot, { recursive: true });
  96. for (const [pluginRoot, name] of [
  97. [inline, "inline-example"],
  98. [installed, "installed-example"],
  99. ] as const) {
  100. await mkdir(join(pluginRoot, ".zcode-plugin"), { recursive: true });
  101. await writeFile(
  102. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  103. JSON.stringify({ name, mcpServers: { demo: { command: "node", args: ["server.js"] } } }),
  104. );
  105. }
  106. await writeFile(
  107. join(pluginStorageRoot, "installed_plugins.json"),
  108. JSON.stringify({
  109. version: 1,
  110. plugins: [
  111. {
  112. id: "installed-example@market",
  113. name: "installed-example",
  114. marketplace: "market",
  115. version: "1.0.0",
  116. installPath: installed,
  117. installedAt: "2026-01-01T00:00:00Z",
  118. scope: "user",
  119. },
  120. ],
  121. }),
  122. );
  123. await writeFile(
  124. join(workspace, ".zcode", "config.json"),
  125. JSON.stringify({
  126. mcp: {
  127. servers: {
  128. shared: { command: "project" },
  129. local: { command: "node", args: ["server.js"], cwd: "tools" },
  130. },
  131. },
  132. }),
  133. );
  134. await writeFile(
  135. user,
  136. JSON.stringify({
  137. mcp: {
  138. servers: {
  139. shared: { command: "user" },
  140. remote: { type: "http", url: "https://example.com/mcp", enabled: false },
  141. },
  142. },
  143. plugins: {
  144. dirs: [inline],
  145. enabledPlugins: { "installed-example@market": true },
  146. },
  147. }),
  148. );
  149. const configResult = createConfig({
  150. env: {},
  151. userConfigPath: user,
  152. workingDirectory: workspace,
  153. });
  154. const pluginOutcome = await resolveStartupPlugins({
  155. cliStorageRoot: root,
  156. configResult,
  157. env: {},
  158. options: { pluginStorageRoot },
  159. startupTimer: { mark() {} } as unknown as Parameters<
  160. typeof resolveStartupPlugins
  161. >[0]["startupTimer"],
  162. workingDirectory: workspace,
  163. });
  164. const builtInMcpServers = { host: { type: "stdio" as const, command: "host" } };
  165. // 设置页与启动插件发现走 createConfig + 插件加载器;会话走动态加载器。两套解析结果必须相同,
  166. // 来源标记也相同:启动路径由 runtime 配置按 createConfig 的来源补标。
  167. const startup = resolveAppRuntimeConfig({
  168. cliStorageRoot: root,
  169. configResult,
  170. options: {},
  171. mcpConfiguration: resolveEffectiveMcpConfiguration({
  172. enabled: configResult.config.features.mcp,
  173. servers: configResult.config.mcp.servers,
  174. pluginServers: pluginOutcome.mcpServers,
  175. builtInServers: builtInMcpServers,
  176. }).mcp,
  177. subagentOutputRootDir: join(root, "output"),
  178. workingDirectory: workspace,
  179. }).runtimeConfig.mcp!;
  180. const source = await createAppMcpConfigurationSource({
  181. options: { pluginStorageRoot },
  182. configResult,
  183. runtimeFeatures: {} as AgentRuntimeConfig["runtimeFeatures"],
  184. pluginOutcome,
  185. builtInMcpServers,
  186. cliStorageRoot: root,
  187. workingDirectory: workspace,
  188. logger: { warn: vi.fn(), debug: vi.fn() } as unknown as Logger,
  189. });
  190. try {
  191. // 官方内置插件同样经过两条路径,只断言夹具中的来源都已出现。
  192. expect(Object.keys(startup.servers)).toEqual(
  193. expect.arrayContaining([
  194. "host",
  195. "local",
  196. "plugin:inline-example:demo",
  197. "plugin:installed-example:demo",
  198. "remote",
  199. "shared",
  200. ]),
  201. );
  202. expect(source!.getSnapshot()).toEqual(startup);
  203. } finally {
  204. source?.close();
  205. }
  206. } finally {
  207. await rm(root, { recursive: true, force: true });
  208. }
  209. });
  210. it("sessions in one process share the injected configuration source registry", async () => {
  211. const root = await mkdtemp(join(tmpdir(), "mcp-app-shared-"));
  212. const workspace = join(root, "workspace");
  213. const user = join(root, "user.json");
  214. await mkdir(workspace, { recursive: true });
  215. await writeFile(user, JSON.stringify({ mcp: { servers: { first: { command: "node" } } } }));
  216. const registry = createMcpConfigSourceRegistry();
  217. const acquire = vi.spyOn(registry, "acquire");
  218. const create = (host: string) =>
  219. createAppMcpConfigurationSource({
  220. options: { pluginStorageRoot: join(root, "plugins"), mcpConfigSourceRegistry: registry },
  221. configResult: { sources: { user: { path: user } } } as ConfigResult,
  222. runtimeFeatures: {} as AgentRuntimeConfig["runtimeFeatures"],
  223. pluginOutcome: { plugins: [] } as unknown as PluginLoadOutcome,
  224. builtInMcpServers: { [host]: { type: "stdio" as const, command: host } },
  225. cliStorageRoot: root,
  226. workingDirectory: workspace,
  227. logger: { warn: vi.fn(), debug: vi.fn() } as unknown as Logger,
  228. });
  229. const first = await create("alpha");
  230. const second = await create("beta");
  231. try {
  232. expect(acquire).toHaveBeenCalledTimes(2);
  233. // 内建 server 由每个会话自己的 prepare 补上,共享条目不会互相串。
  234. expect(Object.keys(first.getSnapshot().servers).sort()).toEqual(["alpha", "first"]);
  235. expect(Object.keys(second.getSnapshot().servers).sort()).toEqual(["beta", "first"]);
  236. const applied = Promise.withResolvers<void>();
  237. second.subscribe(() => {
  238. if (second.getSnapshot().servers.next) applied.resolve();
  239. });
  240. // 关闭会话 A(重复关闭)后,会话 B 仍能热更新。
  241. first.close();
  242. first.close();
  243. await writeFile(user, JSON.stringify({ mcp: { servers: { next: { command: "node" } } } }));
  244. await applied.promise;
  245. expect(Object.keys(second.getSnapshot().servers).sort()).toEqual(["beta", "next"]);
  246. } finally {
  247. first.close();
  248. second.close();
  249. registry.close();
  250. await rm(root, { recursive: true, force: true });
  251. }
  252. });