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
This commit is contained in:
morluto committed 2026-11-30 19:16:40 -05:00
1 parent 87dcb534ba
commit 0fc71ce60f
80 files changed
+728 -489

No files matched your search

+10 -7
View File
@@ -440,14 +440,17 @@ and settings inspection reports it. The stdio frame limit,
When complete Evidence fits, it is delivered inline as before. When it does
not, the work is never refused or truncated:
- MCP retains the complete Evidence in the session and returns the
- MCP retains the complete Evidence in the session and returns
`{"summary": …, "delivery": …}`, the shape the CLI prints. `summary` is the
operation's summary view, the same record `detail: "summary"` returns, so
its identity holds wherever a summary is accepted. The delivery facts
travel beside it, in a second text block `{"delivery": …}` and in
`_meta["rea/agent-budget-delivery"]`: `budget_bytes`, `budget_source`, the
range, `complete_bytes`, `estimated_complete_tokens`, `evidence_id`,
`retained`, `next` (the exact `inspect_analysis_view` call that pages the
complete record) and a `note` with the recovery.
its identity holds wherever a summary is accepted. `delivery` carries
`budget_bytes`, `budget_source`, the range, `complete_bytes`,
`estimated_complete_tokens`, `evidence_id`, `retained`, `next` (the exact
`inspect_analysis_view` call that pages the complete record) and a `note`
with the recovery. Both are in `structuredContent`, and the one text block
is its serialization, so the facts reach the model whether its client
forwards only `structuredContent` (Codex, VS Code) or only text (Gemini
CLI, LangChain). Each budgeted tool's output schema admits this result.
- `inspect_analysis_view` with view
`{kind: "evidence-json", offset, limit}` pages the exact JSON text of the
retained record in UTF-16 code units. It is the recovery every client can
+12 -1
View File
@@ -29,6 +29,14 @@ can be passed directly to `compare_functions`, and `inspect_artifact` Evidence
to `compare_artifacts`. Use `get_evidence_bundle` when the task needs broader
retained session history or an explicit bundle for transfer.
Every result REA returns puts all of its facts in `structuredContent`, and its
one text block is the serialization of that same value, so an agent receives
them whether its client forwards structured content or only text. When a tool
whose `detail` was omitted produces Evidence over the agent result budget, that
value is `{"summary": …, "delivery": …}`: the retained summary record and the
facts that say it is a summary and how to page the complete record. See
[agent result budget](limits-and-recovery.md#agent-result-budget).
`compare_artifacts` does not need that Evidence sent back. Name each side once
with a source that `inspect_analysis_view` also accepts:
`{"kind": "retained-evidence", "evidence_id": "<id>"}` for a record retained in
@@ -585,7 +593,10 @@ the same filters and offset and a smaller limit; export if one head still cannot
fit. When the recovery starts with one MCP operation,
`details.reported_limits.next_operation` names it: `export_evidence_bundle` for
a committed unknown or a one-row page, `list_unknowns` for a page that a smaller
limit can split. It is absent when the recovery is complete CLI JSON output.
limit can split. Any other completed result that exceeds the response budget
names `next_operation` when its producer declared a next call. Otherwise the
recovery names the `rea` CLI command only when the tool has one and reads no
session state, and a call that may have changed state says not to repeat it.
To find missing sources before a downstream analysis refuses them, read
`missing_direct_links` from the summary, or call `get_evidence_bundle` with
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "5410f29d6d7195f1",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "3d7959f5cdca863d",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "38d5b1c230543ed8",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "11b8c13561b47f60",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "03c154678fe7d621",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": [
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "0395893cc47e3a89",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "b6abe16831697f1d",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$", "^occ_[0-9a-f]{64}$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "31cc6bc09d1bb29d",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": [
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "71d7ad04aa702db9",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": [
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "d8bc42e72c3d6756",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "56738775db12a59b",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "961c1bc71b1cf86f",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "79d06f0abbf80d96",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "16bf0853f5fb7fa0",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "23e5246e6a440825",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "3fe6fb83f79175c6",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "2476699dc41f6dc7",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$", "^[^\\x2f]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "9047b0c5aef153cd",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "30fb8db090aa6071",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "447bb9e9132f0384",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "b805503666f3d982",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "432b9d1cce8cbaa1",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "95716cd5713d57c4",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "80b17fd02e3831bb",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^0x[0-9A-Fa-f]{1,8}$", "^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "4da052ea4100ae2a",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "983af8eae7e1bbb7",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "d50348f9415e6058",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "f7bf3f8936afcd55",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "273b3dc42f7bd1f5",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "99a593e8ee1b1a36",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "1e3af2bde466363b",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "515d445c21827e5c",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "46784e3380ef2921",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "5d8db1d69f56b939",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "d77cd7aa06705c28",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "454f43f2d5b6b374",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "1f60381afcd13a28",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "4d6179b4d0d694c1",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "e30c9b8ea56dc0da",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "37c2c73ee2d1c5e6",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "f2ac113b26052065",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "ad6deeb69e540106",
"output compact": "736a987c76cd188a"
"output compact": "42b0abc4695d01f1"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "e6c23cc150ea72d5",
"output compact": "736a987c76cd188a"
"output compact": "42b0abc4695d01f1"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "ad6deeb69e540106",
"output compact": "736a987c76cd188a"
"output compact": "42b0abc4695d01f1"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "eab15d9712a91afa",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "e91653898083fedc",
"output compact": "843e40238bd38c90"
"output compact": "3f0bd2ea1eff0173"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "e91653898083fedc",
"output compact": "e491fe8cfac41177"
"output compact": "5b53ae80a71c76b8"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "e91653898083fedc",
"output compact": "e491fe8cfac41177"
"output compact": "5b53ae80a71c76b8"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "7bd3d5206ada19ea",
"output compact": "f4296b880e26e644"
"output compact": "88733f11ac8c9a26"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "07541a0e1a862339",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "5ead352a637a24da",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "9f4f41150e61f0dc",
"output compact": "736a987c76cd188a"
"output compact": "42b0abc4695d01f1"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "9f4f41150e61f0dc",
"output compact": "736a987c76cd188a"
"output compact": "42b0abc4695d01f1"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "fcfd3ff516c61616",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "ef7bf3f41eddd3cd",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {}
}
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "a0239c9f31bd11d9",
"output compact": "fc6c5d5a78a47254"
"output compact": "d2b94d1517ad80ea"
},
"patterns": {
"input": ["^[^\\x00]*$"]
@@ -1,7 +1,7 @@
{
"schemas": {
"input compact": "ad6deeb69e540106",
"output compact": "e491fe8cfac41177"
"output compact": "5b53ae80a71c76b8"
},
"patterns": {}
}
+30 -7
View File
@@ -21,7 +21,12 @@ import {
isDeclaredEvidenceRecord,
} from "../domain/evidenceInputContract.js";
import { isRecord } from "../kernel/isRecord.js";
import { schemaAnnotations } from "../domain/schemaAnnotations.js";
import {
presentObjectRoot,
schemaAnnotations,
} from "../domain/schemaAnnotations.js";
import { agentBudgetSummaryResultOf } from "../domain/agentResultBudget.js";
import { isAgentBudgetOperation } from "../domain/agentBudgetOperations.js";
const PROPERTY_DESCRIPTIONS: Readonly<Record<string, string>> = {
addresses: "Ordered provider-normalized procedure addresses to analyze.",
@@ -213,13 +218,31 @@ export const advertisedInputJsonSchema = <Contract extends ToolContract>(
target: "draft-2020-12",
}) as Record<string, unknown>;
/**
* Every structured result MCP delivers for a contract: its declared output,
* and for an operation whose omitted `detail` is budgeted, also the
* `{summary, delivery}` result that replaces complete Evidence over the
* agent result budget. The delivery layer owns that alternative, so no
* contract declares it.
*/
const deliveredOutputSchema = (contract: ToolContract): z.ZodType =>
isAgentBudgetOperation(contract.name)
? presentObjectRoot(
z.union([
contract.outputSchema as unknown as z.ZodObject,
agentBudgetSummaryResultOf(contract.outputSchema),
]),
)
: contract.outputSchema;
/** Share output definitions and content-bound validator identities on the wire. */
export const toolOutputSchemaWithMetadata = <Contract extends ToolContract>(
contract: Contract,
): Contract["outputSchema"] =>
oncePerContract(advertisedOutputSchemas, contract, () =>
withAdvertisedJsonSchema(
contract.outputSchema,
oncePerContract(advertisedOutputSchemas, contract, () => {
const delivered = deliveredOutputSchema(contract);
return withAdvertisedJsonSchema(
delivered,
"output",
(project) => (options) => {
const projected = project({
@@ -228,7 +251,7 @@ export const toolOutputSchemaWithMetadata = <Contract extends ToolContract>(
});
const shared = shareOutputDefinitions(
presentOutputJsonSchema(
schemaAnnotations(contract.outputSchema)?.objectRoot === true
schemaAnnotations(delivered)?.objectRoot === true
? objectRoot(projected)
: projected,
),
@@ -245,8 +268,8 @@ export const toolOutputSchemaWithMetadata = <Contract extends ToolContract>(
)}`,
};
},
),
);
) as Contract["outputSchema"];
});
/**
* Return the canonical output JSON Schema registered on MCP for a target: the
+8
View File
@@ -62,3 +62,11 @@ export const AGENT_BUDGET_OPERATIONS = [
"trace_web_source_location",
"xrefs",
] as const;
const AGENT_BUDGET_OPERATION_NAMES: ReadonlySet<string> = new Set(
AGENT_BUDGET_OPERATIONS,
);
/** Whether this operation's omitted `detail` is decided by the agent result budget. */
export const isAgentBudgetOperation = (name: string): boolean =>
AGENT_BUDGET_OPERATION_NAMES.has(name);
+52 -29
View File
@@ -177,47 +177,59 @@ export type AgentBudgetRecovery =
/** Nothing was written; `reason` says why when retention was attempted. */
| { readonly kind: "not-retained"; readonly reason?: string };
/** Placeholder for the caller's choice of a new bundle path. */
export const EVIDENCE_OUTPUT_PLACEHOLDER = "<new-bundle-path>";
/**
* Delivery facts for a result replaced by its summary. They describe the
* delivery, not the analysis, so they travel beside the summary record and
* never change its identity.
* delivery, not the analysis, so they never change the summary record's
* identity: a result carries them beside it as `{summary, delivery}`, and a
* failure as `details.partial_observation_delivery`.
*/
export interface AgentBudgetDelivery {
readonly kind: "agent-budget-summary";
readonly setting: typeof AGENT_RESULT_BUDGET_SETTING;
readonly budget_bytes: number;
readonly budget_source: AgentResultBudget["source"];
readonly budget_minimum: number;
readonly budget_maximum: number;
readonly complete_bytes: number;
export const agentBudgetDeliverySchema = z.strictObject({
kind: z.literal("agent-budget-summary"),
setting: z.literal(AGENT_RESULT_BUDGET_SETTING),
budget_bytes: z.int().positive(),
budget_source: z.enum(["default", "setting", "runtime"]),
budget_minimum: z.int().positive(),
budget_maximum: z.int().positive(),
complete_bytes: z.int().positive(),
/** Estimated at ESTIMATED_JSON_BYTES_PER_TOKEN; not a tokenizer count. */
readonly estimated_complete_tokens: number;
readonly evidence_id: string;
readonly retained: AgentBudgetRecovery["kind"];
estimated_complete_tokens: z.int().positive(),
evidence_id: z.string().min(1),
retained: z.enum(["session", "evidence-file", "cache-file", "not-retained"]),
/** The view call that pages the complete record, when it was retained. */
readonly next?: {
readonly operation: "inspect_analysis_view";
readonly arguments: {
readonly source: Readonly<Record<string, string>>;
readonly view: { readonly kind: "evidence-json"; readonly offset: 0 };
};
};
next: z
.strictObject({
operation: z.literal("inspect_analysis_view"),
arguments: z.strictObject({
source: z.record(z.string(), z.string()),
view: z.strictObject({
kind: z.literal("evidence-json"),
offset: z.literal(0),
}),
}),
})
.optional(),
/**
* For an invocation that retained nothing: the exact arguments to add to
* the same command, for complete Evidence inline or saved to a new bundle.
* Caller inputs are never echoed, since they can carry access credentials.
*/
readonly rerun?: {
readonly complete: readonly string[];
readonly retained: readonly string[];
};
rerun: z
.strictObject({
complete: z.array(z.string()).readonly(),
retained: z.array(z.string()).readonly(),
})
.optional(),
/** Why the CLI's default retention wrote nothing, when it was attempted. */
readonly retention_failure?: string;
readonly note: string;
}
retention_failure: z.string().optional(),
note: z.string().min(1),
});
/** Placeholder for the caller's choice of a new bundle path. */
export const EVIDENCE_OUTPUT_PLACEHOLDER = "<new-bundle-path>";
export type AgentBudgetDelivery = Readonly<
z.output<typeof agentBudgetDeliverySchema>
>;
const RERUN_ARGUMENTS: NonNullable<AgentBudgetDelivery["rerun"]> = {
complete: ["--detail", "complete"],
@@ -297,3 +309,14 @@ export const agentBudgetDelivery = (input: {
note: `Complete ${input.operation} Evidence ${evidenceId} is ${String(completeBytes)} bytes (about ${String(estimatedJsonTokens(completeBytes))} tokens, estimated at ${String(ESTIMATED_JSON_BYTES_PER_TOKEN)} bytes per token), over the agent result budget of ${String(budget.bytes)} bytes (${AGENT_RESULT_BUDGET_SETTING}, source ${budget.source}), so its summary was delivered. Nothing was truncated. ${recoveryNote(recovery)}`,
};
};
/**
* The structured result that replaces complete Evidence over the agent
* result budget: the operation's summary record, unchanged, and the
* delivery facts that say it is a summary and how to read the rest. Clients
* that forward only `structuredContent` and clients that forward only its
* text serialization both receive the facts.
*/
export const agentBudgetSummaryResultOf = <Summary extends z.ZodType>(
summary: Summary,
) => z.strictObject({ summary, delivery: agentBudgetDeliverySchema });
+1 -1
View File
@@ -87,7 +87,7 @@ export const UNRETAINED_EVIDENCE_EXPORT_GUIDANCE =
/** File export when one MCP frame cannot carry the retained session bundle. */
export const MCP_TRANSPORT_EVIDENCE_EXPORT =
"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 complete retained session evidence through export_evidence_bundle to a caller-selected path. The connection remains usable.";
/** 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, selecting a limit and following page.next_offset; then read selected complete records with detail: records and an exact evidence_id, or inspect compatible records through inspect_analysis_view using an exact Evidence reference. ${MCP_TRANSPORT_EVIDENCE_EXPORT}`;
@@ -21,10 +21,7 @@ import {
const VALID_SEED_BYTES = 8192;
import type { Evidence } from "../domain/evidence.js";
import { McpToolRequest, runMcpToolRequest } from "./McpToolRequest.js";
import {
AGENT_BUDGET_DELIVERY_META,
ToolResultDelivery,
} from "./ToolResultDelivery.js";
import { ToolResultDelivery } from "./ToolResultDelivery.js";
import { measureMcpResultWithinBudget } from "./toolResultEncoding.js";
import {
readRetainedEvidenceResource,
@@ -66,6 +63,10 @@ const deliver = (
);
};
/** The delivery facts inside a budget-replaced structured result. */
const deliveryOf = (result: { readonly structuredContent?: unknown }) =>
(result.structuredContent as { readonly delivery?: unknown }).delivery;
const frameBytes = (result: unknown): number => {
const measured = measureMcpResultWithinBudget(
result,
@@ -75,7 +76,7 @@ const frameBytes = (result: unknown): number => {
return measured.bytes;
};
it("counts the delivery facts in the frame check, at the exact boundary", async () => {
it("counts the delivery facts and the link in the frame check, at the exact boundary", async () => {
const evidence = await largeEntropyEvidence();
const unlimited = deliver(
new ToolResultDelivery(1024 * 1024 * 1024),
@@ -83,7 +84,7 @@ it("counts the delivery facts in the frame check, at the exact boundary", async
new EvidenceLedger(),
);
expect(unlimited.isError).not.toBe(true);
expect(unlimited._meta?.[AGENT_BUDGET_DELIVERY_META]).toBeDefined();
expect(deliveryOf(unlimited)).toBeDefined();
// Frames near the summary's size are far below the complete record, so
// they carry no resource link: measure the response without it.
expect(unlimited.content.at(-1)?.type).toBe("resource_link");
@@ -111,9 +112,9 @@ it("counts the delivery facts in the frame check, at the exact boundary", async
},
});
// The reservation is an upper bound: with room for it the response is sent
// and the whole frame, delivery facts included, fits the frame budget.
const roomy = new ToolResultDelivery(total + 64 + 1024);
// With room for the frame the response is sent, and the whole frame,
// delivery facts included, fits the frame budget.
const roomy = new ToolResultDelivery(total + 1024);
const sent = deliver(roomy, evidence, new EvidenceLedger());
expect(sent.isError).not.toBe(true);
expect(frameBytes(sent)).toBeLessThanOrEqual(roomy.resultBudgetBytes);
@@ -130,7 +131,7 @@ it("reads the budget seed from the environment the server captured, not the proc
evidence,
new EvidenceLedger(),
);
expect(defaulted._meta?.[AGENT_BUDGET_DELIVERY_META]).toMatchObject({
expect(deliveryOf(defaulted)).toMatchObject({
budget_bytes: DEFAULT_AGENT_RESULT_BUDGET_BYTES,
budget_source: "default",
});
@@ -145,7 +146,7 @@ it("reads the budget seed from the environment the server captured, not the proc
evidence,
new EvidenceLedger(),
);
expect(seeded._meta?.[AGENT_BUDGET_DELIVERY_META]).toMatchObject({
expect(deliveryOf(seeded)).toMatchObject({
budget_bytes: VALID_SEED_BYTES,
budget_source: "setting",
});
@@ -160,7 +161,7 @@ it("reads the budget seed from the environment the server captured, not the proc
evidence,
new EvidenceLedger(),
);
expect(invalid._meta?.[AGENT_BUDGET_DELIVERY_META]).toBeUndefined();
expect(deliveryOf(invalid)).toBeUndefined();
expect((invalid.structuredContent as Evidence).operation).toBe(
"inspect_byte_entropy",
);
@@ -275,10 +276,7 @@ it("links the complete record only when one read can fit the frame, and refuses
);
const escapedResult = deliver(escaped, evidence, new EvidenceLedger());
expect(escapedResult.isError).not.toBe(true);
expect(escapedResult.content.map(({ type }) => type)).toEqual([
"text",
"text",
]);
expect(escapedResult.content.map(({ type }) => type)).toEqual(["text"]);
// REA's single-string limit bounds a read as well as its bytes.
expect(retainedEvidenceReadFits(evidence, 64 * 1024 * 1024)).toBe(true);
expect(
@@ -290,7 +288,7 @@ it("links the complete record only when one read can fit the frame, and refuses
const narrow = new ToolResultDelivery(completeBytes);
const unlinked = deliver(narrow, evidence, new EvidenceLedger());
expect(unlinked.isError).not.toBe(true);
expect(unlinked.content.map(({ type }) => type)).toEqual(["text", "text"]);
expect(unlinked.content.map(({ type }) => type)).toEqual(["text"]);
expect(() =>
readRetainedEvidenceResource(
uri,
+156 -179
View File
@@ -20,12 +20,6 @@ import { NoBinaryOpenError } from "../domain/configurationErrors.js";
import 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_LINKS,
MCP_TRANSPORT_EVIDENCE_RECORDS,
MCP_TRANSPORT_EVIDENCE_SUMMARY,
} from "../domain/analysisErrorPresentation.js";
import {
nodeStringCeilingRecovery,
stdioResponseBudgetRecovery,
@@ -39,7 +33,6 @@ import {
TARGET_CONTENT_RESULT_META,
type ToolResultEncoding,
} from "./toolResultEncoding.js";
import { isRecord } from "../kernel/isRecord.js";
import { summarizeOverBudgetEvidence } from "../application/analysisView/AnalysisViewService.js";
import { INSPECT_ANALYSIS_VIEW_OPERATION } from "../domain/analysisView/analysisViewErrors.js";
import {
@@ -51,16 +44,9 @@ import {
type AgentBudgetDelivery,
} from "../domain/agentResultBudget.js";
import { currentMcpToolRequest } from "./McpToolRequest.js";
import { AGENT_BUDGET_OPERATIONS } from "../domain/agentBudgetOperations.js";
import { isAgentBudgetOperation } from "../domain/agentBudgetOperations.js";
import { retainedEvidenceLink } from "./retainedEvidenceResource.js";
const AGENT_BUDGET_OPERATION_NAMES: ReadonlySet<string> = new Set(
AGENT_BUDGET_OPERATIONS,
);
/** `_meta` key for the delivery facts of a budget-replaced result. */
export const AGENT_BUDGET_DELIVERY_META = "rea/agent-budget-delivery";
/** Project a response-budget refusal without labeling REA's reserved string limit as Node's ceiling. */
export const mcpResponseOverflowProjection = (input: {
readonly completed: boolean;
@@ -93,94 +79,109 @@ export const mcpResponseOverflowProjection = (input: {
};
};
/**
* The bundle projection a get_evidence_bundle result already selected.
* Each projection owns a different next step when it exceeds one MCP frame.
*/
const evidenceBundleProjection = (value: JsonValue): JsonValue | undefined => {
const payload = isRecord(value) && "result" in value ? value.result : value;
return isRecord(payload) ? payload.kind : undefined;
};
/**
* The recovery for an overflowing completed result: its prose and, when it
* names one MCP operation to call first, that operation. The CLI fallback
* names none.
*/
interface OverflowNextStep {
readonly text: string;
readonly operation?: string;
/** The producer's next call when a completed result does not fit one response. */
export interface OverflowNextCall {
readonly operation: string;
/** One or two sentences on how to use that call. */
readonly guidance: string;
}
const evidenceBundleOverflowStep = (value: JsonValue): OverflowNextStep => {
const projection = evidenceBundleProjection(value);
if (projection === "evidence-bundle-summary")
return {
text: MCP_TRANSPORT_EVIDENCE_SUMMARY,
operation: "get_evidence_bundle",
/**
* What a caller can do when a completed result does not fit one MCP
* response. The producer declares it; delivery renders it and never infers
* it from a tool name.
*
* - `stateless`: nothing was retained or changed, so repeating the call is
* safe. A CLI contract that reads no session can be run there instead.
* - `retained`: the complete result is kept in this session; `next` reads it.
* - `committed`: the call changed state, so it must not be repeated; `next`,
* when present, reads what it committed.
*
* `facts` are the identities the next call needs, such as an Evidence
* reference, a continuation or a committed receipt.
*/
export type OverflowRecovery =
| {
readonly kind: "stateless";
readonly next?: OverflowNextCall;
readonly facts?: Readonly<Record<string, JsonValue>>;
}
| {
readonly kind: "retained";
readonly next: OverflowNextCall;
readonly facts?: Readonly<Record<string, JsonValue>>;
}
| {
readonly kind: "committed";
readonly next?: OverflowNextCall;
readonly facts?: Readonly<Record<string, JsonValue>>;
};
return {
text:
projection === "evidence-link-inspection"
? MCP_TRANSPORT_EVIDENCE_LINKS
: projection === "evidence-record-selection"
? MCP_TRANSPORT_EVIDENCE_RECORDS
: MCP_TRANSPORT_EVIDENCE_DISCOVERY,
operation: "get_evidence_bundle",
};
};
/**
* Rows in an overflowing `list_unknowns` page, delivered as a session
* `{ result }` envelope; a smaller limit only helps above one.
* A contract's recovery when its producer declared none: a non-idempotent
* call may have changed state, so only an idempotent one is safe to repeat.
*/
const unknownPageItems = (value: JsonValue): number => {
const page = isRecord(value) ? value.result : undefined;
return isRecord(page) && Array.isArray(page.items)
? page.items.length
: Number.POSITIVE_INFINITY;
const contractOverflow = (
contract: ToolContract,
facts?: Readonly<Record<string, JsonValue>>,
): OverflowRecovery => ({
kind: contract.effects.idempotent ? "stateless" : "committed",
...(facts === undefined ? {} : { facts }),
});
/** The prose an overflow refusal states for its declared recovery. */
const overflowNextStep = (
overflow: OverflowRecovery,
contract: ToolContract,
): string => {
// Only a one-shot command that reads no session state reproduces the
// result; a session's target, annotations or retained records do not
// exist in a new CLI process.
const cli =
contract.cli === true && contract.requiresActiveTarget !== true
? `Run the same request as the CLI command \`rea ${contract.name.replaceAll("_", "-")}\` for complete JSON output.`
: undefined;
switch (overflow.kind) {
case "stateless":
return (
overflow.next?.guidance ??
cli ??
"Repeat the call with a narrower selection; nothing was retained or changed."
);
case "retained":
return [overflow.next.guidance, cli].filter(Boolean).join(" ");
case "committed":
return [
overflow.next?.guidance,
"Do not repeat the completed call; its change was committed.",
]
.filter(Boolean)
.join(" ");
}
};
const overflowNextStep = (
value: JsonValue,
contract: ToolContract,
recovery: Readonly<Record<string, JsonValue>>,
): OverflowNextStep => {
if (recovery.committed_unknown !== undefined)
return {
text: "Export this session with export_evidence_bundle to inspect the committed unknown and its mutation Evidence. Do not repeat the completed mutation; an individual unknown may be too large for a list_unknowns page.",
operation: "export_evidence_bundle",
};
if (recovery.continuation !== undefined)
return {
text: "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.",
operation: "inspect_analysis_view",
};
if (recovery.evidence_reference !== undefined)
return {
text: "Export retained evidence to consume the complete analysis, or use complete CLI JSON output.",
operation: "export_evidence_bundle",
};
if (contract.name === "list_unknowns" && unknownPageItems(value) <= 1)
return {
text: "One unknown does not fit a list_unknowns response on this connection, so a smaller limit cannot help. Export the session with export_evidence_bundle to recover it.",
operation: "export_evidence_bundle",
};
if (contract.name === "list_unknowns")
return {
text: "Call list_unknowns on this same connection with the same filters and offset, using a smaller limit, then follow next_offset. If a single unknown cannot fit, export the session with export_evidence_bundle to recover it.",
operation: "list_unknowns",
};
if (contract.name === "get_evidence_bundle")
return evidenceBundleOverflowStep(value);
if (contract.name === "inspect_address_context")
return {
text: "Call get_evidence_bundle with detail summary to discover retained facet observations, then export_evidence_bundle to inspect complete records. Some facets may not have been retained; a new analysis can differ.",
operation: "get_evidence_bundle",
};
return { text: "Use complete CLI JSON output to consume the analysis." };
const CONTINUATION_NEXT_CALL: OverflowNextCall = {
operation: "inspect_analysis_view",
guidance:
"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.",
};
/** The recovery for Evidence a session retained, read in pages or exported. */
const retainedEvidenceOverflow = (
facts: Readonly<Record<string, JsonValue>>,
): OverflowRecovery => ({
kind: "retained",
next:
facts.continuation === undefined
? {
operation: "export_evidence_bundle",
guidance:
"Export the retained Evidence with export_evidence_bundle to consume the complete analysis.",
}
: CONTINUATION_NEXT_CALL,
facts,
});
/** Immutable encoding and recovery policy shared by one MCP server. */
/** The encoding already computed by `ToolResultDelivery` for a structured error result. */
export type ProjectedErrorEncoding =
@@ -234,16 +235,23 @@ export class ToolResultDelivery {
);
}
/** Serialize a plain application result or its actionable error. */
/**
* Serialize a plain application result or its actionable error. A
* producer that knows what an overflowing caller can do declares it;
* otherwise the contract's own effects decide.
*/
toCallToolResult(
result: Result<JsonValue, AnalysisError>,
contract: ToolContract,
recovery: Readonly<Record<string, JsonValue>> = {},
alternatives?: (
failure: Extract<ToolResultEncoding, { readonly ok: false }>,
budgetBytes: number,
) => Iterable<JsonValue>,
declared: {
readonly overflow?: OverflowRecovery;
readonly alternatives?: (
failure: Extract<ToolResultEncoding, { readonly ok: false }>,
budgetBytes: number,
) => Iterable<JsonValue>;
} = {},
): CallToolResult {
const { alternatives } = declared;
// A session tool's result is delivered inside `result`, alternatives too.
const shaped = (value: JsonValue): JsonValue =>
contract.kind === "session" ? { result: value } : value;
@@ -251,7 +259,7 @@ export class ToolResultDelivery {
? this.successResult(
shaped(result.value),
contract,
recovery,
declared.overflow ?? contractOverflow(contract),
alternatives === undefined
? undefined
: function* (failure, budgetBytes) {
@@ -334,43 +342,51 @@ export class ToolResultDelivery {
resultBudgetBytes: this.resultBudgetBytes,
});
if (budgeted !== undefined) {
// The frame check covers the delivery facts added after encoding.
// The delivery facts travel inside the structured result, so clients
// that forward only `structuredContent` and clients that forward only
// its text both receive them. The frame check covers the link after it.
const delivered = this.successResult(
budgeted.summary,
contract,
{
summary: budgeted.summary,
delivery: budgeted.delivery,
} as unknown as JsonValue,
contract,
retainedEvidenceOverflow({
evidence_id: budgeted.summary.evidence_id,
evidence_reference: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
agent_budget: budgeted.delivery as unknown as JsonValue,
},
}),
undefined,
agentBudgetDeliveryBytes(budgeted.delivery, budgeted.link),
budgeted.link === undefined ? 0 : contentBlockBytes(budgeted.link),
);
return delivered.isError === true
return delivered.isError === true || budgeted.link === undefined
? delivered
: withAgentBudgetDelivery(delivered, budgeted.delivery, budgeted.link);
: { ...delivered, content: [...delivered.content, budgeted.link] };
}
return this.successResult(evidence, contract, () => {
const resolvedViewSource =
typeof viewSource === "function" ? viewSource() : viewSource;
return {
// A view names its caller's source, which needs no session to read again.
const facts: Readonly<Record<string, JsonValue>> = {
evidence_id: evidence.evidence_id,
...(recorded === undefined
? {}
: {
evidence_reference: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
}),
// A view names its caller's source, which needs no session to read again.
...(recorded === undefined && resolvedViewSource === undefined
? {}
: this.nativeContinuation(evidence, undefined, resolvedViewSource)),
};
if (recorded !== undefined)
return retainedEvidenceOverflow({
...facts,
evidence_reference: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
});
return facts.continuation === undefined
? contractOverflow(contract, facts)
: { kind: "stateless", next: CONTINUATION_NEXT_CALL, facts };
});
}
@@ -387,14 +403,18 @@ export class ToolResultDelivery {
): CallToolResult {
return recorded !== undefined && !recorded.ok
? this.toErrorToolResult(recorded.error, contract.returnsTargetContent)
: this.successResult(view, contract, {
evidence_id: view.evidence_id,
evidence_reference: {
kind: "retained-evidence",
evidence_id: selection.parent.evidence_id,
},
...this.nativeContinuation(selection.parent, selection.request),
});
: this.successResult(
view,
contract,
retainedEvidenceOverflow({
evidence_id: view.evidence_id,
evidence_reference: {
kind: "retained-evidence",
evidence_id: selection.parent.evidence_id,
},
...this.nativeContinuation(selection.parent, selection.request),
}),
);
}
/**
@@ -524,8 +544,7 @@ export class ToolResultDelivery {
budgeted.completeBytes,
this.resultBudgetBytes,
);
const linkBytes =
link === undefined ? 0 : Buffer.byteLength(JSON.stringify(link)) + 1;
const linkBytes = link === undefined ? 0 : contentBlockBytes(link);
let 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.
@@ -614,9 +633,7 @@ export class ToolResultDelivery {
private successResult(
value: JsonValue,
contract: ToolContract,
recovery:
| Readonly<Record<string, JsonValue>>
| (() => Readonly<Record<string, JsonValue>>) = {},
recovery: OverflowRecovery | (() => OverflowRecovery),
alternatives?: (
failure: Extract<ToolResultEncoding, { readonly ok: false }>,
budgetBytes: number,
@@ -653,14 +670,12 @@ export class ToolResultDelivery {
? { _meta: TARGET_CONTENT_RESULT_META }
: {}),
};
const resolvedRecovery =
typeof recovery === "function" ? recovery() : recovery;
const nextStep = overflowNextStep(value, contract, resolvedRecovery);
const overflow = typeof recovery === "function" ? recovery() : recovery;
const projected = mcpResponseOverflowProjection({
completed: true,
constraint: encoded.constraint,
effectiveResponseBytes: this.maximumResponseBytes,
nextStep: nextStep.text,
nextStep: overflowNextStep(overflow, contract),
});
return this.toErrorToolResult(
new AnalysisResourceConstraintError(
@@ -675,10 +690,10 @@ export class ToolResultDelivery {
response_bytes_at_least: encoded.bytesAtLeast,
response_code_units_at_least: encoded.codeUnitsAtLeast,
constraint: encoded.constraint,
...resolvedRecovery,
...(nextStep.operation === undefined
...overflow.facts,
...(overflow.next === undefined
? {}
: { next_operation: nextStep.operation }),
: { next_operation: overflow.next.operation }),
},
{ remediationAction: projected.remediationAction },
),
@@ -713,7 +728,7 @@ const overBudgetSummary = (
if (evidence.operation === INSPECT_ANALYSIS_VIEW_OPERATION) return undefined;
// Only a tool with a detail selector is budgeted: its caller can always
// request complete delivery with detail complete.
if (!AGENT_BUDGET_OPERATION_NAMES.has(contract.name)) return undefined;
if (!isAgentBudgetOperation(contract.name)) return undefined;
const selection = currentMcpToolRequest()?.deliverySelection;
if (selection === undefined) return undefined;
const budget = currentAgentResultBudget(limits.agentBudgetSeed);
@@ -749,47 +764,9 @@ const overBudgetSummary = (
};
};
const agentBudgetDeliveryBlock = (delivery: AgentBudgetDelivery) => ({
type: "text" as const,
text: JSON.stringify({ delivery }),
});
/**
* Upper bound on the wire bytes the delivery facts add: their text block
* with its separator, and their `_meta` member with its separator.
*/
export const agentBudgetDeliveryBytes = (
delivery: AgentBudgetDelivery,
link?: ResourceLink,
): number =>
Buffer.byteLength(JSON.stringify(agentBudgetDeliveryBlock(delivery))) +
1 +
Buffer.byteLength(
JSON.stringify({ [AGENT_BUDGET_DELIVERY_META]: delivery }),
) +
1 +
(link === undefined ? 0 : Buffer.byteLength(JSON.stringify(link)) + 1);
/**
* Carry the delivery facts beside the summary record: a second text block
* the model reads, and `_meta` for clients that read structured metadata.
* A `resource_link` to the complete record follows, for clients that read
* resources; the cursor in the delivery facts stays the recovery every
* client can follow. The structured content stays the summary, unchanged.
*/
const withAgentBudgetDelivery = (
result: CallToolResult,
delivery: AgentBudgetDelivery,
link: ResourceLink | undefined,
): CallToolResult => ({
...result,
content: [
...result.content,
agentBudgetDeliveryBlock(delivery),
...(link === undefined ? [] : [link]),
],
_meta: { ...result._meta, [AGENT_BUDGET_DELIVERY_META]: delivery },
});
/** Wire bytes one more content block adds, with its array separator. */
const contentBlockBytes = (block: ResourceLink): number =>
Buffer.byteLength(JSON.stringify(block)) + 1;
/** A failure whose over-budget partial observation its summary replaced. */
interface BudgetedPartialObservation {
+19 -28
View File
@@ -30,6 +30,7 @@ import { err, ok, type Result } from "../domain/result.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { ToolResultEncoding } from "./toolResultEncoding.js";
import type { OverflowRecovery } from "./ToolResultDelivery.js";
import { logToolExecution } from "./toolLogging.js";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
@@ -217,17 +218,6 @@ export interface ValueToolRequest {
readonly context: ServerContext;
}
/**
* A value that commits a record, with the receipt an overflowing response
* names so the caller still learns what was committed.
*/
export class CommittedValue {
constructor(
readonly value: JsonValue,
readonly receipt: Readonly<Record<string, JsonValue>>,
) {}
}
/**
* Smaller forms of a value, offered in order when the complete value does not
* fit the response budget. Each keeps the contract's result shape.
@@ -237,11 +227,19 @@ export type ValueAlternatives = (
budgetBytes: number,
) => Iterable<JsonValue>;
/** A value delivered complete when it fits, or as its first fitting alternative. */
export class ReducibleValue {
/**
* A value with the delivery facts only its producer knows: what a caller can
* do when the value does not fit one response (a committed record's receipt,
* say), and smaller forms of the value to deliver first, in order, each in
* the contract's result shape.
*/
export class DeclaredValue {
constructor(
readonly value: JsonValue,
readonly alternatives: ValueAlternatives,
readonly declared: {
readonly overflow?: OverflowRecovery;
readonly alternatives?: ValueAlternatives;
},
) {}
}
@@ -269,7 +267,7 @@ export class DetailedFailure {
/** What a value workflow returns. */
export type ValueOutcome = Result<
JsonValue | CommittedValue | ReducibleValue | ForwardedValue,
JsonValue | DeclaredValue | ForwardedValue,
AnalysisError | DetailedFailure
>;
@@ -322,26 +320,19 @@ export const createValueToolHandler =
recordEvidence,
);
const { value } = result;
return value instanceof CommittedValue
return value instanceof DeclaredValue
? server.delivery.toCallToolResult(
ok(value.value),
contract,
value.receipt,
value.declared,
)
: value instanceof ReducibleValue
? server.delivery.toCallToolResult(
: value instanceof ForwardedValue
? server.delivery.toForwardedToolResult(
ok(value.value),
contract,
{},
value.alternatives,
value.content,
)
: value instanceof ForwardedValue
? server.delivery.toForwardedToolResult(
ok(value.value),
contract,
value.content,
)
: server.delivery.toCallToolResult(ok(value), contract);
: server.delivery.toCallToolResult(ok(value), contract);
},
);
+13 -4
View File
@@ -97,7 +97,7 @@ import type { ConfigurationError } from "../domain/configurationErrors.js";
import type { WebRuntimeService } from "../application/WebRuntimeService.js";
import { exportWebScriptsValidated } from "../application/WebScriptExportService.js";
import type { ArtifactResourceScope } from "../resources/index.js";
import { DetailedFailure, ReducibleValue } from "./contractToolHandler.js";
import { DeclaredValue, DetailedFailure } from "./contractToolHandler.js";
import type { DesktopBuildToolComputers } from "./desktopBuildDelivery.js";
import { bindDesktopBuildTools } from "./desktopBuildToolBindings.js";
import {
@@ -641,9 +641,18 @@ const SERVICE_TOOL_BINDINGS = {
const context = inspected.value;
// An oversized context drops its largest Evidence facets first.
return ok(
new ReducibleValue(context, (failure, budgetBytes) =>
omitContextEvidenceForDelivery(context, failure, budgetBytes),
),
new DeclaredValue(context, {
alternatives: (failure, budgetBytes) =>
omitContextEvidenceForDelivery(context, failure, budgetBytes),
overflow: {
kind: "retained",
next: {
operation: "get_evidence_bundle",
guidance:
"Call get_evidence_bundle with detail summary to discover retained facet observations, then export_evidence_bundle to inspect complete records. Some facets may not have been retained; a new analysis can differ.",
},
},
}),
);
},
},
+90 -21
View File
@@ -63,6 +63,13 @@ import {
} from "../application/EvidenceBundleFiles.js";
import { inspectEvidenceBundle } from "../application/investigation/InspectEvidenceBundle.js";
import { toolContract } from "../contracts/toolContracts.js";
import {
MCP_TRANSPORT_EVIDENCE_DISCOVERY,
MCP_TRANSPORT_EVIDENCE_LINKS,
MCP_TRANSPORT_EVIDENCE_RECORDS,
MCP_TRANSPORT_EVIDENCE_SUMMARY,
} from "../domain/analysisErrorPresentation.js";
import { isRecord } from "../kernel/isRecord.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { cancelledBy } from "../domain/analysisErrorCore.js";
import type { AnalysisViewRequest } from "../domain/analysisView/analysisViewRequest.js";
@@ -70,7 +77,8 @@ import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"
import type { ResidualUnknown } from "../domain/residualUnknown.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../resources/index.js";
import { CommittedValue } from "./contractToolHandler.js";
import { DeclaredValue } from "./contractToolHandler.js";
import type { OverflowRecovery } from "./ToolResultDelivery.js";
import type { ContractToolBindings } from "./contractToolBindings.js";
/**
@@ -99,23 +107,69 @@ export interface ApplicationWorkflowToolOptions {
*/
const committedUnknown = (
result: Result<ResidualUnknown, AnalysisError>,
): Result<CommittedValue, AnalysisError> =>
): Result<DeclaredValue, AnalysisError> =>
result.ok
? ok(
new CommittedValue(result.value, {
committed_unknown: {
unknown_id: result.value.unknown_id,
revision: result.value.revision,
mutation_evidence_ids: result.value.mutation_evidence_ids,
},
evidence_reference: {
kind: "retained-evidence",
evidence_id: result.value.mutation_evidence_ids[0]!,
new DeclaredValue(result.value, {
overflow: {
kind: "committed",
next: {
operation: "export_evidence_bundle",
guidance:
"Export this session with export_evidence_bundle to inspect the committed unknown and its mutation Evidence; an individual unknown may be too large for a list_unknowns page.",
},
facts: {
committed_unknown: {
unknown_id: result.value.unknown_id,
revision: result.value.revision,
mutation_evidence_ids: result.value.mutation_evidence_ids,
},
evidence_reference: {
kind: "retained-evidence",
evidence_id: result.value.mutation_evidence_ids[0]!,
},
},
},
}),
)
: result;
/**
* An overflowing `list_unknowns` page: a smaller limit splits a page of more
* than one row; one row that cannot fit needs the session export.
*/
const unknownPageOverflow = (rows: number): OverflowRecovery => ({
kind: "retained",
next:
rows <= 1
? {
operation: "export_evidence_bundle",
guidance:
"One unknown does not fit a list_unknowns response on this connection, so a smaller limit cannot help. Export the session with export_evidence_bundle to recover it.",
}
: {
operation: "list_unknowns",
guidance:
"Call list_unknowns on this same connection with the same filters and offset, using a smaller limit, then follow next_offset. If a single unknown cannot fit, export the session with export_evidence_bundle to recover it.",
},
});
/** An overflowing `get_evidence_bundle` projection names its own smaller read. */
const evidenceBundleOverflow = (projection: unknown): OverflowRecovery => ({
kind: "retained",
next: {
operation: "get_evidence_bundle",
guidance:
projection === "evidence-bundle-summary"
? MCP_TRANSPORT_EVIDENCE_SUMMARY
: projection === "evidence-link-inspection"
? MCP_TRANSPORT_EVIDENCE_LINKS
: projection === "evidence-record-selection"
? MCP_TRANSPORT_EVIDENCE_RECORDS
: MCP_TRANSPORT_EVIDENCE_DISCOVERY,
},
});
/** A requested view, or the summary view a `detail: "summary"` request selects. */
const requestedView = (input: {
readonly detail?: "complete" | "summary";
@@ -601,21 +655,36 @@ export const bindSessionRecordTools = ({
get_evidence_bundle: {
admission: "sdk",
admitted: true,
value: async (input) => inspectEvidenceBundle(session, input),
value: async (input) => {
const inspected = inspectEvidenceBundle(session, input);
return inspected.ok
? ok(
new DeclaredValue(inspected.value, {
overflow: evidenceBundleOverflow(
isRecord(inspected.value) ? inspected.value.kind : undefined,
),
}),
)
: inspected;
},
},
list_unknowns: {
admission: "sdk",
admitted: true,
value: async (input) =>
ok(
session.listUnknownsPage({
...(input.status === undefined ? {} : { status: input.status }),
...(input.severity === undefined ? {} : { severity: input.severity }),
...(input.domain === undefined ? {} : { domain: input.domain }),
offset: input.offset,
...(input.limit === undefined ? {} : { limit: input.limit }),
value: async (input) => {
const page = session.listUnknownsPage({
...(input.status === undefined ? {} : { status: input.status }),
...(input.severity === undefined ? {} : { severity: input.severity }),
...(input.domain === undefined ? {} : { domain: input.domain }),
offset: input.offset,
...(input.limit === undefined ? {} : { limit: input.limit }),
});
return ok(
new DeclaredValue(page, {
overflow: unknownPageOverflow(page.items.length),
}),
),
);
},
},
record_unknown: {
admission: "sdk",
+49 -22
View File
@@ -13,7 +13,6 @@ import {
AGENT_RESULT_BUDGET_SETTING,
EVIDENCE_OUTPUT_PLACEHOLDER,
} from "../../../src/domain/agentResultBudget.js";
import { AGENT_BUDGET_DELIVERY_META } from "../../../src/server/ToolResultDelivery.js";
import { parseEvidence, type Evidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { publishCliAnalysisEvidence } from "../../../src/cli/analysisEvidenceDelivery.js";
@@ -22,17 +21,21 @@ import { createByteEntropyService } from "../../../src/composition/binaryDiagnos
import { inspectAnalysisView } from "../../../src/application/analysisView/AnalysisViewService.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
import { clientProjections } from "../../fixtures/mcpClientProjection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { connectBudgetedLayout } from "./budgetedLayout.js";
const connect = async () => {
const connect = async (overrides: Record<string, string> = {}) => {
const session = createTestBinarySession(() => {
throw new Error("Entropy inspection must not start a deep provider");
});
// Exercise the default budget, not the complete-delivery seed the test
// environment gives spawned processes.
const { REA_AGENT_RESULT_BUDGET_BYTES: _seed, ...environment } = process.env;
const server = createServer({ kind: "session", session }, { environment });
const server = createServer(
{ kind: "session", session },
{ environment: { ...environment, ...overrides } },
);
const client = new Client(
{ name: "agent-result-budget", version: "1" },
{ jsonSchemaValidator: createMcpSchemaValidation() },
@@ -88,24 +91,31 @@ type Link = {
};
/**
* The delivery facts block that follows the summary's own text block, and
* the resource link to the complete record after it.
* The summary and its delivery facts as the model receives them, whether
* its client forwards only `structuredContent` (Codex, VS Code) or only the
* text blocks (Gemini CLI, LangChain), and the resource link to the
* complete record for clients that read resources.
*/
const deliveryOf = (result: {
readonly content?: unknown;
readonly structuredContent?: unknown;
readonly _meta?: Record<string, unknown> | undefined;
}): Delivery & { readonly link: Link } => {
const blocks = result.content as { type: string; text: string }[];
expect(blocks.map(({ type }) => type)).toEqual([
"text",
"text",
"resource_link",
]);
const { delivery } = JSON.parse(blocks[1]!.text) as {
}): Delivery & { readonly summary: Evidence; readonly link: Link } => {
const blocks = result.content as { type: string }[];
expect(blocks.map(({ type }) => type)).toEqual(["text", "resource_link"]);
const { summary, delivery } = clientProjections(result) as {
readonly summary: unknown;
readonly delivery: Delivery;
};
expect(result._meta?.[AGENT_BUDGET_DELIVERY_META]).toEqual(delivery);
return { ...delivery, link: blocks[2] as unknown as Link };
// _meta reaches no model, so it carries no delivery facts of its own.
expect(Object.keys(result._meta ?? {})).not.toContain(
"rea/agent-budget-delivery",
);
return {
...delivery,
summary: parseEvidence(summary),
link: blocks[1] as unknown as Link,
};
};
type EvidenceJsonPage = {
@@ -153,7 +163,8 @@ it("delivers a retained summary with a cursor when complete Evidence exceeds the
expect(textBytes(delivered.content)).toBeLessThanOrEqual(
DEFAULT_AGENT_RESULT_BUDGET_BYTES,
);
const summary = parseEvidence(delivered.structuredContent);
const delivery = deliveryOf(delivered);
const { summary } = delivery;
expect(summary.operation).toBe("inspect_analysis_view");
const view = summary.normalized_result as {
readonly kind: string;
@@ -166,7 +177,6 @@ it("delivers a retained summary with a cursor when complete Evidence exceeds the
parent_operation: "inspect_byte_entropy",
summary: { block_count: 4096 },
});
const delivery = deliveryOf(delivered);
expect(delivery).toMatchObject({
kind: "agent-budget-summary",
budget_bytes: DEFAULT_AGENT_RESULT_BUDGET_BYTES,
@@ -245,6 +255,22 @@ it("delivers a retained summary with a cursor when complete Evidence exceeds the
expect(Buffer.byteLength(contents!.text)).toBe(delivery.link.size);
});
it("advertises the summary result in the compact output schema the client validates", async () => {
const client = await connect({ REA_MCP_OUTPUT_SCHEMA_PROFILE: "compact" });
// Listing caches each advertised output schema; the client then validates
// every structured result against it.
const { tools } = await client.listTools();
expect(
tools.find(({ name }) => name === "inspect_byte_entropy")?.outputSchema,
).toMatchObject({ type: "object" });
const delivered = await client.callTool({
name: "inspect_byte_entropy",
arguments: await entropyTarget(1024 * 1024),
});
expect(delivered.isError).not.toBe(true);
expect(deliveryOf(delivered).summary.operation).toBe("inspect_analysis_view");
});
it("serves retained Evidence by template only, and refuses an ID this session does not retain", async () => {
const client = await connect();
expect(client.getServerCapabilities()?.resources).toBeDefined();
@@ -368,10 +394,9 @@ it("budgets tools whose SDK schema defers validation to the application", async
arguments: target,
});
expect(budgeted.isError).not.toBe(true);
expect(parseEvidence(budgeted.structuredContent).operation).toBe(
"inspect_analysis_view",
);
expect(deliveryOf(budgeted)).toMatchObject({
const delivery = deliveryOf(budgeted);
expect(delivery.summary.operation).toBe("inspect_analysis_view");
expect(delivery).toMatchObject({
budget_bytes: MINIMUM_AGENT_RESULT_BUDGET_BYTES,
evidence_id: parseEvidence(complete.structuredContent).evidence_id,
});
@@ -486,7 +511,9 @@ it("delivers a target failure unchanged by the delivery budget", async () => {
error: { code: "unsupported_target" },
});
// The failure keeps its own projection: no summary, no delivery facts.
expect(omitted._meta?.[AGENT_BUDGET_DELIVERY_META]).toBeUndefined();
expect(JSON.parse(first!.text).error.details).not.toHaveProperty(
"partial_observation_delivery",
);
expect(omitted).toEqual(complete);
});
@@ -1,4 +1,5 @@
import { readFile } from "node:fs/promises";
import { receivedEvidence } from "../../fixtures/mcpClientProjection.js";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
@@ -36,7 +37,7 @@ const connect = async () => {
const evidence = async (name: string, args: Record<string, unknown>) => {
const reply = await call(name, args);
expect(reply.isError, JSON.stringify(reply.content)).not.toBe(true);
return { reply, evidence: parseEvidence(reply.structuredContent) };
return { reply, evidence: parseEvidence(receivedEvidence(reply)) };
};
return { root, evidence };
};
@@ -11,7 +11,7 @@ import {
DEFAULT_AGENT_RESULT_BUDGET_BYTES,
MINIMUM_AGENT_RESULT_BUDGET_BYTES,
} from "../../../src/domain/analysisResourceLimits.js";
import { AGENT_BUDGET_DELIVERY_META } from "../../../src/server/ToolResultDelivery.js";
import { clientProjections } from "../../fixtures/mcpClientProjection.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
@@ -516,9 +516,12 @@ describe("inspect_firmware_vector_table CLI and MCP parity", () => {
),
});
expect(summarized.isError).not.toBe(true);
const delivery = summarized._meta?.[AGENT_BUDGET_DELIVERY_META] as {
readonly budget_bytes: number;
readonly complete_bytes: number;
const { summary, delivery } = clientProjections(summarized) as {
readonly summary: unknown;
readonly delivery: {
readonly budget_bytes: number;
readonly complete_bytes: number;
};
};
expect(delivery.budget_bytes).toBe(MINIMUM_AGENT_RESULT_BUDGET_BYTES);
expect(delivery.complete_bytes).toBeGreaterThan(
@@ -527,7 +530,7 @@ describe("inspect_firmware_vector_table CLI and MCP parity", () => {
expect(delivery.complete_bytes).toBeLessThanOrEqual(
DEFAULT_AGENT_RESULT_BUDGET_BYTES,
);
expect(summarized.structuredContent).toMatchObject({
expect(summary).toMatchObject({
operation: "inspect_analysis_view",
normalized_result: {
kind: "summary",
@@ -538,7 +541,7 @@ describe("inspect_firmware_vector_table CLI and MCP parity", () => {
const complete = await inspectWith(defaults);
expect(complete.isError).not.toBe(true);
expect(complete._meta?.[AGENT_BUDGET_DELIVERY_META]).toBeUndefined();
expect(complete.structuredContent).not.toHaveProperty("delivery");
expect(complete.structuredContent).toMatchObject({
operation: "inspect_firmware_vector_table",
});
+61 -44
View File
@@ -11,14 +11,15 @@ import { describe, expect, it } from "vitest";
import { z } from "zod";
import { createAnalysisExecution } from "../../../src/ports/AnalysisProvider.js";
import { MCP_TRANSPORT_EVIDENCE_SUMMARY } from "../../../src/domain/analysisErrorPresentation.js";
import { MCP_TRANSPORT_EVIDENCE_RECORDS } from "../../../src/domain/analysisErrorPresentation.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../../src/domain/evidence.js";
import { analysisErrorProjectionSchema } from "../../../src/domain/analysisErrorProjectionSchema.js";
import {
jsonObjectSchema,
type JsonValue,
@@ -166,49 +167,65 @@ describe("MCP response budget recovery", () => {
);
});
it("keeps summary discovery when a complete evidence bundle exceeds the budget", () => {
const tight = createToolResultDelivery(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(
stdioResponseBudgetRecovery(
2048,
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
),
);
});
it("offers metadata pagination and export when the evidence summary exceeds the budget", () => {
const tight = createToolResultDelivery(2048);
const delivered = tight.toCallToolResult(
ok({
kind: "evidence-bundle-summary",
records: "x".repeat(1500),
}),
toolContract("get_evidence_bundle"),
);
expect(delivered.isError).toBe(true);
const { error } = z
.object({ error: analysisErrorProjectionSchema })
.parse(delivered.structuredContent);
const action = error.remediation.action;
expect(error.details).toMatchObject({
reported_limits: { next_operation: "get_evidence_bundle" },
it("names the smaller read each get_evidence_bundle projection declares, never the CLI", async () => {
const session = createTestBinarySession(() => {
throw new Error("Bundle inspection must not start a provider");
});
expect(action).toContain(MCP_TRANSPORT_EVIDENCE_SUMMARY);
expect(action).toContain("export_evidence_bundle");
expect(action).toContain("caller-selected path");
expect(action).toContain("or use complete CLI JSON output");
const server = createServer(
{ kind: "session", session },
{ delivery: createToolResultDelivery(8 * 1024) },
);
const client = new Client(
{ name: "bundle-overflow", version: "1" },
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
try {
for (let index = 0; index < 5; index += 1) {
const recorded = await client.callTool({
name: "record_unknown",
arguments: {
question: `${String(index)}-${"q".repeat(1800)}`,
severity: "medium",
domain: "bundle-overflow",
required_authority: null,
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
},
});
expect(recorded.isError).not.toBe(true);
}
const overflowed = async (detail: string) =>
parseMcpToolError(
await client.callTool({
name: "get_evidence_bundle",
arguments: { detail },
}),
).error;
const records = await overflowed("records");
expect(records.details).toMatchObject({
reported_limits: { next_operation: "get_evidence_bundle" },
});
expect(records.remediation.action).toContain(
MCP_TRANSPORT_EVIDENCE_RECORDS,
);
expect(records.remediation.action).toContain(
stdioResponseBudgetRecovery(
8 * 1024,
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
),
);
// A session's records do not exist in a new CLI process.
expect(records.remediation.action).not.toContain("CLI");
} finally {
await Promise.all([client.close(), server.close(), session.close()]);
}
});
});
@@ -1,4 +1,5 @@
import { join } from "node:path";
import { budgetedSummaryOf } from "../../fixtures/mcpClientProjection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { unknownTarget } from "../../../src/domain/targetIdentity.js";
@@ -359,7 +360,7 @@ it("summarizes an inventory above the inline bound when detail is omitted, and r
arguments: {},
});
if (omitted.isError) throw new Error(JSON.stringify(omitted));
const sized = parseEvidence(omitted.structuredContent);
const sized = parseEvidence(budgetedSummaryOf(omitted));
expect(sized).toMatchObject({
operation: "inspect_analysis_view",
normalized_result: { kind: "summary", summary: { row_count: 1000 } },
@@ -434,7 +435,7 @@ it("inlines a small inventory, summarizes a large one, and keeps it complete whe
arguments: {},
});
if (large.isError) throw new Error(JSON.stringify(large));
const summary = parseEvidence(large.structuredContent);
const summary = parseEvidence(budgetedSummaryOf(large));
expect(summary).toMatchObject({
operation: "inspect_analysis_view",
normalized_result: { kind: "summary", summary: { row_count: 600 } },
@@ -533,7 +534,7 @@ it("inlines small xrefs, summarizes large ones and pages them through native-obs
arguments: { address: "0x400000" },
});
if (large.isError) throw new Error(JSON.stringify(large));
const summary = parseEvidence(large.structuredContent);
const summary = parseEvidence(budgetedSummaryOf(large));
expect(summary).toMatchObject({
operation: "inspect_analysis_view",
normalized_result: { kind: "summary", parent_operation: "xrefs" },
+2 -1
View File
@@ -1,4 +1,5 @@
import { nugetNupkgSchema } from "../../../src/domain/nuget/nupkg.js";
import { budgetedSummaryOf } from "../../fixtures/mcpClientProjection.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { ZipReader } from "@zip.js/zip.js";
@@ -192,7 +193,7 @@ mcpTest(
true,
);
const summary = nupkgContract.outputSchema.parse(
summarized.structuredContent,
budgetedSummaryOf(summarized),
);
expect(summary).toMatchObject({
operation: "inspect_analysis_view",
+2 -1
View File
@@ -1,3 +1,4 @@
import { budgetedSummaryOf } from "../../fixtures/mcpClientProjection.js";
import {
OCI_IMAGE_LAYOUT_BUDGETS,
ociImageLayoutSchema,
@@ -139,7 +140,7 @@ mcpTest(
true,
);
const summary = layoutContract.outputSchema.parse(
summarized.structuredContent,
budgetedSummaryOf(summarized),
);
expect(summary).toMatchObject({
operation: "inspect_analysis_view",
+50 -56
View File
@@ -22,6 +22,7 @@ import { HopperProcessError } from "../../../src/hopper/HopperErrors.js";
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import type { OverflowRecovery } from "../../../src/server/ToolResultDelivery.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import {
accountFullyObservedProcessCapture,
@@ -440,62 +441,55 @@ describe("untrusted provenance on failed tool results", () => {
});
describe("response-budget recovery routes", () => {
it.each([
[
"retained Evidence",
"procedure_pseudo_code",
{},
{
const overflowed = (
tool: Parameters<typeof toolContract>[0],
overflow?: OverflowRecovery,
) => {
const result = createToolResultDelivery(4096).toCallToolResult(
{ ok: true, value: { text: "x".repeat(8192) } },
toolContract(tool),
overflow === undefined ? {} : { overflow },
);
const { details, remediation } = z
.object({
error: z.object({
details: z.object({
reported_limits: z.record(z.string(), z.unknown()),
}),
remediation: z.object({ action: z.string() }),
}),
})
.parse(result.structuredContent).error;
return { limits: details.reported_limits, action: remediation.action };
};
it("names the producer's declared next operation and its identities", () => {
const { limits, action } = overflowed("get_evidence_bundle", {
kind: "retained",
next: { operation: "get_evidence_bundle", guidance: "Page it." },
facts: {
evidence_reference: { kind: "retained-evidence", evidence_id: "e" },
},
"export_evidence_bundle",
],
[
"view continuation",
"list_strings",
{},
{ continuation: { name: "inspect_analysis_view", arguments: {} } },
"inspect_analysis_view",
],
[
"address context",
"inspect_address_context",
{},
{},
"get_evidence_bundle",
],
[
"bundle summary",
"get_evidence_bundle",
{ kind: "evidence-bundle-summary" },
{},
"get_evidence_bundle",
],
[
"bundle records",
"get_evidence_bundle",
{ kind: "evidence-record-selection" },
{},
"get_evidence_bundle",
],
] as const)(
"names the %s overflow recovery's first operation",
(_label, tool, shape, recovery, operation) => {
const result = createToolResultDelivery(4096).toCallToolResult(
{ ok: true, value: { ...shape, text: "x".repeat(8192) } },
toolContract(tool),
recovery,
);
const limits = z
.object({
error: z.object({
details: z.object({
reported_limits: z.record(z.string(), z.unknown()),
}),
}),
})
.parse(result.structuredContent).error.details.reported_limits;
expect(limits.next_operation).toBe(operation);
},
);
});
expect(limits).toMatchObject({
next_operation: "get_evidence_bundle",
evidence_reference: { kind: "retained-evidence", evidence_id: "e" },
});
expect(action).toContain("Page it.");
});
it("names the CLI command only for a one-shot contract that reads no session", () => {
const stateless = overflowed("inspect_byte_entropy");
expect(stateless.limits).not.toHaveProperty("next_operation");
expect(stateless.action).toContain("`rea inspect-byte-entropy`");
// A session read and a committed mutation have no CLI equivalent.
expect(overflowed("list_unknowns").action).not.toContain("CLI");
const committed = overflowed("record_unknown");
expect(committed.action).not.toContain("CLI");
expect(committed.action).toContain("Do not repeat the completed call");
// A CLI contract that runs on the session's active target does not either.
expect(overflowed("inspect_native_instruction").action).not.toContain(
"CLI",
);
});
});
+3 -2
View File
@@ -1,4 +1,5 @@
import { vsixPackageSchema } from "../../../src/domain/vsix/vsixPackage.js";
import { budgetedSummaryOf } from "../../fixtures/mcpClientProjection.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { ZipReader } from "@zip.js/zip.js";
@@ -93,7 +94,7 @@ mcpTest(
arguments: { path },
});
const summary = vsixContract.outputSchema.parse(
summarized.structuredContent,
budgetedSummaryOf(summarized),
);
expect(summary.operation).toBe("inspect_analysis_view");
const view = summary.normalized_result;
@@ -184,7 +185,7 @@ mcpTest(
Buffer.byteLength(JSON.stringify(summarized.structuredContent), "utf8"),
).toBeLessThan(32 * 1024);
const summary = vsixContract.outputSchema.parse(
summarized.structuredContent,
budgetedSummaryOf(summarized),
);
expect(summary.operation).toBe("inspect_analysis_view");
const view = summary.normalized_result;
+2 -1
View File
@@ -1,4 +1,5 @@
import { expect, it, onTestFinished } from "vitest";
import { receivedEvidence } from "../../fixtures/mcpClientProjection.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
@@ -137,7 +138,7 @@ it("pages a captured script's metadata without its text, and the text separately
const call = async (name: string, args: Record<string, unknown>) => {
const reply = await client.callTool({ name, arguments: args });
expect(reply.isError, JSON.stringify(reply.content)).not.toBe(true);
return parseEvidence(reply.structuredContent);
return parseEvidence(receivedEvidence(reply));
};
const summary = await call("inspect_web_page", {
cdp_endpoint: browser.endpoint,
+79
View File
@@ -0,0 +1,79 @@
import { expect } from "vitest";
/** A tool result as an MCP client receives it. */
interface ReceivedToolResult {
readonly content?: unknown;
readonly structuredContent?: unknown;
}
const textBlocks = (result: ReceivedToolResult): string[] =>
(Array.isArray(result.content) ? result.content : []).flatMap(
(block: { readonly type?: unknown; readonly text?: unknown }) =>
block.type === "text" && typeof block.text === "string"
? [block.text]
: [],
);
/**
* What a client that forwards only `structuredContent` gives the model, as
* Codex and VS Code do when it is present: that value, with every text block
* dropped. `_meta` reaches no model.
*/
export const structuredOnlyProjection = (
result: ReceivedToolResult,
): unknown => {
if (result.structuredContent !== undefined) return result.structuredContent;
const [text] = textBlocks(result);
if (text === undefined) throw new Error("Tool result carries no text");
return JSON.parse(text);
};
/**
* What a client that forwards only `content` gives the model, as Gemini CLI
* and the LangChain MCP adapter do: the text blocks, never
* `structuredContent` or `_meta`. REA sends one text block, the
* serialization of its structured result.
*/
export const textOnlyProjection = (result: ReceivedToolResult): unknown => {
const blocks = textBlocks(result);
expect(blocks).toHaveLength(1);
return JSON.parse(blocks[0]!);
};
/**
* Both projections, which must agree: a fact the agent needs reaches the
* model whichever channel its client forwards.
*/
export const clientProjections = (result: ReceivedToolResult): unknown => {
const structured = structuredOnlyProjection(result);
expect(textOnlyProjection(result)).toEqual(structured);
return structured;
};
/**
* The summary record that replaced complete Evidence over the agent result
* budget, read as the model receives it in either projection, after
* checking that its delivery facts arrived with it.
*/
export const budgetedSummaryOf = (result: ReceivedToolResult): unknown => {
const { summary, delivery } = clientProjections(result) as {
readonly summary?: unknown;
readonly delivery?: unknown;
};
expect(delivery).toMatchObject({ kind: "agent-budget-summary" });
return summary;
};
/**
* The Evidence record a successful result delivers as the model receives
* it: complete or explicitly selected Evidence as is, or the summary that
* replaced it over the agent result budget.
*/
export const receivedEvidence = (result: ReceivedToolResult): unknown => {
const projected = clientProjections(result);
return typeof projected === "object" &&
projected !== null &&
"delivery" in projected
? budgetedSummaryOf(result)
: projected;
};
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Client } from "@modelcontextprotocol/client";
import { receivedEvidence } from "../../fixtures/mcpClientProjection.js";
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { withCanonicalOutputSchema } from "../../fixtures/canonicalOutputSchema.js";
@@ -17,7 +18,7 @@ export const listedEvidenceCaller = async (client: Client) => {
const call = async (name: string, args: Record<string, unknown>) => {
const result = await reply(name, args);
expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
return parseEvidence(result.structuredContent);
return parseEvidence(receivedEvidence(result));
};
return { call, reply };
};