chore: integrate canonical Evidence changes for MCP error delivery

This commit is contained in:
N0zoM1z0
2026-10-09 12:43:17 +00:00
643 changed files with 12727 additions and 10243 deletions
+12 -6
View File
@@ -17,7 +17,10 @@ import { writeJadxJarInventory } from "./jadxJar.js";
const fixture = fileURLToPath(new URL("./jadx-mcp.mjs", import.meta.url));
/** Real owned subprocess running a synthetic MCP producer, with no module mocks. */
export const createJadxProtocolFixture = async (mode = "normal") => {
export const createJadxProtocolFixture = async (
mode = "normal",
cleanupFailure?: () => boolean,
) => {
const root = await createTestTempDirectory("rea-android-boundary-");
const apk = join(root, "fixture.apk");
const jar = join(root, "fixture.jar");
@@ -64,7 +67,7 @@ export const createJadxProtocolFixture = async (mode = "normal") => {
legacyJavaOptions:
options.env?._JAVA_OPTIONS ?? options.hostEnvironment?._JAVA_OPTIONS,
});
if (mode === "cleanup-failure") {
if (mode === "cleanup-failure" || cleanupFailure !== undefined) {
onTestFinished(async () => {
const supervisor = new ProviderProcessSupervisor({
...spawned,
@@ -77,10 +80,13 @@ export const createJadxProtocolFixture = async (mode = "normal") => {
});
return {
...spawned,
cleanup: async () => ({
cleaned: false,
reason: "injected ownership verification failure",
}),
cleanup: async () =>
(cleanupFailure?.() ?? true)
? {
cleaned: false,
reason: "injected ownership verification failure",
}
: cleanupOwnedProcessGroup(spawned.ownership),
};
}
return spawned;
+2 -1
View File
@@ -1,3 +1,4 @@
import { ok as resultOk } from "../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createTestBinarySession } from "./binarySession.js";
@@ -16,7 +17,7 @@ export interface ApplicationMcpHarness {
export async function createApplicationMcpHarness(): Promise<ApplicationMcpHarness> {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session);
const client = new Client({
+93 -18
View File
@@ -8,7 +8,8 @@ import { HopperStartError } from "../../src/domain/hopperErrors.js";
import type { Result } from "../../src/domain/result.js";
import type {
AnalysisClient,
AnalysisClientFactory,
AnalysisOperation,
AnalysisProviderCandidate,
CapabilityDescriptor,
AnalysisProfileResolution,
AnalysisProfileResolutionOptions,
@@ -16,6 +17,12 @@ import type {
} from "../../src/application/AnalysisProvider.js";
import { BinarySession } from "../../src/application/binary/BinarySession.js";
import { SessionProviderRouter } from "../../src/application/binary/SessionProviderRouter.js";
import { AnalysisProviderRegistry } from "../../src/application/binary/AnalysisProviderRegistry.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../../src/contracts/officialToolContracts.js";
import { ENHANCED_TOOL_CONTRACTS } from "../../src/contracts/enhancedToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "../../src/contracts/native/nativeToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "../../src/contracts/managed/managedToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../../src/contracts/artifactToolContracts.js";
import { err, ok as resultOk } from "../../src/domain/result.js";
import { observed } from "./analysisExecution.js";
@@ -28,22 +35,91 @@ type TestBinarySessionOptions = {
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
};
type TestBinarySessionOptionsOrResolver =
| TestBinarySessionOptions
| TestBinarySessionOptions["resolveAnalysisProfile"];
type FixtureClientFactory = AnalysisProvider["createClient"];
/** Create a focused session around a test-owned provider or client factory. */
export const createTestBinarySession = (
provider: AnalysisProvider | AnalysisClientFactory,
optionsOrResolver?: TestBinarySessionOptionsOrResolver,
): BinarySession => {
const options =
typeof optionsOrResolver === "function"
? { resolveAnalysisProfile: optionsOrResolver }
: (optionsOrResolver ?? {});
return new BinarySession(SessionProviderRouter.single(provider, options));
const FIXTURE_IDENTITY = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
} as const;
const FIXTURE_OPERATIONS: readonly Exclude<AnalysisOperation, "health">[] = [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
...NATIVE_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
].map(({ name }) => name);
/** Declare fixture client operations before composing the production registry route. */
export const createTestProviderRouter = (
provider: AnalysisProvider | FixtureClientFactory,
options: TestBinarySessionOptions = {},
): SessionProviderRouter => {
const declared: AnalysisProvider =
typeof provider === "function"
? {
identity: () => FIXTURE_IDENTITY,
capabilities: () =>
FIXTURE_OPERATIONS.map((operation) => ({
provider: FIXTURE_IDENTITY,
operation,
available: true,
reason: null,
cachePolicy: "live",
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limitations: [],
})),
createClient: provider,
}
: provider;
const resolve =
options.resolveAnalysisProfile ??
declared.resolveAnalysisProfile?.bind(declared);
if (resolve === undefined)
return SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
declared,
]);
const candidate: AnalysisProviderCandidate = {
identity: () => declared.identity(),
capabilities: () => declared.capabilities(),
createClient: (target, profile, context) =>
declared.createClient(target, profile, context),
resolveAnalysisProfile: resolve,
inspectAvailability: () => ({
status: "available",
code: null,
reason: null,
diagnostics: {},
}),
inspectTargetSupport: () => ({
status: "supported",
code: null,
reason: null,
diagnostics: {},
}),
};
return SessionProviderRouter.selectable(
new AnalysisProviderRegistry([candidate]),
[],
);
};
/** Create a focused session with production registry and auxiliary routing. */
export const createTestBinarySession = (
provider: AnalysisProvider | FixtureClientFactory,
options: TestBinarySessionOptions = {},
): BinarySession =>
new BinarySession(createTestProviderRouter(provider, options));
/** Materialize two distinct targets for session lifecycle tests. */
export const createBinarySessionTargets = async (): Promise<
readonly [string, string]
@@ -71,7 +147,6 @@ export const createCacheProvider = (
Promise.resolve(
resultOk({
profile: createAnalysisProfile(identity, { fixture: true }),
compatibility: {},
}),
),
capabilities: () => [
@@ -83,7 +158,7 @@ export const createCacheProvider = (
calls.push(operation);
return Promise.resolve(observed(operation));
},
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}),
};
};
@@ -106,9 +181,9 @@ export class ControllableAnalysisClient implements AnalysisClient {
return this.pendingCall ?? Promise.resolve(observed(null));
}
close(): Promise<void> {
close(): Promise<Result<null, AnalysisError>> {
this.closed += 1;
return Promise.resolve();
return Promise.resolve(resultOk(null));
}
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { silentLogger } from "../../dist/logger.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { BROWSER_TOOL_CONTRACTS } from "../../dist/contracts/browserToolContracts.js";
@@ -22,7 +23,7 @@ if (process.argv[2] === "reversed") {
const { createServer } = await import("../../dist/server/createServer.js");
const config = parseConfig({});
if (!config.ok) throw config.error;
const session = createBinarySession(config.value);
const session = createBinarySession(config.value, silentLogger, {});
const server = createServer(session, session);
const client = new Client({ name: "contract-presentation", version: "1" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+33 -1
View File
@@ -1,3 +1,4 @@
import { parseConfig } from "../../dist/config.js";
import { access, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
@@ -7,6 +8,7 @@ import {
} from "../../dist/application/DirectAnalysis.js";
import { BinarySession } from "../../dist/application/binary/BinarySession.js";
import { SessionProviderRouter } from "../../dist/application/binary/SessionProviderRouter.js";
import { AnalysisProviderRegistry } from "../../dist/application/binary/AnalysisProviderRegistry.js";
import { createAnalysisExecution } from "../../dist/application/AnalysisProvider.js";
import { AnalysisCancelledError } from "../../dist/domain/analysisErrorCore.js";
import { err, ok } from "../../dist/domain/result.js";
@@ -47,11 +49,41 @@ const client = {
await delay(5);
}
await writeFile(join(root, "cleanup-complete"), "complete");
return ok(null);
},
};
const identity = { id: "fixture", name: "Fixture", version: "1" };
const provider = {
identity: () => identity,
capabilities: () =>
["read_bytes", "procedure_address", "inspect_managed_artifact"].map(
(operation) => ({
provider: identity,
operation,
available: true,
reason: null,
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limitations: [],
}),
),
createClient: () => client,
};
const createSession = () =>
new BinarySession(SessionProviderRouter.single(() => client));
new BinarySession(
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
provider,
]),
);
const dependencies = {
readConfiguration: () => parseConfig({}),
createBinarySession: createSession,
createManagedBinarySession: createSession,
};
+18
View File
@@ -16,6 +16,14 @@ interface FakeV8InspectorOptions {
readonly scriptHashes?: readonly string[];
readonly oversizedEventBytes?: number;
readonly contextTransitionCount?: number;
readonly runtimeEvents?: readonly {
readonly method: string;
readonly params: unknown;
}[];
readonly scriptEvents?: readonly {
readonly method: string;
readonly params: unknown;
}[];
readonly additionalTargetUrl?: string;
readonly additionalTargetCount?: number;
readonly closeOnMethod?: string;
@@ -155,6 +163,11 @@ const sendRuntimeEvents = (
socket: WebSocket,
options: FakeV8InspectorOptions,
): void => {
if (options.runtimeEvents !== undefined) {
for (const event of options.runtimeEvents)
socket.send(JSON.stringify(event));
return;
}
socket.send(
JSON.stringify({
method: "Runtime.executionContextCreated",
@@ -181,6 +194,11 @@ const sendScriptEvents = (
socket: WebSocket,
options: FakeV8InspectorOptions,
): void => {
if (options.scriptEvents !== undefined) {
for (const event of options.scriptEvents)
socket.send(JSON.stringify(event));
return;
}
for (const [index, url] of (
options.scriptUrls ?? [options.targetUrl]
).entries())
-247
View File
@@ -1,247 +0,0 @@
const schemaMaps = new Set([
"properties",
"patternProperties",
"dependentSchemas",
]);
const schemaArrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
const schemaChildren = new Set([
"items",
"additionalItems",
"contains",
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"propertyNames",
"not",
"if",
"then",
"else",
]);
const lowerBounds = new Set(["minimum", "exclusiveMinimum"]);
const upperBounds = new Set(["maximum", "exclusiveMaximum"]);
const annotations = new Set([
"title",
"description",
"$comment",
"default",
"examples",
"deprecated",
"readOnly",
"writeOnly",
]);
const scopedKeywords = new Set([
"properties",
"patternProperties",
"additionalProperties",
"items",
"additionalItems",
"prefixItems",
"contains",
"unevaluatedProperties",
"unevaluatedItems",
]);
const record = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const compatibleSibling = (
key: string,
previous: unknown,
value: unknown,
): boolean =>
previous === undefined ||
JSON.stringify(previous) === JSON.stringify(value) ||
annotations.has(key) ||
(typeof previous === "number" &&
typeof value === "number" &&
(lowerBounds.has(key) || upperBounds.has(key)));
const mergeSiblings = (
schema: Record<string, unknown>,
siblings: Record<string, unknown>,
): Record<string, unknown> => {
const merged = { ...schema, ...siblings };
for (const [key, value] of Object.entries(siblings)) {
const previous = schema[key];
if (!compatibleSibling(key, previous, value))
throw new Error(`Conflicting schema reference sibling: ${key}`);
if (typeof previous !== "number" || typeof value !== "number") continue;
if (lowerBounds.has(key)) merged[key] = Math.max(previous, value);
else if (upperBounds.has(key)) merged[key] = Math.min(previous, value);
}
return merged;
};
const normalizeStringIntersection = (
schema: Record<string, unknown>,
): Record<string, unknown> => {
if (
(schema.type !== undefined && schema.type !== "string") ||
!Array.isArray(schema.allOf)
)
return schema;
let requiresString = schema.type === "string";
const validBounds = (value: Record<string, unknown>): boolean =>
["minLength", "maxLength"].every(
(key) =>
!Object.hasOwn(value, key) ||
(typeof value[key] === "number" &&
Number.isInteger(value[key]) &&
value[key] >= 0),
) &&
(!Object.hasOwn(value, "pattern") || typeof value.pattern === "string");
if (!validBounds(schema)) return schema;
const patterns = new Set<string>();
let minimum = typeof schema.minLength === "number" ? schema.minLength : 0;
let maximum =
typeof schema.maxLength === "number" ? schema.maxLength : Infinity;
if (typeof schema.pattern === "string") patterns.add(schema.pattern);
const collect = (child: unknown): boolean => {
if (!record(child) || (child.type !== undefined && child.type !== "string"))
return false;
if (
!validBounds(child) ||
(Object.hasOwn(child, "allOf") && !Array.isArray(child.allOf))
)
return false;
if (child.type === "string") requiresString = true;
if (
Object.keys(child).some(
(key) =>
!["type", "pattern", "minLength", "maxLength", "allOf"].includes(key),
)
)
return false;
if (typeof child.pattern === "string") patterns.add(child.pattern);
if (typeof child.minLength === "number")
minimum = Math.max(minimum, child.minLength);
if (typeof child.maxLength === "number")
maximum = Math.min(maximum, child.maxLength);
return !Array.isArray(child.allOf) || child.allOf.every(collect);
};
if (!schema.allOf.every(collect) || !requiresString) return schema;
const {
allOf: _allOf,
pattern: _pattern,
minLength: _min,
maxLength: _max,
...root
} = schema;
const unique = [...patterns];
return {
...root,
type: "string",
...(minimum > 0 ? { minLength: minimum } : {}),
...(maximum < Infinity ? { maxLength: maximum } : {}),
...(unique.length === 1 ? { pattern: unique[0] } : {}),
...(unique.length > 1
? { allOf: unique.map((pattern) => ({ type: "string", pattern })) }
: {}),
};
};
/** Inline finite local references for representation-independent schema assertions. */
export const inlineLocalJsonSchemaReferences = (
root: Readonly<Record<string, unknown>>,
): unknown => {
const resolve = (reference: string): Record<string, unknown> => {
if (!reference.startsWith("#/"))
throw new Error(`Expected a local schema reference: ${reference}`);
let current: unknown = root;
for (const encoded of reference.slice(2).split("/")) {
const key = encoded.replaceAll("~1", "/").replaceAll("~0", "~");
if (!record(current) || !Object.hasOwn(current, key))
throw new Error(`Missing schema reference: ${reference}`);
current = current[key];
}
if (!record(current))
throw new Error(`Expected a referenced schema object: ${reference}`);
return current;
};
const visit = (value: unknown, active: ReadonlySet<string>): unknown => {
if (!record(value)) return value;
if (typeof value.$ref === "string") {
const { $ref: reference, ...siblings } = value;
if (active.has(reference))
throw new Error(`Recursive schema reference: ${reference}`);
const referenced = resolve(reference);
// Keep declarations in their original evaluation scope.
if (Object.keys(siblings).some((key) => scopedKeywords.has(key)))
return {
allOf: [
visit(referenced, new Set([...active, reference])),
visit(siblings, active),
],
};
return visit(
mergeSiblings(referenced, siblings),
new Set([...active, reference]),
);
}
if (Array.isArray(value.allOf) && value.allOf.length === 1) {
const child = visit(value.allOf[0], active);
const { allOf: _allOf, ...siblings } = value;
if (
record(child) &&
!Object.keys(siblings).some((key) => scopedKeywords.has(key)) &&
Object.entries(siblings).every(([key, entry]) =>
compatibleSibling(key, child[key], entry),
)
) {
return visit(mergeSiblings(child, siblings), active);
}
}
const normalized = { ...value };
if (
typeof normalized.pattern === "string" &&
Array.isArray(normalized.allOf) &&
normalized.allOf.some(
(child: unknown) =>
record(child) && child.pattern === normalized.pattern,
)
)
delete normalized.pattern;
if (
typeof normalized.minimum === "number" &&
typeof normalized.exclusiveMinimum === "number" &&
normalized.exclusiveMinimum >= normalized.minimum
)
delete normalized.minimum;
if (
typeof normalized.maximum === "number" &&
typeof normalized.exclusiveMaximum === "number" &&
normalized.exclusiveMaximum <= normalized.maximum
)
delete normalized.maximum;
return normalizeStringIntersection(
Object.fromEntries(
Object.entries(normalized)
.filter(([key]) => key !== "$defs" && key !== "definitions")
.map(([key, child]) => {
if (schemaMaps.has(key) && record(child))
return [
key,
Object.fromEntries(
Object.entries(child).map(([name, schema]) => [
name,
visit(schema, active),
]),
),
];
if (schemaArrays.has(key) && Array.isArray(child))
return [key, child.map((schema) => visit(schema, active))];
if (schemaChildren.has(key))
return [
key,
Array.isArray(child)
? child.map((schema) => visit(schema, active))
: visit(child, active),
];
return [key, child];
}),
),
);
};
return visit(root, new Set());
};
+65
View File
@@ -0,0 +1,65 @@
import { readFileSync } from "node:fs";
import type { ToolAnnotations } from "@modelcontextprotocol/server";
import type { CapabilityDescriptor } from "../../src/application/AnalysisProvider.js";
import type { ToolKind } from "../../src/contracts/toolContractTypes.js";
import type { ToolEffects } from "../../src/contracts/toolEffects.js";
interface GeneratedTool {
readonly name: string;
readonly analysisOperation: CapabilityDescriptor["operation"] | null;
readonly title: string;
readonly description: string;
readonly kind: ToolKind;
readonly requiresSession: boolean;
readonly inputSchema: Readonly<Record<string, unknown>>;
readonly outputSchema: Readonly<Record<string, unknown>>;
readonly annotations: ToolAnnotations;
readonly effects: ToolEffects;
}
interface GeneratedPayload {
readonly catalog: readonly GeneratedTool[];
}
const generatedPayload: unknown = JSON.parse(
readFileSync(
new URL("../../.cache/mcp-tool-catalog.json", import.meta.url),
"utf8",
),
);
if (!isGeneratedPayload(generatedPayload))
throw new TypeError(
"Generated MCP catalog payload is invalid; run npm run mcp-catalog:generate",
);
/** Canonical schemas advertised through the pinned MCP SDK. */
export const GENERATED_MCP_TOOL_CATALOG = generatedPayload.catalog;
function isGeneratedPayload(value: unknown): value is GeneratedPayload {
return (
isRecord(value) &&
Array.isArray(value.catalog) &&
value.catalog.every(isGeneratedTool)
);
}
function isGeneratedTool(value: unknown): value is GeneratedTool {
return (
isRecord(value) &&
typeof value.name === "string" &&
(typeof value.analysisOperation === "string" ||
value.analysisOperation === null) &&
typeof value.title === "string" &&
typeof value.description === "string" &&
typeof value.kind === "string" &&
typeof value.requiresSession === "boolean" &&
isRecord(value.inputSchema) &&
isRecord(value.outputSchema) &&
isRecord(value.annotations) &&
isRecord(value.effects)
);
}
function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+2 -2
View File
@@ -66,9 +66,9 @@ export const optionalObservationFactories = (
};
return {
browserObservation: async () => browser,
browserScenarioCapture: async () => createBrowserScenarioProvider(),
browserScenarioCapture: async () => createBrowserScenarioProvider({}),
electronObservation: async () => createElectronObservationProvider(),
electronActiveObservation: async () => createElectronScenarioProvider(),
electronActiveObservation: async () => createElectronScenarioProvider({}),
javascriptRuntimeObservation: async () => runtime,
};
};