mcp-protocol.test.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 { createMcpAdapter } from "@zcode/adapters/mcp";
  14. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  15. describe("mcp protocol contracts", () => {
  16. it("registers mcp/list", () => {
  17. expect(zcodeProtocolMethods.mcpList).toBe("mcp/list");
  18. expect(zcodeProtocolSessionMethodContracts[zcodeProtocolMethods.mcpList]).toBeDefined();
  19. });
  20. it("parses an MCP status snapshot", () => {
  21. const parsed = zcodeMcpListResultSchema.parse({
  22. statuses: {
  23. filesystem: {
  24. status: "disconnected",
  25. transport: "stdio",
  26. toolCount: 0,
  27. updatedAt: "2026-06-23T00:00:00.000Z",
  28. },
  29. },
  30. });
  31. expect(parsed.statuses.filesystem?.status).toBe("disconnected");
  32. });
  33. it("defaults mcp/list mode to connect and accepts status-only mode", () => {
  34. expect(
  35. zcodeMcpListParamsSchema.parse({
  36. workspace: {
  37. workspaceKey: "/tmp/project",
  38. workspacePath: "/tmp/project",
  39. },
  40. }).mode,
  41. ).toBe("connect");
  42. expect(
  43. zcodeMcpListParamsSchema.parse({
  44. workspace: {
  45. workspaceKey: "/tmp/project",
  46. workspacePath: "/tmp/project",
  47. },
  48. mode: "status",
  49. }).mode,
  50. ).toBe("status");
  51. });
  52. it("rejects invalid MCP status values", () => {
  53. expect(() =>
  54. zcodeMcpListResultSchema.parse({
  55. statuses: {
  56. broken: {
  57. status: "unknown",
  58. transport: "stdio",
  59. toolCount: 0,
  60. updatedAt: "2026-06-23T00:00:00.000Z",
  61. },
  62. },
  63. }),
  64. ).toThrow();
  65. });
  66. it("parses HTTP MCP OAuth client credentials in protocol params", () => {
  67. const parsed = zcodeMcpListParamsSchema.parse({
  68. workspace: {
  69. workspaceKey: "/tmp/project",
  70. workspacePath: "/tmp/project",
  71. },
  72. mcpServers: [
  73. {
  74. name: "protected",
  75. type: "http",
  76. url: "https://mcp.example.test/mcp",
  77. headers: [],
  78. oauth: {
  79. type: "client_credentials",
  80. clientId: "zcode-client",
  81. clientSecret: "secret",
  82. scope: "mcp:tools",
  83. },
  84. },
  85. ],
  86. });
  87. expect(parsed.mcpServers?.[0]).toMatchObject({
  88. name: "protected",
  89. oauth: {
  90. type: "client_credentials",
  91. clientId: "zcode-client",
  92. },
  93. });
  94. });
  95. it("parses HTTP MCP OAuth authorization code in protocol params", () => {
  96. const parsed = zcodeMcpListParamsSchema.parse({
  97. workspace: {
  98. workspaceKey: "/tmp/project",
  99. workspacePath: "/tmp/project",
  100. },
  101. mcpServers: [
  102. {
  103. name: "figma",
  104. type: "http",
  105. url: "https://mcp.figma.com/mcp",
  106. headers: [],
  107. oauth: {
  108. type: "authorization_code",
  109. clientName: "ZCode",
  110. redirectPath: "/oauth/callback/mcp/figma",
  111. scope: "mcp:connect",
  112. },
  113. },
  114. ],
  115. });
  116. expect(parsed.mcpServers?.[0]).toMatchObject({
  117. name: "figma",
  118. oauth: {
  119. type: "authorization_code",
  120. clientName: "ZCode",
  121. redirectPath: "/oauth/callback/mcp/figma",
  122. scope: "mcp:connect",
  123. },
  124. });
  125. });
  126. });
  127. // Bugfix 回归:设置页刷新的 mcp/list 必须带 revalidate,否则进程级 `protocol-settings` lease
  128. // 会命中连接池里的旧 entry 并回放陈旧快照(由 adapter 统一校验与恢复)。
  129. describe("mcp/list connection revalidation", () => {
  130. it.each([undefined, "404"])(
  131. "projects internal diagnostics out of strict status responses: %s",
  132. async (errorCode) => {
  133. const root = await mkdtemp(join(tmpdir(), "zcode-mcp-status-projection-"));
  134. const adapter = createMcpAdapter();
  135. await adapter.connectServer("disabled", { type: "stdio", command: "node", enabled: false });
  136. const statuses = await adapter.status();
  137. // 使用真实 adapter 的状态形状,包括值为 undefined 但实际存在的内部键。
  138. statuses.disabled!.errorCode = errorCode;
  139. const context = {
  140. deps: {
  141. env: { ...process.env, ZCODE_STORAGE_DIR: join(root, "cli") },
  142. mcpPort: {
  143. status: async () => statuses,
  144. listTools: () => adapter.listTools(),
  145. connectConfiguredServers: async () => ({ statuses, tools: [] }),
  146. // 设置页读取会经过工作区信任 guard:被拦截的声明在连接准入处断开。
  147. disconnectServer: async () => undefined,
  148. },
  149. },
  150. } as unknown as ZCodeProtocolAgentServerContext;
  151. try {
  152. for (const mode of ["connect", "status"] as const) {
  153. const result = await listMcpServers(context, {
  154. workspace: { workspaceKey: root, workspacePath: root },
  155. mcpServers: [],
  156. mode,
  157. });
  158. expect(result.statuses.disabled).toMatchObject({
  159. status: "disabled",
  160. transport: "stdio",
  161. toolCount: 0,
  162. });
  163. expect(result.statuses.disabled).not.toHaveProperty("errorCode");
  164. }
  165. const connecting = Promise.withResolvers<{ statuses: typeof statuses; tools: [] }>();
  166. context.deps.mcpPort!.connectConfiguredServers = () => connecting.promise;
  167. statuses.disabled!.status = "connecting";
  168. statuses.disabled!.authorization = {
  169. type: "oauth_authorization_code",
  170. authorizationUrl: "https://auth.example.test/authorize",
  171. startedAt: new Date().toISOString(),
  172. };
  173. try {
  174. const pending = await listMcpServers(context, {
  175. workspace: { workspaceKey: root, workspacePath: root },
  176. mcpServers: [],
  177. mode: "connect",
  178. });
  179. expect(pending.statuses.disabled).toMatchObject({
  180. status: "connecting",
  181. authorization: statuses.disabled!.authorization,
  182. });
  183. expect(pending.statuses.disabled).not.toHaveProperty("errorCode");
  184. } finally {
  185. connecting.resolve({ statuses, tools: [] });
  186. }
  187. } finally {
  188. await adapter.close();
  189. await rm(root, { force: true, recursive: true });
  190. }
  191. },
  192. );
  193. it("asks the pool to revalidate on the default connect mode and skips it for status mode", async () => {
  194. const root = await mkdtemp(join(tmpdir(), "zcode-mcp-list-revalidate-"));
  195. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  196. process.env.ZCODE_STORAGE_DIR = join(root, "cli");
  197. const connectConfiguredServers = vi.fn(async () => ({ statuses: {}, tools: [] }));
  198. const status = vi.fn(async () => ({}));
  199. const mcpPort = {
  200. callTool: vi.fn(),
  201. close: vi.fn(async () => undefined),
  202. connectConfiguredServers,
  203. connectServer: vi.fn(),
  204. disconnectServer: vi.fn(),
  205. listTools: vi.fn(async () => []),
  206. status,
  207. } as unknown as McpPort;
  208. const context = {
  209. deps: { env: process.env, mcpPort },
  210. } as unknown as ZCodeProtocolAgentServerContext;
  211. const params = {
  212. mcpServers: [],
  213. workspace: { workspaceKey: root, workspacePath: root },
  214. };
  215. try {
  216. await listMcpServers(context, params);
  217. expect(connectConfiguredServers).toHaveBeenCalledWith(
  218. expect.anything(),
  219. expect.objectContaining({ revalidate: true }),
  220. );
  221. connectConfiguredServers.mockClear();
  222. await listMcpServers(context, { ...params, mode: "status" });
  223. expect(connectConfiguredServers).not.toHaveBeenCalled();
  224. } finally {
  225. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  226. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  227. await rm(root, { force: true, recursive: true });
  228. }
  229. });
  230. });
  231. import { convertToZCodeAgentMcpServer, zcodeProtocolMcpServerSchema } from "@zcode/shared";
  232. import { protocolMcpServersToRuntimeMcpConfig } from "../src/zcode-protocol/protocol-mcp-config.js";
  233. it("preserves workspace provenance and cwd from Host DTO to runtime; rejects arbitrary runtime source", () => {
  234. const dto = convertToZCodeAgentMcpServer(
  235. "probe",
  236. { type: "stdio", command: "node", cwd: "tools", args: ["server.mjs"], env: { TEST: "1" } },
  237. "workspace",
  238. );
  239. const parsed = zcodeProtocolMcpServerSchema.parse(dto);
  240. expect(protocolMcpServersToRuntimeMcpConfig([parsed])?.servers.probe).toMatchObject({
  241. source: { kind: "workspace" },
  242. cwd: "tools",
  243. env: { TEST: "1" },
  244. });
  245. expect(zcodeProtocolMcpServerSchema.safeParse({ ...dto, source: { kind: "user" } }).success).toBe(
  246. false,
  247. );
  248. });