Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
feat(mcp): make MCP startup phase budgets configurable (#6304)
morluto584937c7611e
diff --git a/docs/client-configuration.md b/docs/client-configuration.mdindex 1c61c4787..b1235de55 100644--- a/docs/client-configuration.md+++ b/docs/client-configuration.md@@ -249,7 +249,19 @@ registration supports `startup_timeout_sec` for connection initialization andstartup timeout and a tool timeout derived from the known providerallowance plus 120 seconds of operation headroom. This yields 450 seconds forthe default Ghidra allowance; an explicit Ghidra startup timeout of 2700-seconds yields 2820 seconds. Setup preserves positive caller-selected timeout+seconds yields 2820 seconds. That 30-second Codex figure is client guidance.+REA's own phase budgets are `REA_MCP_INITIALIZE_BUDGET_MS` (default 15000),+`REA_MCP_TOOLS_LIST_BUDGET_MS` (default 5000),+`REA_MCP_FIRST_CATALOG_BUDGET_MS` (default 20000), and+`REA_MCP_DOCTOR_DEADLINE_MS` (default 30000). Each is a positive decimal+integer of milliseconds from 1 to 2147483647. Unset keeps the default.+Invalid values fail configuration and name the setting. Setup copies a+caller-selected value into the registration, and a change is read from the+environment that starts REA, so it needs a restart. Doctor and packaged+startup probes name the effective milliseconds, whether they came from the+default or the setting, the default, the floor, and the maximum. REA does+not enforce Codex's 30 seconds as the doctor deadline. The 120000 ms+tool-operation headroom and the 64 KiB doctor stderr cap stay fixed. Setup preserves positive caller-selected timeoutvalues in the REA entry, and doctor reports a non-blocking advisory when a tooltimeout is shorter than the known provider allowance. An explicitly selectedJEB request budget also contributes to the allowance. A configured IDAdiff --git a/scripts/lib/mcp-startup-probe.d.mts b/scripts/lib/mcp-startup-probe.d.mtsindex 4d4d704ea..dda222485 100644--- a/scripts/lib/mcp-startup-probe.d.mts+++ b/scripts/lib/mcp-startup-probe.d.mts@@ -1,9 +1,9 @@-interface McpStartupPolicy {- readonly initializeBudgetMs: number;- readonly toolsListBudgetMs: number;- readonly firstCatalogBudgetMs: number;- readonly doctorDeadlineMs: number;-}+import type {+ McpPhaseBudget,+ McpStartupBudgets,+} from "../../src/config/mcpStartupBudgets.js";++type McpStartupPolicy = McpStartupBudgets;interface McpProcessOptions {readonly command: string;@@ -47,12 +47,8 @@ export function profileMcpModuleLoading(/** Parse Linux procfs VmRSS text into bytes. */export function parseLinuxVmRssBytes(status: string): number | null;-/** Name a fixed MCP startup phase budget. Mirrors `fixedMcpPhaseBudgetRecovery`. */-export function fixedMcpStartupPhaseBudgetRecovery(- phase: string,- value: number,- unit: "ms" | "bytes",-): string;+/** Name one MCP startup phase budget. Mirrors `mcpPhaseBudgetRecovery`. */+export function mcpStartupPhaseBudgetRecovery(budget: McpPhaseBudget): string;/** Collect unique file-backed ESM module URLs from Node diagnostics. */export function createEsmModuleProfileCollector(packageName?: string): {diff --git a/scripts/lib/mcp-startup-probe.mjs b/scripts/lib/mcp-startup-probe.mjsindex 5f1c42cc7..82975e56f 100644--- a/scripts/lib/mcp-startup-probe.mjs+++ b/scripts/lib/mcp-startup-probe.mjs@@ -33,22 +33,24 @@ export async function measureMcpStartup({version: "1.0.0",});const startedAt = performance.now();+ // One deadline for both phases. Each request also uses the time still left,+ // so a shorter first-catalog budget stops a pending initialize or tools/list+ // instead of waiting out that phase's own budget.+ const firstCatalog = armFirstCatalogDeadline(policy.firstCatalog, startedAt);rss.start();try {- await withFixedPhaseBudget(- "MCP initialize phase budget",- policy.initializeBudgetMs,- "ms",- () => client.connect(transport, { timeout: policy.initializeBudgetMs }),+ await awaitPhaseWithinFirstCatalog(+ policy.initialize,+ firstCatalog,+ (timeout) => client.connect(transport, { timeout }),);const initializedAt = performance.now();- const tools = await withFixedPhaseBudget(- "MCP tools/list phase budget",- policy.toolsListBudgetMs,- "ms",- () =>+ const tools = await awaitPhaseWithinFirstCatalog(+ policy.toolsList,+ firstCatalog,+ (timeout) =>client.listTools(undefined, {- timeout: policy.toolsListBudgetMs,+ timeout,}),);const listedAt = performance.now();@@ -69,6 +71,7 @@ export async function measureMcpStartup({{ cause },);} finally {+ firstCatalog.clear();rss.stop();await Promise.allSettled([client.close(), transport.close()]);}@@ -97,23 +100,15 @@ export async function profileMcpModuleLoading({version: "1.0.0",});try {- await withFixedPhaseBudget(- "MCP doctor startup deadline",- policy.doctorDeadlineMs,- "ms",- () =>- client.connect(transport, {- timeout: policy.doctorDeadlineMs,- }),+ await withPhaseBudget(policy.doctor, () =>+ client.connect(transport, {+ timeout: policy.doctor.milliseconds,+ }),);- await withFixedPhaseBudget(- "MCP tools/list phase budget",- policy.toolsListBudgetMs,- "ms",- () =>- client.listTools(undefined, {- timeout: policy.toolsListBudgetMs,- }),+ await withPhaseBudget(policy.toolsList, () =>+ client.listTools(undefined, {+ timeout: policy.toolsList.milliseconds,+ }),);return profile.result();} finally {@@ -224,9 +219,12 @@ const createLinuxRssSampler = (pid) => {};};-/** Same sentence as `fixedMcpPhaseBudgetRecovery`; this script cannot import that TypeScript module. */-export const fixedMcpStartupPhaseBudgetRecovery = (phase, value, unit) =>- `REA's fixed ${phase} is ${String(value)} ${unit} and this release has no runtime override.`;+/** Same sentence as `mcpPhaseBudgetRecovery`; this script cannot import that TypeScript module. */+export const mcpStartupPhaseBudgetRecovery = (budget) =>+ [+ `The effective ${budget.setting} value for the ${budget.phase} is ${String(budget.milliseconds)} ms (source ${budget.source}; default ${String(budget.defaultMilliseconds)} ms, floor ${String(budget.floorMilliseconds)} ms, maximum ${String(budget.maximumMilliseconds)} ms).`,+ `Set ${budget.setting} in the environment that starts REA to a positive decimal integer from ${String(budget.floorMilliseconds)} to ${String(budget.maximumMilliseconds)}, then restart REA.`,+ ].join(" ");const phaseTimeout = (cause) => {const message = cause instanceof Error ? cause.message : String(cause);@@ -237,34 +235,93 @@ const phaseTimeout = (cause) => {);};-const withFixedPhaseBudget = async (phase, value, unit, operation) => {+const withPhaseBudget = async (budget, operation) => {try {return await operation();} catch (cause) {if (!phaseTimeout(cause)) throw cause;const detail = cause instanceof Error ? cause.message : String(cause);- throw new Error(- `${detail} ${fixedMcpStartupPhaseBudgetRecovery(phase, value, unit)}`,- { cause },- );+ throw new Error(`${detail} ${mcpStartupPhaseBudgetRecovery(budget)}`, {+ cause,+ });}};+const firstCatalogBudgetExceeded = (budget) =>+ new Error(+ `packaged MCP exceeded the first-catalog phase budget. ${mcpStartupPhaseBudgetRecovery(budget)}`,+ );++/**+ * Wall-clock end of the first-catalog budget, measured from the same instant+ * as the phase durations. The SDK timeout starts only once its request is+ * sent, so this timer still stops a child that has not reached that request.+ */+const armFirstCatalogDeadline = (budget, startedAt) => {+ const deadline = startedAt + budget.milliseconds;+ let timer;+ const expired = new Promise((resolve) => {+ timer = setTimeout(+ resolve,+ Math.max(1, Math.ceil(deadline - performance.now())),+ );+ });+ return {+ budget,+ deadline,+ expired,+ clear() {+ clearTimeout(timer);+ },+ };+};++const phaseRequestTimeout = (phase, deadline) => {+ const remaining = deadline - performance.now();+ if (remaining <= 0) return 0;+ return Math.max(1, Math.min(phase.milliseconds, Math.ceil(remaining)));+};++/**+ * Bound one pending phase by its own budget and by the time left in the+ * first-catalog budget. The recovery names whichever bound is shorter.+ */+const awaitPhaseWithinFirstCatalog = async (phase, firstCatalog, operation) => {+ const timeout = phaseRequestTimeout(phase, firstCatalog.deadline);+ if (timeout === 0) throw firstCatalogBudgetExceeded(firstCatalog.budget);+ const remaining = firstCatalog.deadline - performance.now();+ const budget = remaining < phase.milliseconds ? firstCatalog.budget : phase;+ const pending = withPhaseBudget(budget, () => operation(timeout)).then(+ (value) => ({ kind: "fulfilled", value }),+ (cause) => ({ kind: "rejected", cause }),+ );+ const outcome = await Promise.race([+ pending,+ firstCatalog.expired.then(() => ({ kind: "expired" })),+ ]);+ if (outcome.kind === "expired")+ throw firstCatalogBudgetExceeded(firstCatalog.budget);+ if (outcome.kind === "rejected") throw outcome.cause;+ return outcome.value;+};+const assertStartupBudgets = (measurement, policy) => {- if (measurement.process_started_to_initialized_ms > policy.initializeBudgetMs)+ if (+ measurement.process_started_to_initialized_ms >+ policy.initialize.milliseconds+ )throw new Error(- `packaged MCP exceeded the initialize phase budget. ${fixedMcpStartupPhaseBudgetRecovery("MCP initialize phase budget", policy.initializeBudgetMs, "ms")}`,+ `packaged MCP exceeded the initialize phase budget. ${mcpStartupPhaseBudgetRecovery(policy.initialize)}`,);- if (measurement.initialized_to_tools_list_ms > policy.toolsListBudgetMs)+ if (measurement.initialized_to_tools_list_ms > policy.toolsList.milliseconds)throw new Error(- `packaged MCP exceeded the tools/list phase budget. ${fixedMcpStartupPhaseBudgetRecovery("MCP tools/list phase budget", policy.toolsListBudgetMs, "ms")}`,+ `packaged MCP exceeded the tools/list phase budget. ${mcpStartupPhaseBudgetRecovery(policy.toolsList)}`,);if (- measurement.process_started_to_tools_list_ms > policy.firstCatalogBudgetMs+ measurement.process_started_to_tools_list_ms >+ policy.firstCatalog.milliseconds)- throw new Error(- `packaged MCP exceeded the first-catalog phase budget. ${fixedMcpStartupPhaseBudgetRecovery("MCP first-catalog phase budget", policy.firstCatalogBudgetMs, "ms")}`,- );+ throw firstCatalogBudgetExceeded(policy.firstCatalog);};const elapsed = (startedAt, completedAt) =>diff --git a/scripts/verify-package-mcp.mjs b/scripts/verify-package-mcp.mjsindex fda067dbe..f4dcbccdd 100644--- a/scripts/verify-package-mcp.mjs+++ b/scripts/verify-package-mcp.mjs@@ -10,7 +10,7 @@ import { readFile, rm } from "node:fs/promises";import { Client } from "@modelcontextprotocol/client";import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";-import { MCP_STARTUP_POLICY } from "../dist/mcpStartupPolicy.js";+import { resolveMcpStartupProbePolicy } from "../dist/mcpStartupPolicy.js";import { parseEvidence } from "../dist/domain/evidence.js";import * as prompts from "./verify-package-prompts.mjs";import { json, verifyCompleteToolCatalog } from "./lib/verify-package-core.mjs";@@ -257,7 +257,7 @@ export async function verifyPackageMcp({(await execute(cli, ["mcp", "doctor", "--json"], {env: environment,- timeout: MCP_STARTUP_POLICY.doctorDeadlineMs,+ timeout: resolveMcpStartupProbePolicy(environment).doctor.milliseconds,})).stdout,);diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjsindex 32bad0a62..6baa081f4 100644--- a/scripts/verify-package.mjs+++ b/scripts/verify-package.mjs@@ -6,7 +6,7 @@ import { promisify } from "node:util";import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";import { PRODUCT_IDENTITY } from "../dist/identity.js";-import { MCP_STARTUP_POLICY } from "../dist/mcpStartupPolicy.js";+import { resolveMcpStartupProbePolicy } from "../dist/mcpStartupPolicy.js";import * as prompts from "./verify-package-prompts.mjs";import { verifyPackageArtifactAndElectron } from "./verify-package-artifact.mjs";import { verifyPackageCapabilitiesAndSearch } from "./verify-package-capabilities.mjs";@@ -124,7 +124,7 @@ try {environment: {...environmentData.environment,},- policy: MCP_STARTUP_POLICY,+ policy: resolveMcpStartupProbePolicy(environmentData.environment),}),);mcpModuleLoading = await runStage("MCP module loading", () =>@@ -134,7 +134,7 @@ try {environment: {...environmentData.environment,},- policy: MCP_STARTUP_POLICY,+ policy: resolveMcpStartupProbePolicy(environmentData.environment),packageName: PRODUCT_IDENTITY.packageName,}),);diff --git a/src/application/Doctor.test.ts b/src/application/Doctor.test.tsindex 3187a4b88..a134fa2a6 100644--- a/src/application/Doctor.test.ts+++ b/src/application/Doctor.test.ts@@ -167,6 +167,10 @@ describe("doctor native analysis configuration", () => {["REA_REGEX_MATCHING_DEADLINE_MS", "0"],["REA_CAPTURE_DECODER_OLD_GENERATION_MIB", "7"],["REA_REGEX_WORKER_HEAP_REQUEST_MIB", "6"],+ ["REA_MCP_INITIALIZE_BUDGET_MS", "0"],+ ["REA_MCP_TOOLS_LIST_BUDGET_MS", "0"],+ ["REA_MCP_FIRST_CATALOG_BUDGET_MS", "0"],+ ["REA_MCP_DOCTOR_DEADLINE_MS", "0"],["REA_GHIDRA_STARTUP_TIMEOUT_MS", "abc"],["REA_SWIFTC_COMPILE_TIMEOUT_MS", "0"],["REA_LOG_LEVEL", "verbose"],diff --git a/src/application/SetupRegistrationEnvironment.ts b/src/application/SetupRegistrationEnvironment.tsindex 864c788d5..7ffef6da4 100644--- a/src/application/SetupRegistrationEnvironment.ts+++ b/src/application/SetupRegistrationEnvironment.ts@@ -10,6 +10,10 @@ const SELECTED_REGISTRATION_SETTINGS = ["REA_MCP_INPUT_SCHEMA_PROFILE","REA_REGEX_MATCHING_DEADLINE_MS","REA_REGEX_WORKER_HEAP_REQUEST_MIB",+ "REA_MCP_INITIALIZE_BUDGET_MS",+ "REA_MCP_TOOLS_LIST_BUDGET_MS",+ "REA_MCP_FIRST_CATALOG_BUDGET_MS",+ "REA_MCP_DOCTOR_DEADLINE_MS",] as const;/** Preserve selected setup settings without copying unrelated process values. */diff --git a/src/config/environment.ts b/src/config/environment.tsindex 09ca39fb5..72447f8b5 100644--- a/src/config/environment.ts+++ b/src/config/environment.ts@@ -22,6 +22,12 @@ import { asarMaxHeaderBytesSchema } from "./asarHeaderAdmission.js";import { captureDecoderOldGenerationMiBSchema } from "./captureDecoderHeap.js";import { regexMatchingDeadlineMsSchema } from "./regexMatchingDeadline.js";import { regexWorkerHeapRequestMiBSchema } from "./regexWorkerHeapRequest.js";+import {+ mcpDoctorDeadlineMsSchema,+ mcpFirstCatalogBudgetMsSchema,+ mcpInitializeBudgetMsSchema,+ mcpToolsListBudgetMsSchema,+} from "./mcpStartupBudgets.js";import { parseLoaderArgs, parseStringArray } from "./parsers.js";const environmentSchema = z.object({@@ -32,6 +38,10 @@ const environmentSchema = z.object({captureDecoderOldGenerationMiBSchema.optional(),REA_REGEX_MATCHING_DEADLINE_MS: regexMatchingDeadlineMsSchema.optional(),REA_REGEX_WORKER_HEAP_REQUEST_MIB: regexWorkerHeapRequestMiBSchema.optional(),+ REA_MCP_INITIALIZE_BUDGET_MS: mcpInitializeBudgetMsSchema.optional(),+ REA_MCP_TOOLS_LIST_BUDGET_MS: mcpToolsListBudgetMsSchema.optional(),+ REA_MCP_FIRST_CATALOG_BUDGET_MS: mcpFirstCatalogBudgetMsSchema.optional(),+ REA_MCP_DOCTOR_DEADLINE_MS: mcpDoctorDeadlineMsSchema.optional(),REA_MCP_INPUT_SCHEMA_PROFILE: mcpInputSchemaProfileSchema.optional(),REA_MCP_OUTPUT_SCHEMA_PROFILE: mcpOutputSchemaProfileSchema.optional(),REA_IDA_MCP_CONFIG: zdiff --git a/src/config/mcpStartupBudgets.test.ts b/src/config/mcpStartupBudgets.test.tsnew file mode 100644index 000000000..5a75de587--- /dev/null+++ b/src/config/mcpStartupBudgets.test.ts@@ -0,0 +1,117 @@+import { expect, it } from "vitest";++import { ConfigurationError } from "../domain/configurationErrors.js";+import { projectAnalysisError } from "../domain/analysisErrorProjection.js";+import { parseEnvironment } from "./environment.js";+import {+ DEFAULT_MCP_STARTUP_BUDGETS,+ MCP_PHASE_BUDGET_MAXIMUM_MS,+ parseMcpStartupBudgets,+ resolveMcpStartupBudgets,+} from "./mcpStartupBudgets.js";+import { parseConfig } from "./parseConfig.js";++it("keeps today's phase budgets when the settings are unset", () => {+ expect(parseMcpStartupBudgets({})).toEqual({+ ok: true,+ value: DEFAULT_MCP_STARTUP_BUDGETS,+ });+ expect(resolveMcpStartupBudgets({})).toEqual(DEFAULT_MCP_STARTUP_BUDGETS);+ const parsed = parseConfig({});+ if (!parsed.ok) throw new Error("unset phase budgets were rejected");+ expect(parsed.value.analysisProvider).toBe("auto");+});++it("uses valid phase budget overrides", () => {+ expect(+ parseMcpStartupBudgets({+ REA_MCP_INITIALIZE_BUDGET_MS: "16000",+ REA_MCP_TOOLS_LIST_BUDGET_MS: "6000",+ REA_MCP_FIRST_CATALOG_BUDGET_MS: "21000",+ REA_MCP_DOCTOR_DEADLINE_MS: String(MCP_PHASE_BUDGET_MAXIMUM_MS),+ }),+ ).toEqual({+ ok: true,+ value: {+ initialize: {+ ...DEFAULT_MCP_STARTUP_BUDGETS.initialize,+ milliseconds: 16_000,+ source: "setting",+ },+ toolsList: {+ ...DEFAULT_MCP_STARTUP_BUDGETS.toolsList,+ milliseconds: 6_000,+ source: "setting",+ },+ firstCatalog: {+ ...DEFAULT_MCP_STARTUP_BUDGETS.firstCatalog,+ milliseconds: 21_000,+ source: "setting",+ },+ doctor: {+ ...DEFAULT_MCP_STARTUP_BUDGETS.doctor,+ milliseconds: MCP_PHASE_BUDGET_MAXIMUM_MS,+ source: "setting",+ },+ },+ });+ const parsed = parseConfig({ REA_MCP_DOCTOR_DEADLINE_MS: "31000" });+ if (!parsed.ok) throw new Error("valid doctor deadline was rejected");+});++it.each([+ ["REA_MCP_INITIALIZE_BUDGET_MS", ""],+ ["REA_MCP_INITIALIZE_BUDGET_MS", "0"],+ ["REA_MCP_TOOLS_LIST_BUDGET_MS", "-1"],+ ["REA_MCP_FIRST_CATALOG_BUDGET_MS", "020000"],+ ["REA_MCP_DOCTOR_DEADLINE_MS", "10_000"],+ ["REA_MCP_DOCTOR_DEADLINE_MS", "1e4"],+ ["REA_MCP_INITIALIZE_BUDGET_MS", " 15000"],+ ["REA_MCP_TOOLS_LIST_BUDGET_MS", "5000 "],+ ["REA_MCP_FIRST_CATALOG_BUDGET_MS", "1.5"],+ ["REA_MCP_DOCTOR_DEADLINE_MS", String(MCP_PHASE_BUDGET_MAXIMUM_MS + 1)],+ ["REA_MCP_INITIALIZE_BUDGET_MS", "9".repeat(40)],+])("rejects invalid %s=%j as a configuration error", (setting, value) => {+ const parsed = parseMcpStartupBudgets({ [setting]: value });+ if (parsed.ok)+ throw new Error(`Accepted ${setting}=${JSON.stringify(value)}`);+ expect(parsed.error).toBeInstanceOf(ConfigurationError);+ expect(parsed.error.settings).toEqual([+ {+ setting,+ constraint: expect.stringContaining(+ `${setting} must be a positive decimal integer from 1 to 2147483647 ms`,+ ),+ },+ ]);+ expect(parsed.error.message).toContain(setting);+ const startup = parseEnvironment({ [setting]: value });+ if (startup.ok) throw new Error(`Startup accepted ${setting}`);+ expect(startup.error.settings).toContainEqual({+ setting,+ constraint: expect.stringContaining("from 1 to 2147483647 ms"),+ });+ const config = parseConfig({ [setting]: value });+ if (config.ok) throw new Error(`parseConfig accepted ${setting}`);+ expect(projectAnalysisError(config.error)).toMatchObject({+ code: "configuration_invalid",+ message: expect.stringContaining(setting),+ });+ expect(() => resolveMcpStartupBudgets({ [setting]: value })).toThrow(+ ConfigurationError,+ );+});++it("names every invalid phase budget instead of keeping a default", () => {+ const parsed = parseMcpStartupBudgets({+ REA_MCP_INITIALIZE_BUDGET_MS: "0",+ REA_MCP_TOOLS_LIST_BUDGET_MS: "6000",+ REA_MCP_DOCTOR_DEADLINE_MS: "nope",+ });+ if (parsed.ok) throw new Error("invalid budgets were accepted");+ expect(parsed.error.settings.map(({ setting }) => setting)).toEqual([+ "REA_MCP_INITIALIZE_BUDGET_MS",+ "REA_MCP_DOCTOR_DEADLINE_MS",+ ]);+ expect(parsed.error.message).not.toContain("6000");+});diff --git a/src/config/mcpStartupBudgets.ts b/src/config/mcpStartupBudgets.tsnew file mode 100644index 000000000..8b0cd9c79--- /dev/null+++ b/src/config/mcpStartupBudgets.ts@@ -0,0 +1,216 @@+import { z } from "zod";++import { ConfigurationError } from "../domain/configurationErrors.js";+import { err, ok, type Result } from "../domain/result.js";++/** Smallest phase budget. Zero is not a deadline, and Node's timer needs a positive delay. */+export const MCP_PHASE_BUDGET_FLOOR_MS = 1;++/**+ * Largest delay Node schedules exactly. A `setTimeout` delay above this+ * signed 32-bit bound is clamped to 1 ms, so a phase budget past it would+ * expire immediately. The setting stops here instead of growing without a bound.+ */+export const MCP_PHASE_BUDGET_MAXIMUM_MS = 2_147_483_647;++/** One MCP startup phase budget and where its effective milliseconds came from. */+export interface McpPhaseBudget {+ readonly setting: string;+ readonly phase: string;+ readonly milliseconds: number;+ readonly source: "default" | "setting";+ readonly defaultMilliseconds: number;+ readonly floorMilliseconds: number;+ readonly maximumMilliseconds: number;+}++/** Effective initialize, tools/list, first-catalog, and doctor budgets. */+export interface McpStartupBudgets {+ readonly initialize: McpPhaseBudget;+ readonly toolsList: McpPhaseBudget;+ readonly firstCatalog: McpPhaseBudget;+ readonly doctor: McpPhaseBudget;+}++interface McpPhaseBudgetDefinition {+ readonly key: keyof McpStartupBudgets;+ readonly setting: string;+ readonly phase: string;+ readonly defaultMilliseconds: number;+}++const PHASES = [+ {+ key: "initialize",+ setting: "REA_MCP_INITIALIZE_BUDGET_MS",+ phase: "MCP initialize phase budget",+ defaultMilliseconds: 15_000,+ },+ {+ key: "toolsList",+ setting: "REA_MCP_TOOLS_LIST_BUDGET_MS",+ phase: "MCP tools/list phase budget",+ defaultMilliseconds: 5_000,+ },+ {+ key: "firstCatalog",+ setting: "REA_MCP_FIRST_CATALOG_BUDGET_MS",+ phase: "MCP first-catalog phase budget",+ defaultMilliseconds: 20_000,+ },+ {+ key: "doctor",+ setting: "REA_MCP_DOCTOR_DEADLINE_MS",+ phase: "MCP doctor startup deadline",+ defaultMilliseconds: 30_000,+ },+] as const satisfies readonly McpPhaseBudgetDefinition[];++/** Initialize budget used when `REA_MCP_INITIALIZE_BUDGET_MS` is unset. */+export const DEFAULT_MCP_INITIALIZE_BUDGET_MS = PHASES[0].defaultMilliseconds;++/** tools/list budget used when `REA_MCP_TOOLS_LIST_BUDGET_MS` is unset. */+export const DEFAULT_MCP_TOOLS_LIST_BUDGET_MS = PHASES[1].defaultMilliseconds;++/** First-catalog budget used when `REA_MCP_FIRST_CATALOG_BUDGET_MS` is unset. */+export const DEFAULT_MCP_FIRST_CATALOG_BUDGET_MS =+ PHASES[2].defaultMilliseconds;++/** Doctor deadline used when `REA_MCP_DOCTOR_DEADLINE_MS` is unset. */+export const DEFAULT_MCP_DOCTOR_DEADLINE_MS = PHASES[3].defaultMilliseconds;++const phaseConstraint = (phase: McpPhaseBudgetDefinition): string =>+ `${phase.setting} must be a positive decimal integer from ${String(MCP_PHASE_BUDGET_FLOOR_MS)} to ${String(MCP_PHASE_BUDGET_MAXIMUM_MS)} ms; the default is ${String(phase.defaultMilliseconds)} ms. Node schedules a delay above that maximum as 1 ms, so a larger value is refused.`;++const decimalInteger = /^[1-9]\d*$/u;++const withinPhaseBudgetRange = (value: string): boolean => {+ // The pattern check reports a non-decimal value. Refine only bounds integers.+ if (!decimalInteger.test(value)) return true;+ const parsed = BigInt(value);+ return (+ parsed >= BigInt(MCP_PHASE_BUDGET_FLOOR_MS) &&+ parsed <= BigInt(MCP_PHASE_BUDGET_MAXIMUM_MS)+ );+};++const phaseBudgetSchema = (phase: McpPhaseBudgetDefinition) => {+ const constraint = phaseConstraint(phase);+ return z+ .string()+ .regex(decimalInteger, { error: constraint })+ .refine(withinPhaseBudgetRange, { error: constraint })+ .transform(Number);+};++/** Optional decimal millisecond count for the MCP initialize phase budget. */+export const mcpInitializeBudgetMsSchema = phaseBudgetSchema(PHASES[0]);++/** Optional decimal millisecond count for the MCP tools/list phase budget. */+export const mcpToolsListBudgetMsSchema = phaseBudgetSchema(PHASES[1]);++/** Optional decimal millisecond count for the MCP first-catalog phase budget. */+export const mcpFirstCatalogBudgetMsSchema = phaseBudgetSchema(PHASES[2]);++/** Optional decimal millisecond count for the MCP doctor startup deadline. */+export const mcpDoctorDeadlineMsSchema = phaseBudgetSchema(PHASES[3]);++const defaultBudget = (phase: McpPhaseBudgetDefinition): McpPhaseBudget => ({+ setting: phase.setting,+ phase: phase.phase,+ milliseconds: phase.defaultMilliseconds,+ source: "default",+ defaultMilliseconds: phase.defaultMilliseconds,+ floorMilliseconds: MCP_PHASE_BUDGET_FLOOR_MS,+ maximumMilliseconds: MCP_PHASE_BUDGET_MAXIMUM_MS,+});++/** Budgets used when every phase setting is unset. */+export const DEFAULT_MCP_STARTUP_BUDGETS: McpStartupBudgets = {+ initialize: defaultBudget(PHASES[0]),+ toolsList: defaultBudget(PHASES[1]),+ firstCatalog: defaultBudget(PHASES[2]),+ doctor: defaultBudget(PHASES[3]),+};++const parsePhaseBudget = (+ phase: McpPhaseBudgetDefinition,+ value: string | undefined,+): Result<McpPhaseBudget, ConfigurationError> => {+ if (value === undefined) return ok(defaultBudget(phase));+ const parsed = phaseBudgetSchema(phase).safeParse(value);+ return parsed.success+ ? ok({+ setting: phase.setting,+ phase: phase.phase,+ milliseconds: parsed.data,+ source: "setting",+ defaultMilliseconds: phase.defaultMilliseconds,+ floorMilliseconds: MCP_PHASE_BUDGET_FLOOR_MS,+ maximumMilliseconds: MCP_PHASE_BUDGET_MAXIMUM_MS,+ })+ : err(+ new ConfigurationError(phaseConstraint(phase), {+ settings: [+ { setting: phase.setting, constraint: phaseConstraint(phase) },+ ],+ }),+ );+};++/**+ * Resolve every phase budget from one environment. Invalid values are+ * configuration errors and do not fall back to the defaults. Every invalid+ * setting is reported together.+ */+export const parseMcpStartupBudgets = (+ environment: Readonly<Record<string, string | undefined>>,+): Result<McpStartupBudgets, ConfigurationError> => {+ const issues: { setting: string; constraint: string }[] = [];+ const budgets = new Map<keyof McpStartupBudgets, McpPhaseBudget>();+ for (const phase of PHASES) {+ const parsed = parsePhaseBudget(phase, environment[phase.setting]);+ if (!parsed.ok) issues.push(...parsed.error.settings);+ else budgets.set(phase.key, parsed.value);+ }+ if (issues.length > 0)+ return err(+ new ConfigurationError(+ issues.map(({ constraint }) => constraint).join(" "),+ {+ settings: issues,+ },+ ),+ );+ const initialize = budgets.get("initialize");+ const toolsList = budgets.get("toolsList");+ const firstCatalog = budgets.get("firstCatalog");+ const doctor = budgets.get("doctor");+ if (+ initialize === undefined ||+ toolsList === undefined ||+ firstCatalog === undefined ||+ doctor === undefined+ )+ throw new Error("MCP startup budget resolution dropped a phase");+ return ok({ initialize, toolsList, firstCatalog, doctor });+};++/**+ * Resolve the budgets from a composition root's selected environment. An+ * invalid setting is refused, not ignored.+ */+export const resolveMcpStartupBudgets = (+ environment: Readonly<Record<string, string | undefined>>,+): McpStartupBudgets => {+ const parsed = parseMcpStartupBudgets(environment);+ if (!parsed.ok) throw parsed.error;+ return parsed.value;+};++/** How to read and change one MCP startup phase budget. */+export const mcpPhaseBudgetRecovery = (budget: McpPhaseBudget): string =>+ [+ `The effective ${budget.setting} value for the ${budget.phase} is ${String(budget.milliseconds)} ms (source ${budget.source}; default ${String(budget.defaultMilliseconds)} ms, floor ${String(budget.floorMilliseconds)} ms, maximum ${String(budget.maximumMilliseconds)} ms).`,+ `Set ${budget.setting} in the environment that starts REA to a positive decimal integer from ${String(budget.floorMilliseconds)} to ${String(budget.maximumMilliseconds)}, then restart REA.`,+ ].join(" ");diff --git a/src/mcpDoctor.ts b/src/mcpDoctor.tsindex 67236c1ca..a2b087914 100644--- a/src/mcpDoctor.ts+++ b/src/mcpDoctor.ts@@ -15,6 +15,10 @@ import { PROMPT_CONTRACTS } from "./contracts/promptContracts.js";import { TOOL_CONTRACTS } from "./contracts/toolContracts.js";import { err, ok } from "./domain/result.js";import { PRODUCT_IDENTITY } from "./identity.js";+import {+ parseMcpStartupBudgets,+ type McpPhaseBudget,+} from "./config/mcpStartupBudgets.js";import {MCP_STARTUP_POLICY,mcpDoctorDeadlineRecovery,@@ -83,8 +87,35 @@ interface McpDoctorCheck {/** Diagnose the actual production stdio adapter with one startup-bounded SDK session. */export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {+ const parsedBudgets = parseMcpStartupBudgets(options.environment);+ if (!parsedBudgets.ok)+ return {+ healthy: false as const,+ adapter: "production-stdio" as const,+ server: null,+ inventory: null,+ identity: null,+ request_flow: {+ tool: "binary_session" as const,+ ok: false as const,+ },+ checks: parsedBudgets.error.settings.map((issue) => ({+ name: issue.setting,+ ok: false as const,+ detail: issue.constraint,+ })),+ diagnostics: {+ stderr: "",+ stderr_bytes: 0,+ stderr_truncated: false,+ },+ };const catalog = catalogIdentityForEnvironment(options.environment);- const budgetMs = options.deadlineMs ?? MCP_STARTUP_POLICY.doctorDeadlineMs;+ const budget = appliedDoctorBudget(+ parsedBudgets.value.doctor,+ options.deadlineMs,+ );+ const budgetMs = budget.milliseconds;const deadline = performance.now() + budgetMs;const controller = new AbortController();const timer = setTimeout(@@ -113,7 +144,7 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {deadline,controller.signal,catalog,- budgetMs,+ budget,);} catch (cause: unknown) {result = {@@ -127,7 +158,7 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {{name: "transport",ok: false,- detail: doctorTransportDetail(cause, budgetMs, controller.signal),+ detail: doctorTransportDetail(cause, budget, controller.signal),},],};@@ -200,7 +231,7 @@ const inspectProductionMcpSession = async (deadline: number,signal: AbortSignal,catalog: ReturnType<typeof createCatalogIdentity>,- budgetMs: number,+ budget: McpPhaseBudget,) => {const request = requestOptions(deadline, signal);const [tools, prompts] = await Promise.all([@@ -219,7 +250,7 @@ const inspectProductionMcpSession = async (.then(ok, (cause: unknown) =>err({kind: "request-flow" as const,- detail: doctorTransportDetail(cause, budgetMs, signal),+ detail: doctorTransportDetail(cause, budget, signal),}),);const inventory = {@@ -549,17 +580,39 @@ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>const errorMessage = (cause: unknown): string =>cause instanceof Error ? cause.message : String(cause);-/** Name the fixed doctor deadline when it fires, without turning Codex's 30s into a REA knob. */+/**+ * Name the applied doctor deadline when an owned abort or SDK request timeout+ * fires. Remote failure text is not a deadline. Codex's 30 second startup+ * figure stays client guidance and is not this deadline.+ */const doctorTransportDetail = (cause: unknown,- budgetMs: number,+ budget: McpPhaseBudget,signal: AbortSignal,): string => {const message = errorMessage(cause);const timedOut =(signal.aborted && cause === signal.reason) ||(cause instanceof SdkError && cause.code === SdkErrorCode.RequestTimeout);- return timedOut- ? `${message} ${mcpDoctorDeadlineRecovery(budgetMs)}`- : message;+ return timedOut ? `${message} ${mcpDoctorDeadlineRecovery(budget)}` : message;};++/**+ * `deadlineMs` is a caller-selected applied deadline, used by tests. Omitted+ * means the budget resolved from `REA_MCP_DOCTOR_DEADLINE_MS`.+ */+const appliedDoctorBudget = (+ resolved: McpPhaseBudget,+ deadlineMs: number | undefined,+): McpPhaseBudget =>+ deadlineMs === undefined+ ? resolved+ : {+ ...resolved,+ milliseconds: deadlineMs,+ source:+ deadlineMs === resolved.defaultMilliseconds &&+ resolved.source === "default"+ ? "default"+ : "setting",+ };diff --git a/src/mcpStartupPolicy.ts b/src/mcpStartupPolicy.tsindex d5fa08387..ef775c9d5 100644--- a/src/mcpStartupPolicy.ts+++ b/src/mcpStartupPolicy.ts@@ -1,38 +1,51 @@import type { AnalysisProviderSelector } from "./contracts/providerSelection.js";+import {+ DEFAULT_MCP_DOCTOR_DEADLINE_MS,+ DEFAULT_MCP_FIRST_CATALOG_BUDGET_MS,+ DEFAULT_MCP_INITIALIZE_BUDGET_MS,+ DEFAULT_MCP_TOOLS_LIST_BUDGET_MS,+ mcpPhaseBudgetRecovery,+ resolveMcpStartupBudgets,+ type McpPhaseBudget,+ type McpStartupBudgets,+} from "./config/mcpStartupBudgets.js";/*** Supported MCP startup deadlines and operation headroom.*- * Client timeouts are caller-facing configuration. The smaller phase budgets- * preserve operational headroom, while the doctor deadline covers additional- * inventory requests after initialization.+ * Client timeouts are caller-facing configuration. The phase budgets below+ * are the unset defaults of `REA_MCP_INITIALIZE_BUDGET_MS`,+ * `REA_MCP_TOOLS_LIST_BUDGET_MS`, `REA_MCP_FIRST_CATALOG_BUDGET_MS`, and+ * `REA_MCP_DOCTOR_DEADLINE_MS`. Callers that enforce a phase read+ * `resolveMcpStartupProbePolicy` so a selected value is not ignored.+ * `codexStartupTimeoutSeconds` stays client guidance and is not a setting.*/export const MCP_STARTUP_POLICY = {codexStartupTimeoutSeconds: 30,kimiStartupTimeoutMs: 30_000,toolOperationHeadroomMs: 120_000,- initializeBudgetMs: 15_000,- toolsListBudgetMs: 5_000,- firstCatalogBudgetMs: 20_000,- doctorDeadlineMs: 30_000,+ initializeBudgetMs: DEFAULT_MCP_INITIALIZE_BUDGET_MS,+ toolsListBudgetMs: DEFAULT_MCP_TOOLS_LIST_BUDGET_MS,+ firstCatalogBudgetMs: DEFAULT_MCP_FIRST_CATALOG_BUDGET_MS,+ doctorDeadlineMs: DEFAULT_MCP_DOCTOR_DEADLINE_MS,doctorStderrBytes: 64 * 1024,} as const;+/** Phase budgets the packaged startup probe enforces. */+export type McpStartupProbePolicy = McpStartupBudgets;+/**- * Recovery for a fixed MCP startup phase budget. Codex's startup figure is- * client guidance and is not named here; doctor text adds that distinction- * because its deadline uses the same 30 second magnitude.+ * Resolve the probe policy from the environment that starts the probe.+ * An invalid phase setting is refused. Codex's 30 second startup figure+ * is not part of this policy.*/-export const fixedMcpPhaseBudgetRecovery = (- phase: string,- value: number,- unit: "ms" | "bytes",-): string =>- `REA's fixed ${phase} is ${String(value)} ${unit} and this release has no runtime override.`;+export const resolveMcpStartupProbePolicy = (+ environment: Readonly<Record<string, string | undefined>>,+): McpStartupProbePolicy => resolveMcpStartupBudgets(environment);/** Doctor startup recovery. The Codex figure is client guidance REA does not enforce. */-export const mcpDoctorDeadlineRecovery = (budgetMs: number): string =>- `${fixedMcpPhaseBudgetRecovery("MCP doctor startup deadline", budgetMs, "ms")} Codex startup_timeout_sec of ${String(MCP_STARTUP_POLICY.codexStartupTimeoutSeconds)} seconds is client guidance; REA does not enforce that figure as this deadline.`;+export const mcpDoctorDeadlineRecovery = (budget: McpPhaseBudget): string =>+ `${mcpPhaseBudgetRecovery(budget)} Codex startup_timeout_sec of ${String(MCP_STARTUP_POLICY.codexStartupTimeoutSeconds)} seconds is client guidance; REA does not enforce that figure as this deadline.`;/** Parsed startup and upstream request budgets affecting a client's tool deadline. */export interface McpToolTimeoutInputs {diff --git a/src/setupEnvironment.test.ts b/src/setupEnvironment.test.tsindex 015e1badb..a065c51da 100644--- a/src/setupEnvironment.test.ts+++ b/src/setupEnvironment.test.ts@@ -188,6 +188,10 @@ it.each([REA_CAPTURE_DECODER_OLD_GENERATION_MIB: "256",REA_REGEX_MATCHING_DEADLINE_MS: "10000",REA_REGEX_WORKER_HEAP_REQUEST_MIB: "256",+ REA_MCP_INITIALIZE_BUDGET_MS: "16000",+ REA_MCP_TOOLS_LIST_BUDGET_MS: "6000",+ REA_MCP_FIRST_CATALOG_BUDGET_MS: "21000",+ REA_MCP_DOCTOR_DEADLINE_MS: "31000",},providerConfigured: false,installHopper: true,@@ -223,11 +227,21 @@ it.each([REA_CAPTURE_DECODER_OLD_GENERATION_MIB: "256",REA_REGEX_MATCHING_DEADLINE_MS: "10000",REA_REGEX_WORKER_HEAP_REQUEST_MIB: "256",+ REA_MCP_INITIALIZE_BUDGET_MS: "16000",+ REA_MCP_TOOLS_LIST_BUDGET_MS: "6000",+ REA_MCP_FIRST_CATALOG_BUDGET_MS: "21000",+ REA_MCP_DOCTOR_DEADLINE_MS: "31000",});} else {expect(initial.providerEnvironment).not.toHaveProperty("REA_REGEX_MATCHING_DEADLINE_MS",);+ expect(initial.providerEnvironment).not.toHaveProperty(+ "REA_REGEX_WORKER_HEAP_REQUEST_MIB",+ );+ expect(initial.providerEnvironment).not.toHaveProperty(+ "REA_MCP_INITIALIZE_BUDGET_MS",+ );}const discovery = await discoverSetupState({host: setupHost,diff --git a/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts b/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.tsindex 142426834..57e5b85a6 100644--- a/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts+++ b/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts@@ -489,6 +489,10 @@ cliTest(REA_CAPTURE_DECODER_OLD_GENERATION_MIB: "256",REA_REGEX_MATCHING_DEADLINE_MS: "10000",REA_REGEX_WORKER_HEAP_REQUEST_MIB: "256",+ REA_MCP_INITIALIZE_BUDGET_MS: "16000",+ REA_MCP_TOOLS_LIST_BUDGET_MS: "6000",+ REA_MCP_FIRST_CATALOG_BUDGET_MS: "21000",+ REA_MCP_DOCTOR_DEADLINE_MS: "31000",REA_UNRELATED_MARKER: "do-not-persist",};const run = (arguments_: readonly string[]) =>@@ -522,6 +526,10 @@ cliTest();expect(codexConfig).toContain('REA_REGEX_MATCHING_DEADLINE_MS = "10000"');expect(codexConfig).toContain('REA_REGEX_WORKER_HEAP_REQUEST_MIB = "256"');+ expect(codexConfig).toContain('REA_MCP_INITIALIZE_BUDGET_MS = "16000"');+ expect(codexConfig).toContain('REA_MCP_TOOLS_LIST_BUDGET_MS = "6000"');+ expect(codexConfig).toContain('REA_MCP_FIRST_CATALOG_BUDGET_MS = "21000"');+ expect(codexConfig).toContain('REA_MCP_DOCTOR_DEADLINE_MS = "31000"');expect(codexConfig).not.toContain("REA_UNRELATED_MARKER");const kimiPath = join(kimiHome, "mcp.json");@@ -540,6 +548,10 @@ cliTest(REA_CAPTURE_DECODER_OLD_GENERATION_MIB: "256",REA_REGEX_MATCHING_DEADLINE_MS: "10000",REA_REGEX_WORKER_HEAP_REQUEST_MIB: "256",+ REA_MCP_INITIALIZE_BUDGET_MS: "16000",+ REA_MCP_TOOLS_LIST_BUDGET_MS: "6000",+ REA_MCP_FIRST_CATALOG_BUDGET_MS: "21000",+ REA_MCP_DOCTOR_DEADLINE_MS: "31000",},});expect(await readFile(kimiPath, "utf8")).not.toContain(diff --git a/tests/boundary/filesystem/clientConfigurationEnvironment.test.ts b/tests/boundary/filesystem/clientConfigurationEnvironment.test.tsindex c13d2615f..2c2f58e36 100644--- a/tests/boundary/filesystem/clientConfigurationEnvironment.test.ts+++ b/tests/boundary/filesystem/clientConfigurationEnvironment.test.ts@@ -506,6 +506,26 @@ it.each([{ REA_REGEX_WORKER_HEAP_REQUEST_MIB: "6" },"REA_REGEX_WORKER_HEAP_REQUEST_MIB",],+ [+ "MCP initialize budget of zero",+ { REA_MCP_INITIALIZE_BUDGET_MS: "0" },+ "REA_MCP_INITIALIZE_BUDGET_MS",+ ],+ [+ "MCP tools/list budget above its maximum",+ { REA_MCP_TOOLS_LIST_BUDGET_MS: "2147483648" },+ "REA_MCP_TOOLS_LIST_BUDGET_MS",+ ],+ [+ "MCP first-catalog budget with a leading zero",+ { REA_MCP_FIRST_CATALOG_BUDGET_MS: "020000" },+ "REA_MCP_FIRST_CATALOG_BUDGET_MS",+ ],+ [+ "MCP doctor deadline that is not decimal",+ { REA_MCP_DOCTOR_DEADLINE_MS: "30_000" },+ "REA_MCP_DOCTOR_DEADLINE_MS",+ ],["malformed loader JSON",{ HOPPER_LOADER_ARGS_JSON: "{" },diff --git a/tests/boundary/mcp/mcpDoctor.test.ts b/tests/boundary/mcp/mcpDoctor.test.tsindex 23ac6c081..c6a4ccfd4 100644--- a/tests/boundary/mcp/mcpDoctor.test.ts+++ b/tests/boundary/mcp/mcpDoctor.test.ts@@ -377,8 +377,13 @@ describe("production MCP doctor child lifecycle", () => {const result = await vi.waitFor(() => pending, { timeout: 10_000 });vi.useRealTimers();expect(result.healthy).toBe(false);- expect(result.checks[0]?.detail).toContain("60000 ms");- expect(result.checks[0]?.detail).toContain("no runtime override");+ expect(result.checks[0]?.detail).toContain(+ "The effective REA_MCP_DOCTOR_DEADLINE_MS value for the MCP doctor startup deadline is 60000 ms (source setting; default 30000 ms, floor 1 ms, maximum 2147483647 ms).",+ );+ expect(result.checks[0]?.detail).toContain(+ "Set REA_MCP_DOCTOR_DEADLINE_MS in the environment that starts REA",+ );+ expect(result.checks[0]?.detail).not.toContain("no runtime override");expect(result.checks[0]?.detail).toContain("Codex startup_timeout_sec of 30 seconds is client guidance",);@@ -417,12 +422,17 @@ describe("production MCP doctor request-flow deadline", () => {(check) => check.name === "request-flow",);expect(requestFlow?.ok).toBe(false);- expect(requestFlow?.detail).toContain("60000 ms");- expect(requestFlow?.detail).toContain("no runtime override");+ expect(requestFlow?.detail).toContain(+ "The effective REA_MCP_DOCTOR_DEADLINE_MS value for the MCP doctor startup deadline is 60000 ms (source setting; default 30000 ms, floor 1 ms, maximum 2147483647 ms).",+ );+ expect(requestFlow?.detail).toContain(+ "Set REA_MCP_DOCTOR_DEADLINE_MS in the environment that starts REA",+ );+ expect(requestFlow?.detail).not.toContain("no runtime override");expect(requestFlow?.detail).toContain("Codex startup_timeout_sec of 30 seconds is client guidance",);- expect(requestFlow?.detail).not.toContain("30000 ms");+ expect(requestFlow?.detail).not.toContain("is 30000 ms");expect(requestFlow?.detail).not.toContain("REA_MCP_STARTUP");}, 15_000);@@ -456,6 +466,63 @@ describe("production MCP doctor request-flow deadline", () => {},10_000,);++ it("uses REA_MCP_DOCTOR_DEADLINE_MS when no caller deadline is passed", async () => {+ const root = await createTestTempDirectory("rea-mcp-doctor-setting-");+ const pidPath = join(root, "pid");+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ const pending = runProductionMcpDoctor({+ command: process.execPath,+ args: [resolve("tests/fixtures/mcpDoctorHang.mjs")],+ cwd: process.cwd(),+ environment: {+ ...process.env,+ REA_MCP_DOCTOR_PID_PATH: pidPath,+ REA_MCP_DOCTOR_DEADLINE_MS: "2000",+ },+ });+ const pid = await vi.waitFor(+ async () => {+ const value = Number.parseInt(await readFile(pidPath, "utf8"), 10);+ expect(Number.isSafeInteger(value) && value > 0).toBe(true);+ return value;+ },+ { timeout: 10_000 },+ );+ await vi.advanceTimersByTimeAsync(2_000);+ const result = await vi.waitFor(() => pending, { timeout: 10_000 });+ vi.useRealTimers();+ expect(result.healthy).toBe(false);+ expect(result.checks[0]?.detail).toContain(+ "The effective REA_MCP_DOCTOR_DEADLINE_MS value for the MCP doctor startup deadline is 2000 ms (source setting; default 30000 ms, floor 1 ms, maximum 2147483647 ms).",+ );+ expect(result.checks[0]?.detail).not.toContain("no runtime override");+ await expect(waitForExit(pid)).resolves.toBeUndefined();+ }, 10_000);++ it("refuses an invalid phase budget before starting a child", async () => {+ const result = await runProductionMcpDoctor({+ command: process.execPath,+ args: ["definitely-missing-mcp-doctor-child.mjs"],+ cwd: process.cwd(),+ environment: {+ ...process.env,+ REA_MCP_INITIALIZE_BUDGET_MS: "0",+ REA_MCP_DOCTOR_DEADLINE_MS: "0",+ },+ });+ expect(result.healthy).toBe(false);+ expect(result.server).toBeNull();+ expect(result.checks.map(({ name }) => name)).toEqual([+ "REA_MCP_INITIALIZE_BUDGET_MS",+ "REA_MCP_DOCTOR_DEADLINE_MS",+ ]);+ expect(result.checks[0]?.detail).toContain(+ "REA_MCP_INITIALIZE_BUDGET_MS must be a positive decimal integer from 1 to 2147483647 ms",+ );+ expect(result.checks[1]?.detail).toContain("REA_MCP_DOCTOR_DEADLINE_MS");+ expect(result.checks[0]?.detail).not.toContain("no runtime override");+ });});const runNoisyDoctorChild = async (body: string) => {diff --git a/tests/boundary/mcp/mcpStartupPolicy.test.ts b/tests/boundary/mcp/mcpStartupPolicy.test.tsindex 796bf3dd9..180e77a8c 100644--- a/tests/boundary/mcp/mcpStartupPolicy.test.ts+++ b/tests/boundary/mcp/mcpStartupPolicy.test.ts@@ -1,61 +1,74 @@import { describe, expect, it } from "vitest";-import { resolve } from "node:path";+import { readFile } from "node:fs/promises";+import { join, resolve } from "node:path";++import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";import {createEsmModuleProfileCollector,- fixedMcpStartupPhaseBudgetRecovery,+ mcpStartupPhaseBudgetRecovery,measureMcpStartup,parseLinuxVmRssBytes,profileMcpModuleLoading,} from "../../../scripts/lib/mcp-startup-probe.mjs";import {- fixedMcpPhaseBudgetRecovery,+ DEFAULT_MCP_STARTUP_BUDGETS,+ mcpPhaseBudgetRecovery,+ resolveMcpStartupBudgets,+ type McpPhaseBudget,+} from "../../../src/config/mcpStartupBudgets.js";+import {mcpDoctorDeadlineRecovery,MCP_STARTUP_POLICY,+ resolveMcpStartupProbePolicy,} from "../../../src/mcpStartupPolicy.js";describe("MCP startup policy", () => {- it("names fixed phase budgets without turning Codex's 30s into a REA knob", () => {- const initialize = fixedMcpPhaseBudgetRecovery(- "MCP initialize phase budget",- MCP_STARTUP_POLICY.initializeBudgetMs,- "ms",- );+ it("names phase budget settings without turning Codex's 30s into a REA knob", () => {+ const budgets = resolveMcpStartupBudgets({});+ expect(budgets).toEqual(DEFAULT_MCP_STARTUP_BUDGETS);+ expect(resolveMcpStartupProbePolicy({})).toEqual(budgets);+ expect(MCP_STARTUP_POLICY.codexStartupTimeoutSeconds).toBe(30);+ expect(MCP_STARTUP_POLICY.initializeBudgetMs).toBe(15_000);+ expect(MCP_STARTUP_POLICY.toolsListBudgetMs).toBe(5_000);+ expect(MCP_STARTUP_POLICY.firstCatalogBudgetMs).toBe(20_000);+ expect(MCP_STARTUP_POLICY.doctorDeadlineMs).toBe(30_000);+ const initialize = mcpPhaseBudgetRecovery(budgets.initialize);expect(initialize).toBe(- "REA's fixed MCP initialize phase budget is 15000 ms and this release has no runtime override.",+ "The effective REA_MCP_INITIALIZE_BUDGET_MS value for the MCP initialize phase budget is 15000 ms (source default; default 15000 ms, floor 1 ms, maximum 2147483647 ms). Set REA_MCP_INITIALIZE_BUDGET_MS in the environment that starts REA to a positive decimal integer from 1 to 2147483647, then restart REA.",);- expect(initialize).toBe(- fixedMcpStartupPhaseBudgetRecovery(- "MCP initialize phase budget",- MCP_STARTUP_POLICY.initializeBudgetMs,- "ms",- ),+ expect(initialize).toBe(mcpStartupPhaseBudgetRecovery(budgets.initialize));+ expect(initialize).not.toContain("no runtime override");+ expect(mcpStartupPhaseBudgetRecovery(budgets.toolsList)).toContain(+ "The effective REA_MCP_TOOLS_LIST_BUDGET_MS value for the MCP tools/list phase budget is 5000 ms (source default; default 5000 ms, floor 1 ms, maximum 2147483647 ms).",);- expect(- fixedMcpStartupPhaseBudgetRecovery(- "MCP tools/list phase budget",- MCP_STARTUP_POLICY.toolsListBudgetMs,- "ms",- ),- ).toContain("5000 ms");- expect(- fixedMcpStartupPhaseBudgetRecovery(- "MCP first-catalog phase budget",- MCP_STARTUP_POLICY.firstCatalogBudgetMs,- "ms",- ),- ).toContain("20000 ms");- const doctor = mcpDoctorDeadlineRecovery(- MCP_STARTUP_POLICY.doctorDeadlineMs,+ expect(mcpStartupPhaseBudgetRecovery(budgets.firstCatalog)).toContain(+ "REA_MCP_FIRST_CATALOG_BUDGET_MS",+ );+ expect(mcpStartupPhaseBudgetRecovery(budgets.firstCatalog)).toContain(+ "20000 ms (source default",+ );+ const doctor = mcpDoctorDeadlineRecovery(budgets.doctor);+ expect(doctor).toContain(+ "The effective REA_MCP_DOCTOR_DEADLINE_MS value for the MCP doctor startup deadline is 30000 ms (source default; default 30000 ms, floor 1 ms, maximum 2147483647 ms).",+ );+ expect(doctor).toContain(+ "Set REA_MCP_DOCTOR_DEADLINE_MS in the environment that starts REA",);- expect(doctor).toContain("30000 ms");- expect(doctor).toContain("no runtime override");+ expect(doctor).not.toContain("no runtime override");expect(doctor).toContain("Codex startup_timeout_sec of 30 seconds is client guidance",);expect(doctor).toContain("does not enforce");expect(doctor).not.toContain("REA_MCP_STARTUP");+ const selected = resolveMcpStartupProbePolicy({+ REA_MCP_INITIALIZE_BUDGET_MS: "16000",+ });+ expect(selected.initialize.milliseconds).toBe(16_000);+ expect(selected.initialize.source).toBe("setting");+ expect(selected.toolsList).toEqual(budgets.toolsList);+ expect(MCP_STARTUP_POLICY.codexStartupTimeoutSeconds).toBe(30);});it("parses Linux resident memory without accepting other fields", () => {@@ -87,6 +100,15 @@ describe("MCP startup policy", () => {const probeChild = resolve("tests/fixtures/mcpStartupProbeChild.mjs");+const selectedBudget = (+ budget: McpPhaseBudget,+ milliseconds: number,+): McpPhaseBudget => ({+ ...budget,+ milliseconds,+ source: "setting",+});+const probePolicy = (overrides: Partial<{initializeBudgetMs: number;@@ -94,13 +116,27 @@ const probePolicy = (firstCatalogBudgetMs: number;doctorDeadlineMs: number;}> = {},-) => ({- initializeBudgetMs: 30_000,- toolsListBudgetMs: 30_000,- firstCatalogBudgetMs: 30_000,- doctorDeadlineMs: 30_000,- ...overrides,-});+) => {+ const generous = 30_000;+ return {+ initialize: selectedBudget(+ DEFAULT_MCP_STARTUP_BUDGETS.initialize,+ overrides.initializeBudgetMs ?? generous,+ ),+ toolsList: selectedBudget(+ DEFAULT_MCP_STARTUP_BUDGETS.toolsList,+ overrides.toolsListBudgetMs ?? generous,+ ),+ firstCatalog: selectedBudget(+ DEFAULT_MCP_STARTUP_BUDGETS.firstCatalog,+ overrides.firstCatalogBudgetMs ?? generous,+ ),+ doctor: selectedBudget(+ DEFAULT_MCP_STARTUP_BUDGETS.doctor,+ overrides.doctorDeadlineMs ?? generous,+ ),+ };+};const errorMessage = (cause: unknown): string =>cause instanceof Error ? cause.message : String(cause);@@ -116,7 +152,7 @@ describe("packaged MCP startup probe failures", () => {policy: probePolicy({ initializeBudgetMs: budgetMs }),}),).rejects.toThrow(- `MCP initialize phase budget is ${String(budgetMs)} ms and this release has no runtime override.`,+ `The effective REA_MCP_INITIALIZE_BUDGET_MS value for the MCP initialize phase budget is ${String(budgetMs)} ms (source setting; default 15000 ms, floor 1 ms, maximum 2147483647 ms).`,);});@@ -133,7 +169,7 @@ describe("packaged MCP startup probe failures", () => {policy: probePolicy({ toolsListBudgetMs: budgetMs }),}),).rejects.toThrow(- `MCP tools/list phase budget is ${String(budgetMs)} ms and this release has no runtime override.`,+ `The effective REA_MCP_TOOLS_LIST_BUDGET_MS value for the MCP tools/list phase budget is ${String(budgetMs)} ms (source setting; default 5000 ms, floor 1 ms, maximum 2147483647 ms).`,);});@@ -147,7 +183,7 @@ describe("packaged MCP startup probe failures", () => {policy: probePolicy({ firstCatalogBudgetMs: budgetMs }),}),).rejects.toThrow(- `MCP first-catalog phase budget is ${String(budgetMs)} ms and this release has no runtime override.`,+ `The effective REA_MCP_FIRST_CATALOG_BUDGET_MS value for the MCP first-catalog phase budget is ${String(budgetMs)} ms (source setting; default 20000 ms, floor 1 ms, maximum 2147483647 ms).`,);});@@ -180,7 +216,7 @@ describe("packaged MCP startup probe failures", () => {packageName: "rea-agents",}),).rejects.toThrow(- `MCP doctor startup deadline is ${String(budgetMs)} ms and this release has no runtime override.`,+ `The effective REA_MCP_DOCTOR_DEADLINE_MS value for the MCP doctor startup deadline is ${String(budgetMs)} ms (source setting; default 30000 ms, floor 1 ms, maximum 2147483647 ms).`,);});@@ -198,7 +234,7 @@ describe("packaged MCP startup probe failures", () => {packageName: "rea-agents",}),).rejects.toThrow(- `MCP tools/list phase budget is ${String(budgetMs)} ms and this release has no runtime override.`,+ `The effective REA_MCP_TOOLS_LIST_BUDGET_MS value for the MCP tools/list phase budget is ${String(budgetMs)} ms (source setting; default 5000 ms, floor 1 ms, maximum 2147483647 ms).`,);});@@ -221,3 +257,83 @@ describe("packaged MCP startup probe failures", () => {}});});++describe("packaged MCP first-catalog budget while a phase is pending", () => {+ it("stops a pending initialize at the shorter first-catalog budget", async () => {+ const firstCatalogMs = 250;+ const initializeMs = 8_000;+ const started = performance.now();+ let caught: unknown;+ try {+ await measureMcpStartup({+ command: process.execPath,+ args: [probeChild],+ environment: { ...process.env, REA_MCP_PROBE_MODE: "hang" },+ policy: probePolicy({+ initializeBudgetMs: initializeMs,+ firstCatalogBudgetMs: firstCatalogMs,+ }),+ });+ } catch (cause) {+ caught = cause;+ }+ expect(caught).toBeInstanceOf(Error);+ const message = errorMessage(caught);+ expect(message).toContain(+ `The effective REA_MCP_FIRST_CATALOG_BUDGET_MS value for the MCP first-catalog phase budget is ${String(firstCatalogMs)} ms (source setting; default 20000 ms, floor 1 ms, maximum 2147483647 ms).`,+ );+ expect(message).not.toContain("REA_MCP_INITIALIZE_BUDGET_MS");+ const elapsedMs = performance.now() - started;+ expect(elapsedMs).toBeLessThan(initializeMs);+ expect(elapsedMs).toBeLessThan(firstCatalogMs + 2_000);+ });++ it("stops a pending tools/list at the remaining first-catalog budget", async () => {+ const firstCatalogMs = 800;+ const toolsListMs = 8_000;+ const root = await createTestTempDirectory("rea-mcp-startup-");+ const initializedPath = join(root, "initialized");+ const started = performance.now();+ let caught: unknown;+ try {+ await measureMcpStartup({+ command: process.execPath,+ args: [probeChild],+ environment: {+ ...process.env,+ REA_MCP_PROBE_MODE: "initialize-then-hang",+ REA_MCP_PROBE_INITIALIZED_PATH: initializedPath,+ },+ policy: probePolicy({+ toolsListBudgetMs: toolsListMs,+ firstCatalogBudgetMs: firstCatalogMs,+ }),+ });+ } catch (cause) {+ caught = cause;+ }+ expect(caught).toBeInstanceOf(Error);+ const message = errorMessage(caught);+ expect(message).toContain(+ `The effective REA_MCP_FIRST_CATALOG_BUDGET_MS value for the MCP first-catalog phase budget is ${String(firstCatalogMs)} ms (source setting; default 20000 ms, floor 1 ms, maximum 2147483647 ms).`,+ );+ expect(message).not.toContain("REA_MCP_TOOLS_LIST_BUDGET_MS");+ const elapsedMs = performance.now() - started;+ expect(elapsedMs).toBeLessThan(toolsListMs);+ expect(elapsedMs).toBeLessThan(firstCatalogMs + 2_000);+ expect(await readFile(initializedPath, "utf8")).toBe("ready");+ });++ it("returns the catalog when every phase finishes inside its budget", async () => {+ const measurement = await measureMcpStartup({+ command: process.execPath,+ args: [probeChild],+ environment: { ...process.env, REA_MCP_PROBE_MODE: "serve" },+ policy: probePolicy(),+ });+ expect(measurement.listed_tool_count).toBe(0);+ expect(measurement.process_started_to_initialized_ms).toBeGreaterThan(0);+ expect(measurement.process_started_to_tools_list_ms).toBeGreaterThan(0);+ expect(measurement.process_started_to_tools_list_ms).toBeLessThan(30_000);+ });+});diff --git a/tests/fixtures/mcpStartupProbeChild.mjs b/tests/fixtures/mcpStartupProbeChild.mjsindex e09a7d6ea..47a2330e1 100644--- a/tests/fixtures/mcpStartupProbeChild.mjs+++ b/tests/fixtures/mcpStartupProbeChild.mjs@@ -1,5 +1,6 @@-import { createInterface } from "node:readline";+import { writeFileSync } from "node:fs";import { writeFile } from "node:fs/promises";+import { createInterface } from "node:readline";const mode = process.env.REA_MCP_PROBE_MODE ?? "serve";@@ -54,6 +55,9 @@ input.on("line", (line) => {capabilities: { tools: {}, prompts: {} },serverInfo: { name: "probe-fixture", version: "1" },};+ // Synchronous so a parent can observe initialize before the next phase hangs.+ if (process.env.REA_MCP_PROBE_INITIALIZED_PATH !== undefined)+ writeFileSync(process.env.REA_MCP_PROBE_INITIALIZED_PATH, "ready");break;case "tools/list":result = { tools: [] };