Skip to content

feat(mcp): keep compact input schemas within ten nesting levels - #2905

Closed
thefolahan wants to merge 4 commits into
morluto:mainfrom
thefolahan:fix/compact-schema-depth
Closed

thefolahan wants to merge 4 commits into
morluto:mainfrom
thefolahan:fix/compact-schema-depth

Conversation

@thefolahan

Copy link
Copy Markdown
Contributor

Summary

Fixes #2813. With REA_MCP_INPUT_SCHEMA_PROFILE=compact, every advertised input schema now stays within ten nesting levels, so clients whose model provider rejects deeper schemas (OpenCode in the report) can load REA's whole tool list. The default full profile is unchanged.

Problem and expected behavior

As @ylwl1997 noted on the issue, the compact profile bounded only serialized size, not depth. Measured on current main (7e3a19863) with the issue's own depth function (every JSON object and array level, data included, root at zero), after the compact profile expands references:

Tools Over 10 levels Deepest
full 193 25 31 (compare_web_captures)
compact before 193 17 17 (reconcile_javascript_runtime)
compact after 193 0 10

I left the full profile alone on purpose. #1005 once bounded its depth, and the later refactor in 63bf91405 chose complete producer schemas instead ("complete producer captures can exceed ten structural levels"). The compact profile is already the opt-in for strict clients, so it seemed the right place for this.

Change and scope

compactAdvertisedInputSchema keeps the inline presentation when it is within ten levels. Otherwise it applies capSchemaDepth and reports the new presentation "capped":

  • Every schema level that fits is kept unchanged. A subschema that would pass level ten is advertised as accepting any JSON value, using the explicit type list the profile already uses so Kimi does not infer string. When there is no room for that, the replacement moves up a level.
  • The advertisement only ever accepts more than the canonical schema, so no valid call is rejected by the client. Three keywords need care:
    • oneOf → anyOf when any alternative was widened. A widened alternative can make a value match two alternatives, which oneOf rejects.
    • not is left out rather than widened, because a wider not rejects more.
    • if, together with its then and else, is left out rather than widened, because a wider if applies then to more inputs.
  • The shallow "reduced" fallback is unchanged and still covers schemas that exceed the byte budget.

Exactly the 17 deep tools change, and each keeps its top levels instead of falling back to the shallow form. They also shrink, for example reconcile_javascript_runtime from 14,571 to 4,742 bytes and compare_wasm_interfaces from 14,296 to 4,876. The other 176 compact schemas are byte for byte identical. Canonical server-side validation is untouched, so a call that relies on the elided detail still gets the canonical typed error.

Contract and boundary impact

  • Semantic owner and earliest changed stage: advertised input presentation in src/contracts/compactInputSchema.ts, compact profile only.
  • CLI and MCP/tool-catalog contract: no change to the default catalog. Under compact, 17 input schemas lose detail below level ten. Output schemas, descriptions and annotations are identical.
  • Docs: docs/mcp-contracts.md (compact profile section) and an OpenCode note in docs/client-configuration.md. The profile's configuration error message mentions the depth limit.

Verification

Node 24.21.0 on macOS (Apple silicon):

  • src/contracts/compactInputSchema.test.ts: new depth-cap tests check every case against the original with Ajv 2020. Inputs the original accepts must stay accepted, while shallow structure (required fields, enums, additionalProperties: false) is still enforced. The not and if cases use inputs the original accepts only because a deep part fails to match. I checked that the tests catch regressions by reverting each rule in turn: disabling the oneOf → anyOf conversion fails the unit test and the existing real-catalog test that compact schemas accept every canonical example, and disabling the not/if drop fails both of its cases.
  • tests/boundary/mcp/compactInputSchemaMcp.test.ts: new check that every compact tool schema listed over an MCP transport is at most ten levels deep. The existing budget, validity and canonical-example checks pass.
  • src/contracts, src/config, tests/conformance/contracts, tests/boundary/mcp/toolSchemaValidity.test.ts: 173 passed. docs:check passes.
  • Current main does not compile (src/application/SupportedClients.ts, the new "devin" format missing from the format union), so the catalog build, toolSchemaValidity and docs:check above ran with a local, uncommitted one-word workaround for that line. tsc reports no errors in the changed files.

Not run: OpenCode itself, and the Kimi Code and Copilot client verifiers. @amikishiyev offered to rerun the depth script from the issue against a candidate, which would be a welcome external check.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T10:53:16.003972Z f481e68 New commits
ℹ️ About Codex in GitHub

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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no new blocking issue remains.

Summary

