Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(gemini): allow-list the tool schema, so one MCP extension key cannot kill the turn
rubenluetke10-beep90c7a4083883
diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.pyindex 30ea5c809d..677b6f725f 100644--- a/jarvis/plugins/brain/gemini.py+++ b/jarvis/plugins/brain/gemini.py@@ -19,6 +19,7 @@ import loggingimport osimport refrom collections.abc import AsyncIterator+from functools import lru_cachefrom typing import Anyfrom uuid import uuid4@@ -399,35 +400,97 @@ def _convert_exclusive_bounds(schema: dict[str, Any]) -> dict[str, Any]:return out-def _sanitize_for_gemini(schema: dict[str, Any]) -> dict[str, Any]:- """Recursively removes OpenAI-specific fields from a JSON schema.+# The documented Gemini schema subset, used when the installed google-genai+# cannot be introspected. Field names AND their JSON aliases, because a tool+# schema arrives in either spelling.+_GEMINI_SCHEMA_KEYS_FALLBACK: frozenset[str] = frozenset({+ "additionalProperties", "additional_properties", "anyOf", "any_of",+ "default", "defs", "description", "enum", "example", "format", "items",+ "maxItems", "max_items", "maxLength", "max_length", "maxProperties",+ "max_properties", "maximum", "minItems", "min_items", "minLength",+ "min_length", "minProperties", "min_properties", "minimum", "nullable",+ "pattern", "properties", "propertyOrdering", "property_ordering", "ref",+ "required", "title", "type",+})+++@lru_cache(maxsize=1)+def _gemini_schema_keys() -> frozenset[str]:+ """Every key google-genai's ``types.Schema`` accepts, names and aliases.++ Read off the installed library rather than spelled out here, because that+ model IS the validator that rejects the request (``extra="forbid"``): its+ own field set is the only honest answer, and a library version that gains+ a keyword gains it here in the same step. A library that cannot be+ introspected falls back to the documented subset above — never to "allow+ everything", which is the failure this exists to prevent.+ """+ try:+ from google.genai import types- Gemini's google-genai SDK validates Tool.functionDeclarations.parameters- via Pydantic with `extra="forbid"`. Fields like `strict`/`input_examples`- are OpenAI tool-use conventions and not allowed in Gemini's schema- subset. Instead of delivering a tool call without tools, we strip those- fields out — the tools themselves keep working unchanged, only the- OpenAI-specific hints are gone.+ fields = types.Schema.model_fields+ keys = set(fields)+ keys.update(f.alias for f in fields.values() if f.alias)+ if keys:+ return frozenset(keys)+ except Exception as exc: # noqa: BLE001 — the fallback list is the answer+ log.debug("gemini: schema field set not introspectable (%s) — using the fallback", exc)+ return _GEMINI_SCHEMA_KEYS_FALLBACK+++#: Keys whose value is one nested schema.+_GEMINI_SCHEMA_VALUED: frozenset[str] = frozenset({"items"})+#: Keys whose value maps FREE names to schemas. Their keys are property names+#: chosen by whoever wrote the tool ("owner", "repo") and must never be judged+#: against the allow-list — only their values are schemas.+_GEMINI_SCHEMA_MAP_VALUED: frozenset[str] = frozenset({"properties", "defs"})+#: Keys whose value is a list of schemas.+_GEMINI_SCHEMA_LIST_VALUED: frozenset[str] = frozenset({"anyOf", "any_of"})+++def _sanitize_for_gemini(schema: dict[str, Any]) -> dict[str, Any]:+ """Reduce a JSON schema to the subset google-genai's Schema model accepts.++ Gemini validates ``Tool.functionDeclarations.parameters`` through Pydantic+ with ``extra="forbid"``: ONE unknown key anywhere in ONE tool's schema+ fails the WHOLE GenerateContent request, so the brain dies and the turn+ falls through the entire provider chain. This has now happened four times+ with a different key each time — OpenAI's ``strict``, Pydantic's ``$defs``,+ an MCP tool's ``propertyNames``, and the GitHub MCP server's+ ``x-mcp-header`` (live 2026-08-26: 81 validation errors, gemini down,+ the front page's chat answered "I can't reach my provider").++ So this keeps an ALLOW-list, not a block-list: a key the library does not+ know is dropped whatever it is called. A block-list can never be complete+ — any connected MCP server may ship any extension key it likes — and+ every one of those four outages was a block-list that was.++ The walk is schema-aware, which the allow-list makes mandatory: under+ ``properties`` the keys are property NAMES a tool author chose, and+ judging those against the allow-list would delete the parameters+ themselves. Values that are data rather than schemas (``example``,+ ``default``, ``enum``) are passed through untouched.Exclusive numeric bounds (``exclusiveMinimum``/``exclusiveMaximum`` fromPydantic ``Field(gt=...)``/``Field(lt=...)``) are first converted to the- inclusive ``minimum``/``maximum`` Gemini accepts, then the exclusive key is- stripped via ``_GEMINI_FORBIDDEN_SCHEMA_KEYS``.+ inclusive ``minimum``/``maximum`` Gemini accepts, then dropped.+ ``_GEMINI_FORBIDDEN_SCHEMA_KEYS`` still runs in front of the allow-list,+ for the keys the model accepts but the API does not."""if not isinstance(schema, dict):return schemaschema = _convert_exclusive_bounds(schema)+ allowed = _gemini_schema_keys()out: dict[str, Any] = {}for k, v in schema.items():- if k in _GEMINI_FORBIDDEN_SCHEMA_KEYS:+ if k in _GEMINI_FORBIDDEN_SCHEMA_KEYS or k not in allowed:continue- if isinstance(v, dict):+ if k in _GEMINI_SCHEMA_MAP_VALUED and isinstance(v, dict):+ out[k] = {name: _sanitize_for_gemini(sub) for name, sub in v.items()}+ elif k in _GEMINI_SCHEMA_LIST_VALUED and isinstance(v, list):+ out[k] = [_sanitize_for_gemini(sub) if isinstance(sub, dict) else sub for sub in v]+ elif k in _GEMINI_SCHEMA_VALUED and isinstance(v, dict):out[k] = _sanitize_for_gemini(v)- elif isinstance(v, list):- out[k] = [- _sanitize_for_gemini(item) if isinstance(item, dict) else item- for item in v- ]else:out[k] = vreturn outdiff --git a/tests/unit/brain/test_gemini_schema_sanitize.py b/tests/unit/brain/test_gemini_schema_sanitize.pyindex f169d408f7..9ed1d07064 100644--- a/tests/unit/brain/test_gemini_schema_sanitize.py+++ b/tests/unit/brain/test_gemini_schema_sanitize.py@@ -12,7 +12,9 @@ Drive question got no real answer for reasons unrelated to Drive.import json-from jarvis.plugins.brain.gemini import _sanitize_for_gemini+import pytest++from jarvis.plugins.brain.gemini import _gemini_schema_keys, _sanitize_for_geminidef _flatten(schema: dict) -> str:@@ -73,3 +75,86 @@ def test_sanitizer_recurses_into_nested_and_lists():assert "propertyNames" not in _flatten(clean)# Structure preserved.assert clean["properties"]["outer"]["items"]["type"] == "object"+++def test_an_unknown_extension_key_is_dropped_whatever_it_is_called():+ """The 2026-08-26 outage: the GitHub MCP server tags parameters with+ ``x-mcp-header``. It was on no block-list, so 81 validation errors killed+ the whole request and the front page's chat answered "I can't reach my+ provider". An allow-list does not need to have heard of it."""+ bad = {+ "type": "object",+ "properties": {+ "owner": {"type": "string", "description": "Repo owner", "x-mcp-header": "owner"},+ "repo": {"type": "string", "x-mcp-header": "repo"},+ },+ "required": ["owner", "repo"],+ }+ clean = _sanitize_for_gemini(bad)+ assert "x-mcp-header" not in _flatten(clean)+ # A stripped tool is not a fix: the parameters and their prose survive.+ assert set(clean["properties"]) == {"owner", "repo"}+ assert clean["properties"]["owner"]["description"] == "Repo owner"+ assert clean["required"] == ["owner", "repo"]+ # And an invented key nobody has seen yet goes the same way.+ invented = _sanitize_for_gemini({"type": "string", "x-vendor-someday": {"a": 1}})+ assert invented == {"type": "string"}+++def test_a_property_named_like_a_schema_keyword_survives():+ """Under ``properties`` the keys are names a tool author chose. Judging+ those against the allow-list would delete the parameters themselves — the+ one way an allow-list can be worse than the block-list it replaces."""+ schema = {+ "type": "object",+ "properties": {+ "strict": {"type": "boolean"},+ "propertyNames": {"type": "string"},+ "x-mcp-header": {"type": "string"},+ },+ }+ clean = _sanitize_for_gemini(schema)+ assert set(clean["properties"]) == {"strict", "propertyNames", "x-mcp-header"}+ assert clean["properties"]["strict"]["type"] == "boolean"+++def test_a_data_value_is_not_walked_as_a_schema():+ """``example``/``default`` carry the tool author's DATA. A dict in there+ that happens to look like a schema must come back byte-identical."""+ schema = {+ "type": "object",+ "properties": {+ "cfg": {"type": "object", "default": {"strict": True, "propertyNames": "x"}},+ },+ }+ clean = _sanitize_for_gemini(schema)+ assert clean["properties"]["cfg"]["default"] == {"strict": True, "propertyNames": "x"}+++def test_the_allow_list_comes_from_the_installed_library():+ """The model that rejects the request is the only honest source for what+ it accepts — so the list is read off it, not spelled out beside it."""+ keys = _gemini_schema_keys()+ assert {"type", "properties", "items", "required", "description"} <= keys+ assert "x-mcp-header" not in keys and "strict" not in keys+++def test_the_sanitized_schema_passes_googles_own_validator():+ """The end-to-end claim: what we send validates where it is validated."""+ types = pytest.importorskip("google.genai.types")+ dirty = {+ "type": "object",+ "properties": {+ "owner": {"type": "string", "x-mcp-header": "owner"},+ "page": {"type": "integer", "exclusiveMinimum": 0},+ "anchor": {"type": "string", "propertyNames": {"type": "string"}},+ "opts": {"type": "object", "strict": True, "additionalProperties": False},+ },+ "required": ["owner"],+ }+ with pytest.raises(Exception):+ types.Schema.model_validate(dirty)+ clean = _sanitize_for_gemini(dirty)+ types.Schema.model_validate(clean) # must not raise+ # The exclusive bound was converted, not merely dropped.+ assert clean["properties"]["page"]["minimum"] == 0