mcp-server-wait.test.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. // 内部等待与动态 MCP:验证普通 step 快照、实时搜索和模型可见提醒。
  2. // 规格见 docs/mcp-async-tool-catalog-cache.md。等待用手动释放的 Promise,不用 sleep。
  3. import { describe, expect, it, vi } from "vitest";
  4. import {
  5. type McpPort,
  6. type McpConnectionSnapshot,
  7. type McpServerToolSnapshot,
  8. type ModelRequest,
  9. toolSearchNameForMode,
  10. } from "@zcode/contracts";
  11. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  12. import type { ToolExecutionContext } from "../src/tool/types.js";
  13. import {
  14. createRuntime,
  15. createSnapshotMcpPort,
  16. deferred,
  17. mcpStatus,
  18. messagesText,
  19. stdioServer,
  20. tool,
  21. toolNames,
  22. } from "./mcp-runtime-fixture.js";
  23. describe("dynamic MCP request boundaries", () => {
  24. it("does not let a plugin mention wait for unrelated background MCP startup", async () => {
  25. const startup = Promise.withResolvers<McpConnectionSnapshot>();
  26. const { runtime, requests } = createRuntime({
  27. label: "plugin-background",
  28. snapshot: { local: { status: mcpStatus("connecting") } },
  29. mcpPort: { connectConfiguredServers: () => startup.promise },
  30. });
  31. const turn = runtime.executeTurn("Use [@Demo](plugin://demo@mkt-a)");
  32. try {
  33. await vi.waitFor(() => expect(requests).toHaveLength(1));
  34. await turn;
  35. } finally {
  36. startup.resolve({ statuses: {}, tools: [] });
  37. await turn;
  38. runtime.beginShutdown();
  39. }
  40. });
  41. it.each(["off", "local", "native"] as const)(
  42. "offers Wait only without ToolSearch and pending-only search otherwise in %s",
  43. async (mode) => {
  44. const { runtime, requests } = createRuntime({
  45. label: mode,
  46. toolSearchMode: mode,
  47. snapshot: { local: { status: mcpStatus("connecting") } },
  48. });
  49. await runtime.executeTurn("find tools");
  50. // ToolSearch 关闭时没有连接中公告,WaitForMcpServers 是唯一提示。
  51. expect(toolNames(requests[0]).includes("WaitForMcpServers")).toBe(mode === "off");
  52. // Local 的控制工具以 LocalToolSearch 发送;按模式取当前入口名。
  53. expect(toolNames(requests[0]).includes(toolSearchNameForMode(mode))).toBe(mode !== "off");
  54. expect(messagesText(requests[0])).not.toContain("WaitForMcpServers");
  55. expect(
  56. messagesText(requests[0]).includes("The following MCP servers are still connecting —"),
  57. ).toBe(mode !== "off");
  58. runtime.beginShutdown();
  59. },
  60. );
  61. it("searches ready tools in the same batch but registers them only for the following step", async () => {
  62. const snapshot: Record<string, McpServerToolSnapshot> = {
  63. local: { status: mcpStatus("connecting") },
  64. };
  65. const { runtime, requests } = createRuntime({
  66. label: "live-search",
  67. toolSearchMode: "native",
  68. toolDisallowlist: ["mcp__local__blocked"],
  69. snapshot,
  70. respond: (_request, index) => {
  71. if (index !== 0) return;
  72. snapshot.local = {
  73. status: mcpStatus("connected"),
  74. tools: [
  75. { ...tool("local", "ping"), description: "live-catalog probe" },
  76. { ...tool("local", "blocked"), description: "live-catalog probe" },
  77. {
  78. ...tool("local", "app_only"),
  79. description: "live-catalog probe",
  80. visibility: ["app"],
  81. },
  82. ],
  83. toolsVersion: "1",
  84. };
  85. return {
  86. text: "",
  87. finishReason: "tool-calls",
  88. usage: {},
  89. toolCalls: [
  90. {
  91. id: "search",
  92. name: "ToolSearch",
  93. input: { query: "live-catalog probe", max_results: 5 },
  94. },
  95. { id: "premature", name: "mcp__local__ping", input: {} },
  96. ],
  97. };
  98. },
  99. });
  100. await runtime.executeTurn("use ping");
  101. expect(toolNames(requests[0])).not.toContain("mcp__local__ping");
  102. expect(messagesText(requests[1])).toContain("tool_reference");
  103. expect(messagesText(requests[1])).toContain("mcp__local__ping");
  104. expect(messagesText(requests[1])).not.toContain("mcp__local__blocked");
  105. expect(messagesText(requests[1])).not.toContain("mcp__local__app_only");
  106. expect(toolNames(requests[1])).toContain("mcp__local__ping");
  107. expect(messagesText(requests[1])).not.toContain("MCP server status for this request");
  108. runtime.beginShutdown();
  109. });
  110. it("preserves the snapshot during continuation and consumes ready state on the next input", async () => {
  111. const snapshot: Record<string, McpServerToolSnapshot> = {
  112. local: { status: mcpStatus("connecting") },
  113. };
  114. const { runtime, requests } = createRuntime({
  115. label: "continuation",
  116. toolSearchMode: "off",
  117. snapshot,
  118. respond: (_request, index) => {
  119. if (index !== 0) return;
  120. snapshot.local = {
  121. status: mcpStatus("connected"),
  122. tools: [tool("local", "ping")],
  123. toolsVersion: "1",
  124. };
  125. return { text: "partial", finishReason: "length", usage: {} };
  126. },
  127. });
  128. await runtime.executeTurn("long answer");
  129. expect(requests).toHaveLength(2);
  130. expect(toolNames(requests[1])).toEqual(toolNames(requests[0]));
  131. await runtime.executeTurn("next input");
  132. expect(toolNames(requests[2])).toContain("mcp__local__ping");
  133. runtime.beginShutdown();
  134. });
  135. it("reconciles configuration in the background and retracts on the next input", async () => {
  136. const snapshot: Record<string, McpServerToolSnapshot> = {
  137. local: { status: mcpStatus("connected"), tools: [tool("local", "ping")], toolsVersion: "1" },
  138. };
  139. let config = { enabled: true, servers: { local: stdioServer() } };
  140. let notify = () => {};
  141. const connected: string[][] = [];
  142. const { runtime, requests } = createRuntime({
  143. label: "reconcile",
  144. toolSearchMode: "native",
  145. snapshot,
  146. mcpConfigurationSource: {
  147. getSnapshot: () => config,
  148. subscribe: (listener) => {
  149. notify = listener;
  150. return () => {};
  151. },
  152. close() {},
  153. },
  154. mcpPort: {
  155. connectConfiguredServers: async (servers) => {
  156. connected.push(Object.keys(servers));
  157. return { statuses: {}, tools: [] };
  158. },
  159. },
  160. });
  161. await runtime.executeTurn("setup");
  162. config = { enabled: true, servers: {} } as typeof config;
  163. notify();
  164. expect(connected.at(-1)).toEqual([]);
  165. expect(requests).toHaveLength(1);
  166. await runtime.executeTurn("after removal");
  167. expect(toolNames(requests[1])).not.toContain("mcp__local__ping");
  168. expect(messagesText(requests[1])).toContain("their MCP server disconnected");
  169. expect(messagesText(requests[1])).not.toContain("Disregard those definitions");
  170. // 其他内置 deferred 工具仍可保留搜索入口。
  171. runtime.beginShutdown();
  172. });
  173. it("does not advance the snapshot during reactive compact", async () => {
  174. const snapshot: Record<string, McpServerToolSnapshot> = {
  175. local: { status: mcpStatus("connecting") },
  176. };
  177. let overflowed = false;
  178. const { runtime, requests } = createRuntime({
  179. label: "compact",
  180. snapshot,
  181. respond: (request) => {
  182. if (messagesText(request).includes("create a detailed summary"))
  183. return { text: "<summary>Continue task.</summary>", finishReason: "stop", usage: {} };
  184. if (messagesText(request).includes("OVERFLOW") && !overflowed) {
  185. overflowed = true;
  186. snapshot.local = {
  187. status: mcpStatus("connected"),
  188. tools: [tool("local", "ping")],
  189. toolsVersion: "1",
  190. };
  191. throw Object.assign(new Error("provider context window exceeded"), {
  192. code: "model_context_exceeded",
  193. });
  194. }
  195. },
  196. });
  197. for (const input of ["one", "two", "three", "OVERFLOW"]) await runtime.executeTurn(input);
  198. expect(messagesText(requests.at(-1))).toContain("Continue task.");
  199. expect(toolNames(requests.at(-1))).not.toContain("mcp__local__ping");
  200. await runtime.executeTurn("normal input");
  201. expect(toolNames(requests.at(-1))).toContain("mcp__local__ping");
  202. runtime.beginShutdown();
  203. });
  204. });
  205. it("consumes ready MCP after a text response followed by guide", async () => {
  206. const snapshot: Record<string, McpServerToolSnapshot> = {
  207. local: { status: mcpStatus("connecting") },
  208. };
  209. const { runtime, requests } = createRuntime({
  210. label: "guide",
  211. snapshot,
  212. respond: async (_request, index) => {
  213. if (index !== 0) return;
  214. snapshot.local = {
  215. status: mcpStatus("connected"),
  216. tools: [tool("local", "ping")],
  217. toolsVersion: "1",
  218. };
  219. await runtime.steerTurn({ delivery: "guide", input: "continue with ping" });
  220. },
  221. });
  222. await runtime.executeTurn("start");
  223. expect(requests).toHaveLength(2);
  224. expect(toolNames(requests[0])).not.toContain("mcp__local__ping");
  225. expect(toolNames(requests[1])).toContain("mcp__local__ping");
  226. runtime.beginShutdown();
  227. });
  228. it("reports an origin-denied server as failed without retracting delivered definitions", async () => {
  229. const snapshot: Record<string, McpServerToolSnapshot> = {
  230. local: { status: mcpStatus("connected"), tools: [tool("local", "ping")], toolsVersion: "1" },
  231. };
  232. const { runtime, requests } = createRuntime({
  233. label: "policy-retraction",
  234. toolSearchMode: "native",
  235. snapshot,
  236. respond: (_request, index) =>
  237. index === 0
  238. ? {
  239. text: "",
  240. finishReason: "tool-calls",
  241. usage: {},
  242. toolCalls: [
  243. {
  244. id: "search",
  245. name: "ToolSearch",
  246. input: { query: "select:mcp__local__ping", max_results: 5 },
  247. },
  248. ],
  249. }
  250. : undefined,
  251. });
  252. try {
  253. await runtime.executeTurn("setup");
  254. snapshot.local = { status: mcpStatus("failed", { failureKind: "official_origin_untrusted" }) };
  255. await runtime.executeTurn("blocked");
  256. // 来源校验失败与连接失败同样处理:工具离开目录、server 列入失败段,已交付定义不撤回。
  257. expect(messagesText(requests.at(-1))).not.toContain("Disregard those definitions");
  258. expect(messagesText(requests.at(-1))).not.toContain("blocked by the organization");
  259. expect(messagesText(requests.at(-1))).toContain(
  260. "The following MCP servers are configured but failed to connect",
  261. );
  262. snapshot.local = {
  263. status: mcpStatus("connected"),
  264. tools: [tool("local", "ping")],
  265. toolsVersion: "2",
  266. };
  267. await runtime.executeTurn("restored");
  268. expect(messagesText(requests.at(-1))).toContain(
  269. "1 deferred tool is available again (MCP server reconnected — names announced earlier in this conversation)",
  270. );
  271. } finally {
  272. runtime.beginShutdown();
  273. }
  274. });
  275. it("explains why a previously offered MCP tool is no longer callable", async () => {
  276. const snapshot: Record<string, McpServerToolSnapshot> = {
  277. local: { status: mcpStatus("connected"), tools: [tool("local", "ping")], toolsVersion: "1" },
  278. };
  279. const { runtime, requests } = createRuntime({
  280. label: "unregistered-reason",
  281. snapshot,
  282. respond: (_request, index) =>
  283. index === 1
  284. ? {
  285. text: "",
  286. finishReason: "tool-calls",
  287. usage: {},
  288. toolCalls: [
  289. { id: "offered", name: "mcp__local__ping", input: {} },
  290. { id: "unknown", name: "mcp__other__ping", input: {} },
  291. ],
  292. }
  293. : undefined,
  294. });
  295. try {
  296. await runtime.executeTurn("first");
  297. snapshot.local = { status: mcpStatus("failed") };
  298. await runtime.executeTurn("second");
  299. const text = messagesText(requests[2]);
  300. // 修复前模型只看到 "No such tool available",无法区分 server 断开与工具下线。
  301. expect(text).toContain(
  302. "<tool_use_error>Error: No such tool available: mcp__local__ping. Its MCP server 'local' has disconnected. Continue without this tool; it becomes callable again only if the server reconnects.</tool_use_error>",
  303. );
  304. // 本会话从未提供过的名称保持原报错。
  305. expect(text).toContain(
  306. "<tool_use_error>Error: No such tool available: mcp__other__ping</tool_use_error>",
  307. );
  308. } finally {
  309. runtime.beginShutdown();
  310. }
  311. });
  312. it("checks configuration again after an execution wait", async () => {
  313. const snapshot = {
  314. local: { status: mcpStatus("connected"), tools: [tool("local", "ping")], toolsVersion: "1" },
  315. };
  316. let waits = 0;
  317. let configuration = { enabled: true, servers: { local: stdioServer() } };
  318. let changed = () => {};
  319. const { runtime } = createRuntime({
  320. label: "withdraw-during-wait",
  321. snapshot,
  322. mcpConfigurationSource: {
  323. getSnapshot: () => configuration,
  324. subscribe: (listener) => {
  325. changed = listener;
  326. return () => {};
  327. },
  328. close() {},
  329. },
  330. mcpPort: {
  331. waitForServer: async () => {
  332. waits++;
  333. configuration = { enabled: false, servers: {} } as typeof configuration;
  334. changed();
  335. return { timedOut: false };
  336. },
  337. },
  338. });
  339. try {
  340. await runtime.executeTurn("prepare tools");
  341. const entry = (runtime as unknown as AgentRuntimeInternal).registry.get("mcp__local__ping")!;
  342. const resolved = await entry.resolveForExecution!({});
  343. expect(waits).toBe(1);
  344. expect(resolved.status).not.toBe("ready");
  345. } finally {
  346. runtime.beginShutdown();
  347. }
  348. });
  349. it("reports recovery from the connection owner's state and retains searchable tools", async () => {
  350. const snapshot: Record<string, McpServerToolSnapshot> = {
  351. local: {
  352. status: mcpStatus("connecting", { error: "stream closed" }),
  353. tools: [tool("local", "ping")],
  354. toolsVersion: "1",
  355. },
  356. };
  357. const { runtime, requests } = createRuntime({
  358. label: "recovery-facts",
  359. toolSearchMode: "native",
  360. snapshot,
  361. });
  362. try {
  363. await runtime.executeTurn("check capabilities");
  364. expect(messagesText(requests[0])).toContain("The following MCP servers are still connecting —");
  365. expect(messagesText(requests[0])).toContain("mcp__local__ping");
  366. } finally {
  367. runtime.beginShutdown();
  368. }
  369. });
  370. it("publishes each server catalog before the other servers finish, including an empty refresh", async () => {
  371. const snapshot: Record<string, McpServerToolSnapshot> = {
  372. fast: { status: mcpStatus("connecting") },
  373. slow: { status: mcpStatus("connecting") },
  374. };
  375. let notify = () => {};
  376. const published: Record<string, McpServerToolSnapshot>[] = [];
  377. const { runtime } = createRuntime({
  378. label: "independent-cache-publication",
  379. snapshot,
  380. servers: { fast: stdioServer(), slow: stdioServer() },
  381. mcpPort: {
  382. onSnapshotChanged(listener) {
  383. notify = listener;
  384. return () => {
  385. notify = () => {};
  386. };
  387. },
  388. },
  389. mcpToolCatalogPort: {
  390. prepare: () => ({
  391. lookup: { status: "incomplete", byServer: {} },
  392. publish: (value) => {
  393. if (value.fast?.status.status === "connected") published.push(structuredClone(value));
  394. },
  395. }),
  396. },
  397. });
  398. try {
  399. await runtime.executeTurn("start");
  400. snapshot.fast = {
  401. status: mcpStatus("connected"),
  402. tools: [tool("fast", "ping")],
  403. toolsVersion: "1",
  404. };
  405. notify();
  406. expect(published.map((value) => value.fast!.tools!.map((tool) => tool.toolName))).toEqual([
  407. ["ping"],
  408. ]);
  409. snapshot.fast = { status: mcpStatus("connected"), tools: [], toolsVersion: "2" };
  410. notify();
  411. expect(published.map((value) => value.fast!.tools!.map((tool) => tool.toolName))).toEqual([
  412. ["ping"],
  413. [],
  414. ]);
  415. expect(snapshot.slow.status.status).toBe("connecting");
  416. } finally {
  417. runtime.beginShutdown();
  418. }
  419. notify();
  420. expect(published).toHaveLength(2);
  421. });
  422. it("admits a destructive live tool on its first call from a display-only catalog", async () => {
  423. const descriptor = { ...tool("local", "erase"), annotations: { destructiveHint: true } };
  424. const snapshot: Record<string, McpServerToolSnapshot> = {
  425. local: { status: mcpStatus("connecting") },
  426. };
  427. const { runtime } = createRuntime({
  428. label: "catalog-unknown-execution-metadata",
  429. snapshot,
  430. mcpToolCatalogPort: {
  431. prepare: () => ({
  432. lookup: { status: "complete", byServer: { local: [tool("local", "erase")] } },
  433. publish() {},
  434. }),
  435. },
  436. });
  437. try {
  438. await runtime.executeTurn("prepare");
  439. const entry = (runtime as unknown as AgentRuntimeInternal).registry.get("mcp__local__erase")!;
  440. expect(entry.metadata.readOnly).toBe(false);
  441. expect(entry.metadata.concurrentSafe).toBe(false);
  442. snapshot.local = { status: mcpStatus("connected"), tools: [descriptor], toolsVersion: "1" };
  443. const live = await entry.resolveForExecution!({});
  444. expect(live.status).toBe("ready");
  445. if (live.status === "ready") expect(live.entry.metadata.destructive).toBe(true);
  446. } finally {
  447. runtime.beginShutdown();
  448. }
  449. });
  450. it.each(["connection", "definition"])(
  451. "runs an approved call after a same-config %s change",
  452. async (change) => {
  453. const descriptor = tool("local", "ping");
  454. const snapshot = {
  455. local: { status: mcpStatus("connected"), tools: [descriptor], toolsVersion: "1" },
  456. };
  457. let generation = 1;
  458. let calls = 0;
  459. const { runtime } = createRuntime({
  460. label: "execution-target-binding",
  461. snapshot,
  462. mcpPort: {
  463. appConnectionSnapshot: () => ({ identity: "local", generation }),
  464. callTool: async () => {
  465. calls++;
  466. return { content: [] };
  467. },
  468. },
  469. });
  470. try {
  471. await runtime.executeTurn("prepare");
  472. const entry = (runtime as unknown as AgentRuntimeInternal).registry.get("mcp__local__ping")!;
  473. const live = await entry.resolveForExecution!({});
  474. expect(live.status).toBe("ready");
  475. if (live.status !== "ready") return;
  476. if (change === "connection") generation++;
  477. else
  478. snapshot.local = {
  479. ...snapshot.local,
  480. tools: [
  481. {
  482. ...descriptor,
  483. inputSchema: { type: "object", properties: { required: { type: "string" } } },
  484. },
  485. ],
  486. toolsVersion: "2",
  487. };
  488. // 模型调用晚绑定当前连接:同配置重连或定义刷新后,已批准的调用仍执行。
  489. await live.entry.handler({}, {
  490. abortSignal: new AbortController().signal,
  491. } as ToolExecutionContext);
  492. expect(calls).toBe(1);
  493. } finally {
  494. runtime.beginShutdown();
  495. }
  496. },
  497. );
  498. it("rejects an approved call after its server configuration changes", async () => {
  499. const snapshot = {
  500. local: { status: mcpStatus("connected"), tools: [tool("local", "ping")], toolsVersion: "1" },
  501. };
  502. let configuration = { enabled: true, servers: { local: stdioServer() } };
  503. let changed = () => {};
  504. let calls = 0;
  505. const { runtime } = createRuntime({
  506. label: "execution-config-change",
  507. snapshot,
  508. mcpConfigurationSource: {
  509. getSnapshot: () => configuration,
  510. subscribe: (listener) => {
  511. changed = listener;
  512. return () => {};
  513. },
  514. close() {},
  515. },
  516. mcpPort: {
  517. callTool: async () => {
  518. calls++;
  519. return { content: [] };
  520. },
  521. },
  522. });
  523. try {
  524. await runtime.executeTurn("prepare");
  525. const entry = (runtime as unknown as AgentRuntimeInternal).registry.get("mcp__local__ping")!;
  526. const live = await entry.resolveForExecution!({});
  527. expect(live.status).toBe("ready");
  528. if (live.status !== "ready") return;
  529. configuration = { enabled: true, servers: { local: { ...stdioServer(), args: ["next"] } } };
  530. changed();
  531. await expect(
  532. live.entry.handler({}, {
  533. abortSignal: new AbortController().signal,
  534. } as ToolExecutionContext),
  535. ).rejects.toThrow(
  536. "MCP tool is unavailable in the current session: mcp__local__ping. Its MCP server 'local' has disconnected.",
  537. );
  538. expect(calls).toBe(0);
  539. } finally {
  540. runtime.beginShutdown();
  541. }
  542. });
  543. // ToolSearch 关闭时没有连接中公告:WaitForMcpServers 与执行器等待是模型知道 server 仍在连接的途径。
  544. // 规格见 docs/mcp-async-tool-catalog-cache.md「ToolSearch 关闭时:WaitForMcpServers」「执行时不可用」。
  545. describe("connecting MCP servers without ToolSearch", () => {
  546. const WAIT_DESCRIPTION = [
  547. "Wait for MCP servers that are still connecting and whose tools are not",
  548. "yet in your tool list. Pass `servers` to wait for specific ones, or omit",
  549. "it to wait for all pending servers (once none is pending, a call without",
  550. "`servers` reports any server that failed to connect or is not configured).",
  551. "",
  552. "If the user's request needs tools from a still-connecting server, call this",
  553. "tool to wait for it. Once it connects, its tools will be added to your tool",
  554. "list and you can use them directly. Returns ready=true when servers are",
  555. "ready, ready=false if they failed to connect, need authentication, or are",
  556. "disabled.",
  557. "",
  558. "You do not need to ask the user for confirmation to use this tool.",
  559. ].join("\n");
  560. function toolCallResponse(calls: Array<{ id: string; name: string; input?: unknown }>) {
  561. return {
  562. text: "",
  563. finishReason: "tool-calls",
  564. usage: {},
  565. toolCalls: calls.map((call) => ({ input: {}, ...call })),
  566. };
  567. }
  568. // MCP 工具总要审批;走真实执行器的用例用放行的 broker。
  569. const allowAll = { requestPermission: async () => ({ decision: "allow" as const }) };
  570. function toolResult(request: ModelRequest | undefined, id: string) {
  571. return request?.messages.find(
  572. (message) => message.role === "tool" && message.toolCallId === id,
  573. ) as { content: unknown; isError?: boolean } | undefined;
  574. }
  575. it("sends the fixed definition in sorted position and latches it after the first send", async () => {
  576. const snapshot: Record<string, McpServerToolSnapshot> = {
  577. local: { status: mcpStatus("connecting") },
  578. };
  579. const { runtime, requests } = createRuntime({ label: "wait-latch", snapshot });
  580. try {
  581. await runtime.executeTurn("first");
  582. const names = toolNames(requests[0]);
  583. const wait = requests[0]?.tools?.find((entry) => entry.name === "WaitForMcpServers");
  584. expect(wait?.description).toBe(WAIT_DESCRIPTION);
  585. expect(JSON.stringify(wait?.inputSchema)).toBe(
  586. '{"$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}',
  587. );
  588. // 进入按名字排序的名单:排在 WebFetch 之前。
  589. expect(names.indexOf("WaitForMcpServers")).toBeLessThan(names.indexOf("WebFetch"));
  590. snapshot.local = {
  591. status: mcpStatus("connected"),
  592. tools: [tool("local", "ping")],
  593. toolsVersion: "1",
  594. };
  595. await runtime.executeTurn("second");
  596. // 发送过一次后保持,tools 段不因连接完成而变化。
  597. expect(toolNames(requests[1])).toContain("WaitForMcpServers");
  598. } finally {
  599. runtime.beginShutdown();
  600. }
  601. });
  602. it("never offers Wait when no server is connecting and nothing was sent", async () => {
  603. const { runtime, requests } = createRuntime({
  604. label: "wait-idle",
  605. snapshot: {
  606. local: {
  607. status: mcpStatus("connected"),
  608. tools: [tool("local", "ping")],
  609. toolsVersion: "1",
  610. },
  611. },
  612. });
  613. try {
  614. await runtime.executeTurn("first");
  615. expect(toolNames(requests[0])).not.toContain("WaitForMcpServers");
  616. // 不带模型的工具名单(持久化记录、子 agent 继承)同样不含它。
  617. expect(runtime.getTools().map((entry) => entry.name)).not.toContain("WaitForMcpServers");
  618. } finally {
  619. runtime.beginShutdown();
  620. }
  621. });
  622. it("waits for pending servers and reports each group with is_error when not ready", async () => {
  623. const snapshot: Record<string, McpServerToolSnapshot> = {
  624. local: { status: mcpStatus("connecting") },
  625. broken: { status: mcpStatus("failed", { error: "refused" }) },
  626. };
  627. const waited: string[] = [];
  628. const { runtime, requests } = createRuntime({
  629. label: "wait-groups",
  630. snapshot,
  631. servers: { local: stdioServer(), broken: stdioServer() },
  632. mcpPort: {
  633. waitForServer: async (name, options) => {
  634. waited.push(`${name}:${options.timeoutMs}`);
  635. snapshot.local = {
  636. status: mcpStatus("connected"),
  637. tools: [tool("local", "ping")],
  638. toolsVersion: "1",
  639. };
  640. return { timedOut: false };
  641. },
  642. },
  643. respond: (_request, index) =>
  644. index === 0
  645. ? toolCallResponse([
  646. { id: "all", name: "WaitForMcpServers" },
  647. { id: "named", name: "WaitForMcpServers", input: { servers: ["broken", "nope"] } },
  648. ])
  649. : undefined,
  650. });
  651. try {
  652. await runtime.executeTurn("wait");
  653. // 不传 servers 时只等 pending;不发起连接或授权。
  654. expect(waited).toEqual(["local:5000"]);
  655. expect(toolResult(requests[1], "all")).toMatchObject({
  656. content:
  657. "ready: true\nConnected (their tools are now available — call them directly): local",
  658. isError: false,
  659. });
  660. expect(toolResult(requests[1], "named")).toMatchObject({
  661. content:
  662. "ready: false\nFailed to connect: broken\nUnknown (no MCP server with this name is configured): nope",
  663. isError: true,
  664. });
  665. } finally {
  666. runtime.beginShutdown();
  667. }
  668. });
  669. it("runs a tool whose server finishes its first connection during the wait", async () => {
  670. const snapshot: Record<string, McpServerToolSnapshot> = {
  671. local: { status: mcpStatus("connecting") },
  672. };
  673. const calls: string[] = [];
  674. const waits: number[] = [];
  675. const { runtime, requests } = createRuntime({
  676. label: "pending-tool-wait",
  677. snapshot,
  678. permissionBroker: allowAll,
  679. mcpPort: {
  680. waitForServer: async (_name, options) => {
  681. // 执行准入(reconnect)对已连接 server 立即返回,不计入首次连接等待。
  682. if (!options.reconnect) waits.push(options.timeoutMs);
  683. snapshot.local = {
  684. status: mcpStatus("connected"),
  685. tools: [tool("local", "ping")],
  686. toolsVersion: "1",
  687. };
  688. return { timedOut: false };
  689. },
  690. callTool: async (request) => {
  691. calls.push(`${request.serverName}/${request.toolName}`);
  692. return { content: [{ type: "text", text: "pong" }] };
  693. },
  694. },
  695. respond: (_request, index) =>
  696. index === 0 ? toolCallResponse([{ id: "early", name: "mcp__local__ping" }]) : undefined,
  697. });
  698. try {
  699. await runtime.executeTurn("call early");
  700. expect(waits).toEqual([10_000]);
  701. expect(calls).toEqual(["local/ping"]);
  702. expect(toolResult(requests[1], "early")).toMatchObject({ isError: false });
  703. expect(JSON.stringify(toolResult(requests[1], "early")?.content)).toContain("pong");
  704. } finally {
  705. runtime.beginShutdown();
  706. }
  707. });
  708. it("shares ten seconds per response and stops waiting for an exhausted connection", async () => {
  709. vi.useFakeTimers({ toFake: ["Date"] });
  710. const snapshot: Record<string, McpServerToolSnapshot> = {
  711. local: { status: mcpStatus("connecting", { updatedAt: "episode-1" }) },
  712. other: { status: mcpStatus("connecting", { updatedAt: "episode-1" }) },
  713. };
  714. const waits: string[] = [];
  715. const { runtime, requests } = createRuntime({
  716. label: "pending-tool-budget",
  717. snapshot,
  718. servers: { local: stdioServer(), other: stdioServer() },
  719. mcpPort: {
  720. waitForServer: async (name, options) => {
  721. waits.push(`${name}:${options.timeoutMs}`);
  722. if (name === "other") {
  723. vi.setSystemTime(Date.now() + 4_000);
  724. snapshot.other = { status: mcpStatus("failed") };
  725. return { timedOut: false };
  726. }
  727. vi.setSystemTime(Date.now() + options.timeoutMs);
  728. return { timedOut: true };
  729. },
  730. },
  731. respond: (_request, index) =>
  732. index === 0
  733. ? toolCallResponse([
  734. { id: "other-call", name: "mcp__other__ping" },
  735. { id: "first", name: "mcp__local__ping" },
  736. { id: "second", name: "mcp__local__ping" },
  737. ])
  738. : index === 1
  739. ? toolCallResponse([{ id: "later", name: "mcp__local__ping" }])
  740. : index === 3
  741. ? toolCallResponse([{ id: "again", name: "mcp__local__ping" }])
  742. : undefined,
  743. });
  744. try {
  745. await runtime.executeTurn("call while connecting");
  746. // 同一回复共用 10 秒:other 用掉 4 秒,local 只剩 6 秒;没等满,不记为用尽。
  747. expect(waits.slice(0, 2)).toEqual(["other:10000", "local:6000"]);
  748. // 下一回复重新计预算;local 这次等满 10 秒,之后同一次连接不再等。
  749. expect(waits.slice(2)).toEqual(["local:10000"]);
  750. const text = JSON.stringify(toolResult(requests[2], "later")?.content);
  751. expect(text).toContain(
  752. "No such tool available: mcp__local__ping. The MCP server 'local' is still connecting. Call WaitForMcpServers to wait for it, then try again.",
  753. );
  754. snapshot.local = { status: mcpStatus("connecting", { updatedAt: "episode-2" }) };
  755. waits.length = 0;
  756. await runtime.executeTurn("new connection");
  757. // 新的一次连接重新允许等待。
  758. expect(waits).toEqual(["local:10000"]);
  759. } finally {
  760. vi.useRealTimers();
  761. runtime.beginShutdown();
  762. }
  763. });
  764. it("marks a connection exhausted when its full wait times out even if the clock reads less", async () => {
  765. vi.useFakeTimers({ toFake: ["Date"] });
  766. const waits: number[] = [];
  767. const { runtime } = createRuntime({
  768. label: "pending-tool-timed-out",
  769. snapshot: { local: { status: mcpStatus("connecting", { updatedAt: "episode-1" }) } },
  770. mcpPort: {
  771. waitForServer: async (_name, options) => {
  772. waits.push(options.timeoutMs);
  773. // 计时器按毫秒截断:等待已超时,墙钟只走了 9999 ms。
  774. vi.setSystemTime(Date.now() + options.timeoutMs - 1);
  775. return { timedOut: true };
  776. },
  777. },
  778. respond: (_request, index) =>
  779. index === 0 || index === 1
  780. ? toolCallResponse([{ id: `call-${index}`, name: "mcp__local__ping" }])
  781. : undefined,
  782. });
  783. try {
  784. await runtime.executeTurn("call twice");
  785. // 第一次等满后记为用尽;下一条回复不再为同一次连接等待。
  786. expect(waits).toEqual([10_000]);
  787. } finally {
  788. vi.useRealTimers();
  789. runtime.beginShutdown();
  790. }
  791. });
  792. it("maps the official computer-use tool prefix to its namespaced server", async () => {
  793. const official = "plugin:computer-use:computer-use";
  794. const snapshot: Record<string, McpServerToolSnapshot> = {
  795. [official]: { status: mcpStatus("connecting") },
  796. };
  797. const waited: string[] = [];
  798. const { runtime, requests } = createRuntime({
  799. label: "cua-prefix",
  800. snapshot,
  801. servers: { [official]: stdioServer() },
  802. mcpPort: {
  803. waitForServer: async (name, options) => {
  804. waited.push(`${name}:${options.timeoutMs}`);
  805. return { timedOut: false };
  806. },
  807. },
  808. respond: (_request, index) =>
  809. index === 0
  810. ? toolCallResponse([
  811. { id: "early", name: "mcp__computer-use__click" },
  812. { id: "wait", name: "WaitForMcpServers", input: { servers: ["computer-use"] } },
  813. ])
  814. : undefined,
  815. });
  816. try {
  817. await runtime.executeTurn("use the computer");
  818. // 规范名 `mcp__computer-use__*` 的连接记录名带插件命名空间:首次连接等待和名称匹配都要认出它。
  819. expect(waited).toEqual([`${official}:10000`, `${official}:5000`]);
  820. expect(toolResult(requests[1], "wait")).toMatchObject({
  821. content: `ready: false\nStill connecting (try again or proceed without): ${official}`,
  822. isError: true,
  823. });
  824. } finally {
  825. runtime.beginShutdown();
  826. }
  827. });
  828. it("does not wait for a recovering server that keeps its tool list", async () => {
  829. let waits = 0;
  830. const { runtime, requests } = createRuntime({
  831. label: "recovering-no-wait",
  832. snapshot: {
  833. local: {
  834. status: mcpStatus("connecting"),
  835. tools: [tool("local", "ping")],
  836. toolsVersion: "1",
  837. },
  838. },
  839. mcpPort: {
  840. waitForServer: async () => {
  841. waits++;
  842. return { timedOut: false };
  843. },
  844. },
  845. respond: (_request, index) =>
  846. index === 0 ? toolCallResponse([{ id: "guess", name: "mcp__local__unknown" }]) : undefined,
  847. });
  848. try {
  849. await runtime.executeTurn("guess a name");
  850. expect(waits).toBe(0);
  851. expect(JSON.stringify(toolResult(requests[1], "guess")?.content)).toContain(
  852. "No such tool available: mcp__local__unknown",
  853. );
  854. } finally {
  855. runtime.beginShutdown();
  856. }
  857. });
  858. it("runs a tool whose server connected after the step without waiting", async () => {
  859. const snapshot: Record<string, McpServerToolSnapshot> = {
  860. local: { status: mcpStatus("connecting") },
  861. };
  862. let waits = 0;
  863. const calls: string[] = [];
  864. const { runtime } = createRuntime({
  865. label: "connected-after-step",
  866. toolSearchMode: "native",
  867. snapshot,
  868. permissionBroker: allowAll,
  869. mcpPort: {
  870. waitForServer: async (_name, options) => {
  871. // 执行准入(reconnect)对已连接 server 立即返回,不计入首次连接等待。
  872. if (!options.reconnect) waits++;
  873. return { timedOut: false };
  874. },
  875. callTool: async (request) => {
  876. calls.push(request.toolName);
  877. return { content: [{ type: "text", text: "pong" }] };
  878. },
  879. },
  880. respond: (_request, index) => {
  881. if (index !== 0) return undefined;
  882. snapshot.local = {
  883. status: mcpStatus("connected"),
  884. tools: [tool("local", "ping")],
  885. toolsVersion: "1",
  886. };
  887. return toolCallResponse([{ id: "fresh", name: "mcp__local__ping" }]);
  888. },
  889. });
  890. try {
  891. await runtime.executeTurn("call fresh");
  892. expect(waits).toBe(0);
  893. expect(calls).toEqual(["ping"]);
  894. } finally {
  895. runtime.beginShutdown();
  896. }
  897. });
  898. });