The compact profile now keeps advertised input schemas within ten nesting levels while leaving canonical server checks unchanged.

  • Compact tool schemas keep their detail within ten levels.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Canonical input schema] --> B{Compact profile?}
  B -->|No| C[Full advertisement]
  B -->|Yes| D[Strip annotations and expand references]
  D --> E{Within byte budget?}
  E -->|No| H[Shallow reduced advertisement]
  E -->|Yes| F{Within ten levels?}
  F -->|Yes| G[Inline advertisement]
  F -->|No| I[Cap depth without rejecting valid inputs]
  I --> J{Fits depth and byte limits?}
  J -->|Yes| K[Capped advertisement]
  J -->|No| H
  L[Incoming tool call] --> M[Canonical parser]
  M --> N[Tool operation]
Loading

Reviews (8) · Last reviewed commit: "fix(mcp): leave root dependency keywords..." · Reviewed by Greptile

Comment thread src/contracts/compactInputSchema.ts Resolved
Comment thread src/contracts/compactInputSchema.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 940a2696d4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +254 to +257
const narrowingWhenWidened: Readonly<Record<string, readonly string[]>> = {
not: ["not"],
if: ["if", "then", "else"],
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Drop maxContains when widening contains

When an array schema combines a depth-capped contains with maxContains, capSchemaDepth widens the matcher but this table leaves maxContains in place. For an array with one deep match and another element differing only below the cap, the canonical match count is one and accepted, while the advertised all-value matcher counts both and rejects for maxContains: 1; omit maxContains or the entire contains constraint when that child changes so the advertised schema remains a superset.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c4ca02a. When capping changes contains, maxContains is dropped too (minContains stays, since a wider contains only makes it easier to satisfy). The new regression case is an array with one item matching the original contains and another differing only below the cap: the original accepts it with maxContains: 1, and the capped schema now accepts it as well. The case fails if the rule is removed.

Comment on lines +277 to +279
return childDepth + ANY_JSON_VALUE_DEPTH <= maximum
? anyJsonValue()
: undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve annotations before replacing applicator branches

When a deep applicator branch contributes properties evaluation annotations to a sibling unevaluatedProperties: false, capChild can replace an intermediate allOf subtree here with a type-only schema. An object such as { foo: ... } then passes the canonical nested properties schema, but after capping no keyword marks foo as evaluated and unevaluatedProperties rejects it; retain that evaluation coverage or remove the affected unevaluated* constraint whenever capping erases annotations.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c4ca02a. unevaluatedProperties and unevaluatedItems now leave any schema object that capping changed, so removed or replaced parts cannot leave properties unmarked. That covers both a dropped if/then/else and an applicator branch replaced by an accepting schema. Unchanged maps and lists keep their identity, so only real changes count. There are two new regression cases, a dropped if whose then evaluated kind, and an allOf branch replaced at depth whose properties evaluated foo. Both inputs are accepted by the original and now by the capped schema, and both cases fail if the rule is removed. The real compact catalog is unchanged by this, since no current tool uses these keywords.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1dcd8afb18

ℹ️ About Codex in GitHub

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

out[key] = capped;
}
if (changed) drop(unevaluatedKeys);
return schemaTreeDepth(out, depth) <= maximum ? out : undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Normalize empty schemas after dropping negative keywords

When a depth-exceeding subschema consists only of not (or if/then/else), dropping those keys leaves out empty and this line returns {} after inlineWithinBudget has already performed its empty-schema normalization. This file notes that Kimi interprets {} as a string schema, so a canonical non-string value that was accepted because it failed the original not is rejected by the client even though AJV regards the capped schema as wider; convert newly empty results to anyJsonValue() (or return undefined so the parent does) before advertising them.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 97bfc56. When dropping not or if leaves a capped node empty, it now becomes the explicit any JSON value schema if it fits, and otherwise returns undefined so the parent replaces it. New test: a { not: <deep> } property is advertised as the full type list and still accepts 5 and a deep number. Reverting the change fails that test.

@morluto
morluto force-pushed the fix/compact-schema-depth branch from 1dcd8af to 1a21f33 Compare October 13, 2026 18:25

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a21f33c31

ℹ️ About Codex in GitHub

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

