Repository navigation
Conversation
Translate staged inputs/mcp-servers.json entries into ~/.gemini/settings.json under mcpServers via scion_harness.apply_mcp_translated: - stdio -> command (optional args, env) - sse -> url (optional headers) - streamable-http -> httpUrl (optional headers, matching Gemini CLI schema) - project-scoped entries demoted to global ~/.gemini/settings.json - fail-closed on malformed, non-UTF-8, or non-object existing settings.json Also declares capabilities.mcp in harnesses/gemini-cli/config.yaml, adds Python and Go capability tests, and updates the Gemini CLI section in supported-harnesses.md. Fixes GoogleCloudPlatform#5766
There was a problem hiding this comment.
Code Review
This pull request introduces Model Context Protocol (MCP) support for the gemini-cli harness, enabling translation and merging of universal MCP server configurations (supporting stdio, sse, and streamable-http transports) into the global ~/.gemini/settings.json file. The changes include documentation updates, capability declarations, translation logic, and extensive unit tests. The reviewer feedback highlights a critical issue where the fail-closed logic for malformed settings files is rendered ineffective because earlier steps in the provisioning flow silently overwrite malformed configurations. Additionally, the reviewer suggests refactoring the transport translation code to reduce duplication and adding an end-to-end test to cover the malformed settings scenario.
| def _write_mcp_servers(servers: dict[str, dict[str, Any]]) -> None: | ||
| """Merge translated MCP server entries into ~/.gemini/settings.json. | ||
|
|
||
| Fails closed (raising OSError so apply_mcp_translated warns and skips) | ||
| when an existing settings.json cannot be read or is not a JSON object, | ||
| preserving existing user settings and hooks untouched. | ||
| """ |
There was a problem hiding this comment.
The docstring states that _write_mcp_servers fails closed to preserve existing user settings and hooks untouched when settings.json is malformed or unreadable. However, in the actual provision(ctx) execution flow, _update_gemini_settings is called at the very beginning (line 370), followed by telemetry writing (line 412) and _apply_model (line 430). All of these functions load settings.json and silently overwrite it with an empty dictionary {} if a json.JSONDecodeError or OSError is encountered.\n\nAs a result, any malformed settings.json will already have been overwritten and replaced with a valid JSON file before _write_mcp_servers is ever called. This makes the fail-closed check here unreachable dead code in the end-to-end flow, and fails to protect the user's malformed settings from being overwritten.\n\nTo fix this and ensure consistent behavior, consider either:\n1. Refactoring provision(ctx) to perform a single read-modify-write cycle on settings.json so that any load failure can be caught upfront and failed closed consistently.\n2. Updating the other settings-writing functions to also fail closed on malformed files if preservation is the desired behavior.
| if transport == "sse": | ||
| url = spec.get("url") | ||
| if not isinstance(url, str) or not url.strip(): | ||
| warn(f"mcp server {name!r}: sse transport missing url") | ||
| return None | ||
| out = {"url": url.strip()} | ||
| headers = spec.get("headers") | ||
| if isinstance(headers, dict) and headers: | ||
| out["headers"] = {str(k): str(v) for k, v in headers.items()} | ||
| return out | ||
|
|
||
| if transport == "streamable-http": | ||
| url = spec.get("url") | ||
| if not isinstance(url, str) or not url.strip(): | ||
| warn(f"mcp server {name!r}: streamable-http transport missing url") | ||
| return None | ||
| out = {"httpUrl": url.strip()} | ||
| headers = spec.get("headers") | ||
| if isinstance(headers, dict) and headers: | ||
| out["headers"] = {str(k): str(v) for k, v in headers.items()} | ||
| return out |
There was a problem hiding this comment.
The blocks for handling sse and streamable-http transports are almost identical, with the only difference being the key used for the URL (url vs httpUrl). We can refactor this to reduce code duplication and improve maintainability.
if transport in (\"sse\", \"streamable-http\"):\n url = spec.get(\"url\")\n if not isinstance(url, str) or not url.strip():\n warn(f\"mcp server {name!r}: {transport} transport missing url\")\n return None\n url_key = \"url\" if transport == \"sse\" else \"httpUrl\"\n out = {url_key: url.strip()}\n headers = spec.get(\"headers\")\n if isinstance(headers, dict) and headers:\n out[\"headers\"] = {str(k): str(v) for k, v in headers.items()}\n return out| cases = ( | ||
| ("malformed_json", b'// jsonc comment\n{"hooks": {"SessionStart": []}}\n'), | ||
| ("non_utf8_bytes", b"\xff\xfe\x00invalid-utf8"), | ||
| ("json_array", b'["not", "an", "object"]\n'), | ||
| ("json_null", b"null\n"), | ||
| ) | ||
| for label, raw_bytes in cases: | ||
| with self.subTest(case=label): | ||
| with open(self.settings_path, "wb") as f: | ||
| f.write(raw_bytes) | ||
| count, warnings = self._apply_mcp( | ||
| {"s1": {"transport": "stdio", "command": "echo"}} | ||
| ) | ||
| self.assertEqual(count, 0) | ||
| self.assertEqual(len(warnings), 1) | ||
| self.assertIn("failed to write MCP config", warnings[0]) | ||
| with open(self.settings_path, "rb") as f: | ||
| self.assertEqual(f.read(), raw_bytes) | ||
|
|
There was a problem hiding this comment.
This test passes because _apply_mcp directly invokes scion_harness.apply_mcp_translated with _write_mcp_servers, bypassing the full provision(ctx) flow. In a real end-to-end run, _update_gemini_settings and _apply_model run before MCP translation and will silently overwrite any malformed settings.json with a valid one. Consider adding an end-to-end test using provision(ctx) with a malformed settings.json to ensure the entire provisioning lifecycle behaves as expected regarding malformed configuration files.
Summary
Wires universal
inputs/mcp-servers.jsonprovisioning for thegemini-cliharness bundle and declares its MCP capabilities.Fixes #5766
Changes
harnesses/gemini-cli/provision.py:_translate_mcp_serverand_write_mcp_servers, invoked viascion_harness.apply_mcp_translatedinsideprovision(ctx)after_apply_model(ctx).apply_mcp_translatedrather thanapply_mcp_servers_simplebecause Gemini CLI's~/.gemini/settings.jsonmcpServersschema has no transporttypefield and distinguishesurl(sse) fromhttpUrl(streamable-http), alongsidecommand/args/env(stdio).commandandurlwhile preservingargs,env, andheadersvalues.project-scoped entries to global~/.gemini/settings.json(matchingcodex,copilot,opencode,hermes,grok-build,muse-code, andpi) so provisioning does not leave untracked.gemini/settings.jsonfiles inside/workspace.OSError, caught and warned byapply_mcp_translated) if an existing~/.gemini/settings.jsonis unreadable, malformed JSON, non-UTF-8, or not a JSON object, preserving existing hooks and user settings.harnesses/gemini-cli/config.yaml: Declaredcapabilities.mcp(stdio: yes,sse: yes,streamable_http: yes,project_scope: no).harnesses/gemini-cli/provision_test.py: Added unit tests coveringstdio,sse(url),streamable-http(httpUrlwithouturl), whitespace trimming,projectscope demotion, merging alongside existingsettings.jsonkeys and usermcpServers, fail-closed handling on malformed/non-UTF-8/non-object files, warn-and-skip on invalid entries, no-op when absent/empty, end-to-endprovision(ctx), andconfig.yamlcapability consistency.pkg/harness/capabilities_test.go: AddedTestGeminiCLIMCPCapabilities.docs-site/src/content/docs/supported-harnesses.md: Added the- **MCP**configuration bullet under## 1. Gemini CLI.Verification
go test -buildvcs=false -v ./harnesses/...: PASS (TestHarnessProvisionPython/gemini-cli: 35 tests in0.126s)go test -buildvcs=false -v ./pkg/harness/...: PASS (TestGeminiCLIMCPCapabilitiesPASS)go test -buildvcs=false -run "Schema|Harness" ./pkg/config/...: PASSGOOS=windows GOARCH=amd64 go build -buildvcs=false ./pkg/harnessand./cmd/scion: PASS (./pkg/harnesstest compilation on Windows pulls in Unix-onlypkg/sciontool/supervisorperdocs-repo/agents/windows-platform-seams.md)bash hack/winsec-guard.sh:winsec-guard: ok (3871 files)node hack/check-docs-links.mjs:0 violation(s)gofmt -l pkg/harness/capabilities_test.go: cleanNote: Companion docs PR for #5768 adds an
MCProw to the Feature Capability Matrix insupported-harnesses.mdreflecting pre-PR state (❌forgemini-cli); whichever PR merges second will update that cell to✅.