mcp-dynamic-config.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. import { mkdtemp, mkdir, writeFile, rm, rename, stat } 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 { activateDirectoryAtomically } from "../src/plugins/atomic-directory.js";
  6. import { createMcpConfigurationLoader } from "../src/mcp/config-loader.js";
  7. import { createDynamicMcpConfigSource } from "../src/mcp/config-source.js";
  8. /** 直接使用加载器的用例按配置源的方式采纳每次结果。 */
  9. async function accept(loader: ReturnType<typeof createMcpConfigurationLoader>) {
  10. const loaded = await loader.load();
  11. loaded.commit();
  12. return loaded;
  13. }
  14. it.each(["config", "legacy"])(
  15. "keeps valid settings with MCP warnings on initial load and refresh (%s)",
  16. async (format) => {
  17. const root = await mkdtemp(join(tmpdir(), "mcp-config-warning-"));
  18. const config = join(root, "config.json");
  19. const legacy = join(root, ".mcp.json");
  20. const plugin = join(root, "plugin");
  21. try {
  22. await mkdir(join(plugin, ".zcode-plugin"), { recursive: true });
  23. await writeFile(
  24. join(plugin, ".zcode-plugin", "plugin.json"),
  25. JSON.stringify({ name: "example", mcpServers: { demo: { command: "node" } } }),
  26. );
  27. const loader = createMcpConfigurationLoader({
  28. configPaths: [config],
  29. userConfigPath: config,
  30. fallbackPaths: format === "legacy" ? { [config]: legacy } : undefined,
  31. pluginStorageRoot: join(root, "plugins"),
  32. pluginRoots: [],
  33. workingDirectory: root,
  34. });
  35. for (const enabled of [false, true]) {
  36. const name = enabled ? "updated" : "initial";
  37. const servers = { [name]: { command: "node" }, broken: { command: 123 } };
  38. await writeFile(
  39. config,
  40. JSON.stringify({
  41. features: { mcp: enabled },
  42. plugins: { enabled, dirs: [plugin] },
  43. ...(format === "config" ? { mcp: { servers } } : {}),
  44. }),
  45. );
  46. if (format === "legacy") await writeFile(legacy, JSON.stringify({ mcpServers: servers }));
  47. const { configuration } = await accept(loader);
  48. expect(configuration.enabled).toBe(enabled);
  49. expect(Object.keys(configuration.servers).sort()).toEqual(
  50. enabled ? ["plugin:example:demo", name].sort() : [name],
  51. );
  52. expect(configuration.servers[name]).toMatchObject({ type: "stdio", command: "node" });
  53. }
  54. const { configuration: valid } = await accept(loader);
  55. // warning 的结果也是有效快照;后续整体解析失败不能回退到更早配置。
  56. for (const invalid of ["{ invalid", JSON.stringify({ features: { mcp: "invalid" } })]) {
  57. await writeFile(config, invalid);
  58. await expect(accept(loader)).resolves.toMatchObject({ configuration: valid });
  59. }
  60. if (format === "legacy") {
  61. await writeFile(legacy, "{ invalid");
  62. await expect(accept(loader)).resolves.toMatchObject({ configuration: valid });
  63. }
  64. await rm(config);
  65. await rm(legacy, { force: true });
  66. await expect(accept(loader)).resolves.toMatchObject({
  67. configuration: { enabled: true, servers: {} },
  68. });
  69. } finally {
  70. await rm(root, { recursive: true, force: true });
  71. }
  72. },
  73. );
  74. it("publishes external atomic config replacement", async () => {
  75. const root = await mkdtemp(join(tmpdir(), "mcp-config-"));
  76. const file = join(root, "config.json");
  77. await writeFile(file, JSON.stringify({ mcp: { servers: {} } }));
  78. const source = await createDynamicMcpConfigSource({
  79. configPaths: [file],
  80. userConfigPath: file,
  81. pluginStorageRoot: join(root, "plugins"),
  82. workingDirectory: root,
  83. pluginRoots: [],
  84. });
  85. try {
  86. const changed = Promise.withResolvers<void>();
  87. source.subscribe(() => {
  88. if (source.getSnapshot().servers.test) changed.resolve();
  89. });
  90. await writeFile(
  91. `${file}.tmp`,
  92. JSON.stringify({ mcp: { servers: { test: { type: "stdio", command: "node" } } } }),
  93. );
  94. await rename(`${file}.tmp`, file);
  95. await changed.promise;
  96. expect(source.getSnapshot().servers.test?.type).toBe("stdio");
  97. } finally {
  98. source.close();
  99. await rm(root, { recursive: true, force: true });
  100. }
  101. }, 5000);
  102. it("reloads an installed plugin on each install record commit and removes it on uninstall", async () => {
  103. const root = await mkdtemp(join(tmpdir(), "mcp-plugin-"));
  104. const config = join(root, "config.json");
  105. const plugins = join(root, "plugins");
  106. const plugin = join(root, "plugin");
  107. await mkdir(plugins);
  108. await mkdir(join(plugin, ".zcode-plugin"), { recursive: true });
  109. await writeFile(
  110. join(plugin, ".zcode-plugin", "plugin.json"),
  111. JSON.stringify({ name: "example", mcpServers: "./.mcp.json" }),
  112. );
  113. await writeFile(
  114. join(plugin, ".mcp.json"),
  115. JSON.stringify({ mcpServers: { demo: { command: "node", args: ["server.js"] } } }),
  116. );
  117. await writeFile(
  118. config,
  119. JSON.stringify({ plugins: { enabledPlugins: { "example@test": true } } }),
  120. );
  121. const source = await createDynamicMcpConfigSource({
  122. configPaths: [config],
  123. userConfigPath: config,
  124. pluginStorageRoot: plugins,
  125. pluginRoots: [],
  126. workingDirectory: root,
  127. });
  128. // 安装和更新流程在替换插件目录后写安装记录(updatedAt 每次不同);配置源只监听这个提交点。
  129. const commit = (updatedAt: string) =>
  130. writeFile(
  131. join(plugins, "installed_plugins.json"),
  132. JSON.stringify({
  133. version: 1,
  134. plugins: [
  135. {
  136. id: "example@test",
  137. name: "example",
  138. marketplace: "test",
  139. version: "1.0.0",
  140. installPath: plugin,
  141. installedAt: "2026-01-01T00:00:00Z",
  142. updatedAt,
  143. scope: "user",
  144. },
  145. ],
  146. }),
  147. );
  148. try {
  149. const loaded = Promise.withResolvers<void>();
  150. const removed = Promise.withResolvers<void>();
  151. let installed = false;
  152. source.subscribe(() => {
  153. if (source.getSnapshot().servers["plugin:example:demo"]) {
  154. installed = true;
  155. loaded.resolve();
  156. } else if (installed) removed.resolve();
  157. });
  158. await commit("2026-01-01T00:00:00Z");
  159. await loaded.promise;
  160. expect(source.getSnapshot().servers["plugin:example:demo"]).toMatchObject({ command: "node" });
  161. const declared = Promise.withResolvers<void>();
  162. const refreshed = Promise.withResolvers<void>();
  163. source.subscribe(() => {
  164. const server = source.getSnapshot().servers["plugin:example:demo"];
  165. if (server?.type === "stdio" && server.args?.[0] === "declared.js") declared.resolve();
  166. if (server?.type === "stdio" && server.args?.[0] === "updated.js") refreshed.resolve();
  167. });
  168. const extra = join(plugin, "extra.json");
  169. await writeFile(
  170. extra,
  171. JSON.stringify({ mcpServers: { demo: { command: "node", args: ["declared.js"] } } }),
  172. );
  173. await writeFile(
  174. join(plugin, ".zcode-plugin", "plugin.json"),
  175. JSON.stringify({ name: "example", mcpServers: "./extra.json" }),
  176. );
  177. await commit("2026-01-02T00:00:00Z");
  178. await declared.promise;
  179. await writeFile(
  180. extra,
  181. JSON.stringify({ mcpServers: { demo: { command: "node", args: ["updated.js"] } } }),
  182. );
  183. await commit("2026-01-03T00:00:00Z");
  184. await refreshed.promise;
  185. await writeFile(
  186. join(plugins, "installed_plugins.json"),
  187. JSON.stringify({ version: 1, plugins: [] }),
  188. );
  189. await removed.promise;
  190. expect(source.getSnapshot().servers).toEqual({});
  191. } finally {
  192. source.close();
  193. await rm(root, { recursive: true, force: true });
  194. }
  195. });
  196. it("keeps an explicit server map and retains a malformed install inventory", async () => {
  197. const root = await mkdtemp(join(tmpdir(), "mcp-explicit-"));
  198. const config = join(root, "config.json");
  199. const manifest = join(root, "plugin", ".zcode-plugin", "plugin.json");
  200. const inventory = join(root, "installed_plugins.json");
  201. await mkdir(join(root, "plugin", ".zcode-plugin"), { recursive: true });
  202. await writeFile(
  203. manifest,
  204. JSON.stringify({ name: "example", mcpServers: { demo: { command: "node" } } }),
  205. );
  206. await writeFile(
  207. inventory,
  208. JSON.stringify({ plugins: { "example@test": [{ installPath: join(root, "plugin") }] } }),
  209. );
  210. await writeFile(
  211. config,
  212. JSON.stringify({ plugins: { enabledPlugins: { "example@test": true } } }),
  213. );
  214. const explicit = { pinned: { type: "stdio" as const, command: "node", args: ["pinned.js"] } };
  215. const source = await createDynamicMcpConfigSource({
  216. configPaths: [config],
  217. userConfigPath: config,
  218. pluginStorageRoot: root,
  219. pluginRoots: [],
  220. workingDirectory: root,
  221. explicitServers: explicit,
  222. });
  223. try {
  224. expect(Object.keys(source.getSnapshot().servers).sort()).toEqual([
  225. "pinned",
  226. "plugin:example:demo",
  227. ]);
  228. const changed = Promise.withResolvers<void>();
  229. source.subscribe(() => {
  230. if (!source.getSnapshot().enabled) changed.resolve();
  231. });
  232. await writeFile(inventory, JSON.stringify({ plugins: "broken" }));
  233. await writeFile(
  234. config,
  235. JSON.stringify({
  236. features: { mcp: false },
  237. plugins: { enabledPlugins: { "example@test": true } },
  238. mcp: { servers: { unexpected: { command: "node" } } },
  239. }),
  240. );
  241. await changed.promise;
  242. expect(Object.keys(source.getSnapshot().servers).sort()).toEqual([
  243. "pinned",
  244. "plugin:example:demo",
  245. ]);
  246. expect(source.getSnapshot().servers.pinned).toEqual(explicit.pinned);
  247. } finally {
  248. source.close();
  249. await rm(root, { recursive: true, force: true });
  250. }
  251. });
  252. it("retains an invalid source while applying a different valid source and detects directory recreation", async () => {
  253. const root = await mkdtemp(join(tmpdir(), "mcp-config-sources-"));
  254. const directory = join(root, "workspace");
  255. await mkdir(directory);
  256. const user = join(root, "config.json");
  257. const project = join(directory, "config.json");
  258. await writeFile(
  259. user,
  260. JSON.stringify({ mcp: { servers: { user: { type: "stdio", command: "node" } } } }),
  261. );
  262. const source = await createDynamicMcpConfigSource({
  263. configPaths: [user, project],
  264. userConfigPath: user,
  265. pluginStorageRoot: root,
  266. pluginRoots: [],
  267. workingDirectory: root,
  268. });
  269. try {
  270. const first = Promise.withResolvers<void>();
  271. const next = Promise.withResolvers<void>();
  272. source.subscribe(() => {
  273. if (source.getSnapshot().servers.one) first.resolve();
  274. if (source.getSnapshot().servers.two) next.resolve();
  275. });
  276. await writeFile(user, "{ invalid");
  277. await writeFile(
  278. project,
  279. JSON.stringify({ mcp: { servers: { one: { type: "stdio", command: "node" } } } }),
  280. );
  281. await first.promise;
  282. expect(source.getSnapshot().servers.user).toBeDefined();
  283. const replacement = join(root, "replacement");
  284. await mkdir(replacement);
  285. await writeFile(
  286. join(replacement, "config.json"),
  287. JSON.stringify({ mcp: { servers: { two: { type: "stdio", command: "node" } } } }),
  288. );
  289. await rename(directory, join(root, "old"));
  290. await rename(replacement, directory);
  291. await next.promise;
  292. expect(Object.keys(source.getSnapshot().servers).sort()).toEqual(["two", "user"]);
  293. } finally {
  294. source.close();
  295. await rm(root, { recursive: true, force: true });
  296. }
  297. });
  298. it("does not reuse a plugin result after its installation path is replaced", async () => {
  299. const root = await mkdtemp(join(tmpdir(), "mcp-plugin-replacement-"));
  300. const config = join(root, "config.json");
  301. const inventory = join(root, "installed_plugins.json");
  302. const pluginId = "example@test";
  303. const record = (version: string) => ({
  304. id: pluginId,
  305. name: "example",
  306. marketplace: "test",
  307. version,
  308. installPath: join(root, version),
  309. installedAt: "2026-01-01T00:00:00Z",
  310. scope: "user",
  311. });
  312. await writeFile(config, JSON.stringify({ plugins: { enabledPlugins: { [pluginId]: true } } }));
  313. for (const version of ["v1", "v2"]) {
  314. await mkdir(join(root, version, ".zcode-plugin"), { recursive: true });
  315. await writeFile(
  316. join(root, version, ".zcode-plugin", "plugin.json"),
  317. JSON.stringify({
  318. name: "example",
  319. mcpServers: {
  320. demo: version === "v1" ? { command: "node", args: ["old.js"] } : { command: 123 },
  321. },
  322. }),
  323. );
  324. }
  325. await writeFile(inventory, JSON.stringify({ version: 1, plugins: [record("v1")] }));
  326. const source = await createDynamicMcpConfigSource({
  327. configPaths: [config],
  328. userConfigPath: config,
  329. pluginStorageRoot: root,
  330. pluginRoots: [],
  331. workingDirectory: root,
  332. });
  333. try {
  334. expect(source.getSnapshot().servers["plugin:example:demo"]).toMatchObject({ args: ["old.js"] });
  335. await writeFile(inventory, JSON.stringify({ version: 1, plugins: [record("v2")] }));
  336. await vi.waitFor(() => expect(source.getSnapshot().servers).toEqual({}));
  337. } finally {
  338. source.close();
  339. await rm(root, { recursive: true, force: true });
  340. }
  341. });
  342. it("isolates malformed plugin server and installation entries", async () => {
  343. const root = await mkdtemp(join(tmpdir(), "mcp-entry-isolation-"));
  344. const plugin = join(root, "plugin");
  345. const config = join(root, "config.json");
  346. try {
  347. await mkdir(join(plugin, ".zcode-plugin"), { recursive: true });
  348. await writeFile(
  349. join(plugin, ".zcode-plugin", "plugin.json"),
  350. JSON.stringify({
  351. name: "example",
  352. mcpServers: { good: { command: "node" }, bad: { command: 42 } },
  353. }),
  354. );
  355. await writeFile(
  356. config,
  357. JSON.stringify({ plugins: { enabledPlugins: { "example@test": true } } }),
  358. );
  359. await writeFile(
  360. join(root, "installed_plugins.json"),
  361. JSON.stringify({
  362. version: 1,
  363. plugins: [
  364. {
  365. id: "example@test",
  366. name: "example",
  367. marketplace: "test",
  368. version: "1",
  369. installPath: plugin,
  370. installedAt: "2026-01-01",
  371. scope: "user",
  372. },
  373. { id: "broken" },
  374. ],
  375. }),
  376. );
  377. const loader = createMcpConfigurationLoader({
  378. configPaths: [config],
  379. userConfigPath: config,
  380. pluginStorageRoot: root,
  381. pluginRoots: [],
  382. workingDirectory: root,
  383. });
  384. expect(Object.keys((await accept(loader)).configuration.servers)).toEqual([
  385. "plugin:example:good",
  386. ]);
  387. // 有效的空声明必须收敛,不能继续回退到旧插件目录。
  388. await writeFile(
  389. join(plugin, ".zcode-plugin", "plugin.json"),
  390. JSON.stringify({ name: "example", mcpServers: {} }),
  391. );
  392. expect((await accept(loader)).configuration.servers).toEqual({});
  393. } finally {
  394. await rm(root, { recursive: true, force: true });
  395. }
  396. });
  397. it("does not fail config loading when an optional filesystem workspace is missing", async () => {
  398. const root = await mkdtemp(join(tmpdir(), "mcp-missing-workspace-"));
  399. const config = join(root, "config.json");
  400. try {
  401. await writeFile(
  402. config,
  403. JSON.stringify({
  404. mcp: {
  405. servers: {
  406. filesystem: { command: "npx", args: ["@modelcontextprotocol/server-filesystem", root] },
  407. other: { command: "node" },
  408. },
  409. },
  410. }),
  411. );
  412. const loader = createMcpConfigurationLoader({
  413. configPaths: [config],
  414. userConfigPath: config,
  415. pluginStorageRoot: root,
  416. pluginRoots: [],
  417. workingDirectory: join(root, "missing"),
  418. });
  419. const { configuration } = await accept(loader);
  420. expect(Object.keys(configuration.servers)).toEqual(["filesystem", "other"]);
  421. expect(configuration.servers.filesystem).toMatchObject({
  422. args: ["@modelcontextprotocol/server-filesystem", root],
  423. });
  424. } finally {
  425. await rm(root, { recursive: true, force: true });
  426. }
  427. });
  428. it("publishes the final value of consecutive atomic replacements", async () => {
  429. const root = await mkdtemp(join(tmpdir(), "mcp-consecutive-replace-"));
  430. const config = join(root, "config.json");
  431. await writeFile(config, "{}");
  432. const source = await createDynamicMcpConfigSource({
  433. configPaths: [config],
  434. userConfigPath: config,
  435. pluginStorageRoot: join(root, "plugins"),
  436. pluginRoots: [],
  437. workingDirectory: root,
  438. });
  439. try {
  440. for (const command of ["first", "second", "third"]) {
  441. const observed = Promise.withResolvers<void>();
  442. const unsubscribe = source.subscribe(() => {
  443. if (
  444. source.getSnapshot().servers.demo?.type === "stdio" &&
  445. source.getSnapshot().servers.demo.command === command
  446. )
  447. observed.resolve();
  448. });
  449. await writeFile(`${config}.tmp`, JSON.stringify({ mcp: { servers: { demo: { command } } } }));
  450. await rename(`${config}.tmp`, config);
  451. try {
  452. await observed.promise;
  453. } finally {
  454. unsubscribe();
  455. }
  456. }
  457. } finally {
  458. source.close();
  459. await rm(root, { recursive: true, force: true });
  460. }
  461. }, 5000);
  462. it("reads only the committed plugin generation during an atomic activation", async () => {
  463. const root = await mkdtemp(join(tmpdir(), "mcp-atomic-plugin-"));
  464. const plugin = join(root, "plugin");
  465. const authority = join(root, "installed_plugins.json");
  466. const config = join(root, "config.json");
  467. let activation: Awaited<ReturnType<typeof activateDirectoryAtomically>> | undefined;
  468. try {
  469. const manifest = (command: string) =>
  470. JSON.stringify({ name: "example", mcpServers: { demo: { command } } });
  471. await mkdir(join(plugin, ".zcode-plugin"), { recursive: true });
  472. await writeFile(join(plugin, ".zcode-plugin", "plugin.json"), manifest("old"));
  473. const record = {
  474. id: "example@test",
  475. name: "example",
  476. marketplace: "test",
  477. version: "1",
  478. installPath: plugin,
  479. installedAt: "2026-01-01",
  480. scope: "user",
  481. };
  482. await writeFile(authority, JSON.stringify({ version: 1, plugins: [record] }));
  483. await writeFile(
  484. config,
  485. JSON.stringify({ plugins: { enabledPlugins: { "example@test": true } } }),
  486. );
  487. const loader = createMcpConfigurationLoader({
  488. configPaths: [config],
  489. userConfigPath: config,
  490. pluginStorageRoot: root,
  491. pluginRoots: [],
  492. workingDirectory: root,
  493. });
  494. const stable = (await accept(loader)).configuration;
  495. activation = await activateDirectoryAtomically({
  496. targetPath: plugin,
  497. authorityPath: authority,
  498. prepare: async (path) => {
  499. await mkdir(join(path, ".zcode-plugin"), { recursive: true });
  500. await writeFile(join(path, ".zcode-plugin", "plugin.json"), manifest("new"));
  501. },
  502. });
  503. expect((await accept(loader)).configuration).toEqual(stable);
  504. const cold = createMcpConfigurationLoader({
  505. configPaths: [config],
  506. userConfigPath: config,
  507. pluginStorageRoot: root,
  508. pluginRoots: [],
  509. workingDirectory: root,
  510. });
  511. expect((await cold.load()).configuration.servers).toEqual({});
  512. await writeFile(
  513. authority,
  514. JSON.stringify({
  515. version: 1,
  516. plugins: [{ ...record, cacheTransactionId: activation.transactionId }],
  517. }),
  518. );
  519. expect((await accept(loader)).configuration.servers["plugin:example:demo"]).toMatchObject({
  520. command: "new",
  521. env: expect.objectContaining({ ZCODE_PLUGIN_ROOT: plugin }),
  522. });
  523. } finally {
  524. await activation?.finalize();
  525. await rm(root, { recursive: true, force: true });
  526. }
  527. });
  528. it.each(["directory", "isolation"])("prepares each plugin independently (%s)", async (mode) => {
  529. const root = await mkdtemp(join(tmpdir(), "mcp-plugin-preparation-"));
  530. const config = join(root, "config.json");
  531. const plugin = join(root, "plugin");
  532. const manifest = join(plugin, ".zcode-plugin", "plugin.json");
  533. try {
  534. await mkdir(join(plugin, ".zcode-plugin"), { recursive: true });
  535. await writeFile(
  536. manifest,
  537. JSON.stringify({
  538. name: "example",
  539. mcpServers: { demo: { command: "node", cwd: "${ZCODE_PLUGIN_DATA}" } },
  540. }),
  541. );
  542. await writeFile(
  543. config,
  544. JSON.stringify({
  545. plugins: { dirs: [plugin] },
  546. mcp: { servers: { old: { command: "node" } } },
  547. }),
  548. );
  549. const loader = createMcpConfigurationLoader({
  550. configPaths: [config],
  551. userConfigPath: config,
  552. pluginStorageRoot: join(root, "plugins"),
  553. pluginRoots: [],
  554. workingDirectory: root,
  555. });
  556. const initial = await accept(loader);
  557. const published = initial.configuration.servers["plugin:example:demo"];
  558. expect(published?.type).toBe("stdio");
  559. if (published?.type !== "stdio") throw new Error("missing plugin server");
  560. if (mode === "directory") {
  561. expect(
  562. await stat(published.cwd!)
  563. .then((s) => s.isDirectory())
  564. .catch(() => false),
  565. ).toBe(true);
  566. return;
  567. }
  568. await writeFile(
  569. manifest,
  570. JSON.stringify({
  571. name: "example",
  572. userConfig: { broken: null },
  573. mcpServers: { demo: { command: "node" } },
  574. }),
  575. );
  576. await writeFile(
  577. config,
  578. JSON.stringify({
  579. plugins: { dirs: [plugin] },
  580. mcp: { servers: { fresh: { command: "node" } } },
  581. }),
  582. );
  583. expect(Object.keys((await accept(loader)).configuration.servers)).toEqual(["fresh"]);
  584. } finally {
  585. await rm(root, { recursive: true, force: true });
  586. }
  587. });
  588. it("holds stable execution paths during standalone activation and observes its commit marker", async () => {
  589. const root = await mkdtemp(join(tmpdir(), "mcp-plugin-commit-"));
  590. const config = join(root, "config.json");
  591. const plugin = join(root, "plugin");
  592. const manifest = (command: string) =>
  593. JSON.stringify({ name: "example", mcpServers: { demo: { command } } });
  594. let activation: Awaited<ReturnType<typeof activateDirectoryAtomically>> | undefined;
  595. let source: Awaited<ReturnType<typeof createDynamicMcpConfigSource>> | undefined;
  596. try {
  597. await mkdir(join(plugin, ".zcode-plugin"), { recursive: true });
  598. await writeFile(join(plugin, ".zcode-plugin", "plugin.json"), manifest("old"));
  599. const settings = { plugins: { dirs: [plugin] }, mcp: { servers: {} } };
  600. await writeFile(config, JSON.stringify(settings));
  601. source = await createDynamicMcpConfigSource({
  602. configPaths: [config],
  603. userConfigPath: config,
  604. pluginStorageRoot: root,
  605. pluginRoots: [],
  606. workingDirectory: root,
  607. });
  608. const stable = source.getSnapshot().servers["plugin:example:demo"];
  609. activation = await activateDirectoryAtomically({
  610. targetPath: plugin,
  611. prepare: async (path) => {
  612. await mkdir(join(path, ".zcode-plugin"), { recursive: true });
  613. await writeFile(join(path, ".zcode-plugin", "plugin.json"), manifest("new"));
  614. },
  615. });
  616. const unrelated = Promise.withResolvers<void>();
  617. source.subscribe(() => {
  618. if (source!.getSnapshot().servers.unrelated) unrelated.resolve();
  619. });
  620. await writeFile(
  621. config,
  622. JSON.stringify({ ...settings, mcp: { servers: { unrelated: { command: "node" } } } }),
  623. );
  624. await unrelated.promise;
  625. expect(source.getSnapshot().servers["plugin:example:demo"]).toEqual(stable);
  626. const committed = Promise.withResolvers<void>();
  627. source.subscribe(() => {
  628. const server = source!.getSnapshot().servers["plugin:example:demo"];
  629. if (server?.type === "stdio" && server.command === "new") committed.resolve();
  630. });
  631. await activation.finalize();
  632. activation = undefined;
  633. await committed.promise;
  634. expect(source.getSnapshot().servers["plugin:example:demo"]).toMatchObject({
  635. env: { ZCODE_PLUGIN_ROOT: plugin },
  636. });
  637. } finally {
  638. source?.close();
  639. await activation?.rollback();
  640. await rm(root, { recursive: true, force: true });
  641. }
  642. }, 5000);
  643. it("does not retain a disabled plugin during activation and restores only the rolled-back generation", async () => {
  644. const root = await mkdtemp(join(tmpdir(), "mcp-plugin-rollback-"));
  645. const config = join(root, "config.json");
  646. const plugin = join(root, "plugin");
  647. let activation: Awaited<ReturnType<typeof activateDirectoryAtomically>> | undefined;
  648. try {
  649. await mkdir(join(plugin, ".zcode-plugin"), { recursive: true });
  650. await writeFile(
  651. join(plugin, ".zcode-plugin", "plugin.json"),
  652. JSON.stringify({ name: "example", mcpServers: { demo: { command: "old" } } }),
  653. );
  654. const settings = { plugins: { dirs: [plugin] } };
  655. await writeFile(config, JSON.stringify(settings));
  656. const loader = createMcpConfigurationLoader({
  657. configPaths: [config],
  658. userConfigPath: config,
  659. pluginStorageRoot: root,
  660. pluginRoots: [],
  661. workingDirectory: root,
  662. });
  663. const stable = (await accept(loader)).configuration;
  664. activation = await activateDirectoryAtomically({
  665. targetPath: plugin,
  666. prepare: async (path) => {
  667. await mkdir(join(path, ".zcode-plugin"), { recursive: true });
  668. await writeFile(
  669. join(path, ".zcode-plugin", "plugin.json"),
  670. JSON.stringify({ name: "example", mcpServers: { demo: { command: "new" } } }),
  671. );
  672. },
  673. });
  674. await writeFile(config, JSON.stringify({ plugins: { ...settings.plugins, enabled: false } }));
  675. expect((await accept(loader)).configuration.servers).toEqual({});
  676. await writeFile(config, JSON.stringify(settings));
  677. expect((await accept(loader)).configuration.servers).toEqual({});
  678. await activation.rollback();
  679. activation = undefined;
  680. expect((await accept(loader)).configuration).toEqual(stable);
  681. } finally {
  682. await activation?.rollback();
  683. await rm(root, { recursive: true, force: true });
  684. }
  685. });