Skip to main content

surjection_core/adapters/
gemini.rs

1//! Gemini CLI (`gemini`): SPEC 7.3, 7.4 and 7.5.
2//!
3//! - User scope: `~/.gemini/settings.json`.
4//! - Project scope: `<P>/.gemini/settings.json`, loaded by Gemini only in
5//!   trusted folders.
6//! - Entries: `mcpServers.<name>` without `type`: `{command, args, env,
7//!   cwd}` (stdio), `{httpUrl, headers}` (Streamable HTTP) or `{url,
8//!   headers}` (SSE: a bare `url` is SSE for Gemini, unlike every other
9//!   client). Gemini's newer explicit `type` (`http`, `sse`) next to `url`
10//!   is read too, and `{"type": "http", "url": ...}` compares equal to the
11//!   `httpUrl` entry Surjection writes. `includeTools`/`excludeTools` are the
12//!   tool filter; `timeout` (milliseconds) and `trust` are passthrough
13//!   fields.
14//! - A project hides a user server by listing its name in the project
15//!   file's `mcp.excluded` ([`ProjectDisable::ListMember`] in the project
16//!   file, as Gemini has no private project file).
17//! - Variables: Gemini expands `${NAME}` and a bare `$NAME` in every
18//!   string value of its settings file, with no escape; Surjection writes
19//!   `${NAME}` and refuses literal text (and inline secret values) holding
20//!   `${` or `$` before a name character (`DollarBrace { bare: true }`).
21//!
22//! Assumptions left for Tier C verification (`scripts/verify-clients.md`,
23//! GEM-*):
24//! `[verify]` that `mcp.excluded` in the project file hides a same-named
25//! user server (GEM-4), that a project entry merges over the user entry
26//! (GEM-5, `ProjectSemantics::DeepMerge` as SPEC 7.4 says), that an entry
27//! holding both `httpUrl` and `url` (or a URL key and `command`) runs as
28//! Streamable HTTP, then SSE, then stdio (GEM-3), the fields `${NAME}` is
29//! expanded in and what a bare `$NAME` in a literal value does (GEM-6),
30//! that there is no native disable field (GEM-7), that any non-empty name
31//! loads (GEM-8), that Windows starts `npx` without `cmd /c` (GEM-9) and
32//! the detection probes (GEM-10). `~/.gemini` alone does not detect
33//! Gemini, since Antigravity keeps its files there too.
34
35use crate::adapters::caps::{
36    Caps, EnvRefSyntax, FieldSet, ProjectDisable, ProjectSemantics, Source, TimeUnit, TimeoutField,
37    ToolFilterMech, TransportSet, TrustGate,
38};
39use crate::adapters::detect::Probe;
40use crate::adapters::location::Location;
41use crate::adapters::mapper::{
42    Canonical, EntryMapper, Launch, MapError, RenderedServer, ServerDef, WriteCx, carry_over,
43    check_name, check_transport, drop_empty, existing_entry, is_tool_key, read_disabled,
44    read_tools, shape, split_rest, string_field, string_list, string_map, string_map_field,
45    strings, unsupported, write_enabled, write_passthrough, write_tools,
46};
47use crate::adapters::spec::{AdapterSpec, ContainerPath, McpSpec, Tier, exact_names};
48use crate::env::Os;
49use crate::formats::{Format, NativeMap, NativeValue};
50use crate::model::clients::passthrough_of;
51use crate::model::server::{ServerFields, Transport};
52
53pub const ID: &str = "gemini";
54
55const TYPE: &str = "type";
56const URL: &str = "url";
57const HTTP_URL: &str = "httpUrl";
58const INCLUDE_TOOLS: &str = "includeTools";
59const EXCLUDE_TOOLS: &str = "excludeTools";
60
61/// The list a project hides user servers with, in the project file.
62pub const EXCLUDED: ContainerPath = ContainerPath(&["mcp", "excluded"]);
63
64const CAPS: Caps = Caps {
65    transports: TransportSet::ALL,
66    env_ref: Some(EnvRefSyntax::DollarBrace {
67        default: false,
68        bare: true,
69    }),
70    env_ref_fields: FieldSet::COMMAND
71        .union(FieldSet::ARGS)
72        .union(FieldSet::ENV)
73        .union(FieldSet::CWD)
74        .union(FieldSet::URL)
75        .union(FieldSet::HEADERS),
76    command_ref: None,
77    native_disable: None,
78    project_disable: Some(ProjectDisable::ListMember(EXCLUDED)),
79    project_semantics: ProjectSemantics::DeepMerge,
80    precedence: &[Source::Project, Source::User],
81    compat_reads: &[],
82    trust_gate: Some(TrustGate::TrustedFolder),
83    rewrites_file_at_runtime: false,
84    restart_required: false,
85    tool_filter: Some(ToolFilterMech::AllowDeny {
86        allow: INCLUDE_TOOLS,
87        deny: EXCLUDE_TOOLS,
88    }),
89    windows_shell_shim: false,
90    timeouts: &[TimeoutField {
91        key: "timeout",
92        unit: TimeUnit::Milliseconds,
93    }],
94    passthrough_allowlist: passthrough_of(ID),
95};
96
97/// Keys the Gemini mapper models besides the tool lists and passthrough.
98const MODELED_KEYS: [&str; 8] = [
99    TYPE, "command", "args", "env", "cwd", URL, HTTP_URL, "headers",
100];
101
102fn is_modeled(key: &str) -> bool {
103    MODELED_KEYS.contains(&key)
104        || is_tool_key(&CAPS, key)
105        || CAPS.passthrough_allowlist.contains(&key)
106}
107
108fn valid_name(name: &str) -> bool {
109    !name.is_empty()
110}
111
112/// The transport Gemini gives an entry without `type`, in the order it
113/// checks the keys: `httpUrl`, then `url`, then `command`.
114fn inferred(entry: &NativeMap) -> Option<Transport> {
115    if entry.contains_key(HTTP_URL) {
116        Some(Transport::Http)
117    } else if entry.contains_key(URL) {
118        Some(Transport::Sse)
119    } else if entry.contains_key("command") {
120        Some(Transport::Stdio)
121    } else {
122        None
123    }
124}
125
126/// The `mcpServers.<name>` entry of Gemini's settings file (see the
127/// module docs).
128#[derive(Debug)]
129pub struct GeminiJson;
130
131impl EntryMapper for GeminiJson {
132    fn to_native(
133        &self,
134        server: &RenderedServer,
135        cx: &WriteCx<'_>,
136    ) -> Result<NativeValue, MapError> {
137        check_name(valid_name, &server.name)?;
138        let transport = check_transport(&CAPS, &server.launch)?;
139        let existing = existing_entry(cx);
140        let keep_empty = |key: &str| existing.is_some_and(|entry| entry.contains_key(key));
141        let mut entry = NativeMap::new();
142        match &server.launch {
143            Launch::Stdio(stdio) => {
144                if !stdio.forward_env.is_empty() {
145                    return unsupported("env_vars");
146                }
147                entry.insert("command", stdio.command.as_str().into());
148                entry.insert("args", strings(stdio.args.clone()));
149                if !stdio.env.is_empty() || keep_empty("env") {
150                    entry.insert("env", string_map(&stdio.env));
151                }
152                if let Some(cwd) = &stdio.cwd {
153                    entry.insert("cwd", cwd.as_str().into());
154                }
155            }
156            Launch::Http(remote) | Launch::Sse(remote) => {
157                if remote.headers_helper.is_some() {
158                    return unsupported("headersHelper");
159                }
160                if remote.bearer_env.is_some() {
161                    return unsupported("bearer_token_env_var");
162                }
163                if !remote.headers_env.is_empty() {
164                    return unsupported("env_http_headers");
165                }
166                let key = match transport {
167                    Transport::Http => HTTP_URL,
168                    Transport::Sse | Transport::Stdio => URL,
169                };
170                entry.insert(key, remote.url.as_str().into());
171                if !remote.headers.is_empty() || keep_empty("headers") {
172                    entry.insert("headers", string_map(&remote.headers));
173                }
174            }
175        }
176        write_enabled(&mut entry, &CAPS, server, existing)?;
177        write_tools(&mut entry, &CAPS, &server.tools)?;
178        write_passthrough(&mut entry, &CAPS, server)?;
179        carry_over(&mut entry, existing, is_modeled);
180        Ok(NativeValue::Object(entry))
181    }
182
183    fn from_native(&self, key: &str, value: &NativeValue) -> Result<ServerDef, MapError> {
184        let entry = value.as_object().ok_or_else(|| MapError::UnexpectedShape {
185            field: key.to_owned(),
186            expected: "an object",
187        })?;
188        // SPEC 7.5: an explicit `type` wins; else `httpUrl` is http and a
189        // bare `url` SSE.
190        let transport = match entry.get(TYPE) {
191            Some(NativeValue::String(kind)) => match kind.as_str() {
192                "stdio" => Transport::Stdio,
193                "http" => Transport::Http,
194                "sse" => Transport::Sse,
195                other => {
196                    return Err(MapError::UnsupportedTransport {
197                        transport: other.to_owned(),
198                    });
199                }
200            },
201            Some(_) => return shape(TYPE, "a string"),
202            None => match inferred(entry) {
203                Some(transport) => transport,
204                None => return shape("command", "set (or `httpUrl` or `url` for a remote server)"),
205            },
206        };
207        let http_url = string_field(entry, HTTP_URL)?;
208        let url = string_field(entry, URL)?;
209        let url = match transport {
210            Transport::Http => http_url.or(url),
211            Transport::Sse | Transport::Stdio => url.or(http_url),
212        };
213        let fields = ServerFields {
214            transport: Some(transport),
215            command: string_field(entry, "command")?,
216            args: string_list(entry, "args")?,
217            cwd: string_field(entry, "cwd")?,
218            url,
219            headers: string_map_field(entry, "headers")?,
220            env: string_map_field(entry, "env")?,
221        };
222        let mut def = ServerDef {
223            fields,
224            disabled: read_disabled(entry, &CAPS)?,
225            tools: read_tools(entry, &CAPS)?,
226            ..ServerDef::default()
227        };
228        split_rest(&mut def, entry, &CAPS, is_modeled);
229        Ok(def)
230    }
231
232    fn canonical(&self, value: &NativeValue) -> Canonical {
233        let Some(entry) = value.as_object() else {
234            return Canonical::of(value);
235        };
236        let mut entry = entry.clone();
237        // `{"type": "http", "url": u}` is Surjection's `{"httpUrl": u}`; a
238        // `type` naming the transport its keys imply is dropped.
239        let kind = entry
240            .get(TYPE)
241            .and_then(NativeValue::as_str)
242            .map(str::to_owned);
243        match kind.as_deref() {
244            Some("http") if !entry.contains_key(HTTP_URL) && entry.contains_key(URL) => {
245                if let Some(url) = entry.remove(URL) {
246                    entry.insert(HTTP_URL, url);
247                }
248                entry.remove(TYPE);
249            }
250            Some(kind) if inferred(&entry).map(Transport::as_str) == Some(kind) => {
251                entry.remove(TYPE);
252            }
253            _ => {}
254        }
255        // Gemini runs an untyped entry with `httpUrl` over Streamable HTTP
256        // and ignores its `url` (`[verify]` GEM-3).
257        if entry.contains_key(HTTP_URL) && !entry.contains_key(TYPE) {
258            entry.remove(URL);
259        }
260        // An empty `includeTools` allows no tool, so it is not a default.
261        drop_empty(&mut entry, &["args", "env", "headers", EXCLUDE_TOOLS]);
262        Canonical::of(&NativeValue::Object(entry))
263    }
264}
265
266static MAPPER: GeminiJson = GeminiJson;
267
268pub static SPEC: AdapterSpec = AdapterSpec {
269    id: ID,
270    display_name: "Gemini CLI",
271    tier: Tier::C,
272    detect: &[
273        Probe::Path(Location::Home(".gemini/settings.json")),
274        Probe::Executable("gemini"),
275    ],
276    mcp: Some(McpSpec {
277        oses: &[Os::Windows, Os::Linux, Os::MacOs],
278        read_only: false,
279        user: &[Location::Home(".gemini/settings.json")],
280        user_files: None,
281        user_mirrors: &[],
282        profiles: None,
283        project: &[Location::Project(".gemini/settings.json")],
284        project_local: &[],
285        format: Format::Json,
286        skeleton: "",
287        container: ContainerPath(&["mcpServers"]),
288        project_local_container: ContainerPath(&["mcpServers"]),
289        legacy_containers: &[],
290        same_name: exact_names,
291        replaced_by: &[],
292        mapper: &MAPPER,
293        caps: CAPS,
294        sign_in: crate::adapters::sign_in::GEMINI,
295    }),
296};