Skip to main content

visdom_cli/agents/
claude.rs

1//! Claude Code.
2//!
3//! MCP servers come from three places: `~/.claude.json` →
4//! `projects[<project>].mcpServers` (local scope) and its top-level
5//! `mcpServers` (user scope), and the repository's committed `.mcp.json`
6//! (project scope). An HTTP entry is
7//! `{"type":"http","url":…,"oauth":{"clientId":…}}`.
8//!
9//! `<project>` is the repository's primary checkout — also for a session
10//! started in a subdirectory or in a linked worktree — and, outside a
11//! repository, exactly the directory Claude was started in (observed with
12//! Claude Code 2.1.327: `claude mcp add -s local` / `claude mcp get`).
13
14use std::path::Path;
15
16use tracevault_cli::agent::Agent;
17
18use super::{read_optional, run_command, AgentAdapter, AgentPaths, McpEntry, McpScope, Workdir};
19use crate::finding::FixAction;
20
21pub struct Claude {
22    paths: AgentPaths,
23    program: String,
24}
25
26impl Claude {
27    pub fn new(paths: AgentPaths, program_override: Option<String>) -> Self {
28        Claude {
29            paths,
30            program: program_override.unwrap_or_else(|| "claude".to_string()),
31        }
32    }
33}
34
35fn scope_name(scope: McpScope) -> &'static str {
36    match scope {
37        McpScope::Local => "local",
38        McpScope::Project => "project",
39        McpScope::User => "user",
40    }
41}
42
43fn parse_json(path: &Path) -> Result<Option<serde_json::Value>, String> {
44    let Some(text) = read_optional(path)? else {
45        return Ok(None);
46    };
47    // Claude creates the file empty before first use.
48    if text.trim().is_empty() {
49        return Ok(None);
50    }
51    serde_json::from_str(&text)
52        .map(Some)
53        .map_err(|e| format!("cannot parse {}: {e}", path.display()))
54}
55
56fn entries(servers: Option<&serde_json::Value>, scope: McpScope, out: &mut Vec<McpEntry>) {
57    let Some(servers) = servers.and_then(|s| s.as_object()) else {
58        return;
59    };
60    for (name, server) in servers {
61        let text = |v: Option<&serde_json::Value>| v.and_then(|v| v.as_str()).map(String::from);
62        let only = |v: Option<&serde_json::Value>, known: &[&str]| {
63            v.and_then(|v| v.as_object())
64                .is_none_or(|o| o.keys().all(|k| known.contains(&k.as_str())))
65        };
66        out.push(McpEntry {
67            name: name.clone(),
68            url: text(server.get("url")),
69            oauth_client_id: text(server.get("oauth").and_then(|o| o.get("clientId"))),
70            scope,
71            extra_settings: !only(Some(server), &["type", "url", "oauth"])
72                || !only(server.get("oauth"), &["clientId"]),
73            disabled: false,
74        });
75    }
76}
77
78impl AgentAdapter for Claude {
79    fn agent(&self) -> Agent {
80        Agent::ClaudeCode
81    }
82
83    fn program(&self) -> &str {
84        &self.program
85    }
86
87    fn mcp_entries(&self, workdir: &Workdir) -> Result<Vec<McpEntry>, String> {
88        let mut out = Vec::new();
89        let state = parse_json(&self.paths.home.join(".claude.json"))?;
90        if let Some(state) = &state {
91            let key = workdir.primary.as_deref().unwrap_or(&workdir.start_dir);
92            let project = state
93                .get("projects")
94                .and_then(|p| p.get(key.to_string_lossy().as_ref()));
95            entries(
96                project.and_then(|p| p.get("mcpServers")),
97                McpScope::Local,
98                &mut out,
99            );
100        }
101        let committed_dir = workdir.checkout.as_deref().unwrap_or(&workdir.start_dir);
102        let committed = parse_json(&committed_dir.join(".mcp.json"))?;
103        entries(
104            committed.as_ref().and_then(|c| c.get("mcpServers")),
105            McpScope::Project,
106            &mut out,
107        );
108        entries(
109            state.as_ref().and_then(|s| s.get("mcpServers")),
110            McpScope::User,
111            &mut out,
112        );
113        // One definition per name is loaded: local wins over project, project
114        // over user (the order collected above).
115        let mut loaded: Vec<McpEntry> = Vec::new();
116        for entry in out {
117            if !loaded.iter().any(|e| e.name == entry.name) {
118                loaded.push(entry);
119            }
120        }
121        Ok(loaded)
122    }
123
124    fn register_mcp(
125        &self,
126        name: &str,
127        url: &str,
128        client_id: &str,
129        scope: McpScope,
130        workdir: &Workdir,
131    ) -> FixAction {
132        // Options before the positionals: `claude mcp add` treats what follows
133        // the URL as arguments of a stdio server.
134        run_command(
135            &self.program,
136            &[
137                "mcp",
138                "add",
139                "--transport",
140                "http",
141                "--scope",
142                scope_name(scope),
143                "--client-id",
144                client_id,
145                name,
146                url,
147            ],
148            Some(&workdir.start_dir),
149        )
150    }
151
152    fn remove_mcp(&self, entry: &McpEntry, workdir: &Workdir) -> FixAction {
153        run_command(
154            &self.program,
155            &[
156                "mcp",
157                "remove",
158                "--scope",
159                scope_name(entry.scope),
160                &entry.name,
161            ],
162            Some(&workdir.start_dir),
163        )
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use std::fs;
171    use std::path::PathBuf;
172
173    fn claude(home: &Path) -> Claude {
174        Claude::new(
175            AgentPaths {
176                home: home.to_path_buf(),
177                codex_home: home.join(".codex"),
178            },
179            None,
180        )
181    }
182
183    fn state_for(project: &Path) -> String {
184        serde_json::json!({
185            "numStartups": 3,
186            "mcpServers": {
187                "global-tool": { "type": "http", "url": "https://global.example.com/mcp" }
188            },
189            "projects": {
190                project.to_string_lossy(): {
191                    "mcpServers": {
192                        "bazaar": {
193                            "type": "http",
194                            "url": "https://ctx.example.com/mcp/remote",
195                            "oauth": { "clientId": "visdom-context-mcp" }
196                        }
197                    }
198                },
199                "/somewhere/else": {
200                    "mcpServers": { "other": { "type": "http", "url": "https://other/mcp" } }
201                }
202            }
203        })
204        .to_string()
205    }
206
207    #[test]
208    fn claude_reads_local_user_and_project_entries() {
209        let home = tempfile::tempdir().unwrap();
210        let repo = tempfile::tempdir().unwrap();
211        fs::write(home.path().join(".claude.json"), state_for(repo.path())).unwrap();
212        fs::write(
213            repo.path().join(".mcp.json"),
214            r#"{"mcpServers":{"team":{"command":"npx","args":["team-mcp"]}}}"#,
215        )
216        .unwrap();
217
218        let got = claude(home.path())
219            .mcp_entries(&Workdir::checkout(repo.path()))
220            .unwrap();
221        assert_eq!(
222            got,
223            [
224                McpEntry {
225                    name: "bazaar".to_string(),
226                    url: Some("https://ctx.example.com/mcp/remote".to_string()),
227                    oauth_client_id: Some("visdom-context-mcp".to_string()),
228                    scope: McpScope::Local,
229                    extra_settings: false,
230                    disabled: false,
231                },
232                McpEntry {
233                    name: "team".to_string(),
234                    url: None,
235                    oauth_client_id: None,
236                    scope: McpScope::Project,
237                    extra_settings: true,
238                    disabled: false,
239                },
240                McpEntry {
241                    name: "global-tool".to_string(),
242                    url: Some("https://global.example.com/mcp".to_string()),
243                    oauth_client_id: None,
244                    scope: McpScope::User,
245                    extra_settings: false,
246                    disabled: false,
247                },
248            ]
249        );
250    }
251
252    /// Claude keys the local entry by the repository's primary checkout, so
253    /// it is found from a subdirectory and from a linked worktree, whose own
254    /// paths appear nowhere in `~/.claude.json`.
255    #[test]
256    fn claude_local_entry_found_from_subdirectory() {
257        let home = tempfile::tempdir().unwrap();
258        let repo = PathBuf::from("/work/repo");
259        fs::write(home.path().join(".claude.json"), state_for(&repo)).unwrap();
260        let has_bazaar = |workdir: &Workdir| {
261            claude(home.path())
262                .mcp_entries(workdir)
263                .unwrap()
264                .iter()
265                .any(|e| e.name == "bazaar" && e.scope == McpScope::Local)
266        };
267
268        assert!(has_bazaar(&Workdir {
269            start_dir: repo.join("src/deep"),
270            checkout: Some(repo.clone()),
271            primary: Some(repo.clone()),
272        }));
273        assert!(has_bazaar(&Workdir {
274            start_dir: PathBuf::from("/work/repo-wt/src"),
275            checkout: Some(PathBuf::from("/work/repo-wt")),
276            primary: Some(repo.clone()),
277        }));
278        // Another repository does not see it.
279        assert!(!has_bazaar(&Workdir::checkout("/work/other")));
280    }
281
282    /// Outside a repository the key is the start directory itself: an entry
283    /// of a parent directory does not apply.
284    #[test]
285    fn outside_a_repository_the_start_directory_is_the_project() {
286        let home = tempfile::tempdir().unwrap();
287        fs::write(
288            home.path().join(".claude.json"),
289            state_for(Path::new("/work/umbrella")),
290        )
291        .unwrap();
292        let scopes = |dir: &str| -> Vec<McpScope> {
293            claude(home.path())
294                .mcp_entries(&Workdir::plain(dir))
295                .unwrap()
296                .iter()
297                .map(|e| e.scope)
298                .collect()
299        };
300        assert_eq!(scopes("/work/umbrella"), [McpScope::Local, McpScope::User]);
301        assert_eq!(scopes("/work/umbrella/sub"), [McpScope::User]);
302    }
303
304    /// Claude loads one definition per name; the shadowed ones must not be
305    /// reported as if they were in effect.
306    #[test]
307    fn a_local_entry_shadows_a_user_entry_of_the_same_name() {
308        let home = tempfile::tempdir().unwrap();
309        let state = serde_json::json!({
310            "mcpServers": {
311                "bazaar": { "type": "http", "url": "https://ctx/mcp", "oauth": { "clientId": "right" } }
312            },
313            "projects": { "/work/repo": { "mcpServers": {
314                "bazaar": { "type": "http", "url": "https://ctx/mcp" }
315            } } }
316        });
317        fs::write(home.path().join(".claude.json"), state.to_string()).unwrap();
318        let got = claude(home.path())
319            .mcp_entries(&Workdir::checkout("/work/repo"))
320            .unwrap();
321        assert_eq!(got.len(), 1, "{got:?}");
322        assert_eq!(got[0].scope, McpScope::Local);
323        assert_eq!(got[0].oauth_client_id, None);
324    }
325
326    #[test]
327    fn settings_beyond_url_and_client_are_flagged() {
328        let home = tempfile::tempdir().unwrap();
329        let state = serde_json::json!({ "mcpServers": {
330            "plain": { "type": "http", "url": "https://a/mcp", "oauth": { "clientId": "c" } },
331            "headers": { "type": "http", "url": "https://b/mcp", "headers": { "X-Key": "k" } },
332            "port": { "type": "http", "url": "https://c/mcp", "oauth": { "clientId": "c", "callbackPort": 8080 } }
333        } });
334        fs::write(home.path().join(".claude.json"), state.to_string()).unwrap();
335        let got = claude(home.path())
336            .mcp_entries(&Workdir::plain("/tmp"))
337            .unwrap();
338        let extra: Vec<(&str, bool)> = got
339            .iter()
340            .map(|e| (e.name.as_str(), e.extra_settings))
341            .collect();
342        assert_eq!(extra, [("plain", false), ("headers", true), ("port", true)]);
343    }
344
345    #[test]
346    fn malformed_claude_json_is_unknown() {
347        let home = tempfile::tempdir().unwrap();
348        let repo = tempfile::tempdir().unwrap();
349        let workdir = Workdir::checkout(repo.path());
350        let path = home.path().join(".claude.json");
351        fs::write(&path, "{ not json").unwrap();
352        let err = claude(home.path()).mcp_entries(&workdir).unwrap_err();
353        assert!(err.contains(&path.display().to_string()), "{err}");
354
355        // A malformed committed .mcp.json is named the same way.
356        fs::write(&path, "{}").unwrap();
357        let committed = repo.path().join(".mcp.json");
358        fs::write(&committed, "[").unwrap();
359        let err = claude(home.path()).mcp_entries(&workdir).unwrap_err();
360        assert!(err.contains(&committed.display().to_string()), "{err}");
361    }
362
363    #[test]
364    fn missing_claude_json_means_no_entries() {
365        let home = tempfile::tempdir().unwrap();
366        let repo = tempfile::tempdir().unwrap();
367        let workdir = Workdir::checkout(repo.path());
368        let entries = || claude(home.path()).mcp_entries(&workdir).unwrap();
369        assert!(entries().is_empty());
370        // So does an empty file, and one whose shape is not what we expect.
371        fs::write(home.path().join(".claude.json"), "").unwrap();
372        assert!(entries().is_empty());
373        fs::write(
374            home.path().join(".claude.json"),
375            r#"{"projects":[],"mcpServers":"x"}"#,
376        )
377        .unwrap();
378        assert!(entries().is_empty());
379    }
380}