mcp-config-source.test.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { EventEmitter } from "node:events";
  2. import { mkdtemp, writeFile, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { expect, it, vi } from "vitest";
  6. import { createDynamicMcpConfigSource } from "../src/mcp/config-source.js";
  7. const { watchers } = vi.hoisted(() => ({ watchers: [] as EventEmitter[] }));
  8. vi.mock("chokidar", () => ({
  9. watch: () => {
  10. const watcher = Object.assign(new EventEmitter(), { close: vi.fn(async () => {}) });
  11. watchers.push(watcher);
  12. queueMicrotask(() => watcher.emit("ready"));
  13. return watcher;
  14. },
  15. }));
  16. it.each([null, undefined, 0])(
  17. "reloads the watched anchor on raw events with filename %s",
  18. async (filename) => {
  19. const root = await mkdtemp(join(tmpdir(), "mcp-raw-event-"));
  20. const config = join(root, "config.json");
  21. await writeFile(config, JSON.stringify({ mcp: { servers: {} } }));
  22. const source = await createDynamicMcpConfigSource({
  23. configPaths: [config],
  24. userConfigPath: config,
  25. pluginStorageRoot: join(root, "plugins"),
  26. pluginRoots: [],
  27. workingDirectory: root,
  28. });
  29. try {
  30. const changed = Promise.withResolvers<void>();
  31. source.subscribe(() => {
  32. if (source.getSnapshot().servers.fresh) changed.resolve();
  33. });
  34. await writeFile(config, JSON.stringify({ mcp: { servers: { fresh: { command: "node" } } } }));
  35. expect(() => {
  36. for (const watcher of watchers)
  37. watcher.emit("raw", "change", filename, { watchedPath: root });
  38. }).not.toThrow();
  39. await changed.promise;
  40. expect(source.getSnapshot().servers.fresh).toMatchObject({ command: "node" });
  41. } finally {
  42. source.close();
  43. await rm(root, { recursive: true, force: true });
  44. watchers.length = 0;
  45. }
  46. },
  47. );