if (inline !== undefined) {
if (schemaTreeDepth(inline) <= COMPACT_INPUT_SCHEMA_MAX_DEPTH)
return { schema: inline, presentation: "inline" };
const capped = capSchemaDepth(inline, 0, COMPACT_INPUT_SCHEMA_MAX_DEPTH);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep root cap failures as widenings

When an under-budget root has a depth-exceeding literal in const or enum, capSchemaDepth leaves that data opaque and returns undefined here, which sends the schema to reduceToShallowProperties. If that object admits names through patternProperties while setting additionalProperties: false, the reduction drops patternProperties but retains additionalProperties: false; a canonical deep constant such as {x: ...} accepted by ^x$ is then rejected by the advertised schema. Make this fallback a widening, for example by dropping the closed-object constraint whenever its name applicators are omitted.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 97bfc56. reduceToShallowProperties now keeps additionalProperties: false only when the schema has no patternProperties, so the reduction stays a widening. New test: a root with patternProperties: { "^x$": {} }, additionalProperties: false and a deep enum literal falls back to reduced, stays open and accepts the canonical value. Reverting the change fails that test.

@morluto
morluto force-pushed the fix/compact-schema-depth branch from 1a21f33 to 672339a Compare October 13, 2026 18:41

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 672339acd6

ℹ️ About Codex in GitHub

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

Comment thread docs/client-configuration.md Outdated
Comment on lines +352 to +354
`"REA_MCP_INPUT_SCHEMA_PROFILE": "compact"` to the REA entry's environment and
restart OpenCode. Compact input schemas stay within ten levels; REA still
validates complete canonical inputs.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Exercise the depth cap through OpenCode before claiming support

Checked the added in-memory MCP boundary and the native verifier: the former stops at Client.listTools(), while scripts/verify-opencode-client.mjs:210-234 builds an OpenCode registration without REA_MCP_INPUT_SCHEMA_PROFILE=compact, so no actual OpenCode run exercises this new path or checks the converted tool.parameters depth. This newly documented workaround can therefore be published without establishing that OpenCode's provider-facing schema remains within ten levels; extend and run the native verifier in compact mode and assert that forwarded depth before making the compatibility claim.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed that the docs claimed more than was verified. I do not have OpenCode on this host, so I could not extend and run the native verifier honestly. In 97bfc56 the note now says that REA's MCP boundary tests keep every compact input schema within ten levels, and that the native OpenCode verifier does not yet run in compact mode, so the workaround is unconfirmed in an OpenCode session. I am happy to add a compact mode case to verify-opencode-client.mjs asserting forwarded parameter depth if you would like it in this PR, though someone with OpenCode would need to run it.

@morluto morluto added area: mcp MCP server, transport, and tool registration enhancement New feature or request labels Oct 14, 2026
@kaoru0822-kitauji kaoru0822-kitauji added the ci-fix-wip Claimed by the CI-fix track label Oct 14, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator

CI-fix track: I merged current main and resolved the conflicts (991b0d3). The failing Static checks, Source tests and shard jobs reflected main's state at the time.

  • Main (80de314) also bounds compact schemas at ten levels, by falling back to the reduced presentation. This PR's capped presentation sits between them: inline if it fits, otherwise capped if the capped form fits the budget, otherwise reduced. Main had a private duplicate (schemaDepth and COMPACT_SCHEMA_MAX_DEPTH); I removed it so the exported schemaTreeDepth and COMPACT_INPUT_SCHEMA_MAX_DEPTH are the single depth owner.
  • In the reduced projection, main drops dependentRequired (Gemini) and this PR keeps a closed object open when patternProperties is absent. Both are kept.
  • Main's does not reintroduce unsupported dialect keywords in reduced schemas test used a 13-level schema at 1500 bytes, which now caps instead of reducing. It now uses a 600-byte budget that the inline form exceeds, so it still checks the reduced path. The capped path is covered by this PR's tests.

Locally: src/contracts and the MCP compact/browser-comparison boundary tests pass (99, 3 skipped), and docs:check and check:fast are clean.

Clients whose model providers reject any tool schema deeper than ten
levels refuse the whole tool list, and the compact profile bounded only
size: 17 compact schemas still nested 11 to 17 levels after references
were expanded.

Compact schemas now keep every level that fits and advertise each
deeper subschema as accepting any JSON value. The result only widens:
a oneOf with a widened alternative becomes anyOf, and a not or an if
with its then and else is left out rather than widened. The default
full profile is unchanged.

Fixes morluto#2813
A widened contains could count more matches than maxContains allows,
and a dropped if or a replaced applicator branch stopped marking
properties as evaluated for a sibling unevaluatedProperties. Drop
maxContains when contains changes, and unevaluatedProperties and
unevaluatedItems from any schema object capping changed. Unchanged maps
and lists keep their identity so only real changes count.
Main now keeps dependentRequired and dependencies out of reduced compact schemas because some clients reject them. The capped tier sits before reduced, so it drops the same root keywords. Dropping a constraint only widens the schema, so capping stays a strict widening.
@thefolahan
thefolahan force-pushed the fix/compact-schema-depth branch from 991b0d3 to f481e68 Compare October 15, 2026 10:42

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f481e681ca

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

).toEqual([]);
});

