mcp-server.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. import { randomUUID } from "node:crypto";
  2. import { existsSync, readFileSync } from "node:fs";
  3. import { createServer } from "node:net";
  4. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  5. import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
  6. import { tmpdir } from "node:os";
  7. import { join, resolve } from "node:path";
  8. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  9. import {
  10. ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY,
  11. ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY,
  12. ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY,
  13. ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY,
  14. } from "@zcode/contracts";
  15. import { CUA_APP_ASSOCIATIONS_META_KEY } from "@zcode/zcode-cua/host-display-contract";
  16. import {
  17. captureComputerUseRuntimeFromEnvironment,
  18. createInProcessNodeReplExecutor,
  19. createNodeReplMcpRuntime,
  20. main,
  21. type NodeReplMcpRuntime,
  22. } from "../src/server.js";
  23. import { toMcpRunResult } from "../src/result.js";
  24. import type { NodeReplCallFacts } from "../src/call-ledger/contract.js";
  25. /** 主线程账本里记下的可信事实(20-node-repl-call-ledger.md「结果组装」)。 */
  26. function ledgerFacts(facts: Partial<NodeReplCallFacts> = {}): NodeReplCallFacts {
  27. return { cuaApps: [], browserScreenshots: [], browserUse: false, computerUse: false, ...facts };
  28. }
  29. import {
  30. NODE_REPL_DEFAULT_TIMEOUT_MS,
  31. NODE_REPL_SERVER_INSTRUCTIONS,
  32. JS_TOOL_DESCRIPTION,
  33. } from "../src/tool-contract.js";
  34. describe("node_repl MCP server", () => {
  35. const packageVersion = (
  36. JSON.parse(readFileSync(resolve(import.meta.dirname, "../package.json"), "utf8")) as {
  37. version: string;
  38. }
  39. ).version;
  40. let client: Client;
  41. let runtime: NodeReplMcpRuntime;
  42. const requestMeta = (
  43. sessionId: string,
  44. runtimeScope: "main" | "subagent" = "main",
  45. turnId = "turn-1",
  46. ) => ({
  47. "com.zcode/request-context": {
  48. runtime_scope: runtimeScope,
  49. session_id: sessionId,
  50. turn_id: turnId,
  51. },
  52. });
  53. beforeEach(async () => {
  54. runtime = createNodeReplMcpRuntime({ executeJs: createInProcessNodeReplExecutor() });
  55. client = new Client({ name: "node-repl-test", version: "0.1.0" });
  56. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  57. await runtime.server.connect(serverTransport);
  58. await client.connect(clientTransport);
  59. });
  60. afterEach(async () => {
  61. await client.close();
  62. runtime.dispose();
  63. });
  64. it("exports the main entrypoint required by the packaged plugin host", () => {
  65. expect(main).toBeTypeOf("function");
  66. expect(client.getServerVersion()).toEqual({
  67. name: "node_repl",
  68. version: packageVersion,
  69. });
  70. });
  71. it("captures Computer Use credentials before the plugin host restores its environment", async () => {
  72. const capturedRuntime = captureComputerUseRuntimeFromEnvironment({
  73. ZCODE_CUA_PERMISSION_BROKER_SOCKET: "/tmp/deferred-cua.sock",
  74. ZCODE_CUA_PERMISSION_BROKER_TOKEN: "deferred-cua-token",
  75. });
  76. expect(capturedRuntime).toBeDefined();
  77. let forwardedBroker: unknown;
  78. const deferredRuntime = createNodeReplMcpRuntime({
  79. cuaRuntime: capturedRuntime,
  80. executeJs: async (input) => {
  81. forwardedBroker = input.cuaBroker;
  82. return { logs: "", result: "ok" };
  83. },
  84. });
  85. const deferredClient = new Client({ name: "deferred-cua-test", version: "0.1.0" });
  86. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  87. await deferredRuntime.server.connect(serverTransport);
  88. await deferredClient.connect(clientTransport);
  89. try {
  90. await deferredClient.callTool({
  91. name: "js",
  92. arguments: { code: "1", title: "验证 Computer Use bridge" },
  93. _meta: requestMeta("deferred-cua-session"),
  94. });
  95. expect(forwardedBroker).toMatchObject({
  96. socketPath: expect.any(String),
  97. token: expect.any(String),
  98. });
  99. } finally {
  100. await deferredClient.close();
  101. deferredRuntime.dispose();
  102. }
  103. });
  104. it("requires user-facing titles in the model schema while preserving legacy runtime input", async () => {
  105. const { tools } = await client.listTools();
  106. expect(tools.map((tool) => tool.name).sort()).toEqual(["js"]);
  107. const js = tools.find((tool) => tool.name === "js");
  108. expect(js?.inputSchema).toMatchObject({
  109. additionalProperties: false,
  110. required: ["code", "title"],
  111. type: "object",
  112. });
  113. expect(Object.keys(js?.inputSchema.properties ?? {}).sort()).toEqual([
  114. "code",
  115. "timeout_ms",
  116. "title",
  117. ]);
  118. expect(js?.inputSchema.properties?.code).toMatchObject({
  119. description: "JavaScript code to execute in the Node REPL session",
  120. });
  121. expect(js?.inputSchema.properties?.timeout_ms).toMatchObject({
  122. description: expect.stringContaining(
  123. "You MUST provide this when the code is expected to run longer than 30000 ms",
  124. ),
  125. });
  126. expect(js?.description).toContain("required `title`");
  127. expect(NODE_REPL_DEFAULT_TIMEOUT_MS).toBe(60_000);
  128. expect(NODE_REPL_SERVER_INSTRUCTIONS).toContain("default to a 60000 ms timeout");
  129. expect(js?.description).toContain("after 60000 ms");
  130. expect(js?.description).toContain(
  131. "you MUST set `timeout_ms` to at least the estimated total runtime plus 15000 ms",
  132. );
  133. expect(js?.description).not.toContain("after 30000 ms");
  134. const legacyCall = await client.callTool({
  135. name: "js",
  136. arguments: { code: '"legacy";' },
  137. });
  138. expect(legacyCall.isError).not.toBe(true);
  139. expect(legacyCall.content).toContainEqual(
  140. expect.objectContaining({ type: "text", text: "=> legacy" }),
  141. );
  142. });
  143. it("states node_repl is unsandboxed while forbidding non-skill work", async () => {
  144. const { tools } = await client.listTools();
  145. const js = tools.find((tool) => tool.name === "js");
  146. for (const text of [NODE_REPL_SERVER_INSTRUCTIONS, js?.description ?? ""]) {
  147. expect(text).toMatch(/^Browser Use and Computer Use only\./);
  148. expect(text).toContain("runs unsandboxed with the ZCode agent's privileges");
  149. expect(text).toContain("skips Bash's dangerous-command approval");
  150. expect(text).toContain("never use it for shell, file, package inspection, or data processing work");
  151. expect(text).not.toContain("start processes");
  152. expect(text).not.toContain("Import only");
  153. expect(text).not.toContain("bare package specifiers");
  154. expect(text).not.toContain("by absolute `file://` URL");
  155. }
  156. });
  157. it("keeps Browser Use and Computer Use usage rules in their skills", () => {
  158. expect(JS_TOOL_DESCRIPTION).toContain("`nodeRepl.write(value)`");
  159. expect(JS_TOOL_DESCRIPTION).toContain("`await nodeRepl.emitImage(imageLike)`");
  160. expect(JS_TOOL_DESCRIPTION).toContain(
  161. "Bootstrap the requested official capability in every call.",
  162. );
  163. for (const text of [NODE_REPL_SERVER_INSTRUCTIONS, JS_TOOL_DESCRIPTION]) {
  164. for (const skillRule of [
  165. "get_app_state",
  166. "state_id",
  167. "state.text",
  168. "console.log",
  169. "action_sent",
  170. "screenshot_display",
  171. "raster",
  172. "same cell",
  173. "earlier call",
  174. "BrowserControl",
  175. "nodeRepl.cwd",
  176. "setResponseMeta",
  177. "open_application",
  178. ]) {
  179. expect(text).not.toContain(skillRule);
  180. }
  181. }
  182. });
  183. it("creates a fresh kernel for every js call", async () => {
  184. const first = await client.callTool({
  185. name: "js",
  186. arguments: {
  187. code: "globalThis.counter = 41; counter;",
  188. title: "初始化计数",
  189. },
  190. _meta: requestMeta("session-1"),
  191. });
  192. expect(first.content).toContainEqual(expect.objectContaining({ type: "text", text: "=> 41" }));
  193. const second = await client.callTool({
  194. name: "js",
  195. arguments: {
  196. code: "({ counterType: typeof globalThis.counter, session: nodeRepl.requestMeta.session_id });",
  197. },
  198. _meta: requestMeta("session-1", "main", "turn-2"),
  199. });
  200. expect(second.content).toContainEqual(
  201. expect.objectContaining({
  202. type: "text",
  203. text: expect.stringContaining('"counterType": "undefined"'),
  204. }),
  205. );
  206. expect(second.content).toContainEqual(
  207. expect.objectContaining({
  208. type: "text",
  209. text: expect.stringContaining('"session": "session-1"'),
  210. }),
  211. );
  212. });
  213. it("exposes js as the only node_repl tool and rejects the two retired ones", async () => {
  214. // 修复原因:2026-09-18 下架 js_reset 与 js_add_node_module_dir,node_repl 只留 js。
  215. // js_reset 自 fresh-kernel 改造起就是固定返回成功的空操作,而"永不失败"会让弱模型连续
  216. // 重复调用它(工单 ZCT-2100503886992535552:155 次连调、19 分钟 4837 万输入 token 直到 429)。
  217. // js_add_node_module_dir 则是把宿主职责推给模型——模型无法自行知道该传哪个 node_modules,
  218. // 能告诉它的只有 skill 文档,而文档知道的路径宿主自己就能注入;实测两者调用量均为 0。
  219. // 必须同时守住两件事:不再出现在模型工具面,且调用时明确失败而非静默成功——
  220. // Tool not found 才是模型换策略所需的信号。
  221. const { tools } = await client.listTools();
  222. expect(tools.map((tool) => tool.name)).toEqual(["js"]);
  223. for (const retired of ["js_reset", "js_add_node_module_dir"]) {
  224. await expect(
  225. client.callTool({ name: retired, arguments: {}, _meta: requestMeta("session-1") }),
  226. ).rejects.toThrow(`Tool ${retired} not found`);
  227. }
  228. });
  229. it("supports top-level await import syntax", async () => {
  230. const result = await client.callTool({
  231. name: "js",
  232. arguments: {
  233. code: 'const pathModule = await import("node:path"); pathModule.sep;',
  234. },
  235. _meta: requestMeta("session-1"),
  236. });
  237. expect(result.isError).not.toBe(true);
  238. expect(result.content).toContainEqual(
  239. expect.objectContaining({
  240. type: "text",
  241. text: expect.stringMatching(/^=> [\\/]$/),
  242. }),
  243. );
  244. });
  245. it("ignores spoofed top-level session metadata in favor of the host namespace", async () => {
  246. const result = await client.callTool({
  247. name: "js",
  248. arguments: { code: "nodeRepl.requestMeta.session_id;" },
  249. _meta: {
  250. session_id: "spoofed-session",
  251. ...requestMeta("trusted-session"),
  252. },
  253. });
  254. expect(result.isError).not.toBe(true);
  255. expect(result.content).toContainEqual(
  256. expect.objectContaining({ type: "text", text: "=> trusted-session" }),
  257. );
  258. });
  259. it("keeps generic JavaScript available for subagent calls", async () => {
  260. const result = await client.callTool({
  261. name: "js",
  262. arguments: { code: "21 * 2;" },
  263. _meta: requestMeta("subagent-session", "subagent"),
  264. });
  265. expect(result.isError).not.toBe(true);
  266. expect(result.content).toContainEqual(expect.objectContaining({ type: "text", text: "=> 42" }));
  267. });
  268. it("returns a structured error without suppressing the standard MCP error marker", async () => {
  269. const result = await client.callTool({
  270. name: "js",
  271. arguments: {
  272. code: [
  273. 'nodeRepl.write("internal diagnostic that must not reach the model");',
  274. "const error = new Error(\"browser tab 'iab-tab:test' returned an invalid viewport\");",
  275. 'error.name = "BrowserCommandError";',
  276. "throw error;",
  277. ].join("\n"),
  278. },
  279. });
  280. expect(result.isError).toBe(true);
  281. expect(result.content).toEqual([
  282. {
  283. type: "text",
  284. text: "browser tab 'iab-tab:test' returned an invalid viewport",
  285. },
  286. ]);
  287. expect(result._meta).toBeUndefined();
  288. expect(JSON.stringify(result)).not.toContain("BrowserCommandError");
  289. expect(JSON.stringify(result)).not.toContain("internal diagnostic");
  290. expect(JSON.stringify(result)).not.toContain(" at ");
  291. });
  292. it("projects images plus response metadata from a fresh call", async () => {
  293. const output = await client.callTool({
  294. name: "js",
  295. arguments: {
  296. code: 'nodeRepl.setResponseMeta({ browser_use: { url: "https://example.test" } }); await nodeRepl.emitImage({ base64: "AAAA", mimeType: "image/png" }); "done";',
  297. },
  298. _meta: requestMeta("session-1"),
  299. });
  300. expect(output.content).toContainEqual(
  301. expect.objectContaining({
  302. type: "image",
  303. data: "AAAA",
  304. mimeType: "image/png",
  305. }),
  306. );
  307. expect(output._meta).toEqual({
  308. browser_use: { url: "https://example.test" },
  309. "zcode/nodeReplEmittedImage": true,
  310. });
  311. });
  312. it("carries no copy of the Computer Use assets", () => {
  313. // 宿主与两个能力插件独立之后,CUA 的 SDK 与文档只有一份,属于 computer-use 插件;
  314. // 宿主按 ZCODE_CUA_PLUGIN_ROOT 去取。2026-09-11 之前 browser-use 各存一份手工副本,
  315. // 其中文档那份悄悄停在重构前的 API,兜底路径会把它发给模型。
  316. for (const relative of [
  317. "../../browser-use-plugin/scripts/computer-use-client.mjs",
  318. "../../browser-use-plugin/docs/computer-use.md",
  319. "../scripts/computer-use-client.mjs",
  320. "../docs/computer-use.md",
  321. ]) {
  322. expect(
  323. existsSync(resolve(import.meta.dirname, relative)),
  324. `${relative} must not exist: the canonical copy lives in zcode-cua-plugin`,
  325. ).toBe(false);
  326. }
  327. expect(
  328. existsSync(
  329. resolve(import.meta.dirname, "../../zcode-cua-plugin/scripts/computer-use-client.mjs"),
  330. ),
  331. ).toBe(true);
  332. });
  333. it("orders image blocks before the text block so image-first providers keep the raster", () => {
  334. const result = toMcpRunResult({
  335. logs: "log line",
  336. result: "done",
  337. images: [
  338. { base64: "AQID", mimeType: "image/png" },
  339. { base64: "BAUG", mimeType: "image/jpeg" },
  340. ],
  341. });
  342. expect(result.content).toEqual([
  343. { type: "image", data: "AQID", mimeType: "image/png" },
  344. { type: "image", data: "BAUG", mimeType: "image/jpeg" },
  345. { type: "text", text: "log line\n=> done" },
  346. ]);
  347. });
  348. it("drops a byte-identical emitImage duplicate so a redundant call cannot cost the whole frame", () => {
  349. // Bug 原因(2026-09-11 真机):模型写
  350. // const shot = await app.getScreenshot(); await nodeRepl.emitImage(shot);
  351. // getScreenshot 已经经 emitStructuredResult 投过「图 + 权威」,于是结果里两张图,
  352. // exact-raster 门按「每个结果只允许一张最终 raster」把整帧原子否决。
  353. //
  354. // 门不能放宽(frame_id 绑定像素坐标),但逐字节相同的那份是纯冗余,丢掉即可,
  355. // 冗余调用不再连累整帧被否决。
  356. const authority = JSON.stringify({
  357. image_ref: { actionable: true, frame_id: "frame-1", height: 2, width: 4 },
  358. });
  359. const result = toMcpRunResult({
  360. structuredResults: [
  361. {
  362. content: [
  363. { type: "image", data: "AQID", mimeType: "image/png" },
  364. { type: "text", text: authority },
  365. ],
  366. },
  367. ],
  368. images: [{ base64: "AQID", mimeType: "image/png" }],
  369. } as never);
  370. const images = result.content.filter((block) => block.type === "image");
  371. expect(images).toEqual([{ type: "image", data: "AQID", mimeType: "image/png" }]);
  372. // 权威必须紧跟在存活的那张图后面 —— 原子对不能被去重打散。
  373. expect(result.content[0]?.type).toBe("image");
  374. expect((result.content[1] as { text?: string }).text).toBe(authority);
  375. });
  376. it("keeps a different model image so a genuine two-raster result still reaches the gate", () => {
  377. // 字节不同就不是冗余:那是真的两张 raster,判定权仍属完整性门,宿主不得代它放行。
  378. const result = toMcpRunResult({
  379. structuredResults: [{ content: [{ type: "image", data: "AQID", mimeType: "image/png" }] }],
  380. images: [{ base64: "ZZZZ", mimeType: "image/png" }],
  381. } as never);
  382. expect(result.content.filter((block) => block.type === "image")).toHaveLength(2);
  383. });
  384. it("flattens an SDK CallToolResult so CUA action-state and image references stay top-level", () => {
  385. const embedded = {
  386. content: [
  387. { type: "text", text: "Clicked Save." },
  388. {
  389. type: "text",
  390. text: JSON.stringify({
  391. schema_version: "zcode-cua-action-outcome-v1",
  392. action_sent: true,
  393. verification_status: "verified",
  394. state_available: true,
  395. }),
  396. },
  397. { type: "text", text: '{"image_ref":"frame-1"}' },
  398. ],
  399. structuredContent: { action_state: { state_id: "state-2" } },
  400. };
  401. const result = toMcpRunResult({
  402. logs: "",
  403. result: `=> ${JSON.stringify(embedded)}`,
  404. images: [{ base64: "AQID", mimeType: "image/png" }],
  405. });
  406. expect(result.content).toEqual([
  407. { type: "image", data: "AQID", mimeType: "image/png" },
  408. ...embedded.content,
  409. ]);
  410. expect(result).toMatchObject({ structuredContent: embedded.structuredContent });
  411. });
  412. it("keeps an SDK result authoritative when the model logs its returned value", () => {
  413. const structured = {
  414. content: [
  415. { type: "image", data: "AQID", mimeType: "image/png" },
  416. { type: "text", text: '{"image_ref":"frame-2"}' },
  417. ],
  418. structuredContent: { state_id: "state-2" },
  419. _meta: { "zcode-cua": "official" },
  420. };
  421. const result = toMcpRunResult({
  422. logs: `console output\n${JSON.stringify({ content: structured.content })}`,
  423. result: JSON.stringify({ content: structured.content }),
  424. structuredResults: [structured],
  425. });
  426. expect(result.content).toEqual([
  427. ...structured.content,
  428. {
  429. type: "text",
  430. text: 'console output\n{"content":[{"type":"image","data":"AQID","mimeType":"image/png"},{"type":"text","text":"{\\"image_ref\\":\\"frame-2\\"}"}]}',
  431. },
  432. ]);
  433. expect(result).toMatchObject({
  434. structuredContent: structured.structuredContent,
  435. _meta: structured._meta,
  436. });
  437. });
  438. it("keeps CUA sideband metadata without adding a legacy action text block", () => {
  439. const result = toMcpRunResult({
  440. logs: "state_id=s-2\nelements (1):",
  441. result: undefined,
  442. structuredResults: [
  443. {
  444. content: [],
  445. _meta: { "zcode.cua/target-app-display-v1": { pid: 7 } },
  446. },
  447. ],
  448. });
  449. expect(result.content).toEqual([{ type: "text", text: "state_id=s-2\nelements (1):" }]);
  450. expect(result._meta).toMatchObject({
  451. "zcode.cua/target-app-display-v1": { pid: 7 },
  452. });
  453. });
  454. it("keeps the single text block when no image is emitted", () => {
  455. expect(toMcpRunResult({ logs: "", result: undefined }).content).toEqual([
  456. { type: "text", text: "(no output)" },
  457. ]);
  458. });
  459. it("projects browser screenshot indices from the ledger and removes spoofed metadata", () => {
  460. const screenshot = toMcpRunResult(
  461. { logs: "", images: [{ base64: "AQID", mimeType: "image/png" }] },
  462. ledgerFacts({ browserScreenshots: [{ base64: "AQID", mimeType: "image/png" }] }),
  463. );
  464. // image 现在从 content[0] 开始,image 下标与 content 下标一致,不再有 +1 偏移。
  465. expect(screenshot.content[0]).toEqual({
  466. type: "image",
  467. data: "AQID",
  468. mimeType: "image/png",
  469. });
  470. expect(screenshot._meta).toMatchObject({
  471. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0],
  472. });
  473. const spoofed = toMcpRunResult({
  474. logs: "",
  475. images: [{ base64: "BAUG", mimeType: "image/png" }],
  476. responseMeta: {
  477. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [1],
  478. },
  479. });
  480. expect(spoofed._meta).not.toHaveProperty(ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY);
  481. // Worker 结果消息里的下标可以被 cell 冒充(MR !3207 评审 CR-01),账本里没有截图时一律不采信。
  482. const forgedRun = toMcpRunResult(
  483. {
  484. logs: "",
  485. images: [{ base64: "BAUG", mimeType: "image/png" }],
  486. browserScreenshotImageIndices: [0],
  487. },
  488. ledgerFacts(),
  489. );
  490. expect(forgedRun._meta).not.toHaveProperty(ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY);
  491. });
  492. it("maps browser screenshot metadata to final content indices after ordering images", () => {
  493. const result = toMcpRunResult(
  494. {
  495. logs: "cell output",
  496. structuredResults: [
  497. {
  498. content: [
  499. { type: "text", text: "observation" },
  500. { type: "image", data: "OTHER", mimeType: "image/png" },
  501. ],
  502. },
  503. ],
  504. images: [{ base64: "BROWSER", mimeType: "image/png" }],
  505. },
  506. ledgerFacts({ browserScreenshots: [{ base64: "BROWSER", mimeType: "image/png" }] }),
  507. );
  508. expect(result.content.map((block) => block.type)).toEqual(["image", "image", "text", "text"]);
  509. expect(result._meta?.[ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]).toEqual([1]);
  510. });
  511. it("projects the CUA app identity recorded in the ledger and drops the sandbox-forgeable key", () => {
  512. // `nodeRepl.setResponseMeta` / `nodeRepl.emitStructuredResult` 都挂在模型可见的 sandbox
  513. // globals 上,所以 producer 键经这两条通道到达时不可信 —— 模型能让工具卡声称自己操作了
  514. // 别的应用。可信事实只来自主线程 CUA broker 记进账本的身份。
  515. const trusted = toMcpRunResult(
  516. {
  517. logs: "",
  518. responseMeta: {
  519. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  520. schemaVersion: 1,
  521. primary: { appKey: "darwin:com.apple.systempreferences", displayName: "System Settings" },
  522. },
  523. },
  524. },
  525. ledgerFacts({ cuaApps: [{ appKey: "darwin:com.apple.notes", displayName: "Notes" }] }),
  526. );
  527. expect(trusted._meta).toMatchObject({
  528. [ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY]: {
  529. appKey: "darwin:com.apple.notes",
  530. displayName: "Notes",
  531. },
  532. });
  533. // 伪造的 producer 键必须整条消失,不能与可信键并存后被下游误取。
  534. expect(trusted._meta).not.toHaveProperty(CUA_APP_ASSOCIATIONS_META_KEY);
  535. // 没有可信记录时,光靠沙箱伪造拿不到任何身份。
  536. const forgedOnly = toMcpRunResult({
  537. logs: "",
  538. responseMeta: {
  539. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  540. schemaVersion: 1,
  541. primary: { appKey: "darwin:com.apple.notes" },
  542. },
  543. },
  544. } as never);
  545. expect(forgedOnly._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY);
  546. expect(forgedOnly._meta ?? {}).not.toHaveProperty(CUA_APP_ASSOCIATIONS_META_KEY);
  547. // Worker 结果消息里的 cuaApp 可以被 cell 冒充(MR !3207 评审 CR-01),不采信。
  548. const forgedRun = toMcpRunResult(
  549. { logs: "", cuaApp: { appKey: "darwin:com.apple.notes" } },
  550. ledgerFacts(),
  551. );
  552. expect(forgedRun._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY);
  553. });
  554. // 会话能力标签的两个 key 只按账本写(session-features-header.md「BUA/CUA 标签的补充规则」)。
  555. it("writes the runtime-call keys only from the ledger and drops copies the cell writes", () => {
  556. const forged = {
  557. [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true,
  558. [ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY]: true,
  559. };
  560. // 口径是真实尝试:cell 以错误结束也写。
  561. const failed = toMcpRunResult(
  562. { logs: "", error: { name: "Error", message: "boom" } },
  563. ledgerFacts({ browserUse: true, computerUse: true }),
  564. );
  565. expect(failed.isError).toBe(true);
  566. expect(failed._meta).toMatchObject(forged);
  567. const browserOnly = toMcpRunResult(
  568. { logs: "", responseMeta: forged },
  569. ledgerFacts({ browserUse: true }),
  570. );
  571. expect(browserOnly._meta).toMatchObject({ [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true });
  572. expect(browserOnly._meta).not.toHaveProperty(ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY);
  573. // sandbox 通道写入的同名 key、Worker 结果消息里冒充的字段(MR !3207 评审 CR-01)一律不采信。
  574. for (const run of [
  575. { logs: "", responseMeta: forged },
  576. {
  577. logs: "",
  578. result: JSON.stringify({ content: [{ type: "text", text: "x" }], _meta: forged }),
  579. },
  580. { logs: "", browserUse: true, computerUse: true },
  581. ]) {
  582. const result = toMcpRunResult(run as never, ledgerFacts());
  583. expect(result._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY);
  584. expect(result._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY);
  585. }
  586. });
  587. it("maps screenshot indices to their real content positions when only some images are screenshots", () => {
  588. const result = toMcpRunResult({
  589. logs: "",
  590. images: [
  591. { base64: "AAAA", mimeType: "image/png" },
  592. { base64: "BBBB", mimeType: "image/png" },
  593. { base64: "CCCC", mimeType: "image/png" },
  594. ],
  595. }, ledgerFacts({
  596. browserScreenshots: [
  597. { base64: "AAAA", mimeType: "image/png" },
  598. { base64: "CCCC", mimeType: "image/png" },
  599. ],
  600. }));
  601. expect(result._meta).toMatchObject({
  602. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0, 2],
  603. });
  604. // 每个声明的下标都必须真的指向 content 里的 image block(越界或指到 text 都会让原图落盘错位)。
  605. for (const index of [0, 2]) {
  606. expect(result.content[index]?.type).toBe("image");
  607. }
  608. expect(result.content[1]).toEqual({ type: "image", data: "BBBB", mimeType: "image/png" });
  609. });
  610. it("derives screenshot indices from what the browser proxy saw, end to end", async () => {
  611. // 真实 MCP server + 浏览器代理 broker + 假的上游浏览器 broker:可信的截图下标只来自代理在
  612. // 主线程记下的截图(20-node-repl-call-ledger.md「结果组装」)。
  613. const upstreamPath =
  614. process.platform === "win32"
  615. ? `\\\\.\\pipe\\zcode-ledger-e2e-${randomUUID()}`
  616. : join(tmpdir(), `zle-${randomUUID()}.sock`);
  617. const upstreamRequests: Array<Record<string, unknown>> = [];
  618. const upstream = createServer((socket) => {
  619. let buffer = "";
  620. socket.on("data", (chunk) => {
  621. buffer += chunk.toString("utf8");
  622. const newline = buffer.indexOf("\n");
  623. if (newline < 0) return;
  624. const request = JSON.parse(buffer.slice(0, newline)) as Record<string, unknown>;
  625. upstreamRequests.push(request);
  626. socket.end(
  627. `${JSON.stringify({
  628. id: request.id,
  629. ok: true,
  630. result: { ok: true, elapsedMs: 1, image: { base64: "AQID", mimeType: "image/png" } },
  631. })}\n`,
  632. );
  633. });
  634. });
  635. await new Promise<void>((resolveListen) => upstream.listen(upstreamPath, resolveListen));
  636. const browserRuntime = createNodeReplMcpRuntime({
  637. executeJs: createInProcessNodeReplExecutor(),
  638. browserBrokerUpstream: { socketPath: upstreamPath, token: "u".repeat(64) },
  639. });
  640. const browserClient = new Client({ name: "node-repl-ledger-e2e", version: "0.1.0" });
  641. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  642. await browserRuntime.server.connect(serverTransport);
  643. await browserClient.connect(clientTransport);
  644. try {
  645. const result = await browserClient.callTool({
  646. name: "js",
  647. arguments: {
  648. code: [
  649. 'const bridge = globalThis[Symbol.for("zcode.node-repl.browser-control-bridge")];',
  650. 'const shot = await bridge.execute("browser-1", 1, { method: "screenshot" });',
  651. "await nodeRepl.emitImage(shot.image);",
  652. '"shot";',
  653. ].join("\n"),
  654. },
  655. _meta: requestMeta("ledger-session"),
  656. });
  657. expect(result.content).toEqual([
  658. { type: "image", data: "AQID", mimeType: "image/png" },
  659. { type: "text", text: "=> shot" },
  660. ]);
  661. expect(result._meta).toMatchObject({
  662. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0],
  663. });
  664. // 上游收到的是上游 token 与本次调用来自 core 的会话信息。
  665. expect(upstreamRequests).toHaveLength(1);
  666. expect(upstreamRequests[0]).toMatchObject({
  667. op: "execute",
  668. token: "u".repeat(64),
  669. sessionId: "ledger-session",
  670. runtimeScope: "main",
  671. turnId: "turn-1",
  672. });
  673. } finally {
  674. await browserClient.close();
  675. browserRuntime.dispose();
  676. await new Promise<void>((resolveClose) => upstream.close(() => resolveClose()));
  677. if (process.platform !== "win32") await rm(upstreamPath, { force: true });
  678. }
  679. });
  680. it("marks runtime calls that reach the real brokers, end to end, and nothing else", async () => {
  681. // 真实 MCP server + 两个 broker:浏览器上游拒绝命令、CUA runtime 抛错,cell 也都接住了错误;
  682. // 口径是真实尝试,两个 key 照样写出(session-features-header.md「BUA/CUA 标签的补充规则」)。
  683. const upstreamPath =
  684. process.platform === "win32"
  685. ? `\\\\.\\pipe\\zcode-runtime-use-e2e-${randomUUID()}`
  686. : join(tmpdir(), `zru-${randomUUID()}.sock`);
  687. const upstream = createServer((socket) => {
  688. let buffer = "";
  689. socket.on("data", (chunk) => {
  690. buffer += chunk.toString("utf8");
  691. const newline = buffer.indexOf("\n");
  692. if (newline < 0) return;
  693. const request = JSON.parse(buffer.slice(0, newline)) as { id?: unknown };
  694. const response = { id: request.id, ok: false, error: "Browser is not connected" };
  695. socket.end(`${JSON.stringify(response)}\n`);
  696. });
  697. });
  698. await new Promise<void>((resolveListen) => upstream.listen(upstreamPath, resolveListen));
  699. let cuaExecuted = 0;
  700. const useRuntime = createNodeReplMcpRuntime({
  701. executeJs: createInProcessNodeReplExecutor(),
  702. browserBrokerUpstream: { socketPath: upstreamPath, token: "u".repeat(64) },
  703. cuaRuntime: {
  704. execute: async () => {
  705. cuaExecuted += 1;
  706. throw new Error("Computer Use Helper is not running");
  707. },
  708. closeSession: async () => undefined,
  709. dispose: async () => undefined,
  710. },
  711. });
  712. const useClient = new Client({ name: "node-repl-runtime-use-e2e", version: "0.1.0" });
  713. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  714. await useRuntime.server.connect(serverTransport);
  715. await useClient.connect(clientTransport);
  716. const forged = JSON.stringify({
  717. [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true,
  718. [ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY]: true,
  719. });
  720. // CUA broker 要求 workspace 信息,缺了会在调用 runtime 之前拒绝。
  721. const callMeta = {
  722. "com.zcode/request-context": {
  723. ...requestMeta("runtime-use-session")["com.zcode/request-context"],
  724. workspace_path: "/workspace",
  725. },
  726. };
  727. try {
  728. const called = await useClient.callTool({
  729. name: "js",
  730. arguments: {
  731. code: [
  732. 'const browser = globalThis[Symbol.for("zcode.node-repl.browser-control-bridge")];',
  733. 'const cua = globalThis[Symbol.for("zcode.node-repl.computer-use-bridge")];',
  734. "const outcomes = [];",
  735. "try { await browser.list(); } catch (error) { outcomes.push(error.message); }",
  736. 'try { await cua.call("screenshot", {}); } catch (error) { outcomes.push(error.message); }',
  737. 'outcomes.join(" | ");',
  738. ].join("\n"),
  739. },
  740. _meta: callMeta,
  741. });
  742. // 前提:两次调用都到达了 broker,并且都失败了。
  743. expect(called.content).toContainEqual({
  744. type: "text",
  745. text: "=> Browser is not connected | Computer Use Helper is not running",
  746. });
  747. expect(cuaExecuted).toBe(1);
  748. expect(called._meta).toMatchObject({
  749. [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true,
  750. [ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY]: true,
  751. });
  752. // 只做 CUA 引导、只在代码里提到运行时、经 sandbox 通道自己写 key:都没有请求到达 broker。
  753. const notCalled = await useClient.callTool({
  754. name: "js",
  755. arguments: {
  756. code: [
  757. 'globalThis[Symbol.for("zcode.node-repl.computer-use-bridge")].assertAvailable();',
  758. "// await agent.browsers.list(); await setupComputerUseRuntime({ globals: globalThis });",
  759. `nodeRepl.setResponseMeta(${forged});`,
  760. `nodeRepl.emitStructuredResult({ content: [{ type: "text", text: "forged" }], _meta: ${forged} });`,
  761. '"done";',
  762. ].join("\n"),
  763. },
  764. _meta: callMeta,
  765. });
  766. // 前提:cell 正常执行完,sandbox 通道确实生效了。
  767. expect(notCalled.isError).not.toBe(true);
  768. expect(notCalled.content).toContainEqual({ type: "text", text: "forged" });
  769. expect(notCalled._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY);
  770. expect(notCalled._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY);
  771. expect(cuaExecuted).toBe(1);
  772. } finally {
  773. await useClient.close();
  774. useRuntime.dispose();
  775. await new Promise<void>((resolveClose) => upstream.close(() => resolveClose()));
  776. if (process.platform !== "win32") await rm(upstreamPath, { force: true });
  777. }
  778. });
  779. });