mcp-tool-bridge.test.ts 50 KB

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