mirror of
https://github.com/morluto/rea.git
synced 2026-11-15 19:23:24 +00:00
* test(mcp): check advertised schemas against a portable dialect in every profile * fix(mcp): re-emit advertised patterns in a portable regex grammar * fix(mcp): present discover_tools input through the selected profile The hot-cold catalog registered discover_tools directly with the SDK, so the default compact input profile still advertised its canonical schema, including page-size defaults clients apply on their own (#5322). Route every listed input schema, transport discovery included, through one server-owned presentation, and pass the selected presentation to the deferred server, which serves recorded tool schemas but not discovery. * fix(mcp): keep the Evidence union on described borrowed inputs borrowEvidenceInput installed its advertised projection on one schema instance. A call site's .describe() rebuilds the schema from its definition, so match_native_functions advertised left and right as unconstrained values in every input profile. Install the projection in the borrowed parser's constructor so derived schemas keep it, for both borrowed inputs and borrowed arrays. * fix(mcp): validate advertised dialect by selected profile * fix(mcp): preserve schema widening through references * feat(mcp): project compact input schemas into the portable advertised dialect One projection (advertisedDialectProjection.ts) owns the compact input advertisement: one type per node, items on every array, string literals as enums, oneOf widened to anyOf, allOf merged, tuples as element unions, exclusive bounds made inclusive, and every keyword outside the dialect dropped. Each rewrite is exact or widening; server validation is unchanged. The root description and sentences for dropped cross-field constraints move to the tool description, which Codex and Zed keep. The compact baseline falls to nullable values only (29), which the dialect cannot express without narrowing an input. The gateway shape repairs (typeArrayItemUnions, hasGatewayIncompatibleShape), the second dependentRequired-to-prose copy and the strict-gateway test denylist are removed; the dialect checker gates the inline presentation instead. * feat(mcp): omit output schemas from tools/list by default No surveyed model API reads an output schema, MCP client validators repeat REA's own result validation, and complete output schemas were about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now resolves to off through one owner (resolveMcpOutputSchemaProfile); compact and full remain selectable. structuredContent is still delivered, and the deferred server serves both off and full from the recorded catalog with the matching recorded identity. Tests and artifact verifiers that validate results against complete advertised output contracts select full explicitly. * docs: describe omitted output schemas as the default in README translations * fix(mcp): select schemas in verification workflows * fix(mcp): refuse zero-padded repeat bounds and record host-specific path patterns * fix(mcp): keep projected schemas permissive * fix(mcp): keep references valid when presentation widens their targets * fix(mcp): keep a single union branch's closure scoped to its properties * fix(mcp): select complete output schemas in the Electron verifier * fix(mcp): select complete output schemas in standalone verifier probes * fix(mcp): keep an allOf member's tuple tail with its own positions * fix(mcp): relax references into negations and conditionals presentation may remove * refactor(contracts): declare root discriminators as typed schema annotations * test(mcp): select the borrowed Evidence contract from its family * fix(mcp): keep astral literals and dynamic references widening in every mode * fix(mcp): omit astral literals and relax untracked references when presentation widens * fix(mcp): select complete output schemas in every verifier transport * fix(mcp): read reference pointers by schema position, not segment spelling * fix(mcp): protect references into collapsing boolean unions and keep referencing branches out of the collapse * fix(mcp): keep reduced schemas open when their root admits names by pattern * test(mcp): keep the reduced-schema pattern case outside the size-limited block * fix(mcp): omit patterns whose classes name astral characters * fix(mcp): decide union collapse and pointer protection from canonical branches * docs(mcp): document non-u astral matching and pin BMP agreement across V8 modes * fix(mcp): keep prototype-named properties as own properties in the dialect projection * test(mcp): select full output schemas in packet and signal schema checks * test(mcp): expect the advertised base64 schema to omit the unbounded pad-bit probe * fix(mcp): protect references into unevaluated keywords lost evaluation removes * fix(mcp): validate the doctor probe reply against the canonical output contract (#10655) * fix(mcp): validate the doctor probe reply against the canonical output contract * test(mcp): replay doctor probe validation under every output profile * test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649) * test(mcp): select full output schemas in HTTP session workflows * fix(mcp): emit stack-safe classes with non-ASCII members and protect draft-07 reference siblings * fix(mcp): protect references into literal siblings of relaxed draft-07 references * feat(mcp): omit output schemas from tools/list by default (#10646) * feat(mcp): omit output schemas from tools/list by default No surveyed model API reads an output schema, MCP client validators repeat REA's own result validation, and complete output schemas were about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now resolves to off through one owner (resolveMcpOutputSchemaProfile); compact and full remain selectable. structuredContent is still delivered, and the deferred server serves both off and full from the recorded catalog with the matching recorded identity. Tests and artifact verifiers that validate results against complete advertised output contracts select full explicitly. * fix(mcp): select schemas in verification workflows * fix(mcp): select complete output schemas in the Electron verifier * fix(mcp): select complete output schemas in standalone verifier probes * fix(mcp): select complete output schemas in every verifier transport * test(mcp): select full output schemas in packet and signal schema checks * fix(mcp): validate the doctor probe reply against the canonical output contract (#10655) * fix(mcp): validate the doctor probe reply against the canonical output contract * test(mcp): replay doctor probe validation under every output profile * test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649) * test(mcp): select full output schemas in HTTP session workflows * fix(mcp): keep the Evidence union on described borrowed inputs (#10597) * fix(mcp): keep the Evidence union on described borrowed inputs borrowEvidenceInput installed its advertised projection on one schema instance. A call site's .describe() rebuilds the schema from its definition, so match_native_functions advertised left and right as unconstrained values in every input profile. Install the projection in the borrowed parser's constructor so derived schemas keep it, for both borrowed inputs and borrowed arrays. * test(mcp): select the borrowed Evidence contract from its family * docs(mcp): admit baseline growth only for restored contract declarations * fix(mcp): state reduced multi-type properties as typed branches, not type lists The reduced fallback derived a property's types and emitted them as a type list, which Gemini, Moonshot and Ark reject. A property whose canonical schema is anyOf string and number therefore traded a typed union for a rejected construct when the inline projection fell back. Emit one type, or anyOf typed branches, so [T, null] becomes the dialect's nullable union. * feat(mcp)!: retire the full schema profiles and declare complete observations as a typed annotation (#10718) * refactor(mcp): declare complete observations as a typed annotation applied only on the wire * test(mcp): compare complete-observation declarations with their owning text * refactor(schema): couple Zod checks with their JSON Schema constraint keywords (#10725) * refactor(schema): couple Zod checks with their JSON Schema constraint keywords * refactor(schema): declare pattern approximations and object output roots as typed annotations (#10754) * refactor(schema): declare pattern approximations and object output roots as typed annotations * fix(schema): refuse pattern declarations JSON Schema cannot state * test(schema): select guided_workflows from its contract family * feat(mcp)!: retire the full input and output schema profiles (#10841) * feat(mcp)!: retire the full input and output schema profiles The compact input presentation is now the only advertised input schema, and output schemas are either omitted (`off`, the default) or bounded (`compact`). Catalog identity, the build-recorded digests and the recorded startup catalog collapse to those presentations: two digest profiles instead of six, one recorded catalog instead of two, and no input dialect baseline. Tests and verifiers that validated replies against listed full output schemas now validate against the canonical output contract, which REA already enforces server-side; tests that asserted canonical input restrictions read the canonical input schema instead of a full listing. BREAKING CHANGE: `REA_MCP_INPUT_SCHEMA_PROFILE=full` and `REA_MCP_OUTPUT_SCHEMA_PROFILE=full` are refused at startup and by `rea setup` with a configuration error naming the setting. Remove the setting from the client registration (or rerun setup with `REA_MCP_INPUT_SCHEMA_PROFILE=compact` / `REA_MCP_OUTPUT_SCHEMA_PROFILE=compact`). `REA_MCP_INPUT_SCHEMA_PROFILE` still accepts `compact`. Server-side validation is unchanged. * test(mcp): validate replies against canonical output contracts at every listed-schema reader tools/list omits output schemas by default, so fixtures, verifiers and the Android analysis runners that read a listed outputSchema now bind the canonical contract instead. connectLocalToolsMcp and advertisedMcpToolSchemas hand the SDK a definition carrying the canonical output schema, so the SDK client and caller-supplied validators check every successful reply. * test(mcp): resolve Android runners' output contracts from the selected repository The Android efficiency runners imported the canonical output-schema helper from the harness checkout while --repository selects the revision under test. Import it from the selected repository, as the runners already do for the SDK and Ajv. * test(mcp): let Android runners compare revisions before the canonical output helper A selected revision without scripts/lib/canonical-output-schema.mjs could not start the Android runners. Choose the output contracts in one harness helper: the selected revision's canonical contracts when it has them, otherwise its listed schemas under the full output profile it still supports. * fix(scripts): keep caller launch settings when the real Hopper verifier builds its server environment The verifier deleted REA_VERIFY_SERVER_COMMAND and REA_VERIFY_SERVER_ARGS_JSON from process.env itself before reading them, so a caller selecting an installed REA command silently ran the checkout's dist/main.js. Copy the environment, as main does, so only the child's environment changes. * test(mcp): validate whole replies against canonical output contracts wherever a listed definition is held tools/list omits output schemas by default and the full output profile is gone, so tests that handed the SDK a listed definition no longer checked complete replies. Attach the canonical output schema with withCanonicalOutputSchema at every held REA tool definition. Environment-served tools (not REA contracts), and the deferred-runtime and doctor tests that exercise per-profile listings, keep their listed definitions. * test(mcp): record the advertised catalog summary without the retired full profiles Retiring the full input and output profiles leaves only the compact input and compact output listings, so the summary drops the full-profile digests and every pattern only the full listings carried. Regenerated with npm run verify:advertised-schemas -- --update-summary.
554 lines
19 KiB
JavaScript
554 lines
19 KiB
JavaScript
#!/usr/bin/env node
|
|
import { canonicalOutputSchema } from "./lib/canonical-output-schema.mjs";
|
|
import assert from "node:assert/strict";
|
|
import {
|
|
requireMcpEvidenceBundle,
|
|
requireMcpOutput,
|
|
requireMcpToolError,
|
|
} from "./lib/mcp-verifier-results.mjs";
|
|
import { estimateTokenCount } from "tokenx";
|
|
import { execFile } from "node:child_process";
|
|
import { createHash } from "node:crypto";
|
|
import { readFile, writeFile, readdir, mkdir, rm } from "node:fs/promises";
|
|
import { isAbsolute, join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { promisify } from "node:util";
|
|
import { Client } from "@modelcontextprotocol/client";
|
|
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
import { PrivateRuntimeRoot } from "../dist/process/PrivateRuntimeRoot.js";
|
|
import { parseEvidence } from "../dist/domain/evidence.js";
|
|
import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs";
|
|
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
|
|
|
|
if (process.platform !== "linux")
|
|
throw new Error(
|
|
"Real packet capture verification requires Linux with util-linux prlimit.",
|
|
);
|
|
if (!isAbsolute(process.env.REA_TSHARK_COMMAND ?? ""))
|
|
throw new Error("Supply absolute REA_TSHARK_COMMAND for TShark 4.x.");
|
|
const entrypoint =
|
|
process.argv[2] ?? fileURLToPath(new URL("./rea.mjs", import.meta.url));
|
|
const run = createVerifierRun();
|
|
const root = await PrivateRuntimeRoot.create({
|
|
prefix: "rea-capture-verifier-",
|
|
});
|
|
const path = join(root.path, "network with spaces.pcap");
|
|
const bluetooth = join(root.path, "bluetooth.pcap");
|
|
const execute = promisify(execFile);
|
|
const environment = {
|
|
...process.env,
|
|
TMPDIR: root.path,
|
|
TMP: root.path,
|
|
TEMP: root.path,
|
|
};
|
|
const client = new Client({ name: "packet-capture-verifier", version: "1" });
|
|
const transport = new StdioClientTransport({
|
|
command: process.execPath,
|
|
args: [entrypoint, "mcp"],
|
|
env: environment,
|
|
stderr: "pipe",
|
|
});
|
|
|
|
// Independently synthesize PCAP bytes; no external captures or device access.
|
|
const pcap = (linktype, packets) => {
|
|
const header = Buffer.alloc(24);
|
|
header.writeUInt32LE(0xa1b2c3d4, 0);
|
|
header.writeUInt16LE(2, 4);
|
|
header.writeUInt16LE(4, 6);
|
|
header.writeUInt32LE(65535, 16);
|
|
header.writeUInt32LE(linktype, 20);
|
|
return Buffer.concat([
|
|
header,
|
|
...packets.flatMap((bytes, i) => {
|
|
const record = Buffer.alloc(16);
|
|
record.writeUInt32LE(1700000000 + i, 0);
|
|
record.writeUInt32LE(bytes.length, 8);
|
|
record.writeUInt32LE(bytes.length, 12);
|
|
return [record, bytes];
|
|
}),
|
|
]);
|
|
};
|
|
const udp = (destination, payload) => {
|
|
const ip = Buffer.from("450000000001000040110000c0000201c0000202", "hex");
|
|
ip.writeUInt16BE(28 + payload.length, 2);
|
|
let checksum = 0;
|
|
for (let i = 0; i < ip.length; i += 2) checksum += ip.readUInt16BE(i);
|
|
while (checksum > 0xffff) checksum = (checksum & 0xffff) + (checksum >>> 16);
|
|
ip.writeUInt16BE(~checksum & 0xffff, 10);
|
|
const header = Buffer.alloc(8);
|
|
header.writeUInt16BE(40000, 0);
|
|
header.writeUInt16BE(destination, 2);
|
|
header.writeUInt16BE(8 + payload.length, 4);
|
|
return Buffer.concat([
|
|
Buffer.from("0200000000020200000000010800", "hex"),
|
|
ip,
|
|
header,
|
|
payload,
|
|
]);
|
|
};
|
|
const dnsQuery = Buffer.from(
|
|
"123401000001000000000000076578616d706c6504746573740000010001",
|
|
"hex",
|
|
);
|
|
const source = pcap(1, [
|
|
udp(5554, Buffer.from("REA")),
|
|
udp(5555, dnsQuery),
|
|
udp(5555, dnsQuery),
|
|
]);
|
|
// LINKTYPE_BLUETOOTH_HCI_H4 = 187; H4 command packet, HCI Reset opcode 0x0c03, no parameters.
|
|
const bluetoothSource = pcap(187, [Buffer.from("01030c00", "hex")]);
|
|
let cases = 0;
|
|
const discoveryMeasurements = [];
|
|
const inheritedAddressSpace = (await readFile("/proc/self/limits", "utf8"))
|
|
.split("\n")
|
|
.find((line) => line.startsWith("Max address space "))
|
|
?.trim()
|
|
.match(/^Max address space\s+(\S+)\s+(\S+)\s+bytes$/u);
|
|
assert.ok(inheritedAddressSpace);
|
|
const expectedAddressSpace = Math.min(
|
|
1073741824,
|
|
...inheritedAddressSpace
|
|
.slice(1)
|
|
.map((value) => (value === "unlimited" ? Infinity : Number(value))),
|
|
);
|
|
|
|
await withVerifierCleanup(async () => {
|
|
await writeFile(path, source);
|
|
await writeFile(bluetooth, bluetoothSource);
|
|
await client.connect(transport);
|
|
const tool = (await client.listTools()).tools.find(
|
|
({ name }) => name === "inspect_packet_capture",
|
|
);
|
|
assert.ok(tool);
|
|
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
|
assert.ok(ajv.validateSchema(tool.inputSchema));
|
|
assert.ok(ajv.validateSchema(canonicalOutputSchema(tool.name)));
|
|
const inspect = async (input) => {
|
|
const response = await client.callTool({
|
|
name: tool.name,
|
|
arguments: input,
|
|
});
|
|
assert.ok(
|
|
ajv.validate(
|
|
canonicalOutputSchema(tool.name),
|
|
response.structuredContent,
|
|
),
|
|
JSON.stringify(ajv.errors),
|
|
);
|
|
const evidence = parseEvidence(
|
|
requireMcpOutput(response, "inspect_packet_capture"),
|
|
);
|
|
const report = evidence.normalized_result;
|
|
assert.equal(
|
|
report.artifact.sha256,
|
|
createHash("sha256")
|
|
.update(await readFile(input.path))
|
|
.digest("hex"),
|
|
);
|
|
assert.equal(report.hardware_acquisition, "not-performed");
|
|
assert.equal(report.limits.address_space_bytes, expectedAddressSpace);
|
|
assert.equal(report.tool.configured_path, process.env.REA_TSHARK_COMMAND);
|
|
assert.equal(
|
|
report.resource_limiter.configured_path,
|
|
process.env.REA_TSHARK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
|
|
);
|
|
assert.ok(
|
|
report.resource_limiter.arguments.includes(
|
|
`--as=${expectedAddressSpace}:${expectedAddressSpace}`,
|
|
),
|
|
);
|
|
assert.equal(report.configuration, "private-empty-personal-profile");
|
|
const flags = Object.entries(input)
|
|
.filter(([key]) => key !== "path")
|
|
.flatMap(([key, value]) =>
|
|
key === "match_limit" && value === null
|
|
? ["--all_matches"]
|
|
: typeof value === "boolean"
|
|
? [value ? `--${key}` : `--no-${key}`]
|
|
: (Array.isArray(value) ? value : [value]).flatMap((item) => [
|
|
`--${key}`,
|
|
String(item),
|
|
]),
|
|
);
|
|
const cli = JSON.parse(
|
|
(
|
|
await execute(
|
|
process.execPath,
|
|
[
|
|
entrypoint,
|
|
"inspect-packet-capture",
|
|
input.path,
|
|
...flags,
|
|
"--format",
|
|
"json",
|
|
],
|
|
{ env: environment, timeout: 60000, maxBuffer: 16 * 1024 * 1024 },
|
|
)
|
|
).stdout,
|
|
);
|
|
const { caller_input_path: callerInputPath, ...cliShared } =
|
|
parseEvidence(cli);
|
|
assert.equal(callerInputPath, input.path);
|
|
assert.equal(Object.hasOwn(evidence, "caller_input_path"), false);
|
|
assert.deepEqual(cliShared, evidence);
|
|
const bundle = requireMcpEvidenceBundle(
|
|
await client.callTool({
|
|
name: "get_evidence_bundle",
|
|
arguments: {},
|
|
}),
|
|
);
|
|
assert.ok(
|
|
bundle.records.some(
|
|
(record) => record.evidence_id === evidence.evidence_id,
|
|
),
|
|
);
|
|
cases++;
|
|
return report;
|
|
};
|
|
for (const two_pass of [true, false]) {
|
|
const report = await inspect({
|
|
path,
|
|
fields: ["ip.addr", "udp.port", "tcp.port"],
|
|
display_filter: "udp.dstport == 5555",
|
|
two_pass,
|
|
});
|
|
assert.deepEqual(
|
|
report.packets.map((p) => p["frame.number"]),
|
|
[["2"], ["3"]],
|
|
);
|
|
assert.deepEqual(report.packets[0]["ip.addr"], ["192.0.2.1", "192.0.2.2"]);
|
|
assert.deepEqual(report.packets[0]["udp.port"], ["40000", "5555"]);
|
|
assert.equal(Object.hasOwn(report.packets[0], "tcp.port"), false);
|
|
assert.equal(report.read_scope, "to-eof");
|
|
}
|
|
const selected = {
|
|
path,
|
|
fields: ["dns.qry.name"],
|
|
decode_as: ["udp.port==5555,dns"],
|
|
display_filter: "dns",
|
|
};
|
|
const dns = await inspect(selected);
|
|
assert.equal(dns.packets.length, 2);
|
|
assert.deepEqual(dns.packets[0]["dns.qry.name"], ["example.test"]);
|
|
const prefix = await inspect({ ...selected, packet_limit: 1 });
|
|
assert.deepEqual(prefix.packets, []);
|
|
assert.equal(prefix.read_scope, "up-to-input-packet-limit");
|
|
const empty = await inspect({
|
|
path,
|
|
fields: ["frame.number"],
|
|
display_filter: "tcp",
|
|
});
|
|
assert.deepEqual(empty.packets, []);
|
|
const pagedPath = join(root.path, "paged.pcap");
|
|
const pagedSource = pcap(
|
|
1,
|
|
Array.from({ length: 120 }, () =>
|
|
udp(5555, Buffer.from("owned paging fixture")),
|
|
),
|
|
);
|
|
await writeFile(pagedPath, pagedSource);
|
|
const page = await inspect({ path: pagedPath, fields: ["ip.addr"] });
|
|
assert.equal(page.packets.length, 50);
|
|
assert.deepEqual(page.output_window, {
|
|
matching_packets: 120,
|
|
returned_packets: 50,
|
|
has_more: true,
|
|
});
|
|
const nextPage = await inspect({
|
|
path: pagedPath,
|
|
fields: ["ip.addr"],
|
|
match_offset: 50,
|
|
match_limit: 40,
|
|
});
|
|
assert.deepEqual(nextPage.packets[0]["frame.number"], ["51"]);
|
|
assert.deepEqual(nextPage.packets.at(-1)["frame.number"], ["90"]);
|
|
const complete = await inspect({
|
|
path: pagedPath,
|
|
fields: ["ip.addr"],
|
|
match_limit: null,
|
|
});
|
|
assert.equal(complete.packets.length, 120);
|
|
assert.equal(complete.output_window.has_more, false);
|
|
assert.deepEqual(await readFile(pagedPath), pagedSource);
|
|
const hci = await inspect({ path: bluetooth, fields: ["bthci_cmd.opcode"] });
|
|
assert.deepEqual(hci.packets[0]["bthci_cmd.opcode"], ["0x0c03"]);
|
|
assert.deepEqual(await readFile(path), source);
|
|
// Exercise the incremental summary workflow against the same owned bytes
|
|
// using real installed Wireshark tools; these inputs are format fixtures.
|
|
const pcapTool = (await client.listTools()).tools.find(
|
|
(t) => t.name === "inspect_pcap_capture",
|
|
);
|
|
assert.ok(pcapTool);
|
|
const pcapAjv = new Ajv2020({ strict: false, validateFormats: false });
|
|
assert.ok(pcapAjv.validateSchema(pcapTool.inputSchema));
|
|
assert.ok(pcapAjv.validateSchema(canonicalOutputSchema(pcapTool.name)));
|
|
for (const capturePath of [path, bluetooth]) {
|
|
const capinfosOutput = (
|
|
await execute(
|
|
process.env.REA_CAPINFOS_COMMAND ?? "capinfos",
|
|
["-M", "-S", "--", capturePath],
|
|
{
|
|
env: { ...environment, LC_ALL: "C", LANG: "C" },
|
|
timeout: 60000,
|
|
maxBuffer: 64 * 1024,
|
|
},
|
|
)
|
|
).stdout;
|
|
// Expected instants come from the independently authored PCAP records above,
|
|
// rather than a second implementation of the product's epoch decoder.
|
|
const captureStartText = /^(?:Earliest|First) packet time:[ \t]*(.+)$/mu
|
|
.exec(capinfosOutput)?.[1]
|
|
?.trim();
|
|
const captureEndText = /^(?:Latest|Last) packet time:[ \t]*(.+)$/mu
|
|
.exec(capinfosOutput)?.[1]
|
|
?.trim();
|
|
const expectedCaptureStart = "2023-11-14T22:13:20.000000Z";
|
|
const expectedCaptureEnd =
|
|
capturePath === path
|
|
? "2023-11-14T22:13:22.000000Z"
|
|
: expectedCaptureStart;
|
|
assert.equal(captureStartText, "1700000000.000000", capinfosOutput);
|
|
assert.equal(
|
|
captureEndText,
|
|
capturePath === path ? "1700000002.000000" : "1700000000.000000",
|
|
capinfosOutput,
|
|
);
|
|
const response = await client.callTool({
|
|
name: pcapTool.name,
|
|
arguments: { path: capturePath, detail: "summary" },
|
|
});
|
|
assert.ok(
|
|
pcapAjv.validate(
|
|
canonicalOutputSchema(pcapTool.name),
|
|
response.structuredContent,
|
|
),
|
|
pcapAjv.errorsText(),
|
|
);
|
|
const summary = parseEvidence(
|
|
requireMcpOutput(response, "inspect_pcap_capture"),
|
|
).normalized_result;
|
|
assert.equal(summary.summary.capture_start, expectedCaptureStart);
|
|
assert.equal(summary.summary.capture_end, expectedCaptureEnd);
|
|
assert.equal(
|
|
summary.summary.target.sha256,
|
|
createHash("sha256")
|
|
.update(await readFile(capturePath))
|
|
.digest("hex"),
|
|
);
|
|
const cli = parseEvidence(
|
|
JSON.parse(
|
|
(
|
|
await execute(
|
|
process.execPath,
|
|
[entrypoint, "inspect-pcap-capture", capturePath, "--json"],
|
|
{ env: environment, timeout: 60000, maxBuffer: 16 * 1024 * 1024 },
|
|
)
|
|
).stdout,
|
|
),
|
|
);
|
|
assert.equal(cli.normalized_result.capture_start, expectedCaptureStart);
|
|
assert.equal(cli.normalized_result.capture_end, expectedCaptureEnd);
|
|
const source = {
|
|
kind: "retained-evidence",
|
|
evidence_id: summary.parent_evidence_id,
|
|
};
|
|
const page = await client.callTool({
|
|
name: "inspect_analysis_view",
|
|
arguments: {
|
|
source,
|
|
view: { kind: "pcap", facet: "protocols", limit: 10 },
|
|
},
|
|
});
|
|
assert.equal(
|
|
parseEvidence(requireMcpOutput(page, "inspect_analysis_view"))
|
|
.normalized_result.parent_evidence_id,
|
|
source.evidence_id,
|
|
);
|
|
cases++;
|
|
}
|
|
|
|
assert.deepEqual(await readFile(bluetooth), bluetoothSource);
|
|
for (const input of [
|
|
{ path, fields: ["frame.number"], display_filter: "this is not a filter" },
|
|
{ path, fields: ["no_such_field"] },
|
|
{
|
|
path,
|
|
fields: ["frame.number"],
|
|
decode_as: ["no_such_protocol==1,unknown"],
|
|
},
|
|
{ path: join(root.path, "absent.pcap"), fields: ["frame.number"] },
|
|
{ path, fields: ["frame.number"], interface: "lo0" },
|
|
]) {
|
|
const response = await client.callTool({
|
|
name: tool.name,
|
|
arguments: input,
|
|
});
|
|
requireMcpToolError(response);
|
|
await client.ping();
|
|
cases++;
|
|
}
|
|
await writeFile(path, "not a capture");
|
|
requireMcpToolError(
|
|
await client.callTool({
|
|
name: tool.name,
|
|
arguments: { path, fields: ["frame.number"] },
|
|
}),
|
|
);
|
|
cases++;
|
|
const discovery = (await client.listTools()).tools.find(
|
|
({ name }) => name === "inspect_packet_fields",
|
|
);
|
|
assert.ok(discovery);
|
|
assert.ok(ajv.validateSchema(discovery.inputSchema));
|
|
assert.ok(ajv.validateSchema(canonicalOutputSchema(discovery.name)));
|
|
const nativeProfile = join(root.path, "native-profile");
|
|
await mkdir(nativeProfile);
|
|
const native = (
|
|
await execute(process.env.REA_TSHARK_COMMAND, ["-G", "fields"], {
|
|
env: { ...environment, WIRESHARK_CONFIG_DIR: nativeProfile },
|
|
timeout: 30000,
|
|
maxBuffer: 32 * 1024 * 1024,
|
|
})
|
|
).stdout;
|
|
await rm(nativeProfile, { recursive: true });
|
|
const nativeLines = native.split(/\r?\n/);
|
|
if (nativeLines.at(-1) === "") nativeLines.pop();
|
|
for (const input of [
|
|
{ query: "usb" },
|
|
{ limit: 1 },
|
|
{ offset: 1, limit: 2 },
|
|
{ kind: "fields", protocol: "usb", query: "idVendor" },
|
|
{ kind: "fields", protocol: "udp", limit: null },
|
|
{ kind: "fields", query: "rea_no_such_field" },
|
|
]) {
|
|
const started = performance.now();
|
|
const response = await client.callTool({
|
|
name: discovery.name,
|
|
arguments: input,
|
|
});
|
|
assert.ok(
|
|
ajv.validate(
|
|
canonicalOutputSchema(discovery.name),
|
|
response.structuredContent,
|
|
),
|
|
JSON.stringify(ajv.errors),
|
|
);
|
|
const evidence = parseEvidence(
|
|
requireMcpOutput(response, "inspect_packet_fields"),
|
|
);
|
|
const report = evidence.normalized_result;
|
|
const kind = input.kind ?? "protocols";
|
|
const query = (input.query ?? "").toLowerCase();
|
|
const expectedMatches = nativeLines.flatMap((line, index) => {
|
|
const columns = line.split("\t");
|
|
if ((kind === "protocols") !== (columns[0] === "P")) return [];
|
|
if (
|
|
input.protocol !== undefined &&
|
|
(columns[0] === "P" ? columns[2] : columns[4]) !== input.protocol
|
|
)
|
|
return [];
|
|
if (
|
|
![
|
|
columns[1],
|
|
columns[2],
|
|
...(columns[0] === "F" ? [columns[7]] : []),
|
|
].some((value) => value.toLowerCase().includes(query))
|
|
)
|
|
return [];
|
|
return [{ sourceLine: index + 1, columns }];
|
|
});
|
|
const offset = input.offset ?? 0;
|
|
const limit = input.limit === null ? undefined : (input.limit ?? 50);
|
|
const expectedPage = expectedMatches.slice(
|
|
offset,
|
|
limit === undefined ? undefined : offset + limit,
|
|
);
|
|
assert.deepEqual(
|
|
report.records.map((record) => record.source_line),
|
|
expectedPage.map((record) => record.sourceLine),
|
|
);
|
|
assert.deepEqual(report.output_window, {
|
|
examined: nativeLines.filter((line) =>
|
|
line.startsWith(kind === "protocols" ? "P\t" : "F\t"),
|
|
).length,
|
|
matching: expectedMatches.length,
|
|
returned: expectedPage.length,
|
|
has_more:
|
|
Math.max(0, expectedMatches.length - offset) > expectedPage.length,
|
|
});
|
|
discoveryMeasurements.push({
|
|
input,
|
|
elapsed_ms: +(performance.now() - started).toFixed(2),
|
|
response_bytes: Buffer.byteLength(JSON.stringify(response)),
|
|
estimated_tokens_one_tool_request_response: estimateTokenCount(
|
|
JSON.stringify(discovery) +
|
|
JSON.stringify(input) +
|
|
JSON.stringify(response),
|
|
),
|
|
});
|
|
for (const record of report.records) {
|
|
const columns = nativeLines[record.source_line - 1].split("\t");
|
|
assert.equal(record.name, columns[1]);
|
|
assert.equal(record.abbreviation, columns[2]);
|
|
assert.equal(record.field_type, columns[0] === "F" ? columns[3] : null);
|
|
assert.equal(
|
|
record.parent_protocol,
|
|
columns[0] === "F" ? columns[4] : null,
|
|
);
|
|
assert.equal(record.description, columns[0] === "F" ? columns[7] : null);
|
|
assert.equal(record.display_base, columns[0] === "F" ? columns[5] : null);
|
|
assert.equal(record.bitmask, columns[0] === "F" ? columns[6] : null);
|
|
}
|
|
if (input.query === "idVendor")
|
|
assert.ok(
|
|
report.records.some(
|
|
(row) =>
|
|
row.abbreviation === "usb.idVendor" &&
|
|
row.field_type === "FT_UINT16",
|
|
),
|
|
);
|
|
if (input.query === "usb")
|
|
assert.ok(report.records.some((row) => row.abbreviation === "usb"));
|
|
if (input.query === "rea_no_such_field")
|
|
assert.equal(report.output_window.matching, 0);
|
|
const flags = Object.entries(input).flatMap(([key, value]) =>
|
|
value === null ? ["--all"] : [`--${key}`, String(value)],
|
|
);
|
|
const cli = JSON.parse(
|
|
(
|
|
await execute(
|
|
process.execPath,
|
|
[entrypoint, "inspect-packet-fields", ...flags, "--format", "json"],
|
|
{ env: environment, timeout: 60000, maxBuffer: 16 * 1024 * 1024 },
|
|
)
|
|
).stdout,
|
|
);
|
|
assert.deepEqual(cli.normalized_result, report);
|
|
cases++;
|
|
}
|
|
await client.close();
|
|
assert.deepEqual((await readdir(root.path)).sort(), [
|
|
"bluetooth.pcap",
|
|
"network with spaces.pcap",
|
|
"paged.pcap",
|
|
]);
|
|
}, [() => client.close(), () => transport.close(), () => root.close()]);
|
|
console.log(
|
|
JSON.stringify(
|
|
{
|
|
status: "passed",
|
|
cases,
|
|
discovery_measurements: discoveryMeasurements,
|
|
measurement_scope:
|
|
"Warm MCP server, fresh TShark processes; tokenx estimates include one advertised tool/request/response, not billed usage. Model-driven selection, CPU and peak process-family memory are unmeasured; no cache/speedup claim.",
|
|
host: `${process.platform}/${process.arch}`,
|
|
scope:
|
|
"real TShark CLI/MCP; synthetic Ethernet/IPv4/UDP/DNS and Bluetooth HCI PCAP; no hardware acquisition",
|
|
...(await completeVerifierRun(run)),
|
|
},
|
|
null,
|
|
2,
|
|
),
|
|
);
|