Skip to main content

surjection_core/adapters/
codex.rs

1//! Codex (`codex`): SPEC 7.3 and 7.4.
2//!
3//! - User scope: `$CODEX_HOME/config.toml` when `CODEX_HOME` is an absolute
4//!   path, else `~/.codex/config.toml`.
5//! - Project scope: `<P>/.codex/config.toml`, loaded by Codex only for
6//!   trusted projects.
7//! - Entries: `[mcp_servers.<name>]`. The legacy `[mcp.servers.<name>]`
8//!   table is read (import) and never edited or deleted.
9//! - Codex expands no `${...}` references: `env` delivery forwards a parent
10//!   variable by name (`env_vars`, `bearer_token_env_var`,
11//!   `env_http_headers`). No SSE.
12
13use std::collections::BTreeMap;
14
15use crate::adapters::caps::{
16    Caps, DisableMech, EnvRefSyntax, FieldSet, ProjectDisable, ProjectSemantics, Source, TimeUnit,
17    TimeoutField, ToolFilterMech, TransportSet, TrustGate,
18};
19use crate::adapters::detect::Probe;
20use crate::adapters::location::Location;
21use crate::adapters::mapper::{
22    Canonical, EntryMapper, Launch, MapError, RenderedServer, ServerDef, WriteCx, carry_over,
23    check_name, check_transport, dotted_word_name, drop_default_enabled, drop_empty,
24    existing_entry, is_tool_key, read_disabled, read_tools, shape, split_rest, string_field,
25    string_list, string_map, string_map_field, strings, unsupported, write_enabled,
26    write_passthrough, write_tools,
27};
28use crate::adapters::spec::{AdapterSpec, ContainerPath, McpSpec, Tier, exact_names};
29use crate::env::Os;
30use crate::formats::{Format, NativeMap, NativeValue};
31use crate::model::clients::passthrough_of;
32use crate::model::server::{ServerFields, Transport};
33
34pub const ID: &str = "codex";
35
36/// `~/.codex`, or `$CODEX_HOME`.
37const CODEX_DIR: Location = Location::EnvDir {
38    var: "CODEX_HOME",
39    fallback: &Location::Home(".codex"),
40    rel: "",
41    tilde: false,
42};
43
44/// `~/.codex/config.toml`, or `$CODEX_HOME/config.toml`.
45const USER_FILE: Location = Location::EnvDir {
46    var: "CODEX_HOME",
47    fallback: &Location::Home(".codex"),
48    rel: "config.toml",
49    tilde: false,
50};
51
52const CAPS: Caps = Caps {
53    transports: TransportSet::STDIO_HTTP,
54    env_ref: Some(EnvRefSyntax::CodexForward),
55    env_ref_fields: FieldSet::ENV.union(FieldSet::HEADERS),
56    command_ref: None,
57    native_disable: Some(DisableMech::EnabledFalse),
58    // `[verify]` that a project `enabled = false` merges over the user
59    // entry of the same name.
60    project_disable: Some(ProjectDisable::EnabledFalse { partial: true }),
61    // `[verify]` deep merge of project over user entries.
62    project_semantics: ProjectSemantics::DeepMerge,
63    precedence: &[Source::Project, Source::User],
64    compat_reads: &[],
65    trust_gate: Some(TrustGate::TrustedProject),
66    rewrites_file_at_runtime: false,
67    restart_required: false,
68    tool_filter: Some(ToolFilterMech::AllowDeny {
69        allow: ENABLED_TOOLS,
70        deny: DISABLED_TOOLS,
71    }),
72    // `[verify]` whether Codex on Windows starts `npx` without `cmd /c`.
73    windows_shell_shim: false,
74    timeouts: &[
75        TimeoutField {
76            key: "startup_timeout_sec",
77            unit: TimeUnit::Seconds,
78        },
79        TimeoutField {
80            key: "tool_timeout_sec",
81            unit: TimeUnit::Seconds,
82        },
83    ],
84    passthrough_allowlist: passthrough_of(ID),
85};
86
87const ENABLED_TOOLS: &str = "enabled_tools";
88const DISABLED_TOOLS: &str = "disabled_tools";
89const ENV_VARS: &str = "env_vars";
90const BEARER: &str = "bearer_token_env_var";
91const HTTP_HEADERS: &str = "http_headers";
92const ENV_HTTP_HEADERS: &str = "env_http_headers";
93
94/// Keys the Codex mapper models besides the tool lists and passthrough.
95const MODELED_KEYS: [&str; 10] = [
96    "command",
97    "args",
98    "env",
99    ENV_VARS,
100    "cwd",
101    "url",
102    BEARER,
103    HTTP_HEADERS,
104    ENV_HTTP_HEADERS,
105    "enabled",
106];
107
108/// The `[mcp_servers.<name>]` table: `command, args, env, env_vars, cwd` or
109/// `url, bearer_token_env_var, http_headers, env_http_headers`, plus
110/// `enabled`, `enabled_tools`, `disabled_tools` and the timeouts. Names
111/// are `[A-Za-z0-9_.-]+` (gate V1, CX-6).
112#[derive(Debug)]
113pub struct CodexToml;
114
115fn is_modeled(key: &str) -> bool {
116    MODELED_KEYS.contains(&key)
117        || is_tool_key(&CAPS, key)
118        || CAPS.passthrough_allowlist.contains(&key)
119}
120
121impl EntryMapper for CodexToml {
122    fn to_native(
123        &self,
124        server: &RenderedServer,
125        cx: &WriteCx<'_>,
126    ) -> Result<NativeValue, MapError> {
127        check_name(dotted_word_name, &server.name)?;
128        check_transport(&CAPS, &server.launch)?;
129        let existing = existing_entry(cx);
130        let keep_empty = |key: &str| existing.is_some_and(|entry| entry.contains_key(key));
131        let mut entry = NativeMap::new();
132        match &server.launch {
133            Launch::Stdio(stdio) => {
134                entry.insert("command", stdio.command.as_str().into());
135                entry.insert("args", strings(stdio.args.clone()));
136                if !stdio.env.is_empty() || keep_empty("env") {
137                    entry.insert("env", string_map(&stdio.env));
138                }
139                if !stdio.forward_env.is_empty() || keep_empty(ENV_VARS) {
140                    entry.insert(ENV_VARS, strings(stdio.forward_env.clone()));
141                }
142                if let Some(cwd) = &stdio.cwd {
143                    entry.insert("cwd", cwd.as_str().into());
144                }
145            }
146            Launch::Http(remote) => {
147                if remote.headers_helper.is_some() {
148                    return unsupported("headersHelper");
149                }
150                entry.insert("url", remote.url.as_str().into());
151                if let Some(variable) = &remote.bearer_env {
152                    entry.insert(BEARER, variable.as_str().into());
153                }
154                if !remote.headers.is_empty() || keep_empty(HTTP_HEADERS) {
155                    entry.insert(HTTP_HEADERS, string_map(&remote.headers));
156                }
157                if !remote.headers_env.is_empty() || keep_empty(ENV_HTTP_HEADERS) {
158                    entry.insert(ENV_HTTP_HEADERS, string_map(&remote.headers_env));
159                }
160            }
161            Launch::Sse(_) => unreachable!("check_transport rejects SSE for Codex"),
162        }
163        write_enabled(&mut entry, &CAPS, server, existing)?;
164        write_tools(&mut entry, &CAPS, &server.tools)?;
165        write_passthrough(&mut entry, &CAPS, server)?;
166        carry_over(&mut entry, existing, is_modeled);
167        Ok(NativeValue::Object(entry))
168    }
169
170    fn from_native(&self, key: &str, value: &NativeValue) -> Result<ServerDef, MapError> {
171        let entry = value.as_object().ok_or_else(|| MapError::UnexpectedShape {
172            field: key.to_owned(),
173            expected: "a table",
174        })?;
175        let fields = match (entry.contains_key("command"), entry.contains_key("url")) {
176            (true, true) => return shape("url", "absent when `command` is set"),
177            (true, false) => {
178                // Forwarded variables read as references; an explicit `env`
179                // value for the same name wins, as it is the literal one.
180                let mut env = forwarded(env_var_names(entry)?);
181                env.extend(string_map_field(entry, "env")?.unwrap_or_default());
182                ServerFields {
183                    transport: Some(Transport::Stdio),
184                    command: string_field(entry, "command")?,
185                    args: string_list(entry, "args")?,
186                    cwd: string_field(entry, "cwd")?,
187                    env: (!env.is_empty()).then_some(env),
188                    ..ServerFields::default()
189                }
190            }
191            (false, true) => {
192                let mut headers = BTreeMap::new();
193                if let Some(variable) = string_field(entry, BEARER)? {
194                    headers.insert(
195                        "Authorization".to_owned(),
196                        format!("Bearer {}", env_ref(&variable)),
197                    );
198                }
199                for (header, variable) in
200                    string_map_field(entry, ENV_HTTP_HEADERS)?.unwrap_or_default()
201                {
202                    headers.insert(header, env_ref(&variable));
203                }
204                headers.extend(string_map_field(entry, HTTP_HEADERS)?.unwrap_or_default());
205                ServerFields {
206                    transport: Some(Transport::Http),
207                    url: string_field(entry, "url")?,
208                    headers: (!headers.is_empty()).then_some(headers),
209                    ..ServerFields::default()
210                }
211            }
212            (false, false) => return shape("command", "set (or `url` for a remote server)"),
213        };
214        let mut def = ServerDef {
215            fields,
216            disabled: read_disabled(entry, &CAPS)?,
217            tools: read_tools(entry, &CAPS)?,
218            ..ServerDef::default()
219        };
220        split_rest(&mut def, entry, &CAPS, is_modeled);
221        Ok(def)
222    }
223
224    fn canonical(&self, value: &NativeValue) -> Canonical {
225        let Some(entry) = value.as_object() else {
226            return Canonical::of(value);
227        };
228        let mut entry = entry.clone();
229        // An empty `enabled_tools` allows no tool, so it is not a default.
230        drop_empty(
231            &mut entry,
232            &[
233                "args",
234                "env",
235                ENV_VARS,
236                HTTP_HEADERS,
237                ENV_HTTP_HEADERS,
238                DISABLED_TOOLS,
239            ],
240        );
241        drop_default_enabled(&mut entry, &CAPS);
242        Canonical::of(&NativeValue::Object(entry))
243    }
244}
245
246/// `${env:NAME}` (SPEC 11.2).
247fn env_ref(name: &str) -> String {
248    format!("${{env:{name}}}")
249}
250
251/// `NAME = "${env:NAME}"` for each forwarded variable.
252fn forwarded(names: Vec<String>) -> BTreeMap<String, String> {
253    names
254        .into_iter()
255        .map(|name| {
256            let value = env_ref(&name);
257            (name, value)
258        })
259        .collect()
260}
261
262/// The names in `env_vars`: strings, or tables with a `name` and an
263/// optional `source = "local"`.
264fn env_var_names(entry: &NativeMap) -> Result<Vec<String>, MapError> {
265    const EXPECTED: &str = "an array of variable names (or `{ name, source = \"local\" }` tables)";
266    let Some(value) = entry.get(ENV_VARS) else {
267        return Ok(Vec::new());
268    };
269    let items = value.as_array().ok_or_else(|| MapError::UnexpectedShape {
270        field: ENV_VARS.to_owned(),
271        expected: EXPECTED,
272    })?;
273    items
274        .iter()
275        .map(|item| match item {
276            NativeValue::String(name) => Some(name.clone()),
277            NativeValue::Object(table) => {
278                let local = table
279                    .get("source")
280                    .is_none_or(|source| source.as_str() == Some("local"));
281                let only_known = table.keys().all(|key| key == "name" || key == "source");
282                table
283                    .get("name")
284                    .and_then(NativeValue::as_str)
285                    .filter(|_| local && only_known)
286                    .map(str::to_owned)
287            }
288            _ => None,
289        })
290        .collect::<Option<Vec<_>>>()
291        .ok_or_else(|| MapError::UnexpectedShape {
292            field: ENV_VARS.to_owned(),
293            expected: EXPECTED,
294        })
295}
296
297static MAPPER: CodexToml = CodexToml;
298
299pub static SPEC: AdapterSpec = AdapterSpec {
300    id: ID,
301    display_name: "Codex",
302    tier: Tier::A,
303    detect: &[Probe::Path(CODEX_DIR), Probe::Executable("codex")],
304    mcp: Some(McpSpec {
305        oses: &[Os::Windows, Os::Linux, Os::MacOs],
306        read_only: false,
307        user: &[USER_FILE],
308        user_files: None,
309        user_mirrors: &[],
310        profiles: None,
311        project: &[Location::Project(".codex/config.toml")],
312        project_local: &[],
313        format: Format::Toml,
314        skeleton: "",
315        container: ContainerPath(&["mcp_servers"]),
316        project_local_container: ContainerPath(&["mcp_servers"]),
317        legacy_containers: &[ContainerPath(&["mcp", "servers"])],
318        same_name: exact_names,
319        replaced_by: &[],
320        mapper: &MAPPER,
321        caps: CAPS,
322        sign_in: crate::adapters::sign_in::CODEX,
323    }),
324};