merge: preserve current MCP paging contracts in organized documentation

Retain list_unknowns paging guidance in docs/reference/mcp-contracts.md and verify the public routes and affected MCP regressions.

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
Matheus Breguêz
2026-10-12 21:24:41 -03:00
co-authored by Codex
54 changed files with 1778 additions and 285 deletions
@@ -0,0 +1,158 @@
import { createServer } from "node:http";
import type { RequestListener, Server } from "node:http";
import { afterEach, describe, expect, it } from "vitest";
import { readCdpJson } from "../../../src/browser/CdpEndpoint.js";
const servers: Server[] = [];
afterEach(async () => {
await Promise.all(
servers.splice(0).map(
(server) =>
new Promise<void>((resolve, reject) => {
server.closeAllConnections();
server.close((error) =>
error === undefined ? resolve() : reject(error),
);
}),
),
);
});
describe("CDP discovery response bounds", () => {
it("accepts a complete JSON response exactly at the byte limit", async () => {
const body = JSON.stringify("x".repeat(14));
expect(Buffer.byteLength(body)).toBe(16);
const server = await startServer((_request, response) =>
response.end(body),
);
await expect(
readCdpJson(server.url, "list_browser_targets", undefined, {
bytes: 16,
timeoutMs: 1_000,
}),
).resolves.toBe("x".repeat(14));
});
it("rejects and closes an oversized chunked response without parsing a prefix", async () => {
let responseClosed: (() => void) | undefined;
const closed = new Promise<void>((resolve) => {
responseClosed = resolve;
});
const server = await startServer((_request, response) => {
response.once("close", () => responseClosed?.());
response.write(JSON.stringify("x".repeat(15)));
});
await expect(
readCdpJson(server.url, "list_browser_targets", undefined, {
bytes: 16,
timeoutMs: 1_000,
}),
).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "payload_limit",
});
await closed;
});
it("ends a response that exceeds the total elapsed deadline", async () => {
let responseClosed: (() => void) | undefined;
let requestStarted: (() => void) | undefined;
const closed = new Promise<void>((resolve) => {
responseClosed = resolve;
});
const started = new Promise<void>((resolve) => {
requestStarted = resolve;
});
const server = await startServer((_request, response) => {
response.once("close", () => responseClosed?.());
requestStarted?.();
});
const pending = readCdpJson(server.url, "list_browser_targets", undefined, {
bytes: 16,
timeoutMs: 50,
});
const timeoutAssertion = expect(pending).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "timeout",
});
await started;
await timeoutAssertion;
await closed;
});
it("preserves caller cancellation and closes the response", async () => {
let responseClosed: (() => void) | undefined;
let requestStarted: (() => void) | undefined;
const closed = new Promise<void>((resolve) => {
responseClosed = resolve;
});
const started = new Promise<void>((resolve) => {
requestStarted = resolve;
});
const server = await startServer((_request, response) => {
response.once("close", () => responseClosed?.());
requestStarted?.();
});
const controller = new AbortController();
const pending = readCdpJson(
server.url,
"list_browser_targets",
controller.signal,
{
bytes: 16,
timeoutMs: 1_000,
},
);
await started;
controller.abort();
await expect(pending).rejects.toMatchObject({
_tag: "AnalysisCancelledError",
operation: "list_browser_targets",
});
await closed;
});
it("destroys an unsuccessful HTTP response", async () => {
let responseClosed: (() => void) | undefined;
const closed = new Promise<void>((resolve) => {
responseClosed = resolve;
});
const server = await startServer((_request, response) => {
response.once("close", () => responseClosed?.());
response.writeHead(503).flushHeaders();
});
await expect(
readCdpJson(server.url, "list_browser_targets", undefined, {
bytes: 16,
timeoutMs: 1_000,
}),
).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "invalid_endpoint_response",
});
await closed;
});
});
const startServer = async (
handler: RequestListener,
): Promise<{ readonly url: URL }> => {
const server = createServer(handler);
servers.push(server);
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (address === null || typeof address === "string")
throw new TypeError("Expected a TCP listener address");
return { url: new URL(`http://127.0.0.1:${String(address.port)}`) };
};
@@ -227,6 +227,9 @@ describe("case-distinct APK resource names", () => {
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
});
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
});
@@ -234,6 +237,13 @@ describe("case-distinct APK resource names", () => {
requireSuccessfulProjection(result).normalized_result,
);
expect(projection.root_format).toBe("apk");
expect(projection.coverage).toEqual({
status: "partial",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
);
expect(projection.components.manifests).toHaveLength(1);
expect(projection.components.dex).toHaveLength(1);
expect(JSON.stringify(inventory)).toContain("res/2F.xml");
@@ -75,6 +75,42 @@ async function createCompleteAppleProjection() {
}
describe("Apple application projection", () => {
it("keeps a case-colliding real IPA inventory partial", async () => {
const root = await createTestTempDirectory("rea-apple-case-collision-");
const path = join(root, "CaseCollision.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"Payload/Example.app/Contents/Info.plist",
new TextReader("upper"),
);
await writer.add(
"Payload/Example.app/contents/Info.plist",
new TextReader("lower"),
);
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
});
const result = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
});
const projection = appleApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(result).normalized_result,
);
expect(projection.coverage).toEqual({
status: "partial",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
);
});
it("projects deterministic IPA components and bridge hypotheses from exact inventory Evidence", async () => {
const root = await createTestTempDirectory("rea-apple-");
const path = join(root, "Fixture.ipa");
@@ -172,6 +172,9 @@ describe("artifact inventory coverage", () => {
authority: "shipped-artifact",
},
);
expect(parseArtifactInventoryEvidence(partial).inventory.complete).toBe(
true,
);
expect(compareArtifacts(partial, partial)).toMatchObject({
status: "unknown",
summary: { unchanged: 0, unknown: 1 },
@@ -20,6 +20,7 @@ import {
} from "../../../src/application/AppBundleExecutable.js";
import {
dosMz,
elf,
fat,
pe,
thinMach,
@@ -846,3 +847,40 @@ describe("DOS binary target I/O", () => {
});
});
});
it.each([
[
"EI_VERSION",
(bytes: Buffer) => {
bytes[6] = 0;
},
],
[
"e_version",
(bytes: Buffer) => {
bytes.writeUInt32LE(0, 20);
},
],
[
"e_ehsize",
(bytes: Buffer) => {
bytes.writeUInt16LE(51, 40);
},
],
])(
"rejects an ELF with malformed %s during public target opening",
async (_name, corrupt) => {
const directory = await createTestTempDirectory("rea-invalid-elf-header-");
const path = join(directory, "invalid.elf");
const bytes = elf(1, 1, 3);
corrupt(bytes);
await writeFile(path, bytes);
expect(await parseBinaryTarget(path)).toMatchObject({
ok: false,
error: {
_tag: "BinaryTargetError",
constraint: "file_format_rejected",
},
});
},
);
@@ -214,6 +214,34 @@ describe("HarmonyOS packaging boundaries", () => {
});
describe("HarmonyOS inventory coverage", () => {
it("keeps a case-colliding inventory partial in the application projection", async () => {
const path = await writeApplicationZip(
"rea-harmony-case-collision-",
"Fixture.hap",
[
{ path: "module.json", content: '{"module":{}}' },
{ path: "MODULE.JSON", content: '{"module":{}}' },
],
);
const inventory = await inventoryApplicationPackage(path);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
});
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(projection.coverage).toEqual({
status: "partial",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
);
});
it.each(ZIP_PACKAGE_FORMATS)(
"retains archive identity and ZIP coverage for %s",
async (format) => {
-5
View File
@@ -227,11 +227,6 @@ it("rejects ELF header tables overlapping the native header", () => {
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(
/header|overlap/i,
);
const declaredSize = createGoBinaryFixture();
declaredSize.bytes.writeUInt16LE(8192, 52);
expect(() => readGoBinaryImage(declaredSize.bytes)).toThrowError(
/truncated|range/i,
);
});
it("rejects contradictory aliases when a metadata address maps to different file bytes", () => {
@@ -4,6 +4,7 @@ import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import type {
AnalysisClient,
AnalysisProvider,
@@ -249,3 +250,158 @@ it("records capture disagreement as a contradicted unknown", async () => {
),
).toEqual(beforeRepeat);
});
it("pages filtered unknown heads through the public MCP contract", async () => {
const session = createTestBinarySession(providerWithCapabilities([]));
const server = createServer({ kind: "session", session });
const client = new Client({ name: "unknown-pagination", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
const created = [
["matching c", "high", "pagination"],
["matching a", "high", "pagination"],
["matching b", "high", "pagination"],
["filtered severity", "medium", "pagination"],
["filtered domain", "high", "other"],
] as const;
for (const [question, severity, domain] of created) {
const result = session.recordUnknown({
question,
severity,
domain,
required_authority: "analyst-inference",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
});
expect(result.ok).toBe(true);
}
const defaultPage = structured(
await client.callTool({ name: "list_unknowns", arguments: {} }),
).result as {
items: { unknown_id: string }[];
total: number;
offset: number;
next_offset: number | null;
};
expect(defaultPage.items.map(({ unknown_id }) => unknown_id)).toEqual(
defaultPage.items.map(({ unknown_id }) => unknown_id).sort(),
);
expect(defaultPage).toMatchObject({ total: 5, offset: 0, next_offset: null });
const detached = session.listUnknownsPage({ limit: 1 });
const detachedHead = detached.items[0];
if (detachedHead === undefined) throw new Error("Expected one unknown head");
const originalQuestion = detachedHead.question;
Reflect.set(detachedHead, "question", "changed outside the ledger");
expect(
session
.listUnknowns()
.find(({ unknown_id }) => unknown_id === detachedHead.unknown_id)
?.question,
).toBe(originalQuestion);
const offsetWithoutLimit = structured(
await client.callTool({
name: "list_unknowns",
arguments: { domain: "pagination", offset: 1 },
}),
).result as typeof defaultPage;
expect(offsetWithoutLimit).toMatchObject({
total: 4,
offset: 1,
next_offset: null,
});
expect(offsetWithoutLimit.items).toHaveLength(3);
const noMatches = structured(
await client.callTool({
name: "list_unknowns",
arguments: { domain: "no-such-domain", limit: 2 },
}),
).result as typeof defaultPage;
expect(noMatches).toMatchObject({
items: [],
total: 0,
offset: 0,
next_offset: null,
});
const beyondEnd = structured(
await client.callTool({
name: "list_unknowns",
arguments: { domain: "pagination", offset: 100, limit: 2 },
}),
).result as typeof defaultPage;
expect(beyondEnd).toMatchObject({
total: 4,
offset: 100,
next_offset: null,
});
expect(beyondEnd.items).toEqual([]);
const maximumSafePage = structured(
await client.callTool({
name: "list_unknowns",
arguments: {
offset: Number.MAX_SAFE_INTEGER,
limit: Number.MAX_SAFE_INTEGER,
},
}),
).result as typeof defaultPage;
expect(maximumSafePage).toMatchObject({
total: 5,
offset: Number.MAX_SAFE_INTEGER,
next_offset: null,
});
expect(maximumSafePage.items).toEqual([]);
const request = {
name: "list_unknowns",
arguments: { domain: "pagination", severity: "high", limit: 2 },
} as const;
const first = structured(await client.callTool(request))
.result as typeof defaultPage;
expect(first).toMatchObject({ total: 3, offset: 0, next_offset: 2 });
expect(first.items).toHaveLength(2);
const second = structured(
await client.callTool({
...request,
arguments: { ...request.arguments, offset: first.next_offset ?? 0 },
}),
).result as typeof defaultPage;
expect(second).toMatchObject({ total: 3, offset: 2, next_offset: null });
expect(second.items).toHaveLength(1);
expect(
[...first.items, ...second.items].map(({ unknown_id }) => unknown_id),
).toEqual(
session
.listUnknowns({ domain: "pagination", severity: "high" })
.map(({ unknown_id }) => unknown_id),
);
expect(
toolContract("list_unknowns").outputSchema.safeParse(
(await client.callTool(request)).structuredContent,
).success,
).toBe(true);
for (const arguments_ of [
{ limit: 0 },
{ offset: -1 },
{ offset: Number.MAX_SAFE_INTEGER + 1 },
{ unexpected: true },
]) {
expect(
(await client.callTool({ name: "list_unknowns", arguments: arguments_ }))
.isError,
).toBe(true);
}
});
@@ -412,7 +412,12 @@ describe("MCP investigation history snapshot replay", () => {
toolContract("list_unknowns").outputSchema.parse(
listed.structuredContent,
).result,
).toEqual({ items: [resolved], total: 1 });
).toEqual({
items: [resolved],
total: 1,
offset: 0,
next_offset: null,
});
},
);
});
@@ -15,6 +15,7 @@ import {
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
import { ArtifactResourceScope } from "../../../../src/artifacts/ArtifactResourceScope.js";
import {
withSignatureTarget,
verifySignatureTarget,
@@ -277,6 +278,7 @@ it("returns typed cancellation at binding entry and final verification", async (
await expect(
withSignatureTarget(
target,
new ArtifactResourceScope(),
async () => {
throw new Error("Cancelled acquisition must not invoke inspection");
},
@@ -286,14 +288,18 @@ it("returns typed cancellation at binding entry and final verification", async (
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
await withSignatureTarget(target, async (binding) => {
const result = await verifySignatureTarget(target, binding, signal);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
return result;
});
await withSignatureTarget(
target,
new ArtifactResourceScope(),
async (binding) => {
const result = await verifySignatureTarget(target, binding, signal);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
return result;
},
);
});
it("preserves cancellation after a capture instead of classifying it as invalid output", async () => {
@@ -348,21 +354,31 @@ it("copies and hashes the same bytes across multiple snapshot chunks", async ()
const bytes = Buffer.alloc(128 * 1024 + 13, 42);
await writeFile(path, bytes);
const target = await nativeMachoTargetForFile(path);
await withSignatureTarget(target, async (binding) => {
expect(await readFile(binding.snapshotPath)).toEqual(bytes);
return verifySignatureTarget(target, binding);
});
await withSignatureTarget(
target,
new ArtifactResourceScope(),
async (binding) => {
expect(await readFile(binding.snapshotPath)).toEqual(bytes);
return verifySignatureTarget(target, binding);
},
);
});
it("cleans the private snapshot when inspection throws", async () => {
const { target } = await fixture();
let snapshotPath: string | undefined;
await expect(
withSignatureTarget(target, async (binding) => {
const result = await withSignatureTarget(
target,
new ArtifactResourceScope(),
async (binding) => {
snapshotPath = binding.snapshotPath;
throw new Error("Invalid parsed output");
}),
).rejects.toThrow("Invalid parsed output");
},
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
if (snapshotPath === undefined) throw new Error("Expected snapshot");
await expect(lstat(dirname(snapshotPath))).rejects.toMatchObject({
code: "ENOENT",