Skip to content

fix(mcp): normalize schemars numeric formats in tool input schemas - #264

Merged
sambitcreate merged 5 commits into
mainfrom
feature/mcp-numeric-schema-formats
Sep 30, 2026
Merged

sambitcreate merged 5 commits into
mainfrom
feature/mcp-numeric-schema-formats

Conversation

@sambitcreate

Copy link
Copy Markdown
Owner

Summary

Rust MCP servers built with schemars put non-standard numeric formats (uint, uint8..uint128, int, int8..int128, float, double) on tool input schemas, and some providers reject tool definitions that carry them. This PR adds a pure normalizer that removes those formats at every nested position and keeps the integer width as minimum/maximum where the bound is an exact JSON number.

Source: pi-mcp-adapter #651.

What changed

  • Shared (main/services/mcp-tool-schema.ts): new normalizeMcpToolInputSchema. It recurses through properties, patternProperties, $defs, definitions, dependentSchemas, items (object or tuple), prefixItems, allOf/anyOf/oneOf, additionalProperties, not, if/then/else, and similar keywords.
    • 8/16/32-bit formats become full ranges. 64/128-bit and pointer-width unsigned formats get only minimum: 0. Float formats are dropped without adding bounds.
    • If the server already sets a tighter bound, that bound is kept.
    • Bounds are added only when the schema allows integer/number. A string field with a numeric format just loses the format.
    • Standard formats such as date-time and uri are left alone, and the input is never mutated.
  • Desktop (main/services/mcp.ts): McpManager.agentContextFor normalizes the schema passed to Type.Unsafe. That one path covers chats, Bots and scheduled tasks.
  • CLI (packages/cli/src/mcp.ts): createCliMcpPool().agentTools normalizes the same way. The per-call drift fence still compares against the raw inventory.
  • Left unchanged on purpose:
    • The subagent read and mutation paths already strip format through their structural allowlist (projectStructuralSchema). Normalizing there would change schema hashes and invalidate existing grants.
    • peer-response.ts validates the Aiden Remote protocol, not tool schemas.
  • Remote/native: no protocol, transcript or native-client change, so no iOS or Android impact.
  • Docs: added a plan doc and a row in docs/plans/README.md, a .memory/ note, and a papercut about the CLI type-check needing a build first.

Tests

  • main/services/mcp-tool-schema.test.ts (registered in test:mcp) uses realistic schemars 0.8 (draft-07, definitions, tuple items) and 1.x (2020-12, $defs, prefixItems) fixtures.
    • Oracle: strict Ajv rejects the raw schemas with "unknown format", then compiles the normalized ones and accepts or rejects boundary values.
  • CLI parity MCP test: the stdio fixture gains a uint32 field. The test checks the model-facing schema and that the raw inventory still carries the format.
  • Commands run:
    • npm run test:mcp: 117 pass
    • npm run type-check (root): clean
    • npx eslint on touched files: clean
    • packages/cli: npm run build && npm run type-check && npm test, all pass

Follow-ups

  • The subagent structural projection also drops $defs/$ref, so subagents see a flattened shape for schemars schemas that use references. Widening that projection needs a grant/schema-hash migration.

🤖 Generated with Claude Code

Rust MCP servers built with schemars emit non-standard numeric formats
(uint32, int8, uint, double, ...) that some providers reject in tool
definitions. Drop those formats at every nested subschema position and
keep exact integer-width ranges as minimum/maximum. Applied to the
model-facing schema on desktop and in the CLI; raw schemas stay the
drift and grant identity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@very-hermes-bot very-hermes-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Inline review — 1 finding(s) anchored to the diff. See the pinned summary comment for the overview.

Comment thread package.json Resolved
@very-hermes-bot

very-hermes-bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Hermes Review Bot

Confidence: 5

Engine: agy/gemini-3.8-flash-high
Review mode: medium
Head: 45f028d19963a0d8d313d7e162205dba933dfa1c
Generated: 2026-09-30T18:53:04+00:00
Reviews: 1

Summary

Normalizes non-standard numeric schema formats generated by Rust's schemars (uint, uint8..uint128, int, int8..int128, float, double) before passing tool schemas to model providers. The pure normalizer in main/services/mcp-tool-schema.ts traverses all subschema keywords iteratively using a worklist and WeakMap, dropping these non-standard formats and mapping exact 8/16/32-bit integer ranges into minimum/maximum constraints while clamping safely against existing bounds. Raw server schemas remain untouched for drift detection and subagent grant hashes. Maintainers should double-check that future schema transforms preserve this separation so that runtime drift fencing continues to compare against the server's raw catalog.

Confidence Score: 5/5

Fully traced and verified end-to-end: verified iterative worklist traversal against deep and cyclic schemas, inspected keyword classification for draft-07 and draft 2020-12 structures, verified integer boundary math, confirmed raw inventory preservation at call sites in desktop and CLI, and reviewed Ajv boundary test coverage.

📁 Important Files Changed
  • main/services/mcp-tool-schema.ts: Implements pure, iterative normalizeMcpToolInputSchema to strip schemars numeric formats and tighten minimum/maximum bounds without recursion depth limits.
  • main/services/mcp-tool-schema.test.ts: Tests strict Ajv compilation against draft-07 and 2020-12 schemars fixtures, range boundary enforcement, 2,000-level deep nesting, draft-07 dependencies, and raw schema immutability.
  • main/services/mcp.ts: Applies schema normalization to tool parameters in McpManager.agentContextFor for desktop chats, bots, and scheduled tasks.
  • packages/cli/src/mcp.ts: Applies schema normalization to tool parameters in createCliMcpPool().agentTools while keeping raw schemas for per-call drift detection.
  • package.json & scripts/ci-test-registry.json: Registers mcp-tool-schema.test.ts in test:mcp and the CI test registry.
  • packages/cli/tests/fixtures/mcp-stdio.mjs & packages/cli/tests/parity.test.mjs: Extends CLI stdio fixture with uint32 and asserts normalized parameters alongside raw inventory preservation.
  • docs/plans/README.md, docs/plans/mcp-numeric-schema-formats-plan.md, & .memory/mcp-numeric-schema-formats.md: Tracks implementation rationale, structural allowlist separation for subagents, and memory history.

