Files
reverse-engineering-anything/src/contracts/compactInputSchema.ts
T
morluto d958391201 fix(mcp): serve refinement-only input rules agents need before the first call (#15437)
* fix(mcp): serve refinement-only input rules agents need before the first call

- UEFI paths use the shared absolute-path schema, so the served schema
  carries the absolute-path pattern instead of a refinement.
- Blank-text checks (guided workflow ids, prompt arguments, guidance
  queries, residual-unknown text) are a served `\S` pattern, not a trim
  refinement.
- Input groups name the selector values that open them, for example
  `operation=architectures` for inspect_with_objdump.
- inspect_native_data_type states its one-of rule in the tool description,
  from the same constant the refusal uses.
- The served-schema parity sweep credits a cross-field rule when the
  description states the refusal or the selecting input group, with
  controls, and drops the fixed refinement gaps.

Refs #15311

* fix(mcp): serve endpoint and literal rules on reduced schemas; state wider patterns

- A reduced schema over budget drops name-derived fallback descriptions
  before its scalar rules, so analyze_web_bundle keeps its bounds.
- Reduced root properties that are unions of literals serve their values
  as one enum (detail, format).
- CDP and Inspector endpoint schemas declare the explicit-port envelope
  that explicitEndpointAuthority reads, as their pattern.
- A pattern the portable grammar can only serve wider (`\S`, the adb
  serial) is also stated exactly in guidance.
- The parity sweep drops the endpoint and literal gaps; the generated
  property accepts the host-independent absolute-path envelope.

Refs #15311
2026-12-01 15:28:35 +00:00

238 lines
8.4 KiB
TypeScript

import {
ADVERTISED_INPUT_SCHEMA_MAX_BYTES,
hasAdvertisedInputDialectViolation,
} from "./advertisedDialect.js";
import {
defaultGuidance,
projectToAdvertisedDialect,
} from "./advertisedDialectProjection.js";
import {
COMPACT_SCHEMA_MAX_DEPTH,
inlineWithinBudget,
isSchemaObject,
pruneSchemaBeyondDepth,
reduceToShallowProperties,
resolveRootProperty,
schemaDepth,
serializedBytes,
} from "./compactJsonSchema.js";
import { JsonSchemaReferences } from "./jsonSchemaReferences.js";
import { fallbackPropertyDescription } from "./propertyFallbackDescriptions.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[];
}
/**
* Work bound on inlining `$ref` dependencies before projection, separate from
* the advertised budget because projection and depth pruning shrink the
* expansion. A schema that expands beyond it is advertised in reduced form.
*/
const INPUT_EXPANSION_MAX_BYTES = 13 * 1024;
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 };
};
const INPUT_PRUNED_GUIDANCE =
"Nested fields past the advertised schema depth are omitted; the server validates the complete input.";
/** The largest example a reduced or pruned schema states in guidance. */
const EXAMPLE_GUIDANCE_MAX_BYTES = 1024;
/**
* The smallest canonical example that fits the guidance budget, for a schema
* whose advertised structure omits fields an agent must otherwise discover by
* failing.
*/
const exampleGuidance = (
schema: Record<string, unknown>,
): readonly string[] => {
if (!Array.isArray(schema.examples)) return [];
// Measure the JSON text itself in UTF-8; serializing it again would count
// its escapes twice.
const [smallest] = schema.examples
.map((example) => JSON.stringify(example))
.filter((text): text is string => typeof text === "string")
.map((text) => ({ text, bytes: Buffer.byteLength(text, "utf8") }))
.sort((left, right) => left.bytes - right.bytes);
return smallest !== undefined && smallest.bytes <= EXAMPLE_GUIDANCE_MAX_BYTES
? [`Example arguments: ${smallest.text}`]
: [];
};
/** Whether a property's description is its own rather than a name fallback. */
const isAuthoredDescription = (name: string, property: unknown): boolean =>
!isSchemaObject(property) ||
property.description !== fallbackPropertyDescription(name, property);
/** Root defaults from the canonical schema, which compaction strips. */
const canonicalDefaultGuidance = (
schema: Record<string, unknown>,
references: JsonSchemaReferences,
): readonly string[] =>
defaultGuidance(schema, (property) =>
resolveRootProperty(property, references),
);
/**
* 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, INPUT_EXPANSION_MAX_BYTES, {
stripAnnotations: true,
references,
});
const inline =
expanded === undefined
? undefined
: projectToAdvertisedDialect(
retainRootPropertyGuidance(schema, expanded),
);
const defaults = canonicalDefaultGuidance(schema, references);
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,
guidance: [...inline.guidance, ...defaults],
presentation: "inline",
};
if (inline !== undefined) {
// 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,
...defaults,
INPUT_PRUNED_GUIDANCE,
...exampleGuidance(schema),
],
presentation: "inline",
};
}
// Scalar rules are a few bytes each, but a very large enum could still
// overflow. Generic name-derived descriptions go first, then the rules;
// root property names, types and required fields come first of all.
for (const [keepScalarRules, keepDescription] of [
[true, () => true],
[true, isAuthoredDescription],
[false, () => true],
] as const) {
const reduced = projectToAdvertisedDialect(
reduceToShallowProperties(
schema,
INPUT_REDUCED_ANNOTATION,
references,
keepScalarRules,
keepDescription,
),
);
if (serializedBytes(reduced.schema) <= budgetBytes)
return {
...reduced,
guidance: [
...reduced.guidance,
...defaults,
...exampleGuidance(schema),
],
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;
};