* fix(mcp): name response-byte and startup ceilings in recovery Name REA_MCP_MAX_RESPONSE_BYTES, its effective value, the 10485760 byte floor, and process restart when the stdio response budget is hit, and state that the setting does not raise Node's string ceiling. Name fixed MCP startup phase budgets when those deadlines fire, and keep Codex's 30 second startup figure as client guidance. Co-authored-by: morluto <[email protected]> * 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 <[email protected]> * fix(mcp): keep retained SDK errors inside the text budget Quoted SDK validation diagnostics expand when recovery JSON is escaped into MCP text. Shorten only that preview so the retained-evidence reference still arrives as parseable error content. Co-authored-by: morluto <[email protected]> * fix(mcp): keep export advice when a summary exceeds the response budget An oversized get_evidence_bundle summary no longer repeats detail: summary. export_evidence_bundle still writes the retained bundle outside one MCP frame, including when a larger byte budget cannot raise the string ceiling. Co-authored-by: morluto <[email protected]> * style(mcp): format the SDK diagnostic preview return oxfmt rejected the fitted-preview ternary in EvidenceMcpServer.ts, which failed Static checks and the CI required gate. Co-authored-by: morluto <[email protected]> --------- Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: morluto <[email protected]>
279 lines
9.9 KiB
TypeScript
279 lines
9.9 KiB
TypeScript
import { isNativeInventoryOperation } from "../domain/native/nativeInventory.js";
|
|
import { INSPECT_ANALYSIS_VIEW_OPERATION } from "../domain/analysisView/analysisViewErrors.js";
|
|
import type { CallToolResult } from "@modelcontextprotocol/server";
|
|
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
|
|
|
|
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
|
import type { Evidence } from "../domain/evidence.js";
|
|
import { inspectAnalysisViewInputSchema } from "../domain/analysisView/analysisView.js";
|
|
import {
|
|
projectAnalysisError,
|
|
type AnalysisErrorProjection,
|
|
} from "../domain/analysisErrorProjection.js";
|
|
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,
|
|
MCP_TRANSPORT_EVIDENCE_EXPORT,
|
|
} 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 labeling REA's reserved string limit as Node's ceiling. */
|
|
export const mcpResponseOverflowProjection = (input: {
|
|
readonly completed: boolean;
|
|
readonly constraint: "receive-buffer" | "string-length";
|
|
readonly effectiveResponseBytes: number;
|
|
readonly nextStep: string;
|
|
}): { readonly reason: string; readonly remediationAction: string } => {
|
|
const facts =
|
|
input.constraint === "string-length"
|
|
? nodeStringCeilingRecovery(
|
|
MCP_RESULT_STRING_LIMIT,
|
|
NODE_MAX_STRING_LENGTH,
|
|
)
|
|
: stdioResponseBudgetRecovery(
|
|
input.effectiveResponseBytes,
|
|
MCP_RESULT_STRING_LIMIT,
|
|
NODE_MAX_STRING_LENGTH,
|
|
);
|
|
const summary =
|
|
input.constraint === "string-length"
|
|
? input.completed
|
|
? "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.";
|
|
return {
|
|
reason: `${summary} ${facts} ${input.nextStep}`,
|
|
remediationAction: `${input.nextStep} ${facts}`,
|
|
};
|
|
};
|
|
|
|
/** Create one delivery policy from the already selected, parsed response budget. */
|
|
export const createToolResultDelivery = (
|
|
maximumResponseBytes: number | undefined,
|
|
): ToolResultDelivery =>
|
|
new ToolResultDelivery(maximumResponseBytes ?? STDIO_DEFAULT_MAX_BUFFER_SIZE);
|
|
|
|
/** Offer a named, schema-validated source page only for retained native analysis. */
|
|
const retainedEvidenceContinuation = (
|
|
evidence: Evidence,
|
|
): Readonly<Record<string, JsonValue>> => {
|
|
const view =
|
|
evidence.operation === "analyze_function"
|
|
? { kind: "native", facet: "pseudocode", offset: 0 }
|
|
: isNativeInventoryOperation(evidence.operation)
|
|
? { kind: "native-inventory", offset: 0, limit: 64 }
|
|
: undefined;
|
|
if (view === undefined) return {};
|
|
const input = inspectAnalysisViewInputSchema.safeParse({
|
|
source: { kind: "retained-evidence", evidence_id: evidence.evidence_id },
|
|
view,
|
|
});
|
|
if (!input.success) return {};
|
|
return {
|
|
continuation: {
|
|
name: INSPECT_ANALYSIS_VIEW_OPERATION,
|
|
arguments: jsonValueSchema.parse(input.data),
|
|
},
|
|
};
|
|
};
|
|
|
|
/**
|
|
* A summary projection has already used `detail: "summary"`.
|
|
* Export still writes the retained bundle outside one MCP frame.
|
|
*/
|
|
const evidenceBundleSummary = (value: JsonValue): boolean => {
|
|
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;
|
|
readonly resultBudgetBytes: number;
|
|
constructor(maximumResponseBytes: number) {
|
|
this.maximumResponseBytes = maximumResponseBytes;
|
|
this.resultBudgetBytes = maximumResponseBytes - 1024;
|
|
Object.freeze(this);
|
|
}
|
|
|
|
/** Serialize a plain application result or its actionable error. */
|
|
toCallToolResult(
|
|
result: Result<JsonValue, AnalysisError>,
|
|
contract: ToolContract,
|
|
): CallToolResult {
|
|
return result.ok
|
|
? this.successResult(
|
|
contract.kind === "session" ? { result: result.value } : result.value,
|
|
contract,
|
|
)
|
|
: this.toErrorToolResult(result.error, contract.returnsTargetContent);
|
|
}
|
|
|
|
/** Deliver Evidence using the producer's explicit recording acknowledgment. */
|
|
toEvidenceToolResult(
|
|
evidence: Evidence,
|
|
contract: ToolContract,
|
|
recorded: Result<unknown, AnalysisError> | undefined,
|
|
): CallToolResult {
|
|
return recorded !== undefined && !recorded.ok
|
|
? this.toErrorToolResult(recorded.error, contract.returnsTargetContent)
|
|
: this.successResult(evidence, contract, {
|
|
evidence_id: evidence.evidence_id,
|
|
...(recorded === undefined
|
|
? {}
|
|
: {
|
|
evidence_reference: {
|
|
kind: "retained-evidence",
|
|
evidence_id: evidence.evidence_id,
|
|
},
|
|
...retainedEvidenceContinuation(evidence),
|
|
}),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Project an error without allocating oversized repeated MCP text.
|
|
* `targetContent` is the failing tool's `returnsTargetContent`: a failure
|
|
* can carry target-derived text (a message, captured output, or a partial
|
|
* observation), so it is marked exactly like that tool's successful results.
|
|
*/
|
|
toErrorToolResult(
|
|
error: AnalysisError,
|
|
targetContent: boolean,
|
|
): CallToolResult {
|
|
return this.projectedErrorResult(
|
|
projectAnalysisError(error),
|
|
targetContent,
|
|
);
|
|
}
|
|
|
|
/** Deliver the original failure with the producer-acknowledged partial Evidence reference. */
|
|
toRecordedPartialErrorToolResult(
|
|
error: AnalysisError,
|
|
evidenceId: string,
|
|
recorded: Result<unknown, AnalysisError>,
|
|
targetContent: boolean,
|
|
): CallToolResult {
|
|
if (!recorded.ok) return this.toErrorToolResult(error, targetContent);
|
|
const projected = projectAnalysisError(error);
|
|
return this.projectedErrorResult(
|
|
{
|
|
...projected,
|
|
details: {
|
|
...projected.details,
|
|
partial_observation: {
|
|
kind: "retained-evidence",
|
|
evidence_id: evidenceId,
|
|
},
|
|
},
|
|
},
|
|
targetContent,
|
|
);
|
|
}
|
|
|
|
private projectedErrorResult(
|
|
projected: AnalysisErrorProjection,
|
|
targetContent: boolean,
|
|
): CallToolResult {
|
|
const structuredContent = { error: projected };
|
|
// Errors reach the wire as text only; the structured copy is a private
|
|
// carrier the transport removes after its own budget check.
|
|
const encoded = encodeToolResult(
|
|
structuredContent,
|
|
this.resultBudgetBytes,
|
|
"error-text",
|
|
targetContent,
|
|
);
|
|
// The transport retains an oversized projected error before replacing it
|
|
// with a recoverable delivery constraint, using this same budget.
|
|
return {
|
|
content: encoded.ok ? [{ type: "text", text: encoded.text }] : [],
|
|
structuredContent,
|
|
isError: true,
|
|
...(targetContent ? { _meta: TARGET_CONTENT_RESULT_META } : {}),
|
|
};
|
|
}
|
|
|
|
private successResult(
|
|
value: JsonValue,
|
|
contract: ToolContract,
|
|
recovery: Readonly<Record<string, JsonValue>> = {},
|
|
): CallToolResult {
|
|
const encoded = encodeToolResult(
|
|
value,
|
|
this.resultBudgetBytes,
|
|
"structured-and-text",
|
|
contract.returnsTargetContent,
|
|
);
|
|
if (encoded.ok)
|
|
return {
|
|
content: [{ type: "text", text: encoded.text }],
|
|
structuredContent: value,
|
|
...(contract.returnsTargetContent
|
|
? { _meta: TARGET_CONTENT_RESULT_META }
|
|
: {}),
|
|
};
|
|
const retainedEvidence = recovery.evidence_reference !== undefined;
|
|
const nextStep =
|
|
recovery.continuation !== undefined
|
|
? "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."
|
|
: contract.name === "get_evidence_bundle"
|
|
? evidenceBundleSummary(value)
|
|
? MCP_TRANSPORT_EVIDENCE_EXPORT
|
|
: MCP_TRANSPORT_EVIDENCE_DISCOVERY
|
|
: "Use complete CLI JSON output to consume the analysis.";
|
|
const projected = mcpResponseOverflowProjection({
|
|
completed: true,
|
|
constraint: encoded.constraint,
|
|
effectiveResponseBytes: this.maximumResponseBytes,
|
|
nextStep,
|
|
});
|
|
return this.toErrorToolResult(
|
|
new AnalysisResourceConstraintError(
|
|
contract.name,
|
|
"transport",
|
|
projected.reason,
|
|
{
|
|
boundary: "mcp-response",
|
|
default_receive_buffer_bytes: STDIO_DEFAULT_MAX_BUFFER_SIZE,
|
|
result_budget_bytes: this.resultBudgetBytes,
|
|
max_string_code_units: MCP_RESULT_STRING_LIMIT,
|
|
response_bytes_at_least: encoded.bytesAtLeast,
|
|
response_code_units_at_least: encoded.codeUnitsAtLeast,
|
|
constraint: encoded.constraint,
|
|
...recovery,
|
|
},
|
|
{ remediationAction: projected.remediationAction },
|
|
),
|
|
contract.returnsTargetContent,
|
|
);
|
|
}
|
|
}
|