Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

A Gemini tool declaration reaches TokenRouter in Google's schema subset (#101)

github-actions[bot]bfc02fc69852
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index e3240389..3388a3e2 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -31,3 +31,19 @@ One session per harness on the instance's own map (TokenRouter, Azure, Vercel),
## Totals
695 pairs over eight columns; every failing row carries the provider's own text in the table.
+
+## TokenRouter's Gemini channels refuse JSON-schema keys (2026-09-06)
+
+TokenRouter's Gemini channels forward a harness's JSON-schema tool declarations to Google's native
+API as sent, and Google's function-declaration validator refuses what its own OpenAI-compatible
+endpoint, OpenRouter and Vercel normalise away: `Unknown name "$schema"` (opencode),
+`Unknown name "exclusiveMinimum"` and `schema didn't specify the schema type field` (cline). The
+first turn of a task fails on the ids those channels serve natively (gemini-3.8-flash for one; the
+same declaration passes on 3.7-flash, 3.5-flash and 3-flash-preview), so it is per channel, not
+per model. Until TokenRouter normalises them itself, the broker and both loopback relays normalise
+tool parameters to Google's Schema subset for that channel and Gemini models only (keys outside the
+subset dropped, oneOf to anyOf, const to a one-value enum, exclusive bounds to bounds, a type list
+to one type plus nullable, a type on every node, items on every array, required limited to existing
+properties, an empty declaration dropped). The report is with TokenRouter; when their channel
+normalises, this comes out of both trees.
+
diff --git a/gateway/app.py b/gateway/app.py
index a13875c8..4c0f42a0 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -3132,6 +3132,105 @@ class _GoogleSigTap:
self.sigs += _google_signatures_in(doc)
+_STRICT_GEMINI_CHANNELS = {"tokenrouter"}
+# ── Gemini function declarations through a strict channel ────────────────────────────────
+# Google's native API validates function declarations against its own Schema (type, format,
+# description, nullable, enum, properties, required, items, min/max, anyOf and a few more) and
+# refuses anything else: "Unknown name \"$schema\" at 'tools[0].function_declarations[0].parameters'",
+# "Unknown name \"exclusiveMinimum\"", "schema didn't specify the schema type field". Google's own
+# OpenAI-compatible endpoint, OpenRouter and Vercel normalise a harness's JSON-schema declarations
+# before they reach it; TokenRouter's Gemini channels forward them as sent, so the first turn of a
+# task on opencode ($schema) and cline (exclusiveMinimum, a property without type) failed on the
+# ids those channels serve natively, gemini-3.8-flash for one (measured 2026-09-06, the platform
+# column). Until TokenRouter normalises them itself, this relay does, for that channel only.
+_GEMINI_SCHEMA_KEYS = {"type", "format", "title", "description", "nullable", "enum", "maxItems", "minItems",
+ "properties", "required", "minProperties", "maxProperties", "minLength", "maxLength",
+ "pattern", "example", "anyOf", "propertyOrdering", "default", "items", "minimum", "maximum"}
+
+
+def _gemini_schema(node):
+ """One JSON schema node as Google's function-declaration validator accepts it: only the keys it
+ names, `oneOf` as `anyOf`, `const` as a one-value enum, an exclusive bound as the bound, a type
+ list as one type plus nullable, a type on every node (inferred from its shape when left out),
+ items on every array, and `required` limited to properties that exist."""
+ if not isinstance(node, dict):
+ return node
+ out: dict = {}
+ for k, v in node.items():
+ if k == "oneOf" and isinstance(v, list):
+ out.setdefault("anyOf", [_gemini_schema(x) for x in v])
+ elif k == "const":
+ out["enum"] = [v]
+ elif k == "exclusiveMinimum" and isinstance(v, (int, float)) and not isinstance(v, bool):
+ out.setdefault("minimum", v)
+ elif k == "exclusiveMaximum" and isinstance(v, (int, float)) and not isinstance(v, bool):
+ out.setdefault("maximum", v)
+ elif k not in _GEMINI_SCHEMA_KEYS:
+ continue
+ elif k == "properties" and isinstance(v, dict):
+ out[k] = {pk: _gemini_schema(pv) for pk, pv in v.items()}
+ elif k == "items":
+ out[k] = _gemini_schema(v) if isinstance(v, dict) else (_gemini_schema(v[0]) if isinstance(v, list) and v else {"type": "string"})
+ elif k == "anyOf" and isinstance(v, list):
+ out[k] = [_gemini_schema(x) for x in v]
+ else:
+ out[k] = v
+ t = out.get("type")
+ if isinstance(t, list):
+ non_null = [x for x in t if x != "null"]
+ out["type"] = non_null[0] if non_null else "string"
+ if "null" in t:
+ out["nullable"] = True
+ if "type" not in out and "anyOf" not in out:
+ out["type"] = "object" if "properties" in out else ("array" if "items" in out else "string")
+ if out.get("type") == "array" and "items" not in out:
+ out["items"] = {"type": "string"}
+ if out.get("type") == "object" and not out.get("properties"):
+ out.pop("properties", None) # an empty properties object is refused too
+ out.pop("required", None)
+ elif isinstance(out.get("required"), list) and isinstance(out.get("properties"), dict):
+ req = [r for r in out["required"] if r in out["properties"]]
+ if req:
+ out["required"] = req
+ else:
+ out.pop("required")
+ return out
+
+
+def _with_gemini_schemas(body: bytes) -> bytes:
+ """The chat request with every tool's parameters normalised for Google's validator; a tool
+ that declares no parameter loses the empty declaration. A body without tools is untouched."""
+ if b'"tools"' not in body:
+ return body
+ try:
+ doc = json.loads(body)
+ except (ValueError, UnicodeDecodeError):
+ return body
+ if not isinstance(doc, dict) or not isinstance(doc.get("tools"), list):
+ return body
+ changed = False
+ for tool in doc["tools"]:
+ fn = tool.get("function") if isinstance(tool, dict) else None
+ if not isinstance(fn, dict) or not isinstance(fn.get("parameters"), dict):
+ continue
+ params = _gemini_schema(fn["parameters"])
+ if params.get("type") == "object" and not params.get("properties"):
+ fn.pop("parameters")
+ else:
+ fn["parameters"] = params
+ changed = True
+ return json.dumps(doc).encode() if changed else body
+
+
+def _body_model_name(body: bytes) -> str:
+ """The model a chat request names, or "" (the body is not a JSON object)."""
+ try:
+ doc = json.loads(body) if body else {}
+ except (ValueError, UnicodeDecodeError):
+ return ""
+ return str(doc.get("model") or "") if isinstance(doc, dict) else ""
+
+
def _without_field(body: bytes, field: str) -> bytes:
"""The JSON request without one top-level field; a body that is not a JSON object is returned as is."""
try:
@@ -3262,6 +3361,8 @@ async def llm_broker(path: str, request: Request):
body = _strip_unsupported(await request.body(), provider=provider, byok=True, path=suffix)
if provider == "google":
body = _google_with_signatures(body, sid)
+ if provider in _STRICT_GEMINI_CHANNELS and "gemini" in _body_model_name(body).lower():
+ body = _with_gemini_schemas(body)
rc = _relay_client()
req = rc.build_request(request.method, url, headers=headers, content=body or None)
up = await rc.send(req, stream=True)
diff --git a/gateway/tests/test_google_provider.py b/gateway/tests/test_google_provider.py
index 4019446c..d5ceb38c 100644
--- a/gateway/tests/test_google_provider.py
+++ b/gateway/tests/test_google_provider.py
@@ -108,3 +108,37 @@ def test_llmtr_and_the_aggregators_carry_fable_5_1_and_llmtr_the_gemini_family()
for h, c in gw._MODEL_CATALOG.items():
if "claude-fable-5" in c["models"]:
assert "claude-fable-5-1" in c["models"], h
+
+
+# ── Gemini function declarations through TokenRouter (2026-09-06) ─────────────────────────
+def test_a_harness_tool_schema_is_normalised_to_googles_subset():
+ cline_like = {"$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "additionalProperties": False,
+ "properties": {"files": {"type": "array", "items": {"type": "object", "properties": {
+ "path": {"type": "string"}, "end_line": {"description": "line"},
+ "count": {"type": "integer", "exclusiveMinimum": 0},
+ "mode": {"oneOf": [{"const": "a"}, {"const": "b"}]},
+ "tag": {"type": ["string", "null"]}}, "required": ["path", "gone"]}},
+ "opts": {"type": "object", "properties": {}}, "list": {"type": "array"}},
+ "required": ["files"]}
+ out = gw._gemini_schema(cline_like)
+ assert "$schema" not in out and "additionalProperties" not in out
+ item = out["properties"]["files"]["items"]
+ assert item["properties"]["end_line"] == {"description": "line", "type": "string"}
+ assert item["properties"]["count"] == {"type": "integer", "minimum": 0}
+ assert item["properties"]["mode"] == {"anyOf": [{"enum": ["a"], "type": "string"}, {"enum": ["b"], "type": "string"}]}
+ assert item["properties"]["tag"] == {"type": "string", "nullable": True}
+ assert item["required"] == ["path"]
+ assert out["properties"]["opts"] == {"type": "object"}
+ assert out["properties"]["list"] == {"type": "array", "items": {"type": "string"}}
+
+
+def test_only_tool_parameters_change_and_an_empty_declaration_is_dropped():
+ body = json.dumps({"model": "google/gemini-3.8-flash", "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"type": "function", "function": {"name": "a", "parameters": {"$schema": "x", "type": "object", "properties": {"p": {"type": "string"}}}}},
+ {"type": "function", "function": {"name": "b", "parameters": {"type": "object", "properties": {}}}}]}).encode()
+ out = json.loads(gw._with_gemini_schemas(body))
+ assert out["tools"][0]["function"]["parameters"] == {"type": "object", "properties": {"p": {"type": "string"}}}
+ assert "parameters" not in out["tools"][1]["function"]
+ assert out["messages"] == [{"role": "user", "content": "hi"}]
+ plain = b'{"model": "google/gemini-3.8-flash", "messages": []}'
+ assert gw._with_gemini_schemas(plain) is plain
diff --git a/runner/dsh_driver.py b/runner/dsh_driver.py
index b8cba72d..b1464b4f 100644
--- a/runner/dsh_driver.py
+++ b/runner/dsh_driver.py
@@ -91,6 +91,96 @@ def _drop_top_level_fields(body: bytes, fields) -> bytes:
return json.dumps(obj).encode()
+_STRICT_GEMINI_HOST = "api.tokenrouter.com" # TokenRouter's channels, by the upstream host
+# ── Gemini function declarations through a strict channel ────────────────────────────────
+# Google's native API validates function declarations against its own Schema (type, format,
+# description, nullable, enum, properties, required, items, min/max, anyOf and a few more) and
+# refuses anything else: "Unknown name \"$schema\" at 'tools[0].function_declarations[0].parameters'",
+# "Unknown name \"exclusiveMinimum\"", "schema didn't specify the schema type field". Google's own
+# OpenAI-compatible endpoint, OpenRouter and Vercel normalise a harness's JSON-schema declarations
+# before they reach it; TokenRouter's Gemini channels forward them as sent, so the first turn of a
+# task on opencode ($schema) and cline (exclusiveMinimum, a property without type) failed on the
+# ids those channels serve natively, gemini-3.8-flash for one (measured 2026-09-06, the platform
+# column). Until TokenRouter normalises them itself, this relay does, for that channel only.
+_GEMINI_SCHEMA_KEYS = {"type", "format", "title", "description", "nullable", "enum", "maxItems", "minItems",
+ "properties", "required", "minProperties", "maxProperties", "minLength", "maxLength",
+ "pattern", "example", "anyOf", "propertyOrdering", "default", "items", "minimum", "maximum"}
+
+
+def _gemini_schema(node):
+ """One JSON schema node as Google's function-declaration validator accepts it: only the keys it
+ names, `oneOf` as `anyOf`, `const` as a one-value enum, an exclusive bound as the bound, a type
+ list as one type plus nullable, a type on every node (inferred from its shape when left out),
+ items on every array, and `required` limited to properties that exist."""
+ if not isinstance(node, dict):
+ return node
+ out = {}
+ for k, v in node.items():
+ if k == "oneOf" and isinstance(v, list):
+ out.setdefault("anyOf", [_gemini_schema(x) for x in v])
+ elif k == "const":
+ out["enum"] = [v]
+ elif k == "exclusiveMinimum" and isinstance(v, (int, float)) and not isinstance(v, bool):
+ out.setdefault("minimum", v)
+ elif k == "exclusiveMaximum" and isinstance(v, (int, float)) and not isinstance(v, bool):
+ out.setdefault("maximum", v)
+ elif k not in _GEMINI_SCHEMA_KEYS:
+ continue
+ elif k == "properties" and isinstance(v, dict):
+ out[k] = {pk: _gemini_schema(pv) for pk, pv in v.items()}
+ elif k == "items":
+ out[k] = _gemini_schema(v) if isinstance(v, dict) else (_gemini_schema(v[0]) if isinstance(v, list) and v else {"type": "string"})
+ elif k == "anyOf" and isinstance(v, list):
+ out[k] = [_gemini_schema(x) for x in v]
+ else:
+ out[k] = v
+ t = out.get("type")
+ if isinstance(t, list):
+ non_null = [x for x in t if x != "null"]
+ out["type"] = non_null[0] if non_null else "string"
+ if "null" in t:
+ out["nullable"] = True
+ if "type" not in out and "anyOf" not in out:
+ out["type"] = "object" if "properties" in out else ("array" if "items" in out else "string")
+ if out.get("type") == "array" and "items" not in out:
+ out["items"] = {"type": "string"}
+ if out.get("type") == "object" and not out.get("properties"):
+ out.pop("properties", None) # an empty properties object is refused too
+ out.pop("required", None)
+ elif isinstance(out.get("required"), list) and isinstance(out.get("properties"), dict):
+ req = [r for r in out["required"] if r in out["properties"]]
+ if req:
+ out["required"] = req
+ else:
+ out.pop("required")
+ return out
+
+
+def _with_gemini_schemas(body: bytes) -> bytes:
+ """The chat request with every tool's parameters normalised for Google's validator; a tool
+ that declares no parameter loses the empty declaration. A body without tools is untouched."""
+ if b'"tools"' not in body:
+ return body
+ try:
+ doc = json.loads(body)
+ except (ValueError, UnicodeDecodeError):
+ return body
+ if not isinstance(doc, dict) or not isinstance(doc.get("tools"), list):
+ return body
+ changed = False
+ for tool in doc["tools"]:
+ fn = tool.get("function") if isinstance(tool, dict) else None
+ if not isinstance(fn, dict) or not isinstance(fn.get("parameters"), dict):
+ continue
+ params = _gemini_schema(fn["parameters"])
+ if params.get("type") == "object" and not params.get("properties"):
+ fn.pop("parameters")
+ else:
+ fn["parameters"] = params
+ changed = True
+ return json.dumps(doc).encode() if changed else body
+
+
def _google_signatures_in(doc: dict) -> list:
"""The (tool call id, thought signature) pairs one answer (a chunk or a whole message) carries."""
found = []
@@ -184,6 +274,13 @@ class _Relay(http.server.BaseHTTPRequestHandler):
google = _GOOGLE_HOST in UPSTREAM_BASE or _google_required
if google and tail.endswith("/chat/completions"):
body = _google_with_signatures(body, _google_sigs)
+ if _STRICT_GEMINI_HOST in UPSTREAM_BASE and tail.endswith("/chat/completions") and b"gemini" in body:
+ try:
+ _model = str((json.loads(body) or {}).get("model") or "")
+ except (ValueError, AttributeError):
+ _model = ""
+ if "gemini" in _model.lower():
+ body = _with_gemini_schemas(body) # TokenRouter's Gemini channels forward tool schemas to Google's validator as sent
resp = None
for attempt in (0, 1, 2):
req = urllib.request.Request(UPSTREAM_BASE.rstrip("/") + tail,
diff --git a/runner/server.py b/runner/server.py
index 2e53fc1b..e8fcfda0 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -2261,6 +2261,97 @@ _GOOGLE_SIG_SKIP = "skip_thought_signature_validator"
_GOOGLE_HOST = "generativelanguage.googleapis.com"
+# The relay's route carries no provider, only the upstream: TokenRouter's channels are the host.
+_STRICT_GEMINI_HOST = "api.tokenrouter.com"
+# ── Gemini function declarations through a strict channel ────────────────────────────────
+# Google's native API validates function declarations against its own Schema (type, format,
+# description, nullable, enum, properties, required, items, min/max, anyOf and a few more) and
+# refuses anything else: "Unknown name \"$schema\" at 'tools[0].function_declarations[0].parameters'",
+# "Unknown name \"exclusiveMinimum\"", "schema didn't specify the schema type field". Google's own
+# OpenAI-compatible endpoint, OpenRouter and Vercel normalise a harness's JSON-schema declarations
+# before they reach it; TokenRouter's Gemini channels forward them as sent, so the first turn of a
+# task on opencode ($schema) and cline (exclusiveMinimum, a property without type) failed on the
+# ids those channels serve natively, gemini-3.8-flash for one (measured 2026-09-06, the platform
+# column). Until TokenRouter normalises them itself, this relay does, for that channel only.
+_GEMINI_SCHEMA_KEYS = {"type", "format", "title", "description", "nullable", "enum", "maxItems", "minItems",
+ "properties", "required", "minProperties", "maxProperties", "minLength", "maxLength",
+ "pattern", "example", "anyOf", "propertyOrdering", "default", "items", "minimum", "maximum"}
+
+
+def _gemini_schema(node):
+ """One JSON schema node as Google's function-declaration validator accepts it: only the keys it
+ names, `oneOf` as `anyOf`, `const` as a one-value enum, an exclusive bound as the bound, a type
+ list as one type plus nullable, a type on every node (inferred from its shape when left out),
+ items on every array, and `required` limited to properties that exist."""
+ if not isinstance(node, dict):
+ return node
+ out: dict = {}
+ for k, v in node.items():
+ if k == "oneOf" and isinstance(v, list):
+ out.setdefault("anyOf", [_gemini_schema(x) for x in v])
+ elif k == "const":
+ out["enum"] = [v]
+ elif k == "exclusiveMinimum" and isinstance(v, (int, float)) and not isinstance(v, bool):
+ out.setdefault("minimum", v)
+ elif k == "exclusiveMaximum" and isinstance(v, (int, float)) and not isinstance(v, bool):
+ out.setdefault("maximum", v)
+ elif k not in _GEMINI_SCHEMA_KEYS:
+ continue
+ elif k == "properties" and isinstance(v, dict):
+ out[k] = {pk: _gemini_schema(pv) for pk, pv in v.items()}
+ elif k == "items":
+ out[k] = _gemini_schema(v) if isinstance(v, dict) else (_gemini_schema(v[0]) if isinstance(v, list) and v else {"type": "string"})
+ elif k == "anyOf" and isinstance(v, list):
+ out[k] = [_gemini_schema(x) for x in v]
+ else:
+ out[k] = v
+ t = out.get("type")
+ if isinstance(t, list):
+ non_null = [x for x in t if x != "null"]
+ out["type"] = non_null[0] if non_null else "string"
+ if "null" in t:
+ out["nullable"] = True
+ if "type" not in out and "anyOf" not in out:
+ out["type"] = "object" if "properties" in out else ("array" if "items" in out else "string")
+ if out.get("type") == "array" and "items" not in out:
+ out["items"] = {"type": "string"}
+ if out.get("type") == "object" and not out.get("properties"):
+ out.pop("properties", None) # an empty properties object is refused too
+ out.pop("required", None)
+ elif isinstance(out.get("required"), list) and isinstance(out.get("properties"), dict):
+ req = [r for r in out["required"] if r in out["properties"]]
+ if req:
+ out["required"] = req
+ else:
+ out.pop("required")
+ return out
+
+
+def _with_gemini_schemas(body: bytes) -> bytes:
+ """The chat request with every tool's parameters normalised for Google's validator; a tool
+ that declares no parameter loses the empty declaration. A body without tools is untouched."""
+ if b'"tools"' not in body:
+ return body
+ try:
+ doc = json.loads(body)
+ except (ValueError, UnicodeDecodeError):
+ return body
+ if not isinstance(doc, dict) or not isinstance(doc.get("tools"), list):
+ return body
+ changed = False
+ for tool in doc["tools"]:
+ fn = tool.get("function") if isinstance(tool, dict) else None
+ if not isinstance(fn, dict) or not isinstance(fn.get("parameters"), dict):
+ continue
+ params = _gemini_schema(fn["parameters"])
+ if params.get("type") == "object" and not params.get("properties"):
+ fn.pop("parameters")
+ else:
+ fn["parameters"] = params
+ changed = True
+ return json.dumps(doc).encode() if changed else body
+
+
def _google_signatures_in(doc: dict) -> list[tuple[str, str]]:
"""The (tool call id, thought signature) pairs one answer (a chunk or a whole message) carries."""
found: list[tuple[str, str]] = []
@@ -2383,6 +2474,12 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
if google and body is not None and self.path.endswith("/chat/completions"):
body = _google_with_signatures(body, flags.setdefault("google_sigs", {}))
headers["content-length"] = str(len(body))
+ if (_STRICT_GEMINI_HOST in base and "gemini" in str(_body_model).lower()
+ and body is not None and self.path.endswith("/chat/completions")):
+ # TokenRouter's Gemini channels hand a harness's JSON-schema tool declarations to Google's
+ # validator as sent; the broker does the same normalisation for brokered traffic
+ body = _with_gemini_schemas(body)
+ headers["content-length"] = str(len(body))
resp = None
tried_slim = False
for attempt in (0, 1, 2):
diff --git a/runner/tests/test_dsh_driver_gemini_schema.py b/runner/tests/test_dsh_driver_gemini_schema.py
new file mode 100644
index 00000000..431c3fc6
--- /dev/null
+++ b/runner/tests/test_dsh_driver_gemini_schema.py
@@ -0,0 +1,41 @@
+"""Gemini tool declarations through TokenRouter's channels, normalised by the dsh relay (2026-09-06)."""
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import dsh_driver # noqa: E402
+
+
+# ── Gemini function declarations through TokenRouter (2026-09-06) ─────────────────────────
+def test_a_harness_tool_schema_is_normalised_to_googles_subset():
+ cline_like = {"$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "additionalProperties": False,
+ "properties": {"files": {"type": "array", "items": {"type": "object", "properties": {
+ "path": {"type": "string"}, "end_line": {"description": "line"},
+ "count": {"type": "integer", "exclusiveMinimum": 0},
+ "mode": {"oneOf": [{"const": "a"}, {"const": "b"}]},
+ "tag": {"type": ["string", "null"]}}, "required": ["path", "gone"]}},
+ "opts": {"type": "object", "properties": {}}, "list": {"type": "array"}},
+ "required": ["files"]}
+ out = dsh_driver._gemini_schema(cline_like)
+ assert "$schema" not in out and "additionalProperties" not in out
+ item = out["properties"]["files"]["items"]
+ assert item["properties"]["end_line"] == {"description": "line", "type": "string"}
+ assert item["properties"]["count"] == {"type": "integer", "minimum": 0}
+ assert item["properties"]["mode"] == {"anyOf": [{"enum": ["a"], "type": "string"}, {"enum": ["b"], "type": "string"}]}
+ assert item["properties"]["tag"] == {"type": "string", "nullable": True}
+ assert item["required"] == ["path"]
+ assert out["properties"]["opts"] == {"type": "object"}
+ assert out["properties"]["list"] == {"type": "array", "items": {"type": "string"}}
+
+
+def test_only_tool_parameters_change_and_an_empty_declaration_is_dropped():
+ body = json.dumps({"model": "google/gemini-3.8-flash", "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"type": "function", "function": {"name": "a", "parameters": {"$schema": "x", "type": "object", "properties": {"p": {"type": "string"}}}}},
+ {"type": "function", "function": {"name": "b", "parameters": {"type": "object", "properties": {}}}}]}).encode()
+ out = json.loads(dsh_driver._with_gemini_schemas(body))
+ assert out["tools"][0]["function"]["parameters"] == {"type": "object", "properties": {"p": {"type": "string"}}}
+ assert "parameters" not in out["tools"][1]["function"]
+ assert out["messages"] == [{"role": "user", "content": "hi"}]
+ plain = b'{"model": "google/gemini-3.8-flash", "messages": []}'
+ assert dsh_driver._with_gemini_schemas(plain) is plain
diff --git a/runner/tests/test_relay_gemini_schema.py b/runner/tests/test_relay_gemini_schema.py
new file mode 100644
index 00000000..5de01bfc
--- /dev/null
+++ b/runner/tests/test_relay_gemini_schema.py
@@ -0,0 +1,41 @@
+"""Gemini tool declarations through TokenRouter's channels, normalised by the loopback relay (2026-09-06)."""
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import server # noqa: E402
+
+
+# ── Gemini function declarations through TokenRouter (2026-09-06) ─────────────────────────
+def test_a_harness_tool_schema_is_normalised_to_googles_subset():
+ cline_like = {"$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "additionalProperties": False,
+ "properties": {"files": {"type": "array", "items": {"type": "object", "properties": {
+ "path": {"type": "string"}, "end_line": {"description": "line"},
+ "count": {"type": "integer", "exclusiveMinimum": 0},
+ "mode": {"oneOf": [{"const": "a"}, {"const": "b"}]},
+ "tag": {"type": ["string", "null"]}}, "required": ["path", "gone"]}},
+ "opts": {"type": "object", "properties": {}}, "list": {"type": "array"}},
+ "required": ["files"]}
+ out = server._gemini_schema(cline_like)
+ assert "$schema" not in out and "additionalProperties" not in out
+ item = out["properties"]["files"]["items"]
+ assert item["properties"]["end_line"] == {"description": "line", "type": "string"}
+ assert item["properties"]["count"] == {"type": "integer", "minimum": 0}
+ assert item["properties"]["mode"] == {"anyOf": [{"enum": ["a"], "type": "string"}, {"enum": ["b"], "type": "string"}]}
+ assert item["properties"]["tag"] == {"type": "string", "nullable": True}
+ assert item["required"] == ["path"]
+ assert out["properties"]["opts"] == {"type": "object"}
+ assert out["properties"]["list"] == {"type": "array", "items": {"type": "string"}}
+
+
+def test_only_tool_parameters_change_and_an_empty_declaration_is_dropped():
+ body = json.dumps({"model": "google/gemini-3.8-flash", "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"type": "function", "function": {"name": "a", "parameters": {"$schema": "x", "type": "object", "properties": {"p": {"type": "string"}}}}},
+ {"type": "function", "function": {"name": "b", "parameters": {"type": "object", "properties": {}}}}]}).encode()
+ out = json.loads(server._with_gemini_schemas(body))
+ assert out["tools"][0]["function"]["parameters"] == {"type": "object", "properties": {"p": {"type": "string"}}}
+ assert "parameters" not in out["tools"][1]["function"]
+ assert out["messages"] == [{"role": "user", "content": "hi"}]
+ plain = b'{"model": "google/gemini-3.8-flash", "messages": []}'
+ assert server._with_gemini_schemas(plain) is plain