fix(kosong,agent-core-v2): hoist type into anyOf/oneOf branches #2662
🦋 Changeset detected
Latest commit: 0f8a3d0305b017fc0c1971ffe4fbb88425b39b0f
The changes in this PR will be included in the next version bump.
<details><summary>This PR includes changesets to release 1 package</summary>
| Name | Type |
| ---------------------- | ----- |
| @moonshot-ai/kimi-code | Patch |
</details>
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR%3A%20hoist%20type%20into%20anyOf%2FoneOf%20branches%0A)
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@0f8a3d0
npx https://pkg.pr.new/@moonshot-ai/kimi-code@0f8a3d0
_commit: <a href="https://github.com/MoonshotAI/kimi-code/runs/93492125921"><code>0f8a3d0</code></a>_
<sub><sub>!P1 Badge</sub></sub> Move v2 helper comments into the file header
In the v2 package, comments are required to live only in the top-of-file block and not beside functions or statements; this new helper-level docblock adds implementation explanation next to hoistCombinatorTypes. Please fold the necessary role-level context into the existing file header or remove it so the file stays within the documented comment convention.
AGENTS.md reference: packages/agent-core-v2/AGENTS.md:L15-L19
Useful? React with 👍 / 👎.
<sub><sub>!P2 Badge</sub></sub> Preserve parent type on skipped combinator branches
When an anyOf/oneOf branch already has its own type or a skip key such as not, this loop does not copy the parent's type into that branch but still deletes the parent type. For schemas like { type: 'object', anyOf: [{ type: 'string' }, { not: { const: null } }] } (the pattern added in the new tests), the normalized schema starts accepting strings/non-null primitives even though the original only permitted objects, so the tool schema sent to Kimi can advertise or validate arguments outside the MCP tool's contract; preserve the parent constraint for every branch, or only delete it once all branches carry an equivalent constraint.
Useful? React with 👍 / 👎.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f529a7d27e
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
</details>
@sailist PTAL when you get a chance — you know this normalizer best, so I'd value a sanity check on the root-flattening trade-off (a root union can't be expressed on the wire, so it widens into one object schema and leaves the exactly-one-of intent to the MCP server). Happy to rework it if you'd prefer a different shape.
Thanks for the thorough fix — the normalizer gap is real, and the wire-log replay validation is solid.
One consequence of the flattenRootUnion approach is worth spelling out explicitly: the wire schema is widened, so the "exactly one of" constraint survives only in whatever prose the tool author happened to put in the root description. Branch-level descriptions and the variant structure itself are dropped, and nothing synthesizes a replacement. For tools with a thin or vague description, the model is left guessing among the merged properties, and the only remaining guard is the MCP server rejecting invalid combinations — which turns schema precision into extra failed tool-call round-trips. That is an acceptable trade-off to unbrick the CLI, but it is a real cost.
If you are open to it, there is a more complete version of this fix: while flattening, synthesize the lost variant information back into the schema description (e.g. enumerate each branch's required/optional fields as text — "Variant 1: filename + content; Variant 2: filename + source_url; Variant 3: source_file_id"), so the model keeps full guidance even when the original description says nothing about the variants. Happy to help sketch the details if that sounds worthwhile.
Thanks — you were right that the cost is real, and worse than I had assumed: in the Notion tool the open first branch forces source_url and source_file_id out of properties entirely (constraining them would narrow the open branch), so the model could not see two of the three variants' key fields at all.
Implemented your suggestion. Flattening now restates the variant structure in the description — the valid field combinations, plus the names and descriptions of fields that had to be dropped:
Provide exactly one of content for inline UTF-8 text, source_url for a direct HTTPS download, …
Valid argument variants (at least one must match): (1) required: filename, content; optional: content_type. (2) required: filename, source_url; optional: content_type. (3) required: source_file_id.
Fields without their own schema entry:
- source_url — A direct, publicly reachable HTTPS URL from which Notion can download the file within one minute. …
- source_file_id — The ID of a file upload this exact integration already created, …
It appends after whatever the tool author wrote, says "exactly one" for oneOf and "at least one" for anyOf, and is skipped when there is nothing to disambiguate (a single branch, or a branch that accepts any object). Tests cover the wording, the dropped-field list, and the skip cases; squashed into the same commit.
wait for it
@sailist gentle ping on this one, and sorry for the nudge — I know review time is scarce.
The variant-restating change you suggested is pushed (squashed into fix(kosong,agent-core-v2): accept MCP tool schemas with union roots), and CI is green. Your read on the trade-off was sharper than mine, so I would rather have you look again than assume I got the shape right — the description wording, the "exactly one" vs "at least one" split, and the skip conditions are all still open to change.
No rush at all, and if someone else is a better fit to review this area, I am happy to redirect it.
The published Walle/MFJS compatibility table currently marks oneOf and allOf as unsupported. Is production using a newer dialect?
This narrates implementation details. Could we keep the module header focused on responsibility?
No inline comments; see AGENTS.md.
HelloWorldU
vinlee19
<!-- Per CONTRIBUTING: clear, reproducible bug fix with a focused diff — full analysis in the linked issue. -->
Related Issue
Resolve #2661 — bug: 400 "not a valid moonshot flavored json schema" when an MCP tool schema declares
typenext toanyOfProblem
The tool validator enforces two rules on
tools.function.parameters— no node may declaretypebesideanyOf/oneOf, and the root must carrytype: "object". Both were hit against the live endpoint:Together they leave a root-level union unrepresentable on the wire: moving the root
typeinto the branches satisfies the first rule and then trips the second.The whole
tools[]array is validated per request, so one MCP tool publishing a (perfectly valid) root-level union makes every prompt fail immediately with a non-retryable error — the CLI becomes unusable in any workspace that loads that server. This is happening in the wild: the official Notion MCP server started publishing such a root fornotion-create-attachmentaround 2026-08-04 (captured wire logs show a plain object root through 08-03 and the union root from 08-05).Kimi Code forwards MCP
inputSchemaverbatim, andnormalizeKimiToolSchematreated the root as a container and skipped every combinator-bearing node, so nothing could repair the shape.derefJsonSchema's$refsibling-key merge can also synthesize it from a root-level$ref, so the exposure is not vendor-specific. Full timeline and analysis in the linked issue.What changed
normalizeKimiToolSchemagains two passes between$refdereferencing and type completion, in both copies of the normalizer (packages/kosong/src/providers/kimi-schema.tsand the agent-core-v2 dialect copy, kept logic-identical):flattenRootUnion. A root union flattens into a single typed object root without narrowing what the schema accepts (the wire schema may only widen — the MCP server performs the final validation): the root's own properties stay authoritative; a property defined differently across branches becomes a nestedanyOfof the distinct variants (deduplicated by canonical JSON); a property is omitted rather than pinned whenever any branch leaves it unconstrained — open additional properties, apatternPropertiesbag that may cover the key (no regex evaluation), or a typeless schema that type completion would pin to a fabricated type (bareenum/constschemas keep their value-implied type); a branch that accepts any object (true,{}, a baretype: "object") drops the branch-derived constraints entirely;requiredkeeps the root's own list plus fields required by every branch, minus anything no longer inproperties(arequirednaming an absent property is itself rejected by the validator). The guarantee covers this step: the root's own property schemas keep whatever the long-standing type-completion pass does to them, union or not.properties. Without it the model is left guessing among merged fields with only the MCP server's rejection as a guard, which turns schema precision into failed tool-call round-trips. For the Notion tool this reads:hoistCombinatorTypes(nestedanyOfwithout a siblingtypeis accepted by the validator): the parenttypemoves into the union branches and is dropped from the parent, preserving the constraint on every branch — typed branches narrow to the type intersection (foldinginteger ⊂ number); enum/const members are judged individually as values, filtering unsatisfiable ones (enum: [1, 1.5]under anintegerparent becomesenum: [1]) and splitting a mixed-type enum into one typed variant per value type;truebranches become the bare parent constraint; dead branches, explicitfalsebranches, and any other non-schema member are dropped, and a union left with no live branch is removed so the node relaxes to its parent constraint (neitheranyOf: []nor a boolean member is legal).Tests (written first, observed failing): unit coverage for both passes in
packages/kosong/test/providers/kimi-schema.test.tsandpackages/agent-core-v2/test/kosong/provider/kimi-schema.test.ts(the v2 copy previously had no dedicated coverage), plus an AJV differential suite asserting that every object the original schema accepts is still accepted after flattening.Verification: replayed all 102 tool schemas captured from a failing real session against the strict rules above — conforming typed object roots, no
typebeside a combinator, no empty or boolean union members, norequirednaming an absent property, no mixed-typeenum— 0 violations. The two new passes act on exactly 1 of the 102 (the rest carry neither a root union nor atypebeside a combinator, so they reach the type-completion pass untouched); full kosong suite,typecheckon both packages,lint:imports, and oxlint all pass. Verified live against the Moonshot endpoint with the affected MCP server connected: prompts complete normally instead of returning 400.Checklist
gen-changesetsskill, or this PR needs no changeset. (changeset added: patch for@moonshot-ai/kimi-code)gen-docsskill, or this PR needs no doc update. (bug fix, no doc change needed)