1use std::path::{Path, PathBuf};
6
7use tracevault_cli::agent::Agent;
8
9use crate::finding::FixAction;
10
11pub mod claude;
12pub mod codex;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum McpScope {
17 Local,
19 Project,
21 User,
23}
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct McpEntry {
27 pub name: String,
28 pub url: Option<String>,
29 pub oauth_client_id: Option<String>,
30 pub scope: McpScope,
31 pub extra_settings: bool,
34 pub disabled: bool,
36}
37
38#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct Workdir {
41 pub start_dir: PathBuf,
43 pub checkout: Option<PathBuf>,
45 pub primary: Option<PathBuf>,
48}
49
50impl Workdir {
51 pub fn plain(start_dir: impl Into<PathBuf>) -> Self {
53 Workdir {
54 start_dir: start_dir.into(),
55 checkout: None,
56 primary: None,
57 }
58 }
59
60 pub fn checkout(dir: impl Into<PathBuf>) -> Self {
62 let dir = dir.into();
63 Workdir {
64 start_dir: dir.clone(),
65 checkout: Some(dir.clone()),
66 primary: Some(dir),
67 }
68 }
69}
70
71#[derive(Clone, Debug)]
73pub struct AgentPaths {
74 pub home: PathBuf,
75 pub codex_home: PathBuf,
77}
78
79pub trait AgentAdapter {
80 fn agent(&self) -> Agent;
81
82 fn program(&self) -> &str;
84
85 fn mcp_entries(&self, workdir: &Workdir) -> Result<Vec<McpEntry>, String>;
88
89 fn register_mcp(
93 &self,
94 name: &str,
95 url: &str,
96 client_id: &str,
97 scope: McpScope,
98 workdir: &Workdir,
99 ) -> FixAction;
100
101 fn remove_mcp(&self, entry: &McpEntry, workdir: &Workdir) -> FixAction;
103
104 fn launch(&self, args: &[String]) -> std::process::Command {
106 let mut cmd = std::process::Command::new(self.program());
107 cmd.args(args);
108 cmd
109 }
110}
111
112pub fn adapter_for(
115 agent: Agent,
116 paths: AgentPaths,
117 program_override: Option<String>,
118) -> Option<Box<dyn AgentAdapter>> {
119 match agent {
120 Agent::ClaudeCode => Some(Box::new(claude::Claude::new(paths, program_override))),
121 Agent::Codex => Some(Box::new(codex::Codex::new(paths, program_override))),
122 Agent::Gsd | Agent::OpenCode | Agent::Amp => None,
123 }
124}
125
126pub(crate) fn read_optional(path: &Path) -> Result<Option<String>, String> {
128 match std::fs::read_to_string(path) {
129 Ok(text) => Ok(Some(text)),
130 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
131 Err(e) => Err(format!("cannot read {}: {e}", path.display())),
132 }
133}
134
135fn run_command(program: &str, args: &[&str], cwd: Option<&Path>) -> FixAction {
136 FixAction::RunCommand {
137 program: program.to_string(),
138 args: args.iter().map(|a| a.to_string()).collect(),
139 cwd: cwd.map(Path::to_path_buf),
140 }
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146
147 fn paths(root: &Path) -> AgentPaths {
148 AgentPaths {
149 home: root.to_path_buf(),
150 codex_home: root.join(".codex"),
151 }
152 }
153
154 fn args_of(action: &FixAction) -> (String, Vec<String>, Option<PathBuf>) {
155 match action {
156 FixAction::RunCommand { program, args, cwd } => {
157 (program.clone(), args.clone(), cwd.clone())
158 }
159 other => panic!("expected a command, got {other:?}"),
160 }
161 }
162
163 #[test]
164 fn register_commands_exact_args() {
165 let tmp = tempfile::tempdir().unwrap();
166 let repo = Path::new("/work/repo");
167 let workdir = Workdir {
168 start_dir: repo.join("src"),
169 checkout: Some(repo.to_path_buf()),
170 primary: Some(repo.to_path_buf()),
171 };
172 let url = "https://ctx.example.com/mcp/remote";
173
174 let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
175 let (program, args, cwd) = args_of(&claude.register_mcp(
176 "bazaar",
177 url,
178 "visdom-context-mcp",
179 McpScope::Local,
180 &workdir,
181 ));
182 assert_eq!(program, "claude");
183 assert_eq!(
184 args,
185 [
186 "mcp",
187 "add",
188 "--transport",
189 "http",
190 "--scope",
191 "local",
192 "--client-id",
193 "visdom-context-mcp",
194 "bazaar",
195 url
196 ]
197 );
198 assert_eq!(
199 cwd.as_deref(),
200 Some(repo.join("src").as_path()),
201 "local scope belongs to the project the command runs in"
202 );
203
204 let codex = adapter_for(Agent::Codex, paths(tmp.path()), None).unwrap();
205 let (program, args, cwd) = args_of(&codex.register_mcp(
206 "bazaar",
207 url,
208 "visdom-context-mcp",
209 McpScope::Local,
210 &workdir,
211 ));
212 assert_eq!(program, "codex");
213 assert_eq!(
214 args,
215 [
216 "mcp",
217 "add",
218 "bazaar",
219 "--url",
220 url,
221 "--oauth-client-id",
222 "visdom-context-mcp"
223 ]
224 );
225 assert_eq!(cwd, None, "Codex has one global configuration");
226
227 let (_, args, _) =
229 args_of(&claude.register_mcp("visdom", url, "c", McpScope::User, &workdir));
230 assert_eq!(args[4..6], ["--scope", "user"]);
231 }
232
233 #[test]
234 fn remove_commands_exact_args() {
235 let tmp = tempfile::tempdir().unwrap();
236 let repo = Path::new("/work/repo");
237 let workdir = Workdir::checkout(repo);
238 let entry = |scope| McpEntry {
239 name: "visdom".to_string(),
240 url: None,
241 oauth_client_id: None,
242 scope,
243 extra_settings: false,
244 disabled: false,
245 };
246 let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
247 let (_, args, cwd) = args_of(&claude.remove_mcp(&entry(McpScope::User), &workdir));
248 assert_eq!(args, ["mcp", "remove", "--scope", "user", "visdom"]);
249 assert_eq!(cwd.as_deref(), Some(repo));
250 let (_, args, _) = args_of(&claude.remove_mcp(&entry(McpScope::Local), &workdir));
251 assert_eq!(args, ["mcp", "remove", "--scope", "local", "visdom"]);
252
253 let codex = adapter_for(Agent::Codex, paths(tmp.path()), None).unwrap();
254 let (_, args, _) = args_of(&codex.remove_mcp(&entry(McpScope::User), &workdir));
255 assert_eq!(args, ["mcp", "remove", "visdom"]);
256 }
257
258 #[test]
259 fn launch_passes_args_through() {
260 let tmp = tempfile::tempdir().unwrap();
261 let args = ["--model".to_string(), "x".to_string()];
262
263 let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
264 let cmd = claude.launch(&args);
265 assert_eq!(cmd.get_program(), "claude");
266 assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["--model", "x"]);
267
268 let codex = adapter_for(
269 Agent::Codex,
270 paths(tmp.path()),
271 Some("/opt/codex".to_string()),
272 )
273 .unwrap();
274 let cmd = codex.launch(&args);
275 assert_eq!(cmd.get_program(), "/opt/codex");
276 assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["--model", "x"]);
277 let (program, ..) = args_of(&codex.register_mcp(
279 "bazaar",
280 "https://x/mcp",
281 "c",
282 McpScope::User,
283 &Workdir::plain("/tmp"),
284 ));
285 assert_eq!(program, "/opt/codex");
286 }
287
288 #[test]
289 fn agents_visdom_cannot_launch_have_no_adapter() {
290 let tmp = tempfile::tempdir().unwrap();
291 for agent in [Agent::Gsd, Agent::OpenCode, Agent::Amp] {
292 assert!(adapter_for(agent, paths(tmp.path()), None).is_none());
293 }
294 }
295}