TypeScript
fix(mcp): keep preview snapshots usable by the agent and let it save them (#10501)
Theo Browne061543e9e5b5
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.tsindex 67dde122e1b..6c4a0005314 100644--- a/apps/desktop/src/preview/Manager.ts+++ b/apps/desktop/src/preview/Manager.ts@@ -117,6 +117,12 @@ const ZOOM_EPSILON = 0.001;const MAX_EVALUATION_BYTES = 64_000;const MAX_VISIBLE_TEXT_LENGTH = 20_000;const MAX_INTERACTIVE_ELEMENTS = 200;+/**+ * A `[role]` container's innerText is its whole subtree, which turned one+ * snapshot's element list into 60 KB of repeated page text. Names are labels,+ * not content, so cap them where they are read.+ */+const MAX_INTERACTIVE_ELEMENT_NAME_LENGTH = 200;const MAX_SCREENSHOT_WIDTH = 1280;/** How long an armed tab keeps the exclusive display-media slot before another tab may take it. */const RECORDING_ARM_GRACE_MS = 10_000;@@ -3582,7 +3588,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functionreturn {tag: element.tagName.toLowerCase(),role: element.getAttribute("role"),- name: element.getAttribute("aria-label") || element.innerText || element.getAttribute("name") || "",+ name: (element.getAttribute("aria-label") || element.innerText || element.getAttribute("name") || "").slice(0, ${MAX_INTERACTIVE_ELEMENT_NAME_LENGTH}),selector: selectorFor(element),x: rect.x,y: rect.y,diff --git a/apps/server/src/config.ts b/apps/server/src/config.tsindex 42df3814b07..1486f6b40a2 100644--- a/apps/server/src/config.ts+++ b/apps/server/src/config.ts@@ -38,6 +38,8 @@ export interface ServerDerivedPaths {readonly providerStatusCacheDir: string;readonly worktreesDir: string;readonly attachmentsDir: string;+ /** Screenshots the agent asks the collaborative browser to keep for the user. */+ readonly browserArtifactsDir: string;readonly logsDir: string;readonly serverLogPath: string;readonly serverTracePath: string;@@ -125,6 +127,7 @@ export const deriveServerPaths = Effect.fn(function* (providerStatusCacheDir,worktreesDir: join(baseDir, "worktrees"),attachmentsDir,+ browserArtifactsDir: join(stateDir, "browser-artifacts"),logsDir,serverLogPath: join(logsDir, "server.log"),serverTracePath: join(logsDir, "server.trace.ndjson"),diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.tsindex 03cb8c18373..133e71bc3bc 100644--- a/apps/server/src/mcp/McpHttpServer.test.ts+++ b/apps/server/src/mcp/McpHttpServer.test.ts@@ -4,12 +4,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";+import * as Path from "effect/Path";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import { McpProtocol, McpSchema, McpServer } from "effect/unstable/ai";import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";+import * as ServerConfig from "../config.ts";import * as McpHttpServer from "./McpHttpServer.ts";import * as McpInvocationContext from "./McpInvocationContext.ts";import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";@@ -18,7 +21,7 @@ const environmentId = EnvironmentId.make("environment-mcp-test");const threadId = ThreadId.make("thread-mcp-test");const tabId = PreviewTabId.make("tab-mcp-test");const alternateTabId = PreviewTabId.make("tab-mcp-alternate");-const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));+const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));const invocation = {environmentId,threadId,@@ -41,9 +44,62 @@ const client = McpSchema.McpServerClient.of({});const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpServer.McpServer.layer),- Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),+ Layer.provideMerge(PreviewAutomationBroker.layer),+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-server-test-" })),+ Layer.provideMerge(NodeServices.layer),);+const snapshotResult = {+ url: "http://example.test/",+ title: "Example",+ loading: false,+ visibleText: "Example",+ interactiveElements: [],+ accessibilityTree: {},+ consoleEntries: [],+ networkEntries: [],+ actionTimeline: [],+ screenshot: {+ mimeType: "image/png",+ data: Buffer.from("png").toString("base64"),+ width: 10,+ height: 5,+ },+};++/** Answers every snapshot request on a fresh broker host with the given result. */+const serveSnapshots = (clientId: string, result: unknown) =>+ Effect.gen(function* () {+ const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;+ const connected = yield* Deferred.make<void>();+ const inputs: Array<unknown> = [];+ const events = yield* broker.connect({ clientId, environmentId });+ yield* Stream.runForEach(events, (event) => {+ if (event.type === "connected") return Deferred.succeed(connected, undefined);+ inputs.push(event.request.input);+ return broker.respond({+ clientId,+ connectionId: event.connectionId,+ requestId: event.request.requestId,+ ok: true,+ result,+ });+ }).pipe(Effect.forkScoped);+ yield* Deferred.await(connected);+ return inputs;+ });++const callSnapshot = (args: Record<string, unknown>) =>+ Effect.gen(function* () {+ const server = yield* McpServer.McpServer;+ return yield* server+ .callTool({ name: "preview_snapshot", arguments: args })+ .pipe(+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),+ Effect.provideService(McpSchema.McpServerClient, client),+ );+ });+it("normalizes empty successful notification responses to accepted", () => {const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(HttpServerResponse.text("", { status: 200, contentType: "application/json" }),@@ -92,7 +148,9 @@ it.effect.each([{}, { includeImage: false }])();expect(snapshot.isError).toBe(true);- expect(snapshot.content).toEqual([{ type: "text", text: "Preview snapshot failed." }]);+ expect(snapshot.content).toEqual([+ { type: "text", text: "Preview snapshot failed: PreviewAutomationExecutionError." },+ ]);expect(snapshot.structuredContent).toEqual({error: {_tag: "PreviewAutomationExecutionError",@@ -174,10 +232,16 @@ it.effect.each([Effect.provideService(McpSchema.McpServerClient, client),);const metadata = { ...page, title: `Snapshot ${call}`, screenshot };+ const { accessibilityTree: _tree, ...boundedMetadata } = metadata;expect(snapshot.isError).toBe(false);expect(snapshot.structuredContent).toEqual(metadata);- expect(snapshot.content).toEqual([- { type: "text", text: encodeJsonText(snapshot.structuredContent) },+ const [text, ...rest] = snapshot.content;+ expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual(boundedMetadata);+ expect(rest).toEqual([+ {+ type: "text",+ text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).",+ },...(images? [{@@ -200,7 +264,7 @@ it.effect.each([Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),Effect.provideService(McpSchema.McpServerClient, client),);- expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "image"]);+ expect(nextDefault.content.map((content) => content.type)).toEqual(["text", "text", "image"]);expect(nextDefault.structuredContent).toEqual({ ...page, title: "Snapshot 7", screenshot });expect(requests).toBe(7);}),@@ -221,7 +285,7 @@ it.effect("rejects non-boolean snapshot image options before selecting a browserEffect.provideService(McpSchema.McpServerClient, client),);expect(result.isError).toBe(true);- expect(result.content).toEqual([{ type: "text", text: "Preview snapshot failed." }]);+ expect(result.content).toEqual([{ type: "text", text: "Preview snapshot failed: AiError." }]);expect(result.structuredContent).toEqual({error: { _tag: "AiError", operation: "snapshot", failureCount: 1 },});@@ -229,6 +293,222 @@ it.effect("rejects non-boolean snapshot image options before selecting a browser}).pipe(Effect.provide(TestLayer)),);+it.effect("saves the snapshot PNG on request and reports its path", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const inputs = yield* serveSnapshots("mcp-save-client", snapshotResult);++ const snapshot = yield* callSnapshot({ save: true });++ expect(snapshot.isError).toBe(false);+ // The browser never receives the server-only `save` flag.+ expect(inputs).toEqual([{}]);+ const structured = snapshot.structuredContent as { readonly screenshotPath?: string };+ const screenshotPath = structured.screenshotPath;+ expect(typeof screenshotPath).toBe("string");+ expect(path.dirname(screenshotPath!)).toBe(config.browserArtifactsDir);+ expect(path.basename(screenshotPath!)).toMatch(+ /^browser-screenshot-example-test-[0-9a-z]+-[0-9a-f]{8}\.png$/,+ );+ expect(Buffer.from(yield* fileSystem.readFile(screenshotPath!)).toString()).toBe("png");+ const text = snapshot.content.find((content) => content.type === "text");+ expect(text?.type === "text" ? text.text : "").toContain(screenshotPath);++ const unsaved = yield* callSnapshot({});+ expect(unsaved.structuredContent).not.toHaveProperty("screenshotPath");+ }),+ ).pipe(Effect.provide(TestLayer)),+);++it.effect("reports a tagged error when the screenshot cannot be saved", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ // A regular file where the artifacts directory should be makes every write fail.+ yield* fileSystem.writeFileString(config.browserArtifactsDir, "");+ yield* serveSnapshots("mcp-save-failure-client", snapshotResult);++ const snapshot = yield* callSnapshot({ save: true });++ expect(snapshot.isError).toBe(true);+ expect(snapshot.content).toEqual([+ { type: "text", text: "Preview snapshot failed: PreviewScreenshotSaveError." },+ ]);+ expect(snapshot.structuredContent).toEqual({+ error: { _tag: "PreviewScreenshotSaveError", operation: "snapshot", failureCount: 1 },+ });+ }),+ ).pipe(Effect.provide(TestLayer)),+);++it.effect("keeps the snapshot text under the agent's output ceiling", () =>+ Effect.scoped(+ Effect.gen(function* () {+ // Mirrors the real failure: a [role] container whose innerText is the whole+ // project list, repeated for several elements, plus a big AX tree.+ const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600);+ const element = (name: string, index: number) => ({+ tag: "div",+ role: "presentation",+ name,+ selector: `div:nth-of-type(${index})`,+ x: 0,+ y: 0,+ width: 10,+ height: 10,+ });+ const oversized = {+ ...snapshotResult,+ visibleText: pageText,+ interactiveElements: [+ element(pageText, 1),+ element(pageText, 2),+ element(pageText, 3),+ element("Continue", 4),+ ],+ accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) },+ consoleEntries: Array.from({ length: 100 }, (_, i) => ({+ level: "log",+ text: `entry ${i}`,+ timestamp: "t",+ })),+ };+ yield* serveSnapshots("mcp-bounded-client", oversized);++ const snapshot = yield* callSnapshot({ includeImage: false });++ expect(snapshot.isError).toBe(false);+ const [text, notice] = snapshot.content;+ expect(text?.type).toBe("text");+ const body = text?.type === "text" ? text.text : "";+ expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(+ McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,+ );+ const parsed = decodeJsonText(body) as {+ readonly accessibilityTree?: unknown;+ readonly visibleText: string;+ readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;+ readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;+ };+ expect(parsed.accessibilityTree).toBeUndefined();+ expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001);+ expect(parsed.interactiveElements).toHaveLength(4);+ expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201);+ expect(parsed.interactiveElements[3]?.name).toBe("Continue");+ expect(parsed.consoleEntries).toHaveLength(40);+ expect(parsed.consoleEntries[0]?.text).toBe("entry 60");+ expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree");+ expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries");+ // The structured result is untouched; only the text the agent reads is bounded.+ expect(snapshot.structuredContent).toMatchObject({+ accessibilityTree: oversized.accessibilityTree,+ });+ }),+ ).pipe(Effect.provide(TestLayer)),+);++it.effect("bounds the snapshot text even when nothing but logs and the title are large", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const oversized = {+ ...snapshotResult,+ title: "t".repeat(70_000),+ interactiveElements: [],+ consoleEntries: [{ level: "log", text: "x".repeat(70_000), timestamp: "t" }],+ };+ yield* serveSnapshots("mcp-bounded-logs-client", oversized);++ const snapshot = yield* callSnapshot({ includeImage: false });++ const [text] = snapshot.content;+ const body = text?.type === "text" ? text.text : "";+ expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(+ McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,+ );+ const parsed = decodeJsonText(body) as {+ readonly title: string;+ readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;+ };+ expect(parsed.title.length).toBe(2_049);+ expect(parsed.consoleEntries[0]?.text.length).toBe(501);+ const notice = snapshot.content[1];+ const noticeText = notice?.type === "text" ? notice.text : "";+ expect(noticeText).toContain("url or title after 2048 characters");+ expect(noticeText).toContain("console entries text after 500 characters");+ }),+ ).pipe(Effect.provide(TestLayer)),+);++it.effect("sheds log entries before locators when every list is full", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const long = "x".repeat(2_000);+ const oversized = {+ ...snapshotResult,+ interactiveElements: Array.from({ length: 20 }, (_, i) => ({+ tag: "button",+ role: "button",+ name: `Button ${i}`,+ selector: `#button-${i}`,+ x: 0,+ y: 0,+ width: 10,+ height: 10,+ })),+ consoleEntries: Array.from({ length: 200 }, () => ({+ level: long,+ text: long,+ timestamp: long,+ source: long,+ })),+ networkEntries: Array.from({ length: 200 }, () => ({+ url: long,+ method: long,+ status: 200,+ failed: false,+ errorText: long,+ timestamp: long,+ })),+ actionTimeline: Array.from({ length: 200 }, () => ({+ id: long,+ action: long,+ status: "succeeded",+ startedAt: long,+ completedAt: long,+ error: long,+ })),+ };+ yield* serveSnapshots("mcp-full-logs-client", oversized);++ const snapshot = yield* callSnapshot({ includeImage: false });++ const [text, notice] = snapshot.content;+ const body = text?.type === "text" ? text.text : "";+ expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual(+ McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES,+ );+ const parsed = decodeJsonText(body) as {+ readonly interactiveElements: ReadonlyArray<unknown>;+ readonly consoleEntries: ReadonlyArray<unknown>;+ readonly networkEntries: ReadonlyArray<unknown>;+ readonly actionTimeline: ReadonlyArray<unknown>;+ };+ // Locators survive; the log lists take the cut.+ expect(parsed.interactiveElements).toHaveLength(20);+ expect(+ parsed.consoleEntries.length + parsed.networkEntries.length + parsed.actionTimeline.length,+ ).toBeLessThan(120);+ const noticeText = notice?.type === "text" ? notice.text : "";+ expect(noticeText).toContain("40 of 40 actionTimeline");+ expect(noticeText).not.toMatch(/\d+ of \d+ interactiveElements/);+ }),+ ).pipe(Effect.provide(TestLayer)),+);+it.effect("terminates HTTP MCP sessions with DELETE", () =>Effect.scoped(Effect.gen(function* () {@@ -306,33 +586,19 @@ it.effect("registers annotated tools and preserves authenticated request contextok: true,result:event.request.operation === "snapshot"- ? {- url: "http://example.test/",- title: "Example",- loading: false,- visibleText: "Example",- interactiveElements: [],- accessibilityTree: {},- consoleEntries: [],- networkEntries: [],- actionTimeline: [],- screenshot: {- mimeType: "image/png",- data: Buffer.from("png").toString("base64"),- width: 10,- height: 5,- },- }- : event.request.operation === "press"- ? undefined- : {- available: true,- visible: true,- tabId,- url: "http://example.test/",- title: "Example",- loading: false,- },+ ? snapshotResult+ : event.request.operation === "evaluate"+ ? ["Connect", "Continue"]+ : event.request.operation === "press"+ ? undefined+ : {+ available: true,+ visible: true,+ tabId,+ url: "http://example.test/",+ title: "Example",+ loading: false,+ },});}).pipe(Effect.forkScoped);yield* Effect.yieldNow;@@ -397,6 +663,22 @@ it.effect("registers annotated tools and preserves authenticated request contextalternateTabId,);+ // Arrays and primitives are wrapped so structuredContent stays a JSON object.+ // Claude Code rejects the whole result otherwise.+ const evaluateTool = server.tools.find(({ tool }) => tool.name === "preview_evaluate");+ expect(evaluateTool?.tool.outputSchema).toMatchObject({ type: "object" });+ const evaluated = yield* server+ .callTool({ name: "preview_evaluate", arguments: { expression: "buttons()" } })+ .pipe(+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),+ Effect.provideService(McpSchema.McpServerClient, client),+ );+ expect(evaluated.isError).toBe(false);+ expect(evaluated.structuredContent).toEqual({ value: ["Connect", "Continue"] });+ expect(evaluated.content).toEqual([+ { type: "text", text: '{"value":["Connect","Continue"]}' },+ ]);+const actionRequests = [{ name: "preview_click", arguments: { x: 10, y: 10 } },{ name: "preview_type", arguments: { text: "Hello" } },diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.tsindex 79bd631c03c..3f3e48ebe4b 100644--- a/apps/server/src/mcp/McpHttpServer.ts+++ b/apps/server/src/mcp/McpHttpServer.ts@@ -1,8 +1,13 @@+import * as NodeCrypto from "node:crypto";import * as Cause from "effect/Cause";+import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as Schema from "effect/Schema";import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";import type * as Types from "effect/Types";@@ -10,6 +15,7 @@ import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";import packageJson from "../../package.json" with { type: "json" };+import * as ServerConfig from "../config.ts";import * as McpInvocationContext from "./McpInvocationContext.ts";import * as McpSessionRegistry from "./McpSessionRegistry.ts";import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";@@ -95,6 +101,204 @@ const McpAuthMiddlewareLive = HttpRouter.middleware<{provides: McpInvocationContext.McpInvocationContext;}>()(makeMcpAuthMiddleware).layer;+/**+ * Claude Code drops every MCP result above 25k tokens (~100 KB of text) and+ * hands the agent a truncation notice instead, so a snapshot that carries the+ * full accessibility tree and 20 KB of page text loses its locators too. Keep+ * the text under that ceiling and tell the agent what was cut.+ */+export const MAX_SNAPSHOT_TEXT_BYTES = 60_000;+const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000;+const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200;+const MAX_SNAPSHOT_LOG_ENTRIES = 40;+const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500;+const MAX_SNAPSHOT_IDENTIFIER_CHARS = 2_048;++const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));+const utf8Length = (text: string) => Buffer.byteLength(text, "utf8");+const cutText = (text: string, max: number) =>+ text.length > max ? `${text.slice(0, max)}…` : text;++/** Shortens every string field of a log entry; other fields pass through. */+const cutEntryStrings = <A>(entry: A): A =>+ typeof entry === "object" && entry !== null+ ? (Object.fromEntries(+ Object.entries(entry).map(([key, value]) => [+ key,+ typeof value === "string" ? cutText(value, MAX_SNAPSHOT_LOG_TEXT_CHARS) : value,+ ]),+ ) as A)+ : entry;++const hasLongString = (entry: unknown, max: number) =>+ typeof entry === "object" &&+ entry !== null &&+ Object.values(entry).some((value) => typeof value === "string" && value.length > max);++type SnapshotMetadata = {+ readonly url: string;+ readonly title: string;+ readonly visibleText: string;+ readonly interactiveElements: ReadonlyArray<{+ readonly name: string;+ readonly [key: string]: unknown;+ }>;+ readonly consoleEntries: ReadonlyArray<unknown>;+ readonly networkEntries: ReadonlyArray<unknown>;+ readonly actionTimeline: ReadonlyArray<unknown>;+ readonly [key: string]: unknown;+};++/**+ * Drops the accessibility tree, shortens page text, element names, identifiers,+ * and log strings, keeps only the newest log entries, and finally sheds+ * interactive elements until the JSON fits. Returns the text plus notes on+ * what is missing so the agent can reach for preview_evaluate.+ */+const boundSnapshotMetadata = (+ metadata: SnapshotMetadata,+): { readonly text: string; readonly omitted: ReadonlyArray<string> } => {+ const omitted: Array<string> = [];+ const { accessibilityTree, ...withoutTree } = metadata;+ if (accessibilityTree !== undefined) {+ omitted.push("accessibilityTree (use interactiveElements locators or preview_evaluate)");+ }+ const tail = <A>(entries: ReadonlyArray<A>, label: string) => {+ if (entries.length > MAX_SNAPSHOT_LOG_ENTRIES) {+ omitted.push(`${entries.length - MAX_SNAPSHOT_LOG_ENTRIES} older ${label}`);+ }+ const kept = entries.slice(-MAX_SNAPSHOT_LOG_ENTRIES);+ if (kept.some((entry) => hasLongString(entry, MAX_SNAPSHOT_LOG_TEXT_CHARS))) {+ omitted.push(`${label} text after ${MAX_SNAPSHOT_LOG_TEXT_CHARS} characters`);+ }+ return kept.map(cutEntryStrings);+ };+ if (+ metadata.url.length > MAX_SNAPSHOT_IDENTIFIER_CHARS ||+ metadata.title.length > MAX_SNAPSHOT_IDENTIFIER_CHARS+ ) {+ omitted.push(`url or title after ${MAX_SNAPSHOT_IDENTIFIER_CHARS} characters`);+ }+ if (+ metadata.interactiveElements.some(+ (element) => element.name.length > MAX_SNAPSHOT_ELEMENT_NAME_CHARS,+ )+ ) {+ omitted.push(`element names longer than ${MAX_SNAPSHOT_ELEMENT_NAME_CHARS} characters`);+ }+ if (metadata.visibleText.length > MAX_SNAPSHOT_VISIBLE_TEXT_CHARS) {+ omitted.push(+ `visibleText after ${MAX_SNAPSHOT_VISIBLE_TEXT_CHARS} characters (use preview_evaluate for more)`,+ );+ }+ const bounded = {+ ...withoutTree,+ url: cutText(metadata.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),+ title: cutText(metadata.title, MAX_SNAPSHOT_IDENTIFIER_CHARS),+ visibleText: cutText(metadata.visibleText, MAX_SNAPSHOT_VISIBLE_TEXT_CHARS),+ interactiveElements: metadata.interactiveElements.map((element) => ({+ ...element,+ name: cutText(element.name, MAX_SNAPSHOT_ELEMENT_NAME_CHARS),+ })),+ consoleEntries: tail(metadata.consoleEntries, "console entries"),+ networkEntries: tail(metadata.networkEntries, "network entries"),+ actionTimeline: tail(metadata.actionTimeline, "action timeline entries"),+ };++ // Per-field caps do not sum below the ceiling: three log arrays of 40 capped+ // entries alone can pass 60 KB. Shed the least useful lists first, halving+ // one list per round, until the JSON fits. With every list empty the rest+ // is bounded by the identifier and visibleText caps, so this terminates.+ const shedOrder = [+ "actionTimeline",+ "networkEntries",+ "consoleEntries",+ "interactiveElements",+ ] as const;+ const lists: Record<(typeof shedOrder)[number], ReadonlyArray<unknown>> = {+ interactiveElements: bounded.interactiveElements,+ consoleEntries: bounded.consoleEntries,+ networkEntries: bounded.networkEntries,+ actionTimeline: bounded.actionTimeline,+ };+ const dropped: Record<(typeof shedOrder)[number], number> = {+ interactiveElements: 0,+ consoleEntries: 0,+ networkEntries: 0,+ actionTimeline: 0,+ };+ let text = encodeJsonText({ ...bounded, ...lists });+ while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) {+ // Elements carry the locators, so they go last; logs shed newest-last.+ const key =+ shedOrder.find(+ (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0,+ ) ?? (lists.interactiveElements.length > 0 ? "interactiveElements" : undefined);+ if (key === undefined) break;+ const keep = Math.floor(lists[key].length / 2);+ dropped[key] += lists[key].length - keep;+ // slice(-0) keeps everything, so spell out the empty case.+ lists[key] =+ keep === 0+ ? []+ : key === "interactiveElements"+ ? lists[key].slice(0, keep)+ : lists[key].slice(-keep);+ text = encodeJsonText({ ...bounded, ...lists });+ }+ for (const key of shedOrder) {+ if (dropped[key] > 0) {+ omitted.push(`${dropped[key]} of ${bounded[key].length} ${key}`);+ }+ }+ return { text, omitted };+};++export class PreviewScreenshotSaveError extends Schema.TaggedError<PreviewScreenshotSaveError>()(+ "PreviewScreenshotSaveError",+ { screenshotPath: Schema.String, cause: Schema.Defect() },+) {+ override get message(): string {+ return `Could not save preview screenshot to ${this.screenshotPath}.`;+ }+}++const MAX_SCREENSHOT_SITE_SLUG_LENGTH = 40;++/** Hostname reduced to a filename-safe slug, matching the desktop's own screenshot names. */+const screenshotSiteSlug = (rawUrl: string): string => {+ try {+ const slug = new URL(rawUrl).hostname+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, MAX_SCREENSHOT_SITE_SLUG_LENGTH)+ .replace(/-+$/g, "");+ return slug || "site";+ } catch {+ return "site";+ }+};++/** Writes the snapshot PNG under the browser artifacts directory and returns its path. */+const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* (+ pageUrl: string,+ data: Uint8Array,+) {+ const config = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const millis = yield* Clock.currentTimeMillis;+ // Two saves in the same millisecond must not overwrite each other.+ const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`;+ const screenshotPath = path.join(config.browserArtifactsDir, fileName);+ yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true }).pipe(+ Effect.andThen(fileSystem.writeFile(screenshotPath, data)),+ Effect.mapError((cause) => new PreviewScreenshotSaveError({ screenshotPath, cause })),+ );+ return screenshotPath;+});+const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {return Effect.failCause(cause).pipe(Effect.orDie);@@ -117,7 +321,8 @@ const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {failureCount: failures.length,},},- content: [{ type: "text", text: "Preview snapshot failed." }],+ // Agents usually see only the text content, so name the tag there too.+ content: [{ type: "text", text: `Preview snapshot failed: ${errorTag}.` }],});return Effect.logWarning("preview snapshot failed", {operation: "snapshot",@@ -129,6 +334,10 @@ const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {const server = yield* McpServer.McpServer;const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;+ // The MCP tool runner only supplies the client, so hand the save path its services here.+ const saveServices = yield* Effect.context<+ ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path+ >();const built = yield* PreviewSnapshotToolkit;const tool = PreviewSnapshotTool;yield* server.addTool({@@ -160,19 +369,21 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshotEffect.flatMap(Effect.fromOption),Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),- Effect.matchCauseEffect({- onFailure: previewSnapshotFailure,- onSuccess: ({ encodedResult }) => {- const snapshot = encodedResult as {+ Effect.flatMap(({ encodedResult }) =>+ Effect.gen(function* () {+ const snapshot = encodedResult as SnapshotMetadata & {+ readonly url: string;readonly screenshot: {readonly mimeType: "image/png";readonly data: string;readonly width: number;readonly height: number;};- readonly [key: string]: unknown;};const { screenshot, ...page } = snapshot;+ const png = new Uint8Array(Buffer.from(screenshot.data, "base64"));+ const screenshotPath =+ payload?.save === true ? yield* saveScreenshot(snapshot.url, png) : undefined;const metadata = {...page,screenshot: {@@ -180,26 +391,33 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshotwidth: screenshot.width,height: screenshot.height,},+ ...(screenshotPath === undefined ? {} : { screenshotPath }),};- return Effect.succeed(- new McpSchema.CallToolResult({- isError: false,- structuredContent: metadata,- content: [- { type: "text", text: JSON.stringify(metadata) },- ...(payload?.includeImage === false- ? []- : [- {- type: "image" as const,- data: new Uint8Array(Buffer.from(screenshot.data, "base64")),- mimeType: screenshot.mimeType,- },- ]),- ],- }),- );- },+ const bounded = boundSnapshotMetadata(metadata);+ return new McpSchema.CallToolResult({+ isError: false,+ structuredContent: metadata,+ content: [+ { type: "text", text: bounded.text },+ ...(bounded.omitted.length === 0+ ? []+ : [+ {+ type: "text" as const,+ text: `Snapshot text was bounded. Omitted: ${bounded.omitted.join("; ")}.`,+ },+ ]),+ ...(payload?.includeImage === false+ ? []+ : [{ type: "image" as const, data: png, mimeType: screenshot.mimeType }]),+ ],+ });+ }),+ ),+ Effect.provide(saveServices),+ Effect.matchCauseEffect({+ onFailure: previewSnapshotFailure,+ onSuccess: Effect.succeed,}),);}),diff --git a/apps/server/src/mcp/toolkits/preview/handlers.ts b/apps/server/src/mcp/toolkits/preview/handlers.tsindex 3cf3322cc62..d34c2d3ba3a 100644--- a/apps/server/src/mcp/toolkits/preview/handlers.ts+++ b/apps/server/src/mcp/toolkits/preview/handlers.ts@@ -166,8 +166,8 @@ const handlers = {preview_set_appearance: (input) =>invokeTargeted<PreviewAutomationSetColorSchemeResult>("setColorScheme", input),preview_snapshot: (input) => {- // Output selection is MCP-only; the browser still produces a complete snapshot.- const { includeImage: _includeImage, ...operationInput } = input ?? {};+ // Output selection and saving are MCP-only; the browser still produces a complete snapshot.+ const { includeImage: _includeImage, save: _save, ...operationInput } = input ?? {};return invokeTargeted<PreviewAutomationSnapshot>("snapshot", operationInput);},preview_click: (input) =>@@ -176,7 +176,9 @@ const handlers = {preview_press: (input) => invokeTargeted<void>("press", input).pipe(Effect.as({})),preview_scroll: (input) => invokeTargeted<void>("scroll", input).pipe(Effect.as({})),preview_evaluate: (input) =>- invokeTargeted<unknown>("evaluate", input).pipe(Effect.map((result) => result ?? null)),+ invokeTargeted<unknown>("evaluate", input).pipe(+ Effect.map((result) => ({ value: result ?? null })),+ ),preview_wait_for: (input) =>invokeTargeted<void>("waitFor", input, input.timeoutMs).pipe(Effect.as({})),preview_recording_start: (input) =>diff --git a/apps/server/src/mcp/toolkits/preview/tools.ts b/apps/server/src/mcp/toolkits/preview/tools.tsindex 0429f441ff0..28a2b96228b 100644--- a/apps/server/src/mcp/toolkits/preview/tools.ts+++ b/apps/server/src/mcp/toolkits/preview/tools.ts@@ -113,7 +113,7 @@ const PreviewSetAppearanceTool = safeBrowserTool(export const PreviewSnapshotTool = readonlyBrowserTool(Tool.make("preview_snapshot", {description:- "Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot. Set includeImage=false for text-only output with the same page metadata.",+ "Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot. Set includeImage=false for text-only output with the same page metadata. Set save=true to also write the PNG to disk and get screenshotPath back; embed that path in your reply as  so the user sees it. This is the only way to show the user a screenshot; the image in the tool result is not saved anywhere.",parameters: Schema.Struct({...PreviewAutomationTabTargetInput.fields,includeImage: Schema.optional(@@ -122,6 +122,12 @@ export const PreviewSnapshotTool = readonlyBrowserTool("Include the PNG image in the tool response. Defaults to true. Set false for text-only output.",}),),+ save: Schema.optional(+ Schema.Boolean.annotate({+ description:+ "Write the screenshot PNG to disk and return its absolute path as screenshotPath. Defaults to false.",+ }),+ ),}),success: PreviewAutomationSnapshot,failure: PreviewAutomationError,@@ -173,12 +179,23 @@ const PreviewScrollTool = safeBrowserTool(}).annotate(Tool.Title, "Scroll preview page"),);+/**+ * MCP `structuredContent` must be a JSON object, and Claude Code rejects the+ * whole result when it is not. Wrapping keeps arrays, strings, numbers, and+ * null valid instead of failing only for non-object expressions.+ */+export const PreviewEvaluateResult = Schema.Struct({+ value: Schema.Unknown.annotate({+ description: "The JSON-serializable value the expression produced, or null.",+ }),+}).annotate({ description: "The evaluated expression result." });+const PreviewEvaluateTool = browserTool(Tool.make("preview_evaluate", {description:- "Evaluate JavaScript in the tab selected by tabId, or this agent session's current tab when omitted. Returns a serializable result up to 64 KB; the expression may mutate page state.",+ "Evaluate JavaScript in the tab selected by tabId, or this agent session's current tab when omitted. Returns {value} with a serializable result up to 64 KB; the expression may mutate page state.",parameters: PreviewAutomationEvaluateInput,- success: Schema.Unknown,+ success: PreviewEvaluateResult,failure: PreviewAutomationError,dependencies,}).annotate(Tool.Title, "Evaluate JavaScript in preview"),