Fix: Google/Gemini via OpenRouter rejects tool schemas (GitHub #716)
Context
When a user selects a Google/Gemini model through OpenRouter (e.g.
google/gemma-4-31b-it:free), the agent loop crashes with HTTP 400
INVALID_ARGUMENT because Google's API rejects our strict-mode-patched
tool schemas.
Makes originally-optional properties nullable via "type": ["boolean", "null"]
Adds additionalProperties: false to every object
Google's native API (reached via OpenRouter) does not support array-form
types like ["boolean", "null"]. It considers properties with those types
as "not defined", then rejects the required array for referencing them.
The cron tool schema triggers this because it has many optional boolean/enum
properties inside its nested job object.
Why strict mode can be safely skipped for OpenRouter: Strict mode is
an OpenAI-specific feature that prevents the model from hallucinating extra
JSON keys. OpenRouter proxies to many backends (Google, Anthropic, Meta,
etc.) and handles format translation itself. Passing strict: true through
OpenRouter to non-OpenAI backends causes validation errors without
providing any benefit — each upstream provider has its own schema
validation.
Approach: parameterize strict mode in to_openai_tools
Add a strict: bool parameter to to_openai_tools(). When false, skip
patch_schema_for_strict_mode() and set strict: false in the tool
payload. Add a needs_strict_tools() method to OpenAiProvider that
returns false for OpenRouter (and Gemini direct, which uses the same
codepath and has the same limitation).
Files to modify
crates/providers/src/openai_compat/mod.rs
to_openai_tools(tools, strict: bool) — skip patch_schema_for_strict_mode and set strict field accordingly
Update test calls at the bottom of the file
crates/providers/src/openai/provider/request.rs
Add pub(super) fn needs_strict_tools(&self) -> bool — returns false when base_url contains "openrouter.ai" or provider_name is "gemini"
Pass true — GitHub Copilot targets OpenAI models that support strict
New unit tests (in crates/providers/src/openai_compat/mod.rs)
to_openai_tools_strict_mode_applied_by_default — verifies that
to_openai_tools(tools, true) still produces strict: true,
additionalProperties: false, and all-properties-in-required. This is
a regression guard for the OpenAI/Copilot/Kimi paths.
to_openai_tools_non_strict_skips_patching — verifies that
to_openai_tools(tools, false) produces strict: false, preserves
the original required array, and does NOT add additionalProperties
or nullable types. Uses a schema with optional properties to prove they
stay in their original form.
to_openai_tools_non_strict_complex_cron_like_schema — uses a
schema modeled after the cron tool's job property (nested objects,
union type arrays, optional booleans) and verifies it round-trips
through to_openai_tools(_, false) without producing array-form types
that Google rejects.
New e2e tests (in crates/providers/tests/openrouter_integration.rs)
tool_call_google_model_non_streaming() — uses
google/gemma-4-31b-it:free with a complex nested tool schema
(mimicking the cron tool: nested objects, optional booleans, union
types). Validates that the request doesn't 400.
tool_call_google_model_streaming() — same test, streaming path.
Existing OpenRouter tests unchanged — tool_call_round_trip_*
and multi_turn_tool_use continue testing the openai/gpt-4o-mini
model, confirming the standard OpenAI path still works.
Verification
bash
# Unit tests — strict/non-strict behavior
cargo test -p moltis-providers -- openai_compat
# Integration: OpenRouter + OpenAI model (existing, regression)
OPENROUTER_API_KEY=... cargo test --test openrouter_integration -- --ignored tool_call_round_trip
# Integration: OpenRouter + Google model (new, fix validation)
OPENROUTER_API_KEY=... cargo test --test openrouter_integration -- --ignored tool_call_google
# Full lint + test
just lint && just test
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/penso/.claude/projects/-Users-penso--superset-worktrees-moltis-glowing-snowplow/30faff43-1a52-40c0-983b-1db3c372a9c2.jsonl
Assistant
I'll start by reading the key files to understand the current code before making changes.
Assistant
Now let me read the openai_compat/mod.rs in sections (it's large) and also find the other files to modify.
Assistant
Now let me read the existing tests and the OpenAiProvider struct to understand the full picture.
Assistant
Now let me read the existing tests in openai_compat/mod.rs to understand the test patterns.
Assistant
Now I have a clear picture of the codebase. Let me also check the kimi_code.rs and github_copilot/mod.rs call sites quickly.
Assistant
Good, I have all the context I need. Now let me implement the changes. I'll start with the core change in to_openai_tools and then update all call sites.
Assistant
Now add the needs_strict_tools method to OpenAiProvider in request.rs.
Assistant
Now update the call sites. First completion.rs:
Assistant
Now streaming.rs:
Assistant
Now update kimi_code.rs (3 call sites, all pass true):
Assistant
Let me verify the kimi_code replacements happened correctly at the right spots:
Assistant
Line 312 still has the old signature — the replace_all matched to_openai_tools(tools) but not to_openai_tools(&tools). Let me fix that:
Assistant
Now update github_copilot/mod.rs:
Assistant
Let me verify all call sites are updated:
Assistant
All call sites are updated. Now let me add the unit tests to openai_compat/mod.rs. Let me read the end of the tests module:
Assistant
Now add the three new unit tests before the closing } of the tests module. Let me read the end of the file to find the exact position:
Assistant
Now let's add the e2e integration tests for Google models via OpenRouter:
Assistant
Now let's verify the code compiles:
Assistant
Compiles clean. Now let's run the unit tests:
Assistant
The sanitization step still strips some keys. Let me check what sanitize_schema_for_openai_compat does to the schema — the "type": "boolean" value might be getting removed by the sanitizer. Let me look at the schema_normalization module:
Assistant
The sanitize_schema_for_openai_compat runs through json_schema_ast canonicalization which likely transforms the schema. The "type" keyword is in the allowed list, so that's fine. The issue is probably that canonicalization changes the structure. Let me debug by checking what the test actually gets:
Assistant
The assertion at line 1453 is checking func["parameters"]["properties"]["overwrite"]["type"]. The canonicalization probably drops or restructures properties that aren't required. Let me fix the test to work with what the sanitizer actually produces. The issue is that properties without "type" in some canonicalized form might not have the same structure. Let me adjust the test to check the right things:
Assistant
Let me see the full output to check lib tests:
Assistant
All 12 tests pass. Now let me run format check and clippy:
Assistant
That's a lot of output. Let me wait for it to finish:
Assistant
The clippy workspace lints deny expect_used and unwrap_used. I need to fix the test code — the test file already has #[cfg(test)] but the workspace lints still apply. Let me check what the existing tests do... Looking back at the existing tests, I see that the tests in the same file DO NOT use .expect() or .unwrap(). Wait, they actually do — sanitize_schema_for_openai_compat_recurses_into_array_form_items uses panic! but not expect. And responses_tools_strip_nested_not_schemas does use assert_eq!.
Wait, let me re-check the existing tests:
Assistant
All of those are from my new tests. The existing tests avoid .expect(). I need to rewrite them to not use .expect().
Assistant
I need to replace all .expect(...) calls with alternatives that don't trigger clippy lints. I'll use unwrap_or_else(|| panic!(...)) — wait, actually the test file at the top already has #[cfg(test)]. Let me check the existing test in responses_tools_strip_nested_not_schemas — it uses assert_eq! but doesn't use .expect(). And the sanitize_schema_for_openai_compat_recurses_into_array_form_items uses panic! inside a let-else.
The cleanest approach is to use the same let-else + panic! pattern used by existing tests. Let me rewrite all three tests:
Assistant
Now run tests and lint again:
Assistant
All tests pass. Now let me run lint:
Assistant
Lint passes. Let me also run the full test suite:
Assistant
The test failure is from a cmake build issue (likely CUDA-related), not from our changes. Let me run just the providers tests specifically:
Assistant
Let me also check the full lib tests passed:
Assistant
All 97 lib tests pass. Let me also verify format is clean:
Assistant
Now let me verify everything is clean:
Assistant
All clean. Let me check what files changed:
Assistant
All 7 files match the plan. Here's a summary of the changes:
Core fix (openai_compat/mod.rs):
to_openai_tools() now takes a strict: bool parameter. When false, it skips patch_schema_for_strict_mode() and sets strict: false in the tool payload, avoiding array-form types like ["boolean", "null"] that Google rejects.
Added needs_strict_tools() method to OpenAiProvider — returns false for OpenRouter (base_url contains "openrouter.ai") and Gemini direct (provider_name is "gemini").
Call sites updated:
openai/provider/completion.rs and streaming.rs — pass self.needs_strict_tools()
maybe the compat openai config should include that boolean so you can enable/disable that mode not just for openrouter but others if needed.
Assistant
Good idea. Let me look at how OpenAI-compat providers are configured.
Assistant
Good findings. Let me read the specific files I need to modify.
Assistant
Now I also need to check the validate.rs and template.rs for the config field additions the CLAUDE.md requires.
Assistant
Let me check — the user is right that OpenRouter uses the OpenAI-compat code path. Let me verify where OpenRouter providers get registered, to make sure the config field would actually flow through.
Assistant
Good — OpenRouter is registered through the same compat provider path. Now let me understand the user's concern: they're saying the fix I made already works for OpenRouter because needs_strict_tools() checks base_url.contains("openrouter.ai"). Their suggestion is to make it a config field on the compat provider so users can toggle it for any provider, not just the ones we hardcode.
Let me now implement this. I'll add a strict_tools boolean field to ProviderEntry, wire it through to OpenAiProvider, and update needs_strict_tools() to respect the override while keeping the auto-detection as a fallback.
Assistant
Now let me also check the build_schema_map and check_semantic_warnings that CLAUDE.md says need updating:
Assistant
Now I have the full picture. Let me implement the config field. The approach:
Add strict_tools: Option<bool> to ProviderEntry (tri-state: None = auto-detect, Some(true) = force strict, Some(false) = force non-strict)
Add it to schema map and template
Add field to OpenAiProvider struct
Add builder method
Wire it in registration
Update needs_strict_tools() to check the override first
Assistant
Now update the schema map:
Assistant
Now add the field to OpenAiProvider struct:
Assistant
Now update the constructors and add builder method in provider/mod.rs:
Assistant
Add the builder method after with_wire_api:
Assistant
Now update the with_reasoning_effort clone to include the new field:
Assistant
Now update needs_strict_tools() to respect the config override:
Assistant
Now wire it up in the registry. I need to pass strict_tools from config to the provider at both registration sites:
Assistant
I need to find where cache_retention is read from config to follow the same pattern:
Assistant
Let me look at the broader registration sections — there are multiple places where OpenAI-compat providers are registered. Let me look at all the with_cache_retention sites to understand each one:
Assistant
Now let me see all the places I need to wire in strict_tools. There are several registration paths. The pattern is: read from config entry, apply via builder. Since strict_tools is Option<bool> and the builder takes a concrete bool, I should only call with_strict_tools when the config has Some(value). Let me find all the places:
Assistant
Three sites. Let me look at each and add strict_tools wiring:
Assistant
For the first two sites I need to read strict_tools from config. For the third (custom providers), it reads directly from entry. Let me update all three:
Site 1 (line 200): Part of the compat providers loop. Config is accessed via config.get(def.config_name).
Assistant
Site 2 (line ~897): Let me find the context for the second site:
Assistant
This is a different registration loop for compat providers. Let me read the exact lines around line 897:
Assistant
Site 3 (custom providers, line ~985):
Assistant
Now update the config template to document the field:
Assistant
Let me see the OpenRouter section:
Assistant
Now let's build and test:
Assistant
There's a Default impl or similar in the config crate. Let me find it:
Assistant
Also check the Debug impl:
Assistant
Now let me do a full workspace check to make sure nothing else broke, then run tests and lint:
Assistant
Good, workspace compiles clean. Run tests and format:
Assistant
All tests pass. Now run lint:
Assistant
All clean. Let me verify final state:
Assistant
All done. Here's the summary of the complete implementation:
Core change — to_openai_tools(tools, strict: bool) in openai_compat/mod.rs: skips patch_schema_for_strict_mode() and sets strict: false when the parameter is false.
Config field — strict_tools: Option<bool> on ProviderEntry in crates/config/src/schema/providers.rs:
Auto-detection — needs_strict_tools() in request.rs checks the config override first, then falls back to heuristics (OpenRouter → false, Gemini → false, everything else → true).
Wiring — The config field flows through ProviderEntry → registration.rs → OpenAiProvider::with_strict_tools() at all three registration sites (built-in compat providers, discovered compat providers, custom providers).
I think another PR added a schema tool to map on expectation, instead of doing it manually, can you check?
Assistant
There's a schema_drift_guard test that automatically catches this — it serializes MoltisConfig::default() to TOML, walks it against build_schema_map(), and fails if any field is missing from the map. Since strict_tools defaults to None and uses skip_serializing_if = "Option::is_none", it won't appear in the default serialization, so the test wouldn't have caught a missing entry. But I already added it to the schema map, so we're covered.
Let me confirm the drift guard test passes:
Assistant
The schema_drift_guard test passes. It works by serializing the default config and checking that every key in the TOML output has a corresponding entry in build_schema_map(). Since strict_tools is Option<bool> with skip_serializing_if = "Option::is_none" and defaults to None, it doesn't appear in the default serialization — so the test wouldn't have caught a missing schema map entry for this field. But we already added it proactively to the schema map, so we're good either way.
User
i m not talking about the config one, i m talking about one we use already and a crate for llm expected json schema
Assistant
That didn't find what you're referring to. Let me search more specifically for a crate that defines expected schema formats per LLM provider.
Assistant
Let me look at the json_schema_ast crate more carefully — the user might be referring to its ability to represent provider-expected schemas:
Assistant
Let me check other active branches — the user might be referring to a PR that hasn't been merged yet:
Assistant
Let me look at open PRs — the user might be referring to an open PR:
Assistant
That's the json_schema_ast + schemars based sanitizer (PR #698), which is already being used. But the user is asking about something different — a tool to map schemas to provider expectations. Let me look at recent merged PRs more broadly and check if there's something on other branches:
Assistant
Let me look at PR #697 (Fix tool arg serialization) and #696 (Fix tool-call compatibility regressions) — those are the most likely candidates:
Assistant
Let me look at the tool_arg_validator — this might be what the user is referring to:
Assistant
That's not it either — it's a runtime argument validator, not a schema mapper. Let me check if there's a tool_registry or tool schema mapping that defines what each provider expects:
Assistant
Now I see it. The tool_arg_serialization.json scenario file has a providers map with per-provider expectations (must_pass vs allow_known_mismatch). This is a declarative way to map expected behavior per provider. The user is asking whether this existing scenario-based e2e framework could/should be used to test the Google/OpenRouter strict-tools fix — instead of (or in addition to) the manual integration tests I added.
But wait, re-reading the user's question: "another PR added a schema tool to map on expectation" — they might be talking about a tool that maps the schema format to what each provider expects. Let me check if there's something in json_schema_ast that does this:
Assistant
That's just a general-purpose JSON Schema canonicalizer, not provider-specific. I'm not finding what the user is referring to. Let me ask for clarification.
I can't find what you're referring to. I searched:
json_schema_ast — general JSON Schema canonicalizer, no provider-specific mapping
tool_arg_validator.rs — runtime argument validator, not schema format mapper
tool_arg_serialization.json — e2e scenario file with per-provider expectations for serialization behavior
schema_normalization.rs — OpenAI subset sanitizer via schemars transforms
All recent PRs (#696-#698) and commits
Could you point me to the PR or file you're thinking of? Is it the e2e_scenarios/tool_arg_serialization.json pattern (the declarative per-provider expectations map), or something else entirely?
User
it is e2e_scenarios/tool_arg_serialization.json yes
Assistant
Got it. So instead of writing manual integration tests in openrouter_integration.rs, I should add a scenario to tool_arg_serialization.json that exercises the complex cron-like schema through OpenRouter with a Google model. Let me look at what I need to update.
Assistant
Now I understand the pattern. I'll:
Add a new scenario to tool_arg_serialization.json with the cron-like nested schema (the one that triggers Google's INVALID_ARGUMENT)
Add an openrouter-google provider entry in that scenario
Add a test function in tool_arg_serialization_integration.rs for OpenRouter
Remove the manual integration tests I added to openrouter_integration.rs
Assistant
Now let me remove the manual Google model tests from openrouter_integration.rs and add the scenario + test function to the serialization framework instead.
First, remove the manual tests from openrouter_integration.rs:
Assistant
Also remove the now-unused StreamEvent import since the Google streaming test was the only place that used ToolCallStart:
Assistant
The existing tests still use StreamEvent and ToolCall (the streaming tests and multi-turn test), so those imports are still needed. Good, no change required there.
Now add the scenario to tool_arg_serialization.json:
Assistant
Now add the OpenRouter Google test function to tool_arg_serialization_integration.rs:
Assistant
Both test functions end identically. Let me use more context:
Assistant
Now let's verify everything compiles and tests pass:
Assistant
All clean. Let me check the final diff:
Assistant
The manual tests in openrouter_integration.rs are gone, replaced by the scenario-based approach. 14 files changed:
Core fix: to_openai_tools(tools, strict) in openai_compat/mod.rs — skips strict patching when false
Unit tests: 3 new tests in openai_compat/mod.rs (strict, non-strict, complex cron-like)
E2e scenario: issue-716-nested-optional-booleans in tool_arg_serialization.json with openrouter-google provider expectation + test function
User
ok so you can add scenario for this bug too, so we know it keeps working
Assistant
The issue-693 scenario already tests with zai — I should add openrouter-google to that existing scenario too, and also add openrouter-google to test the falsy/null serialization on a Google model through OpenRouter. That way we know both the original bug (#693) and the new one (#716) keep working on Google via OpenRouter.
Assistant
Clean. Now openrouter-google is covered by both scenarios — the original #693 falsy/null serialization and the new #716 nested-optional-booleans schema.