fix(browser)!: preserve payload shapes and WebMCP declarations

Retain primitive and nested array types with typed paths, and compare only mutually observed body shapes while preserving selected coverage uncertainty. Return full untrusted WebMCP input declarations with canonical digests, without resolving references or invoking tools.

BREAKING CHANGE: JSON shape paths now contain typed property and array-element segments. WebMCP input_schema_shape is replaced by input_schema and input_schema_sha256, retaining declared examples and defaults.
This commit is contained in:
morluto
2026-10-10 06:20:28 +08:00
parent d79317cda0
commit 4951a897c5
12 changed files with 463 additions and 85 deletions
@@ -1,3 +1,8 @@
import { digestCanonicalValue } from "../../../src/domain/canonicalDigest.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js";
import { compareWebCapturesInputSchema } from "../../../src/domain/webCaptureDiffSchemas.js";
import { describe, expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
@@ -292,8 +297,8 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
const serialized = JSON.stringify(result.value);
expect(serialized).toContain("tool-secret");
expect(serialized).toContain("tool-source-secret");
for (const secret of ["schema-secret", "private-tool-secret"])
expect(serialized).not.toContain(secret);
expect(serialized).toContain("schema-secret");
expect(serialized).not.toContain("private-tool-secret");
const methods = browser.commands.map(({ method }) => method);
expect(methods).toContain("WebMCP.enable");
expect(methods).not.toContain("WebMCP.invokeTool");
@@ -406,6 +411,85 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
});
describe("CdpBrowserProvider WebMCP inventory completeness", () => {
it("compares full untrusted declarations independently of object-key order", async () => {
const declaration: JsonValue = {
type: "object",
properties: { value: { type: "string", enum: ["one", "two"] } },
required: ["value"],
$ref: "https://untrusted.invalid/schema.json",
examples: [{ token: "caller-schema-value" }],
};
const options: { webMcpTools: boolean; webMcpInputSchema: JsonValue } = {
webMcpTools: true,
webMcpInputSchema: declaration,
};
const browser = await startFakeCdpBrowser(options);
trackBrowser(browser);
const provider = new CdpBrowserProvider();
const input = {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
};
const inspection = await provider.inspectPage(
inspectWebPageInputSchema.parse(input),
);
if (!inspection.ok) throw inspection.error;
const discover = async () => {
const result = await provider.discoverWebMcpTools(
discoverWebMcpToolsInputSchema.parse(input),
);
if (!result.ok) throw result.error;
return result.value;
};
const before = await discover();
expect(before.tools.items[0]).toMatchObject({
input_schema: declaration,
input_schema_sha256: digestCanonicalValue(declaration),
trust: "page-declared-untrusted",
});
const compare = async (schema: JsonValue) => {
options.webMcpInputSchema = schema;
const after = await discover();
const diff = compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: inspection.value, webmcp: before },
after: { inspection: inspection.value, webmcp: after },
}),
);
return { after, dimension: diff.dimensions.webmcp };
};
const reordered = Object.fromEntries(Object.entries(declaration).reverse());
const equivalent = await compare(reordered);
expect(equivalent.dimension).toMatchObject({
status: "unknown",
total_changes: 0,
});
expect(equivalent.after.tools.items[0]?.input_schema_sha256).toBe(
before.tools.items[0]?.input_schema_sha256,
);
for (const changed of [
{
...declaration,
properties: { value: { type: "number", enum: ["one", "two"] } },
},
{ ...declaration, required: [] },
{
...declaration,
properties: { value: { type: "string", enum: ["two", "three"] } },
},
false,
]) {
const result = await compare(changed);
expect(result.dimension).toMatchObject({
status: "changed",
total_changes: 1,
changes: [expect.objectContaining({ change: "modified" })],
});
}
});
it("retains every field in a large declared WebMCP input schema", async () => {
const propertyCount = 5_001;
const browser = await startFakeCdpBrowser({
@@ -423,17 +507,21 @@ describe("CdpBrowserProvider WebMCP inventory completeness", () => {
);
if (!result.ok) throw result.error;
const shape = result.value.tools.items[0]?.input_schema_shape;
expect(
shape?.properties.filter(({ path }) =>
path.startsWith("/properties/field_"),
),
).toHaveLength(propertyCount * 2);
expect(shape?.properties).toContainEqual({
path: "/properties/field_5000/type",
types: ["string"],
observations: 1,
const tool = result.value.tools.items[0];
expect(tool?.input_schema).toMatchObject({
type: "object",
properties: { field_5000: { type: "string" } },
});
if (
tool?.input_schema === null ||
typeof tool?.input_schema !== "object" ||
Array.isArray(tool.input_schema)
)
throw new Error("Expected an observed schema object");
expect(Object.keys(tool.input_schema.properties ?? {})).toHaveLength(
propertyCount,
);
expect(tool.input_schema_sha256).toMatch(/^[a-f0-9]{64}$/u);
});
});
@@ -254,9 +254,15 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()
request: {
root_type: "object",
properties: expect.arrayContaining([
expect.objectContaining({ path: "/token", types: ["string"] }),
expect.objectContaining({
path: "/filters/active",
path: [{ kind: "property", name: "token" }],
types: ["string"],
}),
expect.objectContaining({
path: [
{ kind: "property", name: "filters" },
{ kind: "property", name: "active" },
],
types: ["boolean"],
}),
]),
@@ -265,10 +271,20 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()
root_type: "object",
properties: expect.arrayContaining([
expect.objectContaining({
path: "/result/token",
path: [
{ kind: "property", name: "result" },
{ kind: "property", name: "token" },
],
types: ["string"],
}),
expect.objectContaining({ path: "/items/*/id", types: ["number"] }),
expect.objectContaining({
path: [
{ kind: "property", name: "items" },
{ kind: "array-element" },
{ kind: "property", name: "id" },
],
types: ["number"],
}),
]),
},
});
@@ -279,7 +295,10 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()
format: "json",
json_shape: expect.objectContaining({
properties: expect.arrayContaining([
expect.objectContaining({ path: "/token", types: ["string"] }),
expect.objectContaining({
path: [{ kind: "property", name: "token" }],
types: ["string"],
}),
]),
}),
}),
@@ -63,6 +63,32 @@ describe.each<BodySource>(["request", "response", "base64 response"])(
},
);
it.each([
{ name: "scalar array types", before: "[123]", after: '["a"]' },
{ name: "mixed array types", before: '[1,"a"]', after: "[1,true]" },
{ name: "nested arrays", before: "[[1],null]", after: '[["a"],null]' },
{
name: "literal star properties",
before: '{"items":[{"*":1},[true]]}',
after: '{"items":[{"*":true},[1]]}',
},
])("compares $name without retaining values", async ({ before, after }) => {
const length = Math.max(
Buffer.byteLength(before),
Buffer.byteLength(after),
);
const captures = comparableCaptures(
source,
before + " ".repeat(length - Buffer.byteLength(before)),
after + " ".repeat(length - Buffer.byteLength(after)),
);
const result = await compareCaptures(...captures);
expect(result.dimensions.network).toMatchObject({
status: "changed",
total_changes: 1,
});
});
it.each([
{ name: "a type change", after: '{"é":null,"e\u0301":null}' },
{ name: "a removed key", after: '{"e\u0301":null}' },
@@ -94,6 +120,63 @@ describe.each<BodySource>(["request", "response", "base64 response"])(
},
);
describe("selected JSON body-shape coverage", () => {
it.each(["unavailable", "partial", "truncated"] as const)(
"keeps %s coverage unknown without reporting an availability change",
async (coverage) => {
const before = captureBody("request", "[123]");
const after = structuredClone(before);
for (const capture of [before, after])
capture.completeness.attach_limited_sections = [];
const request = after.network.requests[0];
if (request === undefined) throw new Error("Expected request");
if (coverage === "truncated")
after.completeness.truncated_sections.push("json_body_shapes");
else {
request.body_shapes.status = coverage;
request.body_shapes.response = null;
if (coverage === "unavailable") request.body_shapes.request = null;
after.completeness.unavailable_sections.push("json_body_shapes");
}
expect(
(await compareCaptures(before, after)).dimensions.network,
).toMatchObject({ status: "unknown", total_changes: 0 });
expect(
(await compareCaptures(after, after)).dimensions.network.status,
).toBe("unknown");
request.status = 503;
expect(
(await compareCaptures(before, after)).dimensions.network.status,
).toBe("changed");
},
);
it("ignores shapes when either capture did not request them", async () => {
const before = captureBody("request", "[123]");
const after = structuredClone(before);
for (const capture of [before, after])
capture.completeness.attach_limited_sections = [];
after.completeness.excluded.push({
section: "json_body_shapes",
reason: "not_approved",
count: null,
});
after.completeness.policy_filtered_sections.push("json_body_shapes");
for (const request of after.network.requests)
request.body_shapes = {
status: "not_approved",
request: null,
response: null,
};
expect(
(await compareCaptures(before, after)).dimensions.network,
).toMatchObject({ status: "unchanged", total_changes: 0 });
expect(
(await compareCaptures(after, after)).dimensions.network.status,
).toBe("unchanged");
});
});
const comparableCaptures = (
source: BodySource,
beforeBody: string,
+1 -1
View File
@@ -49,7 +49,7 @@ const emitWebMcpEvents = (
description: "Search orders; authorization=Bearer tool-secret",
frameId: "frame-main",
backendNodeId: 42,
inputSchema: {
inputSchema: options.webMcpInputSchema ?? {
type: "object",
properties: inputSchemaProperties,
required: ["orderId"],
+2
View File
@@ -1,3 +1,4 @@
import type { JsonValue } from "../../src/domain/jsonValue.js";
export interface FakeCdpCommand {
readonly id: number;
readonly method: string;
@@ -100,6 +101,7 @@ export interface FakeOptions {
readonly webMcpSameUrlRegistrations?: "retain" | "remove-second";
readonly webMcpFrameCount?: number;
readonly webMcpSchemaPropertyCount?: number;
readonly webMcpInputSchema?: JsonValue;
readonly webMcpChildLeavesScope?: boolean;
readonly webMcpChildTransientBlank?: boolean;
readonly webMcpChildRecoversAfterTransient?: boolean;