subagent-mcp-wait.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import { describe, expect, it, vi } from "vitest";
  2. // 子 agent 启动前的 MCP 等待集合:mcpServers 与 tools 引用的 server 的并集。
  3. import {
  4. createSessionId,
  5. modelMessageContentToText,
  6. type McpServerToolSnapshot,
  7. type ModelRequest,
  8. } from "@zcode/contracts";
  9. import { createSnapshotMcpPort, mcpStatus, stdioServer, tool } from "./mcp-runtime-fixture.js";
  10. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  11. import { createTestSessionEventStore } from "./test-event-store.js";
  12. import { createTestModelFactory } from "./test-runtime-model.js";
  13. const CHILD_AGENT_NAME = "mcp-agent";
  14. const CHILD_REPLY = "mcp-agent 已启动。";
  15. const PARENT_FINAL_REPLY = "父 agent 收到了结果。";
  16. const CHILD_SERVER_WAIT_MS = 30_000;
  17. const MISSING_TOOL_ERROR = "Required MCP tool is not available in the parent MCP snapshot";
  18. type WaitForServer = (name: string) => Promise<{ timedOut: boolean }>;
  19. function requestToolNames(request: ModelRequest | undefined): string[] {
  20. return request?.tools?.map((entry) => entry.name) ?? [];
  21. }
  22. async function runChild(input: {
  23. label: string;
  24. servers: readonly string[];
  25. snapshot: Record<string, McpServerToolSnapshot>;
  26. tools: readonly string[];
  27. waitForServer: WaitForServer;
  28. }) {
  29. const parentRequests: ModelRequest[] = [];
  30. const childRequests: ModelRequest[] = [];
  31. const runtime = createTestAgentRuntime(
  32. createSessionId(`subagent-mcp-wait-${input.label}`),
  33. {
  34. mcp: {
  35. enabled: true,
  36. servers: Object.fromEntries(input.servers.map((name) => [name, stdioServer()])),
  37. },
  38. mode: "build",
  39. workingDirectory: "/workspace/project",
  40. subagents: {
  41. profiles: [
  42. {
  43. name: CHILD_AGENT_NAME,
  44. description: "只在 tools 里声明 MCP 工具的 agent。",
  45. source: "project",
  46. systemPrompt: "使用声明的 MCP 工具。",
  47. tools: [...input.tools],
  48. },
  49. ],
  50. },
  51. },
  52. {
  53. eventStore: createTestSessionEventStore(),
  54. mcpPort: createSnapshotMcpPort(input.snapshot, { waitForServer: input.waitForServer }),
  55. mcpStartupPolicy: "background",
  56. modelFactory: createTestModelFactory({
  57. async generateText(request: ModelRequest) {
  58. if (!requestToolNames(request).includes("Agent")) {
  59. childRequests.push(request);
  60. return { finishReason: "stop", text: CHILD_REPLY, usage: {} };
  61. }
  62. parentRequests.push(request);
  63. if (parentRequests.length > 1) {
  64. return { finishReason: "stop", text: PARENT_FINAL_REPLY, usage: {} };
  65. }
  66. return {
  67. finishReason: "tool-calls",
  68. text: "",
  69. toolCalls: [
  70. {
  71. id: "call_mcp_agent",
  72. name: "Agent",
  73. input: {
  74. description: "启动 MCP 子 agent",
  75. prompt: "调用声明的 MCP 工具。",
  76. subagent_type: CHILD_AGENT_NAME,
  77. },
  78. },
  79. ],
  80. usage: {},
  81. };
  82. },
  83. } as never),
  84. },
  85. );
  86. try {
  87. const result = await runtime.executeTurn("让 mcp-agent 跑一下");
  88. const parentText = (parentRequests[1]?.messages ?? [])
  89. .map((message) => modelMessageContentToText(message.content))
  90. .join("\n");
  91. return { childRequests, parentText, result };
  92. } finally {
  93. runtime.beginShutdown();
  94. }
  95. }
  96. /** 等待结束时把 server 改成已连接并带上一个 search 工具。 */
  97. function connectOnWait(snapshot: Record<string, McpServerToolSnapshot>) {
  98. return vi.fn<WaitForServer>(async (name) => {
  99. snapshot[name] = {
  100. status: mcpStatus("connected", { toolCount: 1 }),
  101. tools: [tool(name, "search")],
  102. toolsVersion: "2",
  103. };
  104. return { timedOut: false };
  105. });
  106. }
  107. describe("subagent MCP wait set", () => {
  108. it("starts a tools-only child after its referenced server finishes connecting", async () => {
  109. const snapshot: Record<string, McpServerToolSnapshot> = {
  110. "required-server": { status: mcpStatus("connecting") },
  111. };
  112. const waitForServer = connectOnWait(snapshot);
  113. // 修复前只等 mcpServers:只写 tools 的子 agent 在启动窗口内直接报工具缺失。
  114. const run = await runChild({
  115. label: "tools-only",
  116. servers: ["required-server"],
  117. snapshot,
  118. tools: ["mcp__required-server__search"],
  119. waitForServer,
  120. });
  121. expect(waitForServer).toHaveBeenCalledExactlyOnceWith("required-server", {
  122. timeoutMs: CHILD_SERVER_WAIT_MS,
  123. });
  124. expect(run.parentText).not.toContain(MISSING_TOOL_ERROR);
  125. expect(run.childRequests).toHaveLength(1);
  126. expect(requestToolNames(run.childRequests[0])).toContain("mcp__required-server__search");
  127. expect(run.result.response).toBe(PARENT_FINAL_REPLY);
  128. });
  129. it("maps model-visible references back to configured names exactly", async () => {
  130. const snapshot: Record<string, McpServerToolSnapshot> = {
  131. "plugin:demo:git": { status: mcpStatus("connecting") },
  132. "plugin:demo:github": { status: mcpStatus("connecting") },
  133. gitlab: { status: mcpStatus("connecting") },
  134. };
  135. const waitForServer = connectOnWait(snapshot);
  136. // 模型可见名 plugin_demo_git 是 plugin_demo_github 的前缀;子串匹配会多等无关 server。
  137. const run = await runChild({
  138. label: "exact-names",
  139. servers: ["plugin:demo:git", "plugin:demo:github", "gitlab"],
  140. snapshot,
  141. tools: ["mcp__plugin_demo_git__search"],
  142. waitForServer,
  143. });
  144. expect(waitForServer).toHaveBeenCalledExactlyOnceWith("plugin:demo:git", {
  145. timeoutMs: CHILD_SERVER_WAIT_MS,
  146. });
  147. expect(run.childRequests).toHaveLength(1);
  148. expect(requestToolNames(run.childRequests[0])).toContain("mcp__plugin_demo_git__search");
  149. });
  150. it("does not wait for unrelated servers when tools use the MCP wildcard", async () => {
  151. const snapshot: Record<string, McpServerToolSnapshot> = {
  152. fast: {
  153. status: mcpStatus("connected", { toolCount: 1 }),
  154. tools: [tool("fast", "ping")],
  155. toolsVersion: "1",
  156. },
  157. slow: { status: mcpStatus("connecting") },
  158. };
  159. const waitForServer = connectOnWait(snapshot);
  160. const run = await runChild({
  161. label: "wildcard",
  162. servers: ["fast", "slow"],
  163. snapshot,
  164. tools: ["mcp__*"],
  165. waitForServer,
  166. });
  167. expect(waitForServer).not.toHaveBeenCalled();
  168. expect(run.childRequests).toHaveLength(1);
  169. });
  170. it("keeps the original error when a referenced server fails while waiting", async () => {
  171. const snapshot: Record<string, McpServerToolSnapshot> = {
  172. "required-server": { status: mcpStatus("connecting") },
  173. };
  174. const waitForServer = vi.fn<WaitForServer>(async (name) => {
  175. snapshot[name] = { status: mcpStatus("failed", { error: "spawn failed" }) };
  176. return { timedOut: false };
  177. });
  178. const run = await runChild({
  179. label: "failed",
  180. servers: ["required-server"],
  181. snapshot,
  182. tools: ["mcp__required-server__search"],
  183. waitForServer,
  184. });
  185. expect(waitForServer).toHaveBeenCalledOnce();
  186. expect(run.childRequests).toEqual([]);
  187. expect(run.parentText).toContain(MISSING_TOOL_ERROR);
  188. expect(run.parentText).toContain("mcp__required-server__search");
  189. });
  190. });