mcp-tool-bridge.test.ts 50 KB

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