mcp-tool-bridge.test.ts 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640
  1. import { createMockMcpPort } from "./mcp-runtime-fixture.js";
  2. import { createHash } from "node:crypto";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import {
  5. createRootTraceContext,
  6. createSessionId,
  7. createToolCallId,
  8. createTurnId,
  9. ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY,
  10. ZCODE_MCP_ERROR_PRESENTATION_MESSAGE_ONLY,
  11. ZCODE_MCP_ERROR_PRESENTATION_META_KEY,
  12. type ImageProcessorPort,
  13. type McpPort,
  14. type ToolArtifactStorePort,
  15. } from "@zcode/contracts";
  16. import {
  17. resetCapturedZCodeCuaBrokerCredentialsForTest,
  18. ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME as ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  19. sanitizeZCodeRuntimeEnv,
  20. ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  21. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  22. ZCODE_PLUGIN_ID_ENV_KEY,
  23. } from "@zcode/shared";
  24. import {
  25. MCP_IMAGE_INLINE_BASE64_BYTES,
  26. MCP_IMAGE_INLINE_RAW_BYTES,
  27. registerMcpTools,
  28. } from "../src/mcp/index.js";
  29. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  30. import { createToolExecutor } from "../src/tool/executor.js";
  31. import { createToolRegistry } from "../src/tool/registry.js";
  32. import type { ToolEntry, ToolExecutionContext } from "../src/tool/types.js";
  33. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  34. import { OFFICIAL_CUA_FRAME_INTEGRITY_META_KEY } from "@zcode/zcode-cua/frame-contract";
  35. import { createTestSessionEventStore } from "./test-event-store.js";
  36. const TEST_PLUGIN_AUTHORITY = "test-plugin-authority";
  37. function officialCuaIntegrityMeta(
  38. frameId: string,
  39. imageData: string,
  40. options: { height?: number; mediaType?: string; width?: number } = {},
  41. ) {
  42. return {
  43. [OFFICIAL_CUA_FRAME_INTEGRITY_META_KEY]: {
  44. version: 1,
  45. frame_id: frameId,
  46. width: options.width ?? 1,
  47. height: options.height ?? 1,
  48. media_type: options.mediaType ?? "image/png",
  49. sha256: createHash("sha256").update(Buffer.from(imageData, "base64")).digest("hex"),
  50. },
  51. };
  52. }
  53. function exactRasterInspector(width: number, height: number): ImageProcessorPort {
  54. return {
  55. resizeToFit: async (request) => ({
  56. data: request.data,
  57. mediaType: request.mediaType,
  58. originalHeight: height,
  59. originalWidth: width,
  60. height,
  61. resized: false,
  62. width,
  63. }),
  64. prepareForModel: async () => {
  65. throw new Error("official CUA frame must not be transcoded");
  66. },
  67. };
  68. }
  69. function cuaActionReceipt(overrides: Record<string, unknown> = {}): string {
  70. return JSON.stringify({
  71. action_receipt: {
  72. schema_version: "zcode-cua-action-receipt-v1",
  73. action_sent: true,
  74. dispatch_status: "accepted",
  75. retry_action: false,
  76. ...overrides,
  77. },
  78. });
  79. }
  80. // computeOfficialCuaServerNames 只信任本进程私有捕获的 authority;测试必须走与生产同一条
  81. // capture 路径(sanitize 时捕获完整凭据组)来播种,绝不能直接改写内部状态。
  82. function seedCapturedBrokerCredentials(): void {
  83. sanitizeZCodeRuntimeEnv({
  84. ZCODE_CUA_PERMISSION_BROKER_SOCKET: "/tmp/zcode-cua-test.sock",
  85. ZCODE_CUA_PERMISSION_BROKER_TOKEN: "test-broker-token",
  86. [ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]: TEST_PLUGIN_AUTHORITY,
  87. });
  88. }
  89. describe("MCP tool bridge", () => {
  90. afterEach(() => {
  91. resetCapturedZCodeCuaBrokerCredentialsForTest();
  92. });
  93. it("marks only authority-verified official CUA entries with the project capability group", () => {
  94. const registry = createToolRegistry();
  95. registerMcpTools(
  96. registry,
  97. createMockMcpPort(),
  98. [
  99. {
  100. inputSchema: { type: "object" },
  101. serverName: "trusted-computer-use",
  102. toolName: "left_click",
  103. },
  104. {
  105. inputSchema: { type: "object" },
  106. serverName: "lookalike-computer-use",
  107. toolName: "left_click",
  108. },
  109. ],
  110. {
  111. officialCuaServerNames: new Set(["trusted-computer-use"]),
  112. },
  113. );
  114. const trusted = registry.get("mcp__trusted-computer-use__left_click") as
  115. | (ToolEntry & { permissionCapabilityGroup?: string })
  116. | undefined;
  117. const lookalike = registry.get("mcp__lookalike-computer-use__left_click") as
  118. | (ToolEntry & { permissionCapabilityGroup?: string })
  119. | undefined;
  120. expect(trusted?.permissionCapabilityGroup).toBe("official_cua");
  121. expect(trusted?.modelContentProtection).toBe("official_cua_frame_v1");
  122. expect(trusted).not.toHaveProperty("preserveStructuredModelContent");
  123. expect(lookalike?.permissionCapabilityGroup).toBeUndefined();
  124. expect(lookalike?.modelContentProtection).toBeUndefined();
  125. });
  126. it("registers the provider alias during runtime startup for the official CUA plugin", async () => {
  127. seedCapturedBrokerCredentials();
  128. const sessionId = createSessionId("official-cua-runtime-alias");
  129. const traceContext = createRootTraceContext({ sessionId });
  130. const callTool = vi.fn(async () => ({
  131. content: [{ type: "text" as const, text: "ok" }],
  132. }));
  133. const mcpPort = createMockMcpPort({
  134. callTool,
  135. connectConfiguredServers: async () => ({
  136. statuses: {
  137. [ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]: {
  138. status: "connected",
  139. transport: "stdio",
  140. toolCount: 1,
  141. updatedAt: "now",
  142. },
  143. },
  144. tools: [
  145. {
  146. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  147. toolName: "open_application",
  148. // adapter 会先按 namespaced serverName 生成这个内部描述符名;core 再把可信官方
  149. // CUA 投影成模型约定的 computer-use 主名,调用路由仍保留原 serverName。
  150. name: "mcp__plugin_zcode-cua_computer-use__open_application",
  151. },
  152. ],
  153. }),
  154. });
  155. const runtime = createTestAgentRuntime(
  156. sessionId,
  157. {
  158. mcp: {
  159. servers: {
  160. [ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]: {
  161. type: "stdio",
  162. command: "zcode-cua",
  163. env: {
  164. [ZCODE_PLUGIN_ID_ENV_KEY]: ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  165. [ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]: TEST_PLUGIN_AUTHORITY,
  166. },
  167. },
  168. },
  169. trustedOfficialCuaServerNames: [ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME],
  170. },
  171. },
  172. {
  173. eventStore: createTestSessionEventStore(),
  174. mcpPort,
  175. traceContext,
  176. },
  177. );
  178. await (
  179. runtime as unknown as {
  180. initializeMcp(trace: typeof traceContext): Promise<void>;
  181. }
  182. ).initializeMcp(traceContext);
  183. const canonical = runtime.getToolRegistry().get("mcp__computer-use__open_application");
  184. const alias = runtime.getToolRegistry().get("mcp__computer_use__open_application");
  185. expect(canonical).toBeDefined();
  186. expect(alias).toBe(canonical);
  187. expect(
  188. runtime.getToolRegistry().get("mcp__plugin_zcode-cua_computer-use__open_application"),
  189. ).toBeUndefined();
  190. await alias?.handler({ app: { name: "notepad.exe" } }, createToolContext());
  191. expect(callTool).toHaveBeenCalledWith(
  192. expect.objectContaining({
  193. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  194. toolName: "open_application",
  195. }),
  196. expect.anything(),
  197. );
  198. });
  199. it("does not trust an official-looking CUA server without the resolver plugin identity", async () => {
  200. seedCapturedBrokerCredentials();
  201. const sessionId = createSessionId("untrusted-cua-runtime-alias");
  202. const traceContext = createRootTraceContext({ sessionId });
  203. const runtime = createTestAgentRuntime(
  204. sessionId,
  205. {
  206. mcp: {
  207. servers: {
  208. [ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]: {
  209. type: "stdio",
  210. command: "zcode-cua",
  211. },
  212. },
  213. trustedOfficialCuaServerNames: [ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME],
  214. },
  215. },
  216. {
  217. eventStore: createTestSessionEventStore(),
  218. mcpPort: createMockMcpPort({
  219. connectConfiguredServers: async () => ({
  220. statuses: {
  221. [ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]: {
  222. status: "connected",
  223. transport: "stdio",
  224. toolCount: 1,
  225. updatedAt: "now",
  226. },
  227. },
  228. tools: [
  229. {
  230. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  231. toolName: "open_application",
  232. name: "mcp__plugin_zcode-cua_computer-use__open_application",
  233. },
  234. ],
  235. }),
  236. }),
  237. traceContext,
  238. },
  239. );
  240. await (
  241. runtime as unknown as {
  242. initializeMcp(trace: typeof traceContext): Promise<void>;
  243. }
  244. ).initializeMcp(traceContext);
  245. expect(runtime.getToolRegistry().get("mcp__computer_use__open_application")).toBeUndefined();
  246. expect(runtime.getToolRegistry().get("mcp__computer-use__open_application")).toBeUndefined();
  247. expect(
  248. runtime.getToolRegistry().get("mcp__plugin_zcode-cua_computer-use__open_application"),
  249. ).toBeDefined();
  250. });
  251. it("classifies the reserved node_repl js tool as high-risk system execution", () => {
  252. const registry = createToolRegistry();
  253. registerMcpTools(registry, createMockMcpPort(), [
  254. {
  255. description: "Run JavaScript",
  256. inputSchema: { type: "object" },
  257. serverName: "node_repl",
  258. toolName: "js",
  259. },
  260. ]);
  261. expect(registry.get("mcp__node_repl__js")?.metadata).toMatchObject({
  262. needsApproval: true,
  263. riskLevel: "high",
  264. sideEffectScope: "system",
  265. });
  266. expect(registry.get("mcp__node_repl__js")?.resultBudget).toMatchObject({
  267. maxModelBytes: 64 * 1024,
  268. strategy: "artifact",
  269. preview: { direction: "tail" },
  270. });
  271. });
  272. it("accepts the underscore server spelling only for an authority-verified official CUA tool", async () => {
  273. const registry = createToolRegistry();
  274. const calls: Array<{ serverName: string; toolName: string }> = [];
  275. const mcpPort = createMockMcpPort({
  276. callTool: async (request) => {
  277. calls.push({
  278. serverName: request.serverName,
  279. toolName: request.toolName,
  280. });
  281. return { content: [{ type: "text", text: "ok" }] };
  282. },
  283. });
  284. registerMcpTools(
  285. registry,
  286. mcpPort,
  287. [
  288. {
  289. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  290. toolName: "open_application",
  291. name: "mcp__computer-use__open_application",
  292. },
  293. ],
  294. {
  295. officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]),
  296. },
  297. );
  298. const canonical = registry.get("mcp__computer-use__open_application");
  299. const alias = registry.get("mcp__computer_use__open_application");
  300. expect(alias).toBe(canonical);
  301. expect(registry.list()).toEqual(["mcp__computer-use__open_application"]);
  302. expect(registry.toContracts().map((contract) => contract.name)).toEqual([
  303. "mcp__computer-use__open_application",
  304. ]);
  305. await alias?.handler({ app: { name: "notepad.exe" } }, createToolContext());
  306. expect(calls).toEqual([
  307. {
  308. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  309. toolName: "open_application",
  310. },
  311. ]);
  312. });
  313. it("does not add the underscore server spelling for an unverified MCP server", () => {
  314. const registry = createToolRegistry();
  315. registerMcpTools(registry, createMockMcpPort(), [
  316. {
  317. serverName: "computer-use",
  318. toolName: "open_application",
  319. name: "mcp__computer-use__open_application",
  320. },
  321. ]);
  322. expect(registry.get("mcp__computer-use__open_application")).toBeDefined();
  323. expect(registry.get("mcp__computer_use__open_application")).toBeUndefined();
  324. });
  325. it("keeps an existing namespaced deny rule effective after official CUA name projection", () => {
  326. const registry = createToolRegistry();
  327. const namespacedName = "mcp__plugin_zcode-cua_computer-use__open_application";
  328. const registered = registerMcpTools(
  329. registry,
  330. createMockMcpPort(),
  331. [
  332. {
  333. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  334. toolName: "open_application",
  335. name: namespacedName,
  336. },
  337. ],
  338. {
  339. disallowedTools: [namespacedName],
  340. officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]),
  341. },
  342. );
  343. expect(registered).toEqual([]);
  344. expect(registry.get("mcp__computer-use__open_application")).toBeUndefined();
  345. expect(registry.get("mcp__computer_use__open_application")).toBeUndefined();
  346. });
  347. it("keeps an existing namespaced allow rule effective after official CUA name projection", () => {
  348. const registry = createToolRegistry();
  349. const namespacedName = "mcp__plugin_zcode-cua_computer-use__open_application";
  350. const registered = registerMcpTools(
  351. registry,
  352. createMockMcpPort(),
  353. [
  354. {
  355. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  356. toolName: "open_application",
  357. name: namespacedName,
  358. },
  359. ],
  360. {
  361. allowedTools: [namespacedName],
  362. officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]),
  363. },
  364. );
  365. expect(registered).toEqual(["mcp__computer-use__open_application"]);
  366. expect(registry.get("mcp__computer_use__open_application")).toBe(
  367. registry.get("mcp__computer-use__open_application"),
  368. );
  369. });
  370. it("registers MCP descriptors as model-facing tools and calls through McpPort", async () => {
  371. const registry = createToolRegistry();
  372. const calls: Array<{
  373. serverName: string;
  374. toolName: string;
  375. arguments?: Record<string, unknown>;
  376. timeoutMs?: number;
  377. }> = [];
  378. const mcpPort: McpPort = {
  379. connectConfiguredServers: async () => ({ statuses: {}, tools: [] }),
  380. connectServer: async () => ({
  381. status: "connected",
  382. transport: "stdio",
  383. toolCount: 1,
  384. updatedAt: "now",
  385. }),
  386. disconnectServer: async () => undefined,
  387. status: async () => ({}),
  388. listTools: async () => [],
  389. callTool: async (request, options) => {
  390. calls.push({
  391. serverName: request.serverName,
  392. toolName: request.toolName,
  393. arguments: request.arguments,
  394. timeoutMs: options?.timeoutMs,
  395. });
  396. return {
  397. content: [{ type: "text", text: `hello ${request.arguments?.name}` }],
  398. };
  399. },
  400. close: async () => {},
  401. };
  402. const registered = registerMcpTools(registry, mcpPort, [
  403. {
  404. serverName: "local server",
  405. toolName: "say-hi",
  406. description: "Say hi",
  407. inputSchema: {
  408. type: "object",
  409. properties: {
  410. name: { type: "string" },
  411. },
  412. },
  413. timeoutMs: 900_000,
  414. annotations: {
  415. readOnlyHint: true,
  416. },
  417. },
  418. ]);
  419. expect(registered).toEqual(["mcp__local_server__say-hi"]);
  420. const entry = registry.get("mcp__local_server__say-hi");
  421. expect(entry?.metadata).toMatchObject({
  422. description: "Say hi",
  423. readOnly: true,
  424. sideEffectScope: "network",
  425. needsApproval: true,
  426. timeoutMs: 900_000,
  427. });
  428. expect(entry?.timeout.defaultMs).toBe(900_000);
  429. // description 必须透传到 model-facing contract,否则 MCP 工具在模型侧没有可用描述
  430. const contract = registry.toContracts().find((c) => c.name === "mcp__local_server__say-hi");
  431. expect(contract?.description).toBe("Say hi");
  432. const output = await entry?.handler({ name: "Ada" }, createToolContext());
  433. expect(calls).toEqual([
  434. {
  435. serverName: "local server",
  436. toolName: "say-hi",
  437. arguments: { name: "Ada" },
  438. timeoutMs: 900_000,
  439. },
  440. ]);
  441. expect(output).toEqual({
  442. content: [{ type: "text", text: "hello Ada" }],
  443. });
  444. expect(entry?.formatModelContent?.(output)).toBe("hello Ada");
  445. });
  446. it("marks MCP calls from a subagent runtime", async () => {
  447. const registry = createToolRegistry();
  448. const callTool = vi.fn(async () => ({ content: [] }));
  449. registerMcpTools(registry, createMockMcpPort({ callTool }), [
  450. {
  451. serverName: "node_repl",
  452. toolName: "js",
  453. inputSchema: { type: "object" },
  454. },
  455. ]);
  456. await registry
  457. .get("mcp__node_repl__js")
  458. ?.handler({}, createToolContext({ runtimeScope: "subagent" }));
  459. expect(callTool).toHaveBeenCalledWith(
  460. expect.objectContaining({ runtimeScope: "subagent" }),
  461. expect.anything(),
  462. );
  463. });
  464. it.each([
  465. ["matches one oneOf branch", { mode: "read" }, true],
  466. ["matches no oneOf branch", { mode: "delete" }, false],
  467. ["matches two oneOf branches", { mode: "write" }, false],
  468. ])("calls the MCP server only when the input %s next to anyOf", async (_case, input, valid) => {
  469. // 同一节点的 anyOf 与 oneOf 都要满足(docs/model-tool-call-validation.md)。工具在 allowedTools 里,
  470. // 合法输入能走到 MCP 调用,所以不合法输入没有调用只能是首次校验拒绝的,不是权限拒绝的。
  471. const registry = createToolRegistry();
  472. const callTool = vi.fn(async () => ({ content: [] }));
  473. registerMcpTools(registry, createMockMcpPort({ callTool }), [
  474. {
  475. serverName: "files",
  476. toolName: "open",
  477. inputSchema: {
  478. type: "object",
  479. properties: { mode: { type: "string" } },
  480. anyOf: [{ required: ["mode"] }],
  481. oneOf: [
  482. { properties: { mode: { const: "read" } } },
  483. { properties: { mode: { const: "write" } } },
  484. { properties: { mode: { enum: ["write", "sync"] } } },
  485. ],
  486. },
  487. },
  488. ]);
  489. const sessionId = createSessionId("mcp-union-validation");
  490. const turnId = createTurnId("mcp-union-turn");
  491. const traceContext = createRootTraceContext({ sessionId, turnId });
  492. const executor = createToolExecutor({
  493. emitEvent: async () => {},
  494. permissionService: new PermissionService({
  495. ...defaultPermissionConfig,
  496. allowedTools: new Set(["mcp__files__open"]),
  497. }),
  498. registry,
  499. sessionId,
  500. turnId,
  501. traceContext,
  502. });
  503. const result = await executor.execute(
  504. { id: createToolCallId("mcp-union-call"), input, name: "mcp__files__open" },
  505. { traceContext },
  506. );
  507. expect(callTool).toHaveBeenCalledTimes(valid ? 1 : 0);
  508. expect(result.success).toBe(valid);
  509. if (!valid) {
  510. expect(result.modelContent).toContain("<tool_use_error>InputValidationError:");
  511. expect(result.modelContent).toContain('"code": "invalid_union"');
  512. }
  513. });
  514. it("uses the session workspace key instead of the working directory (managed worktree)", async () => {
  515. const registry = createToolRegistry();
  516. const callTool = vi.fn(async () => ({ content: [] }));
  517. registerMcpTools(registry, createMockMcpPort({ callTool }), [
  518. { serverName: "node_repl", toolName: "js", inputSchema: { type: "object" } },
  519. ]);
  520. // 受管 worktree 会话:工作目录是 worktree,会话 key 是项目(docs/git/worktree.md §9.3)。
  521. await registry.get("mcp__node_repl__js")?.handler(
  522. {},
  523. createToolContext({
  524. workingDirectory: "/data/.zcode/worktrees/3f2a/repo",
  525. workspaceKey: "/projects/repo",
  526. }),
  527. );
  528. await registry
  529. .get("mcp__node_repl__js")
  530. ?.handler({}, createToolContext({ workingDirectory: "/projects/plain" }));
  531. expect(callTool).toHaveBeenNthCalledWith(
  532. 1,
  533. expect.objectContaining({
  534. workspaceKey: "/projects/repo",
  535. workspacePath: "/data/.zcode/worktrees/3f2a/repo",
  536. }),
  537. expect.anything(),
  538. );
  539. expect(callTool).toHaveBeenNthCalledWith(
  540. 2,
  541. expect.objectContaining({ workspaceKey: "/projects/plain" }),
  542. expect.anything(),
  543. );
  544. });
  545. it("removes disallowed MCP tools from the registry", () => {
  546. const registry = createToolRegistry();
  547. const mcpPort = createMockMcpPort();
  548. const registered = registerMcpTools(
  549. registry,
  550. mcpPort,
  551. [
  552. {
  553. serverName: "local server",
  554. toolName: "say-hi",
  555. description: "Say hi",
  556. inputSchema: { type: "object" },
  557. },
  558. {
  559. serverName: "local server",
  560. toolName: "say-bye",
  561. description: "Say bye",
  562. inputSchema: { type: "object" },
  563. },
  564. ],
  565. {
  566. disallowedTools: ["mcp__local_server__say-hi(*)"],
  567. },
  568. );
  569. expect(registered).toEqual(["mcp__local_server__say-bye"]);
  570. expect(registry.has("mcp__local_server__say-hi")).toBe(false);
  571. expect(registry.has("mcp__local_server__say-bye")).toBe(true);
  572. });
  573. it("does not register explicitly disallowed MCP tools", () => {
  574. const registry = createToolRegistry();
  575. const mcpPort = createMockMcpPort();
  576. const registered = registerMcpTools(
  577. registry,
  578. mcpPort,
  579. [
  580. {
  581. serverName: "zcode-cua",
  582. toolName: "get_app_state",
  583. inputSchema: { type: "object", properties: {} },
  584. },
  585. {
  586. serverName: "zcode-cua",
  587. toolName: "left_click",
  588. inputSchema: { type: "object", properties: {} },
  589. },
  590. ],
  591. { disallowedTools: ["mcp__zcode-cua__left_click"] },
  592. );
  593. expect(registered).toEqual(["mcp__zcode-cua__get_app_state"]);
  594. expect(registry.has("mcp__zcode-cua__get_app_state")).toBe(true);
  595. expect(registry.has("mcp__zcode-cua__left_click")).toBe(false);
  596. });
  597. it("requires a user title for CUA app observation and strips it before MCP dispatch", async () => {
  598. const registry = createToolRegistry();
  599. const callTool = vi.fn(async () => ({ content: [] }));
  600. registerMcpTools(registry, createMockMcpPort({ callTool }), [
  601. {
  602. serverName: "plugin:computer-use:computer-use",
  603. toolName: "get_app_state",
  604. inputSchema: {
  605. type: "object",
  606. required: ["app_ref"],
  607. properties: {
  608. app_ref: { type: "object" },
  609. detail: { type: "string" },
  610. },
  611. additionalProperties: false,
  612. },
  613. },
  614. ]);
  615. const entry = registry.get("mcp__plugin_computer-use_computer-use__get_app_state");
  616. expect(entry?.inputSchema).toMatchObject({
  617. required: ["app_ref", "title"],
  618. properties: {
  619. title: {
  620. type: "string",
  621. minLength: 1,
  622. maxLength: 120,
  623. },
  624. },
  625. additionalProperties: false,
  626. });
  627. await entry?.handler(
  628. {
  629. app_ref: { pid: 42 },
  630. detail: "compact",
  631. title: "检查设置窗口中的隐私权限",
  632. },
  633. createToolContext(),
  634. );
  635. expect(callTool).toHaveBeenCalledWith(
  636. expect.objectContaining({
  637. arguments: {
  638. app_ref: { pid: 42 },
  639. detail: "compact",
  640. },
  641. }),
  642. expect.anything(),
  643. );
  644. });
  645. it("preserves the official CUA element-vs-image target boundary for the model", () => {
  646. const registry = createToolRegistry();
  647. const target = {
  648. description:
  649. "Use an element target only for an accessibility-tree element. When the action is derived from a delivered image, use only its frame-bound coordinate target.",
  650. anyOf: [
  651. {
  652. type: "object",
  653. required: ["type", "state_id", "index"],
  654. properties: {
  655. type: { const: "element" },
  656. state_id: { type: "string" },
  657. index: { type: "integer" },
  658. },
  659. additionalProperties: false,
  660. },
  661. {
  662. type: "object",
  663. required: ["type", "frame_id", "x", "y"],
  664. properties: {
  665. type: { const: "coordinate" },
  666. frame_id: { type: "string", minLength: 1 },
  667. x: { type: "integer", minimum: 0 },
  668. y: { type: "integer", minimum: 0 },
  669. },
  670. additionalProperties: false,
  671. },
  672. ],
  673. };
  674. registerMcpTools(registry, createMockMcpPort(), [
  675. {
  676. serverName: "plugin:computer-use:computer-use",
  677. toolName: "left_click",
  678. inputSchema: {
  679. type: "object",
  680. required: ["target"],
  681. properties: { target },
  682. additionalProperties: false,
  683. },
  684. },
  685. ]);
  686. const modelTarget = registry.get("mcp__plugin_computer-use_computer-use__left_click")
  687. ?.inputSchema.properties?.target as typeof target;
  688. expect(modelTarget).toEqual(target);
  689. });
  690. it("does not add a title contract to unrelated get_app_state MCP tools", () => {
  691. const registry = createToolRegistry();
  692. registerMcpTools(registry, createMockMcpPort(), [
  693. {
  694. serverName: "device-inspector",
  695. toolName: "get_app_state",
  696. inputSchema: {
  697. type: "object",
  698. properties: { app_id: { type: "string" } },
  699. },
  700. },
  701. ]);
  702. const schema = registry.get("mcp__device-inspector__get_app_state")?.inputSchema;
  703. expect(schema).not.toHaveProperty("properties.title");
  704. expect(schema).not.toHaveProperty("required");
  705. });
  706. it.each(["computer-use", "zcode-cua"])(
  707. "recognizes the %s CUA server identity for the title contract",
  708. (serverName) => {
  709. const registry = createToolRegistry();
  710. registerMcpTools(registry, createMockMcpPort(), [
  711. {
  712. serverName,
  713. toolName: "get_app_state",
  714. inputSchema: { type: "object", properties: {} },
  715. },
  716. ]);
  717. expect(registry.get(`mcp__${serverName}__get_app_state`)?.inputSchema).toMatchObject({
  718. required: ["title"],
  719. properties: { title: { type: "string" } },
  720. });
  721. },
  722. );
  723. it("maps destructive MCP annotations into tool metadata", () => {
  724. const registry = createToolRegistry();
  725. const mcpPort = createMockMcpPort();
  726. registerMcpTools(registry, mcpPort, [
  727. {
  728. serverName: "device",
  729. toolName: "reset",
  730. description: "Reset a device",
  731. inputSchema: { type: "object" },
  732. annotations: {
  733. destructiveHint: true,
  734. },
  735. },
  736. ]);
  737. const entry = registry.get("mcp__device__reset");
  738. expect(entry?.metadata).toMatchObject({
  739. destructive: true,
  740. readOnly: false,
  741. riskLevel: "high",
  742. sideEffectScope: "network",
  743. });
  744. expect(entry?.permission).toMatchObject({
  745. permission: "mcp",
  746. riskLevel: "high",
  747. sideEffectScope: "network",
  748. });
  749. });
  750. it("honors the structured message-only MCP error presentation", () => {
  751. const registry = createToolRegistry();
  752. registerMcpTools(registry, createMockMcpPort(), [
  753. {
  754. serverName: "device",
  755. toolName: "validate",
  756. inputSchema: { type: "object" },
  757. },
  758. ]);
  759. const entry = registry.get("mcp__device__validate");
  760. const modelContent = entry?.formatModelContent?.({
  761. content: [
  762. {
  763. type: "text",
  764. text: "browser tab 'iab-tab:test' returned an invalid viewport",
  765. },
  766. ],
  767. isError: true,
  768. _meta: {
  769. [ZCODE_MCP_ERROR_PRESENTATION_META_KEY]: ZCODE_MCP_ERROR_PRESENTATION_MESSAGE_ONLY,
  770. },
  771. });
  772. expect(modelContent).toBe("browser tab 'iab-tab:test' returned an invalid viewport");
  773. });
  774. it("projects non-object MCP 2026-07-28 structured content", () => {
  775. const registry = createToolRegistry();
  776. registerMcpTools(registry, createMockMcpPort(), [
  777. {
  778. serverName: "modern",
  779. toolName: "structured",
  780. inputSchema: { type: "object" },
  781. },
  782. ]);
  783. const entry = registry.get("mcp__modern__structured");
  784. expect(entry?.outputSchema.properties?.structuredContent).toEqual({});
  785. expect(
  786. entry?.formatModelContent?.({
  787. content: [],
  788. structuredContent: ["alpha", { beta: true }],
  789. }),
  790. ).toBe('Structured content:\n[\n "alpha",\n {\n "beta": true\n }\n]');
  791. });
  792. it("preserves multiline MCP error details when they are not stack frames", () => {
  793. const registry = createToolRegistry();
  794. registerMcpTools(registry, createMockMcpPort(), [
  795. {
  796. serverName: "device",
  797. toolName: "validate",
  798. inputSchema: { type: "object" },
  799. },
  800. ]);
  801. const entry = registry.get("mcp__device__validate");
  802. const modelContent = entry?.formatModelContent?.({
  803. content: [
  804. {
  805. type: "text",
  806. text: "Invalid input\n- width is required\n- height is required",
  807. },
  808. ],
  809. isError: true,
  810. _meta: {
  811. [ZCODE_MCP_ERROR_PRESENTATION_META_KEY]: ZCODE_MCP_ERROR_PRESENTATION_MESSAGE_ONLY,
  812. },
  813. });
  814. expect(modelContent).toBe("Invalid input\n- width is required\n- height is required");
  815. });
  816. it("keeps the existing error projection without message-only metadata", () => {
  817. const registry = createToolRegistry();
  818. registerMcpTools(registry, createMockMcpPort(), [
  819. {
  820. serverName: "device",
  821. toolName: "validate",
  822. inputSchema: { type: "object" },
  823. },
  824. ]);
  825. const entry = registry.get("mcp__device__validate");
  826. const errorText = [
  827. "ValidationError: Invalid input",
  828. " at validate (file:///plugins/device.mjs:12:3)",
  829. ].join("\n");
  830. const modelContent = entry?.formatModelContent?.({
  831. content: [{ type: "text", text: errorText }],
  832. isError: true,
  833. });
  834. expect(modelContent).toBe(`MCP tool returned an error:\n${errorText}`);
  835. });
  836. it("projects MCP image content as model-visible image blocks", () => {
  837. const registry = createToolRegistry();
  838. const mcpPort = createMockMcpPort();
  839. registerMcpTools(registry, mcpPort, [
  840. {
  841. serverName: "ios_simulator",
  842. toolName: "ios_screenshot",
  843. inputSchema: {
  844. type: "object",
  845. properties: {},
  846. },
  847. },
  848. ]);
  849. const entry = registry.get("mcp__ios_simulator__ios_screenshot");
  850. const modelContent = entry?.formatModelContent?.({
  851. content: [
  852. { type: "text", text: '{"path":"screenshots/latest.png"}' },
  853. { type: "image", data: "aGVsbG8=", mimeType: "image/png" },
  854. ],
  855. });
  856. expect(modelContent).toEqual([
  857. { type: "text", text: '{"path":"screenshots/latest.png"}' },
  858. {
  859. type: "image",
  860. mediaType: "image/png",
  861. dataUrl: "data:image/png;base64,aGVsbG8=",
  862. source: {
  863. id: "mcp-image",
  864. kind: "inline",
  865. mimeType: "image/png",
  866. placeholder: "MCP image",
  867. sizeBytes: 5,
  868. },
  869. },
  870. ]);
  871. });
  872. it("preserves an authority-verified CUA frame image-first pair byte-for-byte", async () => {
  873. const registry = createToolRegistry();
  874. const imageData =
  875. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";
  876. const result = {
  877. content: [
  878. { type: "image" as const, data: imageData, mimeType: "image/png" },
  879. {
  880. type: "text" as const,
  881. text: JSON.stringify({
  882. image_ref: {
  883. actionable: true,
  884. frame_id: "frame_exact_001",
  885. height: 1,
  886. width: 1,
  887. },
  888. }),
  889. },
  890. ],
  891. _meta: officialCuaIntegrityMeta("frame_exact_001", imageData),
  892. };
  893. const callTool = vi.fn(async () => result);
  894. registerMcpTools(
  895. registry,
  896. createMockMcpPort({ callTool }),
  897. [
  898. {
  899. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  900. toolName: "get_app_state",
  901. inputSchema: { type: "object", properties: {} },
  902. },
  903. ],
  904. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  905. );
  906. const entry = registry.get("mcp__computer-use__get_app_state");
  907. const output = await entry?.handler(
  908. { title: "读取精确坐标图" },
  909. createToolContext({
  910. imageProcessorPort: exactRasterInspector(1, 1),
  911. }),
  912. );
  913. expect(output).toBe(result);
  914. expect(output?.content[0]).toEqual({
  915. type: "image",
  916. data: imageData,
  917. mimeType: "image/png",
  918. });
  919. expect(entry?.resultBudget).toMatchObject({
  920. maxInlineBytes: 256 * 1024,
  921. maxModelBytes: 256 * 1024,
  922. });
  923. expect(entry?.modelContentProtection).toBe("official_cua_frame_v1");
  924. expect(entry?.formatModelContent?.(output)).toEqual([
  925. expect.objectContaining({
  926. type: "image",
  927. dataUrl: `data:image/png;base64,${imageData}`,
  928. }),
  929. {
  930. type: "text",
  931. text: result.content[1].text,
  932. },
  933. ]);
  934. });
  935. it("projects an official CUA action receipt through the generic MCP formatter", async () => {
  936. const result = {
  937. content: [
  938. { type: "text" as const, text: "Dispatched AXPress. (receipt below)" },
  939. { type: "text" as const, text: cuaActionReceipt() },
  940. ],
  941. structuredContent: undefined,
  942. isError: undefined,
  943. _meta: undefined,
  944. };
  945. const registry = createToolRegistry();
  946. registerMcpTools(
  947. registry,
  948. createMockMcpPort({ callTool: async () => result }),
  949. [
  950. {
  951. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  952. toolName: "perform_action",
  953. inputSchema: { type: "object", properties: {} },
  954. },
  955. ],
  956. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  957. );
  958. const entry = registry.get("mcp__computer-use__perform_action");
  959. const output = await entry?.handler({}, createToolContext());
  960. expect(output).toBe(result);
  961. expect(entry?.formatModelContent?.(output)).toBe(
  962. `${result.content[0].text}\n\n${result.content[1].text}`,
  963. );
  964. });
  965. it("does not synthesize refresh_required when a receipt has no post-state", async () => {
  966. const receipt = cuaActionReceipt();
  967. const registry = createToolRegistry();
  968. registerMcpTools(
  969. registry,
  970. createMockMcpPort({
  971. callTool: async () => ({
  972. content: [
  973. { type: "text", text: "state_id=s-9 app=Wrong" },
  974. { type: "text", text: receipt },
  975. ],
  976. }),
  977. }),
  978. [
  979. {
  980. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  981. toolName: "perform_action",
  982. inputSchema: { type: "object", properties: {} },
  983. },
  984. ],
  985. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  986. );
  987. const output = await registry
  988. .get("mcp__computer-use__perform_action")
  989. ?.handler({}, createToolContext());
  990. expect(output?.isError).not.toBe(true);
  991. expect(output?.content).toEqual([
  992. { type: "text", text: "state_id=s-9 app=Wrong" },
  993. { type: "text", text: receipt },
  994. ]);
  995. expect(JSON.stringify(output)).not.toContain("refresh_required");
  996. });
  997. it("keeps official CUA receipt normalization out of the bridge budget path", async () => {
  998. const registry = createToolRegistry();
  999. const oversizedState = `state_id=s-2 app=Example\n${"tree-node ".repeat(30_000)}`;
  1000. const receipt = cuaActionReceipt();
  1001. registerMcpTools(
  1002. registry,
  1003. createMockMcpPort({
  1004. callTool: async () => ({
  1005. content: [
  1006. { type: "text", text: oversizedState },
  1007. { type: "text", text: receipt },
  1008. ],
  1009. }),
  1010. }),
  1011. [
  1012. {
  1013. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  1014. toolName: "perform_action",
  1015. inputSchema: { type: "object", properties: {} },
  1016. },
  1017. ],
  1018. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  1019. );
  1020. const output = await registry
  1021. .get("mcp__computer-use__perform_action")
  1022. ?.handler({}, createToolContext());
  1023. expect(Buffer.byteLength(oversizedState, "utf8")).toBeGreaterThan(256 * 1024);
  1024. expect(output?.isError).not.toBe(true);
  1025. expect(output?.content).toEqual([
  1026. { type: "text", text: oversizedState },
  1027. { type: "text", text: receipt },
  1028. ]);
  1029. });
  1030. it("keeps structured data for consumers while projecting official CUA receipt content", async () => {
  1031. const registry = createToolRegistry();
  1032. registerMcpTools(
  1033. registry,
  1034. createMockMcpPort({
  1035. callTool: async () => ({
  1036. content: [{ type: "text", text: cuaActionReceipt() }],
  1037. structuredContent: { diagnostic: "receipt-only" },
  1038. }),
  1039. }),
  1040. [
  1041. {
  1042. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  1043. toolName: "perform_action",
  1044. inputSchema: { type: "object", properties: {} },
  1045. },
  1046. ],
  1047. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  1048. );
  1049. const output = await registry
  1050. .get("mcp__computer-use__perform_action")
  1051. ?.handler({}, createToolContext());
  1052. const entry = registry.get("mcp__computer-use__perform_action");
  1053. const modelContent = entry?.formatModelContent?.(output);
  1054. expect(output?.isError).not.toBe(true);
  1055. expect(modelContent).toBe(cuaActionReceipt());
  1056. expect(output?.structuredContent).toEqual({ diagnostic: "receipt-only" });
  1057. expect(modelContent).not.toContain("refresh_required");
  1058. });
  1059. it("preserves producer possibly-sent receipts without inventing a post-state", async () => {
  1060. const result = {
  1061. content: [
  1062. {
  1063. type: "text" as const,
  1064. text: JSON.stringify({
  1065. message: "The action may have been sent; refresh first.",
  1066. action_receipt: JSON.parse(
  1067. cuaActionReceipt({
  1068. dispatch_status: "possibly_sent",
  1069. }),
  1070. ).action_receipt,
  1071. state: null,
  1072. }),
  1073. },
  1074. ],
  1075. };
  1076. const registry = createToolRegistry();
  1077. registerMcpTools(
  1078. registry,
  1079. createMockMcpPort({ callTool: async () => result }),
  1080. [
  1081. {
  1082. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  1083. toolName: "perform_action",
  1084. inputSchema: { type: "object", properties: {} },
  1085. },
  1086. ],
  1087. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  1088. );
  1089. const entry = registry.get("mcp__computer-use__perform_action");
  1090. const output = await entry?.handler({}, createToolContext());
  1091. expect(output).toBe(result);
  1092. expect(entry?.formatModelContent?.(output)).toEqual(result.content[0].text);
  1093. });
  1094. it("preserves a large JSON-only result from an official CUA tool", async () => {
  1095. const text = JSON.stringify(
  1096. Array.from({ length: 160 }, (_, index) => ({
  1097. bundle_id: `dev.example.application.${index}`,
  1098. name: `Application ${index}`,
  1099. pid: 10_000 + index,
  1100. })),
  1101. );
  1102. expect(text.length).toBeGreaterThan(1024);
  1103. const result = { content: [{ type: "text" as const, text }] };
  1104. const registry = createToolRegistry();
  1105. registerMcpTools(
  1106. registry,
  1107. createMockMcpPort({ callTool: async () => result }),
  1108. [
  1109. {
  1110. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  1111. toolName: "list_apps",
  1112. inputSchema: { type: "object", properties: {} },
  1113. },
  1114. ],
  1115. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  1116. );
  1117. const output = await registry
  1118. .get("mcp__computer-use__list_apps")
  1119. ?.handler({}, createToolContext());
  1120. expect(output).toBe(result);
  1121. });
  1122. it("persists the original explicit browser screenshot while compressing its model image", async () => {
  1123. const registry = createToolRegistry();
  1124. const originalImage = Buffer.alloc(MCP_IMAGE_INLINE_RAW_BYTES + 1, 7);
  1125. const compressedImage = Buffer.from("compressed-browser-screenshot");
  1126. const mcpPort = createMockMcpPort({
  1127. callTool: async () => ({
  1128. // node_repl 现在把 image 排在 text 之前(见 node-repl-host/src/result.ts),
  1129. // screenshot 下标因此直接是 content 下标。
  1130. content: [
  1131. {
  1132. type: "image",
  1133. data: originalImage.toString("base64"),
  1134. mimeType: "image/png",
  1135. },
  1136. { type: "text", text: "(no output)" },
  1137. ],
  1138. _meta: {
  1139. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0],
  1140. },
  1141. }),
  1142. });
  1143. const artifactWrites: Uint8Array[] = [];
  1144. const artifactStore: ToolArtifactStorePort = {
  1145. writeToolResultArtifact: async () => {
  1146. throw new Error("unexpected text artifact write");
  1147. },
  1148. writeToolResultBinaryArtifact: async (request) => {
  1149. artifactWrites.push(request.content);
  1150. return {
  1151. id: "explicit-browser-shot",
  1152. uri: "zcode-artifact://session/explicit-browser-shot",
  1153. path: "/tmp/explicit-browser-shot.png",
  1154. bytes: request.content.byteLength,
  1155. contentType: request.contentType,
  1156. createdAt: new Date("2026-07-20T00:00:00.000Z"),
  1157. };
  1158. },
  1159. readToolResultArtifact: async () => {
  1160. throw new Error("not used");
  1161. },
  1162. };
  1163. const prepareRequests: Parameters<ImageProcessorPort["prepareForModel"]>[0][] = [];
  1164. const imageProcessorPort: ImageProcessorPort = {
  1165. resizeToFit: async () => {
  1166. throw new Error("unexpected resizeToFit call");
  1167. },
  1168. prepareForModel: async (request) => {
  1169. prepareRequests.push(request);
  1170. return {
  1171. compressed: true,
  1172. data: compressedImage,
  1173. height: 900,
  1174. mediaType: "image/jpeg",
  1175. originalHeight: 3218,
  1176. originalSizeBytes: originalImage.byteLength,
  1177. originalWidth: 942,
  1178. resized: true,
  1179. strategy: "jpeg-quality",
  1180. transformedSizeBytes: compressedImage.byteLength,
  1181. width: 263,
  1182. };
  1183. },
  1184. };
  1185. registerMcpTools(registry, mcpPort, [
  1186. {
  1187. serverName: "node_repl",
  1188. toolName: "js",
  1189. inputSchema: { type: "object", properties: {} },
  1190. },
  1191. ]);
  1192. const entry = registry.get("mcp__node_repl__js");
  1193. const output = await entry?.handler(
  1194. {},
  1195. createToolContext({ artifactStore, imageProcessorPort }),
  1196. );
  1197. const modelContent = entry?.formatModelContent?.(output);
  1198. expect(prepareRequests).toHaveLength(1);
  1199. expect(prepareRequests[0]).toMatchObject({
  1200. maxBase64Bytes: MCP_IMAGE_INLINE_BASE64_BYTES,
  1201. maxDimension: 2000,
  1202. maxRawBytes: MCP_IMAGE_INLINE_RAW_BYTES,
  1203. mediaType: "image/png",
  1204. });
  1205. // artifact 提示文本必须排在 image 之后:它是为 browser screenshot 现场插入的,
  1206. // 插在 image 前会让 tool_result.content 重新变成 text-first,图又会被网关丢掉。
  1207. expect(modelContent).toEqual([
  1208. {
  1209. type: "image",
  1210. dataUrl: `data:image/jpeg;base64,${compressedImage.toString("base64")}`,
  1211. mediaType: "image/jpeg",
  1212. source: expect.objectContaining({
  1213. id: "mcp-image",
  1214. kind: "inline",
  1215. mimeType: "image/jpeg",
  1216. }),
  1217. },
  1218. {
  1219. type: "text",
  1220. text: "Browser screenshot saved to: /tmp/explicit-browser-shot.png",
  1221. },
  1222. { type: "text", text: "(no output)" },
  1223. ]);
  1224. expect(artifactWrites).toHaveLength(1);
  1225. expect(Buffer.from(artifactWrites[0] ?? [])).toEqual(originalImage);
  1226. expect(JSON.stringify(modelContent)).not.toContain(originalImage.toString("base64"));
  1227. });
  1228. it("does not persist ordinary nodeRepl.emitImage content without a screenshot marker", async () => {
  1229. const registry = createToolRegistry();
  1230. const writeToolResultBinaryArtifact = vi.fn(
  1231. async (
  1232. request: Parameters<NonNullable<ToolArtifactStorePort["writeToolResultBinaryArtifact"]>>[0],
  1233. ) => ({
  1234. id: "unexpected",
  1235. uri: "zcode-artifact://session/unexpected",
  1236. path: "/tmp/unexpected.png",
  1237. bytes: request.content.byteLength,
  1238. contentType: request.contentType,
  1239. createdAt: new Date("2026-07-20T00:00:00.000Z"),
  1240. }),
  1241. );
  1242. const artifactStore: ToolArtifactStorePort = {
  1243. writeToolResultArtifact: async () => {
  1244. throw new Error("not used");
  1245. },
  1246. writeToolResultBinaryArtifact,
  1247. readToolResultArtifact: async () => {
  1248. throw new Error("not used");
  1249. },
  1250. };
  1251. const mcpPort = createMockMcpPort({
  1252. callTool: async () => ({
  1253. content: [{ type: "image", data: "AQID", mimeType: "image/png" }],
  1254. }),
  1255. });
  1256. registerMcpTools(registry, mcpPort, [
  1257. {
  1258. serverName: "node_repl",
  1259. toolName: "js",
  1260. inputSchema: { type: "object", properties: {} },
  1261. },
  1262. ]);
  1263. const entry = registry.get("mcp__node_repl__js");
  1264. const output = await entry?.handler({}, createToolContext({ artifactStore }));
  1265. expect(writeToolResultBinaryArtifact).not.toHaveBeenCalled();
  1266. expect(entry?.formatModelContent?.(output)).toEqual([
  1267. expect.objectContaining({ type: "image", mediaType: "image/png" }),
  1268. ]);
  1269. });
  1270. it("falls back to the existing oversized-image policy when node_repl compression fails", async () => {
  1271. const registry = createToolRegistry();
  1272. const originalImage = Buffer.alloc(MCP_IMAGE_INLINE_RAW_BYTES + 1, 13);
  1273. const mcpPort = createMockMcpPort({
  1274. callTool: async () => ({
  1275. content: [
  1276. {
  1277. type: "image",
  1278. data: originalImage.toString("base64"),
  1279. mimeType: "image/png",
  1280. },
  1281. ],
  1282. }),
  1283. });
  1284. const imageProcessorPort: ImageProcessorPort = {
  1285. resizeToFit: async () => {
  1286. throw new Error("unexpected resizeToFit call");
  1287. },
  1288. prepareForModel: async () => {
  1289. throw new Error("decode failed");
  1290. },
  1291. };
  1292. registerMcpTools(registry, mcpPort, [
  1293. {
  1294. serverName: "node_repl",
  1295. toolName: "js",
  1296. inputSchema: { type: "object", properties: {} },
  1297. },
  1298. ]);
  1299. const entry = registry.get("mcp__node_repl__js");
  1300. const output = await entry?.handler({}, createToolContext({ imageProcessorPort }));
  1301. const modelContent = entry?.formatModelContent?.(output);
  1302. expect(modelContent).toContain("MCP image content omitted");
  1303. expect(modelContent).toContain("No artifact store is configured");
  1304. expect(JSON.stringify(modelContent)).not.toContain(originalImage.toString("base64"));
  1305. });
  1306. it("rejects node_repl compression output that still exceeds the inline budget", async () => {
  1307. const registry = createToolRegistry();
  1308. const originalImage = Buffer.alloc(MCP_IMAGE_INLINE_RAW_BYTES + 1, 17);
  1309. const mcpPort = createMockMcpPort({
  1310. callTool: async () => ({
  1311. content: [
  1312. {
  1313. type: "image",
  1314. data: originalImage.toString("base64"),
  1315. mimeType: "image/png",
  1316. },
  1317. ],
  1318. }),
  1319. });
  1320. const imageProcessorPort: ImageProcessorPort = {
  1321. resizeToFit: async () => {
  1322. throw new Error("unexpected resizeToFit call");
  1323. },
  1324. prepareForModel: async () => ({
  1325. compressed: true,
  1326. data: Buffer.alloc(MCP_IMAGE_INLINE_RAW_BYTES + 1, 19),
  1327. mediaType: "image/jpeg",
  1328. originalSizeBytes: originalImage.byteLength,
  1329. resized: false,
  1330. strategy: "jpeg-quality",
  1331. transformedSizeBytes: MCP_IMAGE_INLINE_RAW_BYTES + 1,
  1332. }),
  1333. };
  1334. registerMcpTools(registry, mcpPort, [
  1335. {
  1336. serverName: "node_repl",
  1337. toolName: "js",
  1338. inputSchema: { type: "object", properties: {} },
  1339. },
  1340. ]);
  1341. const entry = registry.get("mcp__node_repl__js");
  1342. const output = await entry?.handler({}, createToolContext({ imageProcessorPort }));
  1343. const modelContent = entry?.formatModelContent?.(output);
  1344. expect(modelContent).toContain("MCP image content omitted");
  1345. expect(modelContent).toContain("No artifact store is configured");
  1346. expect(JSON.stringify(modelContent)).not.toContain(originalImage.toString("base64"));
  1347. });
  1348. it("stores oversized MCP image content before projecting model-visible output", async () => {
  1349. const registry = createToolRegistry();
  1350. const originalImage = Buffer.alloc(MCP_IMAGE_INLINE_BASE64_BYTES, 7);
  1351. const largeBase64 = originalImage.toString("base64");
  1352. const mcpPort = createMockMcpPort({
  1353. callTool: async () => ({
  1354. content: [
  1355. { type: "text", text: '{"path":"screenshots/latest.png"}' },
  1356. { type: "image", data: largeBase64, mimeType: "image/png" },
  1357. ],
  1358. }),
  1359. });
  1360. const artifactWrites: Array<{
  1361. content: Buffer;
  1362. contentType: string;
  1363. extension?: string;
  1364. }> = [];
  1365. const artifactStore: ToolArtifactStorePort = {
  1366. writeToolResultArtifact: async (request) => {
  1367. throw new Error(`unexpected text artifact write: ${request.contentType}`);
  1368. },
  1369. writeToolResultBinaryArtifact: async (request) => {
  1370. const content = Buffer.from(request.content);
  1371. artifactWrites.push({
  1372. content,
  1373. contentType: request.contentType,
  1374. extension: request.extension,
  1375. });
  1376. return {
  1377. id: "artifact-large-image",
  1378. uri: "zcode-artifact://session/artifact-large-image",
  1379. path: "/tmp/mcp-image.png",
  1380. bytes: content.byteLength,
  1381. contentType: request.contentType,
  1382. createdAt: new Date("2026-06-10T00:00:00.000Z"),
  1383. };
  1384. },
  1385. readToolResultArtifact: async () => {
  1386. throw new Error("not used");
  1387. },
  1388. };
  1389. registerMcpTools(registry, mcpPort, [
  1390. {
  1391. serverName: "ios_simulator",
  1392. toolName: "ios_screenshot",
  1393. inputSchema: {
  1394. type: "object",
  1395. properties: {},
  1396. },
  1397. },
  1398. ]);
  1399. const entry = registry.get("mcp__ios_simulator__ios_screenshot");
  1400. const output = await entry?.handler({}, createToolContext({ artifactStore }));
  1401. const modelContent = entry?.formatModelContent?.(output);
  1402. expect(artifactWrites).toHaveLength(1);
  1403. expect(Buffer.byteLength(largeBase64, "utf8")).toBeGreaterThan(MCP_IMAGE_INLINE_BASE64_BYTES);
  1404. expect(artifactWrites[0]).toMatchObject({
  1405. contentType: "image/png",
  1406. extension: ".png",
  1407. });
  1408. expect(artifactWrites[0]?.content).toEqual(originalImage);
  1409. expect(modelContent).toContain("screenshots/latest.png");
  1410. expect(modelContent).toContain("/tmp/mcp-image.png");
  1411. expect(JSON.stringify(modelContent)).not.toContain(largeBase64);
  1412. });
  1413. it("falls back to text artifacts for oversized MCP images when binary artifacts are unsupported", async () => {
  1414. const registry = createToolRegistry();
  1415. const largeBase64 = Buffer.alloc(MCP_IMAGE_INLINE_BASE64_BYTES, 9).toString("base64");
  1416. const mcpPort = createMockMcpPort({
  1417. callTool: async () => ({
  1418. content: [{ type: "image", data: largeBase64, mimeType: "image/png" }],
  1419. }),
  1420. });
  1421. const artifactWrites: Array<{ content: string; contentType?: string }> = [];
  1422. const artifactStore: ToolArtifactStorePort = {
  1423. writeToolResultArtifact: async (request) => {
  1424. artifactWrites.push({
  1425. content: request.content,
  1426. contentType: request.contentType,
  1427. });
  1428. return {
  1429. id: "artifact-large-image",
  1430. uri: "zcode-artifact://session/artifact-large-image",
  1431. path: "/tmp/mcp-image.json",
  1432. bytes: Buffer.byteLength(request.content, "utf8"),
  1433. contentType: request.contentType ?? "application/json",
  1434. createdAt: new Date("2026-06-10T00:00:00.000Z"),
  1435. };
  1436. },
  1437. readToolResultArtifact: async () => {
  1438. throw new Error("not used");
  1439. },
  1440. };
  1441. registerMcpTools(registry, mcpPort, [
  1442. {
  1443. serverName: "ios_simulator",
  1444. toolName: "ios_screenshot",
  1445. inputSchema: {
  1446. type: "object",
  1447. properties: {},
  1448. },
  1449. },
  1450. ]);
  1451. const entry = registry.get("mcp__ios_simulator__ios_screenshot");
  1452. const output = await entry?.handler({}, createToolContext({ artifactStore }));
  1453. const modelContent = entry?.formatModelContent?.(output);
  1454. expect(artifactWrites).toHaveLength(1);
  1455. expect(artifactWrites[0]?.contentType).toBe("application/json");
  1456. expect(JSON.parse(artifactWrites[0]!.content)).toMatchObject({
  1457. dataUrl: `data:image/png;base64,${largeBase64}`,
  1458. inlineLimitBytes: MCP_IMAGE_INLINE_BASE64_BYTES,
  1459. mimeType: "image/png",
  1460. serverName: "ios_simulator",
  1461. toolName: "ios_screenshot",
  1462. type: "mcp-image-artifact",
  1463. });
  1464. expect(modelContent).toContain("/tmp/mcp-image.json");
  1465. expect(JSON.stringify(modelContent)).not.toContain(largeBase64);
  1466. });
  1467. it("omits oversized MCP image content when artifact storage is unavailable", async () => {
  1468. const registry = createToolRegistry();
  1469. const largeBase64 = Buffer.alloc(MCP_IMAGE_INLINE_BASE64_BYTES, 11).toString("base64");
  1470. const mcpPort = createMockMcpPort({
  1471. callTool: async () => ({
  1472. content: [{ type: "image", data: largeBase64, mimeType: "image/png" }],
  1473. }),
  1474. });
  1475. registerMcpTools(registry, mcpPort, [
  1476. {
  1477. serverName: "ios_simulator",
  1478. toolName: "ios_screenshot",
  1479. inputSchema: {
  1480. type: "object",
  1481. properties: {},
  1482. },
  1483. },
  1484. ]);
  1485. const entry = registry.get("mcp__ios_simulator__ios_screenshot");
  1486. const output = await entry?.handler({}, createToolContext());
  1487. const modelContent = entry?.formatModelContent?.(output);
  1488. expect(modelContent).toContain("MCP image content omitted");
  1489. expect(modelContent).toContain("No artifact store is configured");
  1490. expect(JSON.stringify(modelContent)).not.toContain(largeBase64);
  1491. });
  1492. });
  1493. function createToolContext(
  1494. overrides: Partial<
  1495. Pick<
  1496. ToolExecutionContext,
  1497. "artifactStore" | "imageProcessorPort" | "runtimeScope" | "workingDirectory" | "workspaceKey"
  1498. >
  1499. > = {},
  1500. ): ToolExecutionContext {
  1501. return {
  1502. abortSignal: new AbortController().signal,
  1503. sessionId: createSessionId("mcp-tool-bridge"),
  1504. toolCallId: "tool-test",
  1505. traceId: "trace-test" as never,
  1506. workingDirectory: "/tmp/project",
  1507. workspaceRoot: "/tmp/project",
  1508. ...overrides,
  1509. };
  1510. }