Files
reverse-engineering-anything/src/server/EvidenceMcpServerCore.ts
T
morluto 0e07a3c876 fix(delivery)!: deliver over-budget results and errors inside the agent result budget (#15396)
* fix(mcp)!: deliver over-budget delivery facts inside the structured result

Codex and VS Code forward only structuredContent to the model, and Gemini
CLI and LangChain forward only the text blocks; _meta reaches no model. An
over-budget result put its delivery facts in a second text block and in
_meta, so Codex and VS Code agents received a summary with no sign that it
was one.

An over-budget result is now {summary, delivery} in structuredContent,
the shape the CLI already prints, and its one text block is that value's
serialization. The delivery layer owns the alternative: every budgeted
operation's registered output schema admits it, so canonical and compact
advertisements validate the result.

An overflowing completed result no longer picks its recovery by tool
name. The producer declares an overflow recovery (stateless, retained or
committed, with its next call and identities): list_unknowns,
get_evidence_bundle, inspect_address_context and committed unknowns
declare theirs in their bindings, and retained Evidence declares its own.
Undeclared results fall back to the contract's effects. Only a CLI
contract that reads no session is told to use its `rea` command, so
session reads and committed mutations are never told to use CLI JSON.

BREAKING CHANGE: When a budgeted tool's omitted detail returns a retained
summary, structuredContent is {"summary": <summary Evidence>, "delivery":
<delivery facts>} instead of the summary Evidence, the second
{"delivery": ...} text block is gone, and _meta["rea/agent-budget-delivery"]
is no longer set. Read the summary from structuredContent.summary and the
delivery facts from structuredContent.delivery (or the same members of the
text block). Pass detail "summary" or "complete" to receive Evidence at the
root as before.

Refs #15338
Refs #15326

* fix(delivery)!: deliver every error result under the agent result budget

A failure whose text exceeds delivery.agent_result_budget_bytes is now
retained whole as Evidence (mcp_tool_error in the MCP session,
cli_command_error in the CLI's private cache) and replaced by a bounded
summary. The summary keeps the code, category, retry, recovery and
remediation and every detail field that fits, names the fields it left
out, and carries details.failure_delivery with the inspect_analysis_view
call that pages the complete failure. Non-Evidence facts such as a
mid-extraction artifact inventory were previously inlined whole.

The transport's unretained string-ceiling fallback no longer points at
complete CLI JSON output.

BREAKING CHANGE: An MCP error, or a one-shot CLI failure without
--evidence_output, larger than the agent result budget is delivered as a
bounded summary: oversized details fields are listed in
details.omitted_details instead of being inlined, and
details.failure_delivery names the retained failure Evidence and the
inspect_analysis_view call that pages it. Pass detail complete (CLI
--detail complete) for the complete failure inline, or raise
delivery.agent_result_budget_bytes.

Refs #15326

* fix(delivery): keep overflow recovery from repeating effects or losing the session target

A retained overflow no longer offers the CLI command: the retained record is the complete result, and a call with effects is told not to repeat it. The CLI fallback for an unretained result excludes session tools. The MCP result guarantee is limited to successful results. The schema validity test selects the complete-result alternative of a budgeted output schema.

* fix(delivery): keep failure summaries schema-valid and CLI failure retention self-contained

boundedFailureSummary restores the details a code's schema requires. The CLI retains the failure as it was before its partial observation was summarized, so the record does not depend on a partial file the cache could evict, and a cache write that commits before failing or leaves cleanup incomplete keeps its receipt and cleanup owner.

* fix(delivery): retain the delivered CLI failure with its complete partial restored

* fix(delivery): budget CLI-enveloped failures through the envelope's owner

Provider-backed CLI commands wrap the canonical failure in their error envelope (a label and input diagnostics). The strict projection schema rejected the wrapped failure, so an over-budget failure printed whole without being retained. The envelope's owner now splits it; delivery budgets the canonical failure and keeps the envelope fields on the bounded result. CLI logging uses the same splitter instead of its own destructuring.

* fix(cli): print a bounded failure's retrieval facts on a terminal

A failure bounded to the agent budget carries its retained record and paging call in details.failure_delivery. The terminal presentation printed only the concise error for it, because its preserved-Evidence check did not know that field. It now does, so the structured failure is printed whole.
2026-12-01 04:10:00 +00:00

618 lines
22 KiB
TypeScript

import type { AnalysisSettings } from "../application/AnalysisSettings.js";
import { DEFAULT_MCP_MAX_INPUT_ELEMENTS } from "../config/mcpInputBudget.js";
import {
DEFAULT_MCP_TOOLS_LIST_PAGE_BUDGET,
type McpToolsListPageBudget,
} from "../config/mcpToolsListPageBudget.js";
import type {
Implementation,
Icon,
McpServerOptions,
RegisteredTool,
RegisteredPrompt,
ServerContext,
PromptCallback,
ScopeChallengeHandler,
StandardSchemaWithJSON,
ToolAnnotations,
ToolCallback,
Transport,
} from "@modelcontextprotocol/server";
import type { CompactInputSchemaPresentation } from "../contracts/compactInputSchema.js";
import {
advertiseToolInput,
type AdvertisedToolPresentation,
} from "../contracts/advertisedTool.js";
import type { createCatalogIdentity } from "../contracts/catalog/catalogIdentity.js";
import {
hasGuaranteedObjectOutputRoot,
omitAdvertisedOutputJsonSchema,
transformAdvertisedInputJsonSchema,
} from "../contracts/toolSchemaMetadata.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { z } from "zod";
import {
projectedErrorEncoding,
type ToolResultDelivery,
} from "./ToolResultDelivery.js";
import { RequestTrackingMcpServer } from "./RequestTrackingMcpServer.js";
import { AnalysisTargetFailureError } from "../domain/analysisErrorCore.js";
import { DISCOVER_TOOLS } from "../contracts/catalog/catalogDiscovery.js";
import { ProgressiveToolCatalog } from "./ProgressiveToolCatalog.js";
import type {
ToolAdmission,
WithAdmittedAnalysis,
} from "./analysisAdmission.js";
import { canReferenceInlineEvidence } from "./evidenceInputRegistration.js";
import { currentMcpToolRequest } from "./McpToolRequest.js";
import type { PromptCompletionSource } from "./promptCompletion.js";
import {
advertisedToolPresentation,
resolveMcpOutputSchemaProfile,
type McpOutputSchemaProfile,
COMPACT_INPUT_SCHEMA_PRESENTATION,
} from "../contracts/mcpSchemaPresentation.js";
import { ErrorEvidenceTransport } from "./ErrorEvidenceTransport.js";
import type {
AdvertisedToolCatalog,
AdvertisedToolDescriptor,
} from "./toolCatalogSearch.js";
import { isRecord } from "../kernel/isRecord.js";
import { RETAINED_SUMMARY_VIEW_TOOL } from "./retainedSummaryDelivery.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import { registerRetainedEvidenceResource } from "./retainedEvidenceResource.js";
/** Capture caller selections and issues at the canonical SDK validation boundary. */
const captureInputValidation = <Schema extends StandardSchemaWithJSON>(
tool: string,
schema: Schema,
pageable: boolean,
record: () => EvidenceWriter["recordEvidence"] | undefined,
): Schema => {
const standard = schema["~standard"];
// Zod issues feed field-level diagnostics; the delivery selection is
// captured for every vendor, since every admitted call has its own.
const zod = standard.vendor === "zod";
return {
...schema,
"~standard": {
...standard,
validate: (value: unknown) => {
const context = currentMcpToolRequest();
const capture = (
result: Awaited<ReturnType<typeof standard.validate>>,
) => {
if (zod && context?.tool === tool && result.issues !== undefined)
context.validation = {
issues: result.issues as readonly z.core.$ZodIssue[],
input: value,
};
if (zod && result.issues === undefined)
context?.captureCallerParameters(tool, value, result.value);
// A refused call is captured too: its input error is delivered
// under the same agent result budget as any other failure.
if (context?.tool === tool)
context.deliverySelection = {
detail: isRecord(value) ? value.detail : undefined,
pageable,
record: record(),
};
return result;
};
const result = standard.validate(value);
return result instanceof Promise
? result.then(capture)
: capture(result);
},
},
} as Schema;
};
/** A Zod schema whose standard interface exposes a JSON Schema projection. */
const hasAdvertisedInputJsonSchema = (value: unknown): boolean => {
if (typeof value !== "object" || value === null) return false;
const standard = Reflect.get(value, "~standard");
if (typeof standard !== "object" || standard === null) return false;
const jsonSchema = Reflect.get(standard, "jsonSchema");
return (
typeof jsonSchema === "object" &&
jsonSchema !== null &&
Reflect.get(jsonSchema, "input") !== undefined
);
};
/** Standard-schema registration boundary shared with deferred SDK bindings. */
export interface StandardToolRegistration {
readonly title?: string;
readonly description?: string;
readonly inputSchema?: StandardSchemaWithJSON;
readonly outputSchema?: StandardSchemaWithJSON;
readonly annotations?: ToolAnnotations;
readonly icons?: Icon[];
readonly scopeChallenge?: ScopeChallengeHandler;
readonly _meta?: Record<string, unknown>;
}
/** Lifecycle hook registered on {@link EvidenceMcpServerCore} for awaitable close. */
export interface ServerCloseHookOptions {
/** Message used when wrapping failures in an {@link AggregateError}. */
readonly failureMessage?: string | undefined;
/** Wrap even a single failure in an {@link AggregateError} with `failureMessage`. */
readonly alwaysAggregate?: boolean | undefined;
}
interface RegisteredCloseHook {
readonly close: () => Promise<void>;
readonly failureMessage: string | undefined;
readonly alwaysAggregate: boolean;
}
/** Bind oversized MCP error recovery to this server's Evidence ledger. */
export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
private readonly registrations = new Map<string, RegisteredTool>();
private readonly closeHooks: RegisteredCloseHook[] = [];
private readonly transportCloseHooks: (() => void)[] = [];
private transportOncloseInstalled = false;
private progressiveCatalog: ProgressiveToolCatalog | undefined;
private discoveryTool: RegisteredTool | undefined;
private catalogChangeDepth = 0;
private catalogChanged = false;
analysisSettings: AnalysisSettings | undefined;
/** Transport-owned Evidence uses the same lifetime as application writes. */
withAdmittedAnalysis: WithAdmittedAnalysis | undefined;
/** Session admission, read when the SDK refuses a tool's arguments. */
toolAdmission: ToolAdmission | undefined;
private identity: ReturnType<typeof createCatalogIdentity> | undefined;
/** Register an awaitable cleanup hook settled during {@link close}. */
registerCloseHook(
close: () => Promise<void>,
options: ServerCloseHookOptions = {},
): void {
this.closeHooks.push({
close,
failureMessage: options.failureMessage,
alwaysAggregate: options.alwaysAggregate === true,
});
}
/** Register a synchronous cleanup notification fired when the transport closes. */
registerTransportCloseHook(onClose: () => void): void {
this.transportCloseHooks.push(onClose);
if (this.transportOncloseInstalled) return;
this.transportOncloseInstalled = true;
const previousOnclose = this.server.onclose;
this.server.onclose = () => {
try {
previousOnclose?.();
} finally {
for (const hook of this.transportCloseHooks) {
try {
hook();
} catch {
// Hooks own their own error logging; one failure must not block the rest.
}
}
}
};
}
/** Close only the underlying MCP protocol/transport without running registered hooks. */
protected closeProtocol(): Promise<void> {
return super.close();
}
/** Settle all registered close hooks without closing the underlying transport. */
protected async closeRegisteredHooks(): Promise<void> {
if (this.closeHooks.length === 0) return;
await this.settleCloseTasks(this.closeHooks.map((hook) => hook.close()));
}
override async close(): Promise<void> {
await this.settleCloseTasks([
super.close(),
...this.closeHooks.map((hook) => hook.close()),
]);
}
private async settleCloseTasks(
tasks: readonly Promise<void>[],
): Promise<void> {
const results = await Promise.allSettled(tasks);
const failures = results.flatMap((result) =>
result.status === "rejected" ? [result.reason as unknown] : [],
);
if (failures.length === 0) return;
const alwaysAggregateHook = [...this.closeHooks]
.reverse()
.find((hook) => hook.alwaysAggregate);
if (alwaysAggregateHook !== undefined)
throw new AggregateError(
failures,
alwaysAggregateHook.failureMessage ?? "REA server cleanup failed",
);
if (failures.length === 1) throw failures[0];
const message =
[...this.closeHooks]
.reverse()
.find((hook) => hook.failureMessage !== undefined)?.failureMessage ??
"REA server cleanup failed";
throw new AggregateError(failures, message);
}
/** Composition supplies identity without importing the canonical schema graph. */
get catalogIdentity(): ReturnType<typeof createCatalogIdentity> {
if (this.identity === undefined)
throw new Error("MCP catalog identity has not been configured");
return this.progressiveCatalog?.identity ?? this.identity;
}
/** Install discovery after canonical registrations, before connecting. */
enableProgressiveCatalog(): void {
if (this.progressiveCatalog !== undefined) return;
const { name, ...config } = DISCOVER_TOOLS;
// Transport discovery has no target or analysis lifecycle. Domain tools
// continue through registerTool and their original named handlers. Its
// advertisement still follows the selected input presentation.
const adapter = super.registerTool(
name,
{ ...config, ...this.presentInput(name, config) },
(input, context) => {
context.mcpReq.signal.throwIfAborted();
return catalog.discover(input);
},
);
const catalog: ProgressiveToolCatalog = new ProgressiveToolCatalog(
this.registrations,
adapter,
this.catalogIdentity,
(change) => {
this.catalogChangeDepth++;
try {
change();
} finally {
this.catalogChangeDepth--;
if (this.catalogChangeDepth === 0 && this.catalogChanged) {
this.catalogChanged = false;
super.sendToolListChanged();
}
}
},
() => this.delivery,
);
this.discoveryTool = adapter;
this.progressiveCatalog = catalog;
}
override sendToolListChanged(): void {
if (this.catalogChangeDepth > 0) this.catalogChanged = true;
else super.sendToolListChanged();
}
private evidenceLookup: EvidenceLookup | undefined;
private servesRetainedEvidence = false;
/**
* Serve `rea://evidence/{evidence_id}` from the session ledger. The
* template is registered once, before connecting, so the resource
* capability is advertised; a deferred server registers it before its
* runtime, and its ledger lookup attaches with the runtime.
*/
serveRetainedEvidence(lookup: EvidenceLookup | undefined): void {
if (lookup !== undefined) this.evidenceLookup = lookup;
if (this.servesRetainedEvidence) return;
this.servesRetainedEvidence = true;
registerRetainedEvidenceResource(this, () => ({
lookup: this.evidenceLookup,
budgetBytes: this.delivery.resultBudgetBytes,
}));
}
/** Attach the process-owned session only after lazy runtime construction. */
attachRuntime(
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
delivery: ToolResultDelivery,
identity: ReturnType<typeof createCatalogIdentity>,
): void {
if (
this.identity !== undefined &&
this.identity.digests.combined_sha256 !== identity.digests.combined_sha256
)
throw new Error("MCP catalog identity does not match runtime");
this.recordEvidence = recordEvidence;
this.delivery = delivery;
this.identity = identity;
}
protected promptCompletion: PromptCompletionSource | undefined;
bindPromptCompletion(
completion: PromptCompletionSource,
): PromptCompletionSource {
this.promptCompletion = completion;
return completion;
}
registerCanonicalPrompt<Args extends StandardSchemaWithJSON>(
name: string,
config: { title?: string; description?: string; argsSchema: Args },
callback: PromptCallback<Args>,
): RegisteredPrompt {
return super.registerPrompt(name, config, callback);
}
private readonly presentation: AdvertisedToolPresentation;
private readonly maximumInputElements: number;
private readonly evidenceReferenceAlternatives = new Set<string>();
protected registerEvidenceReferenceAlternative(name: string): void {
this.evidenceReferenceAlternatives.add(name);
}
constructor(
info: Implementation,
options: McpServerOptions,
private recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
public delivery: ToolResultDelivery,
compactPresentation: CompactInputSchemaPresentation = COMPACT_INPUT_SCHEMA_PRESENTATION,
outputSchemaProfile:
| McpOutputSchemaProfile
| "recorded" = resolveMcpOutputSchemaProfile(undefined),
identity?: ReturnType<typeof createCatalogIdentity>,
readonly advertisedToolFamilies:
| ReadonlySet<string>
| undefined = undefined,
recordedTools?: ReadonlySet<string>,
readonly toolsListPageBudget: McpToolsListPageBudget = DEFAULT_MCP_TOOLS_LIST_PAGE_BUDGET,
) {
const maximumInputElements =
options.maxToolInputElements ?? DEFAULT_MCP_MAX_INPUT_ELEMENTS;
super(info, { ...options, maxToolInputElements: maximumInputElements });
this.maximumInputElements = maximumInputElements;
this.presentation = advertisedToolPresentation(
outputSchemaProfile,
compactPresentation,
recordedTools,
);
this.identity = identity;
}
/**
* Compact advertised input schemas and bound or omit output-schema
* advertisements. Canonical parsers and contracts remain registered; both
* output profiles validate successful structured results locally.
* The signatures mirror the SDK's registrations so call sites keep their
* inferred handler argument types.
*/
override registerTool<
OutputArgs extends StandardSchemaWithJSON,
InputArgs extends StandardSchemaWithJSON | undefined = undefined,
>(
name: string,
config: {
title?: string;
description?: string;
inputSchema?: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
icons?: Icon[];
scopeChallenge?: ScopeChallengeHandler;
_meta?: Record<string, unknown>;
},
callback: ToolCallback<InputArgs>,
): RegisteredTool {
if (canReferenceInlineEvidence(config.inputSchema))
this.registerEvidenceReferenceAlternative(name);
const advertised = this.advertisesTool(name);
const presented = advertised ? this.presentInput(name, config) : config;
const outputSchema =
this.presentation.output === undefined &&
config.outputSchema !== undefined &&
hasGuaranteedObjectOutputRoot(config.outputSchema)
? omitAdvertisedOutputJsonSchema(config.outputSchema)
: config.outputSchema;
const registeredConfig = advertised
? {
...config,
...(presented.description === undefined
? {}
: { description: presented.description }),
...(presented.inputSchema === undefined
? {}
: {
inputSchema: captureInputValidation(
name,
presented.inputSchema as StandardSchemaWithJSON,
this.advertisesTool(RETAINED_SUMMARY_VIEW_TOOL),
() => this.recordEvidence,
),
}),
...(outputSchema === undefined ? {} : { outputSchema }),
}
: outputSchema === undefined
? config
: { ...config, outputSchema };
const scoped = async (input: never, context: never) => {
const request = currentMcpToolRequest();
request?.beginHandler();
try {
const normalized = (original: ServerContext): ServerContext =>
request === undefined
? original
: {
...original,
mcpReq: {
...original.mcpReq,
signal: AbortSignal.any([
request.cancellation.signal,
original.mcpReq.signal,
]),
},
};
const invoke = () =>
config.inputSchema === undefined
? (callback as ToolCallback<undefined>)(
normalized(input as ServerContext),
)
: (callback as ToolCallback<StandardSchemaWithJSON>)(
input,
normalized(context as ServerContext),
);
let result: Awaited<ReturnType<typeof invoke>>;
try {
result = await (this.analysisSettings === undefined
? invoke()
: this.analysisSettings.run(invoke));
} catch (cause: unknown) {
// The SDK flattens a thrown handler failure into one text block and
// JSON-RPC errors are for protocol faults, so a target failure that
// escapes a handler is still returned as a projected tool result.
// Its message can name target bytes, so it is marked as such.
if (!(cause instanceof AnalysisTargetFailureError)) throw cause;
result = this.delivery.toErrorToolResult(cause, true);
}
if (request !== undefined)
request.projectedErrorEncoding = projectedErrorEncoding(result);
return result;
} finally {
request?.finishHandler();
}
};
const registered = this.bindTool(
name,
registeredConfig as never,
scoped as never,
);
if (!advertised) registered.disable();
return registered;
}
/**
* The input schema and tool description this server advertises for one
* registration: the compact presentation, whose guidance joins the
* description. A registration without an input schema is unchanged. Every
* listed tool, including
* transport discovery, takes this one path.
*/
private presentInput<Schema>(
name: string,
config: { readonly description?: string; readonly inputSchema?: Schema },
): { description?: string; inputSchema?: Schema } {
const { description, inputSchema } = config;
const { input } = this.presentation;
if (inputSchema === undefined || !hasAdvertisedInputJsonSchema(inputSchema))
return config;
let draft2020:
| {
readonly description: string | undefined;
readonly inputSchema: Record<string, unknown> | undefined;
}
| undefined;
const projectDraft2020 = () => {
if (draft2020 !== undefined) return draft2020;
const projected = (inputSchema as StandardSchemaWithJSON)[
"~standard"
].jsonSchema.input({ target: "draft-2020-12" });
draft2020 = isRecord(projected)
? advertiseToolInput(description, projected, input)
: { description, inputSchema: undefined };
return draft2020;
};
return {
...this.describeTool(name, () => projectDraft2020().description),
inputSchema: transformAdvertisedInputJsonSchema(
inputSchema,
(projected) =>
advertiseToolInput(description, projected, input).inputSchema,
(target) =>
target === "draft-2020-12"
? projectDraft2020().inputSchema
: undefined,
),
};
}
/**
* The listed description: guidance the compact input schema omits follows
* the registered description. Reading it projects the schema.
*/
protected describeTool(
_name: string,
advertised: () => string | undefined,
): { description?: string } {
const described = advertised();
return described === undefined ? {} : { description: described };
}
/** Whether this process advertises one named operation. */
advertisesTool(_name: string): boolean {
return true;
}
/** Provider probes consult the registration scope before doing work. */
advertisesFamily(family: string): boolean {
return (
this.advertisedToolFamilies === undefined ||
this.advertisedToolFamilies.has(family)
);
}
protected bindTool(
name: string,
config: StandardToolRegistration,
callback: ToolCallback<StandardSchemaWithJSON | undefined>,
): RegisteredTool {
const registered = super.registerTool(
name,
config as never,
callback as never,
);
this.registrations.set(name, registered);
return registered;
}
/** Snapshot currently enabled (advertised) tools for unknown-tool hints. */
private advertisedToolCatalog(): AdvertisedToolCatalog {
const tools: AdvertisedToolDescriptor[] = [];
for (const [name, registered] of this.registrations) {
if (registered.enabled)
tools.push({ name, description: registered.description });
}
const discoveryAvailable =
this.progressiveCatalog !== undefined &&
this.discoveryTool?.enabled === true;
if (discoveryAvailable)
tools.push({
name: DISCOVER_TOOLS.name,
description:
this.discoveryTool?.description ?? DISCOVER_TOOLS.description,
});
return {
tools,
discoveryAvailable,
...(discoveryAvailable && this.progressiveCatalog !== undefined
? { unloadedTools: this.progressiveCatalog.unloadedTools() }
: {}),
};
}
/** Preserve the SDK transport lifecycle while retaining oversized errors. */
override connect(transport: Transport): Promise<void> {
// HTTP reuses the analysis server after draining the previous transport.
// Reset visibility while disconnected, before the next initialize/list.
if (!this.isConnected()) this.progressiveCatalog?.reset();
return super.connect(
new ErrorEvidenceTransport(
transport,
() => this.recordEvidence,
() => this.delivery,
() => this.withAdmittedAnalysis,
() => this.toolAdmission,
this.presentation.output,
this.maximumInputElements,
this.evidenceReferenceAlternatives,
this.toolsListPageBudget,
() => this.advertisedToolCatalog(),
),
);
}
}