← Back to Pull requests

fix(kosong,agent-core-v2): hoist type into anyOf/oneOf branches #2662

Open
vinlee19 opened this pull request with 2552 lines diff across 5 files
View on GitHub
vinlee19 vinlee19 commented on Aug 05, 2026 15:34 UTC
Author

<!-- 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 type next to anyOf

Problem

The tool validator enforces two rules on tools.function.parameters — no node may declare type beside anyOf/oneOf, and the root must carry type: "object". Both were hit against the live endpoint:

Error: [provider.api_error] 400 tools.function.parameters is not a valid moonshot flavored json schema,
details: <At path 'root': when using anyOf, type should be defined in anyOf items instead of the parent schema>

Error: [provider.api_error] 400 tools.function.parameters.type is required and must be "object"

Together they leave a root-level union unrepresentable on the wire: moving the root type into 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 for notion-create-attachment around 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 inputSchema verbatim, and normalizeKimiToolSchema treated the root as a container and skipped every combinator-bearing node, so nothing could repair the shape. derefJsonSchema's $ref sibling-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

normalizeKimiToolSchema gains two passes between $ref dereferencing and type completion, in both copies of the normalizer (packages/kosong/src/providers/kimi-schema.ts and the agent-core-v2 dialect copy, kept logic-identical):

  • Root — 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 nested anyOf of the distinct variants (deduplicated by canonical JSON); a property is omitted rather than pinned whenever any branch leaves it unconstrained — open additional properties, a patternProperties bag that may cover the key (no regex evaluation), or a typeless schema that type completion would pin to a fabricated type (bare enum/const schemas keep their value-implied type); a branch that accepts any object (true, {}, a bare type: "object") drops the branch-derived constraints entirely; required keeps the root's own list plus fields required by every branch, minus anything no longer in properties (a required naming 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.

  • Restating what widening loses. A flattened root only shows a bag of merged properties, so flattening appends the variant structure to the tool description — the valid field combinations, plus the names and descriptions of fields that had to be dropped from 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:
  •   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 …
      - source_file_id — The ID of a file upload this exact integration already created …
      

  • Nested — hoistCombinatorTypes (nested anyOf without a sibling type is accepted by the validator): the parent type moves into the union branches and is dropped from the parent, preserving the constraint on every branch — typed branches narrow to the type intersection (folding integer ⊂ number); enum/const members are judged individually as values, filtering unsatisfiable ones (enum: [1, 1.5] under an integer parent becomes enum: [1]) and splitting a mixed-type enum into one typed variant per value type; true branches become the bare parent constraint; dead branches, explicit false branches, 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 (neither anyOf: [] nor a boolean member is legal).
  • Tests (written first, observed failing): unit coverage for both passes in packages/kosong/test/providers/kimi-schema.test.ts and packages/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 type beside a combinator, no empty or boolean union members, no required naming an absent property, no mixed-type enum — 0 violations. The two new passes act on exactly 1 of the 102 (the rest carry neither a root union nor a type beside a combinator, so they reach the type-completion pass untouched); full kosong suite, typecheck on 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

  • I have read the CONTRIBUTING document.

  • I have linked a related issue, or explained the problem above.

  • I have added tests that prove my feature works.

  • Ran gen-changesets skill, or this PR needs no changeset. (changeset added: patch for @moonshot-ai/kimi-code)

  • Ran gen-docs skill, or this PR needs no doc update. (bug fix, no doc change needed)
  • Diff: 2552 lines (+2531 / -21) across 5 files Reviewer: HelloWorldU Review duration: 91064m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.56) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 2552 lines diff across 5 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 5 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    14 items
    changeset-bot[bot] changeset-bot[bot] commented on Aug 05, 2026 15:34 UTC
    Bot

    🦋 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)

    pkg-pr-new[bot] pkg-pr-new[bot] commented on Aug 05, 2026 15:36 UTC
    Bot

      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>_

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Aug 05, 2026 15:38 UTC
    Code Review
    packages/agent-core-v2/src/kosong/provider/providers/kimi/kimi-schema.ts:1
    @@ -119,10 +125,44 @@ function ensureKimiPropertyTypes(schema: Record<string, unknown>): Record<string
           'JSON Schema root must normalize to an object.',
         );
       }
    +  // Hoist before type completion so a typeless branch inherits the parent's
    +  // authoritative type instead of a structurally inferred fallback.
    +  hoistCombinatorTypes(normalized);
       recurseSchema(normalized);
       return normalized;
     }
     
    +/**
    + * Repair schema nodes that declare `type` next to `anyOf`/`oneOf`: copy the
    + * parent `type` into each branch that has no `type` of its own (and no
    + * combinator keywords), then drop it from the parent. Semantics are
    + * preserved — the parent constraint applied to every union branch anyway.

    <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 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Aug 05, 2026 15:38 UTC
    Code Review
    packages/kosong/src/providers/kimi-schema.ts:1
    @@ -128,10 +136,44 @@ function ensureKimiPropertyTypes(schema: Record<string, unknown>): Record<string
       if (!isRecord(normalized)) {
         throw new Error('JSON Schema root must normalize to an object.');
       }
    +  // Hoist before type completion so a typeless branch inherits the parent's
    +  // authoritative type instead of a structurally inferred fallback.
    +  hoistCombinatorTypes(normalized);
       recurseSchema(normalized);
       return normalized;
     }
     
    +/**
    + * Repair schema nodes that declare `type` next to `anyOf`/`oneOf`: copy the
    + * parent `type` into each branch that has no `type` of its own (and no
    + * combinator keywords), then drop it from the parent. Semantics are
    + * preserved — the parent constraint applied to every union branch anyway.
    + * Unlike type completion this pass also visits the root: MCP servers may
    + * publish such roots directly, and `derefJsonSchema`'s sibling-key merge can
    + * synthesize them from a root-level `$ref`.
    + */
    +function hoistCombinatorTypes(node: Record<string, unknown>): void {
    +  for (const key of TYPE_HOISTING_COMBINATOR_KEYS) {
    +    const branches = node[key];
    +    if (!hasOwn(node, 'type') || !Array.isArray(branches)) continue;
    +    for (const branch of branches) {
    +      if (
    +        isRecord(branch) &&
    +        !hasOwn(branch, 'type') &&
    +        !hasAnyKey(branch, TYPE_COMPLETION_SKIP_KEYS)
    +      ) {
    +        branch['type'] = cloneJsonValue(node['type']);
    +      }
    +    }
    +    delete node['type'];

    <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 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Aug 05, 2026 15:38 UTC
    Reviewer

    💡 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

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • 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>

    vinlee19 vinlee19 commented on Aug 06, 2026 04:57 UTC
    Author

    @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.

    sailist sailist commented on Aug 06, 2026 10:39 UTC
    Contributor

    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.

    vinlee19 vinlee19 commented on Aug 06, 2026 14:42 UTC
    Author

    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.

    silentsiri silentsiri commented on Aug 09, 2026 17:04 UTC
    Contributor

    wait for it

    vinlee19 vinlee19 commented on Aug 10, 2026 02:42 UTC
    Author

    @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.

    HelloWorldU HelloWorldU commented on code on Aug 10, 2026 12:05 UTC
    Code Review
    packages/kosong/src/providers/kimi-schema.ts:1
    @@ -44,6 +44,12 @@ const TYPE_COMPLETION_SKIP_KEYS = new Set([
       'then',
     ]);
     
    +// Moonshot rejects `type` declared next to `anyOf`/`oneOf` ("type should be
    +// defined in anyOf items instead of the parent schema"). `allOf` is not
    +// listed: a conjunction branch carrying the parent type is redundant, and the
    +// validator accepts `type` next to `allOf`.
    +const TYPE_HOISTING_COMBINATOR_KEYS = ['anyOf', 'oneOf'] as const;

    The published Walle/MFJS compatibility table currently marks oneOf and allOf as unsupported. Is production using a newer dialect?

    HelloWorldU HelloWorldU commented on code on Aug 10, 2026 12:20 UTC
    Code Review
    packages/agent-core-v2/src/kosong/provider/providers/kimi/kimi-schema.ts:1
    @@ -1,9 +1,14 @@
     /**
      * `kosong/provider` domain — Kimi tool-schema dialect normalization.
      *
    - * Pure functions: dereference local `$ref` pointers by inlining definitions,
    - * then complete missing `type` fields from enum/const values or structural
    - * keys — the schema dialect the Kimi tool endpoint accepts.
    + * Pure functions that rewrite a tool's JSON Schema into the dialect the Kimi
    + * tool endpoint accepts — provider-compatibility normalization, not a
    + * general-purpose schema compiler: local `$ref` pointers are inlined, the
    + * parameters root (which Moonshot requires to be a typed object) flattens
    + * `anyOf`/`oneOf` unions into one object schema, a `type` declared next to a
    + * nested `anyOf`/`oneOf` (a shape Moonshot rejects) is folded into the union
    + * branches, and missing or value-contradicting `type` fields are repaired
    + * from enum/const values or structural keys.

    This narrates implementation details. Could we keep the module header focused on responsibility?

    HelloWorldU HelloWorldU commented on code on Aug 10, 2026 12:20 UTC
    Code Review
    packages/agent-core-v2/src/kosong/provider/providers/kimi/kimi-schema.ts:1
    @@ -119,10 +126,367 @@ function ensureKimiPropertyTypes(schema: Record<string, unknown>): Record<string
           'JSON Schema root must normalize to an object.',
         );
       }
    +  flattenRootUnion(normalized);
    +  hoistCombinatorTypes(normalized);
       recurseSchema(normalized);
       return normalized;
     }
     
    +function flattenRootUnion(root: Record<string, unknown>): void {
    +  const variants: VariantEntry[] = [];
    +  let flattened = false;
    +  let exclusive = true;
    +  for (const key of TYPE_HOISTING_COMBINATOR_KEYS) {
    +    const value = root[key];
    +    if (!Array.isArray(value)) continue;
    +    flattened = true;
    +    if (key === 'anyOf') exclusive = false;
    +    for (const branch of value) {
    +      if (mayAcceptAnyObject(branch)) {
    +        variants.push({ kind: 'any' });
    +      } else if (isObjectBranch(branch)) {
    +        variants.push({ kind: 'object', schema: branch });
    +      }
    +      // Anything else cannot match an object and contributes nothing.
    +    }
    +    delete root[key];
    +  }
    +  if (!flattened) return;
    +  // One unrestricted variant means no branch-derived constraint can be
    +  // imposed on the root: for `anyOf` the union accepts any object, and for
    +  // `oneOf` it makes the other variants invalid rather than more permissive —
    +  // widening is the only representable outcome either way.

    No inline comments; see AGENTS.md.

    Reviewers
    Assignees
    vinlee19 vinlee19
    Labels
    risk: low confidence: 89.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 55.9% (MEDIUM) · Higher = larger blast radius
    55.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.6% · Lower = rushed or shallow review
    89.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.8% · Safe to merge
    5.8%