Files
rea/src/contracts/compactInputSchema.ts
T
morlutoandCursor Agent d72dc9d979 perf(contracts): prune only over-depth schema branches instead of reducing whole schemas (#14107)
* perf(contracts): prune only over-depth schema branches instead of reducing whole schemas

A schema whose inlined form exceeded the depth-10 advertised limit fell back to reduceToShallowProperties for the entire tool, erasing enums and nested validation on all root properties. pruneSchemaBeyondDepth now replaces only sub-schemas past the prune depth with type-preserving placeholders (every replacement widens acceptance, so canonical server-side validation is unchanged), and both input and output compaction keep the pruned form as inline when it fits bytes, depth and dialect checks. Two compactInputSchema tests that pinned depth-forces-reduction now pin the pruned-inline contract with the same Ajv/dialect safety assertions.

Refs #13302. Verified: compactInputSchema, compactOutputSchema, toolSchemaMetadata, advertisedInputExamples (59 tests), check:fast, docs:check.

* docs(contracts): refresh advertised schema summary for pruned-inline compaction

Pruned-inline schemas retain patterns (digest, Evidence id and text patterns) that whole-schema reduction dropped on 13 tools; regenerate the committed catalog summary with npm run verify:advertised-schemas -- --update-summary and re-verify clean.

* fix(contracts): make deep-schema pruning widening-safe

Walk schema positions instead of raw JSON, preserve declared integer types, keep branches that fit, return no pruned schema under not/oneOf where widening can reject valid values, and recheck output byte budgets. Add regression coverage for closed objects, unsafe combinators, fitting enums, and nullable integers; refresh advertised summaries.

* fix(contracts): keep untyped deep schemas unconstrained when pruned

Inferring object from properties or array from items narrows an untyped schema, which accepts every JSON value; the placeholder is now always unconstrained when no type is declared. Add an Ajv regression accepting null and nested values through a pruned untyped branch.

* test(contracts): assert pruned untyped schemas at depth 8

The regression accepted values that never reached the replaced node, so
it stayed green for an object placeholder and did not distinguish
branch pruning from whole-schema reduction. Assert the empty schema at
depth 8 and accept null there.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-11-23 12:42:55 -05:00

152 lines
5.6 KiB
TypeScript

import {
ADVERTISED_INPUT_SCHEMA_MAX_BYTES,
hasAdvertisedInputDialectViolation,
} from "./advertisedDialect.js";
import { projectToAdvertisedDialect } from "./advertisedDialectProjection.js";
import {
COMPACT_SCHEMA_MAX_DEPTH,
inlineWithinBudget,
isSchemaObject,
pruneSchemaBeyondDepth,
reduceToShallowProperties,
schemaDepth,
serializedBytes,
} from "./compactJsonSchema.js";
import { JsonSchemaReferences } from "./jsonSchemaReferences.js";
// The compact input presentation: every advertised input schema is
// self-contained (the dialect admits no `$ref` or `$defs`), inside the
// per-tool byte budget, and in the portable advertised dialect. Canonical
// server-side validation remains unchanged.
export type AdvertisedInputSchemaPresentation = "inline" | "reduced";
/** Budget selected by the caller for compact MCP input-schema presentation. */
export interface CompactInputSchemaPresentation {
readonly budgetBytes: number;
}
export interface CompactedInputSchema {
readonly schema: Record<string, unknown>;
readonly presentation: AdvertisedInputSchemaPresentation;
/** Input guidance the schema does not carry; it joins the tool description. */
readonly guidance: readonly string[];
}
const INPUT_REDUCED_ANNOTATION =
"Advertised in reduced form by the compact input schema profile; the server still validates complete canonical inputs.";
// `detail` selects between complete Evidence and a bounded summary. Without
// its guidance, callers default to complete replies that can exceed context.
const retainedRootPropertyDescriptions = ["detail"];
/** Restore the description of root properties whose choice bounds the reply. */
const retainRootPropertyGuidance = (
schema: Record<string, unknown>,
stripped: Record<string, unknown>,
): Record<string, unknown> => {
if (
!isSchemaObject(schema.properties) ||
!isSchemaObject(stripped.properties)
)
return stripped;
let properties: Record<string, unknown> | undefined;
for (const name of retainedRootPropertyDescriptions) {
const source = schema.properties[name];
const kept = (properties ?? stripped.properties)[name];
if (
isSchemaObject(source) &&
isSchemaObject(kept) &&
typeof source.description === "string"
) {
properties ??= { ...stripped.properties };
properties[name] = { ...kept, description: source.description };
}
}
return properties === undefined ? stripped : { ...stripped, properties };
};
/**
* Render an advertised input schema within a per-schema byte budget for
* providers that validate the literal serialized schema size. The complete
* validation structure is projected into the portable dialect when it fits;
* otherwise only root properties and their types remain.
*/
export const compactAdvertisedInputSchema = (
schema: Record<string, unknown>,
budgetBytes: number,
): CompactedInputSchema => {
const references = new JsonSchemaReferences(schema);
const expanded = inlineWithinBudget(schema, budgetBytes, {
stripAnnotations: true,
references,
});
const inline =
expanded === undefined
? undefined
: projectToAdvertisedDialect(
retainRootPropertyGuidance(schema, expanded),
);
if (
inline !== undefined &&
serializedBytes(inline.schema) <= budgetBytes &&
schemaDepth(inline.schema) <= COMPACT_SCHEMA_MAX_DEPTH &&
!hasAdvertisedInputDialectViolation(inline.schema, {
skipRootBounds: budgetBytes <= ADVERTISED_INPUT_SCHEMA_MAX_BYTES,
})
)
return { ...inline, presentation: "inline" };
if (inline !== undefined && serializedBytes(inline.schema) <= budgetBytes) {
// Only the branches past the depth limit are elided; the rest of the
// validation structure stays advertised instead of a whole reduction.
const pruned = pruneSchemaBeyondDepth(inline.schema);
if (
pruned !== undefined &&
serializedBytes(pruned) <= budgetBytes &&
schemaDepth(pruned) <= COMPACT_SCHEMA_MAX_DEPTH &&
!hasAdvertisedInputDialectViolation(pruned, {
skipRootBounds: budgetBytes <= ADVERTISED_INPUT_SCHEMA_MAX_BYTES,
})
)
return {
schema: pruned,
guidance: inline.guidance,
presentation: "inline",
};
}
const reduced = projectToAdvertisedDialect(
reduceToShallowProperties(schema, INPUT_REDUCED_ANNOTATION, references),
);
if (serializedBytes(reduced.schema) <= budgetBytes)
return { ...reduced, presentation: "reduced" };
// A future contract with an extreme root-property count still advertises
// an honest, budget-fitting shape instead of an oversized one.
return {
...projectToAdvertisedDialect(
reduceToShallowProperties({ type: "object" }, INPUT_REDUCED_ANNOTATION),
),
presentation: "reduced",
};
};
// Registration needs the guidance and the SDK later needs the schema; both
// read one projection of the same memoized canonical schema object.
const compacted = new WeakMap<object, Map<number, CompactedInputSchema>>();
/** The compact advertised input with its guidance; `advertisedTool.ts` composes the tool. */
export const presentAdvertisedInput = (
schema: Record<string, unknown>,
compactPresentation: CompactInputSchemaPresentation,
): Pick<CompactedInputSchema, "schema" | "guidance"> => {
const { budgetBytes } = compactPresentation;
let byBudget = compacted.get(schema);
if (byBudget === undefined) compacted.set(schema, (byBudget = new Map()));
let presented = byBudget.get(budgetBytes);
if (presented === undefined)
byBudget.set(
budgetBytes,
(presented = compactAdvertisedInputSchema(schema, budgetBytes)),
);
return presented;
};