Skip to main content

visdom_cli/agents/
mod.rs

1//! What `visdom` knows about each agent it can launch: where the agent keeps
2//! its MCP servers, how to register one through the agent's own CLI, and how
3//! to start it. Components never read an agent's files themselves.
4
5use std::path::{Path, PathBuf};
6
7use tracevault_cli::agent::Agent;
8
9use crate::finding::FixAction;
10
11pub mod claude;
12pub mod codex;
13
14/// Where an MCP server entry is configured.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum McpScope {
17    /// For one project directory, in the user's private agent state.
18    Local,
19    /// In a file committed to the repository.
20    Project,
21    /// For every project of this user.
22    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    /// The entry carries settings beyond its URL and OAuth client (headers,
32    /// timeouts, …) that removing and re-adding it would lose.
33    pub extra_settings: bool,
34    /// Configured but switched off: the agent does not load it.
35    pub disabled: bool,
36}
37
38/// Where the agent is about to run.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct Workdir {
41    /// The directory `visdom` was run in; the agent starts there.
42    pub start_dir: PathBuf,
43    /// Top level of the git checkout around it. `None` outside a repository.
44    pub checkout: Option<PathBuf>,
45    /// The repository's primary checkout: the same as `checkout`, except in a
46    /// linked worktree.
47    pub primary: Option<PathBuf>,
48}
49
50impl Workdir {
51    /// A directory outside any repository.
52    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    /// A primary checkout, entered at its top level.
61    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/// The directories the agents keep their state under.
72#[derive(Clone, Debug)]
73pub struct AgentPaths {
74    pub home: PathBuf,
75    /// `$CODEX_HOME`, or `~/.codex`.
76    pub codex_home: PathBuf,
77}
78
79pub trait AgentAdapter {
80    fn agent(&self) -> Agent;
81
82    /// The executable `visdom` runs for this agent.
83    fn program(&self) -> &str;
84
85    /// Every MCP server the agent would load when started in `workdir`. An
86    /// unreadable or malformed file is an error that names it.
87    fn mcp_entries(&self, workdir: &Workdir) -> Result<Vec<McpEntry>, String>;
88
89    /// The command that registers an HTTP MCP server with a fixed OAuth
90    /// client in `scope`, for an agent started in `workdir`. An agent with a
91    /// single configuration ignores the scope.
92    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    /// The command that removes `entry`.
102    fn remove_mcp(&self, entry: &McpEntry, workdir: &Workdir) -> FixAction;
103
104    /// The command that starts the agent with `args`.
105    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
112/// The adapter for `agent`. `program_override` replaces the executable name.
113/// Agents `visdom` cannot launch have no adapter.
114pub 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
126/// `text` of the file at `path`, `None` when it does not exist.
127pub(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        // A user-scope registration stays a user-scope one.
228        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        // The override also names the program of the registration command.
278        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}