Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
gemini_mcp.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The MCP servers a Gemini turn gets: AgentMux's own `agentmux` server and the
5//! catalog servers, from the `.mcp.json` the launch wrote in the agent's
6//! folder, as a settings file Gemini loads on top of its own.
7//! `SPEC_CONNECTORS_MCP_WHAT_AGENTS_RUN_2026_10_10.md` ยง5.
8//!
9//! The file is per agent, under srv's data folder, and named by the
10//! `GEMINI_CLI_SYSTEM_SETTINGS_PATH` variable the turn is launched with. Gemini
11//! merges its `mcpServers` with the folder's `.gemini/settings.json` and the
12//! user's, so nothing the person set up is replaced.
13//!
14//! A server's `env` is expanded by Gemini from its own environment, and it
15//! hands a server none of the variables named like a key or token unless the
16//! server's `env` asks for them. So a `${VAR}` stays a reference, and the
17//! `agentmux` server asks for every `AGENTMUX_` variable the agent was launched
18//! with by reference, not by value: a key the agent has is not copied into a
19//! second file. A header is expanded against the same stripped environment, so
20//! a server whose header holds a variable is left out (it would be sent
21//! empty) and named in the log.
22
23use std::collections::HashMap;
24use std::path::{Path, PathBuf};
25
26use serde_json::{json, Map, Value};
27
28use super::super::acp_mcp::{resolve_command, server_kind};
29use super::codex_mcp::{env_value, launch_env, scalar};
30
31/// Finds a bare command's absolute path (`resolve_command` in the product).
32type Resolve<'a> = &'a dyn Fn(&str) -> Option<String>;
33
34/// The variable that points Gemini at a settings file of the system's.
35const SETTINGS_ENV: &str = "GEMINI_CLI_SYSTEM_SETTINGS_PATH";
36
37/// What [`gemini_settings`] made of a `.mcp.json`.
38#[derive(Debug, Default, PartialEq)]
39pub(super) struct GeminiMcp {
40    /// The settings file's text, `None` when no server is to be given.
41    pub settings: Option<String>,
42    /// Servers left out, with why. Names only; never a value.
43    pub skipped: Vec<(String, &'static str)>,
44}
45
46/// One server as Gemini's `mcpServers` entry, or why it is left out.
47fn server_entry(name: &str, cfg: &Value, kind: &str, agent_env: &HashMap<String, String>, resolve: Resolve) -> Result<Value, &'static str> {
48    let x = |v: &str| if v.contains("${") { Err("a command, argument or url holds a variable") } else { Ok(v.to_string()) };
49    if kind == "stdio" {
50        let command = x(cfg.get("command").and_then(Value::as_str).ok_or("no command")?)?;
51        let args = cfg.get("args").and_then(Value::as_array).into_iter().flatten().filter_map(scalar).map(|v| x(&v)).collect::<Result<Vec<_>, _>>()?;
52        let mut env: Map<String, Value> = cfg.get("env").and_then(Value::as_object).into_iter().flatten().filter_map(|(k, v)| Some((k.clone(), Value::String(scalar(v)?)))).collect();
53        if name == "agentmux" {
54            // By reference: a value the agent has is not written to this file.
55            let mut own: Vec<&String> = agent_env.keys().filter(|k| k.starts_with("AGENTMUX_")).collect();
56            own.sort();
57            for k in own {
58                env.insert(k.clone(), Value::String(format!("${{{k}}}")));
59            }
60        }
61        let mut entry = json!({ "command": resolve(&command).unwrap_or(command), "args": args });
62        if !env.is_empty() {
63            entry["env"] = Value::Object(env);
64        }
65        Ok(entry)
66    } else {
67        let url = x(cfg.get("url").and_then(Value::as_str).ok_or("no url")?)?;
68        let mut headers = Map::new();
69        for (header, raw) in cfg.get("headers").and_then(Value::as_object).into_iter().flatten() {
70            let Some(raw) = scalar(raw) else { continue };
71            if raw.contains("${") {
72                return Err("a header holds a variable Gemini would send empty");
73            }
74            headers.insert(header.clone(), Value::String(raw));
75        }
76        let mut entry = Map::new();
77        // Gemini's `httpUrl` is the streamable-http transport, `url` the sse one.
78        entry.insert(if kind == "sse" { "url" } else { "httpUrl" }.to_string(), Value::String(url));
79        if !headers.is_empty() {
80            entry.insert("headers".to_string(), Value::Object(headers));
81        }
82        Ok(Value::Object(entry))
83    }
84}
85
86/// The settings file for the servers in `mcp_json`. `agent_env` is the
87/// environment the turn is launched with (see `launch_env`).
88pub(super) fn gemini_settings(mcp_json: &str, agent_env: &HashMap<String, String>, resolve: Resolve) -> GeminiMcp {
89    let mut result = GeminiMcp::default();
90    let Ok(root) = serde_json::from_str::<Value>(mcp_json) else { return result };
91    let Some(servers) = root.get("mcpServers").and_then(Value::as_object) else { return result };
92    let mut given = Map::new();
93    for (name, cfg) in servers {
94        let Some(kind) = server_kind(cfg) else { continue };
95        match server_entry(name, cfg, kind, agent_env, resolve) {
96            Ok(entry) => {
97                given.insert(name.clone(), entry);
98            }
99            Err(why) => result.skipped.push((name.clone(), why)),
100        }
101    }
102    if !given.is_empty() {
103        result.settings = serde_json::to_string_pretty(&json!({ "mcpServers": given })).ok();
104    }
105    result
106}
107
108/// Whether a spawn is a Gemini turn: its command is `gemini`, with or without a
109/// folder or an extension (`gemini.cmd` on Windows).
110pub(super) fn is_gemini(cli_command: &str) -> bool {
111    // Both separators: a Windows path is not split by `Path` on another system.
112    let base = cli_command.rsplit(['/', '\\']).next().unwrap_or(cli_command);
113    Path::new(base).file_stem().and_then(|s| s.to_str()).is_some_and(|s| s.eq_ignore_ascii_case("gemini"))
114}
115
116/// Writes `text` as `<dir>/<block_id>.json` and returns the path. The write is
117/// to a temporary file and a rename, and is skipped when the file already holds
118/// `text`, so a turn that starts as another one reads the file never sees half.
119fn write_settings(dir: &Path, block_id: &str, text: &str) -> Result<PathBuf, String> {
120    std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
121    let name: String = block_id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
122    let path = dir.join(format!("{name}.json"));
123    if std::fs::read_to_string(&path).ok().as_deref() != Some(text) {
124        let tmp = dir.join(format!(".{name}.{}.tmp", uuid::Uuid::new_v4()));
125        std::fs::write(&tmp, text).and_then(|()| std::fs::rename(&tmp, &path)).map_err(|e| {
126            let _ = std::fs::remove_file(&tmp);
127            format!("write {}: {e}", path.display())
128        })?;
129    }
130    Ok(path)
131}
132
133impl super::SubprocessController {
134    /// What this turn adds for MCP when it is a Gemini turn on the host: the
135    /// variable that points Gemini at the settings file made from the folder's
136    /// `.mcp.json`; else nothing.
137    pub(super) fn gemini_mcp(&self, config: &super::SubprocessSpawnConfig) -> Vec<(String, String)> {
138        if !is_gemini(&config.cli_command) || config.working_dir.is_empty() {
139            return Vec::new();
140        }
141        let folder = crate::backend::blockcontroller::core::expand_home_dir(&config.working_dir);
142        // The config may be outside the folder (#3680); `read_for_turn` finds it and keeps the
143        // project's own servers.
144        let Some(raw) = crate::backend::mcp_config_file::read_for_turn(&folder) else { return Vec::new() };
145        let path = config.env_vars.get("PATH").cloned();
146        let env = launch_env(std::env::vars(), &config.env_vars);
147        if env_value(&env, SETTINGS_ENV).is_some() {
148            tracing::warn!(block_id = %self.block_id, "this Gemini turn already has {SETTINGS_ENV} set, so its MCP servers are not given");
149            return Vec::new();
150        }
151        let made = gemini_settings(&raw, &env, &|c| resolve_command(c, path.as_deref()));
152        for (name, why) in &made.skipped {
153            tracing::warn!(block_id = %self.block_id, server = %name, why = %why, "MCP server not given to this Gemini turn");
154        }
155        let Some(text) = made.settings else { return Vec::new() };
156        let dir = crate::backend::base::get_mux_data_dir().join("gemini-mcp");
157        match write_settings(&dir, &self.block_id, &text) {
158            Ok(file) => vec![(SETTINGS_ENV.to_string(), file.to_string_lossy().into_owned())],
159            Err(e) => {
160                tracing::warn!(block_id = %self.block_id, error = %e, "Gemini MCP settings not written; this turn has no MCP servers from .mcp.json");
161                Vec::new()
162            }
163        }
164    }
165}
166
167#[cfg(test)]
168#[path = "gemini_mcp_tests.rs"]
169mod tests;