feat(mcp): derive an API surface view from retained web network captures (#1891)

* feat(mcp): derive an API surface view from retained web network captures

* fix(mcp): fail closed on sensitive parents and budget api-surface path expansion

* fix(mcp): keep recorded api-surface paths and budget only templated segments

* fix(mcp): read api-surface paths only from canonical URLs and charge new values once

* fix(mcp): reject authority-less api-surface URLs and key groups by rule positions

* fix(mcp): label api-surface confidence from all groups and cap transient path memory

* fix(mcp): budget api-surface dedup sets and narrow detail outputs

Charge retained deduplication sets before allocation, advertise only
each analysis operation's summary from its detail output, and document
that any templated group makes every API-surface page inferred.

* fix(mcp): bound api-surface path text and record limitations

Charge retained literal path copies before allocation, publish only
valid media-type essences, and deduplicate examined record limitations
onto the view.

* fix(mcp): keep api-surface refusals and path splits inside the reply budget

Sensitive-parent refusals now use the token sensitive_values_unretained so declared literals are not echoed. A later path split is charged against bytes already retained, and the published example includes the HAR record limitation with its matching digest.

* fix(mcp): budget api-surface method text before group keys

Charge method and origin text against the reply budget before the group key is serialized. Document that samples merge only when method, origin, and exact segment rules match.

* fix(mcp): bound api-surface copies and control-character authorities

Reject authorities containing a tab or newline so WHATWG cannot move userinfo into the recorded path. Charge four path copies, two method and origin copies, and each distinct content type against bytes already retained.

* fix(mcp): preflight combined api-surface group charges

Total path, method, origin, and segment charges before retaining a new group. Track content types in a set so distinct MIME essences are not compared quadratically.

* fix(mcp): charge api-surface content-type sets on first use

Create the per-group content-type set when the first essence is retained, and charge it before allocation. Groups with no content type no longer keep an empty set.

* refactor(analysis): centralize API-surface ownership and admission

Own grouping, deduplication, and combined retained/temporary resource admission in one accumulator. Charge fixed group storage before allocation and materialize only the requested page.

Share recorded URL parsing between capture redaction and projection, preserving source paths and excluding ambiguous credential fields. Cover resource admission invariants and the compiled HAR-to-view workflow.

* fix(analysis): admit capture schema clone before parsing

* fix(javascript): share Electron mutation proof with wrapped calls

* test(mcp): align graph and catalog checks with current contracts

* fix(analysis): admit and validate portable capture views

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Matt Van Horn
2026-10-12 10:44:17 +08:00
committed by GitHub
co-authored by Matt Van Horn Cursor Agent morluto
parent 64b71b180a
commit 880a603fe8
34 changed files with 2533 additions and 189 deletions
+61
View File
@@ -0,0 +1,61 @@
import { expect, it } from "vitest";
import { z } from "zod";
import {
binaryLayoutSummaryViewResultSchema,
javascriptApplicationSummaryViewResultSchema,
projectAnalysisView,
} from "../domain/analysisView/analysisView.js";
import {
analysisViewJavaScriptEvidence,
analysisViewLayoutEvidence,
} from "../../tests/fixtures/analysisView.js";
import { toolContract } from "./toolContracts.js";
const projectSummary = (parent: {
readonly evidence_id: string;
readonly operation: string;
readonly normalized_result: unknown;
readonly limitations: readonly string[];
}) =>
projectAnalysisView(
{
evidenceId: parent.evidence_id,
operation: parent.operation,
normalizedResult: parent.normalized_result,
limitations: parent.limitations,
},
{ kind: "summary" },
);
it("advertises only that operation's summary from analysis detail outputs", () => {
for (const name of [
"inspect_binary_layout",
"analyze_javascript_application",
] as const) {
const schema = JSON.stringify(
z.toJSONSchema(toolContract(name).outputSchema),
);
expect(schema).not.toContain("api-surface");
expect(schema).not.toContain("inspect_web_network_capture");
}
expect(
JSON.stringify(
z.toJSONSchema(toolContract("inspect_analysis_view").outputSchema),
),
).toContain("api-surface");
const layout = projectSummary(analysisViewLayoutEvidence());
const javascript = projectSummary(analysisViewJavaScriptEvidence());
if (!layout.ok || !javascript.ok) throw new Error("Expected summaries");
expect(
binaryLayoutSummaryViewResultSchema.safeParse(layout.value).success,
).toBe(true);
expect(
javascriptApplicationSummaryViewResultSchema.safeParse(javascript.value)
.success,
).toBe(true);
expect(
binaryLayoutSummaryViewResultSchema.safeParse(javascript.value).success,
).toBe(false);
});
+12 -5
View File
@@ -1,6 +1,5 @@
import { z } from "zod";
import { analysisViewResultSchema } from "../domain/analysisView/analysisView.js";
import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
/** Caller-selected delivery of completed analysis Evidence that supports retained views. */
@@ -11,7 +10,15 @@ export const analysisDetailSchema = z
"complete returns the complete analysis Evidence inline. summary retains that complete Evidence in this session and returns its inspect_analysis_view summary; inspect pages, items or facets through normalized_result.parent_evidence_id.",
);
/** Complete analysis Evidence, or the summary view of its retained record. */
export const analysisDetailOutputSchemaOf = <Schema extends z.ZodType>(
analysis: Schema,
) => evidenceResultOf(z.union([analysis, analysisViewResultSchema]));
/**
* Complete analysis Evidence, or that operation's summary view of its retained
* record. Callers pass the summary variant the handler actually returns so the
* advertised output does not accept other view kinds.
*/
export const analysisDetailOutputSchemaOf = <
Analysis extends z.ZodType,
Summary extends z.ZodType,
>(
analysis: Analysis,
summary: Summary,
) => evidenceResultOf(z.union([analysis, summary]));
@@ -0,0 +1,73 @@
/** Generated from the two-request apiSurfaceHar fixture through the HAR decoder and view service. */
export const API_SURFACE_EXAMPLE = {
input: {
source: {
kind: "retained-evidence",
evidence_id:
"ev_9e218c18bc6159ec9c8492a9130c286496fb1b6d9f03ec2f4ea3321ce2b15097",
},
view: {
kind: "api-surface",
offset: 0,
limit: 50,
},
},
output: {
parent_evidence_id:
"ev_9e218c18bc6159ec9c8492a9130c286496fb1b6d9f03ec2f4ea3321ce2b15097",
parent_operation: "inspect_web_network_capture",
parent_digest:
"9e218c18bc6159ec9c8492a9130c286496fb1b6d9f03ec2f4ea3321ce2b15097",
view_digest:
"47c1859b7a86dd10770061767300bdb6ec177a9254e8dc7863d5ea8603343da6",
artifact: {
path: "/fixtures/api-surface.har",
sha256:
"bf58e2c06e55bfe7e0628157c4ad027ce0aeb81a10e8edef8a7f95b8e5f14225",
},
coverage: {
status: "page",
examined: 1,
total: 1,
next_offset: null,
exhausted: true,
},
limitations: [
"Grouping does not establish handler identity, URL-space schemas or causality.",
"HAR text is producer-decoded Unicode. Original body bytes remain unknown unless content explicitly uses valid base64; declared sizes are preserved independently of retained bytes. mitmproxy 12.2.3 SaveHar may report null optional postData.text; that null is retained and omitted only from the upstream validation copy.",
],
unknowns: [],
records: {
examined: 2,
total: 2,
excluded: 0,
},
templated_groups: 1,
groups: [
{
method: "GET",
origin: "https://api.example.test",
path_template: "/users/{numeric}",
templated_segments: [
{
segment_index: 1,
rule: "numeric",
basis: "inferred",
observed_values: ["8812", "9031"],
},
],
record_ordinals: [0, 1],
statuses: [200, 404],
content_types: ["application/json", "text/plain"],
flags: ["mixed-statuses", "mixed-content-types"],
},
],
excluded_records: [],
kind: "api-surface",
view: {
kind: "api-surface",
offset: 0,
limit: 50,
},
},
} as const;
+6 -1
View File
@@ -1,3 +1,4 @@
import { API_SURFACE_EXAMPLE } from "./analysisViewApiSurfaceExample.js";
import {
analysisViewResultSchema,
inspectAnalysisViewInputSchema,
@@ -15,10 +16,14 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_analysis_view"),
kind: "application",
description:
"Inspect selected views of completed binary-layout, JavaScript application or native analyze_function Evidence without repeating analysis. Use an exact same-session retained evidence_id or portable inline Evidence. Select a summary, layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Native views select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.",
"Inspect selected views of completed binary-layout, JavaScript application or native analyze_function Evidence without repeating analysis. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. Use an exact same-session retained evidence_id or portable inline Evidence. Select a summary, layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Native views select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.",
inputSchema: inspectAnalysisViewInputSchema,
outputSchema: evidenceResultOf(analysisViewResultSchema),
examples: [
{
title: "Group requests from retained HAR Evidence",
input: API_SURFACE_EXAMPLE.input,
},
{
title: "Summarize retained JavaScript application Evidence",
input: {
@@ -11,6 +11,7 @@ import {
electronActiveObservationInputSchema,
electronActiveObservationResultSchema,
} from "../../domain/javascript/electronActiveObservation.js";
import { javascriptApplicationSummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
import {
analysisDetailOutputSchemaOf,
analysisDetailSchema,
@@ -34,6 +35,7 @@ export const analyzeJavaScriptApplicationRequestSchema =
});
const applicationOutputSchema = analysisDetailOutputSchemaOf(
javascriptApplicationAnalysisResultSchema,
javascriptApplicationSummaryViewResultSchema,
);
const reconciliationOutputSchema = evidenceResultOf(
javascriptRuntimeReconciliationResultSchema,
@@ -6,6 +6,7 @@ import {
inspectBinaryLayoutInputSchema,
binaryLayoutSchema,
} from "../../domain/native/binaryLayout.js";
import { binaryLayoutSummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
import {
analysisDetailOutputSchemaOf,
analysisDetailSchema,
@@ -46,7 +47,10 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
description:
"Inspect an explicit local binary without launching it as a host process. Returns file-backed section/segment ranges, linked addresses, original symbol/REL/RELA table identities, complete encoded RELR tables and upstream-derived offsets with unknown per-word locations/addends, raw name bytes, dependency/interpreter names and static mitigation inferences inline with artifact SHA-256 Evidence. Initial profile: ELF64 x86-64 little-endian EXEC/DYN/REL on Linux x64 via caller-supplied Python with unchanged pwntools 4.15.0, pyelftools 0.33 and Unicorn 2.1.2. Runtime addresses/library paths, overall relocation inventory completeness and complete derived GOT/PLT coverage remain unknown. Zero executable entry values mean absence; relocatable entries are not applicable. Upstream can emulate PLT instructions with Unicorn for derived static maps. Uses bounded complete output and owned temporary files/processes; malformed, unsupported or oversized objects return no partial success. Select detail summary to retain the complete layout Evidence in this session and receive only its summary view, then inspect sections, symbols, mitigations or linkage with inspect_analysis_view.",
inputSchema: inspectBinaryLayoutRequestSchema,
outputSchema: analysisDetailOutputSchemaOf(binaryLayoutSchema),
outputSchema: analysisDetailOutputSchemaOf(
binaryLayoutSchema,
binaryLayoutSummaryViewResultSchema,
),
examples: [
{
title: "Inspect ELF linked and file layout",
+28
View File
@@ -6,6 +6,34 @@ import { z } from "zod";
import { presentInputJsonSchema } from "./inputSchemaPresentation.js";
import { toolContract } from "./toolContracts.js";
import { toolInputSchemaWithMetadata } from "./toolSchemaMetadata.js";
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "./javascript/javascriptRuntimeReconciliationExample.js";
it.each(["draft-2020-12", "draft-07"] as const)(
"preserves the complete inline Evidence contract before deferred authentication in %s",
(target) => {
const schema = toolInputSchemaWithMetadata(
toolContract("inspect_analysis_view"),
)["~standard"].jsonSchema.input({ target });
const ajv =
target === "draft-2020-12"
? new Ajv2020({ strict: false, validateFormats: false })
: new Ajv({ strict: false, validateFormats: false });
expect(ajv.validateSchema(schema)).toBe(true);
const validate = ajv.compile(schema);
const input = {
source: {
kind: "inline",
evidence: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE,
},
view: { kind: "summary" },
};
expect(validate(input), JSON.stringify(validate.errors)).toBe(true);
expect(
validate({ ...input, source: { kind: "inline", evidence: {} } }),
).toBe(false);
expect(validate({ ...input, source: { kind: "inline" } })).toBe(false);
},
);
describe("advertised input references", () => {
it.each(["draft-2020-12", "draft-07"] as const)(