Skip to content

fix(tool-catalog): inline local $refs in tool input schemas - #6626

Merged
M4n5ter merged 4 commits into
rust-previewfrom
fix/anthropic-inline-schema-refs
Nov 4, 2026
Merged

M4n5ter merged 4 commits into
rust-previewfrom
fix/anthropic-inline-schema-refs

Conversation

@UncertaintyDeterminesYou4ndMe

@UncertaintyDeterminesYou4ndMe UncertaintyDeterminesYou4ndMe commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Endpoints such as Kimi K3 (moonshot Chat Completions, moonshot-global Responses, and kimi-coding-plan Anthropic / Chat Completions) do not resolve $ref inside tool input_schema definitions. When a tool such as SessionCreate references $defs (for example workspace), the model encodes the nested object argument as a JSON string instead of an object.

Instead of re-expanding schemas on every streaming step inside the Anthropic wire codec alone, maka-tool-catalog now inlines document-local JSON Pointer $refs once at admission (ToolCatalog::new, BoundTool::Input, and ToolSearch::definition):

  • Every wire protocol (anthropic-messages, chat-completions, and responses) receives self-contained schemas without per-step or per-retry tree cloning, and maka-agent-engine compaction estimates see the exact wire schema.
  • Pure annotations (title, description, default, examples, deprecated, readOnly, writeOnly, $comment) merge cleanly onto resolved targets without redundant allOf wrappers, while cross-boundary interacting keywords (unevaluatedProperties, unevaluatedItems, additionalProperties / items / contains / if / contentMediaType, sibling allOf, and embedded $id subresources), Projection::project request envelopes, RFC 6901 percent-encoded fragments, and Draft-07 dependencies preserve their exact validation semantics.
  • Recursive, anchor, and dynamic references retain only the definitions they still need, and $ref DAG expansion is bounded by materialized object count (65,536).

Verification

  • node scripts/ci.mjs run tooling (cargo fmt, Biome format, tooling tests, ASF license headers, dependency license audit): passed
  • node scripts/ci.mjs run product (maka-ui-build, bundle tests, reviewed notices): passed
  • cargo nextest run --locked -p maka-tool-catalog -p maka-provider-protocol -p maka-tools -p maka-agent-engine -p maka-python-runtime -p maka-product-native: passed
  • cargo nextest run --locked -p maka-agent-native (all tests, including wire-level SessionCreate schema assertion): passed
  • maka-cli unit and integration tests: passed

AI use

Select exactly one:

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: Claude Code (initial PR exploration and Anthropic schema prototype); Antigravity (catalog-boundary $ref inlining design, implementation, and tests).

Checklist

  • Tests cover the change and fail without it
  • Format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

Kimi's Anthropic-compatible endpoint does not resolve $ref. Given
SessionCreate's schema, where workspace is a $ref into $defs, K3.1 Pro
sent workspace as a JSON-encoded string; with the same schema inlined it
sent the object. Function tool schemas are now expanded before they are
sent. Recursive, external and anchor references stay as written along
with the root definitions, and a schema whose expansion would exceed
10,000 schema objects is sent unchanged.

Generated-by: Claude Code
A field's description or default next to its $ref now replaces the
target's annotation instead of wrapping the target in allOf, which an
endpoint that cannot resolve $ref may handle no better. Siblings that
depend on neighbouring keywords, such as additionalProperties, still
stay apart under allOf.

Generated-by: Claude Code

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

I reviewed all three changed files at a927d682351466a1a8e4cbae7d8c63274e979a8d. I found two P2 issues in the claim that tool-schema expansion preserves accepted inputs; both are detailed inline.

I compiled and ran this commit's actual, unmodified anthropic/schema.rs in an isolated Rust 1.99.1 harness with the repository's serde_json 1.0.154. An independent Draft 2020-12 validator rejects each counterexample against its original schema and accepts it against the actual expanded output. A local control that keeps the referenced schema and its siblings as separate allOf operands restores rejection for both cases while preserving the ordinary object-reference case. I did not change the PR branch.

I also read the production PreparedTools::build call site: expansion applies to every function tool on this adapter, while constrained_schema remains separate. The three new hosted schema tests passed in CI 41807836369, including actual prepared tools. They cover ordinary nesting, recursion/external-reference retention and the object-count budget, but not these semantic counterexamples. The same CI fails two native composer fixtures with executor of undefined, also present on its base after #6617; I am not attributing those failures to this schema change.

