Skip to content
TypeScript

fix(mcp): preview snapshots fit in the agent's tool output again (#13558)

Theo Browne4f27a8463105
diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts
index 16bf696e935..1415e2e8dcb 100644
--- a/apps/server/src/mcp/McpHttpServer.test.ts
+++ b/apps/server/src/mcp/McpHttpServer.test.ts
@@ -248,7 +248,10 @@ it.effect.each([
const metadata = { ...page, title: `Snapshot ${call}`, screenshot };
const { accessibilityTree: _tree, ...boundedMetadata } = metadata;
expect(snapshot.isError).toBe(false);
- expect(snapshot.structuredContent).toEqual(metadata);
+ expect(snapshot.structuredContent).toEqual({
+ ...boundedMetadata,
+ omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"],
+ });
const [identity, text, ...rest] = snapshot.content;
expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({
url: page.url,
@@ -287,7 +290,8 @@ it.effect.each([
"text",
"image",
]);
- expect(nextDefault.structuredContent).toEqual({ ...page, title: "Snapshot 7", screenshot });
+ expect(nextDefault.structuredContent).toMatchObject({ title: "Snapshot 7", screenshot });
+ expect(nextDefault.structuredContent).not.toHaveProperty("accessibilityTree");
expect(requests).toBe(7);
}),
).pipe(Effect.provide(TestLayer)),
@@ -341,6 +345,15 @@ it.effect("saves the snapshot PNG on request and reports its path", () =>
const unsaved = yield* callSnapshot({});
expect(unsaved.structuredContent).not.toHaveProperty("screenshotPath");
+
+ // A save without the image skips the page dump.
+ const pathOnly = yield* callSnapshot({ save: true, includeImage: false });
+ const saved = pathOnly.structuredContent as { readonly screenshotPath: string };
+ expect(saved).toEqual({ url: snapshotResult.url, screenshotPath: expect.any(String) });
+ expect(Buffer.from(yield* fileSystem.readFile(saved.screenshotPath)).toString()).toBe("png");
+ const [only, ...others] = pathOnly.content;
+ expect(others).toEqual([]);
+ expect(only?.type === "text" ? decodeJsonText(only.text) : null).toEqual(saved);
}),
).pipe(Effect.provide(TestLayer)),
);
@@ -460,9 +473,10 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () =>
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,
+ // Claude Code shows the model structuredContent instead of the text, so it is bounded too.
+ expect(snapshot.structuredContent).toEqual({
+ ...parsed,
+ omitted: expect.arrayContaining(["60 older console entries"]),
});
}),
).pipe(Effect.provide(TestLayer)),
@@ -500,6 +514,45 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are
).pipe(Effect.provide(TestLayer)),
);
+it.effect("bounds page text made of wide characters before dropping locators", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ // The character caps alone leave 8,000 three-byte characters, about 24 KB.
+ yield* serveSnapshots("mcp-wide-text-client", {
+ ...snapshotResult,
+ visibleText: "界".repeat(9_000),
+ interactiveElements: Array.from({ length: 20 }, (_, i) => ({
+ tag: "button",
+ role: "button",
+ name: `Button ${i}`,
+ selector: `#button-${i}`,
+ x: 0,
+ y: 0,
+ width: 10,
+ height: 10,
+ })),
+ });
+
+ 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 visibleText: string;
+ readonly interactiveElements: ReadonlyArray<unknown>;
+ };
+ expect(parsed.visibleText).toMatch(/^界+…$/);
+ expect(parsed.interactiveElements).toHaveLength(20);
+ expect(notice?.type === "text" ? notice.text : "").toContain(
+ "visibleText after 4000 characters",
+ );
+ }),
+ ).pipe(Effect.provide(TestLayer)),
+);
+
it.effect("sheds log entries before locators when every list is full", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts
index 5a8cb573ad8..f93c7643daf 100644
--- a/apps/server/src/mcp/McpHttpServer.ts
+++ b/apps/server/src/mcp/McpHttpServer.ts
@@ -114,12 +114,15 @@ const McpAuthMiddlewareLive = HttpRouter.middleware<{
}>()(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.
+ * Claude Code moves an MCP result above its output limit to a file and hands
+ * the agent a notice instead, so a snapshot that carries the full
+ * accessibility tree and page text loses its locators too. Claude Code also
+ * shows the model `structuredContent` in place of the text blocks when a
+ * result has both, so both carry the same bounded snapshot. Keep it near
+ * 20 KB and tell the agent what was cut. The short `omitted` notes may go a
+ * little over; the provider limit is far above this.
*/
-export const MAX_SNAPSHOT_TEXT_BYTES = 60_000;
+export const MAX_SNAPSHOT_TEXT_BYTES = 20_000;
const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000;
const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200;
const MAX_SNAPSHOT_LOG_ENTRIES = 40;
@@ -164,12 +167,11 @@ type SnapshotMetadata = {
/**
* 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.
+ * interactive elements until the JSON fits. Returns the bounded value, its
+ * text, and 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 boundSnapshotMetadata = (metadata: SnapshotMetadata) => {
const omitted: Array<string> = [];
const { accessibilityTree, ...withoutTree } = metadata;
if (accessibilityTree !== undefined) {
@@ -198,16 +200,10 @@ const boundSnapshotMetadata = (
) {
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),
@@ -218,9 +214,10 @@ const boundSnapshotMetadata = (
};
// 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.
+ // entries alone can pass 60 KB, and the caps count characters, not bytes.
+ // Halve one thing per round until the JSON fits: logs first, then page
+ // text, then the locators. The identifier caps bound the rest, so this
+ // terminates.
const shedOrder = [
"actionTimeline",
"networkEntries",
@@ -239,31 +236,51 @@ const boundSnapshotMetadata = (
networkEntries: 0,
actionTimeline: 0,
};
- let text = encodeJsonText({ ...bounded, ...lists });
+ let visibleTextChars = Math.min(metadata.visibleText.length, MAX_SNAPSHOT_VISIBLE_TEXT_CHARS);
+ const value = () => ({
+ ...bounded,
+ visibleText: cutText(metadata.visibleText, visibleTextChars),
+ ...lists,
+ });
+ let text = encodeJsonText(value());
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);
+ ) ??
+ (visibleTextChars > 0
+ ? "visibleText"
+ : 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 });
+ if (key === "visibleText") {
+ visibleTextChars = Math.floor(visibleTextChars / 2);
+ } else {
+ 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(value());
+ }
+ if (visibleTextChars < metadata.visibleText.length) {
+ omitted.push(
+ `visibleText after ${visibleTextChars} characters (use preview_evaluate for more)`,
+ );
}
for (const key of shedOrder) {
if (dropped[key] > 0) {
omitted.push(`${dropped[key]} of ${bounded[key].length} ${key}`);
}
}
- return { text, omitted };
+ return { value: value(), text, omitted };
};
export class PreviewScreenshotSaveError extends Schema.TaggedError<PreviewScreenshotSaveError>()(
@@ -396,6 +413,18 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
const png = new Uint8Array(Buffer.from(screenshot.data, "base64"));
const screenshotPath =
payload?.save === true ? yield* saveScreenshot(snapshot.url, png) : undefined;
+ if (screenshotPath !== undefined && payload?.includeImage === false) {
+ // The agent only wants a file to show the user. The url keeps the site icon on the tool row.
+ const saved = {
+ url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
+ screenshotPath,
+ };
+ return new McpSchema.CallToolResult({
+ isError: false,
+ structuredContent: saved,
+ content: [{ type: "text", text: encodeJsonText(saved) }],
+ });
+ }
const metadata = {
...page,
screenshot: {
@@ -408,7 +437,10 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
const bounded = boundSnapshotMetadata(metadata);
return new McpSchema.CallToolResult({
isError: false,
- structuredContent: metadata,
+ structuredContent:
+ bounded.omitted.length === 0
+ ? bounded.value
+ : { ...bounded.value, omitted: bounded.omitted },
content: [
// Keep the page identity readable even if a provider truncates the snapshot.
{
diff --git a/apps/server/src/mcp/toolkits/preview/tools.ts b/apps/server/src/mcp/toolkits/preview/tools.ts
index 3f80e84e9a5..1c790e8b643 100644
--- a/apps/server/src/mcp/toolkits/preview/tools.ts
+++ b/apps/server/src/mcp/toolkits/preview/tools.ts
@@ -119,7 +119,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. Set save=true to also write the PNG to disk and get screenshotPath back; embed that path in your reply as ![alt](screenshotPath) 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.",
+ "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. The text is capped near 20 KB and lists what it omitted; use preview_evaluate to read more. 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; with includeImage=false, save=true returns only the url and screenshotPath. Embed that path in your reply as ![alt](screenshotPath) 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(
@@ -131,7 +131,7 @@ export const PreviewSnapshotTool = readonlyBrowserTool(
save: Schema.optional(
Schema.Boolean.annotate({
description:
- "Write the screenshot PNG to disk and return its absolute path as screenshotPath. Defaults to false.",
+ "Write the screenshot PNG to disk and return its absolute path as screenshotPath. With includeImage=false, return only the url and screenshotPath. Defaults to false.",
}),
),
}),