Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix(mcp): distinguish string ceilings and keep dossier recovery
Name REA's reserved string limit separately from Node's ceiling, restore
detail:summary discovery for an oversized complete evidence bundle, and
apply the doctor deadline sentence when binary_session itself times out.

Co-authored-by: morluto <morluto@users.noreply.github.com>
  • Loading branch information
cursoragent and morluto committed Oct 21, 2026
commit 5808b7756dcfa5417f84409ce66df5e41048bf4c
7 changes: 4 additions & 3 deletions docs/mcp-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,10 @@ 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 Node's separate single-string ceiling, and it
does not change analysis coverage or retained content. Ordinary responses keep
their existing complete result contract.
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
19 changes: 13 additions & 6 deletions src/config/mcpResponseBudget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,26 @@ 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, not Node's separate string ceiling.
* 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,
stringCeilingCodeUnits: 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 Node's separate single-string ceiling of ${String(stringCeilingCodeUnits)} UTF-16 code units, which has no runtime override.`;
`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 the Node string ceiling. This setting is not REA_MCP_MAX_RESPONSE_BYTES. */
/**
* 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 = (
stringCeilingCodeUnits: number,
reservedStringCodeUnits: number,
nodeStringCeilingCodeUnits: number,
): string =>
`Node's single-string ceiling is ${String(stringCeilingCodeUnits)} UTF-16 code units. This release has no runtime override, and REA_MCP_MAX_RESPONSE_BYTES does not raise it.`;
`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 @@ -38,6 +38,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 @@ -70,7 +74,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
7 changes: 6 additions & 1 deletion src/mcpDoctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
deadline,
controller.signal,
catalog,
budgetMs,
);
} catch (cause: unknown) {
result = {
Expand Down Expand Up @@ -199,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 @@ -215,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
42 changes: 37 additions & 5 deletions src/server/toolResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import type { Result } from "../domain/result.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import { MCP_TRANSPORT_EVIDENCE_DISCOVERY } from "../domain/analysisErrorPresentation.js";
import {
nodeStringCeilingRecovery,
stdioResponseBudgetRecovery,
} from "../config/mcpResponseBudget.js";
import {
encodeToolResult,
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
TARGET_CONTENT_RESULT_META,
} from "./toolResultEncoding.js";

/** Project a response-budget refusal without pointing the stdio setting at Node's string ceiling. */
/** Project a response-budget refusal without labeling REA's reserved string limit as Node's ceiling. */
export const mcpResponseOverflowProjection = (input: {
readonly completed: boolean;
readonly constraint: "receive-buffer" | "string-length";
Expand All @@ -33,16 +35,20 @@ export const mcpResponseOverflowProjection = (input: {
}): { readonly reason: string; readonly remediationAction: string } => {
const facts =
input.constraint === "string-length"
? nodeStringCeilingRecovery(MCP_RESULT_STRING_LIMIT)
? nodeStringCeilingRecovery(
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
)
: stdioResponseBudgetRecovery(
input.effectiveResponseBytes,
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
const summary =
input.constraint === "string-length"
? input.completed
? "The operation completed, but its complete MCP response exceeds Node's single-string representation limit."
: "The tool failed, but its complete error response exceeds Node's single-string representation limit."
? "The operation completed, but its complete MCP response exceeds REA's reserved single-string limit."
: "The tool failed, but its complete error response exceeds REA's reserved single-string limit."
: input.completed
? "The operation completed, but its complete MCP response exceeds the stdio response budget. The analysis result was not truncated."
: "The tool failed, but its complete error response exceeds the MCP response budget.";
Expand Down Expand Up @@ -82,6 +88,30 @@ const retainedEvidenceContinuation = (
};
};

/**
* A complete `get_evidence_bundle` still has a summary discovery path.
* An oversized summary has already used that path.
*/
const completeEvidenceBundleOverflow = (
contractName: string,
value: JsonValue,
): boolean => {
if (contractName !== "get_evidence_bundle") return false;
const payload =
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
"result" in value
? value.result
: value;
return !(
typeof payload === "object" &&
payload !== null &&
!Array.isArray(payload) &&
payload.kind === "evidence-bundle-summary"
);
};

/** Immutable encoding and recovery policy shared by one MCP server. */
export class ToolResultDelivery {
readonly maximumResponseBytes: number;
Expand Down Expand Up @@ -215,7 +245,9 @@ export class ToolResultDelivery {
? "Call inspect_analysis_view with the supplied continuation arguments to read retained analysis. Follow coverage.next_offset for subsequent pages; reduce the page limit if needed, or export the complete retained Evidence."
: retainedEvidence
? "Export retained evidence to consume the complete analysis, or use complete CLI JSON output."
: "Use complete CLI JSON output to consume the analysis.";
: completeEvidenceBundleOverflow(contract.name, value)
? MCP_TRANSPORT_EVIDENCE_DISCOVERY
: "Use complete CLI JSON output to consume the analysis.";
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
const projected = mcpResponseOverflowProjection({
completed: true,
constraint: encoded.constraint,
Expand Down
6 changes: 5 additions & 1 deletion src/server/toolResultEncoding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { constants as bufferConstants } from "node:buffer";
import type { JsonValue } from "../domain/jsonValue.js";
import { bufferedJsonParts, jsonParts } from "../domain/jsonSerialization.js";

export const MCP_RESULT_STRING_LIMIT = bufferConstants.MAX_STRING_LENGTH - 1024;
/** Node's actual single-string ceiling. REA refuses earlier, at MCP_RESULT_STRING_LIMIT. */
export const NODE_MAX_STRING_LENGTH = bufferConstants.MAX_STRING_LENGTH;

/** REA's reserved serialization limit, 1024 code units under Node's ceiling. */
export const MCP_RESULT_STRING_LIMIT = NODE_MAX_STRING_LENGTH - 1024;

const RESULT_ENVELOPE_BYTES =
Buffer.byteLength(
Expand Down
3 changes: 3 additions & 0 deletions tests/boundary/mcp/analysisViewMcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,9 @@ it("discovers an oversized native dossier by exact metadata and reads its retain
expect(broadError.remediation?.action).toContain(
"get_evidence_bundle and detail: summary",
);
expect(broadError.remediation?.action).toContain(
"REA_MCP_MAX_RESPONSE_BYTES",
);
const response = await client.callTool({
name: "get_evidence_bundle",
arguments: {
Expand Down
74 changes: 69 additions & 5 deletions tests/boundary/mcp/largeToolResult.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ import {
ToolResultDelivery,
} from "../../../src/server/toolResult.js";
import { MINIMUM_RESPONSE_BYTES } from "../../../src/config/mcpResponseBudget.js";
import { MCP_RESULT_STRING_LIMIT } from "../../../src/server/toolResultEncoding.js";
import {
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
} from "../../../src/server/toolResultEncoding.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { encodeToolResult } from "../../../src/server/toolResultEncoding.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
Expand Down Expand Up @@ -116,7 +119,19 @@ describe("MCP response budget recovery", () => {
expect(projected.reason).toContain("restarting the REA process");
expect(projected.reason).toContain("does not raise");
expect(projected.reason).toContain("no runtime override");
expect(projected.reason).toContain(String(MCP_RESULT_STRING_LIMIT));
expect(NODE_MAX_STRING_LENGTH - MCP_RESULT_STRING_LIMIT).toBe(1024);
expect(projected.reason).toContain(
`REA's reserved single-string limit of ${String(MCP_RESULT_STRING_LIMIT)} UTF-16 code units`,
);
expect(projected.reason).toContain(
`Node's single-string ceiling of ${String(NODE_MAX_STRING_LENGTH)} UTF-16 code units`,
);
expect(projected.reason).not.toContain(
`Node's single-string ceiling of ${String(MCP_RESULT_STRING_LIMIT)}`,
);
expect(projected.reason).not.toContain(
`Node's single-string ceiling is ${String(MCP_RESULT_STRING_LIMIT)}`,
);
expect(projected.remediationAction).toContain("REA_MCP_MAX_RESPONSE_BYTES");
expect(projected.remediationAction).not.toContain(
"set REA_MCP_MAX_RESPONSE_BYTES above Node",
Expand All @@ -130,16 +145,65 @@ describe("MCP response budget recovery", () => {
effectiveResponseBytes: MINIMUM_RESPONSE_BYTES * 2,
nextStep: "Use complete CLI JSON output when the analysis completed.",
});
expect(projected.reason).toContain("single-string representation limit");
expect(projected.reason).toContain("REA's reserved single-string limit");
expect(projected.reason).toContain(
`REA's reserved single-string limit is ${String(MCP_RESULT_STRING_LIMIT)} UTF-16 code units`,
);
expect(projected.reason).toContain(
`below Node's single-string ceiling of ${String(NODE_MAX_STRING_LENGTH)} UTF-16 code units`,
);
expect(projected.reason).not.toContain(
`Node's single-string ceiling is ${String(MCP_RESULT_STRING_LIMIT)}`,
);
expect(projected.reason).not.toContain(
`Node's single-string ceiling of ${String(MCP_RESULT_STRING_LIMIT)}`,
);
expect(projected.reason).toContain(
"REA_MCP_MAX_RESPONSE_BYTES does not raise it",
"REA_MCP_MAX_RESPONSE_BYTES does not raise them",
);
expect(projected.reason).toContain("no runtime override");
expect(projected.reason).not.toContain("floor 10485760");
expect(projected.remediationAction).toContain(
"REA_MCP_MAX_RESPONSE_BYTES does not raise it",
"REA_MCP_MAX_RESPONSE_BYTES does not raise them",
);
});

