Add structured runtime logging
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { parseConfig } from "../config.js";
|
||||
import type { JsonValue } from "../hopper/protocol.js";
|
||||
import { createBinarySession } from "./runtime.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
|
||||
/**
|
||||
* Open one binary, execute one tool, and always release the bridge session.
|
||||
@@ -11,11 +12,12 @@ export const runDirectAnalysis = async (
|
||||
path: string,
|
||||
tool: "binary_overview" | "procedure_pseudo_code",
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
logger: Logger = silentLogger,
|
||||
): Promise<JsonValue> => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
const session = createBinarySession(config.value);
|
||||
const session = createBinarySession(config.value, logger);
|
||||
try {
|
||||
const opened = await session.open(path);
|
||||
if (!opened.ok)
|
||||
|
||||
@@ -4,13 +4,17 @@ import type { AppConfig } from "../config.js";
|
||||
import { BinarySession } from "./BinarySession.js";
|
||||
import { HopperApplicationLauncher } from "../hopper/BridgeLauncher.js";
|
||||
import { HopperClient } from "../hopper/HopperClient.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
|
||||
/**
|
||||
* Compose the target-switching runtime shared directly by CLI and MCP adapters.
|
||||
* This is the sole production wiring point for Hopper so neither adapter shells
|
||||
* out to the other and both retain identical loader and bridge semantics.
|
||||
*/
|
||||
export const createBinarySession = (config: AppConfig): BinarySession => {
|
||||
export const createBinarySession = (
|
||||
config: AppConfig,
|
||||
logger: Logger = silentLogger,
|
||||
): BinarySession => {
|
||||
const bridgeScriptPath = fileURLToPath(
|
||||
new URL("../../bridge/hopper_bridge.py", import.meta.url),
|
||||
);
|
||||
@@ -27,6 +31,7 @@ export const createBinarySession = (config: AppConfig): BinarySession => {
|
||||
: target.loaderArgs,
|
||||
bridgeScriptPath,
|
||||
}),
|
||||
logger: logger.child({ layer: "bridge" }),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
+53
-6
@@ -5,6 +5,7 @@ import { runDoctor } from "./application/Doctor.js";
|
||||
import { runDirectAnalysis } from "./application/DirectAnalysis.js";
|
||||
import { runSetup } from "./application/Setup.js";
|
||||
import { PRODUCT_IDENTITY } from "./identity.js";
|
||||
import { createLogger, parseLogLevel, type Logger } from "./logger.js";
|
||||
|
||||
/**
|
||||
* Build the one-shot Incur CLI without starting Hopper at import time.
|
||||
@@ -12,6 +13,12 @@ import { PRODUCT_IDENTITY } from "./identity.js";
|
||||
* `--mcp` are intercepted by the executable dispatcher before this module loads.
|
||||
*/
|
||||
export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
const logger = createLogger(
|
||||
"cli",
|
||||
process.env.REA_LOG_LEVEL === undefined
|
||||
? "silent"
|
||||
: parseLogLevel(process.env.REA_LOG_LEVEL),
|
||||
);
|
||||
const cli = Cli.create(PRODUCT_IDENTITY.cliBinary, {
|
||||
version: "0.1.0",
|
||||
description: "Install, diagnose, and automate Hopper binary analysis.",
|
||||
@@ -40,21 +47,26 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
.describe("Approve prerequisite installation"),
|
||||
}),
|
||||
alias: { yes: "y" },
|
||||
run: ({ options }) => runSetup(options.yes),
|
||||
run: ({ options }) =>
|
||||
logCliCommand(logger, "setup", () => runSetup(options.yes)),
|
||||
});
|
||||
cli.command("doctor", {
|
||||
description: "Diagnose the local Hopper integration",
|
||||
options: z.object({
|
||||
target: z.string().optional().describe("Optional binary path to check"),
|
||||
}),
|
||||
run: ({ options }) => runDoctor(options.target),
|
||||
run: ({ options }) =>
|
||||
logCliCommand(logger, "doctor", () => runDoctor(options.target)),
|
||||
});
|
||||
cli.command("analyze", {
|
||||
description: "Analyze a binary through the shared Hopper core",
|
||||
args: z.object({
|
||||
path: z.string().describe("Binary or Hopper database path"),
|
||||
}),
|
||||
run: ({ args }) => runDirectAnalysis(args.path, "binary_overview", {}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "analyze", () =>
|
||||
runDirectAnalysis(args.path, "binary_overview", {}, logger),
|
||||
),
|
||||
});
|
||||
cli.command("decompile", {
|
||||
description: "Decompile an address through the shared Hopper core",
|
||||
@@ -63,9 +75,44 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
address: z.string().describe("Procedure address"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
runDirectAnalysis(args.path, "procedure_pseudo_code", {
|
||||
procedure: args.address,
|
||||
}),
|
||||
logCliCommand(logger, "decompile", () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"procedure_pseudo_code",
|
||||
{ procedure: args.address },
|
||||
logger,
|
||||
),
|
||||
),
|
||||
});
|
||||
return cli;
|
||||
};
|
||||
|
||||
const logCliCommand = async <Value>(
|
||||
logger: Logger,
|
||||
command: string,
|
||||
execute: () => Promise<Value>,
|
||||
): Promise<Value> => {
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
const value = await execute();
|
||||
logger.info(
|
||||
{
|
||||
command,
|
||||
durationMs: Math.round((performance.now() - startedAt) * 100) / 100,
|
||||
status: "ok",
|
||||
},
|
||||
"CLI command completed",
|
||||
);
|
||||
return value;
|
||||
} catch (cause: unknown) {
|
||||
logger.error(
|
||||
{
|
||||
command,
|
||||
durationMs: Math.round((performance.now() - startedAt) * 100) / 100,
|
||||
status: "error",
|
||||
},
|
||||
"CLI command failed",
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
import { ConfigurationError } from "./domain/errors.js";
|
||||
import { err, ok, type Result } from "./domain/result.js";
|
||||
import type { LogLevel } from "./logger.js";
|
||||
|
||||
const DEFAULT_HOPPER_LAUNCHER_PATH =
|
||||
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper";
|
||||
@@ -11,6 +12,7 @@ export interface AppConfig {
|
||||
readonly hopperTargetPath: string | undefined;
|
||||
readonly hopperTargetKind: "executable" | "database";
|
||||
readonly hopperLoaderArgs: readonly string[];
|
||||
readonly logLevel: LogLevel;
|
||||
}
|
||||
|
||||
const environmentSchema = z.object({
|
||||
@@ -18,6 +20,9 @@ const environmentSchema = z.object({
|
||||
HOPPER_TARGET_PATH: z.string().min(1).optional(),
|
||||
HOPPER_TARGET_KIND: z.enum(["executable", "database"]).default("executable"),
|
||||
HOPPER_LOADER_ARGS_JSON: z.string().optional(),
|
||||
REA_LOG_LEVEL: z
|
||||
.enum(["trace", "debug", "info", "warn", "error", "fatal", "silent"])
|
||||
.default("info"),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -66,5 +71,6 @@ export const parseConfig = (
|
||||
hopperTargetPath: parsedEnvironment.data.HOPPER_TARGET_PATH,
|
||||
hopperTargetKind: parsedEnvironment.data.HOPPER_TARGET_KIND,
|
||||
hopperLoaderArgs: parsedArgs.data,
|
||||
logLevel: parsedEnvironment.data.REA_LOG_LEVEL,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { BridgeLaunch, BridgeLauncher } from "./BridgeLauncher.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import {
|
||||
parseResponseLine,
|
||||
responseResult,
|
||||
@@ -29,6 +30,7 @@ export interface HopperClientOptions {
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly startupTimeoutMs?: number;
|
||||
readonly onDiagnostic?: (event: HopperDiagnostic) => void;
|
||||
readonly logger?: Logger;
|
||||
}
|
||||
|
||||
/** Safe launcher telemetry; stderr content is intentionally never exposed. */
|
||||
@@ -62,6 +64,7 @@ export class HopperClient {
|
||||
> &
|
||||
HopperClientOptions;
|
||||
readonly #pending = new Map<number, PendingRequest>();
|
||||
readonly #logger: Logger;
|
||||
#socket: Socket | undefined;
|
||||
#launch: BridgeLaunch | undefined;
|
||||
#directory: string | undefined;
|
||||
@@ -73,6 +76,7 @@ export class HopperClient {
|
||||
#closePromise: Promise<void> | undefined;
|
||||
|
||||
constructor(options: HopperClientOptions) {
|
||||
this.#logger = options.logger ?? silentLogger;
|
||||
this.#options = {
|
||||
...options,
|
||||
requestTimeoutMs: options.requestTimeoutMs ?? 30_000,
|
||||
@@ -224,6 +228,7 @@ export class HopperClient {
|
||||
if (options.signal?.aborted === true)
|
||||
return err(new HopperCancelledError());
|
||||
const id = this.#nextId++;
|
||||
const startedAt = performance.now();
|
||||
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
|
||||
const response = new Promise<Result<JsonValue, HopperError>>((resolve) => {
|
||||
const onAbort =
|
||||
@@ -252,7 +257,17 @@ export class HopperClient {
|
||||
this.#settle(id, err(new HopperProcessError(null)));
|
||||
},
|
||||
);
|
||||
return response;
|
||||
const result = await response;
|
||||
this.#logger[result.ok ? "debug" : "warn"](
|
||||
{
|
||||
method,
|
||||
durationMs: Math.round((performance.now() - startedAt) * 100) / 100,
|
||||
status: result.ok ? "ok" : "error",
|
||||
...(result.ok ? {} : { errorTag: result.error._tag }),
|
||||
},
|
||||
"Hopper bridge request completed",
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
#attachSocket(socket: Socket): void {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import pino, { type Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
|
||||
/** Supported structured log levels at the process boundary. */
|
||||
export type LogLevel = z.infer<typeof logLevelSchema>;
|
||||
|
||||
const logLevelSchema = z
|
||||
.enum(["trace", "debug", "info", "warn", "error", "fatal", "silent"])
|
||||
.default("info");
|
||||
|
||||
/** Parse the optional REA_LOG_LEVEL environment variable. */
|
||||
export const parseLogLevel = (value: unknown): LogLevel =>
|
||||
logLevelSchema.parse(value);
|
||||
|
||||
/** Create a JSON logger whose destination cannot corrupt MCP stdout frames. */
|
||||
export const createLogger = (mode: "mcp" | "cli", level: LogLevel): Logger =>
|
||||
pino(
|
||||
{
|
||||
level,
|
||||
base: { application: "rea", mode },
|
||||
redact: {
|
||||
paths: [
|
||||
"token",
|
||||
"*.token",
|
||||
"params",
|
||||
"*.params",
|
||||
"arguments",
|
||||
"*.arguments",
|
||||
"environment",
|
||||
"*.environment",
|
||||
],
|
||||
censor: "[Redacted]",
|
||||
},
|
||||
},
|
||||
pino.destination({ dest: mode === "mcp" ? 2 : 1, sync: false }),
|
||||
);
|
||||
|
||||
/** Logger used by embedders that have not opted into process output. */
|
||||
export const silentLogger = pino({ level: "silent" });
|
||||
|
||||
export type { Logger };
|
||||
+12
-2
@@ -11,6 +11,7 @@ import {
|
||||
import { parseConfig } from "./config.js";
|
||||
import { createBinarySession } from "./application/runtime.js";
|
||||
import { createServer } from "./server/createServer.js";
|
||||
import { createLogger } from "./logger.js";
|
||||
|
||||
/**
|
||||
* Start the long-lived MCP adapter and install idempotent shutdown handlers.
|
||||
@@ -23,27 +24,35 @@ export const run = async (): Promise<number> => {
|
||||
process.stderr.write(`${config.error._tag}: ${config.error.message}\n`);
|
||||
return 1;
|
||||
}
|
||||
const logger = createLogger("mcp", config.value.logLevel);
|
||||
const serverLogger = logger.child({ layer: "server" });
|
||||
|
||||
const session = createBinarySession(config.value);
|
||||
const session = createBinarySession(config.value, logger);
|
||||
if (config.value.hopperTargetPath !== undefined) {
|
||||
const opened = await session.open(config.value.hopperTargetPath, {
|
||||
targetKind: config.value.hopperTargetKind,
|
||||
});
|
||||
if (!opened.ok) {
|
||||
await session.close();
|
||||
serverLogger.error(
|
||||
{ errorTag: opened.error._tag },
|
||||
"Initial target failed to open",
|
||||
);
|
||||
process.stderr.write(`${opened.error._tag}: ${opened.error.message}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
let handle: StdioServerHandle;
|
||||
try {
|
||||
handle = serveStdio(() => createServer(session, session), {
|
||||
handle = serveStdio(() => createServer(session, session, logger), {
|
||||
onerror: () => {
|
||||
serverLogger.error("MCP stdio transport error");
|
||||
process.stderr.write("MCP stdio transport error\n");
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
await session.close();
|
||||
serverLogger.error("Failed to start MCP stdio transport");
|
||||
process.stderr.write("Failed to start MCP stdio transport\n");
|
||||
return 1;
|
||||
}
|
||||
@@ -59,6 +68,7 @@ export const run = async (): Promise<number> => {
|
||||
const requestShutdown = (): void => {
|
||||
shutdown().catch(() => {
|
||||
process.exitCode = 1;
|
||||
serverLogger.error("Failed to shut down cleanly");
|
||||
process.stderr.write("Failed to shut down cleanly\n");
|
||||
});
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { registerEnhancedTools } from "./registerEnhancedTools.js";
|
||||
import { registerOfficialTools } from "./registerOfficialTools.js";
|
||||
import { registerSessionTools } from "./registerSessionTools.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
|
||||
/**
|
||||
* Construct one MCP server without acquiring subprocess resources.
|
||||
@@ -15,6 +16,7 @@ import { registerSessionTools } from "./registerSessionTools.js";
|
||||
export const createServer = (
|
||||
hopper: HopperToolPort,
|
||||
session?: BinarySession,
|
||||
logger: Logger = silentLogger,
|
||||
): McpServer => {
|
||||
const server = new McpServer(
|
||||
{ name: PRODUCT_IDENTITY.mcpServerKey, version: "0.1.0" },
|
||||
@@ -26,8 +28,9 @@ export const createServer = (
|
||||
: "Reverse-engineering tools for Hopper Disassembler. Open a target with open_binary, then start with binary_overview.",
|
||||
},
|
||||
);
|
||||
registerOfficialTools(server, hopper);
|
||||
registerEnhancedTools(server, hopper);
|
||||
if (session !== undefined) registerSessionTools(server, session);
|
||||
const toolLogger = logger.child({ layer: "server" });
|
||||
registerOfficialTools(server, hopper, toolLogger);
|
||||
registerEnhancedTools(server, hopper, toolLogger);
|
||||
if (session !== undefined) registerSessionTools(server, session, toolLogger);
|
||||
return server;
|
||||
};
|
||||
|
||||
@@ -8,15 +8,18 @@ import {
|
||||
type ToolContract,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
|
||||
/** Register composed workflows against the same port as direct bridge tools. */
|
||||
export const registerEnhancedTools = (
|
||||
server: McpServer,
|
||||
hopper: HopperToolPort,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
const services = new EnhancedTools(hopper);
|
||||
for (const contract of ENHANCED_TOOL_CONTRACTS) {
|
||||
registerEnhancedTool(server, services, contract);
|
||||
registerEnhancedTool(server, services, contract, logger);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -24,6 +27,7 @@ const registerEnhancedTool = (
|
||||
server: McpServer,
|
||||
services: EnhancedTools,
|
||||
contract: ToolContract,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
const name = enhancedToolNameSchema.parse(contract.name);
|
||||
server.registerTool(
|
||||
@@ -31,7 +35,9 @@ const registerEnhancedTool = (
|
||||
{ description: contract.description, inputSchema: contract.inputSchema },
|
||||
async (input, context) =>
|
||||
toCallToolResult(
|
||||
await services.execute(name, input, context.mcpReq.signal),
|
||||
await logToolExecution(logger, name, () =>
|
||||
services.execute(name, input, context.mcpReq.signal),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -7,14 +7,17 @@ import {
|
||||
} from "../contracts/toolContracts.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../hopper/protocol.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
|
||||
/** Register direct bridge proxies, preserving MCP cancellation and typed errors. */
|
||||
export const registerOfficialTools = (
|
||||
server: McpServer,
|
||||
hopper: HopperToolPort,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
for (const contract of OFFICIAL_TOOL_CONTRACTS) {
|
||||
registerOfficialTool(server, hopper, contract);
|
||||
registerOfficialTool(server, hopper, contract, logger);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -22,6 +25,7 @@ const registerOfficialTool = (
|
||||
server: McpServer,
|
||||
hopper: HopperToolPort,
|
||||
contract: ToolContract,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
@@ -31,9 +35,11 @@ const registerOfficialTool = (
|
||||
},
|
||||
async (input, context) => {
|
||||
const arguments_ = projectOfficialArguments(contract, input);
|
||||
const result = await hopper.callTool(contract.name, arguments_, {
|
||||
signal: context.mcpReq.signal,
|
||||
});
|
||||
const result = await logToolExecution(logger, contract.name, () =>
|
||||
hopper.callTool(contract.name, arguments_, {
|
||||
signal: context.mcpReq.signal,
|
||||
}),
|
||||
);
|
||||
return toCallToolResult(result);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -4,11 +4,14 @@ import { z } from "zod";
|
||||
import type { BinarySession } from "../application/BinarySession.js";
|
||||
import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
|
||||
/** Register MCP-only target lifecycle operations on a long-lived session. */
|
||||
export const registerSessionTools = (
|
||||
server: McpServer,
|
||||
session: BinarySession,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
const [openContract, closeContract, statusContract] = SESSION_TOOL_CONTRACTS;
|
||||
server.registerTool(
|
||||
@@ -19,9 +22,9 @@ export const registerSessionTools = (
|
||||
},
|
||||
async (input, context) => {
|
||||
const parsed = z.object({ path: z.string().min(1) }).parse(input);
|
||||
const opened = await session.open(parsed.path, {
|
||||
signal: context.mcpReq.signal,
|
||||
});
|
||||
const opened = await logToolExecution(logger, openContract.name, () =>
|
||||
session.open(parsed.path, { signal: context.mcpReq.signal }),
|
||||
);
|
||||
return opened.ok
|
||||
? toCallToolResult({
|
||||
ok: true,
|
||||
@@ -41,7 +44,12 @@ export const registerSessionTools = (
|
||||
description: closeContract.description,
|
||||
inputSchema: closeContract.inputSchema,
|
||||
},
|
||||
async () => toCallToolResult(await session.close()),
|
||||
async () =>
|
||||
toCallToolResult(
|
||||
await logToolExecution(logger, closeContract.name, () =>
|
||||
session.close(),
|
||||
),
|
||||
),
|
||||
);
|
||||
server.registerTool(
|
||||
statusContract.name,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
/** Log one MCP tool's duration and status without recording caller input. */
|
||||
export const logToolExecution = async <Value, Failure>(
|
||||
logger: Logger,
|
||||
tool: string,
|
||||
execute: () => Promise<Result<Value, Failure>>,
|
||||
): Promise<Result<Value, Failure>> => {
|
||||
const startedAt = performance.now();
|
||||
const result = await execute();
|
||||
logger[result.ok ? "info" : "warn"](
|
||||
{
|
||||
tool,
|
||||
durationMs: Math.round((performance.now() - startedAt) * 100) / 100,
|
||||
status: result.ok ? "ok" : "error",
|
||||
},
|
||||
"MCP tool execution completed",
|
||||
);
|
||||
return result;
|
||||
};
|
||||
Reference in New Issue
Block a user