Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions docs/mcp-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,11 +234,14 @@ The destination changes only when a complete export is atomically published.

Clients that explicitly configure a larger receive buffer can set the REA
server's `REA_MCP_MAX_RESPONSE_BYTES` environment variable to the same byte
count. This setting must be a safe decimal integer at least 10485760; REA
reserves 1024 bytes for the envelope. Raising it restores complete inline
delivery for responses that fit that buffer and Node's single-string limit.
It does not change the client's buffer, analysis coverage, or retained content.
Ordinary responses keep their existing complete result contract.
count. This setting must be a safe decimal integer at least 10485760 (10 MiB);
REA reserves 1024 bytes for the envelope. The value is read when the REA
process starts, so a change requires a restart and a matching client receive
buffer. Raising it restores complete inline delivery for responses that fit
that buffer. It does not raise REA's reserved single-string limit, which is
1024 UTF-16 code units below Node's single-string ceiling, and it does not
raise that Node ceiling. It does not change analysis coverage or retained
content. Ordinary responses keep their existing complete result contract.

### Error recovery and deadline ownership

Expand Down
7 changes: 7 additions & 0 deletions scripts/lib/mcp-startup-probe.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ 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;

/** Collect unique file-backed ESM module URLs from Node diagnostics. */
export function createEsmModuleProfileCollector(packageName?: string): {
append(chunk: string): void;
Expand Down
85 changes: 71 additions & 14 deletions scripts/lib/mcp-startup-probe.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,22 @@ export async function measureMcpStartup({
const startedAt = performance.now();
rss.start();
try {
await client.connect(transport, { timeout: policy.initializeBudgetMs });
await withFixedPhaseBudget(
"MCP initialize phase budget",
policy.initializeBudgetMs,
"ms",
() => client.connect(transport, { timeout: policy.initializeBudgetMs }),
);
const initializedAt = performance.now();
const tools = await client.listTools(undefined, {
timeout: policy.toolsListBudgetMs,
});
const tools = await withFixedPhaseBudget(
"MCP tools/list phase budget",
policy.toolsListBudgetMs,
"ms",
() =>
client.listTools(undefined, {
timeout: policy.toolsListBudgetMs,
}),
);
const listedAt = performance.now();
rss.stop();
const measurement = {
Expand All @@ -52,7 +63,11 @@ export async function measureMcpStartup({
assertStartupBudgets(measurement, policy);
return measurement;
} catch (cause) {
throw new Error(`packaged MCP startup probe failed: ${stderr}`, { cause });
const detail = cause instanceof Error ? cause.message : String(cause);
throw new Error(
`packaged MCP startup probe failed: ${detail}${stderr.length === 0 ? "" : `\n${stderr}`}`,
{ cause },
);
} finally {
rss.stop();
await Promise.allSettled([client.close(), transport.close()]);
Expand Down Expand Up @@ -82,12 +97,24 @@ export async function profileMcpModuleLoading({
version: "1.0.0",
});
try {
await client.connect(transport, {
timeout: policy.doctorDeadlineMs,
});
await client.listTools(undefined, {
timeout: policy.toolsListBudgetMs,
});
await withFixedPhaseBudget(
"MCP doctor startup deadline",
policy.doctorDeadlineMs,
"ms",
() =>
client.connect(transport, {
timeout: policy.doctorDeadlineMs,
}),
);
await withFixedPhaseBudget(
"MCP tools/list phase budget",
policy.toolsListBudgetMs,
"ms",
() =>
client.listTools(undefined, {
timeout: policy.toolsListBudgetMs,
}),
);
return profile.result();
} finally {
await Promise.allSettled([client.close(), transport.close()]);
Expand Down Expand Up @@ -197,16 +224,46 @@ 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.`;

const phaseTimeout = (cause) => {
const message = cause instanceof Error ? cause.message : String(cause);
return (
message.includes("Request timed out") ||
message.includes("Maximum total timeout exceeded") ||
message.includes("timed out")
);
};

const withFixedPhaseBudget = async (phase, value, unit, 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 },
);
}
};

const assertStartupBudgets = (measurement, policy) => {
if (measurement.process_started_to_initialized_ms > policy.initializeBudgetMs)
throw new Error("packaged MCP exceeded the initialize regression budget");
throw new Error(
`packaged MCP exceeded the initialize phase budget. ${fixedMcpStartupPhaseBudgetRecovery("MCP initialize phase budget", policy.initializeBudgetMs, "ms")}`,
);
if (measurement.initialized_to_tools_list_ms > policy.toolsListBudgetMs)
throw new Error("packaged MCP exceeded the tools/list regression budget");
throw new Error(
`packaged MCP exceeded the tools/list phase budget. ${fixedMcpStartupPhaseBudgetRecovery("MCP tools/list phase budget", policy.toolsListBudgetMs, "ms")}`,
);
if (
measurement.process_started_to_tools_list_ms > policy.firstCatalogBudgetMs
)
throw new Error(
"packaged MCP exceeded the first-catalog regression budget",
`packaged MCP exceeded the first-catalog phase budget. ${fixedMcpStartupPhaseBudgetRecovery("MCP first-catalog phase budget", policy.firstCatalogBudgetMs, "ms")}`,
);
};

Expand Down
26 changes: 25 additions & 1 deletion src/config/mcpResponseBudget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,31 @@ import { err, ok, type Result } from "../domain/result.js";
// This override supports clients with larger frames. Keep the configuration
// parser independent of the SDK's eager server imports; conformance verifies
// this floor against the pinned SDK's actual default receive-buffer size.
const MINIMUM_RESPONSE_BYTES = 10 * 1024 * 1024;
export const MINIMUM_RESPONSE_BYTES = 10 * 1024 * 1024;

/**
* Facts for a completed or failed MCP result that exceeded the stdio receive
* budget. The effective value is the configured receive buffer, including the
* envelope reservation. REA's reserved string limit is separate from, and
* lower than, Node's single-string ceiling. This setting raises neither.
*/
export const stdioResponseBudgetRecovery = (
effectiveResponseBytes: number,
reservedStringCodeUnits: number,
nodeStringCeilingCodeUnits: number,
): string =>
`The effective REA_MCP_MAX_RESPONSE_BYTES value is ${String(effectiveResponseBytes)} bytes (floor ${String(MINIMUM_RESPONSE_BYTES)} bytes, 10 MiB). A change requires restarting the REA process and a matching client receive buffer. It does not raise REA's reserved single-string limit of ${String(reservedStringCodeUnits)} UTF-16 code units or Node's single-string ceiling of ${String(nodeStringCeilingCodeUnits)} UTF-16 code units. This release has no runtime override for either limit.`;

/**
* Facts for a result that exceeded REA's reserved string limit.
* `reservedStringCodeUnits` is that REA limit. `nodeStringCeilingCodeUnits`
* is Node's own ceiling and is not the same number.
*/
export const nodeStringCeilingRecovery = (
reservedStringCodeUnits: number,
nodeStringCeilingCodeUnits: number,
): string =>
`REA's reserved single-string limit is ${String(reservedStringCodeUnits)} UTF-16 code units, below Node's single-string ceiling of ${String(nodeStringCeilingCodeUnits)} UTF-16 code units. This release has no runtime override for either limit, and REA_MCP_MAX_RESPONSE_BYTES does not raise them.`;

/** Optional stdio response budget, including room for the protocol envelope. */
export const mcpResponseBudgetSchema = z
Expand Down
6 changes: 5 additions & 1 deletion src/domain/analysisErrorPresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ import {
} from "./analysisErrorBase.js";
import type { AnalysisErrorProjection } from "./analysisErrorProjection.js";

/** Next step when one MCP frame cannot carry a complete retained session bundle. */
export const MCP_TRANSPORT_EVIDENCE_DISCOVERY =
"Discover retained records with get_evidence_bundle and detail: summary, then inspect compatible records through inspect_analysis_view using an exact Evidence reference. Export complete retained session evidence through export_evidence_bundle to a caller-selected path, or use complete CLI JSON output. The connection remains usable.";

export const analysisErrorRemediationAction = (
error: AnalysisError,
): string => {
Expand Down Expand Up @@ -76,7 +80,7 @@ export const analysisErrorRemediationAction = (
: error.resource === "capacity"
? "Wait for an active analysis to complete, then retry within the reported admission limits."
: error.resource === "transport"
? "Discover retained records with get_evidence_bundle and detail: summary, then inspect compatible records through inspect_analysis_view using an exact Evidence reference. Export complete retained session evidence through export_evidence_bundle to a caller-selected path, or use complete CLI JSON output. The connection remains usable."
? MCP_TRANSPORT_EVIDENCE_DISCOVERY
: error.resource === "cpu"
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
: error.resource === "file-size"
Expand Down
2 changes: 1 addition & 1 deletion src/domain/jsonValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export function* jsonValueValidationSteps(
if (item === undefined) break;
if (item.depth > MAX_JSON_DEPTH)
return finish(
`JSON value exceeds maximum nesting depth of ${MAX_JSON_DEPTH}`,
`JSON value exceeds maximum nesting depth of ${MAX_JSON_DEPTH}. This release has no runtime override.`,
);
const value = item.value;
if (typeof value === "object" && value !== null && types.isProxy(value))
Expand Down
38 changes: 32 additions & 6 deletions src/mcpDoctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +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 { MCP_STARTUP_POLICY } from "./mcpStartupPolicy.js";
import {
MCP_STARTUP_POLICY,
mcpDoctorDeadlineRecovery,
} from "./mcpStartupPolicy.js";

const OUTPUT_FORMATS = ["toon", "json", "yaml", "md", "jsonl"] as const;
type OutputFormat = (typeof OUTPUT_FORMATS)[number];
Expand Down Expand Up @@ -81,9 +84,8 @@ interface McpDoctorCheck {
/** Diagnose the actual production stdio adapter with one startup-bounded SDK session. */
export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
const catalog = catalogIdentityForEnvironment(options.environment);
const deadline =
performance.now() +
(options.deadlineMs ?? MCP_STARTUP_POLICY.doctorDeadlineMs);
const budgetMs = options.deadlineMs ?? MCP_STARTUP_POLICY.doctorDeadlineMs;
const deadline = performance.now() + budgetMs;
const controller = new AbortController();
const timer = setTimeout(
() => controller.abort(new Error("Production MCP doctor deadline expired")),
Expand Down Expand Up @@ -111,6 +113,7 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
deadline,
controller.signal,
catalog,
budgetMs,
);
} catch (cause: unknown) {
result = {
Expand All @@ -124,7 +127,7 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
{
name: "transport",
ok: false,
detail: errorMessage(cause),
detail: doctorTransportDetail(cause, budgetMs),
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
},
],
};
Expand Down Expand Up @@ -197,6 +200,7 @@ const inspectProductionMcpSession = async (
deadline: number,
signal: AbortSignal,
catalog: ReturnType<typeof createCatalogIdentity>,
budgetMs: number,
) => {
const request = requestOptions(deadline, signal);
const [tools, prompts] = await Promise.all([
Expand All @@ -213,7 +217,10 @@ const inspectProductionMcpSession = async (
},
)
.then(ok, (cause: unknown) =>
err({ kind: "request-flow" as const, detail: errorMessage(cause) }),
err({
kind: "request-flow" as const,
detail: doctorTransportDetail(cause, budgetMs),
}),
);
const inventory = {
tools: compareInventory(
Expand Down Expand Up @@ -541,3 +548,22 @@ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>

const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);

const doctorDeadlineFired = (cause: unknown): boolean => {
const message = errorMessage(cause);
return (
message.includes("Production MCP doctor deadline expired") ||
message.includes("Request timed out") ||
message.includes("Maximum total timeout exceeded") ||
(cause instanceof Error &&
(cause.name === "TimeoutError" || cause.name === "AbortError"))
);
};

/** Name the fixed doctor deadline when it fires, without turning Codex's 30s into a REA knob. */
const doctorTransportDetail = (cause: unknown, budgetMs: number): string => {
const message = errorMessage(cause);
return doctorDeadlineFired(cause)
? `${message} ${mcpDoctorDeadlineRecovery(budgetMs)}`
: message;
};
16 changes: 16 additions & 0 deletions src/mcpStartupPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,22 @@ export const MCP_STARTUP_POLICY = {
doctorStderrBytes: 64 * 1024,
} as const;

/**
* 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.
*/
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.`;

/** 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.`;

/** Parsed startup and upstream request budgets affecting a client's tool deadline. */
export interface McpToolTimeoutInputs {
readonly analysisProvider: AnalysisProviderSelector;
Expand Down
23 changes: 16 additions & 7 deletions src/server/EvidenceMcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ import {
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import type { ToolResultDelivery } from "./toolResult.js";
import {
mcpResponseOverflowProjection,
type ToolResultDelivery,
} from "./toolResult.js";
import { toolReturnsTargetContent } from "../contracts/toolEffects.js";
import {
carriesTargetContentMarker,
Expand Down Expand Up @@ -480,10 +483,20 @@ class ErrorEvidenceTransport implements Transport {
);
const recorded = this.recordEvidence?.(evidence);
const retained = recorded !== undefined && recorded.ok;
const projected = mcpResponseOverflowProjection({
completed: false,
constraint: encoded.constraint,
effectiveResponseBytes: this.delivery.maximumResponseBytes,
nextStep: retained
? "Export the retained original error through export_evidence_bundle to a caller-selected path. The connection remains usable."
: encoded.constraint === "string-length"
? "The original error could not be retained by this server. Use complete CLI JSON output when the analysis completed. Repeating the unchanged MCP call fails the same way."
: "The original error could not be retained by this server. Restart REA with a larger REA_MCP_MAX_RESPONSE_BYTES and a matching client receive buffer, then retry.",
});
const failure = new AnalysisResourceConstraintError(
operation,
"transport",
"The tool failed, but its complete error response exceeds the MCP response budget.",
projected.reason,
{
boundary: "mcp-response",
...(originalError?.success
Expand All @@ -510,11 +523,7 @@ class ErrorEvidenceTransport implements Transport {
? { retention_error: projectAnalysisError(recorded.error) }
: {}),
},
{
remediationAction: retained
? "Export the retained original error through export_evidence_bundle to a caller-selected path. The connection remains usable."
: "Restart REA with a larger REA_MCP_MAX_RESPONSE_BYTES and matching client receive buffer, then retry. The original error could not be retained by this server.",
},
{ remediationAction: projected.remediationAction },
);
const replacement = this.delivery.toErrorToolResult(failure, targetContent);
return {
Expand Down
Loading
Loading