mcp-config-loader-rules.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, expect, it, vi } from "vitest";
  5. import type { Logger } from "@zcode/contracts";
  6. import { createMcpConfigurationLoader } from "../src/mcp/config-loader.js";
  7. import { inspectWorkspacePluginRoot } from "../src/plugins/workspace-plugin-declaration/index.js";
  8. /** 存活的另一个进程:父进程一定存在,用它模拟仍在写入的 writer。 */
  9. const LIVE_OWNER_PID = process.ppid;
  10. const SERVER_NAME = "plugin:example:demo";
  11. let root: string;
  12. let config: string;
  13. let plugins: string;
  14. let plugin: string;
  15. beforeEach(async () => {
  16. root = await mkdtemp(join(tmpdir(), "mcp-loader-rules-"));
  17. config = join(root, "config.json");
  18. plugins = join(root, "plugins");
  19. plugin = join(root, "plugin");
  20. await mkdir(plugins);
  21. });
  22. afterEach(() => rm(root, { recursive: true, force: true }));
  23. function createLoader(logger?: Logger) {
  24. return createMcpConfigurationLoader({
  25. configPaths: [config],
  26. userConfigPath: config,
  27. pluginStorageRoot: plugins,
  28. pluginRoots: [],
  29. workingDirectory: root,
  30. ...(logger ? { logger } : {}),
  31. });
  32. }
  33. async function writeManifest(directory: string, value: string): Promise<void> {
  34. await mkdir(join(plugin, directory), { recursive: true });
  35. await writeFile(join(plugin, directory, "plugin.json"), value);
  36. }
  37. it("skips a plugin whose first existing manifest is invalid", async () => {
  38. // 修复前无效的首个 manifest 会回退到下一个目录,与启动时的插件发现结论不同。
  39. await writeManifest(".zcode-plugin", "{ invalid");
  40. await writeManifest(
  41. ".claude-plugin",
  42. JSON.stringify({ name: "example", mcpServers: { demo: { command: "node" } } }),
  43. );
  44. await writeFile(config, JSON.stringify({ plugins: { dirs: [plugin] } }));
  45. const { configuration } = await createLoader().load();
  46. expect(configuration.servers).toEqual({});
  47. });
  48. it("keeps the fallback of the last accepted load, not of an unaccepted one", async () => {
  49. const loader = createLoader();
  50. await writeFile(config, JSON.stringify({ mcp: { servers: { accepted: { command: "a" } } } }));
  51. (await loader.load()).commit();
  52. await writeFile(config, JSON.stringify({ mcp: { servers: { superseded: { command: "b" } } } }));
  53. // 未被采纳的读取(例如 drain 期间又有文件变化)不能改变回退基础。
  54. await loader.load();
  55. await writeFile(config, "{ invalid");
  56. const { configuration } = await loader.load();
  57. expect(Object.keys(configuration.servers)).toEqual(["accepted"]);
  58. });
  59. it("logs plugin MCP diagnostics only when they change between accepted loads", async () => {
  60. const warn = vi.fn();
  61. const loader = createLoader({ warn, debug: vi.fn() } as unknown as Logger);
  62. // 缺少的 user_config 值会生成 plugin_variable_missing 诊断。
  63. const manifest = (key: string) =>
  64. JSON.stringify({
  65. name: "example",
  66. mcpServers: { demo: { command: "node", args: [`\${user_config.${key}}`] } },
  67. });
  68. const diagnosticWarnings = () =>
  69. warn.mock.calls.filter(([message]) => message === "Plugin MCP configuration diagnostic");
  70. await writeManifest(".zcode-plugin", manifest("token_a"));
  71. await writeFile(config, JSON.stringify({ plugins: { dirs: [plugin] } }));
  72. (await loader.load()).commit();
  73. const first = diagnosticWarnings().length;
  74. expect(first).toBeGreaterThan(0);
  75. // 修复前每次重读都把同一条诊断再记一遍,用户频繁保存配置时日志持续增长。
  76. await writeFile(config, JSON.stringify({ plugins: { dirs: [plugin] }, mcp: { servers: {} } }));
  77. (await loader.load()).commit();
  78. expect(diagnosticWarnings()).toHaveLength(first);
  79. await writeManifest(".zcode-plugin", manifest("token_b"));
  80. (await loader.load()).commit();
  81. expect(diagnosticWarnings().length).toBeGreaterThan(first);
  82. });
  83. it("logs each load warning once until it changes, keeping unchanged ones quiet", async () => {
  84. const warn = vi.fn();
  85. const loader = createLoader({ warn, debug: vi.fn() } as unknown as Logger);
  86. const count = (message: string) =>
  87. warn.mock.calls.filter(([logged]) => logged === message).length;
  88. await writeManifest(".zcode-plugin", "{ invalid");
  89. await writeFile(config, JSON.stringify({ plugins: { dirs: [plugin] } }));
  90. (await loader.load()).commit();
  91. expect(count("Plugin manifest invalid")).toBe(1);
  92. // Skill 实时目录读同一批插件,记同样的文案;context 标出读取方。
  93. expect(warn).toHaveBeenCalledWith(
  94. "Plugin manifest invalid",
  95. expect.objectContaining({ reader: "MCP configuration" }),
  96. );
  97. // 修复前 manifest 无效、配置读取失败等 warn 每次重读都再记一遍。
  98. await writeFile(config, JSON.stringify({ plugins: { dirs: [plugin] }, mcp: { servers: {} } }));
  99. (await loader.load()).commit();
  100. expect(count("Plugin manifest invalid")).toBe(1);
  101. // 新出现的 warn 照常记录;没变的那条不因此重记。配置读取失败时沿用上次有效内容,插件仍在。
  102. await writeFile(config, "{ invalid");
  103. (await loader.load()).commit();
  104. expect(count("MCP configuration read failed")).toBe(1);
  105. expect(count("Plugin manifest invalid")).toBe(1);
  106. });
  107. it("does not prepare plugin data directories while MCP is disabled", async () => {
  108. await writeManifest(
  109. ".zcode-plugin",
  110. JSON.stringify({ name: "example", mcpServers: { demo: { command: "node" } } }),
  111. );
  112. await writeFile(
  113. config,
  114. JSON.stringify({ features: { mcp: false }, plugins: { dirs: [plugin] } }),
  115. );
  116. await createLoader().load();
  117. await expect(stat(join(plugins, "data"))).rejects.toMatchObject({ code: "ENOENT" });
  118. });
  119. it("skips the workspace directory when it cannot be inspected", async () => {
  120. const warn = vi.fn();
  121. const filesystem = {
  122. type: "stdio",
  123. command: "npx",
  124. args: ["@modelcontextprotocol/server-filesystem", "/Users/dev"],
  125. };
  126. await writeFile(config, JSON.stringify({ mcp: { servers: { filesystem } } }));
  127. const loader = createMcpConfigurationLoader({
  128. configPaths: [config],
  129. userConfigPath: config,
  130. pluginStorageRoot: plugins,
  131. pluginRoots: [],
  132. // 名称超长使 stat 报 ENAMETOOLONG;修复前非 ENOENT 错误会让整次加载失败。
  133. workingDirectory: join(root, "x".repeat(300)),
  134. logger: { warn, debug: vi.fn(), info: vi.fn(), error: vi.fn() } as unknown as Logger,
  135. });
  136. const loaded = await loader.load();
  137. expect(loaded.configuration.servers.filesystem).toMatchObject({ args: filesystem.args });
  138. // 加载 warn 在结果被采纳时记录。
  139. loaded.commit();
  140. expect(warn).toHaveBeenCalledWith(
  141. "MCP filesystem workspace unavailable",
  142. expect.objectContaining({ error: expect.stringContaining("ENAMETOOLONG") }),
  143. );
  144. });
  145. it("reads installed plugins from the backup while a writer replaces the inventory", async () => {
  146. await writeManifest(
  147. ".zcode-plugin",
  148. JSON.stringify({ name: "example", mcpServers: { demo: { command: "node" } } }),
  149. );
  150. await writeFile(
  151. config,
  152. JSON.stringify({ plugins: { enabledPlugins: { "example@test": true } } }),
  153. );
  154. // Windows 不能覆盖已有文件:writer 先把清单移到 backup,再放入新文件。窗口内正式文件不存在。
  155. await writeFile(
  156. join(plugins, ".installed_plugins.json.backup"),
  157. JSON.stringify({
  158. version: 1,
  159. plugins: [
  160. {
  161. id: "example@test",
  162. name: "example",
  163. marketplace: "test",
  164. version: "1.0.0",
  165. installPath: plugin,
  166. installedAt: "2026-01-01T00:00:00Z",
  167. scope: "user",
  168. },
  169. ],
  170. }),
  171. );
  172. await writeFile(
  173. join(plugins, ".installed_plugins.json.transaction.json"),
  174. JSON.stringify({
  175. version: 2,
  176. stageName: ".installed_plugins.json.stage-next",
  177. transactionId: "inventory",
  178. ownerId: "other-process",
  179. ownerPid: LIVE_OWNER_PID,
  180. hadTarget: true,
  181. mode: "standalone",
  182. }),
  183. );
  184. const { configuration } = await createLoader().load();
  185. expect(configuration.servers[SERVER_NAME]).toMatchObject({ command: "node" });
  186. });
  187. it("ignores plugin directories declared by project configuration", async () => {
  188. // 修复前项目配置的 plugins.dirs 原样进入加载器:未信任仓库可借 inline 插件注册并启动 MCP。
  189. await writeManifest(
  190. ".zcode-plugin",
  191. JSON.stringify({ name: "example", mcpServers: { demo: { command: "node" } } }),
  192. );
  193. const project = join(root, "project.json");
  194. await writeFile(project, JSON.stringify({ plugins: { dirs: [plugin] } }));
  195. const loader = createMcpConfigurationLoader({
  196. configPaths: [project, config],
  197. userConfigPath: config,
  198. pluginStorageRoot: plugins,
  199. pluginRoots: [],
  200. workingDirectory: root,
  201. });
  202. expect((await loader.load()).configuration.servers).toEqual({});
  203. // 用户配置仍可声明插件目录。
  204. await writeFile(config, JSON.stringify({ plugins: { dirs: [plugin] } }));
  205. expect(Object.keys((await loader.load()).configuration.servers)).toEqual([SERVER_NAME]);
  206. });
  207. it("uses private plugin options for live MCP reloads and never repository options", async () => {
  208. const id = "example@inline";
  209. const project = join(root, "workspace", ".zcode", "config.json");
  210. const workspace = join(root, "workspace");
  211. const secrets = join(root, "plugin-secrets.json");
  212. await mkdir(join(workspace, ".zcode"), { recursive: true });
  213. await writeManifest(
  214. ".zcode-plugin",
  215. JSON.stringify({
  216. name: "example",
  217. userConfig: { pythonPath: { type: "file" }, token: { type: "string", sensitive: true } },
  218. mcpServers: {
  219. demo: {
  220. command: "node",
  221. env: { PYTHON: "${user_config.pythonPath}", TOKEN: "${user_config.token}" },
  222. },
  223. },
  224. }),
  225. );
  226. await writeFile(
  227. config,
  228. JSON.stringify({
  229. plugins: {
  230. dirs: [plugin],
  231. options: { [id]: { pythonPath: "user-python", token: "user-token" } },
  232. },
  233. }),
  234. );
  235. await writeFile(
  236. project,
  237. JSON.stringify({
  238. plugins: {
  239. options: { [id]: { pythonPath: "./repository-python", token: "repository-token" } },
  240. },
  241. }),
  242. );
  243. const loader = createMcpConfigurationLoader({
  244. configPaths: [project, config],
  245. userConfigPath: config,
  246. pluginStorageRoot: plugins,
  247. pluginRoots: [],
  248. workingDirectory: workspace,
  249. });
  250. const initial = await loader.load();
  251. expect(initial.configuration.servers[SERVER_NAME]).toMatchObject({
  252. env: { PYTHON: "user-python", TOKEN: "user-token" },
  253. });
  254. expect(initial.files.has(secrets)).toBe(true);
  255. initial.commit();
  256. await writeFile(
  257. secrets,
  258. JSON.stringify({
  259. version: 1,
  260. user: { [id]: { token: "private-user-token" } },
  261. workspaces: { [workspace]: { [id]: { pythonPath: "private-workspace-python" } } },
  262. }),
  263. );
  264. const saved = await loader.load();
  265. expect(saved.configuration.servers[SERVER_NAME]).toMatchObject({
  266. env: { PYTHON: "private-workspace-python", TOKEN: "private-user-token" },
  267. });
  268. saved.commit();
  269. // 私有文件损坏不能复用旧执行参数,更不能回退到仓库值。
  270. await writeFile(secrets, "{ invalid");
  271. const corrupt = await loader.load();
  272. expect(corrupt.configuration.servers[SERVER_NAME]).toMatchObject({
  273. env: { PYTHON: "user-python", TOKEN: "user-token" },
  274. });
  275. corrupt.commit();
  276. await rm(secrets);
  277. expect((await loader.load()).configuration.servers[SERVER_NAME]).toMatchObject({
  278. env: { PYTHON: "user-python", TOKEN: "user-token" },
  279. });
  280. });
  281. it("tags each server with the source of the file that declared it, including fallbacks", async () => {
  282. // 修复前加载器不标来源,工作区 guard 找不到项目声明时把回退文件里的 server 当作非工作区配置放行。
  283. const project = join(root, "zcode.json");
  284. const workspaceConfig = join(root, "workspace-config.json");
  285. const workspaceFallback = join(root, "workspace-agents.json");
  286. const userFallback = join(root, "user-agents.json");
  287. await writeFile(project, JSON.stringify({ mcp: { servers: { declared: { command: "a" } } } }));
  288. await writeFile(
  289. workspaceFallback,
  290. JSON.stringify({ mcpServers: { fallback: { command: "b" } } }),
  291. );
  292. await writeFile(config, JSON.stringify({}));
  293. await writeFile(userFallback, JSON.stringify({ mcpServers: { personal: { command: "c" } } }));
  294. const loader = createMcpConfigurationLoader({
  295. configPaths: [project, workspaceConfig, config],
  296. userConfigPath: config,
  297. fallbackPaths: { [workspaceConfig]: workspaceFallback, [config]: userFallback },
  298. pluginStorageRoot: plugins,
  299. pluginRoots: [],
  300. workingDirectory: root,
  301. });
  302. const { servers } = (await loader.load()).configuration;
  303. expect(servers.declared?.source).toEqual({ kind: "workspace" });
  304. expect(servers.fallback?.source).toEqual({ kind: "workspace" });
  305. expect(servers.personal?.source).toEqual({ kind: "user" });
  306. });
  307. it("watches commit points instead of installed plugin directories, but keeps inline plugin files", async () => {
  308. // 修复前加载器把每个已安装插件的 manifest、MCP 声明和事务记录都放进监听集合:26 个插件约 84 个
  309. // 目录 watcher,新会话要串行等它们就绪。缓存插件目录只由安装流程写入,并以写安装记录结束,
  310. // 监听安装记录即可。inline 插件没有提交点,仍监听它的文件。
  311. const cached = join(plugins, "cache", "test", "example", "1.0.0");
  312. const inline = join(root, "inline");
  313. const declare = async (path: string, name: string) => {
  314. await mkdir(join(path, ".zcode-plugin"), { recursive: true });
  315. await writeFile(
  316. join(path, ".zcode-plugin", "plugin.json"),
  317. JSON.stringify({ name, mcpServers: "./.mcp.json" }),
  318. );
  319. await writeFile(
  320. join(path, ".mcp.json"),
  321. JSON.stringify({ mcpServers: { demo: { command: "node" } } }),
  322. );
  323. };
  324. await declare(cached, "example");
  325. await declare(inline, "local");
  326. const inventory = join(plugins, "installed_plugins.json");
  327. await writeFile(
  328. inventory,
  329. JSON.stringify({
  330. version: 1,
  331. plugins: [
  332. {
  333. id: "example@test",
  334. name: "example",
  335. marketplace: "test",
  336. version: "1.0.0",
  337. installPath: cached,
  338. installedAt: "2026-01-01T00:00:00Z",
  339. scope: "user",
  340. },
  341. ],
  342. }),
  343. );
  344. await writeFile(
  345. config,
  346. JSON.stringify({ plugins: { dirs: [inline], enabledPlugins: { "example@test": true } } }),
  347. );
  348. const loaded = await createLoader().load();
  349. // 两个插件都照常加载,只是缓存插件的文件不进入监听集合。
  350. expect(Object.keys(loaded.configuration.servers).sort()).toEqual([
  351. "plugin:example:demo",
  352. "plugin:local:demo",
  353. ]);
  354. const files = [...loaded.files];
  355. expect(files).toContain(config);
  356. expect(files).toContain(inventory);
  357. expect(files.filter((file) => file.startsWith(join(plugins, "cache")))).toEqual([]);
  358. expect(files).toContain(join(inline, ".zcode-plugin", "plugin.json"));
  359. expect(files).toContain(join(inline, ".mcp.json"));
  360. expect(files).toContain(join(root, ".inline.transaction.json"));
  361. });
  362. it("reads project files with the startup project whitelist", async () => {
  363. // 规则见根目录 docs/security/deep-link-project-trust-boundary.md:项目文件只认扩展声明与启停。
  364. const project = join(root, "workspace", ".zcode", "config.json");
  365. const official = join(root, "official");
  366. await writeManifest(
  367. ".zcode-plugin",
  368. JSON.stringify({ name: "example", mcpServers: { demo: { command: "node" } } }),
  369. );
  370. await mkdir(join(official, ".zcode-plugin"), { recursive: true });
  371. await writeFile(
  372. join(official, ".zcode-plugin", "plugin.json"),
  373. JSON.stringify({ name: "offi", mcpServers: { pong: { command: "node" } } }),
  374. );
  375. await writeFile(
  376. config,
  377. JSON.stringify({
  378. plugins: { dirs: [plugin] },
  379. mcp: { servers: { mine: { command: "node" } } },
  380. }),
  381. );
  382. await mkdir(join(root, "workspace", ".zcode"), { recursive: true });
  383. const loader = createMcpConfigurationLoader({
  384. configPaths: [project, config],
  385. userConfigPath: config,
  386. pluginStorageRoot: plugins,
  387. pluginRoots: [
  388. { rootPath: official, marketplace: "zcode-plugins-official", source: "official" },
  389. ],
  390. defaultEnabledPlugins: new Set(["offi@zcode-plugins-official"]),
  391. workingDirectory: root,
  392. });
  393. const servers = ["mine", "plugin:example:demo", "plugin:offi:pong", "proj"];
  394. // 运行参数不生效:项目不能关掉 MCP、关掉全部插件或隐藏官方插件。
  395. await writeFile(
  396. project,
  397. JSON.stringify({
  398. features: { mcp: false },
  399. plugins: { enabled: false, suppressedBuiltins: ["offi@zcode-plugins-official"] },
  400. mcp: { servers: { proj: { command: "node" } } },
  401. }),
  402. );
  403. const restricted = (await loader.load()).configuration;
  404. expect(restricted.enabled).toBe(true);
  405. expect(Object.keys(restricted.servers).sort()).toEqual(servers);
  406. // 运行参数的非法值在校验前排除,同一文件的 server 照常加载。
  407. await writeFile(
  408. project,
  409. JSON.stringify({ storage: 5, mcp: { servers: { proj: { command: "node" } } } }),
  410. );
  411. expect(Object.keys((await loader.load()).configuration.servers).sort()).toEqual(servers);
  412. });
  413. it("keeps user fields that a project file does not declare", async () => {
  414. const project = join(root, "workspace", ".zcode", "config.json");
  415. await mkdir(join(root, "workspace", ".zcode"), { recursive: true });
  416. await writeFile(config, JSON.stringify({ features: { mcp: false } }));
  417. await writeFile(project, JSON.stringify({ plugins: { enabledPlugins: { "x@test": true } } }));
  418. const { configuration } = await createMcpConfigurationLoader({
  419. configPaths: [project, config],
  420. userConfigPath: config,
  421. pluginStorageRoot: plugins,
  422. pluginRoots: [],
  423. workingDirectory: root,
  424. }).load();
  425. // 与 createConfig 相同:项目层没声明 features,不能冲掉用户层的关闭。
  426. expect(configuration.enabled).toBe(false);
  427. });
  428. it("keeps a trusted workspace plugin only while its declarations match the trusted digest", async () => {
  429. // docs/plugins/workspace-plugin-dir-trust.md:项目目录插件只沿用会话启动时已准入的那批;
  430. // 会话中途声明变了(例如 git pull)就撤下它的 MCP,不能沿用旧信任执行新声明。
  431. const manifest = (command: string) =>
  432. JSON.stringify({ name: "example", mcpServers: { demo: { command } } });
  433. await writeManifest(".zcode-plugin", manifest("node"));
  434. await writeFile(config, JSON.stringify({}));
  435. const inspected = await inspectWorkspacePluginRoot({ workspaceRoot: root, rootPath: plugin });
  436. const loader = createMcpConfigurationLoader({
  437. configPaths: [config],
  438. userConfigPath: config,
  439. pluginStorageRoot: plugins,
  440. pluginRoots: [
  441. {
  442. rootPath: plugin,
  443. marketplace: "inline",
  444. source: "inline",
  445. workspaceTrust: {
  446. state: "trusted",
  447. pluginRoot: inspected!.pluginRoot,
  448. declarationDigest: inspected!.declarationDigest,
  449. },
  450. },
  451. ],
  452. workingDirectory: root,
  453. });
  454. expect(Object.keys((await loader.load()).configuration.servers)).toEqual([SERVER_NAME]);
  455. await writeManifest(".zcode-plugin", manifest("python"));
  456. expect((await loader.load()).configuration.servers).toEqual({});
  457. });
  458. it("never loads a pending workspace plugin root in an open session", async () => {
  459. await writeManifest(
  460. ".zcode-plugin",
  461. JSON.stringify({ name: "example", mcpServers: { demo: { command: "node" } } }),
  462. );
  463. await writeFile(config, JSON.stringify({}));
  464. const loader = createMcpConfigurationLoader({
  465. configPaths: [config],
  466. userConfigPath: config,
  467. pluginStorageRoot: plugins,
  468. pluginRoots: [
  469. {
  470. rootPath: plugin,
  471. marketplace: "inline",
  472. source: "inline",
  473. workspaceTrust: { state: "pending", pluginRoot: "plugin", declarationDigest: "0".repeat(64) },
  474. },
  475. ],
  476. workingDirectory: root,
  477. });
  478. expect((await loader.load()).configuration.servers).toEqual({});
  479. });