mcp-protocol.test.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import type { McpPort } from "@zcode/contracts";
  5. import { describe, expect, it, vi } from "vitest";
  6. import {
  7. zcodeMcpListResultSchema,
  8. zcodeMcpListParamsSchema,
  9. zcodeProtocolMethods,
  10. zcodeProtocolSessionMethodContracts,
  11. } from "@zcode/shared";
  12. import { listMcpServers } from "../src/zcode-protocol/mcp.js";
  13. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  14. describe("mcp protocol contracts", () => {
  15. it("registers mcp/list", () => {
  16. expect(zcodeProtocolMethods.mcpList).toBe("mcp/list");
  17. expect(zcodeProtocolSessionMethodContracts[zcodeProtocolMethods.mcpList]).toBeDefined();
  18. });
  19. it("parses an MCP status snapshot", () => {
  20. const parsed = zcodeMcpListResultSchema.parse({
  21. statuses: {
  22. filesystem: {
  23. status: "disconnected",
  24. transport: "stdio",
  25. toolCount: 0,
  26. updatedAt: "2026-06-23T00:00:00.000Z",
  27. },
  28. },
  29. });
  30. expect(parsed.statuses.filesystem?.status).toBe("disconnected");
  31. });
  32. it("defaults mcp/list mode to connect and accepts status-only mode", () => {
  33. expect(
  34. zcodeMcpListParamsSchema.parse({
  35. workspace: {
  36. workspaceKey: "/tmp/project",
  37. workspacePath: "/tmp/project",
  38. },
  39. }).mode,
  40. ).toBe("connect");
  41. expect(
  42. zcodeMcpListParamsSchema.parse({
  43. workspace: {
  44. workspaceKey: "/tmp/project",
  45. workspacePath: "/tmp/project",
  46. },
  47. mode: "status",
  48. }).mode,
  49. ).toBe("status");
  50. });
  51. it("rejects invalid MCP status values", () => {
  52. expect(() =>
  53. zcodeMcpListResultSchema.parse({
  54. statuses: {
  55. broken: {
  56. status: "unknown",
  57. transport: "stdio",
  58. toolCount: 0,
  59. updatedAt: "2026-06-23T00:00:00.000Z",
  60. },
  61. },
  62. }),
  63. ).toThrow();
  64. });
  65. it("parses HTTP MCP OAuth client credentials in protocol params", () => {
  66. const parsed = zcodeMcpListParamsSchema.parse({
  67. workspace: {
  68. workspaceKey: "/tmp/project",
  69. workspacePath: "/tmp/project",
  70. },
  71. mcpServers: [
  72. {
  73. name: "protected",
  74. type: "http",
  75. url: "https://mcp.example.test/mcp",
  76. headers: [],
  77. oauth: {
  78. type: "client_credentials",
  79. clientId: "zcode-client",
  80. clientSecret: "secret",
  81. scope: "mcp:tools",
  82. },
  83. },
  84. ],
  85. });
  86. expect(parsed.mcpServers?.[0]).toMatchObject({
  87. name: "protected",
  88. oauth: {
  89. type: "client_credentials",
  90. clientId: "zcode-client",
  91. },
  92. });
  93. });
  94. it("parses HTTP MCP OAuth authorization code in protocol params", () => {
  95. const parsed = zcodeMcpListParamsSchema.parse({
  96. workspace: {
  97. workspaceKey: "/tmp/project",
  98. workspacePath: "/tmp/project",
  99. },
  100. mcpServers: [
  101. {
  102. name: "figma",
  103. type: "http",
  104. url: "https://mcp.figma.com/mcp",
  105. headers: [],
  106. oauth: {
  107. type: "authorization_code",
  108. clientName: "ZCode",
  109. redirectPath: "/oauth/callback/mcp/figma",
  110. scope: "mcp:connect",
  111. },
  112. },
  113. ],
  114. });
  115. expect(parsed.mcpServers?.[0]).toMatchObject({
  116. name: "figma",
  117. oauth: {
  118. type: "authorization_code",
  119. clientName: "ZCode",
  120. redirectPath: "/oauth/callback/mcp/figma",
  121. scope: "mcp:connect",
  122. },
  123. });
  124. });
  125. });
  126. // Bugfix 回归:设置页刷新的 mcp/list 必须带 revalidate,否则进程级 `protocol-settings` lease
  127. // 会命中连接池里的旧 entry 并回放陈旧快照(见 adapters/src/mcp/pool.ts revalidateEntry)。
  128. describe("mcp/list connection revalidation", () => {
  129. it("asks the pool to revalidate on the default connect mode and skips it for status mode", async () => {
  130. const root = await mkdtemp(join(tmpdir(), "zcode-mcp-list-revalidate-"));
  131. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  132. process.env.ZCODE_STORAGE_DIR = join(root, "cli");
  133. const connectConfiguredServers = vi.fn(async () => ({ statuses: {}, tools: [] }));
  134. const status = vi.fn(async () => ({}));
  135. const mcpPort = {
  136. callTool: vi.fn(),
  137. close: vi.fn(async () => undefined),
  138. connectConfiguredServers,
  139. connectServer: vi.fn(),
  140. disconnectServer: vi.fn(),
  141. listTools: vi.fn(async () => []),
  142. status,
  143. } as unknown as McpPort;
  144. const context = {
  145. deps: { env: process.env, mcpPort },
  146. } as unknown as ZCodeProtocolAgentServerContext;
  147. const params = {
  148. mcpServers: [],
  149. workspace: { workspaceKey: root, workspacePath: root },
  150. };
  151. try {
  152. await listMcpServers(context, params);
  153. expect(connectConfiguredServers).toHaveBeenCalledWith(
  154. expect.anything(),
  155. expect.objectContaining({ revalidate: true }),
  156. );
  157. connectConfiguredServers.mockClear();
  158. await listMcpServers(context, { ...params, mode: "status" });
  159. expect(connectConfiguredServers).not.toHaveBeenCalled();
  160. } finally {
  161. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  162. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  163. await rm(root, { force: true, recursive: true });
  164. }
  165. });
  166. });
  167. import { convertToZCodeAgentMcpServer, zcodeProtocolMcpServerSchema } from "@zcode/shared";
  168. import { protocolMcpServersToRuntimeMcpConfig } from "../src/zcode-protocol/protocol-mcp-config.js";
  169. it("preserves workspace provenance and cwd from Host DTO to runtime; rejects arbitrary runtime source", () => {
  170. const dto = convertToZCodeAgentMcpServer(
  171. "probe",
  172. { type: "stdio", command: "node", cwd: "tools", args: ["server.mjs"], env: { TEST: "1" } },
  173. "workspace",
  174. );
  175. const parsed = zcodeProtocolMcpServerSchema.parse(dto);
  176. expect(protocolMcpServersToRuntimeMcpConfig([parsed])?.servers.probe).toMatchObject({
  177. source: { kind: "workspace" },
  178. cwd: "tools",
  179. env: { TEST: "1" },
  180. });
  181. expect(zcodeProtocolMcpServerSchema.safeParse({ ...dto, source: { kind: "user" } }).success).toBe(
  182. false,
  183. );
  184. });