Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
codex_mcp.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The MCP servers a Codex `exec` turn gets: AgentMux's own `agentmux` server
5//! and the catalog servers, from the `.mcp.json` the launch wrote in the
6//! agent's folder, as `-c mcp_servers.<name>.<key>=<toml>` overrides.
7//! `SPEC_CONNECTORS_MCP_WHAT_AGENTS_RUN_2026_10_10.md` ยง5.
8//!
9//! The overrides are on the command line, which other processes on the machine
10//! can read, so no secret goes in them. A value in a server's `env` or
11//! `headers`, where a key lives, is not written there: it travels in the
12//! environment the Codex process is launched with, and the server asks Codex to
13//! forward it by NAME (`env_vars`, `env_http_headers`, `bearer_token_env_var`).
14//! A `${VAR}` that is the whole of such a value is forwarded the same way, from
15//! the environment the agent was launched with. A command, argument or url is
16//! written as it is in `.mcp.json`; a server with a variable in one, or with a
17//! variable mixed into other text in an env or header value, is left out and
18//! named in the log, never written with the variable's value.
19
20use std::collections::HashMap;
21
22use serde_json::Value;
23
24use super::super::acp_mcp::{resolve_command, server_kind};
25
26/// Finds a bare command's absolute path (`resolve_command` in the product).
27type Resolve<'a> = &'a dyn Fn(&str) -> Option<String>;
28
29/// What [`codex_mcp_overrides`] made of a `.mcp.json`.
30#[derive(Debug, Default, PartialEq)]
31pub(super) struct CodexMcp {
32    /// `-c`, `key=value` pairs to put after `exec`.
33    pub overrides: Vec<String>,
34    /// Variables to launch Codex with, which the servers' `env_vars` and
35    /// `env_http_headers` forward by name.
36    pub env: Vec<(String, String)>,
37    /// Servers left out, with why. Names only; never a value.
38    pub skipped: Vec<(String, &'static str)>,
39}
40
41/// A TOML basic string. JSON's string escapes are valid TOML ones.
42fn toml_str(s: &str) -> String {
43    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_string())
44}
45
46fn toml_key(k: &str) -> String {
47    if !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') {
48        k.to_string()
49    } else {
50        toml_str(k)
51    }
52}
53
54fn toml_array(items: &[String]) -> String {
55    format!("[{}]", items.iter().map(|i| toml_str(i)).collect::<Vec<_>>().join(","))
56}
57
58fn toml_table(pairs: &[(String, String)]) -> String {
59    format!("{{{}}}", pairs.iter().map(|(k, v)| format!("{}={}", toml_key(k), toml_str(v))).collect::<Vec<_>>().join(","))
60}
61
62/// Codex accepts a server name of letters, digits, `_` and `-` only.
63fn valid_name(name: &str) -> bool {
64    !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
65}
66
67/// The text of a JSON string, number or bool value; `None` for anything else.
68pub(super) fn scalar(v: &Value) -> Option<String> {
69    match v {
70        Value::String(s) => Some(s.clone()),
71        Value::Number(_) | Value::Bool(_) => Some(v.to_string()),
72        _ => None,
73    }
74}
75
76/// `${NAME}` when `raw` is exactly that.
77fn whole_placeholder(raw: &str) -> Option<&str> {
78    raw.strip_prefix("${")?.strip_suffix('}').filter(|n| !n.is_empty() && !n.contains(['$', '{', '}', ':']))
79}
80
81/// What one server needs: its overrides, and the variables the Codex process
82/// must be launched with for `env_vars` and `env_http_headers` to forward.
83#[derive(Default)]
84struct Plan {
85    overrides: Vec<(String, String)>,
86    env: Vec<(String, String)>,
87}
88
89/// A name Codex can forward from its own environment.
90fn valid_env_name(k: &str) -> bool {
91    let mut chars = k.chars();
92    chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
93}
94
95/// One server's plan, or why it can't be given without a secret on the
96/// command line. `slot` numbers the server among those given, for the names of
97/// the variables its literal header values travel in.
98fn server_plan(
99    name: &str,
100    cfg: &Value,
101    kind: &str,
102    slot: usize,
103    agent_env: &HashMap<String, String>,
104    resolve: Resolve,
105) -> Result<Plan, &'static str> {
106    // A command, argument or url is written as it is, so one that holds a
107    // variable can't be given without putting its value on the command line.
108    let x = |v: &str| if v.contains("${") { Err("a command, argument or url holds a variable") } else { Ok(v.to_string()) };
109    let mut plan = Plan::default();
110    let mut put = |key: &str, value: String| plan.overrides.push((format!("mcp_servers.{name}.{key}"), value));
111    if kind == "stdio" {
112        let command = x(cfg.get("command").and_then(Value::as_str).ok_or("no command")?)?;
113        put("command", toml_str(&resolve(&command).unwrap_or(command)));
114        let args = cfg.get("args").and_then(Value::as_array).into_iter().flatten().filter_map(scalar).map(|v| x(&v)).collect::<Result<Vec<_>, _>>()?;
115        put("args", toml_array(&args));
116        let (set_env, forwarded) = split_env(cfg.get("env"), name == "agentmux", agent_env)?;
117        if !forwarded.is_empty() {
118            put("env_vars", toml_array(&forwarded));
119        }
120        plan.env = set_env;
121    } else {
122        let url = x(cfg.get("url").and_then(Value::as_str).ok_or("no url")?)?;
123        put("url", toml_str(&url));
124        let (from_env, bearer, set_env) = split_headers(cfg.get("headers"), slot)?;
125        if !from_env.is_empty() {
126            put("env_http_headers", toml_table(&from_env));
127        }
128        if let Some(var) = bearer {
129            put("bearer_token_env_var", toml_str(&var));
130        }
131        plan.env = set_env;
132    }
133    Ok(plan)
134}
135
136/// A stdio server's `env`: the variables to launch Codex with (a literal value
137/// travels in the environment too, since an `env` table would put it on the
138/// command line) and the names Codex forwards to the server. For `agentmux`,
139/// also every `AGENTMUX_` variable the agent was launched with (its endpoint,
140/// keys and identity), since Codex gives a server only a small set of its own;
141/// the agent's own value of such a variable wins over a copy in `.mcp.json`.
142#[allow(clippy::type_complexity)]
143fn split_env(env: Option<&Value>, is_agentmux: bool, agent_env: &HashMap<String, String>) -> Result<(Vec<(String, String)>, Vec<String>), &'static str> {
144    let mut set_env = Vec::new();
145    let mut forwarded: Vec<String> = Vec::new();
146    for (key, raw) in env.and_then(Value::as_object).into_iter().flatten() {
147        let Some(raw) = scalar(raw) else { continue };
148        if !valid_env_name(key) {
149            return Err("an env name Codex can't forward");
150        }
151        if !raw.contains("${") {
152            let own = is_agentmux && key.starts_with("AGENTMUX_") && agent_env.contains_key(key);
153            if !own {
154                set_env.push((key.clone(), raw));
155            }
156            forwarded.push(key.clone());
157        } else if let Some(source) = whole_placeholder(&raw) {
158            // The server's `KEY` is read from the variable `source`. Codex forwards a
159            // name as it is, so another source's value is staged under `KEY`; a
160            // source the turn does not have gives the server no `KEY`.
161            if source != key {
162                if let Some(value) = env_value(agent_env, source) {
163                    set_env.push((key.clone(), value.clone()));
164                    forwarded.push(key.clone());
165                }
166            } else {
167                forwarded.push(key.clone());
168            }
169        } else {
170            return Err("an env value mixes a variable into other text");
171        }
172    }
173    if is_agentmux {
174        let mut names: Vec<&String> = agent_env.keys().filter(|k| k.starts_with("AGENTMUX_") && !forwarded.contains(k)).collect();
175        names.sort();
176        forwarded.extend(names.into_iter().cloned());
177    }
178    Ok((set_env, forwarded))
179}
180
181/// An http server's `headers`: the headers Codex reads from a variable, the
182/// variable behind `Authorization: Bearer ${VAR}`, and the variables to launch
183/// Codex with for the literal headers (a header value is as likely a key as an
184/// env value is, so it never goes on the command line either).
185#[allow(clippy::type_complexity)]
186fn split_headers(headers: Option<&Value>, slot: usize) -> Result<(Vec<(String, String)>, Option<String>, Vec<(String, String)>), &'static str> {
187    let (mut from_env, mut bearer, mut set_env) = (Vec::new(), None, Vec::new());
188    for (i, (header, raw)) in headers.and_then(Value::as_object).into_iter().flatten().enumerate() {
189        let Some(raw) = scalar(raw) else { continue };
190        if !raw.contains("${") {
191            let var = format!("AGENTMUX_MCP_S{slot}_H{i}");
192            from_env.push((header.clone(), var.clone()));
193            set_env.push((var, raw));
194        } else if let Some(var) = whole_placeholder(&raw) {
195            from_env.push((header.clone(), var.to_string()));
196        } else if let Some(var) = header.eq_ignore_ascii_case("authorization").then(|| raw.strip_prefix("Bearer ")).flatten().and_then(whole_placeholder) {
197            bearer = Some(var.to_string());
198        } else {
199            return Err("a header value mixes a variable into other text");
200        }
201    }
202    Ok((from_env, bearer, set_env))
203}
204
205/// The `-c` overrides for the servers in `mcp_json`, and the variables to
206/// launch Codex with for them. `agent_env` is the environment the turn is
207/// launched with (see [`launch_env`]). A server of a kind Codex can't take
208/// (`sse`), one that is switched off, or one whose name Codex refuses is left
209/// out; so is one that would need a secret on the command line, or sets a
210/// variable Codex already has to another value.
211pub(super) fn codex_mcp_overrides(mcp_json: &str, agent_env: &HashMap<String, String>, resolve: Resolve) -> CodexMcp {
212    let mut result = CodexMcp::default();
213    let Ok(root) = serde_json::from_str::<Value>(mcp_json) else { return result };
214    let Some(servers) = root.get("mcpServers").and_then(Value::as_object) else { return result };
215    let mut given = 0;
216    for (name, cfg) in servers {
217        let Some(kind) = server_kind(cfg) else { continue };
218        let plan = if kind == "sse" {
219            Err("Codex takes no sse server")
220        } else if !valid_name(name) {
221            Err("Codex takes only letters, digits, _ and - in a server name")
222        } else {
223            server_plan(name, cfg, kind, given, agent_env, resolve).and_then(|plan| {
224                let taken = |k: &String, v: &String| env_value(agent_env, k).is_some_and(|o| o != v) || result.env.iter().any(|(rk, rv)| rk.eq_ignore_ascii_case(k) && rv != v);
225                if plan.env.iter().any(|(k, v)| taken(k, v)) { Err("an env name is already set to another value for this turn") } else { Ok(plan) }
226            })
227        };
228        match plan {
229            Ok(plan) => {
230                given += 1;
231                for (key, value) in plan.overrides {
232                    result.overrides.push("-c".to_string());
233                    result.overrides.push(format!("{key}={value}"));
234                }
235                result.env.extend(plan.env);
236            }
237            Err(why) => result.skipped.push((name.clone(), why)),
238        }
239    }
240    result
241}
242
243/// `argv` with `overrides` right after the `exec` subcommand, where the other
244/// provider flags are; unchanged when there is none or no `exec`.
245pub(super) fn with_overrides(argv: &[String], overrides: &[String]) -> Vec<String> {
246    let mut out = argv.to_vec();
247    if let Some(at) = out.iter().position(|a| a == "exec") {
248        out.splice(at + 1..at + 1, overrides.iter().cloned());
249    }
250    out
251}
252
253/// The environment the Codex process starts with: srv's own, except the
254/// AgentMux variables a pane must not inherit (`pane_env`), then the turn's
255/// own, which win. The servers' forwarding needs it for two things: Codex gives
256/// a server only the names it is told to forward, and `agentmux-mcp` needs
257/// srv's endpoint, which is inherited, not in the turn's own variables; and a
258/// server's literal env value must not replace a variable Codex already has.
259pub(super) fn launch_env(inherited: impl Iterator<Item = (String, String)>, own: &HashMap<String, String>) -> HashMap<String, String> {
260    let mut env: HashMap<String, String> = inherited.filter(|(k, _)| !crate::backend::pane_env::should_strip(k)).collect();
261    env.extend(own.iter().map(|(k, v)| (k.clone(), v.clone())));
262    env
263}
264
265/// The value `env` has for `name`; a Windows name is matched without regard to case.
266pub(super) fn env_value<'a>(env: &'a HashMap<String, String>, name: &str) -> Option<&'a String> {
267    if cfg!(windows) { env.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v) } else { env.get(name) }
268}
269
270/// Launch the Codex process with the variables its servers forward by name.
271/// Set as they are, after the agent's own, which [`codex_mcp_overrides`] has
272/// checked they do not contradict.
273pub(super) fn apply_env(cmd: &mut tokio::process::Command, env: &[(String, String)]) {
274    for (k, v) in env {
275        cmd.env(k, v);
276    }
277}
278
279impl super::SubprocessController {
280    /// What this turn adds for MCP: those of the `.mcp.json` in the turn's
281    /// folder when it is a Codex `exec` turn on the host, else nothing.
282    pub(super) fn codex_mcp(&self, config: &super::SubprocessSpawnConfig) -> CodexMcp {
283        if config.resume_strategy != "codex-exec" || config.working_dir.is_empty() {
284            return CodexMcp::default();
285        }
286        // The folder as the spawn expands it (`~` is the home directory). The config may be
287        // outside it (#3680); `read_for_turn` finds it and keeps the project's own servers.
288        let folder = crate::backend::blockcontroller::core::expand_home_dir(&config.working_dir);
289        let Some(raw) = crate::backend::mcp_config_file::read_for_turn(&folder) else { return CodexMcp::default() };
290        let path = config.env_vars.get("PATH").cloned();
291        let env = launch_env(std::env::vars(), &config.env_vars);
292        let made = codex_mcp_overrides(&raw, &env, &|c| resolve_command(c, path.as_deref()));
293        for (name, why) in &made.skipped {
294            tracing::warn!(block_id = %self.block_id, server = %name, why = %why, "MCP server not given to this Codex turn");
295        }
296        made
297    }
298}
299
300#[cfg(test)]
301#[path = "codex_mcp_tests.rs"]
302mod tests;