1use tracevault_cli::agent::Agent;
9
10use std::path::Path;
11
12use super::{read_optional, run_command, AgentAdapter, AgentPaths, McpEntry, McpScope, Workdir};
13use crate::finding::FixAction;
14
15pub struct Codex {
16 paths: AgentPaths,
17 program: String,
18}
19
20impl Codex {
21 pub fn new(paths: AgentPaths, program_override: Option<String>) -> Self {
22 Codex {
23 paths,
24 program: program_override.unwrap_or_else(|| "codex".to_string()),
25 }
26 }
27}
28
29fn read_servers(path: &Path, scope: McpScope, out: &mut Vec<McpEntry>) -> Result<(), String> {
32 let Some(text) = read_optional(path)? else {
33 return Ok(());
34 };
35 let config: toml::Value =
36 toml::from_str(&text).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
37 let Some(servers) = config.get("mcp_servers").and_then(|s| s.as_table()) else {
38 return Ok(());
39 };
40 let text = |v: Option<&toml::Value>| v.and_then(|v| v.as_str()).map(String::from);
41 let only = |v: Option<&toml::Value>, known: &[&str]| {
42 v.and_then(|v| v.as_table())
43 .is_none_or(|t| t.keys().all(|k| known.contains(&k.as_str())))
44 };
45 for (name, server) in servers {
46 if out.iter().any(|e| &e.name == name) {
47 continue;
48 }
49 out.push(McpEntry {
50 name: name.clone(),
51 url: text(server.get("url")),
52 oauth_client_id: text(server.get("oauth").and_then(|o| o.get("client_id"))),
53 scope,
54 extra_settings: !only(Some(server), &["url", "oauth", "enabled"])
55 || !only(server.get("oauth"), &["client_id"]),
56 disabled: server.get("enabled").and_then(|e| e.as_bool()) == Some(false),
57 });
58 }
59 Ok(())
60}
61
62impl AgentAdapter for Codex {
63 fn agent(&self) -> Agent {
64 Agent::Codex
65 }
66
67 fn program(&self) -> &str {
68 &self.program
69 }
70
71 fn mcp_entries(&self, workdir: &Workdir) -> Result<Vec<McpEntry>, String> {
72 let mut out = Vec::new();
75 if let Some(checkout) = &workdir.checkout {
76 read_servers(
77 &checkout.join(".codex").join("config.toml"),
78 McpScope::Project,
79 &mut out,
80 )?;
81 }
82 read_servers(
83 &self.paths.codex_home.join("config.toml"),
84 McpScope::User,
85 &mut out,
86 )?;
87 Ok(out)
88 }
89
90 fn register_mcp(
91 &self,
92 name: &str,
93 url: &str,
94 client_id: &str,
95 _scope: McpScope,
96 _workdir: &Workdir,
97 ) -> FixAction {
98 run_command(
99 &self.program,
100 &[
101 "mcp",
102 "add",
103 name,
104 "--url",
105 url,
106 "--oauth-client-id",
107 client_id,
108 ],
109 None,
110 )
111 }
112
113 fn remove_mcp(&self, entry: &McpEntry, _workdir: &Workdir) -> FixAction {
114 run_command(&self.program, &["mcp", "remove", &entry.name], None)
115 }
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121 use std::fs;
122 use std::path::Path;
123
124 fn codex(codex_home: &Path) -> Codex {
125 Codex::new(
126 AgentPaths {
127 home: codex_home.to_path_buf(),
128 codex_home: codex_home.to_path_buf(),
129 },
130 None,
131 )
132 }
133
134 #[test]
135 fn codex_reads_url_and_client_id() {
136 let tmp = tempfile::tempdir().unwrap();
137 fs::write(
138 tmp.path().join("config.toml"),
139 r#"model = "gpt-6"
140
141[mcp_servers.bazaar]
142url = "https://ctx.example.com/mcp/remote"
143
144[mcp_servers.bazaar.oauth]
145client_id = "visdom-context-mcp"
146
147[mcp_servers.local-tool]
148command = "npx"
149args = ["tool"]
150"#,
151 )
152 .unwrap();
153 let got = codex(tmp.path())
154 .mcp_entries(&Workdir::plain("/tmp"))
155 .unwrap();
156 assert_eq!(
157 got,
158 [
159 McpEntry {
160 name: "bazaar".to_string(),
161 url: Some("https://ctx.example.com/mcp/remote".to_string()),
162 oauth_client_id: Some("visdom-context-mcp".to_string()),
163 scope: McpScope::User,
164 extra_settings: false,
165 disabled: false,
166 },
167 McpEntry {
168 name: "local-tool".to_string(),
169 url: None,
170 oauth_client_id: None,
171 scope: McpScope::User,
172 extra_settings: true,
173 disabled: false,
174 },
175 ]
176 );
177 }
178
179 #[test]
180 fn project_config_is_read_and_wins_by_name() {
181 let home = tempfile::tempdir().unwrap();
182 let repo = tempfile::tempdir().unwrap();
183 fs::write(
184 home.path().join("config.toml"),
185 "[mcp_servers.bazaar]\nurl = \"https://ctx/mcp\"\n[mcp_servers.bazaar.oauth]\n\
186 client_id = \"right\"\n[mcp_servers.other]\nurl = \"https://o/mcp\"\nenabled = false\n",
187 )
188 .unwrap();
189 fs::create_dir_all(repo.path().join(".codex")).unwrap();
190 fs::write(
191 repo.path().join(".codex/config.toml"),
192 "[mcp_servers.bazaar]\nurl = \"https://ctx/mcp\"\n",
193 )
194 .unwrap();
195 let got = codex(home.path())
196 .mcp_entries(&Workdir::checkout(repo.path()))
197 .unwrap();
198 let seen: Vec<(&str, McpScope, Option<&str>, bool)> = got
199 .iter()
200 .map(|e| {
201 (
202 e.name.as_str(),
203 e.scope,
204 e.oauth_client_id.as_deref(),
205 e.disabled,
206 )
207 })
208 .collect();
209 assert_eq!(
210 seen,
211 [
212 ("bazaar", McpScope::Project, None, false),
213 ("other", McpScope::User, None, true),
214 ]
215 );
216 assert!(!got[1].extra_settings, "`enabled` alone is not an extra");
217 }
218
219 #[test]
220 fn missing_codex_config_means_no_entries() {
221 let tmp = tempfile::tempdir().unwrap();
222 assert!(codex(tmp.path())
223 .mcp_entries(&Workdir::plain("/tmp"))
224 .unwrap()
225 .is_empty());
226 fs::write(tmp.path().join("config.toml"), "model = \"x\"\n").unwrap();
227 assert!(codex(tmp.path())
228 .mcp_entries(&Workdir::plain("/tmp"))
229 .unwrap()
230 .is_empty());
231 }
232
233 #[test]
234 fn malformed_codex_config_is_an_error_naming_the_file() {
235 let tmp = tempfile::tempdir().unwrap();
236 let path = tmp.path().join("config.toml");
237 fs::write(&path, "[mcp_servers").unwrap();
238 let err = codex(tmp.path())
239 .mcp_entries(&Workdir::plain("/tmp"))
240 .unwrap_err();
241 assert!(err.contains(&path.display().to_string()), "{err}");
242 }
243}