mcp-runtime.test.ts 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  1. import { createMockMcpPort, mcpStatus } from "./mcp-runtime-fixture.js";
  2. import { afterEach, describe, expect, it } from "vitest";
  3. import {
  4. resetCapturedZCodeCuaBrokerCredentialsForTest,
  5. sanitizeZCodeRuntimeEnv,
  6. ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME,
  7. ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  8. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  9. ZCODE_PLUGIN_ID_ENV_KEY,
  10. } from "@zcode/shared";
  11. import {
  12. ModelTransportKind,
  13. SessionEventType,
  14. createSessionId,
  15. createTraceId,
  16. createWorkspaceId,
  17. type McpConnectionSnapshot,
  18. type McpPort,
  19. type McpServerStatus,
  20. type McpServerToolSnapshot,
  21. type McpToolDescriptor,
  22. type McpToolCatalogPort,
  23. type PermissionBrokerPort,
  24. type PermissionBrokerRequest,
  25. type SessionEventStorePort,
  26. type SessionId,
  27. } from "@zcode/contracts";
  28. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  29. import { createTestSessionEventStore } from "./test-event-store.js";
  30. import { createTestModelFactory } from "./test-runtime-model.js";
  31. describe("AgentRuntime MCP integration", () => {
  32. afterEach(() => {
  33. resetCapturedZCodeCuaBrokerCredentialsForTest();
  34. });
  35. it.each(["tavily_search", "tavily_extract", "lookup_record"])(
  36. "%s sends one complete result to subsequent model requests",
  37. async (toolName) => {
  38. const sessionId = createSessionId(`runtime-${toolName}`);
  39. const structuredContent = {
  40. results: [{ url: "https://example.com", content: "result ".repeat(4_000) }],
  41. };
  42. const text = JSON.stringify(structuredContent);
  43. const toolResult = { content: [{ type: "text", text }], structuredContent };
  44. const modelToolName = `mcp__custom_search__${toolName}`;
  45. let modelCallCount = 0;
  46. let mcpCallCount = 0;
  47. const runtime = createTestAgentRuntime(
  48. sessionId,
  49. {
  50. mode: "build",
  51. mcp: {
  52. enabled: true,
  53. servers: { custom_search: { type: "stdio", command: "node" } },
  54. },
  55. },
  56. {
  57. eventStore: createTestSessionEventStore(),
  58. permissionBroker: {
  59. requestPermission: async () => ({ decision: "allow", reason: "Test approval" }),
  60. },
  61. mcpPort: createMockMcpPort({
  62. connectConfiguredServers: async () => ({
  63. statuses: { custom_search: mcpStatus("connected", { toolCount: 1 }) },
  64. tools: [
  65. {
  66. serverName: "custom_search",
  67. toolName,
  68. inputSchema: { type: "object" },
  69. annotations: { readOnlyHint: true },
  70. },
  71. ],
  72. }),
  73. callTool: async () => {
  74. mcpCallCount++;
  75. return toolResult;
  76. },
  77. }),
  78. modelFactory: createTestModelFactory({
  79. async generateText(request) {
  80. modelCallCount++;
  81. if (modelCallCount === 1) {
  82. return {
  83. finishReason: "tool-calls",
  84. text: "",
  85. toolCalls: [{ id: "mcp-call", name: modelToolName, input: {} }],
  86. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  87. };
  88. }
  89. const messages = request.messages.filter((message) => message.role === "tool");
  90. expect(messages).toHaveLength(1);
  91. expect(messages[0]?.content).toBe(text);
  92. return {
  93. finishReason: "stop",
  94. text: "done",
  95. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  96. };
  97. },
  98. }),
  99. },
  100. );
  101. await runtime.startMcpStartup({ sessionId, traceId: createTraceId(`startup-${toolName}`) });
  102. expect((await runtime.executeTurn("Search")).response).toBe("done");
  103. expect((await runtime.executeTurn("Use the previous result")).response).toBe("done");
  104. expect(modelCallCount).toBe(3);
  105. expect(mcpCallCount).toBe(1);
  106. expect(toolResult.structuredContent).toEqual(structuredContent);
  107. },
  108. );
  109. it("keeps the session resident while detached MCP startup is pending", async () => {
  110. const sessionId = createSessionId("runtime-mcp-residency");
  111. const startup = deferred<McpConnectionSnapshot>();
  112. const runtime = createTestAgentRuntime(
  113. sessionId,
  114. {
  115. mode: "build",
  116. mcp: {
  117. enabled: true,
  118. servers: {
  119. local: {
  120. type: "stdio",
  121. command: "node",
  122. args: ["server.js"],
  123. },
  124. },
  125. },
  126. },
  127. {
  128. eventStore: createTestSessionEventStore(),
  129. mcpPort: createMockMcpPort({
  130. connectConfiguredServers: async () => startup.promise,
  131. }),
  132. },
  133. );
  134. expect(runtime.hasResidencyBlockingWork()).toBe(true);
  135. startup.resolve(emptyMcpSnapshot());
  136. await runtime.startMcpStartup({
  137. sessionId,
  138. traceId: createTraceId("runtime-mcp-residency"),
  139. });
  140. expect(runtime.hasResidencyBlockingWork()).toBe(false);
  141. });
  142. it("starts configured MCP servers when the runtime is constructed", () => {
  143. const sessionId = createSessionId("runtime-mcp-startup");
  144. const eventStore = createTestSessionEventStore();
  145. let connectCalls = 0;
  146. const mcpPort = createMockMcpPort({
  147. connectConfiguredServers: async () => {
  148. connectCalls++;
  149. return emptyMcpSnapshot();
  150. },
  151. });
  152. createTestAgentRuntime(
  153. sessionId,
  154. {
  155. mode: "build",
  156. mcp: {
  157. enabled: true,
  158. servers: {
  159. local: {
  160. type: "stdio",
  161. command: "node",
  162. args: ["server.js"],
  163. },
  164. },
  165. },
  166. },
  167. {
  168. eventStore,
  169. mcpPort,
  170. },
  171. );
  172. expect(connectCalls).toBe(1);
  173. });
  174. it("passes a 15s OAuth authorization wait limit to session MCP startup", () => {
  175. const sessionId = createSessionId("runtime-mcp-oauth-timeout");
  176. const eventStore = createTestSessionEventStore();
  177. let connectOptions: Parameters<McpPort["connectConfiguredServers"]>[1];
  178. const mcpPort = createMockMcpPort({
  179. connectConfiguredServers: async (_servers, options) => {
  180. connectOptions = options;
  181. return emptyMcpSnapshot();
  182. },
  183. });
  184. createTestAgentRuntime(
  185. sessionId,
  186. {
  187. mode: "build",
  188. mcp: {
  189. enabled: true,
  190. servers: {
  191. notion: {
  192. type: "http",
  193. url: "https://mcp.example.test/mcp",
  194. oauth: {
  195. type: "authorization_code",
  196. },
  197. },
  198. },
  199. },
  200. },
  201. {
  202. eventStore,
  203. mcpPort,
  204. },
  205. );
  206. expect(connectOptions?.oauthAuthorizationTimeoutMs).toBe(15_000);
  207. });
  208. it("emits turn_started before pending MCP startup resolves and waits before model request", async () => {
  209. const sessionId = createSessionId("runtime-mcp-background-startup");
  210. const eventStore = createTestSessionEventStore();
  211. const startup = deferred<McpConnectionSnapshot>();
  212. let modelRequestCount = 0;
  213. let toolNames: string[] = [];
  214. const mcpPort = createMockMcpPort({
  215. connectConfiguredServers: async () => startup.promise,
  216. });
  217. const runtime = createTestAgentRuntime(
  218. sessionId,
  219. {
  220. mode: "build",
  221. mcp: {
  222. enabled: true,
  223. servers: {
  224. local: {
  225. type: "stdio",
  226. command: "node",
  227. args: ["server.js"],
  228. },
  229. },
  230. },
  231. },
  232. {
  233. eventStore,
  234. mcpPort,
  235. modelFactory: createTestModelFactory({
  236. async generateText(request: any) {
  237. modelRequestCount++;
  238. toolNames = request.tools.map((tool: { name: string }) => tool.name);
  239. return {
  240. finishReason: "stop",
  241. providerMetadata: undefined,
  242. text: "done",
  243. usage: {
  244. inputTokens: 1,
  245. outputTokens: 1,
  246. totalTokens: 2,
  247. },
  248. };
  249. },
  250. } as never),
  251. },
  252. );
  253. const turn = runtime.executeTurn("use mcp if needed");
  254. await waitForEvent(eventStore, sessionId, SessionEventType.TurnStarted);
  255. expect(modelRequestCount).toBe(0);
  256. startup.resolve({
  257. statuses: {
  258. local: {
  259. status: "connected",
  260. transport: "stdio",
  261. toolCount: 1,
  262. updatedAt: "now",
  263. },
  264. },
  265. tools: [
  266. {
  267. serverName: "local",
  268. toolName: "ping",
  269. inputSchema: {
  270. type: "object",
  271. properties: {},
  272. },
  273. annotations: {
  274. readOnlyHint: true,
  275. },
  276. },
  277. ],
  278. });
  279. await turn;
  280. expect(modelRequestCount).toBe(1);
  281. expect(toolNames).toContain("mcp__local__ping");
  282. });
  283. it("uses the cached catalog without waiting and applies the live list on the next request", async () => {
  284. const sessionId = createSessionId("runtime-mcp-cached-startup");
  285. const startup = deferred<McpConnectionSnapshot>();
  286. const providerToolSnapshots: string[] = [];
  287. const publishedSnapshots: Record<string, McpServerToolSnapshot>[] = [];
  288. let listToolsCalls = 0;
  289. const cachedTool = {
  290. serverName: "local",
  291. toolName: "ping",
  292. description: "cached description",
  293. inputSchema: { type: "object", properties: {} } as const,
  294. };
  295. const snapshot: Record<string, McpServerToolSnapshot> = {
  296. local: { status: mcpStatus("connecting") },
  297. };
  298. const catalogPort: McpToolCatalogPort = {
  299. prepare: () => ({
  300. lookup: { status: "complete", byServer: { local: [cachedTool] } },
  301. publish: (published) => {
  302. publishedSnapshots.push(published);
  303. },
  304. }),
  305. };
  306. const runtime = createTestAgentRuntime(
  307. sessionId,
  308. {
  309. mode: "build",
  310. mcp: {
  311. enabled: true,
  312. servers: {
  313. local: { type: "stdio", command: "node", args: ["server.js"] },
  314. },
  315. },
  316. },
  317. {
  318. eventStore: createTestSessionEventStore(),
  319. mcpPort: createSnapshotMcpPort(snapshot, {
  320. connectConfiguredServers: async () => startup.promise,
  321. // 快照端口不再走 listTools 轮询;请求准备只读内存快照。
  322. listTools: async () => {
  323. listToolsCalls += 1;
  324. return [];
  325. },
  326. }),
  327. mcpStartupPolicy: "background",
  328. mcpToolCatalogPort: catalogPort,
  329. modelAdapter: {
  330. async generateText(request: any) {
  331. providerToolSnapshots.push(JSON.stringify(request.tools));
  332. return {
  333. finishReason: "stop",
  334. model: request.model,
  335. providerMetadata: undefined,
  336. text: "done",
  337. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  338. };
  339. },
  340. } as never,
  341. },
  342. );
  343. await runtime.executeTurn("first request");
  344. expect(providerToolSnapshots).toHaveLength(1);
  345. expect(providerToolSnapshots[0]).toContain("mcp__local__ping");
  346. expect(providerToolSnapshots[0]).toContain("cached description");
  347. const liveTools = [
  348. {
  349. ...cachedTool,
  350. description: "live description changed",
  351. inputSchema: {
  352. type: "object" as const,
  353. properties: { live: { type: "boolean" } },
  354. },
  355. },
  356. {
  357. serverName: "local",
  358. toolName: "new-tool",
  359. inputSchema: { type: "object" as const, properties: {} },
  360. },
  361. ];
  362. snapshot.local = { status: mcpStatus("connected"), tools: liveTools, toolsVersion: "c1:1" };
  363. startup.resolve({ statuses: { local: mcpStatus("connected") }, tools: liveTools });
  364. await runtime.startMcpStartup({ sessionId, traceId: createTraceId("cached-startup") });
  365. await runtime.executeTurn("second request");
  366. expect(publishedSnapshots.at(-1)?.local?.tools).toEqual(liveTools);
  367. expect(providerToolSnapshots).toHaveLength(2);
  368. expect(providerToolSnapshots[1]).toContain("live description changed");
  369. expect(providerToolSnapshots[1]).toContain("mcp__local__new-tool");
  370. expect(listToolsCalls).toBe(0);
  371. });
  372. it("applies the official CUA name projection to cached catalog entries", async () => {
  373. // 缓存命中走快照注册路径时,官方 CUA 的规范名投影 / 别名必须同样成立,
  374. // 且执行期 live 解析要按同一投影规则比对名称。
  375. const TEST_PLUGIN_AUTHORITY = "test-plugin-authority";
  376. sanitizeZCodeRuntimeEnv({
  377. ZCODE_CUA_PERMISSION_BROKER_SOCKET: "/tmp/zcode-cua-test.sock",
  378. ZCODE_CUA_PERMISSION_BROKER_TOKEN: "test-broker-token",
  379. [ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]: TEST_PLUGIN_AUTHORITY,
  380. });
  381. const sessionId = createSessionId("runtime-mcp-cached-cua");
  382. const cuaTool = {
  383. serverName: ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME,
  384. toolName: "open_application",
  385. name: "mcp__plugin_zcode-cua_computer-use__open_application",
  386. inputSchema: { type: "object", properties: {} } as const,
  387. };
  388. const snapshot: Record<string, McpServerToolSnapshot> = {
  389. [ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME]: { status: mcpStatus("connecting") },
  390. };
  391. const runtime = createTestAgentRuntime(
  392. sessionId,
  393. {
  394. mode: "build",
  395. mcp: {
  396. enabled: true,
  397. servers: {
  398. [ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME]: {
  399. type: "stdio",
  400. command: "zcode-cua",
  401. env: {
  402. [ZCODE_PLUGIN_ID_ENV_KEY]: ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  403. [ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]: TEST_PLUGIN_AUTHORITY,
  404. },
  405. },
  406. },
  407. trustedOfficialCuaServerNames: [ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME],
  408. },
  409. },
  410. {
  411. eventStore: createTestSessionEventStore(),
  412. mcpPort: createSnapshotMcpPort(snapshot, {
  413. connectConfiguredServers: () => new Promise(() => {}),
  414. }),
  415. mcpStartupPolicy: "background",
  416. mcpToolCatalogPort: {
  417. prepare: () => ({
  418. lookup: {
  419. status: "complete",
  420. byServer: { [ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME]: [cuaTool] },
  421. },
  422. publish: () => {},
  423. }),
  424. },
  425. modelAdapter: createStopModelAdapter(),
  426. },
  427. );
  428. await runtime.executeTurn("first request");
  429. const registry = runtime.getToolRegistry();
  430. const canonical = registry.get("mcp__computer-use__open_application");
  431. expect(canonical).toBeDefined();
  432. expect(registry.get("mcp__computer_use__open_application")).toBe(canonical);
  433. expect(registry.get("mcp__plugin_zcode-cua_computer-use__open_application")).toBeUndefined();
  434. expect((canonical as { permissionCapabilityGroup?: string }).permissionCapabilityGroup).toBe(
  435. "official_cua",
  436. );
  437. snapshot[ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME] = {
  438. status: mcpStatus("connected"),
  439. tools: [cuaTool],
  440. toolsVersion: "c1:1",
  441. };
  442. const resolution = await canonical!.resolveForExecution!({});
  443. expect(resolution.status).toBe("ready");
  444. if (resolution.status === "ready") {
  445. expect(resolution.entry.metadata.name).toBe("mcp__computer-use__open_application");
  446. }
  447. });
  448. it("waits only for the target server and revalidates cached tools before permission", async () => {
  449. const sessionId = createSessionId("runtime-mcp-cached-live-preflight");
  450. const serverReady = deferred<{ timedOut: boolean }>();
  451. const waitCalls: { serverName: string; timeoutMs: number }[] = [];
  452. let modelRequestCount = 0;
  453. let mcpCallCount = 0;
  454. const cachedTool = {
  455. serverName: "device",
  456. toolName: "reset",
  457. inputSchema: { type: "object", properties: {} } as const,
  458. };
  459. const snapshot: Record<string, McpServerToolSnapshot> = {
  460. device: { status: mcpStatus("connecting") },
  461. other: { status: mcpStatus("connecting") },
  462. };
  463. const runtime = createTestAgentRuntime(
  464. sessionId,
  465. {
  466. mode: "plan",
  467. mcp: {
  468. enabled: true,
  469. servers: {
  470. device: { type: "stdio", command: "node", args: ["server.js"] },
  471. other: { type: "stdio", command: "node", args: ["other.js"] },
  472. },
  473. },
  474. },
  475. {
  476. eventStore: createTestSessionEventStore(),
  477. mcpPort: createSnapshotMcpPort(snapshot, {
  478. connectConfiguredServers: () => new Promise(() => {}),
  479. waitForServer: (serverName, options) => {
  480. waitCalls.push({ serverName, timeoutMs: options.timeoutMs });
  481. return serverReady.promise;
  482. },
  483. callTool: async () => {
  484. mcpCallCount++;
  485. return { content: [{ type: "text", text: "should-not-run" }] };
  486. },
  487. }),
  488. mcpStartupPolicy: "background",
  489. mcpToolCatalogPort: {
  490. prepare: () => ({
  491. lookup: { status: "complete", byServer: { device: [cachedTool] } },
  492. publish: () => {},
  493. }),
  494. },
  495. modelAdapter: {
  496. async generateText(request: any) {
  497. modelRequestCount++;
  498. if (modelRequestCount === 1) {
  499. snapshot.device.status = mcpStatus("disconnected");
  500. return toolCallResult(request, "reset", "mcp__device__reset");
  501. }
  502. return stopModelResult(request);
  503. },
  504. } as never,
  505. },
  506. );
  507. const turn = runtime.executeTurn("do not mutate");
  508. await waitForCondition(() => waitCalls.length === 1);
  509. // 已注册工具使用连接超时,不能继承搜索的短等待预算。
  510. expect(waitCalls).toEqual([{ serverName: "device", timeoutMs: 30_000 }]);
  511. snapshot.device = {
  512. status: mcpStatus("connected"),
  513. tools: [{ ...cachedTool, annotations: { destructiveHint: true } }],
  514. toolsVersion: "c1:1",
  515. };
  516. serverReady.resolve({ timedOut: false });
  517. await turn;
  518. expect(modelRequestCount).toBe(2);
  519. expect(mcpCallCount).toBe(0);
  520. });
  521. it("reports a timed-out server wait as unavailable without calling the server", async () => {
  522. const sessionId = createSessionId("runtime-mcp-wait-timeout");
  523. const eventStore = createTestSessionEventStore();
  524. const waitCalls: number[] = [];
  525. let mcpCallCount = 0;
  526. const cachedTool = {
  527. serverName: "slow",
  528. toolName: "lookup",
  529. inputSchema: { type: "object", properties: {} } as const,
  530. };
  531. const runtime = createTestAgentRuntime(
  532. sessionId,
  533. {
  534. mode: "plan",
  535. mcp: {
  536. enabled: true,
  537. servers: {
  538. slow: { type: "stdio", command: "node", args: ["server.js"], timeoutMs: 3_000 },
  539. },
  540. },
  541. },
  542. {
  543. eventStore,
  544. mcpPort: createSnapshotMcpPort(
  545. { slow: { status: mcpStatus("connecting") } },
  546. {
  547. connectConfiguredServers: () => new Promise(() => {}),
  548. waitForServer: async (_serverName, options) => {
  549. waitCalls.push(options.timeoutMs);
  550. return { timedOut: true };
  551. },
  552. callTool: async () => {
  553. mcpCallCount++;
  554. return { content: [{ type: "text", text: "should-not-run" }] };
  555. },
  556. },
  557. ),
  558. mcpStartupPolicy: "background",
  559. mcpToolCatalogPort: {
  560. prepare: () => ({
  561. lookup: { status: "complete", byServer: { slow: [cachedTool] } },
  562. publish: () => {},
  563. }),
  564. },
  565. modelFactory: createTestModelFactory({
  566. async generateText(request: any) {
  567. if (!request.messages.some((message: any) => message.role === "tool")) {
  568. return toolCallResult(request, "lookup", "mcp__slow__lookup");
  569. }
  570. return stopModelResult(request);
  571. },
  572. } as never),
  573. },
  574. );
  575. await runtime.executeTurn("look it up");
  576. expect(waitCalls).toEqual([3_000]);
  577. expect(mcpCallCount).toBe(0);
  578. });
  579. it.each([
  580. {
  581. label: "reconnects and checks the recovered definition",
  582. recovered: (tool: McpToolDescriptor): McpServerToolSnapshot => ({
  583. status: mcpStatus("connected"),
  584. tools: [{ ...tool, annotations: { destructiveHint: true } }],
  585. toolsVersion: "c2:1",
  586. }),
  587. },
  588. {
  589. label: "reports a failed reconnect as unavailable",
  590. recovered: (): McpServerToolSnapshot => ({ status: mcpStatus("failed") }),
  591. },
  592. ])("does not run a disconnected server's stale definition: $label", async ({ recovered }) => {
  593. const sessionId = createSessionId("runtime-mcp-disconnected-preflight");
  594. const waitCalls: { reconnect?: boolean; reauthorize?: boolean }[] = [];
  595. let mcpCallCount = 0;
  596. const staleTool = {
  597. serverName: "device",
  598. toolName: "reset",
  599. inputSchema: { type: "object", properties: {} } as const,
  600. annotations: { readOnlyHint: true },
  601. };
  602. const snapshot: Record<string, McpServerToolSnapshot> = {
  603. device: { status: mcpStatus("connected"), tools: [staleTool], toolsVersion: "c1:1" },
  604. };
  605. const runtime = createTestAgentRuntime(
  606. sessionId,
  607. {
  608. mode: "plan",
  609. mcp: {
  610. enabled: true,
  611. servers: { device: { type: "stdio", command: "node", args: ["server.js"] } },
  612. },
  613. },
  614. {
  615. eventStore: createTestSessionEventStore(),
  616. mcpPort: createSnapshotMcpPort(snapshot, {
  617. connectConfiguredServers: () => new Promise(() => {}),
  618. waitForServer: async (_serverName, options) => {
  619. waitCalls.push({ reconnect: options.reconnect, reauthorize: options.reauthorize });
  620. // 执行前检查要求重连:断线 server 恢复后发布新定义,或重连失败。
  621. if (options.reconnect) snapshot.device = recovered(staleTool);
  622. return { timedOut: false };
  623. },
  624. callTool: async () => {
  625. mcpCallCount++;
  626. return { content: [{ type: "text", text: "should-not-run" }] };
  627. },
  628. }),
  629. mcpStartupPolicy: "background",
  630. modelFactory: createTestModelFactory({
  631. async generateText(request: any) {
  632. if (!request.messages.some((message: any) => message.role === "tool")) {
  633. snapshot.device.status = mcpStatus("disconnected");
  634. return toolCallResult(request, "reset", "mcp__device__reset");
  635. }
  636. return stopModelResult(request);
  637. },
  638. } as never),
  639. },
  640. );
  641. await runtime.executeTurn("reset the device");
  642. expect(mcpCallCount).toBe(0);
  643. // 只有工具执行准入要求授权失败的 server 重新授权;MCP App 打开不传。
  644. expect(waitCalls).toEqual([{ reconnect: true, reauthorize: true }]);
  645. });
  646. it("keeps remote workspaces on the cold path until remote session identity is available", async () => {
  647. const sessionId = createSessionId("runtime-mcp-remote-cold");
  648. const startup = deferred<McpConnectionSnapshot>();
  649. let catalogPrepareCount = 0;
  650. let modelRequestCount = 0;
  651. const runtime = createTestAgentRuntime(
  652. sessionId,
  653. {
  654. mode: "build",
  655. mcp: {
  656. enabled: true,
  657. servers: {
  658. remote: { type: "stdio", command: "node", args: ["server.js"] },
  659. },
  660. },
  661. workspaceIdentity: createWorkspaceId("ssh://host/workspace"),
  662. },
  663. {
  664. eventStore: createTestSessionEventStore(),
  665. isRemoteWorkspace: () => true,
  666. mcpPort: createMockMcpPort({
  667. connectConfiguredServers: async () => startup.promise,
  668. }),
  669. mcpToolCatalogPort: {
  670. prepare: () => {
  671. catalogPrepareCount++;
  672. return {
  673. lookup: {
  674. status: "complete",
  675. byServer: {
  676. remote: [
  677. {
  678. serverName: "remote",
  679. toolName: "cached",
  680. inputSchema: { type: "object", properties: {} },
  681. },
  682. ],
  683. },
  684. },
  685. publish: () => {},
  686. };
  687. },
  688. },
  689. modelAdapter: {
  690. async generateText(request: any) {
  691. modelRequestCount++;
  692. return stopModelResult(request);
  693. },
  694. } as never,
  695. },
  696. );
  697. const turn = runtime.executeTurn("remote request");
  698. await waitForCondition(() => runtime.hasResidencyBlockingWork());
  699. expect(catalogPrepareCount).toBe(0);
  700. expect(modelRequestCount).toBe(0);
  701. startup.resolve(emptyMcpSnapshot());
  702. await turn;
  703. expect(modelRequestCount).toBe(1);
  704. });
  705. it("does not register or cache a startup that resolves after shutdown began", async () => {
  706. const sessionId = createSessionId("runtime-mcp-late-startup-after-shutdown");
  707. const startup = deferred<McpConnectionSnapshot>();
  708. let publishCount = 0;
  709. const liveTool = {
  710. serverName: "local",
  711. toolName: "ping",
  712. inputSchema: { type: "object", properties: {} } as const,
  713. };
  714. const snapshot: Record<string, McpServerToolSnapshot> = {
  715. local: { status: mcpStatus("connecting") },
  716. };
  717. const runtime = createTestAgentRuntime(
  718. sessionId,
  719. {
  720. mode: "build",
  721. mcp: {
  722. enabled: true,
  723. servers: { local: { type: "stdio", command: "node", args: ["server.js"] } },
  724. },
  725. },
  726. {
  727. eventStore: createTestSessionEventStore(),
  728. mcpPort: createSnapshotMcpPort(snapshot, {
  729. connectConfiguredServers: async () => startup.promise,
  730. }),
  731. mcpToolCatalogPort: {
  732. prepare: () => ({
  733. lookup: { status: "incomplete", byServer: {} },
  734. publish: (rows) => {
  735. if (Object.values(rows).some((row) => row.status.status === "connected"))
  736. publishCount++;
  737. },
  738. }),
  739. },
  740. modelAdapter: createStopModelAdapter(),
  741. },
  742. );
  743. const turn = runtime.executeTurn("blocking request");
  744. await waitForCondition(() => runtime.hasResidencyBlockingWork());
  745. // 等待启动期间开始关闭,随后启动成功返回。
  746. runtime.beginShutdown();
  747. snapshot.local = { status: mcpStatus("connected"), tools: [liveTool], toolsVersion: "c1:1" };
  748. startup.resolve({ statuses: { local: mcpStatus("connected") }, tools: [liveTool] });
  749. await turn.catch(() => {});
  750. expect(runtime.getToolRegistry().get("mcp__local__ping")).toBeUndefined();
  751. expect(publishCount).toBe(0);
  752. });
  753. it.each([
  754. {
  755. label: "reordered tools with the same content",
  756. next: (tools: McpToolDescriptor[]) => [...tools].reverse(),
  757. reregistered: false,
  758. },
  759. {
  760. label: "a repeated list_changed with identical content",
  761. next: (tools: McpToolDescriptor[]) => tools.map((tool) => ({ ...tool })),
  762. reregistered: false,
  763. },
  764. {
  765. label: "a schema-only update",
  766. next: (tools: McpToolDescriptor[]) =>
  767. tools.map((tool) =>
  768. tool.toolName === "alpha"
  769. ? { ...tool, inputSchema: { type: "object", properties: { q: { type: "string" } } } }
  770. : tool,
  771. ),
  772. reregistered: true,
  773. },
  774. ])("compares MCP tool content across versions for $label", async ({ next, reregistered }) => {
  775. const sessionId = createSessionId("runtime-mcp-content-compare");
  776. const toolNames: string[][] = [];
  777. const tools: McpToolDescriptor[] = [
  778. { serverName: "a", toolName: "alpha", inputSchema: { type: "object", properties: {} } },
  779. { serverName: "a", toolName: "beta", inputSchema: { type: "object", properties: {} } },
  780. ];
  781. const snapshot: Record<string, McpServerToolSnapshot> = {
  782. a: { status: mcpStatus("connected"), tools, toolsVersion: "c1:1" },
  783. };
  784. const runtime = createTestAgentRuntime(
  785. sessionId,
  786. {
  787. mode: "build",
  788. mcp: {
  789. enabled: true,
  790. servers: { a: { type: "stdio", command: "node", args: ["a.js"] } },
  791. },
  792. titleGeneration: { enabled: false },
  793. },
  794. {
  795. eventStore: createTestSessionEventStore(),
  796. mcpPort: createSnapshotMcpPort(snapshot, {
  797. connectConfiguredServers: () => new Promise(() => {}),
  798. }),
  799. mcpStartupPolicy: "background",
  800. modelAdapter: createStopModelAdapter(toolNames),
  801. },
  802. );
  803. await runtime.executeTurn("first");
  804. const before = runtime.getToolRegistry().get("mcp__a__alpha");
  805. snapshot.a = { status: mcpStatus("connected"), tools: next(tools), toolsVersion: "c1:2" };
  806. await runtime.executeTurn("second");
  807. const after = runtime.getToolRegistry().get("mcp__a__alpha");
  808. const mcpOrder = (names: string[] | undefined) =>
  809. names?.filter((name) => name.startsWith("mcp__"));
  810. expect(mcpOrder(toolNames[1])).toEqual(mcpOrder(toolNames[0]));
  811. if (reregistered) expect(after).not.toBe(before);
  812. else expect(after).toBe(before);
  813. });
  814. it("does not wait for MCP startup on a background request without cache", async () => {
  815. const sessionId = createSessionId("runtime-mcp-background-cold");
  816. const toolNames: string[][] = [];
  817. const snapshot: Record<string, McpServerToolSnapshot> = {
  818. local: { status: mcpStatus("connecting") },
  819. };
  820. const runtime = createTestAgentRuntime(
  821. sessionId,
  822. {
  823. mode: "build",
  824. mcp: {
  825. enabled: true,
  826. servers: { local: { type: "stdio", command: "node", args: ["server.js"] } },
  827. },
  828. },
  829. {
  830. eventStore: createTestSessionEventStore(),
  831. mcpPort: createSnapshotMcpPort(snapshot, {
  832. connectConfiguredServers: () => new Promise(() => {}),
  833. }),
  834. mcpStartupPolicy: "background",
  835. modelAdapter: createStopModelAdapter(toolNames),
  836. },
  837. );
  838. await runtime.executeTurn("first request");
  839. expect(toolNames[0]?.some((name) => name.startsWith("mcp__"))).toBe(false);
  840. });
  841. it("waits for MCP startup by default even when the port exposes tool snapshots", async () => {
  842. const sessionId = createSessionId("runtime-mcp-snapshot-blocking");
  843. const startup = deferred<McpConnectionSnapshot>();
  844. const toolNames: string[][] = [];
  845. const liveTool = {
  846. serverName: "local",
  847. toolName: "ping",
  848. inputSchema: { type: "object", properties: {} } as const,
  849. };
  850. const snapshot: Record<string, McpServerToolSnapshot> = {
  851. local: { status: mcpStatus("connecting") },
  852. };
  853. const runtime = createTestAgentRuntime(
  854. sessionId,
  855. {
  856. mode: "build",
  857. mcp: {
  858. enabled: true,
  859. servers: { local: { type: "stdio", command: "node", args: ["server.js"] } },
  860. },
  861. },
  862. {
  863. eventStore: createTestSessionEventStore(),
  864. mcpPort: createSnapshotMcpPort(snapshot, {
  865. connectConfiguredServers: async () => startup.promise,
  866. }),
  867. modelAdapter: createStopModelAdapter(toolNames),
  868. },
  869. );
  870. const turn = runtime.executeTurn("blocking request");
  871. await waitForCondition(() => runtime.hasResidencyBlockingWork());
  872. expect(toolNames).toHaveLength(0);
  873. snapshot.local = { status: mcpStatus("connected"), tools: [liveTool], toolsVersion: "c1:1" };
  874. startup.resolve({ statuses: { local: mcpStatus("connected") }, tools: [liveTool] });
  875. await turn;
  876. expect(toolNames[0]).toContain("mcp__local__ping");
  877. });
  878. it.each([
  879. ["automation", { automationId: "automation-1" }],
  880. ["off-peak", { offPeakTaskId: "offpeak-1" }],
  881. ] as const)(
  882. "waits for MCP startup on a background-policy %s turn",
  883. async (label, attribution) => {
  884. const sessionId = createSessionId(`runtime-mcp-auto-${label}`);
  885. const startup = deferred<McpConnectionSnapshot>();
  886. const toolNames: string[][] = [];
  887. const liveTool = {
  888. serverName: "local",
  889. toolName: "ping",
  890. inputSchema: { type: "object", properties: {} } as const,
  891. };
  892. const snapshot: Record<string, McpServerToolSnapshot> = {
  893. local: { status: mcpStatus("connecting") },
  894. };
  895. const runtime = createTestAgentRuntime(
  896. sessionId,
  897. {
  898. mode: "build",
  899. mcp: {
  900. enabled: true,
  901. servers: { local: { type: "stdio", command: "node", args: ["server.js"] } },
  902. },
  903. },
  904. {
  905. eventStore: createTestSessionEventStore(),
  906. mcpPort: createSnapshotMcpPort(snapshot, {
  907. connectConfiguredServers: async () => startup.promise,
  908. }),
  909. mcpStartupPolicy: "background",
  910. modelAdapter: createStopModelAdapter(toolNames),
  911. },
  912. );
  913. // 自动任务无人可交互,即使会话策略是 background 也必须等启动结束。
  914. const turn = runtime.executeTurn("automatic task", undefined, attribution);
  915. // 启动未释放前模型请求不得发出;background 不等待时这里会先看到模型请求。
  916. await expect(waitForCondition(() => toolNames.length > 0)).rejects.toThrow("Timed out");
  917. snapshot.local = { status: mcpStatus("connected"), tools: [liveTool], toolsVersion: "c1:1" };
  918. startup.resolve({ statuses: { local: mcpStatus("connected") }, tools: [liveTool] });
  919. await turn;
  920. expect(toolNames[0]).toContain("mcp__local__ping");
  921. },
  922. );
  923. it.each([
  924. ["reconnecting", { status: mcpStatus("connecting") }],
  925. ["failed", { status: mcpStatus("failed") }],
  926. [
  927. "oauth pending",
  928. {
  929. status: {
  930. ...mcpStatus("connecting"),
  931. authorization: {
  932. type: "oauth_authorization_code",
  933. authorizationUrl: "https://auth.example.com/authorize",
  934. startedAt: "now",
  935. },
  936. },
  937. },
  938. ],
  939. ] as const)(
  940. "uses the connection snapshot during recovery and clears terminal failure: %s",
  941. async (_label, reconnecting) => {
  942. const sessionId = createSessionId(`runtime-mcp-keep-shown-${_label}`);
  943. const toolNames: string[][] = [];
  944. const docsTool = {
  945. serverName: "docs",
  946. toolName: "search",
  947. inputSchema: { type: "object", properties: {} } as const,
  948. };
  949. const snapshot: Record<string, McpServerToolSnapshot> = {
  950. docs: { status: mcpStatus("connected"), tools: [docsTool], toolsVersion: "c1:1" },
  951. };
  952. const runtime = createTestAgentRuntime(
  953. sessionId,
  954. {
  955. mode: "build",
  956. mcp: {
  957. enabled: true,
  958. servers: { docs: { type: "http", url: "https://mcp.example.com/docs" } },
  959. },
  960. },
  961. {
  962. eventStore: createTestSessionEventStore(),
  963. mcpPort: createSnapshotMcpPort(snapshot, {
  964. connectConfiguredServers: () => new Promise(() => {}),
  965. }),
  966. mcpStartupPolicy: "background",
  967. modelAdapter: createStopModelAdapter(toolNames),
  968. },
  969. );
  970. await runtime.executeTurn("first");
  971. // 重连保留目录由连接层负责;session 不再维护另一份旧列表。
  972. snapshot.docs = { ...reconnecting, tools: [docsTool], toolsVersion: "c1:1" };
  973. await runtime.executeTurn("second");
  974. // 合法的空清单才替换已展示的工具。
  975. snapshot.docs = { status: mcpStatus("connected"), tools: [], toolsVersion: "c2:1" };
  976. await runtime.executeTurn("third");
  977. expect(toolNames[0]).toContain("mcp__docs__search");
  978. if (_label === "failed") expect(toolNames[1]).not.toContain("mcp__docs__search");
  979. else expect(toolNames[1]).toContain("mcp__docs__search");
  980. expect(toolNames[2]).not.toContain("mcp__docs__search");
  981. },
  982. );
  983. it.each(["disabled", "untrusted"] as const)(
  984. "drops the shown list of a %s server",
  985. async (status) => {
  986. const sessionId = createSessionId(`runtime-mcp-drop-shown-${status}`);
  987. const toolNames: string[][] = [];
  988. const docsTool = {
  989. serverName: "docs",
  990. toolName: "search",
  991. inputSchema: { type: "object", properties: {} } as const,
  992. };
  993. const snapshot: Record<string, McpServerToolSnapshot> = {
  994. docs: { status: mcpStatus("connected"), tools: [docsTool], toolsVersion: "c1:1" },
  995. };
  996. const runtime = createTestAgentRuntime(
  997. sessionId,
  998. {
  999. mode: "build",
  1000. mcp: {
  1001. enabled: true,
  1002. servers: { docs: { type: "http", url: "https://mcp.example.com/docs" } },
  1003. },
  1004. },
  1005. {
  1006. eventStore: createTestSessionEventStore(),
  1007. mcpPort: createSnapshotMcpPort(snapshot, {
  1008. connectConfiguredServers: () => new Promise(() => {}),
  1009. }),
  1010. mcpStartupPolicy: "background",
  1011. modelAdapter: createStopModelAdapter(toolNames),
  1012. },
  1013. );
  1014. await runtime.executeTurn("first");
  1015. snapshot.docs = { status: mcpStatus(status) };
  1016. await runtime.executeTurn("second");
  1017. expect(toolNames[0]).toContain("mcp__docs__search");
  1018. expect(toolNames[1]).not.toContain("mcp__docs__search");
  1019. },
  1020. );
  1021. it("applies a server published during a tool call on the next request of the same turn", async () => {
  1022. const sessionId = createSessionId("runtime-mcp-publish-mid-turn");
  1023. const toolNames: string[][] = [];
  1024. const pingTool = {
  1025. serverName: "a",
  1026. toolName: "ping",
  1027. inputSchema: { type: "object", properties: {} } as const,
  1028. };
  1029. const lateTool = {
  1030. serverName: "b",
  1031. toolName: "late",
  1032. inputSchema: { type: "object", properties: {} } as const,
  1033. };
  1034. const snapshot: Record<string, McpServerToolSnapshot> = {
  1035. a: { status: mcpStatus("connected"), tools: [pingTool], toolsVersion: "c1:1" },
  1036. b: { status: mcpStatus("connecting") },
  1037. };
  1038. const runtime = createTestAgentRuntime(
  1039. sessionId,
  1040. {
  1041. // 用 yolo 让 MCP 工具免审批执行;本用例只验证同一轮下一次请求的工具列表,不验证权限。
  1042. mode: "yolo",
  1043. mcp: {
  1044. enabled: true,
  1045. servers: {
  1046. a: { type: "stdio", command: "node", args: ["a.js"] },
  1047. b: { type: "stdio", command: "node", args: ["b.js"] },
  1048. },
  1049. },
  1050. },
  1051. {
  1052. eventStore: createTestSessionEventStore(),
  1053. mcpPort: createSnapshotMcpPort(snapshot, {
  1054. connectConfiguredServers: () => new Promise(() => {}),
  1055. callTool: async () => {
  1056. // server b 在工具调用期间就绪,下一次正常请求才生效。
  1057. snapshot.b = {
  1058. status: mcpStatus("connected"),
  1059. tools: [lateTool],
  1060. toolsVersion: "c2:1",
  1061. };
  1062. return { content: [{ type: "text", text: "pong" }] };
  1063. },
  1064. }),
  1065. mcpStartupPolicy: "background",
  1066. modelAdapter: {
  1067. async generateText(request: any) {
  1068. toolNames.push(request.tools.map((tool: { name: string }) => tool.name));
  1069. if (toolNames.length === 1) return toolCallResult(request, "ping", "mcp__a__ping");
  1070. return stopModelResult(request);
  1071. },
  1072. } as never,
  1073. },
  1074. );
  1075. await runtime.executeTurn("ping");
  1076. expect(toolNames).toHaveLength(2);
  1077. expect(toolNames[0]).toContain("mcp__a__ping");
  1078. expect(toolNames[0]).not.toContain("mcp__b__late");
  1079. expect(toolNames[1]).toContain("mcp__b__late");
  1080. });
  1081. it("keeps the request tool list fixed during output token continuation", async () => {
  1082. const sessionId = createSessionId("runtime-mcp-continuation-fixed");
  1083. const toolNames: string[][] = [];
  1084. const snapshot: Record<string, McpServerToolSnapshot> = {
  1085. a: { status: mcpStatus("connecting") },
  1086. };
  1087. const runtime = createTestAgentRuntime(
  1088. sessionId,
  1089. {
  1090. mode: "build",
  1091. mcp: {
  1092. enabled: true,
  1093. servers: { a: { type: "stdio", command: "node", args: ["a.js"] } },
  1094. },
  1095. titleGeneration: { enabled: false },
  1096. },
  1097. {
  1098. eventStore: createTestSessionEventStore(),
  1099. mcpPort: createSnapshotMcpPort(snapshot, {
  1100. connectConfiguredServers: () => new Promise(() => {}),
  1101. }),
  1102. mcpStartupPolicy: "background",
  1103. modelAdapter: {
  1104. async generateText(request: any) {
  1105. toolNames.push(request.tools.map((tool: { name: string }) => tool.name));
  1106. if (toolNames.length === 1) {
  1107. snapshot.a = {
  1108. status: mcpStatus("connected"),
  1109. tools: [
  1110. {
  1111. serverName: "a",
  1112. toolName: "late",
  1113. inputSchema: { type: "object", properties: {} },
  1114. },
  1115. ],
  1116. toolsVersion: "c1:1",
  1117. };
  1118. return { ...stopModelResult(request), finishReason: "length", text: "partial" };
  1119. }
  1120. return stopModelResult(request);
  1121. },
  1122. } as never,
  1123. },
  1124. );
  1125. await runtime.executeTurn("long answer");
  1126. expect(toolNames).toHaveLength(2);
  1127. expect(toolNames[1]).not.toContain("mcp__a__late");
  1128. await runtime.executeTurn("next request");
  1129. expect(toolNames[2]).toContain("mcp__a__late");
  1130. });
  1131. it("keeps the request tool list fixed during reasoning stream recovery", async () => {
  1132. const sessionId = createSessionId("runtime-mcp-stream-recovery-fixed");
  1133. const toolNames: string[][] = [];
  1134. const snapshot: Record<string, McpServerToolSnapshot> = {
  1135. a: { status: mcpStatus("connecting") },
  1136. };
  1137. const publishStatus = async (
  1138. observation: any,
  1139. requestId: string,
  1140. event: Record<string, unknown>,
  1141. ) =>
  1142. observation.invocationContext?.statusSink?.publish({
  1143. attempt: 1,
  1144. maxAttempts: 1,
  1145. providerId: String(observation.model.providerId),
  1146. modelId: String(observation.model.modelId),
  1147. requestId,
  1148. timestamp: new Date().toISOString(),
  1149. traceId:
  1150. observation.invocationContext?.traceContext?.traceId ?? createTraceId("mcp-recovery"),
  1151. transport: ModelTransportKind.Sse,
  1152. ...event,
  1153. });
  1154. const runtime = createTestAgentRuntime(
  1155. sessionId,
  1156. {
  1157. mode: "yolo",
  1158. modelStreaming: "on",
  1159. mcp: {
  1160. enabled: true,
  1161. servers: { a: { type: "stdio", command: "node", args: ["a.js"] } },
  1162. },
  1163. titleGeneration: { enabled: false },
  1164. },
  1165. {
  1166. eventStore: createTestSessionEventStore(),
  1167. mcpPort: createSnapshotMcpPort(snapshot, {
  1168. connectConfiguredServers: () => new Promise(() => {}),
  1169. }),
  1170. mcpStartupPolicy: "background",
  1171. modelFactory: createTestModelFactory({
  1172. async generateText() {
  1173. throw new Error("streaming path expected");
  1174. },
  1175. async *streamText(request: any, observation: any) {
  1176. toolNames.push(request.tools.map((tool: { name: string }) => tool.name));
  1177. const requestId = `mcp-recovery-${toolNames.length}`;
  1178. await publishStatus(observation, requestId, { type: "model_request_started" });
  1179. if (toolNames.length === 1) {
  1180. yield { type: "reasoning_start", id: "r1" };
  1181. yield { type: "reasoning_delta", id: "r1", text: "thinking" };
  1182. // 断流前 server 就绪;恢复请求仍沿用原请求的工具清单。
  1183. snapshot.a = {
  1184. status: mcpStatus("connected"),
  1185. tools: [
  1186. {
  1187. serverName: "a",
  1188. toolName: "late",
  1189. inputSchema: { type: "object", properties: {} },
  1190. },
  1191. ],
  1192. toolsVersion: "c1:1",
  1193. };
  1194. const error = new Error("Provider stream failed with ECONNRESET.") as Error & {
  1195. code?: string;
  1196. context?: Record<string, unknown>;
  1197. };
  1198. error.code = "model_network_error";
  1199. error.context = { reason: "network_error", retryable: true };
  1200. await publishStatus(observation, requestId, {
  1201. message: error.message,
  1202. reason: "network_error",
  1203. retryable: true,
  1204. type: "model_request_failed",
  1205. });
  1206. throw error;
  1207. }
  1208. yield { type: "text_delta", text: "done" };
  1209. yield {
  1210. type: "finish",
  1211. finishReason: "stop",
  1212. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1213. };
  1214. },
  1215. } as never),
  1216. },
  1217. );
  1218. await runtime.executeTurn("think");
  1219. expect(toolNames).toHaveLength(2);
  1220. expect(toolNames[1]).not.toContain("mcp__a__late");
  1221. await runtime.executeTurn("next request");
  1222. expect(toolNames[2]).toContain("mcp__a__late");
  1223. });
  1224. it.each([
  1225. {
  1226. label: "readOnly",
  1227. registered: { annotations: { readOnlyHint: true } },
  1228. live: { annotations: {} },
  1229. },
  1230. {
  1231. label: "model visibility",
  1232. registered: {},
  1233. live: { visibility: ["app"] as ("app" | "model")[] },
  1234. },
  1235. {
  1236. label: "destructive",
  1237. registered: { annotations: {} },
  1238. live: { annotations: { destructiveHint: true } },
  1239. },
  1240. {
  1241. label: "concurrency",
  1242. registered: { annotations: { idempotentHint: true } },
  1243. live: { annotations: {} },
  1244. },
  1245. ])("rejects a call when the live $label constraint is stricter", async ({ registered, live }) => {
  1246. const sessionId = createSessionId("runtime-mcp-stricter-live");
  1247. const eventStore = createTestSessionEventStore();
  1248. let mcpCallCount = 0;
  1249. const baseTool = {
  1250. serverName: "a",
  1251. toolName: "lookup",
  1252. inputSchema: { type: "object", properties: {} } as const,
  1253. };
  1254. const snapshot: Record<string, McpServerToolSnapshot> = {
  1255. a: {
  1256. status: mcpStatus("connected"),
  1257. tools: [{ ...baseTool, ...registered }],
  1258. toolsVersion: "c1:1",
  1259. },
  1260. };
  1261. const runtime = createTestAgentRuntime(
  1262. sessionId,
  1263. {
  1264. mode: "plan",
  1265. mcp: {
  1266. enabled: true,
  1267. servers: { a: { type: "stdio", command: "node", args: ["a.js"] } },
  1268. },
  1269. },
  1270. {
  1271. eventStore,
  1272. mcpPort: createSnapshotMcpPort(snapshot, {
  1273. connectConfiguredServers: () => new Promise(() => {}),
  1274. callTool: async () => {
  1275. mcpCallCount++;
  1276. return { content: [{ type: "text", text: "should-not-run" }] };
  1277. },
  1278. }),
  1279. mcpStartupPolicy: "background",
  1280. modelFactory: createTestModelFactory({
  1281. async generateText(request: any) {
  1282. if (!request.messages.some((message: any) => message.role === "tool")) {
  1283. snapshot.a = {
  1284. ...snapshot.a!,
  1285. tools: [{ ...baseTool, ...live }],
  1286. toolsVersion: "c1:2",
  1287. };
  1288. return toolCallResult(request, "lookup", "mcp__a__lookup");
  1289. }
  1290. return stopModelResult(request);
  1291. },
  1292. } as never),
  1293. },
  1294. );
  1295. await runtime.executeTurn("lookup");
  1296. expect(mcpCallCount).toBe(0);
  1297. const events = await eventStore.getEvents(sessionId);
  1298. expect(JSON.stringify(events)).toContain("stricter");
  1299. });
  1300. it("does not execute a read-only idempotent MCP call while the model is still streaming", async () => {
  1301. const sessionId = createSessionId("runtime-mcp-no-stream-execution");
  1302. let mcpCallCount = 0;
  1303. let callsBeforeFinish: number | undefined;
  1304. const snapshot: Record<string, McpServerToolSnapshot> = {
  1305. a: {
  1306. status: mcpStatus("connected"),
  1307. tools: [
  1308. {
  1309. serverName: "a",
  1310. toolName: "lookup",
  1311. inputSchema: { type: "object", properties: {} },
  1312. annotations: { readOnlyHint: true, idempotentHint: true },
  1313. },
  1314. ],
  1315. toolsVersion: "c1:1",
  1316. },
  1317. };
  1318. let requestCount = 0;
  1319. const runtime = createTestAgentRuntime(
  1320. sessionId,
  1321. {
  1322. mode: "yolo",
  1323. modelStreaming: "on",
  1324. mcp: {
  1325. enabled: true,
  1326. servers: { a: { type: "stdio", command: "node", args: ["a.js"] } },
  1327. },
  1328. },
  1329. {
  1330. eventStore: createTestSessionEventStore(),
  1331. mcpPort: createSnapshotMcpPort(snapshot, {
  1332. callTool: async () => {
  1333. mcpCallCount++;
  1334. return { content: [{ type: "text", text: "ok" }] };
  1335. },
  1336. }),
  1337. modelFactory: createTestModelFactory({
  1338. async *streamText() {
  1339. requestCount++;
  1340. if (requestCount === 1) {
  1341. yield {
  1342. type: "tool_call",
  1343. toolCall: { id: "lookup", name: "mcp__a__lookup", input: {} },
  1344. };
  1345. // MCP 必须等流结束、经执行前校验后才调用;提前执行会在这里被看到。
  1346. await expect(waitForCondition(() => mcpCallCount > 0)).rejects.toThrow("Timed out");
  1347. callsBeforeFinish = mcpCallCount;
  1348. yield { type: "finish", finishReason: "tool-calls", usage: {} };
  1349. return;
  1350. }
  1351. yield { type: "text_delta", text: "done" };
  1352. yield { type: "finish", finishReason: "stop", usage: {} };
  1353. },
  1354. } as never),
  1355. },
  1356. );
  1357. await runtime.executeTurn("lookup");
  1358. expect(callsBeforeFinish).toBe(0);
  1359. expect(mcpCallCount).toBe(1);
  1360. });
  1361. it("registers configured MCP tools before the first model request", async () => {
  1362. const sessionId = createSessionId("runtime-mcp-tools");
  1363. const eventStore = createTestSessionEventStore();
  1364. let toolNames: string[] = [];
  1365. const mcpPort = createMockMcpPort({
  1366. connectConfiguredServers: async () => ({
  1367. statuses: {
  1368. local: {
  1369. status: "connected",
  1370. transport: "stdio",
  1371. toolCount: 1,
  1372. updatedAt: "now",
  1373. },
  1374. },
  1375. tools: [
  1376. {
  1377. serverName: "local",
  1378. toolName: "ping",
  1379. inputSchema: {
  1380. type: "object",
  1381. properties: {},
  1382. },
  1383. annotations: {
  1384. readOnlyHint: true,
  1385. },
  1386. },
  1387. ],
  1388. }),
  1389. });
  1390. const runtime = createTestAgentRuntime(
  1391. sessionId,
  1392. {
  1393. mode: "build",
  1394. mcp: {
  1395. enabled: true,
  1396. servers: {
  1397. local: {
  1398. type: "stdio",
  1399. command: "node",
  1400. args: ["server.js"],
  1401. },
  1402. },
  1403. },
  1404. },
  1405. {
  1406. eventStore,
  1407. mcpPort,
  1408. modelFactory: createTestModelFactory({
  1409. async generateText(request: any) {
  1410. toolNames = request.tools.map((tool: { name: string }) => tool.name);
  1411. return {
  1412. finishReason: "stop",
  1413. providerMetadata: undefined,
  1414. text: "done",
  1415. usage: {
  1416. inputTokens: 1,
  1417. outputTokens: 1,
  1418. totalTokens: 2,
  1419. },
  1420. };
  1421. },
  1422. } as never),
  1423. },
  1424. );
  1425. await runtime.executeTurn("use mcp if needed");
  1426. expect(toolNames).toContain("mcp__local__ping");
  1427. });
  1428. // 修复原因:Plan 曾直接放行非 destructive MCP,比 build 更宽;现在单次询问且不提供始终允许。
  1429. it("asks once before non-read-only MCP tools run in plan mode", async () => {
  1430. const sessionId = createSessionId("runtime-mcp-plan-mode");
  1431. const eventStore = createTestSessionEventStore();
  1432. let modelCallCount = 0;
  1433. let mcpCallCount = 0;
  1434. let admissionRefreshes = 0;
  1435. const permissionRequests: PermissionBrokerRequest[] = [];
  1436. const permissionBroker: PermissionBrokerPort = {
  1437. async requestPermission(request) {
  1438. permissionRequests.push(request);
  1439. return { decision: "allow", reason: "Approved once" };
  1440. },
  1441. };
  1442. const mcpPort = createMockMcpPort({
  1443. refreshWorkspaceTrustAdmission: async () => {
  1444. admissionRefreshes++;
  1445. },
  1446. connectConfiguredServers: async () => ({
  1447. statuses: {
  1448. local: {
  1449. status: "connected",
  1450. transport: "stdio",
  1451. toolCount: 1,
  1452. updatedAt: "now",
  1453. },
  1454. },
  1455. tools: [
  1456. {
  1457. serverName: "local",
  1458. toolName: "lookup",
  1459. inputSchema: {
  1460. type: "object",
  1461. properties: {
  1462. query: { type: "string" },
  1463. },
  1464. },
  1465. },
  1466. ],
  1467. }),
  1468. callTool: async (request) => {
  1469. mcpCallCount++;
  1470. return {
  1471. content: [{ type: "text", text: `lookup:${request.arguments?.query}` }],
  1472. };
  1473. },
  1474. });
  1475. const runtime = createTestAgentRuntime(
  1476. sessionId,
  1477. {
  1478. mode: "plan",
  1479. mcp: {
  1480. enabled: true,
  1481. servers: {
  1482. local: {
  1483. type: "stdio",
  1484. command: "node",
  1485. args: ["server.js"],
  1486. },
  1487. },
  1488. },
  1489. },
  1490. {
  1491. eventStore,
  1492. mcpPort,
  1493. permissionBroker,
  1494. modelFactory: createTestModelFactory({
  1495. async generateText(request: any) {
  1496. modelCallCount++;
  1497. if (modelCallCount === 1) {
  1498. expect(request.tools.map((tool: { name: string }) => tool.name)).toContain(
  1499. "mcp__local__lookup",
  1500. );
  1501. return {
  1502. finishReason: "tool-calls",
  1503. providerMetadata: undefined,
  1504. text: "I will look this up.",
  1505. toolCalls: [
  1506. {
  1507. id: "mcp-lookup",
  1508. name: "mcp__local__lookup",
  1509. input: { query: "plan context" },
  1510. },
  1511. ],
  1512. usage: {
  1513. inputTokens: 1,
  1514. outputTokens: 1,
  1515. totalTokens: 2,
  1516. },
  1517. };
  1518. }
  1519. expect(
  1520. request.messages.some((message: any) => {
  1521. return (
  1522. message.role === "tool" && String(message.content).includes("lookup:plan context")
  1523. );
  1524. }),
  1525. ).toBe(true);
  1526. return {
  1527. finishReason: "stop",
  1528. providerMetadata: undefined,
  1529. text: "done",
  1530. usage: {
  1531. inputTokens: 1,
  1532. outputTokens: 1,
  1533. totalTokens: 2,
  1534. },
  1535. };
  1536. },
  1537. } as never),
  1538. },
  1539. );
  1540. const result = await runtime.executeTurn("use mcp while planning");
  1541. expect(result.response).toBe("done");
  1542. expect(mcpCallCount).toBe(1);
  1543. expect(permissionRequests).toHaveLength(1);
  1544. expect(permissionRequests[0]).toMatchObject({
  1545. optionsPolicy: "no-always-allow",
  1546. ruleId: "mode.plan.mcp",
  1547. toolName: "mcp__local__lookup",
  1548. });
  1549. expect(modelCallCount).toBe(2);
  1550. expect(admissionRefreshes).toBe(1);
  1551. await runtime.executeTurn("next user prompt");
  1552. expect(admissionRefreshes).toBe(2);
  1553. });
  1554. // EnterPlanMode 免确认;进入 Plan 后调用 MCP 仍须用户确认,模型不能借进入 Plan 绕过审批。
  1555. it("does not let EnterPlanMode unlock MCP tools without approval", async () => {
  1556. let modelCallCount = 0;
  1557. let mcpCallCount = 0;
  1558. const permissionRequests: PermissionBrokerRequest[] = [];
  1559. const runtime = createTestAgentRuntime(
  1560. createSessionId("runtime-mcp-enter-plan"),
  1561. {
  1562. mode: "build",
  1563. mcp: { enabled: true, servers: { local: { type: "stdio", command: "node" } } },
  1564. },
  1565. {
  1566. eventStore: createTestSessionEventStore(),
  1567. permissionBroker: {
  1568. async requestPermission(request) {
  1569. permissionRequests.push(request);
  1570. return { decision: "deny", reason: "denied in test" };
  1571. },
  1572. },
  1573. mcpPort: createMockMcpPort({
  1574. // 会话只从按 server 分组的快照读工具;没有状态的 server 不会出现在工具列表里。
  1575. connectConfiguredServers: async () => ({
  1576. statuses: { local: mcpStatus("connected") },
  1577. tools: [{ serverName: "local", toolName: "js", inputSchema: { type: "object" } }],
  1578. }),
  1579. callTool: async () => {
  1580. mcpCallCount++;
  1581. return { content: [{ type: "text", text: "executed" }] };
  1582. },
  1583. }),
  1584. modelFactory: createTestModelFactory({
  1585. generateText: async () => {
  1586. modelCallCount++;
  1587. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  1588. if (modelCallCount === 1)
  1589. return {
  1590. finishReason: "tool-calls",
  1591. text: "",
  1592. toolCalls: [{ id: "enter-plan", name: "EnterPlanMode", input: {} }],
  1593. usage,
  1594. };
  1595. if (modelCallCount === 2)
  1596. return {
  1597. finishReason: "tool-calls",
  1598. text: "",
  1599. toolCalls: [{ id: "mcp-js", name: "mcp__local__js", input: { code: "x" } }],
  1600. usage,
  1601. };
  1602. return { finishReason: "stop", text: "done", usage };
  1603. },
  1604. }),
  1605. },
  1606. );
  1607. await runtime.executeTurn("plan then run");
  1608. expect(permissionRequests).toHaveLength(1);
  1609. expect(permissionRequests[0]).toMatchObject({
  1610. ruleId: "mode.plan.mcp",
  1611. toolName: "mcp__local__js",
  1612. });
  1613. expect(mcpCallCount).toBe(0);
  1614. });
  1615. it.each([
  1616. ["user_steer", false],
  1617. ["user_steer", true],
  1618. ["coordinator_steer", false],
  1619. ["coordinator_steer", true],
  1620. ] as const)(
  1621. "refreshes admission only for user guide: %s, attachment: %s",
  1622. async (inputPresentation, withAttachment) => {
  1623. const toolStarted = deferred<void>();
  1624. const releaseTool = deferred<void>();
  1625. let refreshes = 0;
  1626. let modelSteps = 0;
  1627. const runtime = createTestAgentRuntime(
  1628. createSessionId(`mcp-admission-${inputPresentation}`),
  1629. {
  1630. // 用 yolo 让 MCP 工具免审批执行;本用例只验证 admission 刷新,不验证权限。
  1631. // 原先借 plan 放行 readOnlyHint MCP,plan 现在交给原模式判定,build 会请求审批。
  1632. mode: "yolo",
  1633. mcp: { enabled: true, servers: { local: { type: "stdio", command: "node" } } },
  1634. },
  1635. {
  1636. eventStore: createTestSessionEventStore(),
  1637. mcpPort: createMockMcpPort({
  1638. refreshWorkspaceTrustAdmission: async () => {
  1639. refreshes++;
  1640. },
  1641. connectConfiguredServers: async () => ({
  1642. // 会话从连接快照读取目录;快照行由状态产生,没有状态的工具不会进入目录。
  1643. statuses: {
  1644. local: { status: "connected", transport: "stdio", toolCount: 1, updatedAt: "now" },
  1645. },
  1646. tools: [
  1647. {
  1648. serverName: "local",
  1649. toolName: "ping",
  1650. inputSchema: { type: "object" },
  1651. annotations: { readOnlyHint: true },
  1652. },
  1653. ],
  1654. }),
  1655. callTool: async () => {
  1656. toolStarted.resolve();
  1657. await releaseTool.promise;
  1658. return { content: [{ type: "text", text: "pong" }] };
  1659. },
  1660. }),
  1661. modelFactory: createTestModelFactory({
  1662. generateText: async () => {
  1663. modelSteps++;
  1664. return {
  1665. finishReason: modelSteps === 1 ? "tool-calls" : "stop",
  1666. text: modelSteps === 1 ? "checking" : "done",
  1667. toolCalls:
  1668. modelSteps === 1
  1669. ? [{ id: "ping", name: "mcp__local__ping", input: {} }]
  1670. : undefined,
  1671. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1672. };
  1673. },
  1674. }),
  1675. },
  1676. );
  1677. const turn = runtime.executeTurn("start");
  1678. try {
  1679. await toolStarted.promise;
  1680. const result = await runtime.steerTurn({
  1681. input: "follow up",
  1682. delivery: "guide",
  1683. inputPresentation,
  1684. ...(withAttachment
  1685. ? { attachments: [{ type: "file" as const, content: "note", path: "note.txt" }] }
  1686. : {}),
  1687. });
  1688. expect(result.kind).toBe("queued");
  1689. } finally {
  1690. releaseTool.resolve();
  1691. }
  1692. await turn;
  1693. expect(modelSteps).toBe(2);
  1694. expect(refreshes).toBe(inputPresentation === "user_steer" ? 2 : 1);
  1695. },
  1696. );
  1697. it("refreshes admission for new user input, not model-only or coordinator continuations", async () => {
  1698. let refreshes = 0;
  1699. let failRefresh = false;
  1700. const runtime = createTestAgentRuntime(
  1701. createSessionId("mcp-admission-user-boundary"),
  1702. { mode: "build", mcp: { enabled: true, servers: {} } },
  1703. {
  1704. eventStore: createTestSessionEventStore(),
  1705. modelFactory: createTestModelFactory({
  1706. generateText: async () => ({
  1707. finishReason: "stop",
  1708. text: "done",
  1709. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1710. }),
  1711. }),
  1712. mcpPort: createMockMcpPort({
  1713. refreshWorkspaceTrustAdmission: async () => {
  1714. refreshes++;
  1715. if (failRefresh) throw new Error("admission read failed");
  1716. },
  1717. }),
  1718. },
  1719. );
  1720. await runtime.executeTurn("first user prompt");
  1721. expect(refreshes).toBe(1);
  1722. await runtime.executeTurn("continue goal", undefined, {
  1723. inputSource: "goal-continuation",
  1724. inputVisibility: "model-only",
  1725. });
  1726. await runtime.executeTurn("background result", undefined, {
  1727. inputSource: "background_task",
  1728. inputVisibility: "model-only",
  1729. });
  1730. await runtime.executeTurn("coordinator message", undefined, {
  1731. inputPresentation: "coordinator_input",
  1732. });
  1733. expect(refreshes).toBe(1);
  1734. await runtime.executeTurn("second user prompt");
  1735. expect(refreshes).toBe(2);
  1736. failRefresh = true;
  1737. await expect(runtime.executeTurn("keep chatting on read failure")).resolves.toBeDefined();
  1738. expect(refreshes).toBe(3);
  1739. });
  1740. it("denies destructive MCP tools in plan mode before calling the MCP server", async () => {
  1741. const sessionId = createSessionId("runtime-mcp-plan-destructive");
  1742. const eventStore = createTestSessionEventStore();
  1743. let modelCallCount = 0;
  1744. let mcpCallCount = 0;
  1745. let secondRequest: any;
  1746. const mcpPort = createMockMcpPort({
  1747. connectConfiguredServers: async () => ({
  1748. statuses: {
  1749. device: {
  1750. status: "connected",
  1751. transport: "stdio",
  1752. toolCount: 1,
  1753. updatedAt: "now",
  1754. },
  1755. },
  1756. tools: [
  1757. {
  1758. serverName: "device",
  1759. toolName: "reset",
  1760. inputSchema: {
  1761. type: "object",
  1762. properties: {},
  1763. },
  1764. annotations: {
  1765. destructiveHint: true,
  1766. },
  1767. },
  1768. ],
  1769. }),
  1770. callTool: async () => {
  1771. mcpCallCount++;
  1772. return { content: [{ type: "text", text: "should-not-run" }] };
  1773. },
  1774. });
  1775. const runtime = createTestAgentRuntime(
  1776. sessionId,
  1777. {
  1778. mode: "plan",
  1779. mcp: {
  1780. enabled: true,
  1781. servers: {
  1782. device: {
  1783. type: "stdio",
  1784. command: "node",
  1785. args: ["server.js"],
  1786. },
  1787. },
  1788. },
  1789. },
  1790. {
  1791. eventStore,
  1792. mcpPort,
  1793. modelFactory: createTestModelFactory({
  1794. async generateText(request: any) {
  1795. modelCallCount++;
  1796. if (modelCallCount === 1) {
  1797. return {
  1798. finishReason: "tool-calls",
  1799. providerMetadata: undefined,
  1800. text: "I will reset the device.",
  1801. toolCalls: [
  1802. {
  1803. id: "mcp-reset",
  1804. name: "mcp__device__reset",
  1805. input: {},
  1806. },
  1807. ],
  1808. usage: {
  1809. inputTokens: 1,
  1810. outputTokens: 1,
  1811. totalTokens: 2,
  1812. },
  1813. };
  1814. }
  1815. secondRequest = request;
  1816. return {
  1817. finishReason: "stop",
  1818. providerMetadata: undefined,
  1819. text: "done",
  1820. usage: {
  1821. inputTokens: 1,
  1822. outputTokens: 1,
  1823. totalTokens: 2,
  1824. },
  1825. };
  1826. },
  1827. } as never),
  1828. },
  1829. );
  1830. const result = await runtime.executeTurn("do not mutate while planning");
  1831. const toolMessage = secondRequest.messages.find((message: any) => message.role === "tool");
  1832. expect(result.response).toBe("done");
  1833. expect(mcpCallCount).toBe(0);
  1834. expect(toolMessage?.content).toContain(
  1835. "Plan mode only allows read-only, non-destructive tools",
  1836. );
  1837. });
  1838. });
  1839. function mcpStatus(status: McpServerStatus["status"]): McpServerStatus {
  1840. return { status, transport: "stdio", toolCount: 0, updatedAt: "now" };
  1841. }
  1842. function createSnapshotMcpPort(
  1843. snapshot: Record<string, McpServerToolSnapshot>,
  1844. overrides: Partial<McpPort> = {},
  1845. ): McpPort {
  1846. return createMockMcpPort({
  1847. getToolSnapshot: () => snapshot,
  1848. waitForServer: async () => ({ timedOut: false }),
  1849. ...overrides,
  1850. });
  1851. }
  1852. function stopModelResult(request: any) {
  1853. return {
  1854. finishReason: "stop",
  1855. model: request.model,
  1856. providerMetadata: undefined,
  1857. text: "done",
  1858. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1859. };
  1860. }
  1861. function toolCallResult(request: any, id: string, name: string) {
  1862. return {
  1863. ...stopModelResult(request),
  1864. finishReason: "tool-calls",
  1865. text: "calling",
  1866. toolCalls: [{ id, name, input: {} }],
  1867. };
  1868. }
  1869. function createStopModelAdapter(toolNames: string[][] = []): never {
  1870. return {
  1871. async generateText(request: any) {
  1872. toolNames.push(request.tools.map((tool: { name: string }) => tool.name));
  1873. return stopModelResult(request);
  1874. },
  1875. } as never;
  1876. }
  1877. function emptyMcpSnapshot(): McpConnectionSnapshot {
  1878. return {
  1879. statuses: {},
  1880. tools: [],
  1881. };
  1882. }
  1883. function deferred<T>(): {
  1884. promise: Promise<T>;
  1885. reject: (error: unknown) => void;
  1886. resolve: (value: T) => void;
  1887. } {
  1888. let reject!: (error: unknown) => void;
  1889. let resolve!: (value: T) => void;
  1890. const promise = new Promise<T>((promiseResolve, promiseReject) => {
  1891. resolve = promiseResolve;
  1892. reject = promiseReject;
  1893. });
  1894. return { promise, reject, resolve };
  1895. }
  1896. async function waitForEvent(
  1897. eventStore: SessionEventStorePort,
  1898. sessionId: SessionId,
  1899. type: string,
  1900. ): Promise<void> {
  1901. const deadline = Date.now() + 500;
  1902. while (Date.now() < deadline) {
  1903. const events = await eventStore.getEvents(sessionId);
  1904. if (events.some((event) => event.type === type)) return;
  1905. await new Promise((resolve) => setTimeout(resolve, 5));
  1906. }
  1907. throw new Error(`Timed out waiting for event: ${type}`);
  1908. }
  1909. async function waitForCondition(condition: () => boolean): Promise<void> {
  1910. const deadline = Date.now() + 500;
  1911. while (Date.now() < deadline) {
  1912. if (condition()) return;
  1913. await new Promise((resolve) => setTimeout(resolve, 5));
  1914. }
  1915. throw new Error("Timed out waiting for condition");
  1916. }