The actual Git merge against rust-preview at a08d327f19a0afd17dbe4c941123c06b4a46d871 succeeds. I did not call Kimi or another live Anthropic-compatible endpoint, reproduce the reported response-frequency comparison, or build the full workspace. The AI declaration and Generated-by: Claude Code trailer are present.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

},
resolved => {
let mut result = siblings;
result.insert("allOf".into(), Value::Array(vec![resolved]));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Preserve an existing sibling allOf instead of replacing it.

For {"$ref":"#/$defs/N","type":"integer","allOf":[{"maximum":5}],"$defs":{"N":{"type":"integer","minimum":0}}}, the colliding type selects this arm. insert("allOf", ...) overwrites the sibling maximum and produces {"type":"integer","allOf":[{"type":"integer","minimum":0}]}. I ran the actual Rust function: 9 is rejected by the original Draft 2020-12 schema and accepted by its output. Since this output becomes the function tool's input_schema, the provider loses a real restriction and can generate arguments the Host will reject. Keep both complete operands, or append without discarding the existing conjunction, and add an equivalence regression.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

.keys()
.all(|keyword| !resolved.contains_key(keyword)) =>
{
resolved.extend(siblings);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Disjoint keyword names do not make two schemas safe to flatten.

For {"$ref":"#/$defs/N","properties":{"extra":{"type":"string"}},"$defs":{"N":{"type":"object","additionalProperties":false}}}, the original referenced schema rejects {"extra":"x"}: N declares no properties. This branch merges the sibling properties into N, so additionalProperties:false now treats extra as declared and accepts it. I reproduced that change with the actual Rust function and an independent Draft 2020-12 validator. Preserve reference/sibling evaluation scopes, rather than flattening based only on key collisions; otherwise every Anthropic-compatible function request can advertise a different input contract.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

I reviewed the increment from a927d682 to 7903f75b1b5718f10bb59c0a96743e80d9706f36. Both previously reported P2 issues still reproduce at this head.

I reran the same two counterexamples by compiling the actual current anthropic/schema.rs, unmodified, under Rust 1.99.1 with serde_json 1.0.154. Independent Draft 2020-12 validation still changes from rejection to acceptance for both the lost allOf maximum and the referenced target's additionalProperties:false. A separate local control retaining the complete target and sibling operands as a conjunction rejects both and keeps the ordinary object-reference case valid. The new annotation handling and protection when the adjacent keyword is on the sibling side do not address these original cases; the current locations are inline.

I read CI 41817115082's actual provider test logs: prepared tools passed in 0.004 seconds, the schema expansion test in 0.005 seconds, and retained references/budget in 0.036 seconds. Its two failed CLI jobs still show the inherited #6617 composer fixture error, not a demonstrated consequence of this increment. The actual Git merge against rust-preview at a08d327f19a0afd17dbe4c941123c06b4a46d871 succeeds.

The revised PR description appropriately leaves unresolved whether Kimi's endpoint ignores references or its model mishandles them. Its new 10-call comparisons, Bot-tool schema sizes and Claude comparison remain the author's observations; I did not repeat those live requests. I also did not run the full workspace or a native desktop.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

Value::Object(resolved) if siblings.is_empty() => resolved,
resolved => {
let mut result = siblings;
result.insert("allOf".into(), Value::Array(vec![resolved]));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 still present at this head: preserve an existing sibling allOf instead of replacing it.

For {"$ref":"#/$defs/N","type":"integer","allOf":[{"maximum":5}],"$defs":{"N":{"type":"integer","minimum":0}}}, the colliding type selects this arm. insert("allOf", ...) overwrites the sibling maximum and produces {"type":"integer","allOf":[{"type":"integer","minimum":0}]}. I ran the actual Rust function: 9 is rejected by the original Draft 2020-12 schema and accepted by its output. Since this output becomes the function tool's input_schema, the provider loses a real restriction and can generate arguments the Host will reject. Keep both complete operands, or append without discarding the existing conjunction, and add an equivalence regression.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

Value::Object(mut resolved)
if siblings.keys().all(|keyword| {
ANNOTATIONS.contains(&keyword.as_str())
|| (!resolved.contains_key(keyword) && !ADJACENT.contains(&keyword.as_str()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 still present: the adjacency check needs to account for the target as well as the siblings.

The new guard checks ADJACENT only for sibling keys. In the original counterexample the sibling key is properties, while additionalProperties belongs to the resolved target, so this guard still flattens them.

For {"$ref":"#/$defs/N","properties":{"extra":{"type":"string"}},"$defs":{"N":{"type":"object","additionalProperties":false}}}, the original referenced schema rejects {"extra":"x"}: N declares no properties. This branch merges the sibling properties into N, so additionalProperties:false now treats extra as declared and accepts it. I reproduced that change with the actual Rust function and an independent Draft 2020-12 validator. Preserve reference/sibling evaluation scopes, rather than flattening based only on key collisions; otherwise every Anthropic-compatible function request can advertise a different input contract.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

Move document-local JSON Pointer `$ref` inlining from the Anthropic wire
adapter to `maka-tool-catalog` admission (`ToolCatalog::new`,
`BoundTool::Input`, and `ToolSearch::definition`):

- Cover every wire protocol (`anthropic-messages`, `chat-completions`, and
  `responses`) once at catalog admission without per-step re-expansion, and
  keep context compaction token estimates aligned with the wire schema.
- Preserve JSON Schema validation semantics across sibling `allOf` arrays,
  `unevaluatedProperties` / `unevaluatedItems`, embedded `$id` subresources,
  `Projection::project` request envelopes, RFC 6901 percent-encoded fragments,
  and recursive / anchor / dynamic references while bounding only
  `$ref`-materialized DAG expansion.
- Update the terminal composer completion test fixture to match the structured
  `AgentBackendPreference` and `skills({ query, backend })` contract from #6617.

Generated-by: Antigravity
@M4n5ter M4n5ter changed the title fix(anthropic): inline local $refs in tool input schemas fix(tool-catalog): inline local $refs in tool input schemas Nov 4, 2026
@M4n5ter
M4n5ter merged commit 0a46419 into rust-preview Nov 4, 2026
@M4n5ter
M4n5ter deleted the fix/anthropic-inline-schema-refs branch November 4, 2026 12:44

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

I reviewed the final nine-file diff at 157a41a5f61806936bd3a255002ea140aa28d076, separating the catalog rewrite from the merge of #6628. Both previously reported P2 counterexamples are fixed, but there is a different P2 for declared Draft-07 schemas, detailed inline.

Normalization now happens at ToolCatalog::new, dynamically bound BoundTool::Input schemas and ToolSearch definitions, rather than only in the Anthropic adapter. The admitted definition and its validator therefore share the normalized schema, and other wire protocols and request estimates see it as well. The new conjunction handling preserves the old allOf and target additionalProperties examples. Annotation overrides, embedded resources, retained references and the 65,536 materialized-object budget are handled in the new module.

I compiled the actual unmodified final input/inline.rs under Rust 1.99.1 with serde_json 1.0.154. The two original counterexamples remain rejected after expansion and the ordinary object remains accepted. Two declared Draft-07 examples instead change from accepted to rejected. Both the repository's jsonschema 0.60.1, configured with the catalog's offline/no-format options, and an independent Python validator confirm those results. A conservative local control retaining the original declared Draft-07 schema preserves acceptance without undoing the two verified Draft 2020-12 repairs. This is a validation-semantics problem at catalog admission, not evidence of a provider misreading the schema.

This change has already merged as 0a46419ef6331cbeb6429d362bf9944de40f9377; the new module is byte-identical in current rust-preview at 89e7dcdaf070566f511f4b8d99239b9a944d2993. Final-head CI 41831357297 fails the external-agent consent UI wait introduced in #6628; its log matches that workflow's own failing run, rather than demonstrating a schema-rewrite failure. I did not run the complete workspace, live model comparisons or an end-to-end performance benchmark.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

self.expanding.push(pointer.into_owned());
let resolved = self.schema(target, false, true);
self.expanding.pop();
Some(merge(resolved?, siblings))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Preserve the declared dialect's $ref semantics before merging siblings.

This unconditional merge applies adjacent assertions in Draft-07, where a $ref object ignores its siblings. For example:

{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"x":{"$ref":"#/definitions/N","maximum":5}},"definitions":{"N":{"type":"integer"}}}

{"x":9} is valid before normalization. The actual current inline_refs replaces the reference with {"type":"integer","maximum":5}, making that same input invalid. I reproduced the change using the repository's jsonschema 0.60.1 with the same offline/no-format options as ToolCatalog::new, as well as an independent Draft-07 validator. Since the new catalog constructs its executable-input validator from the normalized schema, this can reject formerly valid tool calls; it is not limited to wire presentation. The module is byte-identical in current rust-preview at 89e7dcda.

Track the active dialect when deciding whether siblings apply, or conservatively retain such older-dialect schemas. Include a declared Draft-07 object-input regression; the current Draft 2020-12 sibling tests do not cover this difference.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants