mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
perf(mcp/cli): skip unused output schema projection, error deep-clones, and startup z.toJSONSchema (#13426)
* perf(mcp/cli): skip unused output schema projection, error deep-clones, and startup z.toJSONSchema Addresses #13354, #13275, #13302. * refactor(contracts): share advertised input dialect traversal and rules
This commit is contained in:
1 parent
48d4b6145a
commit
375483b6b3
9 files changed
+585
-111
No files matched your search
+87
-12
@@ -859,8 +859,85 @@ const commandShape = (description: ContractCliDescription) => ({
|
||||
),
|
||||
});
|
||||
|
||||
const schemaSignature = (schema: z.ZodType): string =>
|
||||
JSON.stringify(z.toJSONSchema(schema, { unrepresentable: "any" }));
|
||||
const schemaSignatures = new WeakMap<z.ZodType, string>();
|
||||
|
||||
const schemaSignature = (schema: z.ZodType): string => {
|
||||
const cached = schemaSignatures.get(schema);
|
||||
if (cached !== undefined) return cached;
|
||||
const serialized = JSON.stringify(
|
||||
z.toJSONSchema(schema, { unrepresentable: "any" }),
|
||||
);
|
||||
schemaSignatures.set(schema, serialized);
|
||||
return serialized;
|
||||
};
|
||||
|
||||
const simpleSchemasIdentical = (left: z.ZodType, right: z.ZodType): boolean => {
|
||||
if (left === right) return true;
|
||||
if (
|
||||
z.globalRegistry.get(left) !== undefined ||
|
||||
z.globalRegistry.get(right) !== undefined
|
||||
)
|
||||
return false;
|
||||
const leftDef = left._zod.def as unknown as Readonly<Record<string, unknown>>;
|
||||
const rightDef = right._zod.def as unknown as Readonly<
|
||||
Record<string, unknown>
|
||||
>;
|
||||
if (leftDef.type !== rightDef.type) return false;
|
||||
switch (leftDef.type) {
|
||||
case "boolean":
|
||||
case "string":
|
||||
return (
|
||||
(leftDef.checks as readonly unknown[] | undefined)?.length ===
|
||||
undefined &&
|
||||
(rightDef.checks as readonly unknown[] | undefined)?.length ===
|
||||
undefined
|
||||
);
|
||||
case "number":
|
||||
return (
|
||||
leftDef.format === undefined &&
|
||||
rightDef.format === undefined &&
|
||||
(leftDef.checks as readonly unknown[] | undefined)?.length ===
|
||||
undefined &&
|
||||
(rightDef.checks as readonly unknown[] | undefined)?.length ===
|
||||
undefined
|
||||
);
|
||||
case "literal": {
|
||||
const leftValues = leftDef.values as readonly unknown[];
|
||||
const rightValues = rightDef.values as readonly unknown[];
|
||||
return (
|
||||
leftValues.length === rightValues.length &&
|
||||
leftValues.every((value, index) => Object.is(value, rightValues[index]))
|
||||
);
|
||||
}
|
||||
case "enum": {
|
||||
const leftEntries = Object.entries(
|
||||
leftDef.entries as Record<string, string | number>,
|
||||
);
|
||||
const rightEntries = rightDef.entries as Record<string, string | number>;
|
||||
return (
|
||||
leftEntries.length === Object.keys(rightEntries).length &&
|
||||
leftEntries.every(
|
||||
([key, value]) =>
|
||||
Object.hasOwn(rightEntries, key) &&
|
||||
Object.is(rightEntries[key], value),
|
||||
)
|
||||
);
|
||||
}
|
||||
case "optional":
|
||||
case "nullable":
|
||||
case "readonly":
|
||||
return simpleSchemasIdentical(
|
||||
leftDef.innerType as z.ZodType,
|
||||
rightDef.innerType as z.ZodType,
|
||||
);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const schemasAgree = (left: z.ZodType, right: z.ZodType): boolean =>
|
||||
simpleSchemasIdentical(left, right) ||
|
||||
schemaSignature(left) === schemaSignature(right);
|
||||
|
||||
/**
|
||||
* Register one CLI command whose input chooses the contract input it runs,
|
||||
@@ -902,20 +979,18 @@ export const registerRoutedCommand = (
|
||||
const owners = new Map<string, CliCommandRoute>();
|
||||
for (const [index, shape] of shapes.entries()) {
|
||||
if (
|
||||
shape.args.length !== args.length ||
|
||||
shape.args.some(
|
||||
([key, schema], position) =>
|
||||
key !== args[position]![0] ||
|
||||
schemaSignature(schema) !== schemaSignature(args[position]![1]),
|
||||
)
|
||||
index > 0 &&
|
||||
(shape.args.length !== args.length ||
|
||||
shape.args.some(
|
||||
([key, schema], position) =>
|
||||
key !== args[position]![0] ||
|
||||
!schemasAgree(schema, args[position]![1]),
|
||||
))
|
||||
)
|
||||
throw new Error(`${name} routes take different arguments`);
|
||||
for (const [key, schema] of Object.entries(shape.options)) {
|
||||
const shared = options.get(key);
|
||||
if (
|
||||
shared !== undefined &&
|
||||
schemaSignature(shared) !== schemaSignature(schema)
|
||||
)
|
||||
if (shared !== undefined && !schemasAgree(shared, schema))
|
||||
throw new Error(`${name} routes disagree on --${key}`);
|
||||
options.set(key, schema);
|
||||
owners.set(key, routes[index]!);
|
||||
|
||||
@@ -344,27 +344,88 @@ type SchemaKind = "input" | "output";
|
||||
const visitSchemas = (
|
||||
schema: unknown,
|
||||
path: string,
|
||||
visit: (node: unknown, path: string, keyword: string | undefined) => void,
|
||||
visit: (
|
||||
node: unknown,
|
||||
path: string,
|
||||
keyword: string | undefined,
|
||||
) => boolean | void,
|
||||
keyword?: string,
|
||||
): void => {
|
||||
visit(schema, path, keyword);
|
||||
if (!isRecord(schema)) return;
|
||||
trackPaths = true,
|
||||
): boolean => {
|
||||
if (visit(schema, path, keyword) === true) return true;
|
||||
if (!isRecord(schema)) return false;
|
||||
for (const [key, value] of Object.entries(schema)) {
|
||||
if (schemaMaps.has(key) && isRecord(value))
|
||||
if (schemaMaps.has(key) && isRecord(value)) {
|
||||
for (const [name, child] of Object.entries(value))
|
||||
visitSchemas(child, `${path}.${key}.${name}`, visit, key);
|
||||
else if (schemaArrays.has(key) && Array.isArray(value))
|
||||
value.forEach((child, index) =>
|
||||
visitSchemas(child, `${path}.${key}[${String(index)}]`, visit, key),
|
||||
);
|
||||
else if (schemaChildren.has(key)) {
|
||||
if (Array.isArray(value))
|
||||
value.forEach((child, index) =>
|
||||
visitSchemas(child, `${path}.${key}[${String(index)}]`, visit, key),
|
||||
);
|
||||
else visitSchemas(value, `${path}.${key}`, visit, key);
|
||||
if (
|
||||
visitSchemas(
|
||||
child,
|
||||
trackPaths ? `${path}.${key}.${name}` : "",
|
||||
visit,
|
||||
key,
|
||||
trackPaths,
|
||||
)
|
||||
)
|
||||
return true;
|
||||
} else if (schemaArrays.has(key) && Array.isArray(value)) {
|
||||
for (let index = 0; index < value.length; index++)
|
||||
if (
|
||||
visitSchemas(
|
||||
value[index],
|
||||
trackPaths ? `${path}.${key}[${String(index)}]` : "",
|
||||
visit,
|
||||
key,
|
||||
trackPaths,
|
||||
)
|
||||
)
|
||||
return true;
|
||||
} else if (schemaChildren.has(key)) {
|
||||
if (Array.isArray(value)) {
|
||||
for (let index = 0; index < value.length; index++)
|
||||
if (
|
||||
visitSchemas(
|
||||
value[index],
|
||||
trackPaths ? `${path}.${key}[${String(index)}]` : "",
|
||||
visit,
|
||||
key,
|
||||
trackPaths,
|
||||
)
|
||||
)
|
||||
return true;
|
||||
} else if (
|
||||
visitSchemas(
|
||||
value,
|
||||
trackPaths ? `${path}.${key}` : "",
|
||||
visit,
|
||||
key,
|
||||
trackPaths,
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const visitNodePatterns = (
|
||||
node: unknown,
|
||||
path: string,
|
||||
onPattern: (patternPath: string, pattern: string) => boolean | void,
|
||||
): boolean => {
|
||||
if (!isRecord(node)) return false;
|
||||
if (typeof node.pattern === "string" && onPattern(path, node.pattern))
|
||||
return true;
|
||||
if (isRecord(node.patternProperties))
|
||||
for (const pattern of Object.keys(node.patternProperties))
|
||||
if (
|
||||
onPattern(
|
||||
`${path}.patternProperties[${JSON.stringify(pattern)}]`,
|
||||
pattern,
|
||||
)
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -376,15 +437,9 @@ export const advertisedSchemaPatterns = (
|
||||
): readonly { readonly path: string; readonly pattern: string }[] => {
|
||||
const patterns: { path: string; pattern: string }[] = [];
|
||||
visitSchemas(root, "$", (node, path) => {
|
||||
if (!isRecord(node)) return;
|
||||
if (typeof node.pattern === "string")
|
||||
patterns.push({ path, pattern: node.pattern });
|
||||
if (isRecord(node.patternProperties))
|
||||
for (const pattern of Object.keys(node.patternProperties))
|
||||
patterns.push({
|
||||
path: `${path}.patternProperties[${JSON.stringify(pattern)}]`,
|
||||
pattern,
|
||||
});
|
||||
visitNodePatterns(node, path, (patternPath, pattern) => {
|
||||
patterns.push({ path: patternPath, pattern });
|
||||
});
|
||||
});
|
||||
return patterns;
|
||||
};
|
||||
@@ -429,85 +484,133 @@ const isNullableUnion = (node: Readonly<Record<string, unknown>>): boolean =>
|
||||
PRIMITIVE_TYPES.has(branch.type),
|
||||
);
|
||||
|
||||
const nodeViolations = (
|
||||
tool: string,
|
||||
const hasDisallowedRootShape = (input: unknown): boolean =>
|
||||
!isRecord(input) ||
|
||||
input.type !== "object" ||
|
||||
Object.hasOwn(input, "anyOf") ||
|
||||
Object.hasOwn(input, "oneOf") ||
|
||||
Object.hasOwn(input, "allOf");
|
||||
|
||||
const scanNodeInputViolations = (
|
||||
node: unknown,
|
||||
path: string,
|
||||
keyword: string | undefined,
|
||||
): AdvertisedDialectViolation[] => {
|
||||
const violations: AdvertisedDialectViolation[] = [];
|
||||
const add = (rule: AdvertisedDialectRule, detail?: string) =>
|
||||
violations.push({
|
||||
tool,
|
||||
schema: "input",
|
||||
path,
|
||||
rule,
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
});
|
||||
report: (rule: AdvertisedDialectRule, detail?: string) => boolean,
|
||||
): boolean => {
|
||||
if (!isRecord(node)) {
|
||||
// `additionalProperties: false` is the closed-object form every target accepts.
|
||||
if (
|
||||
return (
|
||||
typeof node === "boolean" &&
|
||||
!(node === false && keyword === "additionalProperties")
|
||||
)
|
||||
add("boolean-schema");
|
||||
return violations;
|
||||
!(node === false && keyword === "additionalProperties") &&
|
||||
report("boolean-schema")
|
||||
);
|
||||
}
|
||||
for (const key of Object.keys(node))
|
||||
if (!ALLOWED_KEYWORDS.has(key)) add("keyword", key);
|
||||
if (!ALLOWED_KEYWORDS.has(key) && report("keyword", key)) return true;
|
||||
const { type } = node;
|
||||
if (Array.isArray(type)) add("type", "type-list");
|
||||
else if (type === undefined) {
|
||||
if (!isNullableUnion(node)) add("type", "untyped");
|
||||
}
|
||||
// The null branch of a nullable union is typed by its own `type`.
|
||||
else if (
|
||||
if (Array.isArray(type)) {
|
||||
if (report("type", "type-list")) return true;
|
||||
} else if (type === undefined) {
|
||||
if (!isNullableUnion(node) && report("type", "untyped")) return true;
|
||||
} else if (
|
||||
// The null branch of a nullable union is typed by its own `type`.
|
||||
type === "null" &&
|
||||
keyword === "anyOf" &&
|
||||
Object.keys(node).length === 1
|
||||
) {
|
||||
return false;
|
||||
} else if (typeof type !== "string" || !PRIMITIVE_TYPES.has(type)) {
|
||||
if (report("type", `type:${String(type)}`)) return true;
|
||||
}
|
||||
if (
|
||||
type === "array" &&
|
||||
node.items === undefined &&
|
||||
report("array-items", "missing")
|
||||
)
|
||||
return violations;
|
||||
else if (typeof type !== "string" || !PRIMITIVE_TYPES.has(type))
|
||||
add("type", `type:${String(type)}`);
|
||||
if (type === "array" && node.items === undefined)
|
||||
add("array-items", "missing");
|
||||
if (node.items !== undefined && type !== "array")
|
||||
add("array-items", "beside-non-array-type");
|
||||
if (Array.isArray(node.items)) add("array-items", "tuple");
|
||||
return true;
|
||||
if (
|
||||
node.items !== undefined &&
|
||||
type !== "array" &&
|
||||
report("array-items", "beside-non-array-type")
|
||||
)
|
||||
return true;
|
||||
if (Array.isArray(node.items) && report("array-items", "tuple")) return true;
|
||||
if (node.enum !== undefined) {
|
||||
const values = node.enum;
|
||||
if (!Array.isArray(values) || values.length === 0) add("enum", "empty");
|
||||
else if (values.some((value) => typeof value !== "string"))
|
||||
add("enum", "non-string");
|
||||
else if (values.includes("")) add("enum", "empty-string");
|
||||
if (type !== "string") add("enum", "not-on-string-type");
|
||||
if (!Array.isArray(values) || values.length === 0) {
|
||||
if (report("enum", "empty")) return true;
|
||||
} else if (values.some((value) => typeof value !== "string")) {
|
||||
if (report("enum", "non-string")) return true;
|
||||
} else if (values.includes("") && report("enum", "empty-string")) {
|
||||
return true;
|
||||
}
|
||||
if (type !== "string" && report("enum", "not-on-string-type")) return true;
|
||||
}
|
||||
if (node.anyOf !== undefined) {
|
||||
const branches = node.anyOf;
|
||||
if (path === "$") add("any-of", "root");
|
||||
if (!Array.isArray(branches) || branches.length < 2)
|
||||
add("any-of", "fewer-than-two-branches");
|
||||
else if (
|
||||
branches.some((branch) => !isRecord(branch) || branch.type === undefined)
|
||||
)
|
||||
add("any-of", "untyped-branch");
|
||||
if (node.properties !== undefined) add("any-of", "beside-properties");
|
||||
if (path === "$" && report("any-of", "root")) return true;
|
||||
if (!Array.isArray(branches) || branches.length < 2) {
|
||||
if (report("any-of", "fewer-than-two-branches")) return true;
|
||||
} else if (
|
||||
branches.some(
|
||||
(branch) => !isRecord(branch) || branch.type === undefined,
|
||||
) &&
|
||||
report("any-of", "untyped-branch")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (node.properties !== undefined && report("any-of", "beside-properties"))
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
typeof node.description === "string" &&
|
||||
node.description.length > ADVERTISED_DESCRIPTION_MAX_CHARACTERS
|
||||
node.description.length > ADVERTISED_DESCRIPTION_MAX_CHARACTERS &&
|
||||
report("description-length")
|
||||
)
|
||||
add("description-length");
|
||||
return true;
|
||||
for (const bound of ["minLength", "maxLength", "minItems", "maxItems"])
|
||||
if (
|
||||
typeof node[bound] === "number" &&
|
||||
node[bound] >= ADVERTISED_BOUND_LIMIT
|
||||
node[bound] >= ADVERTISED_BOUND_LIMIT &&
|
||||
report("bound", bound)
|
||||
)
|
||||
add("bound", bound);
|
||||
return true;
|
||||
if (isRecord(node.properties))
|
||||
for (const name of Object.keys(node.properties))
|
||||
if (!PROPERTY_NAME.test(name)) add("property-name", name);
|
||||
return violations;
|
||||
if (!PROPERTY_NAME.test(name) && report("property-name", name))
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Short-circuiting equivalent of `advertisedInputDialectViolations(tool).length > 0`
|
||||
* for an input schema without allocating per-violation diagnostics.
|
||||
*/
|
||||
export const hasAdvertisedInputDialectViolation = (
|
||||
input: unknown,
|
||||
options?: { readonly skipRootBounds?: boolean },
|
||||
): boolean => {
|
||||
if (
|
||||
!options?.skipRootBounds &&
|
||||
(serializedBytes(input) > ADVERTISED_INPUT_SCHEMA_MAX_BYTES ||
|
||||
schemaDepth(input) > COMPACT_SCHEMA_MAX_DEPTH)
|
||||
)
|
||||
return true;
|
||||
if (hasDisallowedRootShape(input)) return true;
|
||||
return visitSchemas(
|
||||
input,
|
||||
"$",
|
||||
(node, path, keyword) =>
|
||||
scanNodeInputViolations(node, path, keyword, () => true) ||
|
||||
visitNodePatterns(
|
||||
node,
|
||||
path,
|
||||
(_patternPath, pattern) =>
|
||||
portablePatternViolations(pattern).length > 0,
|
||||
),
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
};
|
||||
|
||||
/** Advertised tool fields the portable dialect constrains. */
|
||||
@@ -537,15 +640,19 @@ export const advertisedInputDialectViolations = (
|
||||
whole("input", "input-bytes");
|
||||
if (schemaDepth(input) > COMPACT_SCHEMA_MAX_DEPTH)
|
||||
whole("input", "input-depth");
|
||||
if (
|
||||
!isRecord(input) ||
|
||||
input.type !== "object" ||
|
||||
["anyOf", "oneOf", "allOf"].some((key) => Object.hasOwn(input, key))
|
||||
)
|
||||
whole("input", "root-shape");
|
||||
visitSchemas(input, "$", (node, path, keyword) =>
|
||||
violations.push(...nodeViolations(name, node, path, keyword)),
|
||||
);
|
||||
if (hasDisallowedRootShape(input)) whole("input", "root-shape");
|
||||
visitSchemas(input, "$", (node, path, keyword) => {
|
||||
scanNodeInputViolations(node, path, keyword, (rule, detail) => {
|
||||
violations.push({
|
||||
tool: name,
|
||||
schema: "input",
|
||||
path,
|
||||
rule,
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
});
|
||||
return false;
|
||||
});
|
||||
});
|
||||
violations.push(...patternViolations(name, "input", input));
|
||||
return violations;
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ADVERTISED_INPUT_SCHEMA_MAX_BYTES,
|
||||
advertisedInputDialectViolations,
|
||||
hasAdvertisedInputDialectViolation,
|
||||
} from "./advertisedDialect.js";
|
||||
import { compactAdvertisedInputSchema } from "./compactInputSchema.js";
|
||||
import { inlineWithinBudget, stripAnnotations } from "./compactJsonSchema.js";
|
||||
@@ -1131,3 +1132,42 @@ describe("on-the-fly annotation stripping parity", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasAdvertisedInputDialectViolation", () => {
|
||||
it("agrees with advertisedInputDialectViolations across synthetic and failing cases", () => {
|
||||
const cases: Record<string, unknown>[] = [
|
||||
{ type: "object", properties: { name: { type: "string" } } },
|
||||
{ type: "string" },
|
||||
{ type: "object", oneOf: [{ type: "object" }] },
|
||||
{
|
||||
type: "object",
|
||||
properties: { bad: { type: "string", pattern: "[a-" } },
|
||||
},
|
||||
{ type: "object", properties: { bad: { type: "array" } } },
|
||||
{
|
||||
type: "object",
|
||||
properties: { bad: { type: "string", enum: [] } },
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: { "1bad": { type: "string" } },
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
ok: {
|
||||
anyOf: [{ type: "string" }, { type: "null" }],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
for (const schema of cases) {
|
||||
const expected =
|
||||
advertisedInputDialectViolations({
|
||||
name: "tool_name",
|
||||
inputSchema: schema,
|
||||
}).length > 0;
|
||||
expect(hasAdvertisedInputDialectViolation(schema)).toBe(expected);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,7 @@
|
||||
import { advertisedInputDialectViolations } from "./advertisedDialect.js";
|
||||
import {
|
||||
ADVERTISED_INPUT_SCHEMA_MAX_BYTES,
|
||||
hasAdvertisedInputDialectViolation,
|
||||
} from "./advertisedDialect.js";
|
||||
import { projectToAdvertisedDialect } from "./advertisedDialectProjection.js";
|
||||
import {
|
||||
COMPACT_SCHEMA_MAX_DEPTH,
|
||||
@@ -62,12 +65,6 @@ const retainRootPropertyGuidance = (
|
||||
return properties === undefined ? stripped : { ...stripped, properties };
|
||||
};
|
||||
|
||||
const withinDialect = (schema: Record<string, unknown>): boolean =>
|
||||
advertisedInputDialectViolations({
|
||||
name: "input",
|
||||
inputSchema: schema,
|
||||
}).length === 0;
|
||||
|
||||
/**
|
||||
* Render an advertised input schema within a per-schema byte budget for
|
||||
* providers that validate the literal serialized schema size. The complete
|
||||
@@ -93,7 +90,9 @@ export const compactAdvertisedInputSchema = (
|
||||
inline !== undefined &&
|
||||
serializedBytes(inline.schema) <= budgetBytes &&
|
||||
schemaDepth(inline.schema) <= COMPACT_SCHEMA_MAX_DEPTH &&
|
||||
withinDialect(inline.schema)
|
||||
!hasAdvertisedInputDialectViolation(inline.schema, {
|
||||
skipRootBounds: budgetBytes <= ADVERTISED_INPUT_SCHEMA_MAX_BYTES,
|
||||
})
|
||||
)
|
||||
return { ...inline, presentation: "inline" };
|
||||
const reduced = projectToAdvertisedDialect(
|
||||
|
||||
@@ -12,6 +12,8 @@ import { compactAdvertisedInputSchema } from "./compactInputSchema.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
|
||||
import {
|
||||
advertisedInputJsonSchema,
|
||||
hasGuaranteedObjectOutputRoot,
|
||||
omitAdvertisedOutputJsonSchema,
|
||||
toolInputSchemaWithMetadata,
|
||||
toolOutputSchemaWithMetadata,
|
||||
} from "./toolSchemaMetadata.js";
|
||||
@@ -56,6 +58,65 @@ it("declares an object root only on the advertised output of an object union", (
|
||||
expect(z.toJSONSchema(contract.outputSchema)).not.toHaveProperty("type");
|
||||
});
|
||||
|
||||
it("identifies guaranteed object-root outputs and omits unused output projections safely", async () => {
|
||||
const objectContract = ELECTRON_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "analyze_javascript_application",
|
||||
);
|
||||
const unionObjectContract = APPLICATION_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "guided_workflows",
|
||||
);
|
||||
const nonObjectUnionContract = APPLICATION_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "search_guidance",
|
||||
);
|
||||
if (
|
||||
objectContract === undefined ||
|
||||
unionObjectContract === undefined ||
|
||||
nonObjectUnionContract === undefined
|
||||
)
|
||||
throw new Error("Missing expected contract fixtures");
|
||||
|
||||
expect(
|
||||
hasGuaranteedObjectOutputRoot(toolOutputSchemaWithMetadata(objectContract)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
hasGuaranteedObjectOutputRoot(
|
||||
toolOutputSchemaWithMetadata(unionObjectContract),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
hasGuaranteedObjectOutputRoot(
|
||||
toolOutputSchemaWithMetadata(nonObjectUnionContract),
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
const schema = z.strictObject({ ok: z.literal(true) });
|
||||
const originalOutput = schema["~standard"].jsonSchema.output;
|
||||
let calls = 0;
|
||||
Object.defineProperty(schema, "~standard", {
|
||||
value: {
|
||||
...schema["~standard"],
|
||||
jsonSchema: {
|
||||
...schema["~standard"].jsonSchema,
|
||||
output: (options: unknown) => {
|
||||
calls += 1;
|
||||
return originalOutput(options as never);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const omitted = omitAdvertisedOutputJsonSchema(schema);
|
||||
expect(
|
||||
omitted["~standard"].jsonSchema.output({ target: "draft-2020-12" }),
|
||||
).toEqual({ type: "object" });
|
||||
expect(calls).toBe(0);
|
||||
expect(omitted["~standard"].validate({ ok: true })).toEqual({
|
||||
value: { ok: true },
|
||||
});
|
||||
expect(omitted["~standard"].validate({ ok: false })).toMatchObject({
|
||||
issues: expect.any(Array),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps update_analysis_settings compact advertised input inline under the depth cap", () => {
|
||||
const contract = ANALYSIS_SETTINGS_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "update_analysis_settings",
|
||||
|
||||
@@ -236,6 +236,38 @@ export const advertisedOutputJsonSchema = <Contract extends ToolContract>(
|
||||
target,
|
||||
}) as Record<string, unknown>;
|
||||
|
||||
/** A wire projection already proven object-rooted, or its original schema. */
|
||||
const OBJECT_ROOT_OUTPUT_STUB: Readonly<Record<string, unknown>> =
|
||||
Object.freeze({ type: "object" });
|
||||
|
||||
/** Whether every valid instance of this output schema has an object root. */
|
||||
export const hasGuaranteedObjectOutputRoot = (schema: unknown): boolean =>
|
||||
schema instanceof z.ZodObject ||
|
||||
(schema instanceof z.core.$ZodType &&
|
||||
schemaAnnotations(schema)?.objectRoot === true);
|
||||
|
||||
/**
|
||||
* Omit canonical JSON Schema generation on a server profile that strips
|
||||
* `outputSchema` from `tools/list`, preserving runtime `~standard.validate`
|
||||
* and object-root identity for wire codecs without running a 5 MB projection.
|
||||
*/
|
||||
export const omitAdvertisedOutputJsonSchema = <Schema>(
|
||||
schema: Schema,
|
||||
): Schema => {
|
||||
const standard = Reflect.get(schema as object, "~standard");
|
||||
if (!isRecord(standard)) return schema;
|
||||
const jsonSchema = Reflect.get(standard, "jsonSchema");
|
||||
if (!isRecord(jsonSchema)) return schema;
|
||||
if (typeof Reflect.get(jsonSchema, "output") !== "function") return schema;
|
||||
return {
|
||||
...(schema as object),
|
||||
"~standard": {
|
||||
...standard,
|
||||
jsonSchema: { ...jsonSchema, output: () => OBJECT_ROOT_OUTPUT_STUB },
|
||||
},
|
||||
} as Schema;
|
||||
};
|
||||
|
||||
/**
|
||||
* Apply a wire-presentation transform to one schema's advertised input
|
||||
* projection. The wrapper preserves the schema's own parser and standard
|
||||
|
||||
@@ -676,3 +676,92 @@ describe("SDK argument name guidance", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("skips object-root output schema projection on output=off while keeping runtime validation and legacy wrapping", async () => {
|
||||
const server = new EvidenceMcpServer(
|
||||
{ name: "output-off-skip-test", version: "1" },
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
createToolResultDelivery(4096),
|
||||
undefined,
|
||||
"off",
|
||||
);
|
||||
let objectOutputCalls = 0;
|
||||
const spyObjectOutput = z.strictObject({ count: z.int() });
|
||||
const baseStandard = spyObjectOutput["~standard"];
|
||||
Object.defineProperty(spyObjectOutput, "~standard", {
|
||||
value: {
|
||||
...baseStandard,
|
||||
jsonSchema: {
|
||||
...baseStandard.jsonSchema,
|
||||
output: (options: unknown) => {
|
||||
objectOutputCalls += 1;
|
||||
return baseStandard.jsonSchema.output(options as never);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
server.registerTool(
|
||||
"object_tool",
|
||||
{
|
||||
inputSchema: z.strictObject({ n: z.int() }),
|
||||
outputSchema: spyObjectOutput,
|
||||
},
|
||||
async ({ n }) => ({
|
||||
content: [],
|
||||
structuredContent: n >= 0 ? { count: n } : ({ count: "bad" } as never),
|
||||
}),
|
||||
);
|
||||
const nonObjectUnionOutput = z.union([
|
||||
z.strictObject({ status: z.literal("ok") }),
|
||||
z.string(),
|
||||
]);
|
||||
server.registerTool(
|
||||
"union_tool",
|
||||
{
|
||||
inputSchema: z.strictObject({}),
|
||||
outputSchema: nonObjectUnionOutput,
|
||||
},
|
||||
async () => ({
|
||||
content: [],
|
||||
structuredContent: { status: "ok" as const },
|
||||
}),
|
||||
);
|
||||
const client = new Client(
|
||||
{ name: "output-off-client", version: "1" },
|
||||
{ supportedProtocolVersions: ["2025-11-25"] },
|
||||
);
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const serving = serveStdio(() => server, { transport: serverTransport });
|
||||
try {
|
||||
await client.connect(clientTransport);
|
||||
expect(client.getNegotiatedProtocolVersion()).toBe("2025-11-25");
|
||||
const listed = await client.listTools();
|
||||
expect(objectOutputCalls).toBe(0);
|
||||
for (const tool of listed.tools) expect(tool.outputSchema).toBeUndefined();
|
||||
|
||||
const valid = await client.callTool({
|
||||
name: "object_tool",
|
||||
arguments: { n: 42 },
|
||||
});
|
||||
expect(valid.isError).toBeFalsy();
|
||||
expect(valid.structuredContent).toEqual({ count: 42 });
|
||||
|
||||
const invalidOutput = await client.callTool({
|
||||
name: "object_tool",
|
||||
arguments: { n: -1 },
|
||||
});
|
||||
expect(invalidOutput.isError).toBe(true);
|
||||
|
||||
// Non-object union root keeps 2025 legacy `{ result }` wrapping.
|
||||
const wrapped = await client.callTool({
|
||||
name: "union_tool",
|
||||
arguments: {},
|
||||
});
|
||||
expect(wrapped.isError).toBeFalsy();
|
||||
expect(wrapped.structuredContent).toEqual({ result: { status: "ok" } });
|
||||
} finally {
|
||||
await Promise.all([client.close(), serving.close()]);
|
||||
}
|
||||
});
|
||||
@@ -37,7 +37,11 @@ import {
|
||||
type AdvertisedToolPresentation,
|
||||
} from "../contracts/advertisedTool.js";
|
||||
import type { createCatalogIdentity } from "../contracts/catalog/catalogIdentity.js";
|
||||
import { transformAdvertisedInputJsonSchema } from "../contracts/toolSchemaMetadata.js";
|
||||
import {
|
||||
hasGuaranteedObjectOutputRoot,
|
||||
omitAdvertisedOutputJsonSchema,
|
||||
transformAdvertisedInputJsonSchema,
|
||||
} from "../contracts/toolSchemaMetadata.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
@@ -50,7 +54,7 @@ import { projectAnalysisErrorWithoutPartialObservation } from "../domain/analysi
|
||||
import { projectInputIssueGroupsWithinBudget } from "../domain/inputIssueProjection.js";
|
||||
import type { z } from "zod";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ownedJsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
mcpResponseOverflowProjection,
|
||||
type ToolResultDelivery,
|
||||
@@ -447,6 +451,12 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
|
||||
this.registerEvidenceReferenceAlternative(name);
|
||||
const advertised = this.advertisesTool(name);
|
||||
const presented = advertised ? this.presentInput(name, config) : config;
|
||||
const outputSchema =
|
||||
this.presentation.output === undefined &&
|
||||
config.outputSchema !== undefined &&
|
||||
hasGuaranteedObjectOutputRoot(config.outputSchema)
|
||||
? omitAdvertisedOutputJsonSchema(config.outputSchema)
|
||||
: config.outputSchema;
|
||||
const registeredConfig = advertised
|
||||
? {
|
||||
...config,
|
||||
@@ -461,8 +471,11 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
|
||||
presented.inputSchema as StandardSchemaWithJSON,
|
||||
),
|
||||
}),
|
||||
...(outputSchema === undefined ? {} : { outputSchema }),
|
||||
}
|
||||
: config;
|
||||
: outputSchema === undefined
|
||||
? config
|
||||
: { ...config, outputSchema };
|
||||
const scoped = async (input: never, context: never) => {
|
||||
const request = currentMcpToolRequest();
|
||||
request?.beginHandler();
|
||||
@@ -883,7 +896,7 @@ class ErrorEvidenceTransport implements Transport {
|
||||
// text-only result without serializing the complete JSON-RPC message.
|
||||
const isStructured = message.result.structuredContent !== undefined;
|
||||
const structured = isStructured
|
||||
? jsonObjectSchema.parse(message.result.structuredContent)
|
||||
? ownedJsonObjectSchema.parse(message.result.structuredContent)
|
||||
: undefined;
|
||||
const sdkResultWithMarker =
|
||||
!isStructured &&
|
||||
@@ -924,7 +937,7 @@ class ErrorEvidenceTransport implements Transport {
|
||||
encoded =
|
||||
normalized.result.content.length === 0
|
||||
? encodeToolResult(
|
||||
jsonObjectSchema.parse(structuredContent),
|
||||
ownedJsonObjectSchema.parse(structuredContent),
|
||||
budget,
|
||||
"error-text",
|
||||
targetContent,
|
||||
@@ -936,7 +949,7 @@ class ErrorEvidenceTransport implements Transport {
|
||||
}
|
||||
if (encoded.ok) return message;
|
||||
const operation = tool ?? "mcp_tool_error";
|
||||
const originalResult = jsonObjectSchema.parse(message.result);
|
||||
const originalResult = ownedJsonObjectSchema.parse(message.result);
|
||||
const retainedResult = structured ?? originalResult;
|
||||
const originalError = isStructured
|
||||
? analysisErrorProjectionSchema.safeParse(structured?.["error"])
|
||||
|
||||
@@ -174,3 +174,61 @@ it("refuses routes that check a shared JSON input differently", () => {
|
||||
),
|
||||
).toThrow("probe routes check --policy differently");
|
||||
});
|
||||
|
||||
it("accepts structurally matching shared options and rejects differing constraints or metadata", () => {
|
||||
const cli = createCommandCli();
|
||||
const command = { command: "probe", description: "Probe" };
|
||||
const route = (name: string, extra: z.ZodType) =>
|
||||
commandRoute(
|
||||
{
|
||||
name,
|
||||
inputSchema: z.object({
|
||||
path: absoluteLocalPathStringSchema,
|
||||
flag: z.boolean().optional(),
|
||||
mode: z.enum(["a", "b"]).optional(),
|
||||
extra,
|
||||
}),
|
||||
},
|
||||
{
|
||||
...command,
|
||||
positionals: ["path"],
|
||||
},
|
||||
async () => ({}),
|
||||
{ takes: async () => true, requirement: name },
|
||||
);
|
||||
expect(() =>
|
||||
registerRoutedCommand(
|
||||
cli as unknown as CliInstance,
|
||||
pino({ enabled: false }),
|
||||
command,
|
||||
[
|
||||
route("one_probe", z.string().optional()),
|
||||
route("two_probe", z.string().optional()),
|
||||
],
|
||||
),
|
||||
).not.toThrow();
|
||||
|
||||
expect(() =>
|
||||
registerRoutedCommand(
|
||||
createCommandCli() as unknown as CliInstance,
|
||||
pino({ enabled: false }),
|
||||
command,
|
||||
[
|
||||
route("one_probe", z.string().optional()),
|
||||
route("two_probe", z.string().min(2).optional()),
|
||||
],
|
||||
),
|
||||
).toThrow("probe routes disagree on --extra");
|
||||
|
||||
expect(() =>
|
||||
registerRoutedCommand(
|
||||
createCommandCli() as unknown as CliInstance,
|
||||
pino({ enabled: false }),
|
||||
command,
|
||||
[
|
||||
route("one_probe", z.string().describe("first").optional()),
|
||||
route("two_probe", z.string().describe("second").optional()),
|
||||
],
|
||||
),
|
||||
).toThrow("probe routes disagree on --extra");
|
||||
});
|
||||
Reference in new issue
Block a user