fix(browser): retain passive coverage and failure identity (#13231)

This commit is contained in:
morluto authored and GitHub committed 2026-11-21 23:03:00 +00:00
1 parent cfa04985c2
commit eba41afd6c
6 files changed
+240 -252

No files matched your search

+1 -1
View File
@@ -64,7 +64,7 @@ export async function startBrowserVerifierSite() {
}
if (request.url === "/screenshot-noise") {
response.setHeader("content-type", "text/html");
response.end(`<!doctype html><html><body style="margin:0"><canvas width="2048" height="1536"></canvas><script>
response.end(`<!doctype html><html><body style="margin:0"><canvas style="display:block" width="2048" height="1536"></canvas><script>
const context = document.querySelector('canvas').getContext('2d');
const image = context.createImageData(2048, 1536);
let state = 0x6d2b79f5;
+27 -21
View File
@@ -3,11 +3,9 @@ import {
requireMcpToolError,
} from "./mcp-verifier-results.mjs";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright-core";
import { Client } from "@modelcontextprotocol/client";
@@ -15,14 +13,12 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { parseEvidence } from "../../dist/domain/evidence.js";
import { webScreenshotSchema } from "../../dist/domain/webScreenshot.js";
import { comparePngScreenshots } from "../../dist/domain/pngVisualDiff.js";
import { withVerifierCleanup } from "./verifier-cleanup.mjs";
import { createVerifierCommands } from "./verify-commands.mjs";
/** Verify a real, large PNG through production CLI and stdio MCP boundaries. */
export async function verifyLargeScreenshotE2e(endpoint, origin) {
const browser = await chromium.connectOverCDP(endpoint);
const context = await browser.newContext({
viewport: { width: 2048, height: 1536 },
deviceScaleFactor: 1,
});
const commands = await createVerifierCommands();
const entrypoint = fileURLToPath(new URL("../rea.mjs", import.meta.url));
const env = {
PATH: process.env.PATH ?? "/usr/bin:/bin",
@@ -31,17 +27,32 @@ export async function verifyLargeScreenshotE2e(endpoint, origin) {
};
let client;
let transport;
try {
let browser;
let context;
return withVerifierCleanup(async () => {
browser = await chromium.connectOverCDP(endpoint);
context = await browser.newContext({
viewport: { width: 2048, height: 1536 },
deviceScaleFactor: 1,
});
const page = await context.newPage();
await page.goto(`${origin}/screenshot-noise`);
await page.waitForFunction(() => document.body.dataset.ready === "true");
assert.deepEqual(
await page.evaluate(() => [
document.documentElement.scrollWidth,
document.documentElement.scrollHeight,
]),
[2048, 1536],
"Noise canvas must fill the intended viewport without document overflow",
);
const targets = await (await fetch(`${endpoint}/json/list`)).json();
const target = targets.find((value) => value.url === page.url());
assert.ok(
target,
"Owned screenshot page is absent from actual CDP discovery",
);
const { stdout } = await promisify(execFile)(
const { stdout } = await commands.exec(
process.execPath,
[
entrypoint,
@@ -120,18 +131,13 @@ export async function verifyLargeScreenshotE2e(endpoint, origin) {
matched_large_buffer: true,
png_bytes: bytes.byteLength,
};
} finally {
try {
if (client !== undefined) await client.close();
} finally {
try {
if (transport !== undefined) await transport.close();
} finally {
await context.close();
await browser.close();
}
}
}
}, [
() => client?.close(),
() => transport?.close(),
() => context?.close(),
() => browser?.close(),
() => commands.close(),
]);
}
const verifyDefaultScreenshotDelivery = async ({
+95 -79
View File
@@ -1,5 +1,6 @@
import { expect, it } from "vitest";
import { startFakeCdpBrowser } from "../../tests/fixtures/fakeCdpBrowser.js";
import { resultFor } from "../../tests/fixtures/fakeCdpBrowserResults.js";
import { fakeCdpEvents } from "../../tests/fixtures/fakeCdpEvents.js";
import { fakeCdpSend } from "../../tests/fixtures/fakeCdpSend.js";
import { createBrowserObservationProvider } from "../composition/browserObservation.js";
@@ -8,6 +9,7 @@ import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
import { webPageInspectionSchema } from "../domain/browserObservationSchemas.js";
import { discoverWebMcpToolsInputSchema } from "../domain/webMcpDiscovery.js";
import { discoverWebMcp } from "./CdpWebMcpDiscovery.js";
import { captureCdpScreenshot } from "./CdpScreenshot.js";
import type { CdpConnection } from "./CdpConnection.js";
import { captureWebScreenshotInputSchema } from "../domain/webScreenshot.js";
@@ -94,27 +96,48 @@ it.each(["", "h:"])(
},
);
it.each(["progress", "enable", "terminal", "complete"] as const)(
"releases WebMCP subscriptions after %s settlement",
it.each([
"progress",
"enable",
"webmcp-document",
"screenshot-document",
"terminal",
"complete",
] as const)(
"releases passive browser subscriptions after %s settlement",
async (stage) => {
const events = fakeCdpEvents();
const failure = new Error("controlled discovery interruption");
const unexpectedTerminal = new Error("terminal progress after failure");
let interrupted = true;
let treeReads = 0;
const documentChanged = stage.endsWith("-document");
const progressUpdates: number[] = [];
const connection = {
onEvent: events.onEvent,
send: fakeCdpSend((method) => {
send: fakeCdpSend((method, params) => {
if (method === "Page.getFrameTree")
return {
frameTree: { frame: { id: "main", url: "https://app.test/" } },
frameTree: {
frame: {
id:
interrupted && documentChanged && ++treeReads === 2
? "replacement"
: "main",
url: "https://app.test/",
},
},
};
if (method === "WebMCP.enable" && stage === "enable" && interrupted)
throw failure;
return {};
return resultFor({ id: 0, method, params }, 9222, {}, 0) ?? {};
}),
} as unknown as CdpConnection;
const context: Parameters<typeof discoverWebMcp>[0] = {
const selection = {
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "selected",
allowed_origins: ["https://app.test"],
};
const context: Omit<Parameters<typeof discoverWebMcp>[0], "input"> = {
connection,
sessionId: undefined,
discovery: {
@@ -135,21 +158,9 @@ it.each(["progress", "enable", "terminal", "complete"] as const)(
url: "https://app.test/",
attached: false,
},
input: discoverWebMcpToolsInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "selected",
allowed_origins: ["https://app.test"],
observation_ms: 0,
}),
progress: {
report: async (update) => {
progressUpdates.push(update.completed);
if (
interrupted &&
update.completed === 2 &&
(stage === "progress" || stage === "enable")
)
throw unexpectedTerminal;
if (
interrupted &&
((stage === "progress" && update.completed === 1) ||
@@ -159,66 +170,79 @@ it.each(["progress", "enable", "terminal", "complete"] as const)(
},
},
};
const result = discoverWebMcp(context);
const screenshot = stage === "screenshot-document";
const run = () =>
screenshot
? captureCdpScreenshot({
...context,
input: captureWebScreenshotInputSchema.parse(selection),
})
: discoverWebMcp({
...context,
input: discoverWebMcpToolsInputSchema.parse({
...selection,
observation_ms: 0,
}),
});
const result = run();
if (stage === "complete")
await expect(result).resolves.toMatchObject({ status: "available" });
else if (documentChanged)
await expect(result).rejects.toMatchObject({
_tag: "BrowserObservationError",
operation: screenshot
? "capture_web_screenshot"
: "discover_webmcp_tools",
reason: "target_changed",
});
else await expect(result).rejects.toBe(failure);
expect(events.listenerCount()).toBe(0);
expect(progressUpdates).toEqual(
stage === "progress" || stage === "enable" ? [1] : [1, 2],
stage === "complete" || stage === "terminal" ? [1, 2] : [1],
);
interrupted = false;
await expect(discoverWebMcp(context)).resolves.toMatchObject({
status: "available",
});
expect(events.listenerCount()).toBe(0);
if (stage !== "complete") {
interrupted = false;
await expect(run()).resolves.toMatchObject(
screenshot
? { target: { target_id: "selected" } }
: { status: "available" },
);
expect(events.listenerCount()).toBe(0);
}
},
);
const loader = "loader-main";
const documentCases = [
["unchanged", loader, loader, "complete"],
["unknown initial loader", "", loader, "initial"],
["unknown final loader", loader, undefined, "final"],
["replacement loader", loader, "replacement-loader", "changed"],
] as const;
it.each(
["screenshot", "webmcp"].flatMap((operation) =>
[
"unchanged",
"unknown-loader",
"unknown-initial-loader",
"missing-final-loader",
"empty-final-loader",
"frame",
"loader",
].map((change) => ({
documentCases.map(([change, initialLoader, finalLoader, coverage]) => ({
operation,
change,
initialLoader,
finalLoader,
coverage,
})),
),
)(
"verifies final $operation document identity from tree snapshots: $change",
async ({ operation, change }) => {
async ({ operation, change, initialLoader, finalLoader, coverage }) => {
let trees = 0;
const browser = await startFakeCdpBrowser({
commandResult: (command, origin) => {
if (command.method !== "Page.getFrameTree") return undefined;
trees += 1;
const initial = trees++ === 0;
return {
frameTree: {
frame: {
id:
trees > 1 && change === "frame"
? "replacement-main"
: "frame-main",
loaderId:
trees > 1 && change === "missing-final-loader"
? undefined
: trees > 1 && change === "empty-final-loader"
? ""
: change === "unknown-initial-loader" && trees === 1
? undefined
: change === "unknown-loader"
? trees > 1
? undefined
: ""
: trees > 1 && change === "loader"
? "replacement-loader"
: "loader-main",
id: "frame-main",
loaderId: initial ? initialLoader : finalLoader,
url: `${origin}/app`,
},
},
@@ -243,34 +267,26 @@ it.each(
observation_ms: 0,
}),
);
// A missing loader leaves the document unproven: coverage is limited
// and the initial document stays the subject, never a protocol error.
if (change !== "frame" && change !== "loader") {
if (!result.ok) throw result.error;
const unknown = change !== "unchanged";
const finalOnly =
change === "missing-final-loader" || change === "empty-final-loader";
expect(
result.value.limitations.some((value) =>
value.includes(
`${finalOnly ? "final" : "initial"} document loader identity was unavailable`,
),
),
).toBe(unknown);
expect(result.value.completeness.attach_limited_sections).toEqual(
unknown
? expect.arrayContaining([
operation === "screenshot" ? "screenshot" : "webmcp_tools",
])
: expect.not.arrayContaining([
operation === "screenshot" ? "screenshot" : "webmcp_tools",
]),
);
} else
if (coverage === "changed") {
expect(result).toMatchObject({
ok: false,
error: { reason: "target_changed" },
});
return;
}
if (!result.ok) throw result.error;
const limited = coverage !== "complete";
const section =
operation === "screenshot" ? "screenshot" : "webmcp_tools";
expect(
result.value.completeness.attach_limited_sections.includes(section),
).toBe(limited);
if (limited)
expect(result.value.limitations).toContainEqual(
expect.stringContaining(
`${coverage} document loader identity was unavailable`,
),
);
} finally {
await provider.close?.();
await browser.close();
+20 -25
View File
@@ -37,6 +37,8 @@ interface ScreenshotContext {
readonly progress?: ProgressReporter;
}
const screenshotOperation = "capture_web_screenshot";
/** Capture the current viewport without navigation, evaluation, or page mutation. */
export const captureCdpScreenshot = async (
context: ScreenshotContext,
@@ -66,9 +68,9 @@ export const captureCdpScreenshot = async (
beforeFacts.scope === "outside_policy" ||
beforeFacts.scope === "unsupported"
)
throw cdpOriginScopeRefusal("capture_web_screenshot");
throw cdpOriginScopeRefusal(screenshotOperation);
if (beforeObservation.kind !== "observed")
throw new BrowserObservationError("inspect_web_page", "protocol_error");
throw new BrowserObservationError(screenshotOperation, "protocol_error");
const beforeUrl = beforeFacts.url;
const selected = cdpRootDocument(before);
if (
@@ -76,10 +78,7 @@ export const captureCdpScreenshot = async (
beforeFacts.origin === null ||
selected === undefined
)
throw new BrowserObservationError(
"capture_web_screenshot",
"protocol_error",
);
throw new BrowserObservationError(screenshotOperation, "protocol_error");
const navigation: ScreenshotNavigation = {
document: CdpTargetDocument.watch(context, selected),
urlChanged: false,
@@ -94,13 +93,12 @@ export const captureCdpScreenshot = async (
// visible URL moving within the document still invalidates the image.
const assertCurrentDocument = () => {
if (navigation.document.changed)
throw new BrowserObservationError("inspect_web_page", "target_changed");
if (navigation.leftScope)
throw cdpOriginScopeRefusal("capture_web_screenshot");
throw new BrowserObservationError(screenshotOperation, "target_changed");
if (navigation.leftScope) throw cdpOriginScopeRefusal(screenshotOperation);
if (navigation.invalidIdentity)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
throw new BrowserObservationError(screenshotOperation, "protocol_error");
if (navigation.urlChanged)
throw new BrowserObservationError("inspect_web_page", "target_changed");
throw new BrowserObservationError(screenshotOperation, "target_changed");
};
let screenshot: Awaited<ReturnType<typeof captureScreenshotImage>>;
let after: CdpFrameTree;
@@ -122,7 +120,7 @@ export const captureCdpScreenshot = async (
assertSameViewport(currentViewport, recoveredViewport);
if (!coversViewport(screenshot, recoveredViewport))
throw new BrowserObservationError(
"inspect_web_page",
screenshotOperation,
"protocol_error",
{
detail:
@@ -146,7 +144,7 @@ export const captureCdpScreenshot = async (
!(cause instanceof AnalysisCancelledError) &&
!(cause instanceof AnalysisError && cause.userCategory === "cancelled")
)
throw new BrowserObservationError("inspect_web_page", "target_changed", {
throw new BrowserObservationError(screenshotOperation, "target_changed", {
cause,
});
throw cause;
@@ -156,24 +154,21 @@ export const captureCdpScreenshot = async (
assertCurrentDocument();
const final = cdpRootDocument(after);
if (final === undefined)
throw new BrowserObservationError(
"capture_web_screenshot",
"protocol_error",
);
throw new BrowserObservationError(screenshotOperation, "protocol_error");
const comparison = navigation.document.observeTree(after);
if (comparison === "changed")
throw new BrowserObservationError("inspect_web_page", "target_changed");
throw new BrowserObservationError(screenshotOperation, "target_changed");
const afterObservation = after.root.url;
const afterFacts = classifyCdpFrameUrl(afterObservation, origins);
if (
afterFacts.scope === "outside_policy" ||
afterFacts.scope === "unsupported"
)
throw cdpOriginScopeRefusal("capture_web_screenshot");
throw cdpOriginScopeRefusal(screenshotOperation);
if (afterObservation.kind !== "observed")
throw new BrowserObservationError("inspect_web_page", "protocol_error");
throw new BrowserObservationError(screenshotOperation, "protocol_error");
if (afterFacts.url === undefined || final.url !== selected.url)
throw new BrowserObservationError("inspect_web_page", "target_changed");
throw new BrowserObservationError(screenshotOperation, "target_changed");
const unverified = navigation.document.unknown || comparison === "unknown";
if (unverified) navigation.completeness.attachLimited("screenshot");
await context.progress?.report({
@@ -220,7 +215,7 @@ const readScreenshotViewport = async (context: ScreenshotContext) => {
const { clientWidth: pixelWidth, clientHeight: pixelHeight } = visualViewport;
// Both viewports describe one page zoom; disagreement is incoherent geometry.
if (visualViewport.scale !== scale)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
throw new BrowserObservationError(screenshotOperation, "protocol_error");
// Keep ordinary surface captures, including their scrollbars and pixel
// density. The visual viewport excludes scrollbars and supplies only a
// lower bound on the expected image size, allowing subpixel rounding.
@@ -230,7 +225,7 @@ const readScreenshotViewport = async (context: ScreenshotContext) => {
!Number.isSafeInteger(minimumWidth) ||
!Number.isSafeInteger(minimumHeight)
)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
throw new BrowserObservationError(screenshotOperation, "protocol_error");
return {
clip: { x: pageX, y: pageY, width, height, scale },
pixelWidth,
@@ -262,7 +257,7 @@ const assertSameViewport = (
before.pixelWidth !== after.pixelWidth ||
before.pixelHeight !== after.pixelHeight
)
throw new BrowserObservationError("inspect_web_page", "target_changed", {
throw new BrowserObservationError(screenshotOperation, "target_changed", {
detail: "The visual viewport changed during screenshot capture.",
});
};
@@ -293,7 +288,7 @@ const captureScreenshotImage = async (
);
const screenshot = decodeScreenshot(data);
if (screenshot === undefined)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
throw new BrowserObservationError(screenshotOperation, "protocol_error");
return screenshot;
};
+72 -109
View File
@@ -85,7 +85,7 @@ export const discoverWebMcp = async (
);
document.observeTree(frameTree);
const frameUrls = new Map<string, FrameScopeFrame>();
const tools = new Map<string, WebMcpDiscovery["tools"]["items"][number]>();
const tools = new Map<string, WebMcpTool>();
const frameScope = {
origins,
frames: frameUrls,
@@ -95,11 +95,7 @@ export const discoverWebMcp = async (
resolvedTransientFrames: new Set<string>(),
};
ingestInitialFrameTree(frameTree, frameScope);
if (
[...frameUrls.values()].some(
(frame) => frame.parentFrameId !== null && frame.origin !== null,
)
) {
if ([...frameUrls.values()].some((frame) => frame.parentFrameId !== null)) {
completeness.attachLimited("webmcp_tools");
limitations.push(
"WebMCP.enable replay does not establish coverage of pre-existing subframe registrations. Later live registrations are retained, but cannot recover descriptors omitted before attachment.",
@@ -116,15 +112,7 @@ export const discoverWebMcp = async (
context.sessionId,
(event) => {
if (ingestFrameScopeEvent(event, frameScope)) return;
ingestWebMcpEvent({
event,
input: context.input,
frames: frameUrls,
tools,
completeness,
transientFrames: frameScope.transientFrames,
resolvedTransientFrames: frameScope.resolvedTransientFrames,
});
ingestWebMcpEvent(event, frameScope);
},
);
let result: ReturnType<typeof buildWebMcpResult>;
@@ -170,6 +158,7 @@ export const discoverWebMcp = async (
result = buildWebMcpResult({
context,
frameTree,
origins,
tools,
completeness,
limitations,
@@ -189,10 +178,12 @@ export const discoverWebMcp = async (
return result;
};
type WebMcpTool = WebMcpDiscovery["tools"]["items"][number];
interface FrameScopeState {
readonly origins: ReadonlySet<string>;
readonly frames: Map<string, FrameScopeFrame>;
readonly tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>;
readonly tools: Map<string, WebMcpTool>;
readonly completeness: CdpCaptureCompleteness;
readonly transientFrames: Set<string>;
readonly resolvedTransientFrames: Set<string>;
@@ -200,7 +191,7 @@ interface FrameScopeState {
interface FrameScopeFrame {
readonly url: string;
readonly origin: string | null;
readonly origin: string;
readonly parentFrameId: string | null;
}
@@ -337,7 +328,7 @@ const updateFrameScope = (
const unverifiedSubframeTools = (
document: CdpTargetDocument,
frames: ReadonlyMap<string, FrameScopeFrame>,
tools: ReadonlyMap<string, WebMcpDiscovery["tools"]["items"][number]>,
tools: ReadonlyMap<string, WebMcpTool>,
): string[] => {
const withTools = new Set([...tools.values()].map((tool) => tool.frame_id));
return [...frames]
@@ -353,7 +344,7 @@ const unverifiedSubframeTools = (
const removeFrameTools = (
frameId: string,
tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>,
tools: Map<string, WebMcpTool>,
): void => {
for (const [key, tool] of tools)
if (tool.frame_id === frameId) tools.delete(key);
@@ -377,7 +368,7 @@ const isTransientFrameUrl = (url: string): boolean => {
const removeFrame = (
frameId: string,
frames: Map<string, FrameScopeFrame>,
tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>,
tools: Map<string, WebMcpTool>,
): void => {
const pending = [frameId];
const removed = new Set<string>();
@@ -415,7 +406,10 @@ const assertStableAuthorizedFrame = async (
);
document.observe(discoveryDocument(finalTree));
if (document.changed)
throw new BrowserObservationError("inspect_web_page", "target_changed");
throw new BrowserObservationError(
"discover_webmcp_tools",
"target_changed",
);
requiredDiscoveryFrame(finalTree, origins);
if (document.unknown) {
coverage.completeness.attachLimited("webmcp_tools");
@@ -443,35 +437,19 @@ const requiredDiscoveryFrame = (
if (facts.scope === "outside_policy" || facts.scope === "unsupported")
throw cdpOriginScopeRefusal("discover_webmcp_tools");
if (observed.kind !== "observed")
throw new BrowserObservationError("inspect_web_page", "protocol_error");
if (facts.url === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
throw new BrowserObservationError(
"discover_webmcp_tools",
"protocol_error",
);
return discoveryDocument(tree);
};
interface WebMcpIngestOptions {
readonly event: CdpReceivedEvent;
readonly input: DiscoverWebMcpToolsInput;
readonly frames: ReadonlyMap<
string,
{ readonly url: string; readonly origin: string | null }
>;
readonly tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>;
readonly completeness: CdpCaptureCompleteness;
readonly transientFrames: Set<string>;
readonly resolvedTransientFrames: Set<string>;
}
const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
const {
event,
input,
frames,
tools,
completeness,
transientFrames,
resolvedTransientFrames,
} = options;
const ingestWebMcpEvent = (
event: CdpReceivedEvent,
state: FrameScopeState,
): void => {
const { tools, completeness, transientFrames, resolvedTransientFrames } =
state;
const registered = event.registered;
if (
registered?.method !== "WebMCP.toolsAdded" &&
@@ -493,17 +471,17 @@ const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
}
for (const tool of declared) {
const frameId = cdpStringValue(tool.frameId);
if (frameId !== undefined && transientFrames.has(frameId)) {
if (!resolvedTransientFrames.has(frameId)) continue;
transientFrames.delete(frameId);
resolvedTransientFrames.delete(frameId);
if (frameId === undefined) {
completeness.exclude("webmcp_tools", "invalid_protocol_value");
continue;
}
const normalized = normalizeTool(tool, input, frames, completeness);
if (transientFrames.has(frameId) && !resolvedTransientFrames.has(frameId))
continue;
const normalized = normalizeTool(tool, frameId, state);
if (normalized === undefined) continue;
tools.set(
registrationKey(normalized.frame_id, normalized.name),
normalized,
);
if (transientFrames.delete(frameId))
resolvedTransientFrames.delete(frameId);
tools.set(registrationKey(frameId, normalized.name), normalized);
}
};
@@ -529,21 +507,16 @@ const webMcpEventTools = (
const normalizeTool = (
value: UnknownRecord,
input: DiscoverWebMcpToolsInput,
frames: ReadonlyMap<
string,
{ readonly url: string; readonly origin: string | null }
>,
completeness: CdpCaptureCompleteness,
): WebMcpDiscovery["tools"]["items"][number] | undefined => {
const frameId = cdpStringValue(value.frameId);
frameId: string,
{ frames, origins, completeness }: FrameScopeState,
): WebMcpTool | undefined => {
const name = cdpStringValue(value.name);
const frame = frameId === undefined ? undefined : frames.get(frameId);
if (frameId === undefined || name === undefined) {
if (name === undefined) {
completeness.exclude("webmcp_tools", "invalid_protocol_value");
return undefined;
}
if (frame?.origin === null || frame === undefined) {
const frame = frames.get(frameId);
if (frame === undefined) {
completeness.exclude("webmcp_tools", "out_of_target_scope");
return undefined;
}
@@ -553,20 +526,15 @@ const normalizeTool = (
Object.hasOwn(value, "annotations") && annotations === undefined;
if (malformedAnnotations)
completeness.exclude("webmcp_tools", "invalid_protocol_value");
const annotation = (key: string): boolean | null => {
const annotation = (key: string): boolean | null | undefined => {
if (annotations === undefined || !Object.hasOwn(annotations, key))
return null;
const hint = annotations[key];
if (typeof hint === "boolean") return hint;
completeness.exclude("webmcp_tools", "invalid_protocol_value");
return null;
return undefined;
};
const consequential = annotation("consequential");
const unknownConsequential =
malformedAnnotations ||
(annotations !== undefined &&
Object.hasOwn(annotations, "consequential") &&
typeof annotations.consequential !== "boolean");
const declaration = Object.hasOwn(value, "inputSchema")
? jsonValueSchema.safeParse(value.inputSchema)
: undefined;
@@ -579,6 +547,10 @@ const normalizeTool = (
);
if (!registrationFrame.ok || coordinates.invalid)
completeness.exclude("webmcp_tools", "invalid_protocol_value");
const registrationUrl =
registrationFrame.ok && !coordinates.invalid
? allowedSanitizedUrl(registrationFrame.value?.url, origins)
: undefined;
return {
tool_key: toolKey(frame.url, frameId, name),
name,
@@ -594,56 +566,47 @@ const normalizeTool = (
input_schema_sha256:
declaration?.success === true ? digestCanonicalValue(schema) : null,
annotations: {
read_only: annotation("readOnly"),
untrusted_content: annotation("untrustedContent"),
...(unknownConsequential ? {} : { consequential }),
autosubmit: annotation("autosubmit"),
read_only: annotation("readOnly") ?? null,
untrusted_content: annotation("untrustedContent") ?? null,
...(malformedAnnotations || consequential === undefined
? {}
: { consequential }),
autosubmit: annotation("autosubmit") ?? null,
},
registration_source: registrationSource(
registrationFrame.ok && !coordinates.invalid
? registrationFrame.value
: undefined,
new Set(input.allowed_origins),
),
registration_source:
registrationUrl === undefined
? null
: {
url: registrationUrl.url,
line: coordinates.line,
column: coordinates.column,
},
trust: "page-declared-untrusted",
};
};
const registrationSource = (
frame: UnknownRecord | undefined,
allowedOrigins: ReadonlySet<string>,
): WebMcpDiscovery["tools"]["items"][number]["registration_source"] => {
const url = allowedSanitizedUrl(frame?.url, allowedOrigins);
const coordinates = cdpSourceCoordinates(frame);
return frame === undefined || url === undefined
? null
: {
url: url.url,
line: coordinates.line,
column: coordinates.column,
};
};
interface WebMcpResultOptions {
readonly context: DiscoveryContext;
readonly frameTree: CdpFrameTree;
readonly tools: ReadonlyMap<
string,
WebMcpDiscovery["tools"]["items"][number]
>;
readonly origins: ReadonlySet<string>;
readonly tools: ReadonlyMap<string, WebMcpTool>;
readonly completeness: CdpCaptureCompleteness;
readonly limitations: string[];
readonly available: boolean;
}
const buildWebMcpResult = (options: WebMcpResultOptions): WebMcpDiscovery => {
const { context, frameTree, tools, completeness, limitations, available } =
options;
const {
context,
frameTree,
origins,
tools,
completeness,
limitations,
available,
} = options;
const targetUrl = observedFrameUrl(frameTree.root.url) ?? context.target.url;
const sanitized = allowedSanitizedUrl(
targetUrl,
new Set(context.input.allowed_origins),
);
const sanitized = allowedSanitizedUrl(targetUrl, origins);
return {
browser: context.discovery.version,
target: {
@@ -22,13 +22,14 @@ const transientChildren = [
];
it.each([
{ phase: "initial", recover: false },
{ phase: "initial", recover: true },
{ phase: "event", recover: false },
{ phase: "event", recover: true },
{ phase: "initial", replay: "absent" },
{ phase: "initial", replay: "valid" },
{ phase: "initial", replay: "malformed" },
{ phase: "event", replay: "absent" },
{ phase: "event", replay: "valid" },
] as const)(
"keeps temporary document policy independent of URL encoding: $phase/$recover",
async ({ phase, recover }) => {
"keeps temporary document policy independent of URL encoding: $phase/$replay",
async ({ phase, replay }) => {
let document = phase === "initial" ? "transient" : "old";
const frames = (origin: string) =>
transientChildren.map(({ id, location }) => ({
@@ -47,13 +48,6 @@ it.each([
name: `read-${id}`,
description,
frameId: id,
inputSchema: {},
annotations: {
readOnly: true,
untrustedContent: true,
consequential: false,
autosubmit: false,
},
}));
const browser = await startFakeCdpBrowser({
eventsBeforeReply: ["WebMCP.enable"],
@@ -87,12 +81,17 @@ it.each([
];
document = "transient";
if (phase === "event") events.push(...navigationEvents());
if (recover) {
if (replay !== "absent") {
document = "fresh";
events.push(...navigationEvents(), {
method: "WebMCP.toolsAdded",
sessionId,
params: { tools: registrations("Current registration") },
params: {
tools:
replay === "valid"
? registrations("Current registration")
: transientChildren.map(({ id }) => ({ frameId: id })),
},
});
}
return events;
@@ -115,7 +114,7 @@ it.each([
left.name.localeCompare(right.name),
),
).toMatchObject(
recover
replay === "valid"
? transientChildren.map(({ id }) => ({
name: `read-${id}`,
frame_id: id,
@@ -127,12 +126,21 @@ it.each([
expect(result.value.completeness.policy_filtered_sections).not.toContain(
"webmcp_tools",
);
const complete = recover && phase === "initial";
if (replay === "malformed")
expect(result.value.completeness.excluded).toEqual([
{
section: "webmcp_tools",
reason: "invalid_protocol_value",
count: transientChildren.length,
},
]);
const complete = replay === "valid" && phase === "initial";
expect(
result.value.completeness.attach_limited_sections.includes(
"webmcp_tools",
),
).toBe(!complete);
if (phase !== "initial" || replay === "malformed") return;
const inspection = await provider.inspectPage(
inspectWebPageInputSchema.parse(input),
);