it("advertises every tool input schema within the client nesting limit", async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fold the duplicate depth test into the existing boundary case

The immediately preceding test already starts the same compact server, lists the same catalog, and rejects every schema for which the locally defined schemaDepth(inputSchema) > 10; that helper is behaviorally identical to schemaTreeDepth, and the literal bound is the exported constant's value. This case therefore repeats the full boundary setup without adding a failure mode, so use the exported helper/constant in the preceding assertion instead of retaining a second catalog pass.

AGENTS.md reference: AGENTS.md:L23-L23

Useful? React with 👍 / 👎.

Comment on lines +464 to +468
const {
dependencies: _dependencies,
dependentRequired: _dependentRequired,
...presented
} = capped;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Normalize after dropping root dependency keywords

When a depth-capped schema has only a root dependencies entry (for example, a deep dependency schema whose valid input is {}), capSchemaDepth normalizes before this block and returns a nonempty object, but this later destructuring reduces it to {}. This file records that Kimi infers {} as a string schema, so the valid object is rejected client-side; normalize presented to anyJsonValue() (or fall back) before returning it. Fresh evidence beyond the resolved child case is that this newly added root-keyword removal runs after the empty-schema check.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

Comment thread docs/mcp-contracts.md
Comment on lines +748 to +749
deeper schema keeps every level that fits, and each subschema below that is
advertised as accepting any JSON value. The result only ever accepts more

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reconcile the conflicting deep-schema descriptions

This new paragraph says a deep schema retains every level that fits, but the immediately preceding bullet still says every schema deeper than ten uses the shallow reduced projection. compactAdvertisedInputSchema now returns the "capped" presentation when possible, so these statements describe mutually exclusive contracts and leave users unable to tell whether nested constraints survive; remove the stale bullet or limit it to the actual reduced fallback.

Useful? React with 👍 / 👎.

@thefolahan

Copy link
Copy Markdown
Contributor Author

I rebased this branch onto current main and force pushed it (head f481e681c), because main had moved on since the merge in 991b0d3 and the pull request was conflicting again. Thank you @kaoru0822-kitauji for the earlier merge; the rebase keeps the same resolution choices.

How the conflicts were resolved:

  • 80de314 added schemaDepth and COMPACT_SCHEMA_MAX_DEPTH to compactInputSchema.ts. They measure depth the same way as this branch's schemaTreeDepth and COMPACT_INPUT_SCHEMA_MAX_DEPTH, so I kept a single helper and a single constant rather than two.
  • dependentRequired stays out of the reduced form, as main now requires.
  • The profile description in mcpInputSchemaProfile.ts keeps this branch's wording, which names the ten level limit; the new compactPresentationForMcpInputSchemaProfile from main is unchanged.

One new commit, f481e68: the test added in 204b9f3 ("does not reintroduce unsupported dialect keywords in reduced schemas") expected a schema twelve levels deep to fall back to reduced. With this branch it is caught by the capped tier first, and that tier still carried the root dependentRequired. In production presentInputJsonSchema removes it before compaction, so no advertised tool was affected, but the compactor itself should keep the guarantee the test describes. The capped tier now leaves out root dependentRequired and dependencies as well. Dropping a constraint only widens the schema, so capping remains a strict widening. The test now expects capped and checks the same two properties.

Verified on Node 24 after npm run compile and npm run artifacts:mcp-catalog: tsc --noEmit is clean, and src/contracts, src/config and tests/boundary/mcp pass (950 passed, 8 skipped). The commit hooks passed as well.

@morluto

morluto commented Oct 25, 2026

Copy link
Copy Markdown
Owner

Closed as superseded by main commit 80de3145e458474319f160d2d2c09586e7a282a4. The compact input-schema builder now caps expanded schema trees at ten levels; the advertised-catalog boundary test checks every tool schema, and docs describe the limit. See compactInputSchema.ts, compactInputSchemaMcp.test.ts, and mcp-contracts.md. This is a source-derived comparison; no new client runtime verification was performed.

@morluto morluto closed this Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: mcp MCP server, transport, and tool registration enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

inputSchema nesting depth exceeds 10 on 24 tools (max 19: compare_web_captures) — breaks strict-depth MCP clients

3 participants