fix(mcp): flatten root union input schemas (#1062)

* fix(mcp): flatten root union input schemas

* fix(mcp): preserve minimum input requirements in object schemas

---------

Co-authored-by: N0zoM1z0 <1705004398@qq.com>
This commit is contained in:
cevieiras
2026-10-08 20:54:51 +08:00
committed by GitHub
co-authored by N0zoM1z0
parent 170600541b
commit 6a7650e93c
2 changed files with 68 additions and 8 deletions
+56 -4
View File
@@ -56,10 +56,11 @@ export const toolInputSchemaWithMetadata = <Contract extends ToolContract>(
withAdvertisedJsonSchema(
contract.inputSchema,
"input",
(project) => (options) => ({
...describeProperties(project(options)),
examples: contract.examples.map(({ input }) => input),
}),
(project) => (options) =>
flattenRootUnion({
...describeProperties(project(options)),
examples: contract.examples.map(({ input }) => input),
}),
);
/** Advertise a canonical output schema without reconverting it per listing. */
@@ -113,6 +114,57 @@ const memoizeByTarget = (
};
};
/** Keep MCP tool roots object-shaped for clients that reject root unions. */
const flattenRootUnion = (
value: Record<string, unknown>,
): Record<string, unknown> => {
if (!Array.isArray(value.anyOf)) return value;
const branches = value.anyOf.filter(isObject);
if (branches.length === 0 || branches.length !== value.anyOf.length)
return value;
const properties: Record<string, unknown> = {};
for (const branch of branches) {
if (!isObject(branch.properties)) return value;
for (const [name, schema] of Object.entries(branch.properties)) {
const previous = properties[name];
if (previous === undefined) properties[name] = schema;
else if (JSON.stringify(previous) !== JSON.stringify(schema))
properties[name] = {
anyOf: [previous, schema],
description: fallbackPropertyDescription(name),
};
}
}
// The canonical Zod parser still enforces branch validation at invocation.
const { anyOf: _anyOf, required: _required, ...root } = value;
const requiredByBranch = branches.map((branch) =>
Array.isArray(branch.required)
? branch.required.filter(
(item): item is string => typeof item === "string",
)
: [],
);
const required = requiredByBranch.reduce((common, current) =>
common.filter((name) => current.includes(name)),
);
const minProperties = Math.max(
typeof root.minProperties === "number" ? root.minProperties : 0,
Math.min(...requiredByBranch.map((names) => names.length)),
);
return {
...root,
type: "object",
properties,
...(minProperties > 0 ? { minProperties } : {}),
...(required.length > 0 ? { required } : {}),
...(branches.every((branch) => branch.additionalProperties === false)
? { additionalProperties: false }
: {}),
};
};
const describeProperties = (
value: Readonly<Record<string, unknown>>,
): Record<string, unknown> =>