mcp-server-wait-wire.test.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // ToolSearch 动态 MCP 端到端发包:runtime 实际产出的请求经 Anthropic SDK 序列化后的工具定义与引用。
  2. // 规格见 docs/mcp-async-tool-catalog-cache.md §5;server 就绪由等待端口手动触发,不用 sleep。
  3. import { createAnthropic } from "@ai-sdk/anthropic";
  4. import { generateText } from "ai";
  5. import { expect, it } from "vitest";
  6. import {
  7. createSessionId,
  8. type McpPort,
  9. type McpServerStatus,
  10. type McpServerToolSnapshot,
  11. type Model,
  12. type ModelRequest,
  13. toolSearchNameForMode,
  14. } from "@zcode/contracts";
  15. import { toAiSdkMessages } from "../src/model/transform.js";
  16. import { toAiSdkTools } from "../src/model/tool-transform.js";
  17. import { toolSearchHeaders } from "../src/model/tool-search.js";
  18. import { createTestAgentRuntime } from "../../core/tests/test-agent-runtime.js";
  19. import { createTestSessionEventStore } from "../../core/tests/test-event-store.js";
  20. import { createTestModelFactory } from "../../core/tests/test-runtime-model.js";
  21. const MCP_TOOL = "mcp__local__ping";
  22. const STATUS_REMINDER = "The following MCP servers are still connecting —";
  23. type WireTool = { name: string; input_schema?: unknown; defer_loading?: boolean };
  24. type Wire = { tools?: WireTool[]; messages: unknown[] };
  25. function mcpStatus(status: McpServerStatus["status"]): McpServerStatus {
  26. return { status, transport: "stdio", toolCount: 0, updatedAt: "now" };
  27. }
  28. async function toWire(request: ModelRequest): Promise<Wire> {
  29. let wire: Wire | undefined;
  30. const provider = createAnthropic({
  31. apiKey: "test",
  32. fetch: async (_url, init) => {
  33. wire = JSON.parse(String(init?.body));
  34. return new Response(
  35. JSON.stringify({ error: { type: "invalid_request_error", message: "capture" } }),
  36. { status: 400, headers: { "content-type": "application/json" } },
  37. );
  38. },
  39. });
  40. const options = {
  41. providerKind: "anthropic" as const,
  42. toolSearchEnabled: request.toolSearchEnabled ?? false,
  43. };
  44. await expect(
  45. generateText({
  46. model: provider("test"),
  47. maxRetries: 0,
  48. headers: toolSearchHeaders(undefined, options.toolSearchEnabled),
  49. tools: toAiSdkTools(request.tools ?? [], options),
  50. messages: toAiSdkMessages(request.messages, options),
  51. }),
  52. ).rejects.toBeDefined();
  53. return wire!;
  54. }
  55. async function runWaitThenReady(mode: "local" | "native") {
  56. const snapshot: Record<string, McpServerToolSnapshot> = {
  57. local: { status: mcpStatus("connecting") },
  58. };
  59. const port: McpPort = {
  60. connectConfiguredServers: () => new Promise(() => {}),
  61. connectServer: async () => mcpStatus("connected"),
  62. disconnectServer: async () => undefined,
  63. status: async () => ({}),
  64. listTools: async () => [],
  65. callTool: async () => ({ content: [{ type: "text", text: "pong" }] }),
  66. close: async () => {},
  67. getToolSnapshot: () => snapshot,
  68. // 等待返回时 server 已就绪:本批结果之后的下一次正常请求才应用新列表。
  69. waitForServer: async () => {
  70. snapshot.local = {
  71. status: mcpStatus("connected"),
  72. tools: [
  73. {
  74. serverName: "local",
  75. toolName: "ping",
  76. inputSchema: { type: "object", properties: {} },
  77. },
  78. ],
  79. toolsVersion: "c1",
  80. };
  81. return { timedOut: false };
  82. },
  83. };
  84. const requests: ModelRequest[] = [];
  85. const factory = createTestModelFactory({
  86. async generateText(request) {
  87. requests.push(request);
  88. const call = [
  89. {
  90. id: "search-1",
  91. name: "ToolSearch",
  92. input: { query: `select:${MCP_TOOL}`, max_results: 5 },
  93. },
  94. mode === "native"
  95. ? { id: "ping-1", name: MCP_TOOL, input: {} }
  96. : { id: "ping-1", name: "DeferredToolCall", input: { name: MCP_TOOL, input: {} } },
  97. ][requests.length - 1];
  98. return (
  99. call
  100. ? { text: "", finishReason: "tool-calls", usage: {}, toolCalls: [call] }
  101. : { text: "done", finishReason: "stop", usage: {} }
  102. ) as never;
  103. },
  104. });
  105. const wrap = (model: Model): Model => ({
  106. ...model,
  107. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  108. bind: (options) => wrap(model.bind(options)),
  109. });
  110. const runtime = createTestAgentRuntime(
  111. createSessionId(`mcp-wait-wire-${mode}`),
  112. {
  113. mode: "yolo",
  114. modelStreaming: "off",
  115. titleGeneration: { enabled: false },
  116. toolSearch: { mode },
  117. mcp: { enabled: true, servers: { local: { type: "stdio", command: "node", args: [] } } },
  118. },
  119. {
  120. eventStore: createTestSessionEventStore(),
  121. mcpPort: port,
  122. mcpStartupPolicy: "background",
  123. modelFactory: (input) => wrap(factory(input)),
  124. },
  125. );
  126. await runtime.executeTurn("needs local");
  127. await runtime.closeBrowserSession();
  128. expect(requests).toHaveLength(3);
  129. return Promise.all(requests.map(toWire));
  130. }
  131. it.each(["local", "native"] as const)(
  132. "searches pending MCP and calls the ready tool with the expected wire protocol (%s)",
  133. async (mode) => {
  134. const [first, second, third] = await runWaitThenReady(mode);
  135. const names = (wire: Wire) => wire.tools?.map((entry) => entry.name) ?? [];
  136. for (const wire of [first!, second!, third!]) {
  137. expect(names(wire)).not.toContain("WaitForMcpServers");
  138. expect(JSON.stringify(wire.messages)).not.toContain("WaitForMcpServers");
  139. expect(JSON.stringify(wire.messages)).not.toContain("MCP server status for this request:");
  140. }
  141. // Local 的控制工具以 LocalToolSearch 发送;schema 入口不随改名变化。
  142. expect(
  143. first!.tools?.find((entry) => entry.name === toolSearchNameForMode(mode))?.input_schema,
  144. ).toMatchObject({ required: ["query", "max_results"] });
  145. expect(names(first!)).not.toContain(MCP_TOOL);
  146. expect(JSON.stringify(first!.messages)).toContain(STATUS_REMINDER);
  147. const text = JSON.stringify(second!.messages);
  148. if (mode === "native") {
  149. expect(second!.tools?.find((entry) => entry.name === MCP_TOOL)?.defer_loading).toBe(true);
  150. expect(text).toContain(`"tool_name":"${MCP_TOOL}"`);
  151. } else {
  152. expect(names(second!)).not.toContain(MCP_TOOL);
  153. expect(names(second!)).toContain("DeferredToolCall");
  154. expect(text).toContain("<function>");
  155. expect(text).toContain(MCP_TOOL);
  156. }
  157. expect(JSON.stringify(third!.messages)).toContain("pong");
  158. },
  159. );
  160. // ToolSearch 关闭时没有连接中公告:WaitForMcpServers 是唯一提示,定义字节固定、发送后保持。
  161. it("offers WaitForMcpServers without ToolSearch and keeps it after the server connects (off)", async () => {
  162. const snapshot: Record<string, McpServerToolSnapshot> = {
  163. local: { status: mcpStatus("connecting") },
  164. };
  165. const port: McpPort = {
  166. connectConfiguredServers: () => new Promise(() => {}),
  167. connectServer: async () => mcpStatus("connected"),
  168. disconnectServer: async () => undefined,
  169. status: async () => ({}),
  170. listTools: async () => [],
  171. callTool: async () => ({ content: [{ type: "text", text: "pong" }] }),
  172. close: async () => {},
  173. getToolSnapshot: () => snapshot,
  174. waitForServer: async () => {
  175. snapshot.local = {
  176. status: mcpStatus("connected"),
  177. tools: [
  178. {
  179. serverName: "local",
  180. toolName: "ping",
  181. inputSchema: { type: "object", properties: {} },
  182. },
  183. ],
  184. toolsVersion: "c1",
  185. };
  186. return { timedOut: false };
  187. },
  188. };
  189. const requests: ModelRequest[] = [];
  190. const factory = createTestModelFactory({
  191. async generateText(request) {
  192. requests.push(request);
  193. const call = [
  194. { id: "wait-1", name: "WaitForMcpServers", input: {} },
  195. { id: "ping-1", name: MCP_TOOL, input: {} },
  196. ][requests.length - 1];
  197. return (
  198. call
  199. ? { text: "", finishReason: "tool-calls", usage: {}, toolCalls: [call] }
  200. : { text: "done", finishReason: "stop", usage: {} }
  201. ) as never;
  202. },
  203. });
  204. const runtime = createTestAgentRuntime(
  205. createSessionId("mcp-wait-wire-off"),
  206. {
  207. mode: "yolo",
  208. modelStreaming: "off",
  209. titleGeneration: { enabled: false },
  210. toolSearch: { mode: "off" },
  211. mcp: { enabled: true, servers: { local: { type: "stdio", command: "node", args: [] } } },
  212. },
  213. {
  214. eventStore: createTestSessionEventStore(),
  215. mcpPort: port,
  216. mcpStartupPolicy: "background",
  217. modelFactory: factory,
  218. },
  219. );
  220. await runtime.executeTurn("needs local");
  221. await runtime.closeBrowserSession();
  222. expect(requests).toHaveLength(3);
  223. const [first, second, third] = await Promise.all(requests.map(toWire));
  224. const wait = first!.tools?.find((entry) => entry.name === "WaitForMcpServers") as
  225. | (WireTool & { description?: string })
  226. | undefined;
  227. expect(JSON.stringify(wait?.input_schema)).toBe(
  228. '{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"servers":{"description":"Server names to wait for (default: all pending)","type":"array","items":{"type":"string"}}},"additionalProperties":false}',
  229. );
  230. expect(wait?.description).toMatch(/^Wait for MCP servers that are still connecting/);
  231. expect(JSON.stringify(first!.messages)).not.toContain(STATUS_REMINDER);
  232. // 结果按分组逐行给模型;就绪时不是错误结果。
  233. expect(JSON.stringify(second!.messages)).toContain(
  234. "ready: true\\nConnected (their tools are now available — call them directly): local",
  235. );
  236. expect(JSON.stringify(second!.messages)).not.toContain('"is_error":true');
  237. // 连上之后 tools 段保留 WaitForMcpServers,只在末尾增加 MCP 工具。
  238. const names = (wire: Wire) => wire.tools?.map((entry) => entry.name) ?? [];
  239. expect(names(second!)).toEqual([...names(first!), MCP_TOOL]);
  240. expect(JSON.stringify(third!.messages)).toContain("pong");
  241. });