mcp-tool-bridge.test.ts 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  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("removes disallowed MCP tools from the registry", () => {
  446. const registry = createToolRegistry();
  447. const mcpPort = createMockMcpPort();
  448. const registered = registerMcpTools(
  449. registry,
  450. mcpPort,
  451. [
  452. {
  453. serverName: "local server",
  454. toolName: "say-hi",
  455. description: "Say hi",
  456. inputSchema: { type: "object" },
  457. },
  458. {
  459. serverName: "local server",
  460. toolName: "say-bye",
  461. description: "Say bye",
  462. inputSchema: { type: "object" },
  463. },
  464. ],
  465. {
  466. disallowedTools: ["mcp__local_server__say-hi(*)"],
  467. },
  468. );
  469. expect(registered).toEqual(["mcp__local_server__say-bye"]);
  470. expect(registry.has("mcp__local_server__say-hi")).toBe(false);
  471. expect(registry.has("mcp__local_server__say-bye")).toBe(true);
  472. });
  473. it("does not register explicitly disallowed MCP tools", () => {
  474. const registry = createToolRegistry();
  475. const mcpPort = createMockMcpPort();
  476. const registered = registerMcpTools(
  477. registry,
  478. mcpPort,
  479. [
  480. {
  481. serverName: "zcode-cua",
  482. toolName: "get_app_state",
  483. inputSchema: { type: "object", properties: {} },
  484. },
  485. {
  486. serverName: "zcode-cua",
  487. toolName: "left_click",
  488. inputSchema: { type: "object", properties: {} },
  489. },
  490. ],
  491. { disallowedTools: ["mcp__zcode-cua__left_click"] },
  492. );
  493. expect(registered).toEqual(["mcp__zcode-cua__get_app_state"]);
  494. expect(registry.has("mcp__zcode-cua__get_app_state")).toBe(true);
  495. expect(registry.has("mcp__zcode-cua__left_click")).toBe(false);
  496. });
  497. it("requires a user title for CUA app observation and strips it before MCP dispatch", async () => {
  498. const registry = createToolRegistry();
  499. const callTool = vi.fn(async () => ({ content: [] }));
  500. registerMcpTools(registry, createMockMcpPort({ callTool }), [
  501. {
  502. serverName: "plugin:computer-use:computer-use",
  503. toolName: "get_app_state",
  504. inputSchema: {
  505. type: "object",
  506. required: ["app_ref"],
  507. properties: {
  508. app_ref: { type: "object" },
  509. detail: { type: "string" },
  510. },
  511. additionalProperties: false,
  512. },
  513. },
  514. ]);
  515. const entry = registry.get("mcp__plugin_computer-use_computer-use__get_app_state");
  516. expect(entry?.inputSchema).toMatchObject({
  517. required: ["app_ref", "title"],
  518. properties: {
  519. title: {
  520. type: "string",
  521. minLength: 1,
  522. maxLength: 120,
  523. },
  524. },
  525. additionalProperties: false,
  526. });
  527. await entry?.handler(
  528. {
  529. app_ref: { pid: 42 },
  530. detail: "compact",
  531. title: "检查设置窗口中的隐私权限",
  532. },
  533. createToolContext(),
  534. );
  535. expect(callTool).toHaveBeenCalledWith(
  536. expect.objectContaining({
  537. arguments: {
  538. app_ref: { pid: 42 },
  539. detail: "compact",
  540. },
  541. }),
  542. expect.anything(),
  543. );
  544. });
  545. it("preserves the official CUA element-vs-image target boundary for the model", () => {
  546. const registry = createToolRegistry();
  547. const target = {
  548. description:
  549. "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.",
  550. anyOf: [
  551. {
  552. type: "object",
  553. required: ["type", "state_id", "index"],
  554. properties: {
  555. type: { const: "element" },
  556. state_id: { type: "string" },
  557. index: { type: "integer" },
  558. },
  559. additionalProperties: false,
  560. },
  561. {
  562. type: "object",
  563. required: ["type", "frame_id", "x", "y"],
  564. properties: {
  565. type: { const: "coordinate" },
  566. frame_id: { type: "string", minLength: 1 },
  567. x: { type: "integer", minimum: 0 },
  568. y: { type: "integer", minimum: 0 },
  569. },
  570. additionalProperties: false,
  571. },
  572. ],
  573. };
  574. registerMcpTools(registry, createMockMcpPort(), [
  575. {
  576. serverName: "plugin:computer-use:computer-use",
  577. toolName: "left_click",
  578. inputSchema: {
  579. type: "object",
  580. required: ["target"],
  581. properties: { target },
  582. additionalProperties: false,
  583. },
  584. },
  585. ]);
  586. const modelTarget = registry.get("mcp__plugin_computer-use_computer-use__left_click")
  587. ?.inputSchema.properties?.target as typeof target;
  588. expect(modelTarget).toEqual(target);
  589. });
  590. it("does not add a title contract to unrelated get_app_state MCP tools", () => {
  591. const registry = createToolRegistry();
  592. registerMcpTools(registry, createMockMcpPort(), [
  593. {
  594. serverName: "device-inspector",
  595. toolName: "get_app_state",
  596. inputSchema: {
  597. type: "object",
  598. properties: { app_id: { type: "string" } },
  599. },
  600. },
  601. ]);
  602. const schema = registry.get("mcp__device-inspector__get_app_state")?.inputSchema;
  603. expect(schema).not.toHaveProperty("properties.title");
  604. expect(schema).not.toHaveProperty("required");
  605. });
  606. it.each(["computer-use", "zcode-cua"])(
  607. "recognizes the %s CUA server identity for the title contract",
  608. (serverName) => {
  609. const registry = createToolRegistry();
  610. registerMcpTools(registry, createMockMcpPort(), [
  611. {
  612. serverName,
  613. toolName: "get_app_state",
  614. inputSchema: { type: "object", properties: {} },
  615. },
  616. ]);
  617. expect(registry.get(`mcp__${serverName}__get_app_state`)?.inputSchema).toMatchObject({
  618. required: ["title"],
  619. properties: { title: { type: "string" } },
  620. });
  621. },
  622. );
  623. it("maps destructive MCP annotations into tool metadata", () => {
  624. const registry = createToolRegistry();
  625. const mcpPort = createMockMcpPort();
  626. registerMcpTools(registry, mcpPort, [
  627. {
  628. serverName: "device",
  629. toolName: "reset",
  630. description: "Reset a device",
  631. inputSchema: { type: "object" },
  632. annotations: {
  633. destructiveHint: true,
  634. },
  635. },
  636. ]);
  637. const entry = registry.get("mcp__device__reset");
  638. expect(entry?.metadata).toMatchObject({
  639. destructive: true,
  640. readOnly: false,
  641. riskLevel: "high",
  642. sideEffectScope: "network",
  643. });
  644. expect(entry?.permission).toMatchObject({
  645. permission: "mcp",
  646. riskLevel: "high",
  647. sideEffectScope: "network",
  648. });
  649. });
  650. it("honors the structured message-only MCP error presentation", () => {
  651. const registry = createToolRegistry();
  652. registerMcpTools(registry, createMockMcpPort(), [
  653. {
  654. serverName: "device",
  655. toolName: "validate",
  656. inputSchema: { type: "object" },
  657. },
  658. ]);
  659. const entry = registry.get("mcp__device__validate");
  660. const modelContent = entry?.formatModelContent?.({
  661. content: [
  662. {
  663. type: "text",
  664. text: "browser tab 'iab-tab:test' returned an invalid viewport",
  665. },
  666. ],
  667. isError: true,
  668. _meta: {
  669. [ZCODE_MCP_ERROR_PRESENTATION_META_KEY]: ZCODE_MCP_ERROR_PRESENTATION_MESSAGE_ONLY,
  670. },
  671. });
  672. expect(modelContent).toBe("browser tab 'iab-tab:test' returned an invalid viewport");
  673. });
  674. it("projects non-object MCP 2026-07-28 structured content", () => {
  675. const registry = createToolRegistry();
  676. registerMcpTools(registry, createMockMcpPort(), [
  677. {
  678. serverName: "modern",
  679. toolName: "structured",
  680. inputSchema: { type: "object" },
  681. },
  682. ]);
  683. const entry = registry.get("mcp__modern__structured");
  684. expect(entry?.outputSchema.properties?.structuredContent).toEqual({});
  685. expect(
  686. entry?.formatModelContent?.({
  687. content: [],
  688. structuredContent: ["alpha", { beta: true }],
  689. }),
  690. ).toBe('Structured content:\n[\n "alpha",\n {\n "beta": true\n }\n]');
  691. });
  692. it("preserves multiline MCP error details when they are not stack frames", () => {
  693. const registry = createToolRegistry();
  694. registerMcpTools(registry, createMockMcpPort(), [
  695. {
  696. serverName: "device",
  697. toolName: "validate",
  698. inputSchema: { type: "object" },
  699. },
  700. ]);
  701. const entry = registry.get("mcp__device__validate");
  702. const modelContent = entry?.formatModelContent?.({
  703. content: [
  704. {
  705. type: "text",
  706. text: "Invalid input\n- width is required\n- height is required",
  707. },
  708. ],
  709. isError: true,
  710. _meta: {
  711. [ZCODE_MCP_ERROR_PRESENTATION_META_KEY]: ZCODE_MCP_ERROR_PRESENTATION_MESSAGE_ONLY,
  712. },
  713. });
  714. expect(modelContent).toBe("Invalid input\n- width is required\n- height is required");
  715. });
  716. it("keeps the existing error projection without message-only metadata", () => {
  717. const registry = createToolRegistry();
  718. registerMcpTools(registry, createMockMcpPort(), [
  719. {
  720. serverName: "device",
  721. toolName: "validate",
  722. inputSchema: { type: "object" },
  723. },
  724. ]);
  725. const entry = registry.get("mcp__device__validate");
  726. const errorText = [
  727. "ValidationError: Invalid input",
  728. " at validate (file:///plugins/device.mjs:12:3)",
  729. ].join("\n");
  730. const modelContent = entry?.formatModelContent?.({
  731. content: [{ type: "text", text: errorText }],
  732. isError: true,
  733. });
  734. expect(modelContent).toBe(`MCP tool returned an error:\n${errorText}`);
  735. });
  736. it("projects MCP image content as model-visible image blocks", () => {
  737. const registry = createToolRegistry();
  738. const mcpPort = createMockMcpPort();
  739. registerMcpTools(registry, mcpPort, [
  740. {
  741. serverName: "ios_simulator",
  742. toolName: "ios_screenshot",
  743. inputSchema: {
  744. type: "object",
  745. properties: {},
  746. },
  747. },
  748. ]);
  749. const entry = registry.get("mcp__ios_simulator__ios_screenshot");
  750. const modelContent = entry?.formatModelContent?.({
  751. content: [
  752. { type: "text", text: '{"path":"screenshots/latest.png"}' },
  753. { type: "image", data: "aGVsbG8=", mimeType: "image/png" },
  754. ],
  755. });
  756. expect(modelContent).toEqual([
  757. { type: "text", text: '{"path":"screenshots/latest.png"}' },
  758. {
  759. type: "image",
  760. mediaType: "image/png",
  761. dataUrl: "data:image/png;base64,aGVsbG8=",
  762. source: {
  763. id: "mcp-image",
  764. kind: "inline",
  765. mimeType: "image/png",
  766. placeholder: "MCP image",
  767. sizeBytes: 5,
  768. },
  769. },
  770. ]);
  771. });
  772. it("preserves an authority-verified CUA frame image-first pair byte-for-byte", async () => {
  773. const registry = createToolRegistry();
  774. const imageData =
  775. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";
  776. const result = {
  777. content: [
  778. { type: "image" as const, data: imageData, mimeType: "image/png" },
  779. {
  780. type: "text" as const,
  781. text: JSON.stringify({
  782. image_ref: {
  783. actionable: true,
  784. frame_id: "frame_exact_001",
  785. height: 1,
  786. width: 1,
  787. },
  788. }),
  789. },
  790. ],
  791. _meta: officialCuaIntegrityMeta("frame_exact_001", imageData),
  792. };
  793. const callTool = vi.fn(async () => result);
  794. registerMcpTools(
  795. registry,
  796. createMockMcpPort({ callTool }),
  797. [
  798. {
  799. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  800. toolName: "get_app_state",
  801. inputSchema: { type: "object", properties: {} },
  802. },
  803. ],
  804. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  805. );
  806. const entry = registry.get("mcp__computer-use__get_app_state");
  807. const output = await entry?.handler(
  808. { title: "读取精确坐标图" },
  809. createToolContext({
  810. imageProcessorPort: exactRasterInspector(1, 1),
  811. }),
  812. );
  813. expect(output).toBe(result);
  814. expect(output?.content[0]).toEqual({
  815. type: "image",
  816. data: imageData,
  817. mimeType: "image/png",
  818. });
  819. expect(entry?.resultBudget).toMatchObject({
  820. maxInlineBytes: 256 * 1024,
  821. maxModelBytes: 256 * 1024,
  822. });
  823. expect(entry?.modelContentProtection).toBe("official_cua_frame_v1");
  824. expect(entry?.formatModelContent?.(output)).toEqual([
  825. expect.objectContaining({
  826. type: "image",
  827. dataUrl: `data:image/png;base64,${imageData}`,
  828. }),
  829. {
  830. type: "text",
  831. text: result.content[1].text,
  832. },
  833. ]);
  834. });
  835. it("projects an official CUA action receipt through the generic MCP formatter", async () => {
  836. const result = {
  837. content: [
  838. { type: "text" as const, text: "Dispatched AXPress. (receipt below)" },
  839. { type: "text" as const, text: cuaActionReceipt() },
  840. ],
  841. structuredContent: undefined,
  842. isError: undefined,
  843. _meta: undefined,
  844. };
  845. const registry = createToolRegistry();
  846. registerMcpTools(
  847. registry,
  848. createMockMcpPort({ callTool: async () => result }),
  849. [
  850. {
  851. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  852. toolName: "perform_action",
  853. inputSchema: { type: "object", properties: {} },
  854. },
  855. ],
  856. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  857. );
  858. const entry = registry.get("mcp__computer-use__perform_action");
  859. const output = await entry?.handler({}, createToolContext());
  860. expect(output).toBe(result);
  861. expect(entry?.formatModelContent?.(output)).toBe(
  862. `${result.content[0].text}\n\n${result.content[1].text}`,
  863. );
  864. });
  865. it("does not synthesize refresh_required when a receipt has no post-state", async () => {
  866. const receipt = cuaActionReceipt();
  867. const registry = createToolRegistry();
  868. registerMcpTools(
  869. registry,
  870. createMockMcpPort({
  871. callTool: async () => ({
  872. content: [
  873. { type: "text", text: "state_id=s-9 app=Wrong" },
  874. { type: "text", text: receipt },
  875. ],
  876. }),
  877. }),
  878. [
  879. {
  880. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  881. toolName: "perform_action",
  882. inputSchema: { type: "object", properties: {} },
  883. },
  884. ],
  885. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  886. );
  887. const output = await registry
  888. .get("mcp__computer-use__perform_action")
  889. ?.handler({}, createToolContext());
  890. expect(output?.isError).not.toBe(true);
  891. expect(output?.content).toEqual([
  892. { type: "text", text: "state_id=s-9 app=Wrong" },
  893. { type: "text", text: receipt },
  894. ]);
  895. expect(JSON.stringify(output)).not.toContain("refresh_required");
  896. });
  897. it("keeps official CUA receipt normalization out of the bridge budget path", async () => {
  898. const registry = createToolRegistry();
  899. const oversizedState = `state_id=s-2 app=Example\n${"tree-node ".repeat(30_000)}`;
  900. const receipt = cuaActionReceipt();
  901. registerMcpTools(
  902. registry,
  903. createMockMcpPort({
  904. callTool: async () => ({
  905. content: [
  906. { type: "text", text: oversizedState },
  907. { type: "text", text: receipt },
  908. ],
  909. }),
  910. }),
  911. [
  912. {
  913. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  914. toolName: "perform_action",
  915. inputSchema: { type: "object", properties: {} },
  916. },
  917. ],
  918. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  919. );
  920. const output = await registry
  921. .get("mcp__computer-use__perform_action")
  922. ?.handler({}, createToolContext());
  923. expect(Buffer.byteLength(oversizedState, "utf8")).toBeGreaterThan(256 * 1024);
  924. expect(output?.isError).not.toBe(true);
  925. expect(output?.content).toEqual([
  926. { type: "text", text: oversizedState },
  927. { type: "text", text: receipt },
  928. ]);
  929. });
  930. it("keeps structured content as ordinary MCP result text for official CUA receipts", async () => {
  931. const registry = createToolRegistry();
  932. registerMcpTools(
  933. registry,
  934. createMockMcpPort({
  935. callTool: async () => ({
  936. content: [{ type: "text", text: cuaActionReceipt() }],
  937. structuredContent: { diagnostic: "receipt-only" },
  938. }),
  939. }),
  940. [
  941. {
  942. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  943. toolName: "perform_action",
  944. inputSchema: { type: "object", properties: {} },
  945. },
  946. ],
  947. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  948. );
  949. const output = await registry
  950. .get("mcp__computer-use__perform_action")
  951. ?.handler({}, createToolContext());
  952. const entry = registry.get("mcp__computer-use__perform_action");
  953. const modelContent = entry?.formatModelContent?.(output);
  954. expect(output?.isError).not.toBe(true);
  955. expect(modelContent).toContain("Structured content:");
  956. expect(modelContent).toContain("receipt-only");
  957. expect(modelContent).not.toContain("refresh_required");
  958. });
  959. it("preserves producer possibly-sent receipts without inventing a post-state", async () => {
  960. const result = {
  961. content: [
  962. {
  963. type: "text" as const,
  964. text: JSON.stringify({
  965. message: "The action may have been sent; refresh first.",
  966. action_receipt: JSON.parse(
  967. cuaActionReceipt({
  968. dispatch_status: "possibly_sent",
  969. }),
  970. ).action_receipt,
  971. state: null,
  972. }),
  973. },
  974. ],
  975. };
  976. const registry = createToolRegistry();
  977. registerMcpTools(
  978. registry,
  979. createMockMcpPort({ callTool: async () => result }),
  980. [
  981. {
  982. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  983. toolName: "perform_action",
  984. inputSchema: { type: "object", properties: {} },
  985. },
  986. ],
  987. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  988. );
  989. const entry = registry.get("mcp__computer-use__perform_action");
  990. const output = await entry?.handler({}, createToolContext());
  991. expect(output).toBe(result);
  992. expect(entry?.formatModelContent?.(output)).toEqual(result.content[0].text);
  993. });
  994. it("preserves a large JSON-only result from an official CUA tool", async () => {
  995. const text = JSON.stringify(
  996. Array.from({ length: 160 }, (_, index) => ({
  997. bundle_id: `dev.example.application.${index}`,
  998. name: `Application ${index}`,
  999. pid: 10_000 + index,
  1000. })),
  1001. );
  1002. expect(text.length).toBeGreaterThan(1024);
  1003. const result = { content: [{ type: "text" as const, text }] };
  1004. const registry = createToolRegistry();
  1005. registerMcpTools(
  1006. registry,
  1007. createMockMcpPort({ callTool: async () => result }),
  1008. [
  1009. {
  1010. serverName: ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME,
  1011. toolName: "list_apps",
  1012. inputSchema: { type: "object", properties: {} },
  1013. },
  1014. ],
  1015. { officialCuaServerNames: new Set([ZCODE_CUA_OFFICIAL_MCP_SERVER_NAME]) },
  1016. );
  1017. const output = await registry
  1018. .get("mcp__computer-use__list_apps")
  1019. ?.handler({}, createToolContext());
  1020. expect(output).toBe(result);
  1021. });
  1022. it("persists the original explicit browser screenshot while compressing its model image", async () => {
  1023. const registry = createToolRegistry();
  1024. const originalImage = Buffer.alloc(MCP_IMAGE_INLINE_RAW_BYTES + 1, 7);
  1025. const compressedImage = Buffer.from("compressed-browser-screenshot");
  1026. const mcpPort = createMockMcpPort({
  1027. callTool: async () => ({
  1028. // node_repl 现在把 image 排在 text 之前(见 node-repl-host/src/result.ts),
  1029. // screenshot 下标因此直接是 content 下标。
  1030. content: [
  1031. {
  1032. type: "image",
  1033. data: originalImage.toString("base64"),
  1034. mimeType: "image/png",
  1035. },
  1036. { type: "text", text: "(no output)" },
  1037. ],
  1038. _meta: {
  1039. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0],
  1040. },
  1041. }),
  1042. });
  1043. const artifactWrites: Uint8Array[] = [];
  1044. const artifactStore: ToolArtifactStorePort = {
  1045. writeToolResultArtifact: async () => {
  1046. throw new Error("unexpected text artifact write");
  1047. },
  1048. writeToolResultBinaryArtifact: async (request) => {
  1049. artifactWrites.push(request.content);
  1050. return {
  1051. id: "explicit-browser-shot",
  1052. uri: "zcode-artifact://session/explicit-browser-shot",
  1053. path: "/tmp/explicit-browser-shot.png",
  1054. bytes: request.content.byteLength,
  1055. contentType: request.contentType,
  1056. createdAt: new Date("2026-07-20T00:00:00.000Z"),
  1057. };
  1058. },
  1059. readToolResultArtifact: async () => {
  1060. throw new Error("not used");
  1061. },
  1062. };
  1063. const prepareRequests: Parameters<ImageProcessorPort["prepareForModel"]>[0][] = [];
  1064. const imageProcessorPort: ImageProcessorPort = {
  1065. resizeToFit: async () => {
  1066. throw new Error("unexpected resizeToFit call");
  1067. },
  1068. prepareForModel: async (request) => {
  1069. prepareRequests.push(request);
  1070. return {
  1071. compressed: true,
  1072. data: compressedImage,
  1073. height: 900,
  1074. mediaType: "image/jpeg",
  1075. originalHeight: 3218,
  1076. originalSizeBytes: originalImage.byteLength,
  1077. originalWidth: 942,
  1078. resized: true,
  1079. strategy: "jpeg-quality",
  1080. transformedSizeBytes: compressedImage.byteLength,
  1081. width: 263,
  1082. };
  1083. },
  1084. };
  1085. registerMcpTools(registry, mcpPort, [
  1086. {
  1087. serverName: "node_repl",
  1088. toolName: "js",
  1089. inputSchema: { type: "object", properties: {} },
  1090. },
  1091. ]);
  1092. const entry = registry.get("mcp__node_repl__js");
  1093. const output = await entry?.handler(
  1094. {},
  1095. createToolContext({ artifactStore, imageProcessorPort }),
  1096. );
  1097. const modelContent = entry?.formatModelContent?.(output);
  1098. expect(prepareRequests).toHaveLength(1);
  1099. expect(prepareRequests[0]).toMatchObject({
  1100. maxBase64Bytes: MCP_IMAGE_INLINE_BASE64_BYTES,
  1101. maxDimension: 2000,
  1102. maxRawBytes: MCP_IMAGE_INLINE_RAW_BYTES,
  1103. mediaType: "image/png",
  1104. });
  1105. // artifact 提示文本必须排在 image 之后:它是为 browser screenshot 现场插入的,
  1106. // 插在 image 前会让 tool_result.content 重新变成 text-first,图又会被网关丢掉。
  1107. expect(modelContent).toEqual([
  1108. {
  1109. type: "image",
  1110. dataUrl: `data:image/jpeg;base64,${compressedImage.toString("base64")}`,
  1111. mediaType: "image/jpeg",
  1112. source: expect.objectContaining({
  1113. id: "mcp-image",
  1114. kind: "inline",
  1115. mimeType: "image/jpeg",
  1116. }),
  1117. },
  1118. {
  1119. type: "text",
  1120. text: "Browser screenshot saved to: /tmp/explicit-browser-shot.png",
  1121. },
  1122. { type: "text", text: "(no output)" },
  1123. ]);
  1124. expect(artifactWrites).toHaveLength(1);
  1125. expect(Buffer.from(artifactWrites[0] ?? [])).toEqual(originalImage);
  1126. expect(JSON.stringify(modelContent)).not.toContain(originalImage.toString("base64"));
  1127. });
  1128. it("does not persist ordinary nodeRepl.emitImage content without a screenshot marker", async () => {
  1129. const registry = createToolRegistry();
  1130. const writeToolResultBinaryArtifact = vi.fn(
  1131. async (
  1132. request: Parameters<NonNullable<ToolArtifactStorePort["writeToolResultBinaryArtifact"]>>[0],
  1133. ) => ({
  1134. id: "unexpected",
  1135. uri: "zcode-artifact://session/unexpected",
  1136. path: "/tmp/unexpected.png",
  1137. bytes: request.content.byteLength,
  1138. contentType: request.contentType,
  1139. createdAt: new Date("2026-07-20T00:00:00.000Z"),
  1140. }),
  1141. );
  1142. const artifactStore: ToolArtifactStorePort = {
  1143. writeToolResultArtifact: async () => {
  1144. throw new Error("not used");
  1145. },
  1146. writeToolResultBinaryArtifact,
  1147. readToolResultArtifact: async () => {
  1148. throw new Error("not used");
  1149. },
  1150. };
  1151. const mcpPort = createMockMcpPort({
  1152. callTool: async () => ({
  1153. content: [{ type: "image", data: "AQID", mimeType: "image/png" }],
  1154. }),
  1155. });
  1156. registerMcpTools(registry, mcpPort, [
  1157. {
  1158. serverName: "node_repl",
  1159. toolName: "js",
  1160. inputSchema: { type: "object", properties: {} },
  1161. },
  1162. ]);
  1163. const entry = registry.get("mcp__node_repl__js");
  1164. const output = await entry?.handler({}, createToolContext({ artifactStore }));
  1165. expect(writeToolResultBinaryArtifact).not.toHaveBeenCalled();
  1166. expect(entry?.formatModelContent?.(output)).toEqual([
  1167. expect.objectContaining({ type: "image", mediaType: "image/png" }),
  1168. ]);
  1169. });
  1170. it("falls back to the existing oversized-image policy when node_repl compression fails", async () => {
  1171. const registry = createToolRegistry();
  1172. const originalImage = Buffer.alloc(MCP_IMAGE_INLINE_RAW_BYTES + 1, 13);
  1173. const mcpPort = createMockMcpPort({
  1174. callTool: async () => ({
  1175. content: [
  1176. {
  1177. type: "image",
  1178. data: originalImage.toString("base64"),
  1179. mimeType: "image/png",
  1180. },
  1181. ],
  1182. }),
  1183. });
  1184. const imageProcessorPort: ImageProcessorPort = {
  1185. resizeToFit: async () => {
  1186. throw new Error("unexpected resizeToFit call");
  1187. },
  1188. prepareForModel: async () => {
  1189. throw new Error("decode failed");
  1190. },
  1191. };
  1192. registerMcpTools(registry, mcpPort, [
  1193. {
  1194. serverName: "node_repl",
  1195. toolName: "js",
  1196. inputSchema: { type: "object", properties: {} },
  1197. },
  1198. ]);
  1199. const entry = registry.get("mcp__node_repl__js");
  1200. const output = await entry?.handler({}, createToolContext({ imageProcessorPort }));
  1201. const modelContent = entry?.formatModelContent?.(output);
  1202. expect(modelContent).toContain("MCP image content omitted");
  1203. expect(modelContent).toContain("No artifact store is configured");
  1204. expect(JSON.stringify(modelContent)).not.toContain(originalImage.toString("base64"));
  1205. });
  1206. it("rejects node_repl compression output that still exceeds the inline budget", async () => {
  1207. const registry = createToolRegistry();
  1208. const originalImage = Buffer.alloc(MCP_IMAGE_INLINE_RAW_BYTES + 1, 17);
  1209. const mcpPort = createMockMcpPort({
  1210. callTool: async () => ({
  1211. content: [
  1212. {
  1213. type: "image",
  1214. data: originalImage.toString("base64"),
  1215. mimeType: "image/png",
  1216. },
  1217. ],
  1218. }),
  1219. });
  1220. const imageProcessorPort: ImageProcessorPort = {
  1221. resizeToFit: async () => {
  1222. throw new Error("unexpected resizeToFit call");
  1223. },
  1224. prepareForModel: async () => ({
  1225. compressed: true,
  1226. data: Buffer.alloc(MCP_IMAGE_INLINE_RAW_BYTES + 1, 19),
  1227. mediaType: "image/jpeg",
  1228. originalSizeBytes: originalImage.byteLength,
  1229. resized: false,
  1230. strategy: "jpeg-quality",
  1231. transformedSizeBytes: MCP_IMAGE_INLINE_RAW_BYTES + 1,
  1232. }),
  1233. };
  1234. registerMcpTools(registry, mcpPort, [
  1235. {
  1236. serverName: "node_repl",
  1237. toolName: "js",
  1238. inputSchema: { type: "object", properties: {} },
  1239. },
  1240. ]);
  1241. const entry = registry.get("mcp__node_repl__js");
  1242. const output = await entry?.handler({}, createToolContext({ imageProcessorPort }));
  1243. const modelContent = entry?.formatModelContent?.(output);
  1244. expect(modelContent).toContain("MCP image content omitted");
  1245. expect(modelContent).toContain("No artifact store is configured");
  1246. expect(JSON.stringify(modelContent)).not.toContain(originalImage.toString("base64"));
  1247. });
  1248. it("stores oversized MCP image content before projecting model-visible output", async () => {
  1249. const registry = createToolRegistry();
  1250. const originalImage = Buffer.alloc(MCP_IMAGE_INLINE_BASE64_BYTES, 7);
  1251. const largeBase64 = originalImage.toString("base64");
  1252. const mcpPort = createMockMcpPort({
  1253. callTool: async () => ({
  1254. content: [
  1255. { type: "text", text: '{"path":"screenshots/latest.png"}' },
  1256. { type: "image", data: largeBase64, mimeType: "image/png" },
  1257. ],
  1258. }),
  1259. });
  1260. const artifactWrites: Array<{
  1261. content: Buffer;
  1262. contentType: string;
  1263. extension?: string;
  1264. }> = [];
  1265. const artifactStore: ToolArtifactStorePort = {
  1266. writeToolResultArtifact: async (request) => {
  1267. throw new Error(`unexpected text artifact write: ${request.contentType}`);
  1268. },
  1269. writeToolResultBinaryArtifact: async (request) => {
  1270. const content = Buffer.from(request.content);
  1271. artifactWrites.push({
  1272. content,
  1273. contentType: request.contentType,
  1274. extension: request.extension,
  1275. });
  1276. return {
  1277. id: "artifact-large-image",
  1278. uri: "zcode-artifact://session/artifact-large-image",
  1279. path: "/tmp/mcp-image.png",
  1280. bytes: content.byteLength,
  1281. contentType: request.contentType,
  1282. createdAt: new Date("2026-06-10T00:00:00.000Z"),
  1283. };
  1284. },
  1285. readToolResultArtifact: async () => {
  1286. throw new Error("not used");
  1287. },
  1288. };
  1289. registerMcpTools(registry, mcpPort, [
  1290. {
  1291. serverName: "ios_simulator",
  1292. toolName: "ios_screenshot",
  1293. inputSchema: {
  1294. type: "object",
  1295. properties: {},
  1296. },
  1297. },
  1298. ]);
  1299. const entry = registry.get("mcp__ios_simulator__ios_screenshot");
  1300. const output = await entry?.handler({}, createToolContext({ artifactStore }));
  1301. const modelContent = entry?.formatModelContent?.(output);
  1302. expect(artifactWrites).toHaveLength(1);
  1303. expect(Buffer.byteLength(largeBase64, "utf8")).toBeGreaterThan(MCP_IMAGE_INLINE_BASE64_BYTES);
  1304. expect(artifactWrites[0]).toMatchObject({
  1305. contentType: "image/png",
  1306. extension: ".png",
  1307. });
  1308. expect(artifactWrites[0]?.content).toEqual(originalImage);
  1309. expect(modelContent).toContain("screenshots/latest.png");
  1310. expect(modelContent).toContain("/tmp/mcp-image.png");
  1311. expect(JSON.stringify(modelContent)).not.toContain(largeBase64);
  1312. });
  1313. it("falls back to text artifacts for oversized MCP images when binary artifacts are unsupported", async () => {
  1314. const registry = createToolRegistry();
  1315. const largeBase64 = Buffer.alloc(MCP_IMAGE_INLINE_BASE64_BYTES, 9).toString("base64");
  1316. const mcpPort = createMockMcpPort({
  1317. callTool: async () => ({
  1318. content: [{ type: "image", data: largeBase64, mimeType: "image/png" }],
  1319. }),
  1320. });
  1321. const artifactWrites: Array<{ content: string; contentType?: string }> = [];
  1322. const artifactStore: ToolArtifactStorePort = {
  1323. writeToolResultArtifact: async (request) => {
  1324. artifactWrites.push({
  1325. content: request.content,
  1326. contentType: request.contentType,
  1327. });
  1328. return {
  1329. id: "artifact-large-image",
  1330. uri: "zcode-artifact://session/artifact-large-image",
  1331. path: "/tmp/mcp-image.json",
  1332. bytes: Buffer.byteLength(request.content, "utf8"),
  1333. contentType: request.contentType ?? "application/json",
  1334. createdAt: new Date("2026-06-10T00:00:00.000Z"),
  1335. };
  1336. },
  1337. readToolResultArtifact: async () => {
  1338. throw new Error("not used");
  1339. },
  1340. };
  1341. registerMcpTools(registry, mcpPort, [
  1342. {
  1343. serverName: "ios_simulator",
  1344. toolName: "ios_screenshot",
  1345. inputSchema: {
  1346. type: "object",
  1347. properties: {},
  1348. },
  1349. },
  1350. ]);
  1351. const entry = registry.get("mcp__ios_simulator__ios_screenshot");
  1352. const output = await entry?.handler({}, createToolContext({ artifactStore }));
  1353. const modelContent = entry?.formatModelContent?.(output);
  1354. expect(artifactWrites).toHaveLength(1);
  1355. expect(artifactWrites[0]?.contentType).toBe("application/json");
  1356. expect(JSON.parse(artifactWrites[0]!.content)).toMatchObject({
  1357. dataUrl: `data:image/png;base64,${largeBase64}`,
  1358. inlineLimitBytes: MCP_IMAGE_INLINE_BASE64_BYTES,
  1359. mimeType: "image/png",
  1360. serverName: "ios_simulator",
  1361. toolName: "ios_screenshot",
  1362. type: "mcp-image-artifact",
  1363. });
  1364. expect(modelContent).toContain("/tmp/mcp-image.json");
  1365. expect(JSON.stringify(modelContent)).not.toContain(largeBase64);
  1366. });
  1367. it("omits oversized MCP image content when artifact storage is unavailable", async () => {
  1368. const registry = createToolRegistry();
  1369. const largeBase64 = Buffer.alloc(MCP_IMAGE_INLINE_BASE64_BYTES, 11).toString("base64");
  1370. const mcpPort = createMockMcpPort({
  1371. callTool: async () => ({
  1372. content: [{ type: "image", data: largeBase64, mimeType: "image/png" }],
  1373. }),
  1374. });
  1375. registerMcpTools(registry, mcpPort, [
  1376. {
  1377. serverName: "ios_simulator",
  1378. toolName: "ios_screenshot",
  1379. inputSchema: {
  1380. type: "object",
  1381. properties: {},
  1382. },
  1383. },
  1384. ]);
  1385. const entry = registry.get("mcp__ios_simulator__ios_screenshot");
  1386. const output = await entry?.handler({}, createToolContext());
  1387. const modelContent = entry?.formatModelContent?.(output);
  1388. expect(modelContent).toContain("MCP image content omitted");
  1389. expect(modelContent).toContain("No artifact store is configured");
  1390. expect(JSON.stringify(modelContent)).not.toContain(largeBase64);
  1391. });
  1392. });
  1393. function createMockMcpPort(overrides: Partial<McpPort> = {}): McpPort {
  1394. return {
  1395. connectConfiguredServers: async () => ({ statuses: {}, tools: [] }),
  1396. connectServer: async () => ({
  1397. status: "connected",
  1398. transport: "stdio",
  1399. toolCount: 1,
  1400. updatedAt: "now",
  1401. }),
  1402. disconnectServer: async () => undefined,
  1403. status: async () => ({}),
  1404. listTools: async () => [],
  1405. callTool: async () => ({ content: [] }),
  1406. close: async () => {},
  1407. ...overrides,
  1408. };
  1409. }
  1410. function createToolContext(
  1411. overrides: Partial<
  1412. Pick<ToolExecutionContext, "artifactStore" | "imageProcessorPort" | "runtimeScope">
  1413. > = {},
  1414. ): ToolExecutionContext {
  1415. return {
  1416. abortSignal: new AbortController().signal,
  1417. sessionId: createSessionId("mcp-tool-bridge"),
  1418. toolCallId: "tool-test",
  1419. traceId: "trace-test" as never,
  1420. workingDirectory: "/tmp/project",
  1421. workspaceRoot: "/tmp/project",
  1422. ...overrides,
  1423. };
  1424. }