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
+10 -11
View File
@@ -5,7 +5,8 @@ import type {
DiscoverWebMcpToolsInput,
WebMcpDiscovery,
} from "../domain/webMcpDiscovery.js";
import { inferJsonShape } from "../domain/jsonShape.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { digestCanonicalValue } from "../domain/canonicalDigest.js";
import { compositeKey } from "../domain/unicodeCodePointOrder.js";
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
@@ -413,6 +414,10 @@ const normalizeTool = (
}
const description = cdpStringValue(value.description) ?? "";
const annotations = recordValue(value.annotations);
const declaration = jsonValueSchema.safeParse(value.inputSchema);
if (!declaration.success)
completeness.exclude("webmcp_tools", "invalid_protocol_value");
const schema = declaration.success ? declaration.data : null;
return {
tool_key: toolKey(frame.url, frameId, name),
name,
@@ -424,7 +429,10 @@ const normalizeTool = (
numberValue(value.backendNodeId) === undefined
? "imperative"
: "declarative",
input_schema_shape: schemaShape(value.inputSchema),
input_schema: schema,
input_schema_sha256: declaration.success
? digestCanonicalValue(schema)
: null,
annotations: {
read_only: booleanOrNull(annotations?.readOnly),
untrusted_content: booleanOrNull(annotations?.untrustedContent),
@@ -438,15 +446,6 @@ const normalizeTool = (
};
};
const schemaShape = (value: unknown) => {
if (recordValue(value) === undefined) return null;
const encoded = JSON.stringify(value);
const shape = inferJsonShape(encoded);
if (shape === null)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
return shape;
};
const registrationSource = (
stack: UnknownRecord | undefined,
allowedOrigins: ReadonlySet<string>,
+89 -15
View File
@@ -2,6 +2,9 @@ import { describe, expect, it } from "vitest";
import { inferJsonShape } from "./jsonShape.js";
const property = (name: string) => ({ kind: "property" as const, name });
const element = { kind: "array-element" as const };
describe("inferJsonShape", () => {
it("retains paths and types without retaining JSON values", () => {
const shape = inferJsonShape(
@@ -18,14 +21,18 @@ describe("inferJsonShape", () => {
expect(shape).toMatchObject({
root_type: "object",
properties: expect.arrayContaining([
{ path: "/token", types: ["string"], observations: 1 },
{
path: "/users/*/id",
path: [property("token")],
types: ["string"],
observations: 1,
},
{
path: [property("users"), element, property("id")],
types: ["number", "string"],
observations: 2,
},
{
path: "/users/*/active",
path: [property("users"), element, property("active")],
types: ["boolean"],
observations: 2,
},
@@ -35,11 +42,36 @@ describe("inferJsonShape", () => {
expect(JSON.stringify(shape)).not.toContain("second-secret");
});
it("distinguishes array elements from literal star properties and counts primitive types", () => {
const shape = inferJsonShape('{"items":[{"*":1},[true,"x",null],2]}');
expect(shape?.properties).toEqual(
expect.arrayContaining([
{
path: [property("items"), element],
types: ["array", "number", "object"],
observations: 3,
},
{
path: [property("items"), element, property("*")],
types: ["number"],
observations: 1,
},
{
path: [property("items"), element, element],
types: ["boolean", "null", "string"],
observations: 3,
},
]),
);
});
it("rejects malformed JSON", () => {
expect(inferJsonShape("not-json")).toBeNull();
});
});
it("preserves pointer escaping and code-point ordering independently of key insertion order", () => {
describe("JSON shape completeness and ordering", () => {
it("preserves raw property names and code-point ordering independently of key insertion order", () => {
for (const reverse of [false, true]) {
const object = (number: number, value: unknown) => {
const entries = [
@@ -64,24 +96,66 @@ describe("inferJsonShape", () => {
node_count: 23,
max_depth_observed: 4,
properties: [
{ path: "/nested", types: ["array"], observations: 1 },
{ path: "/nested/*/A", types: ["boolean"], observations: 2 },
{ path: "/nested/*/_", types: ["boolean"], observations: 2 },
{ path: "/nested/*/a", types: ["boolean"], observations: 2 },
{
path: "/nested/*/e\u0301~1~0",
path: [property("nested")],
types: ["array"],
observations: 1,
},
{
path: [property("nested"), element],
types: ["object"],
observations: 2,
},
{
path: [property("nested"), element, property("A")],
types: ["boolean"],
observations: 2,
},
{
path: [property("nested"), element, property("_")],
types: ["boolean"],
observations: 2,
},
{
path: [property("nested"), element, property("a")],
types: ["boolean"],
observations: 2,
},
{
path: [property("nested"), element, property("e\u0301/~")],
types: ["array", "null"],
observations: 2,
},
{
path: "/nested/*/e\u0341~1~0",
path: [property("nested"), element, property("e\u0301/~"), element],
types: ["null"],
observations: 1,
},
{
path: [property("nested"), element, property("e\u0341/~")],
types: ["boolean"],
observations: 2,
},
{
path: [property("nested"), element, property("z")],
types: ["boolean"],
observations: 2,
},
{
path: [property("nested"), element, property("é/~")],
types: ["number"],
observations: 2,
},
{
path: [property("nested"), element, property("\uE000")],
types: ["boolean"],
observations: 2,
},
{
path: [property("nested"), element, property("\u{10000}")],
types: ["boolean"],
observations: 2,
},
{ path: "/nested/*/z", types: ["boolean"], observations: 2 },
{ path: "/nested/*/é~1~0", types: ["number"], observations: 2 },
{ path: "/nested/*/\uE000", types: ["boolean"], observations: 2 },
{ path: "/nested/*/\u{10000}", types: ["boolean"], observations: 2 },
],
});
}
@@ -96,7 +170,7 @@ describe("inferJsonShape", () => {
expect(shape?.properties).toHaveLength(5_001);
expect(shape?.node_count).toBe(5_002);
expect(shape?.properties).toContainEqual({
path: "/field_5000",
path: [property("field_5000")],
types: ["number"],
observations: 1,
});
+55 -20
View File
@@ -12,6 +12,12 @@ const jsonValueTypeSchema = z.enum([
]);
type JsonValueType = z.infer<typeof jsonValueTypeSchema>;
const jsonShapePathSegmentSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("property"), name: z.string() }),
z.object({ kind: z.literal("array-element") }),
]);
type JsonShapePathSegment = z.infer<typeof jsonShapePathSegmentSchema>;
/** Value-free structural summary of one approved JSON payload. */
export const jsonShapeSchema = z.object({
root_type: jsonValueTypeSchema,
@@ -19,7 +25,7 @@ export const jsonShapeSchema = z.object({
max_depth_observed: z.number().int().min(0),
properties: z.array(
z.object({
path: z.string(),
path: z.array(jsonShapePathSegmentSchema).min(1),
types: z.array(jsonValueTypeSchema).min(1),
observations: z.number().int().min(1),
}),
@@ -39,13 +45,17 @@ export const inferJsonShape = (text: string): JsonShape | null => {
}
const properties = new Map<
string,
{ readonly types: Set<JsonValueType>; observations: number }
{
readonly path: JsonShapePathSegment[];
readonly types: Set<JsonValueType>;
observations: number;
}
>();
const pending: Array<{
readonly value: unknown;
readonly path: string;
readonly path: JsonShapePathSegment[];
readonly depth: number;
}> = [{ value: root, path: "", depth: 0 }];
}> = [{ value: root, path: [], depth: 0 }];
let nodeCount = 0;
let maxDepthObserved = 0;
while (pending.length > 0) {
@@ -53,11 +63,26 @@ export const inferJsonShape = (text: string): JsonShape | null => {
if (current === undefined) break;
nodeCount += 1;
maxDepthObserved = Math.max(maxDepthObserved, current.depth);
if (current.path.length > 0) {
const key = JSON.stringify(current.path);
const type = jsonValueType(current.value);
const existing = properties.get(key);
if (existing === undefined)
properties.set(key, {
path: current.path,
types: new Set([type]),
observations: 1,
});
else {
existing.types.add(type);
existing.observations += 1;
}
}
if (Array.isArray(current.value)) {
for (let index = current.value.length - 1; index >= 0; index -= 1)
pending.push({
value: current.value[index],
path: `${current.path}/*`,
path: [...current.path, { kind: "array-element" }],
depth: current.depth + 1,
});
continue;
@@ -68,15 +93,10 @@ export const inferJsonShape = (text: string): JsonShape | null => {
const entry = allEntries[index];
if (entry === undefined) continue;
const [name, value] = entry;
const path = `${current.path}/${pointerName(name)}`;
const type = jsonValueType(value);
const existing = properties.get(path);
if (existing === undefined)
properties.set(path, { types: new Set([type]), observations: 1 });
else {
existing.types.add(type);
existing.observations += 1;
}
const path: JsonShapePathSegment[] = [
...current.path,
{ kind: "property", name },
];
pending.push({ value, path, depth: current.depth + 1 });
}
}
@@ -84,13 +104,13 @@ export const inferJsonShape = (text: string): JsonShape | null => {
root_type: jsonValueType(root),
node_count: nodeCount,
max_depth_observed: maxDepthObserved,
properties: [...properties.entries()]
.map(([path, value]) => ({
path,
properties: [...properties.values()]
.map((value) => ({
path: value.path,
types: [...value.types].sort(),
observations: value.observations,
}))
.sort((left, right) => compareUnicodeCodePoints(left.path, right.path)),
.sort((left, right) => compareShapePaths(left.path, right.path)),
});
};
@@ -112,5 +132,20 @@ const jsonValueType = (value: unknown): JsonValueType => {
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const pointerName = (value: string): string =>
value.replaceAll("~", "~0").replaceAll("/", "~1");
const compareShapePaths = (
left: readonly JsonShapePathSegment[],
right: readonly JsonShapePathSegment[],
): number => {
for (let index = 0; index < Math.min(left.length, right.length); index += 1) {
const a = left[index];
const b = right[index];
if (a === undefined || b === undefined) break;
const order =
compareUnicodeCodePoints(a.kind, b.kind) ||
(a.kind === "property" && b.kind === "property"
? compareUnicodeCodePoints(a.name, b.name)
: 0);
if (order !== 0) return order;
}
return left.length - right.length;
};
+81 -13
View File
@@ -196,13 +196,7 @@ const compareWebCaptureDimensions = (
sectionsComplete(after, ["resources"]),
"Resource inventory was incomplete in at least one observation.",
),
network: compareDimension(
networkMap(before),
networkMap(after),
sectionsComplete(before, ["network_requests"]) &&
sectionsComplete(after, ["network_requests"]),
"Network capture is attach-window limited or incomplete.",
),
network: networkDimension(before, after),
metadata: compareDimension(
singleton("metadata", digestCanonicalValue(metadataProjection(before))),
singleton("metadata", digestCanonicalValue(metadataProjection(after))),
@@ -229,16 +223,85 @@ const keyed = <T>(
values.map((value) => [identity(value), digestCanonicalValue(value)]),
);
type BodyShapeSources = {
readonly request: boolean;
readonly response: boolean;
};
const bodyShapesSelected = (inspection: WebPageInspection): boolean =>
!inspection.completeness.excluded.some(
({ section, reason }) =>
section === "json_body_shapes" && reason === "not_approved",
) &&
(inspection.network.requests.length === 0 ||
inspection.network.requests.some(
({ body_shapes }) => body_shapes.status !== "not_approved",
));
const networkIdentity = (
request: WebPageInspection["network"]["requests"][number],
): string =>
`net_${digestCanonicalValue({ method: request.method, url: request.url, resource_type: request.resource_type })}`;
const networkDimension = (
before: WebPageInspection,
after: WebPageInspection,
): Dimension => {
const selected = bodyShapesSelected(before) && bodyShapesSelected(after);
const sources = new Map<string, BodyShapeSources>();
if (selected) {
const observedSources = (inspection: WebPageInspection) => {
const result = new Map<string, BodyShapeSources>();
for (const request of inspection.network.requests) {
const identity = networkIdentity(request);
const previous = result.get(identity);
result.set(identity, {
request:
previous?.request !== false && request.body_shapes.request !== null,
response:
previous?.response !== false &&
request.body_shapes.response !== null,
});
}
return result;
};
const left = observedSources(before);
const right = observedSources(after);
for (const [identity, coverage] of left) {
const next = right.get(identity);
sources.set(identity, {
request: coverage.request && next?.request === true,
response: coverage.response && next?.response === true,
});
}
}
const shapesComplete =
!selected ||
[before, after].every(
(inspection) =>
sectionsComplete(inspection, ["json_body_shapes"]) &&
inspection.network.requests.every(
({ body_shapes }) => body_shapes.status === "included",
),
);
return compareDimension(
networkMap(before, sources),
networkMap(after, sources),
sectionsComplete(before, ["network_requests"]) &&
sectionsComplete(after, ["network_requests"]) &&
shapesComplete,
"Network capture or selected JSON body-shape coverage is attach-window limited, unavailable, or incomplete.",
);
};
const networkMap = (
inspection: WebPageInspection,
sources: ReadonlyMap<string, BodyShapeSources>,
): ReadonlyMap<string, string> => {
const grouped = new Map<string, unknown[]>();
for (const request of inspection.network.requests) {
const identity = `net_${digestCanonicalValue({
method: request.method,
url: request.url,
resource_type: request.resource_type,
})}`;
const identity = networkIdentity(request);
const shapes = sources.get(identity);
const values = grouped.get(identity) ?? [];
values.push({
status: request.status,
@@ -252,7 +315,12 @@ const networkMap = (
}) => redirect,
),
initiator: request.initiator,
body_shapes: request.body_shapes,
...(shapes?.request === true
? { request_shape: request.body_shapes.request }
: {}),
...(shapes?.response === true
? { response_shape: request.body_shapes.response }
: {}),
});
grouped.set(identity, values);
}
+4 -3
View File
@@ -6,8 +6,8 @@ import {
browserEndpointSchema,
} from "./browserObservation.js";
import { browserVersionSchema } from "./browserObservationSchemas.js";
import { jsonShapeSchema } from "./jsonShape.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { jsonValueSchema } from "./jsonValue.js";
import { digestSchema, prefixedDigestSchema } from "./../domain/digests.js";
/** Input for passive discovery of page-registered WebMCP tools. */
export const discoverWebMcpToolsInputSchema = z.strictObject({
@@ -28,7 +28,8 @@ const webMcpToolSchema = z.object({
frame_url: z.string(),
owner_origin: z.string(),
declaration_kind: z.enum(["declarative", "imperative"]),
input_schema_shape: jsonShapeSchema.nullable(),
input_schema: jsonValueSchema.nullable(),
input_schema_sha256: digestSchema.nullable(),
annotations: z.object({
read_only: z.boolean().nullable(),
untrusted_content: z.boolean().nullable(),