GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): recover dropped T3 MCP screenshot and snapshot outputs i… · Ryoku-dev/hyakki@f8465b9

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src
    • mcp
      • McpHttpServer.test.ts
      • McpHttpServer.ts
    • orchestration-v2/Adapters
      • AntigravityAdapterV2.test.ts
    • provider/acp
      • AntigravityProtocol.test.ts
      • AntigravityProtocol.ts
  • packages
    • provider-acp/src/server
      • adapter.ts
    • provider-core/src/server
      • McpProviderSessions.test.ts
      • McpProviderSessions.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/mcp/McpHttpServer.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/mcp/McpHttpServer.test.ts
+29Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import * as McpToolAccess from "./McpToolAccess.ts";
5959
import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
6060
import * as McpClientInput from "./McpClientInput.ts";
6161
import * as McpInvocationContext from "./McpInvocationContext.ts";
62+
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
6263
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
6364
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
6465
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
@@ -567,6 +568,34 @@ it.effect("saves the uncapped screenshot while the agent sees the capped one", (
567568
).pipe(Effect.provide(layerTest)),
568569
);
569570

571+
it.effect("keeps screenshot results only for provider instances that recover them", () =>
572+
Effect.scoped(
573+
Effect.gen(function* () {
574+
const sessions = yield* McpProviderSessions.McpProviderSessions;
575+
const png =
576+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
577+
yield* serveSnapshots("mcp-capture-client", {
578+
...snapshotResult,
579+
screenshot: { mimeType: "image/png", data: png, width: 1, height: 1 },
580+
});
581+
const args = { tabId: alternateTabId, includeImage: true };
582+
583+
yield* callSnapshot(args);
584+
expect(yield* sessions.takeToolResult(threadId, "preview_snapshot", args)).toBeUndefined();
585+
586+
yield* sessions.recoversToolResultImages(invocation.thread.providerInstanceId);
587+
yield* callSnapshot(args);
588+
expect(yield* sessions.takeToolResult(threadId, "preview_snapshot", args)).toMatchObject({
589+
content: [{ type: "image", mimeType: "image/png", data: png }],
590+
structuredContent: {
591+
url: snapshotResult.url,
592+
screenshot: { mimeType: "image/png", width: 1, height: 1 },
593+
},
594+
});
595+
}),
596+
).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(McpProviderSessions.layer)))),
597+
);
598+
570599
it.effect("names the screenshot destination when saving it fails", () =>
571600
Effect.scoped(
572601
Effect.gen(function* () {
Collapse file

‎apps/server/src/mcp/McpHttpServer.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/mcp/McpHttpServer.ts
+63-20Lines changed: 63 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,12 @@ import * as McpToolAccess from "./McpToolAccess.ts";
5959
import * as McpToolExposure from "./McpToolExposure.ts";
6060
import * as McpWebhookTransport from "./McpWebhookTransport.ts";
6161
import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender";
62-
import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput";
62+
import {
63+
compactT3McpToolOutput,
64+
MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH,
65+
MAX_TOOL_OUTPUT_IMAGES,
66+
} from "@t3tools/shared/toolOutput";
67+
import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
6368
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
6469
import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession";
6570
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
@@ -1224,6 +1229,34 @@ const withToolAnalytics =
12241229
return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
12251230
});
12261231

1232+
const SCREENSHOT_TOOLS: ReadonlySet<string> = new Set([
1233+
"preview_snapshot",
1234+
"device_screenshot",
1235+
"html_preview",
1236+
]);
1237+
1238+
/** A screenshot tool's images and details, in the shape an MCP result takes on a tool item. */
1239+
const isCallToolResult = Schema.is(McpSchema.CallToolResult);
1240+
1241+
function screenshotToolOutput(result: unknown): Record<string, unknown> | undefined {
1242+
if (!isCallToolResult(result) || result.isError === true) return undefined;
1243+
const images = result.content.flatMap((block) => {
1244+
if (block.type !== "image") return [];
1245+
const data = Buffer.from(block.data).toString("base64");
1246+
return data.length <= MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH
1247+
? [{ type: "image", mimeType: block.mimeType, data }]
1248+
: [];
1249+
});
1250+
const details = Predicate.isObject(result.structuredContent)
1251+
? (result.structuredContent as Record<string, unknown>)
1252+
: undefined;
1253+
if (images.length === 0) return details;
1254+
return {
1255+
content: images.slice(0, MAX_TOOL_OUTPUT_IMAGES),
1256+
...(details === undefined ? {} : { structuredContent: details }),
1257+
};
1258+
}
1259+
12271260
/**
12281261
* ACP runtimes and Code Mode wrappers can drop or replace structured MCP tool results on
12291262
* completion. Recording each thread-scoped call's compact result before returning lets adapters
@@ -1258,25 +1291,35 @@ const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(f
12581291
? undefined
12591292
: yield* mcpSessions.value.toolResultEpoch(thread.threadId);
12601293
return yield* options.handle(payload).pipe(
1261-
Effect.onExit((exit) => {
1262-
if (thread === undefined) return Effect.void;
1263-
if (exit._tag === "Success" && exit.value instanceof McpSchema.InputRequired) {
1264-
return Effect.void;
1265-
}
1266-
if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) {
1267-
return Effect.void;
1268-
}
1269-
const output =
1270-
exit._tag === "Success"
1271-
? compactT3McpToolOutput(toolName, exit.value)
1272-
: { isError: true };
1273-
return output === undefined
1274-
? Effect.void
1275-
: mcpSessions.value.recordToolResult(thread.threadId, toolName, payload, output, {
1276-
providerSessionId: thread.providerSessionId,
1277-
epoch,
1278-
});
1279-
}),
1294+
Effect.onExit(
1295+
Effect.fnUntraced(function* (exit) {
1296+
if (thread === undefined) return;
1297+
if (exit._tag === "Success" && exit.value instanceof McpSchema.InputRequired) {
1298+
return;
1299+
}
1300+
if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) {
1301+
return;
1302+
}
1303+
const screenshot =
1304+
exit._tag === "Success" &&
1305+
SCREENSHOT_TOOLS.has(resolveT3McpToolId(toolName) ?? toolName) &&
1306+
(yield* mcpSessions.value.areToolResultImagesRecovered(thread.providerInstanceId))
1307+
? screenshotToolOutput(exit.value)
1308+
: undefined;
1309+
const output =
1310+
exit._tag === "Success"
1311+
? (screenshot ?? compactT3McpToolOutput(toolName, exit.value))
1312+
: { isError: true };
1313+
if (output === undefined) return;
1314+
yield* mcpSessions.value.recordToolResult(
1315+
thread.threadId,
1316+
toolName,
1317+
payload,
1318+
output,
1319+
{ providerSessionId: thread.providerSessionId, epoch },
1320+
);
1321+
}),
1322+
),
12801323
);
12811324
}),
12821325
});
Collapse file

‎apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+34Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
htmlRenderFromToolItem,
1919
previewRecordingIdFromToolItem,
2020
sentMessageFromToolItem,
21+
toolOutputImages,
2122
} from "@t3tools/shared/toolOutput";
2223
import * as SecureRandom from "effect/crypto/SecureRandom";
2324
import * as DateTime from "effect/DateTime";
@@ -1054,6 +1055,7 @@ describe("AntigravityAdapterV2 html_render pages", () => {
10541055
const lateText = "Confirmed on a later completion.";
10551056
const lateErrorText = "Late explicit error.";
10561057
const unfinishedText = "Still running when turn ended.";
1058+
const largeShot = "A".repeat(12 * 1024 * 1024);
10571059
const adapter = yield* makeAntigravityAdapterV2({
10581060
instanceId,
10591061
selfInvocation: yield* resolveSelfInvocation(),
@@ -1239,6 +1241,28 @@ describe("AntigravityAdapterV2 html_render pages", () => {
12391241
);
12401242
yield* updateTool("recording-stop", "completed");
12411243

1244+
// The agent offloads a screenshot and completes the call with no result.
1245+
yield* startTool("snapshot", "preview_snapshot", { includeImage: true });
1246+
yield* mcpSessions.recordToolResult(
1247+
threadId,
1248+
"preview_snapshot",
1249+
{ includeImage: true },
1250+
{ content: [{ type: "image", mimeType: "image/png", data: "AAAA" }] },
1251+
);
1252+
yield* updateTool("snapshot", "completed");
1253+
1254+
// Recovered screenshots stay with the turn, so their bytes are bounded.
1255+
for (const tabId of ["tab-1", "tab-2", "tab-3"]) {
1256+
yield* startTool(`large-${tabId}`, "preview_snapshot", { tabId });
1257+
yield* mcpSessions.recordToolResult(
1258+
threadId,
1259+
"preview_snapshot",
1260+
{ tabId },
1261+
{ content: [{ type: "image", mimeType: "image/png", data: largeShot }] },
1262+
);
1263+
yield* updateTool(`large-${tabId}`, "completed");
1264+
}
1265+
12421266
// Unfinished call projected at turn end must not claim or leak to Turn 2.
12431267
yield* startTool("send-unfinished", "send_to_user", {
12441268
message: unfinishedText,
@@ -1352,6 +1376,16 @@ describe("AntigravityAdapterV2 html_render pages", () => {
13521376
previewRecordingIdFromToolItem(tool("recording-stop")!),
13531377
`${threadId}-rec-1`,
13541378
);
1379+
assert.deepEqual(toolOutputImages(tool("snapshot")?.output), [
1380+
{ mimeType: "image/png", data: "AAAA" },
1381+
]);
1382+
assert.isTrue(yield* mcpSessions.areToolResultImagesRecovered(instanceId));
1383+
assert.deepEqual(
1384+
["tab-1", "tab-2", "tab-3"].map((tabId) =>
1385+
toolOutputImages(tool(`large-${tabId}`)?.output).map((image) => image.data?.length),
1386+
),
1387+
[[largeShot.length], [largeShot.length], [undefined]],
1388+
);
13551389
}).pipe(Effect.provide(layerSession)),
13561390
);
13571391
});
Collapse file

‎apps/server/src/provider/acp/AntigravityProtocol.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/provider/acp/AntigravityProtocol.test.ts
+35Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
} from "@t3tools/provider-acp/server/runtimeModel";
2323
import { acpToolCallDiffPatch } from "@t3tools/provider-acp/server/adapter";
2424
import { acpChangedPathsOfToolCall } from "@t3tools/provider-acp/server/clientPolicy";
25+
import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
2526

2627
const isSessionNotification = Schema.is(AcpWireSchema.SessionNotification);
2728

@@ -675,6 +676,40 @@ describe("Antigravity tool results", () => {
675676
);
676677
});
677678

679+
it("keeps bounded screenshot bytes from T3 MCP tool results", () => {
680+
const png =
681+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
682+
const tooLarge = "A".repeat(MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH + 4);
683+
const notification = {
684+
sessionId: "session-1",
685+
update: {
686+
sessionUpdate: "tool_call_update",
687+
toolCallId: "shot-1",
688+
status: "completed",
689+
rawOutput: {
690+
content: [
691+
{ type: "image", mimeType: "image/png", data: png },
692+
{ type: "image", mimeType: "image/png", data: tooLarge },
693+
{ type: "text", text: JSON.stringify({ url: "https://example.test/" }) },
694+
],
695+
},
696+
content: [
697+
{ type: "content", content: { type: "image", mimeType: "image/png", data: png } },
698+
],
699+
},
700+
} satisfies EffectAcpSchema.SessionNotification;
701+
const normalized = normalizeAntigravitySessionUpdate(notification);
702+
expect(isSessionNotification(normalized)).toBe(true);
703+
const update = parseToolUpdate(normalized).toolCall.data;
704+
expect(toolOutputImages(update.rawOutput)).toEqual([
705+
{ mimeType: "image/png", data: png },
706+
{ mimeType: "image/png" },
707+
]);
708+
expect(normalized.update).toMatchObject({
709+
content: [{ type: "content", content: { type: "image", mimeType: "image/png", data: png } }],
710+
});
711+
});
712+
678713
const changesBeyondSizeLimits: ReadonlyArray<{
679714
readonly part: string;
680715
readonly update: Pick<EffectAcpSchema.ToolCallUpdate, "content" | "rawInput">;
Collapse file

‎apps/server/src/provider/acp/AntigravityProtocol.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/provider/acp/AntigravityProtocol.ts
+26-2Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import type {
55
} from "@t3tools/contracts";
66
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
77
import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
8+
import {
9+
MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH,
10+
MAX_TOOL_OUTPUT_IMAGES,
11+
} from "@t3tools/shared/toolOutput";
812
import * as Option from "effect/Option";
913
import * as Predicate from "effect/Predicate";
1014
import * as Schema from "effect/Schema";
@@ -272,8 +276,18 @@ export const isCutAntigravityToolText = (text: string) => text.includes(TOOL_TEX
272276
interface ToolPayloadBudget {
273277
nodes: number;
274278
text: number;
279+
images: number;
275280
}
276281

282+
const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
283+
284+
const isKeptImageData = (value: unknown): value is string =>
285+
typeof value === "string" &&
286+
value.length > 0 &&
287+
value.length <= MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH &&
288+
value.length % 4 === 0 &&
289+
BASE64_PATTERN.test(value);
290+
277291
function sanitizeToolValue(
278292
value: unknown,
279293
budget: ToolPayloadBudget,
@@ -314,6 +328,12 @@ function sanitizeToolValue(
314328
const entries: Array<readonly [string, unknown]> = [];
315329
for (const [key, entry] of Object.entries(value)) {
316330
if (budget.nodes <= 0) break;
331+
// Screenshot tools return their result as image bytes; keep them outside the text budget.
332+
if (value.type === "image" && key === "data" && budget.images > 0 && isKeptImageData(entry)) {
333+
budget.images -= 1;
334+
entries.push([key, entry]);
335+
continue;
336+
}
317337
if (
318338
(value.type === "image" && (key === "data" || key === "blob")) ||
319339
(key === "blob" &&
@@ -331,7 +351,11 @@ function sanitizeToolValue(
331351
}
332352

333353
export function sanitizeAntigravityToolPayload(payload: unknown): unknown {
334-
return sanitizeToolValue(payload, { nodes: 512, text: 64_000 }, 0);
354+
return sanitizeToolValue(
355+
payload,
356+
{ nodes: 512, text: 64_000, images: MAX_TOOL_OUTPUT_IMAGES },
357+
0,
358+
);
335359
}
336360
const isJsonRecord = Schema.is(Schema.Record(Schema.String, Schema.Json));
337361

@@ -499,7 +523,7 @@ export function normalizeAntigravitySessionUpdate(
499523
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
500524
return notification;
501525
}
502-
const contentBudget = { nodes: 512, text: 32_000 };
526+
const contentBudget = { nodes: 512, text: 32_000, images: MAX_TOOL_OUTPUT_IMAGES };
503527
const content = update.content?.flatMap((entry) => {
504528
const decoded = Option.getOrUndefined(
505529
decodeToolCallContent(sanitizeToolValue(entry, contentBudget, 0)),
Collapse file

‎packages/provider-acp/src/server/adapter.ts‎

Copy file name to clipboardExpand all lines: packages/provider-acp/src/server/adapter.ts
+26Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ import {
4646
compactT3McpToolOutput,
4747
htmlRenderFromToolItem,
4848
mcpToolResultOutput,
49+
omitToolOutputImageData,
50+
toolOutputImages,
4951
} from "@t3tools/shared/toolOutput";
5052
import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
5153
import * as Cause from "effect/Cause";
@@ -1331,6 +1333,25 @@ function appendToolContentText(content: unknown, text: string): unknown[] {
13311333
return next;
13321334
}
13331335

1336+
// Claims live until the turn ends; past this, recovered screenshots keep their details only.
1337+
const MAX_RECOVERED_IMAGE_CHARS_PER_TURN = 32 * 1024 * 1024;
1338+
1339+
function withinRecoveredImageBudget(
1340+
context: Pick<ActiveAcpTurn, "recoveredImageChars">,
1341+
output: unknown,
1342+
): unknown {
1343+
const chars = toolOutputImages(output).reduce(
1344+
(total, image) => total + (image.data?.length ?? 0),
1345+
0,
1346+
);
1347+
if (chars === 0) return output;
1348+
if (context.recoveredImageChars + chars > MAX_RECOVERED_IMAGE_CHARS_PER_TURN) {
1349+
return omitToolOutputImageData(output);
1350+
}
1351+
context.recoveredImageChars += chars;
1352+
return output;
1353+
}
1354+
13341355
function acpMcpToolCallOutput(rawOutput: unknown): unknown {
13351356
const record = unknownRecord(rawOutput);
13361357
if (record === undefined) return rawOutput;
@@ -1806,6 +1827,8 @@ interface ActiveAcpTurn {
18061827
readonly tools: Map<string, AcpToolCallState & { readonly backgroundCommandTaskId?: string }>;
18071828
/** Confirmed Hyakki MCP tool outputs keyed by `${toolCallId}\0${tool}\0${inputHash}`. */
18081829
readonly claimedToolResults: Map<string, unknown>;
1830+
/** Image characters recovered into `claimedToolResults` this turn. */
1831+
recoveredImageChars: number;
18091832
/** `${toolCallId}\0${tool}\0${inputHash}` keys that already drained a recorded MCP result. */
18101833
readonly drainedToolResultKeys: Set<string>;
18111834
/** `${toolCallId}\0${tool}\0${inputHash}` keys that reached terminal failure and must never do input-only recovery. */
@@ -2403,6 +2426,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
24032426
const idAllocator = yield* IdAllocator.IdAllocatorV2;
24042427
const host = yield* ProviderHost.ProviderHost;
24052428
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
2429+
yield* mcpSessions.recoversToolResultImages(options.instanceId);
24062430
const { flavor, selfInvocation: self } = options;
24072431
const callLauncher = yield* writeAcpMcpCallLauncher(host.paths.stateDir);
24082432
const readMcpContext = (threadId: ThreadId | null) =>
@@ -5826,6 +5850,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
58265850
);
58275851
if (recoveredOutput !== undefined) {
58285852
context.drainedToolResultKeys.add(callInputKey);
5853+
recoveredOutput = withinRecoveredImageBudget(context, recoveredOutput);
58295854
}
58305855
}
58315856
if (recoveredOutput !== undefined) {
@@ -10582,6 +10607,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1058210607
nativeMetadata: initialNativeMetadata,
1058310608
tools: new Map(),
1058410609
claimedToolResults: new Map(),
10610+
recoveredImageChars: 0,
1058510611
drainedToolResultKeys: new Set(),
1058610612
blockedInputRecoveryKeys: new Set(),
1058710613
attemptedInputRecoveryKeys: new Set(),

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.