Findings

No findings.

📊 Sequence Diagram

Unchanged or not applicable for this change.

Machine-Readable Findings

[]

Last reviewed commit: 45f028d19963
Reviews (1) · Comment /hermes review to trigger a new review · /hermes review full for full re-review

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

Important

Draft-07 schema-valued dependencies entries bypass normalization, leaving provider-hostile numeric formats in some valid tool schemas.

Reviewed changes This review covers the initial implementation of MCP numeric schema normalization across the desktop and CLI model-facing MCP tool paths.

  • Schema normalization. Adds a pure walker that removes mapped non-standard numeric formats and preserves representable integer bounds.
  • Desktop and CLI integration. Normalizes schemas only for model consumption while retaining raw schemas for drift and identity checks.
  • Tests and documentation. Adds Ajv compatibility and boundary coverage plus CLI parity assertions, and records the change in the MCP test script, plan docs, and project memory.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Luna | 𝕏

Comment thread main/services/mcp-tool-schema.ts Resolved

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

✅ No new issues found.

Reviewed changes Incremental review of c8b3114b — the delta since the prior pullfrog review at 401beb75. It fixes the previously flagged gap where Draft-07 schema-valued dependencies bypassed normalization.

  • Normalized Draft-07 schema-valued dependencies entries — "dependencies" now joins SUBSCHEMA_MAP_KEYWORDS, so numeric formats inside dependency schemas are stripped with their width bounds, while property-name dependency lists pass through unchanged. This closes the prior review finding.
  • Added a regression test with a real oracle — strict Ajv rejects the un-normalized form (unknown format "uint8"), and the normalized form enforces the retries range at both boundaries; the raw schema's immutability and the property-list form are pinned too.
  • Registered mcp-tool-schema.test.ts in the core-git CI lane, fixing two pre-existing alphabetical order violations in the same file.

Verified locally: focused schema tests 7/7, npm run test:mcp 118/118, npm run test:ci-policy 46/46, and the core-git lane validates with the new file registered. Also re-checked the untouched model-facing paths: the four Type.Unsafe call sites are covered (desktop and CLI normalize; the subagent read/mutation sites receive schemas already projected through the format-stripping structural allowlist), so no other path leaks schemars formats to the model.

Pullfrog  | View workflow run | Using GLM Flash | 𝕏

@pullfrog

pullfrog Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Pullfrog stalled

The agent stopped emitting events for 120s and was killed by the activity-timeout watchdog. The model produced no output at all before the stall — the request was sent but nothing came back. This is usually transient; re-running often succeeds.

Recent agent stderr
timestamp=2026-09-27T17:43:05.097Z level=ERROR run=7127138c message="stream error" providerID=opencode-go modelID=glm-5.3-flash session.id=ses_f1c097011ffeaMdjljm80h9p3B small=false agent=build mode=primary error.error="AI_APICallError: Go usage limit exceeded"

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using GLM Flash | 𝕏

@pullfrog

pullfrog Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Pullfrog stalled

The agent stopped emitting events for 125s and was killed by the activity-timeout watchdog. The model produced no output at all before the stall — the request was sent but nothing came back. This is usually transient; re-running often succeeds.

Recent agent stderr
timestamp=2026-09-27T17:52:01.665Z level=ERROR run=e0a88da7 message="stream error" providerID=opencode-go modelID=glm-5.3-flash session.id=ses_f1c0140c7ffeRr86EWI1rBirXV small=false agent=build mode=primary error.error="AI_APICallError: Go usage limit exceeded"

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using GLM Flash | 𝕏

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

Important

A wide, valid-size remote schema can make the new worklist allocate millions of queue entries synchronously in Electron's main process.

Reviewed changes This incremental review covers changes since c8b3114b: the recursive 64-level cutoff was replaced with iterative normalization, and a deep-schema regression test was added.

  • Removed the depth cutoff. Replaced recursive traversal with a WeakMap-backed worklist and added coverage for 2,000 nested schema levels.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Luna | 𝕏

if (existing) return existing;
const target: Record<string, unknown> = {};
copies.set(source, target);
pending.push({ source, target });

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.

MCP servers control these schemas, and the desktop's 8 MiB response limit still permits millions of tiny subschemas. This worklist retains a { source, target } record for each child before draining the queue, which can substantially amplify memory use and synchronously stall or crash the main process.

Technical details
# Bound work queued from remote schemas

## Affected sites
- `main/services/mcp-tool-schema.ts:102` — each discovered schema object adds a retained queue record.
- `main/services/mcp-tool-schema.ts:115-116` — array-valued keywords enqueue all children before the worklist drains.
- `main/services/mcp.ts:365-376` — the desktop applies this normalizer to server-provided tool schemas after transport-level byte limiting.

## Required outcome
- Enforce a schema-node/work-queue budget and reject oversized schemas before model registration; never forward a partially normalized schema.

# Conflicts:
#	docs/plans/README.md
@sambitcreate
sambitcreate merged commit 45e09a9 into main Sep 30, 2026
24 checks passed
@sambitcreate
sambitcreate deleted the feature/mcp-numeric-schema-formats branch September 30, 2026 20:42
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.

2 participants