Skip to content

feat(harness): wire universal mcp_servers provisioning for gemini-cli - #5769

Open
ernani wants to merge 1 commit into
GoogleCloudPlatform:mainfrom
ernani:feat/gemini-cli-mcp-provisioning
Open

ernani wants to merge 1 commit into
GoogleCloudPlatform:mainfrom
ernani:feat/gemini-cli-mcp-provisioning

Conversation

@ernani

@ernani ernani commented Nov 28, 2026

Copy link
Copy Markdown

Summary

Wires universal inputs/mcp-servers.json provisioning for the gemini-cli harness bundle and declares its MCP capabilities.

Fixes #5766

Changes

  • harnesses/gemini-cli/provision.py:
    • Added _translate_mcp_server and _write_mcp_servers, invoked via scion_harness.apply_mcp_translated inside provision(ctx) after _apply_model(ctx).
    • Uses apply_mcp_translated rather than apply_mcp_servers_simple because Gemini CLI's ~/.gemini/settings.json mcpServers schema has no transport type field and distinguishes url (sse) from httpUrl (streamable-http), alongside command / args / env (stdio).
    • Trims surrounding whitespace on command and url while preserving args, env, and headers values.
    • Demotes project-scoped entries to global ~/.gemini/settings.json (matching codex, copilot, opencode, hermes, grok-build, muse-code, and pi) so provisioning does not leave untracked .gemini/settings.json files inside /workspace.
    • Fails closed (OSError, caught and warned by apply_mcp_translated) if an existing ~/.gemini/settings.json is unreadable, malformed JSON, non-UTF-8, or not a JSON object, preserving existing hooks and user settings.
  • harnesses/gemini-cli/config.yaml: Declared capabilities.mcp (stdio: yes, sse: yes, streamable_http: yes, project_scope: no).
  • harnesses/gemini-cli/provision_test.py: Added unit tests covering stdio, sse (url), streamable-http (httpUrl without url), whitespace trimming, project scope demotion, merging alongside existing settings.json keys and user mcpServers, fail-closed handling on malformed/non-UTF-8/non-object files, warn-and-skip on invalid entries, no-op when absent/empty, end-to-end provision(ctx), and config.yaml capability consistency.
  • pkg/harness/capabilities_test.go: Added TestGeminiCLIMCPCapabilities.
  • 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 in 0.126s)
  • go test -buildvcs=false -v ./pkg/harness/...: PASS (TestGeminiCLIMCPCapabilities PASS)
  • go test -buildvcs=false -run "Schema|Harness" ./pkg/config/...: PASS
  • GOOS=windows GOARCH=amd64 go build -buildvcs=false ./pkg/harness and ./cmd/scion: PASS (./pkg/harness test compilation on Windows pulls in Unix-only pkg/sciontool/supervisor per docs-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: clean

Note: Companion docs PR for #5768 adds an MCP row to the Feature Capability Matrix in supported-harnesses.md reflecting pre-PR state (❌ for gemini-cli); whichever PR merges second will update that cell to ✅.

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

@gemini-code-assist gemini-code-assist 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.

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.

Comment on lines +335 to +341
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.
"""

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.

medium

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.

Comment on lines +309 to +329
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

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.

medium

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

Comment on lines +600 to +618
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)

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.

medium

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.

This branch has not been deployed

No deployments
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.

feat(harness): wire universal mcp_servers provisioning for gemini-cli

1 participant