feat(jeb): add JEB engine provider over its MCP interface (#1536)
* feat(jeb): add JEB engine provider over its MCP interface
Add a bring-your-own JEB provider that serves project, unit, and
decompilation inspection from a caller-started JEB client speaking MCP
(streamable HTTP, selected with REA_JEB_MCP_URL). Expose four provider-neutral
operations through shared CLI/MCP workflows: inspect_jeb_client,
open_jeb_project, list_jeb_units, and decompile_jeb_item, each returning
Evidence with engine identity, endpoint, and preserved refusal reasons.
The adapter keeps JEB's envelope semantics: success fields are parsed
format-aware at the boundary, message-only refusals become unsupported-target
errors with the engine's own reason, transport failures become availability
failures with recovery guidance, and unit pagination derives coverage from the
engine's 100-item page cap. Explicit unknowns (implicitly selected unit,
omitted filters) are reported instead of guessed.
Verified against a real JEB 5.48.0 licensed build serving jeb-mcp-server 1.3.0
headless: client inspection, unit listing, and method decompilation were
exercised through the CLI, MCP boundary, and scripts/verify-jeb.mjs.
JEB 5.48.0 headless instances do not advertise open_project; the refusal is
preserved and documented.
* fix(jeb): verify against a real signed APK and fix CLI option surface
Verify the provider against a locally built, v1/v2/v3-signed probe APK
(binary manifest, classes.dex with a launcher activity) on JEB 5.48.0: the
full unit tree (apk, manifest, three certificate units, dex bytecode,
decompiler), wildcard-filtered and paginated unit listing with derived
coverage, parent-restricted listing, and launcher-activity method
decompilation through both CLI and MCP, including dexdec's inline
constant folding of the probe's obfuscated tag.
Move list-jeb-units filter/pagination and decompile-jeb-item unit selection
from positional arguments to options; the MCP schemas are unchanged.
* fix(jeb): preserve engine refusals through the real MCP boundary
Testing against the published Signal 8.30.3 universal APK exposed a boundary
bug the scripted provider tests missed: decodeJebToolResult raised a protocol
error for isError results before the provider could map JEB's
{success:false, message} envelope, so real engine refusals surfaced as
unreadable output instead of the engine's own reason. Decode refusal
envelopes like any structured result and let the provider preserve the
reason; cover the decoder directly, including contentless and unparseable
results.
Signal verification: full 109 MB R8/Kotlin/Compose APK with four signature
schemes and native arm64 ELF units parsed; MainActivity.onCreate and R8
synthetic lambdas decompiled through CLI and MCP; paginated, filtered, and
parent-restricted unit listing; refusal path confirmed on the live engine.
* docs(jeb): record Flutter Gallery verification on the real-engine lane
Verify the provider against the official Flutter Gallery 2.9.2 release APK
(112 MB): per-ABI libapp.so Dart AOT snapshot images analyzed as native code
with 75k methods on arm64, snapshot internals and wrapper methods decompiled
through both CLI and MCP with explicit unit selection, decoded manifest, and
filtered native-library unit discovery. Note that JEB 5.48.0 headless does
not expose the dedicated Dart snapshot processor or run_script; both remain
GUI-only engine surfaces.
* docs(jeb): translate the README JEB row for every supported language
The JEB row was inserted in English across all translated READMEs; each now
carries its own label, capability summary, requirements, and guide link
following that language's Android-row conventions.
* fix(jeb): enforce local endpoints and preserve cancellation
* fix(jeb): refuse redirects across the local MCP boundary
---------
Co-authored-by: REA Contributor <contributor@rea.tools>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
co-authored by
REA Contributor
morluto
parent
ded59689ce
commit
749e58772a
@@ -40,6 +40,7 @@ export type AvailabilityPolicy = {
|
||||
readonly firmwareInspectionEnabled?: boolean;
|
||||
readonly firmwareExtractionEnabled?: boolean;
|
||||
readonly androidAnalysisAvailability?: ProviderAvailability;
|
||||
readonly jebAnalysisAvailability?: ProviderAvailability;
|
||||
readonly javascriptRecoveryEnabled?: boolean;
|
||||
readonly webModuleResolutionEnabled?: boolean;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
@@ -356,6 +357,15 @@ const workflowAvailabilityFor = ({
|
||||
policy.androidAnalysisAvailability?.reason ??
|
||||
"Set REA_JADX_MCP_JAR to a caller-supplied jadx-headless-mcp 0.7.1 JAR and provide a full JDK on Linux, macOS, or Windows x64 with its matching bundled native controls.",
|
||||
};
|
||||
if (kind === "jeb-provider")
|
||||
return policy.jebAnalysisAvailability?.status === "available"
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
policy.jebAnalysisAvailability?.reason ??
|
||||
"Start a JEB client serving MCP (GUI client, or headless via its programmatic launcher) and point REA_JEB_MCP_URL at it (default http://127.0.0.1:8425/mcp). REA does not install or launch JEB.",
|
||||
};
|
||||
const browser = browserProviderAvailability(name, kind, policy);
|
||||
if (browser !== null) return browser;
|
||||
if (name === "capture_process_scenario" && !policy.processCaptureEnabled)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
ProviderAvailability,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { JebRequest } from "../../domain/jeb/jebAnalysis.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/**
|
||||
* JEB inspection boundary served by a caller-supplied running engine client.
|
||||
* Implementation details belong to the provider adapter.
|
||||
*/
|
||||
export interface JebAnalysisPort {
|
||||
/** Probe the running JEB client without opening a project. */
|
||||
inspectAvailability(signal?: AbortSignal): Promise<ProviderAvailability>;
|
||||
/** Release engine connection state; the JEB client itself keeps running. */
|
||||
close(): Promise<void>;
|
||||
execute(
|
||||
request: JebRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { JebAnalysisService } from "./JebAnalysisService.js";
|
||||
import type { JebAnalysisPort } from "./JebAnalysisPort.js";
|
||||
import type { JebRequest } from "../../domain/jeb/jebAnalysis.js";
|
||||
import { createAnalysisExecution } from "../AnalysisProvider.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
|
||||
const identity = { id: "jeb", name: "JEB", version: "5.48.0" } as const;
|
||||
|
||||
const fakePort = (
|
||||
requests: JebRequest[],
|
||||
outcome: ReturnType<typeof ok> | ReturnType<typeof err> = ok(
|
||||
createAnalysisExecution({ observed: true }, identity, {
|
||||
limitations: ["engine-side analysis"],
|
||||
}),
|
||||
),
|
||||
): JebAnalysisPort => ({
|
||||
async inspectAvailability() {
|
||||
return {
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: {},
|
||||
};
|
||||
},
|
||||
async close() {},
|
||||
async execute(request) {
|
||||
requests.push(request);
|
||||
return outcome as Result<
|
||||
ReturnType<typeof createAnalysisExecution>,
|
||||
AnalysisError
|
||||
>;
|
||||
},
|
||||
});
|
||||
|
||||
describe("JebAnalysisService admission", () => {
|
||||
it("rejects malformed input before any provider call", async () => {
|
||||
const requests: JebRequest[] = [];
|
||||
const service = new JebAnalysisService(fakePort(requests));
|
||||
const result = await service.execute("list_jeb_units", {
|
||||
count: 101,
|
||||
index: -1,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toBeInstanceOf(AnalysisInputError);
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns cancellation without provider effects when already aborted", async () => {
|
||||
const requests: JebRequest[] = [];
|
||||
const service = new JebAnalysisService(fakePort(requests));
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const result = await service.execute(
|
||||
"inspect_jeb_client",
|
||||
{},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("applies protocol defaults and composes provider evidence", async () => {
|
||||
const requests: JebRequest[] = [];
|
||||
const service = new JebAnalysisService(fakePort(requests));
|
||||
const result = await service.execute("list_jeb_units", {});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(requests[0]?.operation).toBe("list_jeb_units");
|
||||
const request = requests[0];
|
||||
if (request?.operation !== "list_jeb_units") return;
|
||||
expect(request.input.index).toBe(0);
|
||||
expect(request.input.count).toBe(100);
|
||||
expect(result.value.normalized_result).toEqual({ observed: true });
|
||||
expect(result.value.parameters).toEqual({ index: 0, count: 100 });
|
||||
expect(result.value.limitations).toContain("engine-side analysis");
|
||||
expect(result.value.provider.id).toBe("jeb");
|
||||
});
|
||||
|
||||
it("preserves provider failure reasons", async () => {
|
||||
const service = new JebAnalysisService(
|
||||
fakePort([], err(new AnalysisCancelledError("open_jeb_project"))),
|
||||
);
|
||||
const result = await service.execute("open_jeb_project", {
|
||||
path: "/tmp/Example.apk",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { JebAnalysisPort } from "./JebAnalysisPort.js";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import {
|
||||
jebRequestSchema,
|
||||
type JebOperation,
|
||||
} from "../../domain/jeb/jebAnalysis.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { jsonObjectSchema } from "../../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
|
||||
/** Shared CLI/MCP admission, execution and Evidence composition for JEB. */
|
||||
export class JebAnalysisService {
|
||||
constructor(readonly provider: JebAnalysisPort) {}
|
||||
|
||||
/** Run one caller-selected JEB request and retain engine provenance inline. */
|
||||
async execute(
|
||||
operation: JebOperation,
|
||||
input: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const request = jebRequestSchema.safeParse({ operation, input });
|
||||
if (!request.success)
|
||||
return err(new AnalysisInputError(operation, { cause: request.error }));
|
||||
const executed = await this.provider.execute(request.data, options);
|
||||
if (!executed.ok) return executed;
|
||||
const execution = executed.value;
|
||||
return ok(
|
||||
createEvidence(execution.subject ?? undefined, execution.provider, {
|
||||
operation,
|
||||
parameters: jsonObjectSchema.parse(request.data.input),
|
||||
result: execution.result,
|
||||
rawResult: execution.rawResult,
|
||||
limitations: execution.limitations,
|
||||
locations: execution.locations,
|
||||
confidence: operation === "decompile_jeb_item" ? "derived" : "observed",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { registerArtifactCommands } from "./cli/artifactCommands.js";
|
||||
import { registerManagedCommands } from "./cli/managedCommands.js";
|
||||
import { registerFirmwareCommands } from "./cli/firmwareCommands.js";
|
||||
import { registerAndroidCommands } from "./cli/androidCommands.js";
|
||||
import { registerJebCommands } from "./cli/jebCommands.js";
|
||||
import { registerAdbCommands } from "./cli/adbCommands.js";
|
||||
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
|
||||
import { registerProcessCommands } from "./cli/processCommands.js";
|
||||
@@ -74,6 +75,7 @@ export const createCli = (
|
||||
registerArtifactCommands(cli, logger, analysis.runProviderAnalysis);
|
||||
registerManagedCommands(cli, logger, analysis.runProviderAnalysis);
|
||||
registerAndroidCommands(cli, logger, environment);
|
||||
registerJebCommands(cli, logger, environment);
|
||||
registerAdbCommands(cli, logger, environment);
|
||||
registerFirmwareCommands(cli, logger, environment);
|
||||
registerBinaryDiagnosticsCommands(cli, logger, environment);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { z } from "incur";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { JebAnalysisService } from "../application/jeb/JebAnalysisService.js";
|
||||
import type { JebAnalysisPort } from "../application/jeb/JebAnalysisPort.js";
|
||||
import { createJebAnalysisProvider } from "../composition/jeb.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { JebOperation } from "../domain/jeb/jebAnalysis.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** Expose the same explicit JEB requests through one-shot CLI commands. */
|
||||
export const registerJebCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
provider: JebAnalysisPort = createJebAnalysisProvider(environment),
|
||||
): void => {
|
||||
const service = new JebAnalysisService(provider);
|
||||
const execute = (name: string, operation: JebOperation, input: unknown) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, name, async () => {
|
||||
const result = await service.execute(operation, input, { signal });
|
||||
try {
|
||||
await provider.close();
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisError)
|
||||
return projectAnalysisError(cause);
|
||||
throw cause;
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
);
|
||||
|
||||
cli.command(CLI_COMMANDS.inspectJebClient, {
|
||||
description: "Inspect the running JEB MCP client without opening a target",
|
||||
args: z.object({}),
|
||||
run: () => execute(CLI_COMMANDS.inspectJebClient, "inspect_jeb_client", {}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.openJebProject, {
|
||||
description:
|
||||
"Open or create a JEB project from an artifact or .jdb2 database",
|
||||
args: z.object({
|
||||
path: z
|
||||
.string()
|
||||
.describe("Artifact or .jdb2 path resolved by the JEB engine host"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
execute(CLI_COMMANDS.openJebProject, "open_jeb_project", args),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.listJebUnits, {
|
||||
description: "List JEB project units by path and type with optional filter",
|
||||
args: z.object({}),
|
||||
options: z.object({
|
||||
filter: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Wildcard filter matched against unit paths"),
|
||||
"parent-unit-path": z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Restrict results to descendants of this unit path"),
|
||||
index: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.default(0)
|
||||
.describe("Zero-based index of the first result to return"),
|
||||
count: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.default(100)
|
||||
.describe("Maximum results; the engine caps unit pages at 100"),
|
||||
}),
|
||||
run: ({ options }) =>
|
||||
execute(CLI_COMMANDS.listJebUnits, "list_jeb_units", {
|
||||
index: options.index,
|
||||
count: options.count,
|
||||
...(options.filter === undefined ? {} : { filter: options.filter }),
|
||||
...(options["parent-unit-path"] === undefined
|
||||
? {}
|
||||
: { parent_unit_path: options["parent-unit-path"] }),
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.decompileJebItem, {
|
||||
description: "Decompile one JEB type or method to engine pseudo-code",
|
||||
args: z.object({
|
||||
"item-address": z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Type or method address within the unit"),
|
||||
"item-kind": z
|
||||
.enum(["type", "method"])
|
||||
.describe("Kind of item to decompile"),
|
||||
}),
|
||||
options: z.object({
|
||||
"unit-path": z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
"Target code unit; the engine's first code unit when omitted",
|
||||
),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
execute(CLI_COMMANDS.decompileJebItem, "decompile_jeb_item", {
|
||||
item_address: args["item-address"],
|
||||
item_kind: args["item-kind"],
|
||||
...(options["unit-path"] === undefined
|
||||
? {}
|
||||
: { unit_path: options["unit-path"] }),
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -74,6 +74,10 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
inspectAndroidClass: "inspect-android-class",
|
||||
inspectAndroidMethod: "inspect-android-method",
|
||||
traceAndroidReferences: "trace-android-references",
|
||||
inspectJebClient: "inspect-jeb-client",
|
||||
openJebProject: "open-jeb-project",
|
||||
listJebUnits: "list-jeb-units",
|
||||
decompileJebItem: "decompile-jeb-item",
|
||||
inspectManagedMembers: "inspect-managed-members",
|
||||
inspectManagedNativeBoundaries: "inspect-managed-native-boundaries",
|
||||
compareManagedMembers: "compare-managed-members",
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { JebAnalysisPort } from "../application/jeb/JebAnalysisPort.js";
|
||||
import type { JebMcpConnectionFactory } from "../jeb/JebMcpConnection.js";
|
||||
import { JebProvider } from "../jeb/JebProvider.js";
|
||||
|
||||
/** Construct one JEB provider bound to the caller-selected MCP endpoint. */
|
||||
export const createJebAnalysisProvider = (
|
||||
environment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
connectionFactory?: JebMcpConnectionFactory,
|
||||
): JebAnalysisPort =>
|
||||
new JebProvider({
|
||||
environment,
|
||||
...(connectionFactory === undefined ? {} : { connectionFactory }),
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { JEB_TOOL_CONTRACTS } from "./jebToolContracts.js";
|
||||
import { TOOL_CONTRACTS } from "../toolContracts.js";
|
||||
|
||||
const registered = new Set(TOOL_CONTRACTS.map((contract) => contract.name));
|
||||
|
||||
it("registers every JEB contract in the canonical inventory with audited effects", () => {
|
||||
for (const contract of JEB_TOOL_CONTRACTS) {
|
||||
expect(registered.has(contract.name)).toBe(true);
|
||||
expect(contract.effects.accessesNetwork).toBe(true);
|
||||
expect(contract.effects.launchesProcess).toBe(false);
|
||||
expect(contract.effects.writesFilesystem).toBe(false);
|
||||
expect(contract.effects.mutatesTarget).toBe(false);
|
||||
}
|
||||
expect(contractByName("open_jeb_project").effects.idempotent).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps executable examples valid against their advertised input schemas", () => {
|
||||
for (const contract of JEB_TOOL_CONTRACTS) {
|
||||
for (const example of contract.examples) {
|
||||
expect(
|
||||
contract.inputSchema.safeParse(example.input).success,
|
||||
`${contract.name}: ${example.title ?? "example"}`,
|
||||
).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("describes engine authority truthfully", () => {
|
||||
for (const contract of JEB_TOOL_CONTRACTS) {
|
||||
expect(contract.kind).toBe("jeb-provider");
|
||||
expect(contract.description).toMatch(/JEB|[Ee]ngine/);
|
||||
}
|
||||
expect(contractByName("open_jeb_project").description).toContain(
|
||||
"REA does not",
|
||||
);
|
||||
});
|
||||
|
||||
const contractByName = (name: string) => {
|
||||
const contract = JEB_TOOL_CONTRACTS.find(
|
||||
(candidate) => candidate.name === name,
|
||||
);
|
||||
if (contract === undefined) throw new Error(`Missing JEB contract: ${name}`);
|
||||
return contract;
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
jebInputSchemas,
|
||||
jebResultSchemas,
|
||||
} from "../../domain/jeb/jebAnalysis.js";
|
||||
import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
|
||||
/** JEB-backed inspection served by a caller-supplied running engine client. */
|
||||
export const JEB_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_jeb_client",
|
||||
...toolContractMetadata("inspect_jeb_client"),
|
||||
description:
|
||||
"Inspect the running JEB client serving MCP: engine version, GUI or headless mode, and startup time. Does not open a target. Requires a caller-started JEB client reachable at REA_JEB_MCP_URL (default http://127.0.0.1:8425/mcp); REA never installs or launches JEB.",
|
||||
kind: "jeb-provider",
|
||||
inputSchema: jebInputSchemas.inspect_jeb_client,
|
||||
outputSchema: evidenceResultOf(jebResultSchemas.inspect_jeb_client),
|
||||
examples: [{ title: "Check the engine", input: {} }],
|
||||
},
|
||||
{
|
||||
name: "open_jeb_project",
|
||||
...toolContractMetadata("open_jeb_project"),
|
||||
description:
|
||||
"Open or create a JEB project from an artifact file or existing .jdb2 database on the engine host. Returns the project's input-file digests and top-level units. The engine analyzes the target itself; REA does not read the file or execute it. Fails when a project is already open.",
|
||||
kind: "jeb-provider",
|
||||
inputSchema: jebInputSchemas.open_jeb_project,
|
||||
outputSchema: evidenceResultOf(jebResultSchemas.open_jeb_project),
|
||||
examples: [
|
||||
{
|
||||
title: "Open a target for analysis",
|
||||
input: { path: "/tmp/Example.apk" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "list_jeb_units",
|
||||
...toolContractMetadata("list_jeb_units"),
|
||||
description:
|
||||
"List project units by stable unit path and type, with optional wildcard filter, parent restriction, and pagination. The engine caps pages at 100 units; a full page reports partial coverage because more units may exist. Read-only.",
|
||||
kind: "jeb-provider",
|
||||
inputSchema: jebInputSchemas.list_jeb_units,
|
||||
outputSchema: evidenceResultOf(jebResultSchemas.list_jeb_units),
|
||||
examples: [
|
||||
{
|
||||
title: "List units",
|
||||
input: {},
|
||||
},
|
||||
{
|
||||
title: "Find DEX units",
|
||||
input: { filter: "*.dex" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "decompile_jeb_item",
|
||||
...toolContractMetadata("decompile_jeb_item"),
|
||||
description:
|
||||
"Decompile one type or method to engine pseudo-code using its decompiler (Dalvik, Java, or native). item_address comes from the engine's code item listing; unit_path defaults to the engine's first code unit and stays unknown when omitted. Read-only with respect to the target file.",
|
||||
kind: "jeb-provider",
|
||||
inputSchema: jebInputSchemas.decompile_jeb_item,
|
||||
outputSchema: evidenceResultOf(jebResultSchemas.decompile_jeb_item),
|
||||
examples: [
|
||||
{
|
||||
title: "Decompile a method",
|
||||
input: {
|
||||
item_address: "Lcom/example/Main;->onCreate()V",
|
||||
item_kind: "method",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -25,6 +25,7 @@ export const TOOL_KINDS = [
|
||||
"artifact-provider",
|
||||
"managed-provider",
|
||||
"android-provider",
|
||||
"jeb-provider",
|
||||
"adb-provider",
|
||||
"firmware-provider",
|
||||
"browser-provider",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
|
||||
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
|
||||
import { JEB_TOOL_CONTRACTS } from "./jeb/jebToolContracts.js";
|
||||
import { ADB_TOOL_CONTRACTS } from "./adb/adbToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managed/managedWorkflowToolContracts.js";
|
||||
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.js";
|
||||
@@ -31,6 +32,7 @@ export const TOOL_CONTRACTS = [
|
||||
...EVM_TOOL_CONTRACTS,
|
||||
...MANAGED_TOOL_CONTRACTS,
|
||||
...ANDROID_TOOL_CONTRACTS,
|
||||
...JEB_TOOL_CONTRACTS,
|
||||
...ADB_TOOL_CONTRACTS,
|
||||
...FIRMWARE_TOOL_CONTRACTS,
|
||||
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
|
||||
@@ -98,6 +98,23 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
inspect_jeb_client: effects({
|
||||
mutatesSession: true,
|
||||
accessesNetwork: true,
|
||||
}),
|
||||
open_jeb_project: effects({
|
||||
mutatesSession: true,
|
||||
accessesNetwork: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
list_jeb_units: effects({
|
||||
mutatesSession: true,
|
||||
accessesNetwork: true,
|
||||
}),
|
||||
decompile_jeb_item: effects({
|
||||
mutatesSession: true,
|
||||
accessesNetwork: true,
|
||||
}),
|
||||
inspect_adb_client: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { z } from "zod";
|
||||
import { localPathStringSchema } from "../localPath.js";
|
||||
|
||||
/**
|
||||
* Caller intent for JEB-backed inspection, independent of the engine build.
|
||||
*
|
||||
* JEB resolves paths on the host running the JEB client that serves MCP; REA
|
||||
* never launches the engine or opens the target itself.
|
||||
*/
|
||||
export const jebInputSchemas = {
|
||||
inspect_jeb_client: z.strictObject({}),
|
||||
open_jeb_project: z.strictObject({
|
||||
path: localPathStringSchema.describe(
|
||||
"Artifact file or existing .jdb2 project database, resolved by the running JEB client",
|
||||
),
|
||||
}),
|
||||
list_jeb_units: z.strictObject({
|
||||
filter: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Wildcard filter matched against unit paths; '*' allowed"),
|
||||
parent_unit_path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Restrict results to descendants of this unit path"),
|
||||
index: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.default(0)
|
||||
.describe("Zero-based index of the first result to return"),
|
||||
count: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.default(100)
|
||||
.describe(
|
||||
"Maximum results to return; the engine protocol caps pages at 100",
|
||||
),
|
||||
}),
|
||||
decompile_jeb_item: z.strictObject({
|
||||
unit_path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
"Target code unit; the engine's first code unit in the project when omitted",
|
||||
),
|
||||
item_address: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe(
|
||||
"Type or method address within the unit, as listed by the engine",
|
||||
),
|
||||
item_kind: z.enum(["type", "method"]).describe("Kind of item to decompile"),
|
||||
}),
|
||||
} as const;
|
||||
|
||||
/** Supported JEB-backed operations. */
|
||||
export type JebOperation = keyof typeof jebInputSchemas;
|
||||
/** Validated JEB requests carry their selected operation. */
|
||||
export type JebRequest = {
|
||||
[Name in JebOperation]: {
|
||||
operation: Name;
|
||||
input: z.infer<(typeof jebInputSchemas)[Name]>;
|
||||
};
|
||||
}[JebOperation];
|
||||
|
||||
/** Validate operation and input together so their types remain correlated. */
|
||||
export const jebRequestSchema = z.discriminatedUnion("operation", [
|
||||
z.strictObject({
|
||||
operation: z.literal("inspect_jeb_client"),
|
||||
input: jebInputSchemas.inspect_jeb_client,
|
||||
}),
|
||||
z.strictObject({
|
||||
operation: z.literal("open_jeb_project"),
|
||||
input: jebInputSchemas.open_jeb_project,
|
||||
}),
|
||||
z.strictObject({
|
||||
operation: z.literal("list_jeb_units"),
|
||||
input: jebInputSchemas.list_jeb_units,
|
||||
}),
|
||||
z.strictObject({
|
||||
operation: z.literal("decompile_jeb_item"),
|
||||
input: jebInputSchemas.decompile_jeb_item,
|
||||
}),
|
||||
]);
|
||||
|
||||
const engine = z.strictObject({
|
||||
name: z.string().min(1),
|
||||
version: z.string().nullable(),
|
||||
endpoint: z.string().min(1),
|
||||
gui_client: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
const unit = z.strictObject({
|
||||
unit_path: z.string(),
|
||||
unit_type: z.string(),
|
||||
});
|
||||
|
||||
/** Portable JEB observations with explicit identity and coverage limitations. */
|
||||
export const jebResultSchemas = {
|
||||
inspect_jeb_client: z.strictObject({
|
||||
engine,
|
||||
startup_ts: z.number().int().nonnegative().nullable(),
|
||||
message: z.string().nullable(),
|
||||
}),
|
||||
open_jeb_project: z.strictObject({
|
||||
engine,
|
||||
project_name: z.string().nullable(),
|
||||
creation_datetime: z.string().nullable(),
|
||||
input_files: z.array(
|
||||
z.strictObject({
|
||||
file_name: z.string(),
|
||||
file_size: z.number().int().nonnegative(),
|
||||
contents_sha256_hash: z.string(),
|
||||
}),
|
||||
),
|
||||
units: z.array(unit),
|
||||
}),
|
||||
list_jeb_units: z.strictObject({
|
||||
engine,
|
||||
filter: z.string().nullable(),
|
||||
parent_unit_path: z.string().nullable(),
|
||||
index: z.number().int().nonnegative(),
|
||||
count: z.number().int().positive(),
|
||||
units: z.array(unit),
|
||||
coverage: z.enum(["complete", "partial"]),
|
||||
}),
|
||||
decompile_jeb_item: z.strictObject({
|
||||
engine,
|
||||
unit_path: z.string().nullable(),
|
||||
item_address: z.string(),
|
||||
item_kind: z.enum(["type", "method"]),
|
||||
text: z.string(),
|
||||
}),
|
||||
} as const;
|
||||
@@ -0,0 +1,86 @@
|
||||
import { createServer } from "node:http";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
decodeJebToolResult,
|
||||
createStreamableHttpJebMcpConnection,
|
||||
} from "./JebMcpConnection.js";
|
||||
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
|
||||
|
||||
describe("decodeJebToolResult", () => {
|
||||
it("passes refusal envelopes through so the provider preserves the engine reason", () => {
|
||||
expect(
|
||||
decodeJebToolResult({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
success: false,
|
||||
message: "The decompilation failed because the item is missing",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
success: false,
|
||||
message: "The decompilation failed because the item is missing",
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes a single JSON text block", () => {
|
||||
expect(
|
||||
decodeJebToolResult({
|
||||
content: [
|
||||
{ type: "text", text: '{"success":true,"text":"int x(){}"}' },
|
||||
],
|
||||
}),
|
||||
).toEqual({ success: true, text: "int x(){}" });
|
||||
});
|
||||
|
||||
it("keeps non-JSON success text as an observed string", () => {
|
||||
expect(
|
||||
decodeJebToolResult({
|
||||
content: [{ type: "text", text: "plain observation" }],
|
||||
}),
|
||||
).toBe("plain observation");
|
||||
});
|
||||
|
||||
it("rejects unparseable error text as a protocol failure with the engine text", () => {
|
||||
expect(() =>
|
||||
decodeJebToolResult({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: "engine exploded" }],
|
||||
}),
|
||||
).toThrow(/engine exploded/);
|
||||
});
|
||||
|
||||
it("rejects contentless results instead of inventing an observation", () => {
|
||||
expect(() => decodeJebToolResult({ content: [] })).toThrow(
|
||||
AnalysisProtocolError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses HTTP redirects before sending requests to another endpoint", async () => {
|
||||
let followed = false;
|
||||
const server = createServer((request, response) => {
|
||||
if (request.url === "/redirected") followed = true;
|
||||
request.resume();
|
||||
response.writeHead(307, { Location: "/redirected" });
|
||||
response.end();
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string")
|
||||
throw new Error("Expected TCP listener");
|
||||
const connection = createStreamableHttpJebMcpConnection(
|
||||
new URL(`http://127.0.0.1:${address.port}/mcp`),
|
||||
);
|
||||
try {
|
||||
await expect(connection.connect()).rejects.toThrow();
|
||||
expect(followed).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
server.close((cause) =>
|
||||
cause === undefined ? resolve() : reject(cause),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import {
|
||||
Client,
|
||||
StreamableHTTPClientTransport,
|
||||
} from "@modelcontextprotocol/client";
|
||||
import { z } from "zod";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
|
||||
|
||||
/** Injectable MCP boundary used by the provider and conformance tests. */
|
||||
export interface JebMcpConnection {
|
||||
/** Connect lazily and return the advertised tool names. */
|
||||
connect(signal?: AbortSignal): Promise<readonly string[]>;
|
||||
/** Invoke one JEB MCP tool and decode its single structured result. */
|
||||
call(
|
||||
name: string,
|
||||
args: Readonly<Record<string, JsonValue>>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<JsonValue>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
const toolResultSchema = z.object({
|
||||
isError: z.boolean().optional(),
|
||||
structuredContent: z.record(z.string(), z.unknown()).optional(),
|
||||
content: z
|
||||
.array(
|
||||
z.object({ type: z.string(), text: z.string().optional() }).passthrough(),
|
||||
)
|
||||
.default([]),
|
||||
});
|
||||
|
||||
/** Decode a JEB MCP tool result without inventing an empty observation. */
|
||||
export const decodeJebToolResult = (input: unknown): JsonValue => {
|
||||
const result = toolResultSchema.parse(input);
|
||||
const blocks = result.content.flatMap((block) =>
|
||||
block.type === "text" && block.text !== undefined ? [block.text] : [],
|
||||
);
|
||||
if (result.structuredContent !== undefined) {
|
||||
// isError envelopes carry JEB's {success:false, message} refusal semantics;
|
||||
// decode them so the provider can preserve the engine's own reason.
|
||||
return jsonValueSchema.parse(result.structuredContent);
|
||||
}
|
||||
if (blocks.length !== 1)
|
||||
throw new AnalysisProtocolError(
|
||||
"JEB MCP omitted a single structured or text result; unsupported content cannot establish an empty observation.",
|
||||
);
|
||||
try {
|
||||
return jsonValueSchema.parse(JSON.parse(blocks[0] ?? "null"));
|
||||
} catch {
|
||||
if (result.isError === true)
|
||||
throw new AnalysisProtocolError(
|
||||
`JEB MCP tool failed: ${blocks[0] ?? "unexplained engine failure"}`,
|
||||
);
|
||||
return blocks[0] ?? null;
|
||||
}
|
||||
};
|
||||
|
||||
export type JebMcpConnectionFactory = (endpoint: URL) => JebMcpConnection;
|
||||
|
||||
/** Serve JEB requests from a running engine client over streamable HTTP. */
|
||||
export const createStreamableHttpJebMcpConnection: JebMcpConnectionFactory = (
|
||||
endpoint,
|
||||
) => {
|
||||
let client: Client | undefined;
|
||||
let serverTools: readonly string[] | undefined;
|
||||
return {
|
||||
async connect(signal) {
|
||||
client ??= new Client({ name: "rea-jeb", version: "0.0.0" });
|
||||
if (serverTools === undefined) {
|
||||
await client.connect(
|
||||
new StreamableHTTPClientTransport(endpoint, {
|
||||
requestInit: { redirect: "error" },
|
||||
}),
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
const listing = await client.listTools(
|
||||
{},
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
serverTools = listing.tools.map((tool) => tool.name);
|
||||
}
|
||||
return serverTools;
|
||||
},
|
||||
async call(name, args, signal) {
|
||||
if (serverTools === undefined) await this.connect(signal);
|
||||
if (client === undefined)
|
||||
throw new AnalysisProtocolError("JEB MCP client failed to connect");
|
||||
const result = await client.callTool(
|
||||
{ name, arguments: args },
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
return decodeJebToolResult(result);
|
||||
},
|
||||
async close() {
|
||||
const active = client;
|
||||
if (active !== undefined) await active.close();
|
||||
client = undefined;
|
||||
serverTools = undefined;
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Default JEB MCP endpoint documented by the engine's headless client. */
|
||||
export const DEFAULT_JEB_MCP_ENDPOINT = "http://127.0.0.1:8425/mcp";
|
||||
|
||||
/**
|
||||
* Normalize the caller-selected JEB MCP endpoint.
|
||||
*
|
||||
* Only the scheme, host, and port select the engine; credentials, paths with
|
||||
* segments beyond the MCP route, queries, and fragments are rejected rather
|
||||
* than silently dropped.
|
||||
*/
|
||||
export const parseJebMcpEndpoint = (
|
||||
value: string | undefined,
|
||||
): Result<URL, AnalysisError> => {
|
||||
const raw = value === undefined || value.length === 0 ? null : value;
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw ?? DEFAULT_JEB_MCP_ENDPOINT);
|
||||
} catch {
|
||||
return err(
|
||||
new AnalysisInputError("jeb_mcp_endpoint", {
|
||||
cause: "Expected an absolute http(s) URL",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:")
|
||||
return err(
|
||||
new AnalysisInputError("jeb_mcp_endpoint", {
|
||||
cause: "Only http and https JEB MCP endpoints are supported",
|
||||
}),
|
||||
);
|
||||
if (url.hostname !== "127.0.0.1" && url.hostname !== "[::1]")
|
||||
return err(
|
||||
new AnalysisInputError("jeb_mcp_endpoint", {
|
||||
cause:
|
||||
"JEB MCP endpoint must use a literal loopback host (127.0.0.1 or ::1)",
|
||||
}),
|
||||
);
|
||||
if (url.username !== "" || url.password !== "")
|
||||
return err(
|
||||
new AnalysisInputError("jeb_mcp_endpoint", {
|
||||
cause:
|
||||
"Embedding credentials in the JEB MCP endpoint is not supported; configure authentication with the engine",
|
||||
}),
|
||||
);
|
||||
if (url.search !== "" || url.hash !== "")
|
||||
return err(
|
||||
new AnalysisInputError("jeb_mcp_endpoint", {
|
||||
cause: "JEB MCP endpoint query strings and fragments are not supported",
|
||||
}),
|
||||
);
|
||||
return ok(url);
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { JebProvider } from "./JebProvider.js";
|
||||
import type { JebMcpConnection } from "./JebMcpConnection.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
AnalysisCancelledError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
|
||||
const scriptedConnection = (
|
||||
responses: Readonly<Record<string, JsonValue | Error>>,
|
||||
): JebMcpConnection & { readonly calls: unknown[][] } => {
|
||||
const calls: unknown[][] = [];
|
||||
return {
|
||||
calls,
|
||||
async connect() {
|
||||
return [];
|
||||
},
|
||||
async call(name, args) {
|
||||
calls.push([name, args]);
|
||||
const response = responses[name];
|
||||
if (response === undefined)
|
||||
throw new Error(`Unexpected JEB MCP call: ${name}`);
|
||||
if (response instanceof Error) throw response;
|
||||
return response;
|
||||
},
|
||||
async close() {},
|
||||
};
|
||||
};
|
||||
|
||||
const providerWith = (connection: JebMcpConnection) =>
|
||||
new JebProvider({
|
||||
environment: { REA_JEB_MCP_URL: "http://127.0.0.1:8425/mcp" },
|
||||
connectionFactory: () => connection,
|
||||
});
|
||||
|
||||
describe("JebProvider boundary", () => {
|
||||
it("normalizes client information and caches engine identity", async () => {
|
||||
const connection = scriptedConnection({
|
||||
get_client_information: {
|
||||
success: true,
|
||||
version: "5.48.0.202610071539",
|
||||
gui_client: false,
|
||||
startup_ts: 1791623439,
|
||||
},
|
||||
});
|
||||
const provider = providerWith(connection);
|
||||
const result = await provider.execute({
|
||||
operation: "inspect_jeb_client",
|
||||
input: {},
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
const normalized = result.value.result as {
|
||||
readonly engine: { readonly version: string | null };
|
||||
readonly startup_ts: number | null;
|
||||
};
|
||||
expect(normalized.engine.version).toBe("5.48.0.202610071539");
|
||||
expect(normalized.startup_ts).toBe(1791623439);
|
||||
expect(result.value.provider.version).toBe("5.48.0.202610071539");
|
||||
});
|
||||
|
||||
it("reports unavailable when the engine endpoint is unreachable", async () => {
|
||||
const provider = providerWith(
|
||||
scriptedConnection({
|
||||
get_client_information: new Error(
|
||||
"connect ECONNREFUSED 127.0.0.1:8425",
|
||||
),
|
||||
list_units: new Error("connect ECONNREFUSED 127.0.0.1:8425"),
|
||||
}),
|
||||
);
|
||||
const availability = await provider.inspectAvailability();
|
||||
expect(availability.status).toBe("unavailable");
|
||||
const result = await provider.execute({
|
||||
operation: "list_jeb_units",
|
||||
input: { count: 10, index: 0 },
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toBeInstanceOf(AnalysisCapabilityUnavailableError);
|
||||
expect(result.error.message).toContain("ECONNREFUSED");
|
||||
});
|
||||
|
||||
it("maps transport failures during an operation to provider unavailability", async () => {
|
||||
const provider = providerWith(
|
||||
scriptedConnection({
|
||||
get_client_information: {
|
||||
success: true,
|
||||
version: "5.48.0",
|
||||
gui_client: false,
|
||||
},
|
||||
list_units: new Error("connect ECONNREFUSED 127.0.0.1:8425"),
|
||||
}),
|
||||
);
|
||||
const result = await provider.execute({
|
||||
operation: "list_jeb_units",
|
||||
input: { count: 10, index: 0 },
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toBeInstanceOf(AnalysisCapabilityUnavailableError);
|
||||
expect(result.error.message).toContain("ECONNREFUSED");
|
||||
});
|
||||
|
||||
it("preserves engine refusal reasons as unsupported targets", async () => {
|
||||
const provider = providerWith(
|
||||
scriptedConnection({
|
||||
get_client_information: {
|
||||
success: true,
|
||||
version: "5.48.0",
|
||||
gui_client: false,
|
||||
},
|
||||
decompile_code_item: {
|
||||
success: false,
|
||||
message:
|
||||
"The decompilation failed because the item address does not reference an existing code item",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const result = await provider.execute({
|
||||
operation: "decompile_jeb_item",
|
||||
input: { item_address: "LNope;->x()V", item_kind: "method" },
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.message).toContain("does not reference an existing");
|
||||
});
|
||||
|
||||
it("derives partial coverage only from a full engine page", async () => {
|
||||
const provider = providerWith(
|
||||
scriptedConnection({
|
||||
get_client_information: {
|
||||
success: true,
|
||||
version: "5.48.0",
|
||||
gui_client: false,
|
||||
},
|
||||
list_units: {
|
||||
success: true,
|
||||
units: Array.from({ length: 3 }, (_, index) => ({
|
||||
unit_path: `a/class${index}.dex`,
|
||||
unit_type: "dex",
|
||||
})),
|
||||
},
|
||||
}),
|
||||
);
|
||||
const full = await provider.execute({
|
||||
operation: "list_jeb_units",
|
||||
input: { count: 3, index: 0 },
|
||||
});
|
||||
expect(
|
||||
full.ok &&
|
||||
(full.value.result as { coverage: string }).coverage === "partial",
|
||||
).toBe(true);
|
||||
const last = await provider.execute({
|
||||
operation: "list_jeb_units",
|
||||
input: { count: 4, index: 0 },
|
||||
});
|
||||
expect(
|
||||
last.ok &&
|
||||
(last.value.result as { coverage: string }).coverage === "complete",
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JebProvider target and endpoint selection", () => {
|
||||
it("keeps the implicitly selected unit unknown when unit_path is omitted", async () => {
|
||||
const provider = providerWith(
|
||||
scriptedConnection({
|
||||
get_client_information: {
|
||||
success: true,
|
||||
version: "5.48.0",
|
||||
gui_client: false,
|
||||
},
|
||||
decompile_code_item: { success: true, text: "int x() { return 1; }" },
|
||||
}),
|
||||
);
|
||||
const result = await provider.execute({
|
||||
operation: "decompile_jeb_item",
|
||||
input: { item_address: "LFoo;->x()I", item_kind: "method" },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
const normalized = result.value.result as {
|
||||
readonly unit_path: string | null;
|
||||
};
|
||||
expect(normalized.unit_path).toBeNull();
|
||||
expect(result.value.limitations.join(" ")).toContain("implicitly");
|
||||
});
|
||||
|
||||
it("rejects unusable endpoints at construction", () => {
|
||||
const rejection = (value: string): AnalysisInputError => {
|
||||
try {
|
||||
new JebProvider({ environment: { REA_JEB_MCP_URL: value } });
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisInputError) return cause;
|
||||
throw cause;
|
||||
}
|
||||
throw new Error("endpoint should have been rejected");
|
||||
};
|
||||
expect(rejection("ftp://example.invalid/mcp").cause).toMatch(
|
||||
/http and https/,
|
||||
);
|
||||
expect(rejection("http://user:pass@127.0.0.1:8425/mcp").cause).toMatch(
|
||||
/credentials/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses remote endpoints before constructing a connection", () => {
|
||||
expect(
|
||||
() =>
|
||||
new JebProvider({
|
||||
environment: { REA_JEB_MCP_URL: "http://example.com/mcp" },
|
||||
}),
|
||||
).toThrow(AnalysisInputError);
|
||||
});
|
||||
|
||||
it.each(["list_jeb_units", "decompile_jeb_item"] as const)(
|
||||
"rejects an omitted successful payload for %s",
|
||||
async (operation) => {
|
||||
const provider = providerWith(
|
||||
scriptedConnection({
|
||||
get_client_information: { success: true, version: "5.48.0" },
|
||||
list_units: { success: true },
|
||||
decompile_code_item: { success: true },
|
||||
}),
|
||||
);
|
||||
const result = await provider.execute(
|
||||
operation === "list_jeb_units"
|
||||
? { operation, input: { count: 10, index: 0 } }
|
||||
: {
|
||||
operation,
|
||||
input: { item_address: "LTest;->x()V", item_kind: "method" },
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisProtocolError);
|
||||
},
|
||||
);
|
||||
|
||||
it("forwards in-flight cancellation to the MCP call", async () => {
|
||||
const controller = new AbortController();
|
||||
let entered!: () => void;
|
||||
const started = new Promise<void>((resolve) => {
|
||||
entered = resolve;
|
||||
});
|
||||
const provider = providerWith({
|
||||
async connect() {
|
||||
return [];
|
||||
},
|
||||
async close() {},
|
||||
async call(_name, _args, signal) {
|
||||
entered();
|
||||
await new Promise<void>((_resolve, reject) =>
|
||||
signal!.addEventListener("abort", () => reject(signal!.reason), {
|
||||
once: true,
|
||||
}),
|
||||
);
|
||||
return {};
|
||||
},
|
||||
});
|
||||
const pending = provider.execute(
|
||||
{ operation: "inspect_jeb_client", input: {} },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
await started;
|
||||
controller.abort();
|
||||
const result = await pending;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
@@ -0,0 +1,421 @@
|
||||
import { z } from "zod";
|
||||
import type { JebAnalysisPort } from "../application/jeb/JebAnalysisPort.js";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
ProviderAvailability,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { createAnalysisExecution } from "../application/AnalysisProvider.js";
|
||||
import type { JebOperation, JebRequest } from "../domain/jeb/jebAnalysis.js";
|
||||
import { jebResultSchemas } from "../domain/jeb/jebAnalysis.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
parseJebMcpEndpoint,
|
||||
DEFAULT_JEB_MCP_ENDPOINT,
|
||||
} from "./JebMcpEndpoint.js";
|
||||
import {
|
||||
createStreamableHttpJebMcpConnection,
|
||||
type JebMcpConnection,
|
||||
type JebMcpConnectionFactory,
|
||||
} from "./JebMcpConnection.js";
|
||||
|
||||
export const JEB_PROVIDER_IDENTITY: ProviderIdentity = {
|
||||
id: "jeb",
|
||||
name: "JEB",
|
||||
version: null,
|
||||
} as const;
|
||||
|
||||
export interface JebProviderOptions {
|
||||
/** Caller environment carrying REA_JEB_MCP_URL. */
|
||||
readonly environment?: Readonly<Record<string, string | undefined>>;
|
||||
/** Injectable MCP boundary; defaults to the streamable HTTP client. */
|
||||
readonly connectionFactory?: JebMcpConnectionFactory;
|
||||
}
|
||||
|
||||
/** JEB's tool envelope: success with typed fields, or a message-only failure. */
|
||||
const failure = z
|
||||
.object({
|
||||
success: z.literal(false),
|
||||
message: z.string().optional(),
|
||||
error: z
|
||||
.object({
|
||||
code: z.string().optional(),
|
||||
message: z.string().optional(),
|
||||
recovery_tool: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.passthrough();
|
||||
const clientInformation = z
|
||||
.object({
|
||||
success: z.literal(true),
|
||||
version: z.string().optional(),
|
||||
gui_client: z.boolean().optional(),
|
||||
startup_ts: z.number().int().nonnegative().optional(),
|
||||
message: z.string().nullish(),
|
||||
})
|
||||
.passthrough();
|
||||
const unitEntry = z.object({ unit_path: z.string(), unit_type: z.string() });
|
||||
const openProject = z
|
||||
.object({
|
||||
success: z.literal(true),
|
||||
name: z.string().nullish(),
|
||||
creation_datetime: z.string().nullish(),
|
||||
input_files: z
|
||||
.array(
|
||||
z.object({
|
||||
file_name: z.string(),
|
||||
file_size: z.number().int().nonnegative(),
|
||||
contents_sha256_hash: z.string(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
units: z.array(unitEntry).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
const listUnits = z
|
||||
.object({ success: z.literal(true), units: z.array(unitEntry) })
|
||||
.passthrough();
|
||||
const decompiledItem = z
|
||||
.object({ success: z.literal(true), text: z.string() })
|
||||
.passthrough();
|
||||
|
||||
const refusalReason = (payload: unknown, fallback: string): string => {
|
||||
const parsed = failure.safeParse(payload);
|
||||
if (!parsed.success) return fallback;
|
||||
const envelope = parsed.data;
|
||||
const reason =
|
||||
envelope.error?.message ?? envelope.message ?? envelope.error?.code;
|
||||
if (reason !== undefined && reason.length > 0) return reason;
|
||||
return fallback;
|
||||
};
|
||||
|
||||
/** Serve REA's JEB operations from a running engine client over MCP. */
|
||||
export class JebProvider implements JebAnalysisPort {
|
||||
readonly #connection: JebMcpConnection;
|
||||
readonly #endpoint: URL;
|
||||
#identity: ProviderIdentity = JEB_PROVIDER_IDENTITY;
|
||||
#guiClient: boolean | null = null;
|
||||
|
||||
constructor(options: JebProviderOptions = {}) {
|
||||
const environment = options.environment ?? {};
|
||||
const endpoint = parseJebMcpEndpoint(environment.REA_JEB_MCP_URL);
|
||||
if (!endpoint.ok) throw endpoint.error;
|
||||
this.#endpoint = endpoint.value;
|
||||
this.#connection = (
|
||||
options.connectionFactory ??
|
||||
((url: URL) => createStreamableHttpJebMcpConnection(url))
|
||||
)(this.#endpoint);
|
||||
}
|
||||
|
||||
async inspectAvailability(
|
||||
signal?: AbortSignal,
|
||||
): Promise<ProviderAvailability> {
|
||||
try {
|
||||
await this.#refreshClientInformation(signal);
|
||||
return {
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: {
|
||||
endpoint: this.#endpoint.toString(),
|
||||
engine_version: this.#identity.version,
|
||||
},
|
||||
};
|
||||
} catch (cause) {
|
||||
if (signal?.aborted === true) throw cause;
|
||||
return {
|
||||
status: "unavailable",
|
||||
code: "not_configured",
|
||||
reason:
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: "The JEB MCP endpoint did not respond",
|
||||
diagnostics: { endpoint: this.#endpoint.toString() },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
await this.#connection.close();
|
||||
}
|
||||
|
||||
async execute(
|
||||
request: JebRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
try {
|
||||
const execution = await this.#dispatch(request, options?.signal);
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
if (execution.ok)
|
||||
this.#identity = {
|
||||
...this.#identity,
|
||||
version: execution.value.provider.version,
|
||||
};
|
||||
return execution;
|
||||
} catch (cause) {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(request.operation, { cause }));
|
||||
return err(this.#providerFailure(request.operation, cause));
|
||||
}
|
||||
}
|
||||
|
||||
async #dispatch(
|
||||
request: JebRequest,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
const cancelled = (operation: JebOperation) => {
|
||||
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
|
||||
};
|
||||
switch (request.operation) {
|
||||
case "inspect_jeb_client": {
|
||||
cancelled(request.operation);
|
||||
return this.#inspectClient(signal);
|
||||
}
|
||||
case "open_jeb_project": {
|
||||
cancelled(request.operation);
|
||||
return this.#openProject(request, signal);
|
||||
}
|
||||
case "list_jeb_units": {
|
||||
cancelled(request.operation);
|
||||
return this.#listUnits(request, signal);
|
||||
}
|
||||
case "decompile_jeb_item": {
|
||||
cancelled(request.operation);
|
||||
return this.#decompileItem(request, signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #engine(signal?: AbortSignal): Promise<{
|
||||
readonly name: string;
|
||||
readonly version: string | null;
|
||||
readonly endpoint: string;
|
||||
readonly gui_client: boolean | null;
|
||||
}> {
|
||||
await this.#requireClientInformation(signal);
|
||||
return {
|
||||
name: "jeb",
|
||||
version: this.#identity.version,
|
||||
endpoint: this.#endpoint.toString(),
|
||||
gui_client: this.#guiClient,
|
||||
};
|
||||
}
|
||||
|
||||
async #requireClientInformation(signal?: AbortSignal): Promise<void> {
|
||||
if (this.#identity.version !== null) return;
|
||||
await this.#refreshClientInformation(signal);
|
||||
}
|
||||
|
||||
async #refreshClientInformation(
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<void> {
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError("inspect_jeb_client");
|
||||
const payload = await this.#connection.call(
|
||||
"get_client_information",
|
||||
{},
|
||||
signal,
|
||||
);
|
||||
const information = clientInformation.parse(
|
||||
this.#requireSuccess(payload, "inspect_jeb_client"),
|
||||
);
|
||||
this.#identity = {
|
||||
...this.#identity,
|
||||
version: information.version ?? null,
|
||||
};
|
||||
this.#guiClient = information.gui_client ?? null;
|
||||
}
|
||||
|
||||
async #inspectClient(signal?: AbortSignal) {
|
||||
const payload = await this.#connection.call(
|
||||
"get_client_information",
|
||||
{},
|
||||
signal,
|
||||
);
|
||||
const information = clientInformation.parse(
|
||||
this.#requireSuccess(payload, "inspect_jeb_client"),
|
||||
);
|
||||
this.#identity = {
|
||||
...this.#identity,
|
||||
version: information.version ?? null,
|
||||
};
|
||||
this.#guiClient = information.gui_client ?? null;
|
||||
const result = jebResultSchemas.inspect_jeb_client.parse({
|
||||
engine: {
|
||||
name: "jeb",
|
||||
version: information.version ?? null,
|
||||
endpoint: this.#endpoint.toString(),
|
||||
gui_client: information.gui_client ?? null,
|
||||
},
|
||||
startup_ts: information.startup_ts ?? null,
|
||||
message: information.message ?? null,
|
||||
});
|
||||
return ok(
|
||||
createAnalysisExecution(result, this.#identity, {
|
||||
rawResult: payload,
|
||||
limitations:
|
||||
information.version === undefined
|
||||
? ["The engine did not report its version."]
|
||||
: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async #openProject(
|
||||
request: Extract<JebRequest, { operation: "open_jeb_project" }>,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const payload = await this.#connection.call(
|
||||
"open_project",
|
||||
{
|
||||
file_path: request.input.path,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
const opened = openProject.parse(
|
||||
this.#requireSuccess(payload, request.operation),
|
||||
);
|
||||
const engine = await this.#engine(signal);
|
||||
const result = jebResultSchemas.open_jeb_project.parse({
|
||||
engine,
|
||||
project_name: opened.name ?? null,
|
||||
creation_datetime: opened.creation_datetime ?? null,
|
||||
input_files: opened.input_files ?? [],
|
||||
units: opened.units ?? [],
|
||||
});
|
||||
return ok(
|
||||
createAnalysisExecution(result, this.#identity, {
|
||||
rawResult: payload,
|
||||
limitations: [
|
||||
"JEB resolves and analyzes the artifact on the engine host; REA did not open the target itself.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async #listUnits(
|
||||
request: Extract<JebRequest, { operation: "list_jeb_units" }>,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const { count, index, filter, parent_unit_path } = request.input;
|
||||
const payload = await this.#connection.call(
|
||||
"list_units",
|
||||
{
|
||||
count,
|
||||
index,
|
||||
...(filter === undefined ? {} : { filter }),
|
||||
...(parent_unit_path === undefined ? {} : { parent_unit_path }),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
const listed = listUnits.parse(
|
||||
this.#requireSuccess(payload, request.operation),
|
||||
);
|
||||
const units = listed.units;
|
||||
const engine = await this.#engine(signal);
|
||||
const result = jebResultSchemas.list_jeb_units.parse({
|
||||
engine,
|
||||
filter: filter ?? null,
|
||||
parent_unit_path: parent_unit_path ?? null,
|
||||
index,
|
||||
count,
|
||||
units,
|
||||
coverage: units.length < count ? "complete" : "partial",
|
||||
});
|
||||
return ok(
|
||||
createAnalysisExecution(result, this.#identity, {
|
||||
rawResult: payload,
|
||||
limitations: [
|
||||
"The engine caps unit pages at 100; a full page means more units may exist.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async #decompileItem(
|
||||
request: Extract<JebRequest, { operation: "decompile_jeb_item" }>,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const { item_address, item_kind, unit_path } = request.input;
|
||||
const payload = await this.#connection.call(
|
||||
"decompile_code_item",
|
||||
{
|
||||
item_address,
|
||||
item_kind,
|
||||
...(unit_path === undefined ? {} : { unit_path }),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
const decompiled = decompiledItem.parse(
|
||||
this.#requireSuccess(payload, request.operation),
|
||||
);
|
||||
const engine = await this.#engine(signal);
|
||||
const result = jebResultSchemas.decompile_jeb_item.parse({
|
||||
engine,
|
||||
unit_path: unit_path ?? null,
|
||||
item_address,
|
||||
item_kind,
|
||||
text: decompiled.text,
|
||||
});
|
||||
return ok(
|
||||
createAnalysisExecution(result, this.#identity, {
|
||||
rawResult: payload,
|
||||
limitations:
|
||||
unit_path === undefined
|
||||
? [
|
||||
"The engine selected the project's first code unit implicitly; the effective unit identity is unknown.",
|
||||
]
|
||||
: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#requireSuccess(payload: unknown, operation: JebOperation): unknown {
|
||||
if (typeof payload !== "object" || payload === null)
|
||||
throw new AnalysisProtocolError(
|
||||
"JEB MCP returned a non-object envelope; no observation can be established",
|
||||
);
|
||||
const success = (payload as { success?: unknown }).success;
|
||||
if (success === false)
|
||||
throw new AnalysisUnsupportedTargetError(
|
||||
operation,
|
||||
this.#endpoint.toString(),
|
||||
refusalReason(payload, "The engine refused the request"),
|
||||
);
|
||||
if (success !== true)
|
||||
throw new AnalysisProtocolError(
|
||||
"JEB MCP omitted its success field; no observation can be established",
|
||||
);
|
||||
return payload;
|
||||
}
|
||||
|
||||
#providerFailure(operation: JebOperation, cause: unknown): AnalysisError {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof z.ZodError)
|
||||
return new AnalysisProtocolError(
|
||||
"JEB omitted or malformed required observation fields",
|
||||
{ cause },
|
||||
);
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
"jeb",
|
||||
operation,
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
{
|
||||
cause: cause instanceof Error ? cause : undefined,
|
||||
userMessage: `Start a JEB client serving MCP (default ${DEFAULT_JEB_MCP_ENDPOINT}) or set REA_JEB_MCP_URL to the running endpoint.`,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -64,12 +64,16 @@ import { FirmwareAnalysisService } from "../application/firmware/FirmwareAnalysi
|
||||
import type { FirmwareAnalysisPort } from "../application/firmware/FirmwareAnalysisPort.js";
|
||||
import { createFirmwareAnalysisProvider } from "../composition/firmware.js";
|
||||
import { registerAndroidTools } from "./registerAndroidTools.js";
|
||||
import { registerJebTools } from "./registerJebTools.js";
|
||||
import { registerAdbTools } from "./registerAdbTools.js";
|
||||
import { AndroidAnalysisService } from "../application/android/AndroidAnalysisService.js";
|
||||
import { JebAnalysisService } from "../application/jeb/JebAnalysisService.js";
|
||||
import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js";
|
||||
import type { JebAnalysisPort } from "../application/jeb/JebAnalysisPort.js";
|
||||
import { createAndroidAnalysisProvider } from "../composition/android.js";
|
||||
import { createJebAnalysisProvider } from "../composition/jeb.js";
|
||||
import type { AdbDeviceAnalysisPort } from "../application/adb/AdbDeviceAnalysisPort.js";
|
||||
import { AdbDeviceAnalysisService } from "../application/adb/AdbDeviceAnalysisService.js";
|
||||
import { createAndroidAnalysisProvider } from "../composition/android.js";
|
||||
import { createAdbDeviceAnalysisProvider } from "../composition/adb.js";
|
||||
import { registerManagedWorkflowTools } from "./registerManagedWorkflowTools.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js";
|
||||
@@ -105,6 +109,7 @@ export interface CreateServerOptions {
|
||||
readonly webRuntime?: WebRuntimeService;
|
||||
readonly webNetworkCapture?: WebNetworkCaptureService;
|
||||
readonly androidAnalysis?: AndroidAnalysisPort;
|
||||
readonly jebAnalysis?: JebAnalysisPort;
|
||||
readonly adbDeviceAnalysis?: AdbDeviceAnalysisPort;
|
||||
readonly browserObservation?: BrowserObservationPort;
|
||||
readonly browserScenarioCapture?: BrowserScenarioCapturePort;
|
||||
@@ -204,6 +209,7 @@ export const createServer = (
|
||||
);
|
||||
const android =
|
||||
options.androidAnalysis ?? createAndroidAnalysisProvider(environment);
|
||||
const jeb = options.jebAnalysis ?? createJebAnalysisProvider(environment);
|
||||
const adbDevice =
|
||||
options.adbDeviceAnalysis ?? createAdbDeviceAnalysisProvider(environment);
|
||||
const availability = installSessionToolAvailability(
|
||||
@@ -240,14 +246,24 @@ export const createServer = (
|
||||
"Android provider cleanup failed",
|
||||
);
|
||||
});
|
||||
void jeb.close().catch((cause: unknown) => {
|
||||
logger.error(
|
||||
{ error: cause instanceof Error ? cause.message : String(cause) },
|
||||
"JEB provider cleanup failed",
|
||||
);
|
||||
});
|
||||
};
|
||||
const closeServer = server.close.bind(server);
|
||||
server.close = async () => {
|
||||
const results = await Promise.allSettled([closeServer(), android.close()]);
|
||||
const results = await Promise.allSettled([
|
||||
closeServer(),
|
||||
android.close(),
|
||||
jeb.close(),
|
||||
]);
|
||||
for (const result of results)
|
||||
if (result.status === "rejected") throw result.reason;
|
||||
};
|
||||
registerConfiguredAnalysisTools(toolContext, android);
|
||||
registerConfiguredAnalysisTools(toolContext, android, jeb);
|
||||
registerAdbTools(
|
||||
server,
|
||||
new AdbDeviceAnalysisService(adbDevice),
|
||||
@@ -304,6 +320,7 @@ const registerConfiguredAnalysisTools = (
|
||||
recordEvidence,
|
||||
}: ServerToolContext,
|
||||
android: AndroidAnalysisPort,
|
||||
jeb: JebAnalysisPort,
|
||||
): void => {
|
||||
registerAndroidTools(
|
||||
server,
|
||||
@@ -311,6 +328,12 @@ const registerConfiguredAnalysisTools = (
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
);
|
||||
registerJebTools(
|
||||
server,
|
||||
new JebAnalysisService(jeb),
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
);
|
||||
registerBinaryDiagnosticsTools(
|
||||
server,
|
||||
options.binaryLayout ?? createBinaryLayoutService(environment),
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { ServerContext } from "@modelcontextprotocol/server";
|
||||
import { JebAnalysisService } from "../application/jeb/JebAnalysisService.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import type { JebOperation } from "../domain/jeb/jebAnalysis.js";
|
||||
import type { Logger } from "pino";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
|
||||
/** Bind JEB handlers to their exact named contracts through shared workflows. */
|
||||
export const registerJebTools = (
|
||||
server: EvidenceMcpServer,
|
||||
service: JebAnalysisService,
|
||||
logger: Logger,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
): void => {
|
||||
const handler = (contract: ToolContract<JebOperation>) => {
|
||||
const name = contract.name;
|
||||
return async (input: unknown, context: ServerContext) => {
|
||||
const result = await logToolExecution(logger, name, () =>
|
||||
service.execute(name, input, { signal: context.mcpReq.signal }),
|
||||
);
|
||||
if (!result.ok) return server.delivery.toCallToolResult(result, contract);
|
||||
const recorded = recordEvidence?.(result.value);
|
||||
return server.delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
contract,
|
||||
recorded,
|
||||
);
|
||||
};
|
||||
};
|
||||
const clientContract = toolContract("inspect_jeb_client");
|
||||
server.registerTool(
|
||||
clientContract.name,
|
||||
toolRegistrationOptions(clientContract),
|
||||
handler(clientContract),
|
||||
);
|
||||
const openContract = toolContract("open_jeb_project");
|
||||
server.registerTool(
|
||||
openContract.name,
|
||||
toolRegistrationOptions(openContract),
|
||||
handler(openContract),
|
||||
);
|
||||
const unitsContract = toolContract("list_jeb_units");
|
||||
server.registerTool(
|
||||
unitsContract.name,
|
||||
toolRegistrationOptions(unitsContract),
|
||||
handler(unitsContract),
|
||||
);
|
||||
const decompileContract = toolContract("decompile_jeb_item");
|
||||
server.registerTool(
|
||||
decompileContract.name,
|
||||
toolRegistrationOptions(decompileContract),
|
||||
handler(decompileContract),
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user