it("keeps summary discovery when a complete evidence bundle exceeds the budget", () => {
const tight = new ToolResultDelivery(2048);
const delivered = tight.toCallToolResult(
ok({ records: "x".repeat(1500) }),
toolContract("get_evidence_bundle"),
);
expect(delivered.isError).toBe(true);
const action = z
.object({
error: z.object({ remediation: z.object({ action: z.string() }) }),
})
.parse(delivered.structuredContent).error.remediation.action;
expect(action).toContain("get_evidence_bundle and detail: summary");
expect(action).toContain("REA_MCP_MAX_RESPONSE_BYTES");
expect(action).toContain(
`Node's single-string ceiling of ${String(NODE_MAX_STRING_LENGTH)}`,
);
});

it("does not repeat summary discovery when the summary itself exceeds the budget", () => {
const tight = new ToolResultDelivery(2048);
const delivered = tight.toCallToolResult(
ok({
kind: "evidence-bundle-summary",
records: "x".repeat(1500),
}),
toolContract("get_evidence_bundle"),
);
const action = z
.object({
error: z.object({ remediation: z.object({ action: z.string() }) }),
})
.parse(delivered.structuredContent).error.remediation.action;
expect(action).not.toContain("get_evidence_bundle and detail: summary");
expect(action).toContain("Use complete CLI JSON output");
});
});

