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:
Quentin Limo
2026-10-10 23:03:27 +08:00
committed by GitHub
co-authored by REA Contributor morluto
parent ded59689ce
commit 749e58772a
48 changed files with 2051 additions and 4 deletions
+86
View File
@@ -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),
),
);
}
});
+101
View File
@@ -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;
},
};
};
+56
View File
@@ -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);
};
+274
View File
@@ -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);
});
+421
View File
@@ -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.`,
},
);
}
}