describe("large complete Evidence MCP delivery", () => {
Expand Down
61 changes: 61 additions & 0 deletions tests/boundary/mcp/mcpDoctor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,67 @@ describe("production MCP doctor child lifecycle", () => {
}, 10_000);
});

describe("production MCP doctor request-flow deadline", () => {
it("names the applied deadline when binary_session exceeds it after the catalog", async () => {
const root = await createTestTempDirectory("rea-mcp-doctor-session-");
const readyPath = join(root, "ready");
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
const pending = runProductionMcpDoctor({
command: process.execPath,
args: [resolve("tests/fixtures/mcpStartupProbeChild.mjs")],
cwd: process.cwd(),
environment: {
...process.env,
REA_MCP_PROBE_MODE: "hang-on-call",
REA_MCP_PROBE_READY_PATH: readyPath,
},
deadlineMs: 60_000,
});
await vi.waitFor(
async () => {
await readFile(readyPath, "utf8");
},
{ timeout: 10_000 },
);
await vi.advanceTimersByTimeAsync(60_000);
const result = await vi.waitFor(() => pending, { timeout: 10_000 });
vi.useRealTimers();
expect(result.server).not.toBeNull();
const requestFlow = result.checks.find(
(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(
"Codex startup_timeout_sec of 30 seconds is client guidance",
);
expect(requestFlow?.detail).not.toContain("30000 ms");
expect(requestFlow?.detail).not.toContain("REA_MCP_STARTUP");
}, 15_000);

it("does not add deadline guidance to an unrelated binary_session failure", async () => {
const result = await runProductionMcpDoctor({
command: process.execPath,
args: [resolve("tests/fixtures/mcpStartupProbeChild.mjs")],
cwd: process.cwd(),
environment: {
...process.env,
REA_MCP_PROBE_MODE: "refuse-call",
},
deadlineMs: 5_000,
});
expect(result.server).not.toBeNull();
const requestFlow = result.checks.find(
(check) => check.name === "request-flow",
);
expect(requestFlow?.ok).toBe(false);
expect(requestFlow?.detail).toContain("unrelated fixture method refusal");
expect(requestFlow?.detail).not.toContain("no runtime override");
expect(requestFlow?.detail).not.toContain("MCP doctor startup deadline");
}, 10_000);
});

const runNoisyDoctorChild = async (body: string) => {
const root = await createTestTempDirectory("rea-mcp-doctor-stderr-");
const scriptPath = join(root, "noisy.mjs");
Expand Down
Loading
Loading