Skip to main content

rust_anything/
setup.rs

1//! `setup`: register rust-anything with the coding agents on this machine, in one command.
2//!
3//! For each agent it finds (or is told about), it adds the MCP server (`rust-anything mcp`) to
4//! the agent's own configuration and, where the agent reads skills, installs the workflow skill.
5//! Existing settings are kept: only the `rust-anything` entries are added or replaced, and a file
6//! that does not parse is left alone with an error. `--remove` takes the entries out again.
7
8use std::path::{Path, PathBuf};
9
10use anyhow::{Context, Result, bail};
11use serde::Serialize;
12use serde_json::{Value, json};
13
14/// The server and skill name in every agent.
15pub const NAME: &str = "rust-anything";
16
17/// The workflow skill, as shipped in `skills/rust-anything/SKILL.md`.
18pub const SKILL: &str = include_str!("../skills/rust-anything/SKILL.md");
19const SKILL_FILES: &[(&str, &str)] = &[
20    ("SKILL.md", SKILL),
21    (
22        "whole-app.md",
23        include_str!("../skills/rust-anything/whole-app.md"),
24    ),
25];
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
28#[serde(rename_all = "lowercase")]
29pub enum Agent {
30    /// Claude Code: `~/.claude.json`, skill in `~/.claude/skills`.
31    Claude,
32    /// OpenAI Codex CLI: `~/.codex/config.toml`, skill in `~/.codex/skills`.
33    Codex,
34    /// Cursor: `~/.cursor/mcp.json`.
35    Cursor,
36    /// Gemini CLI: `~/.gemini/settings.json`.
37    Gemini,
38}
39
40impl Agent {
41    pub const ALL: [Agent; 4] = [Agent::Claude, Agent::Codex, Agent::Cursor, Agent::Gemini];
42
43    pub fn name(self) -> &'static str {
44        match self {
45            Agent::Claude => "Claude Code",
46            Agent::Codex => "Codex",
47            Agent::Cursor => "Cursor",
48            Agent::Gemini => "Gemini CLI",
49        }
50    }
51
52    /// The agent's folder in the home directory, and its command.
53    fn markers(self) -> (&'static str, &'static str) {
54        match self {
55            Agent::Claude => (".claude", "claude"),
56            Agent::Codex => (".codex", "codex"),
57            Agent::Cursor => (".cursor", "cursor"),
58            Agent::Gemini => (".gemini", "gemini"),
59        }
60    }
61
62    /// Whether the agent seems installed: its folder exists or its command is on `PATH`.
63    fn present(self, home: &Path) -> bool {
64        let (dir, command) = self.markers();
65        home.join(dir).is_dir() || on_path(command)
66    }
67}
68
69fn on_path(command: &str) -> bool {
70    std::env::var_os("PATH").is_some_and(|paths| {
71        std::env::split_paths(&paths).any(|dir| {
72            let file = dir.join(command);
73            file.is_file()
74                || file.with_extension("exe").is_file()
75                || file.with_extension("cmd").is_file()
76        })
77    })
78}
79
80pub struct Options<'a> {
81    pub home: &'a Path,
82    /// Agents to set up; empty means every agent found.
83    pub agents: Vec<Agent>,
84    /// The command the agents run; the current executable by default.
85    pub command: PathBuf,
86    pub remove: bool,
87    pub dry_run: bool,
88}
89
90/// One change: which agent, which file, and what happened.
91#[derive(Debug, Serialize)]
92pub struct Change {
93    pub agent: Agent,
94    pub file: PathBuf,
95    /// `added`, `updated`, `unchanged`, `removed` or `absent`.
96    pub action: &'static str,
97    /// The copy of the file as it was, when an existing file was changed.
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub backup: Option<PathBuf>,
100}
101
102#[derive(Debug, Serialize)]
103pub struct Report {
104    pub command: PathBuf,
105    pub agents: Vec<Agent>,
106    pub changes: Vec<Change>,
107    pub dry_run: bool,
108}
109
110/// The home directory: `HOME`, or `USERPROFILE` on Windows.
111pub fn home() -> Result<PathBuf> {
112    std::env::var_os("HOME")
113        .or_else(|| std::env::var_os("USERPROFILE"))
114        .map(PathBuf::from)
115        .context("no home directory (HOME is not set)")
116}
117
118pub fn setup(opts: &Options) -> Result<Report> {
119    let agents: Vec<Agent> = if opts.agents.is_empty() {
120        Agent::ALL
121            .into_iter()
122            .filter(|a| a.present(opts.home))
123            .collect()
124    } else {
125        opts.agents.clone()
126    };
127    if agents.is_empty() {
128        bail!(
129            "no coding agent found (looked for ~/.claude, ~/.codex, ~/.cursor, ~/.gemini and their commands); \
130             name one with --agent claude|codex|cursor|gemini"
131        );
132    }
133    let command = opts.command.to_string_lossy().into_owned();
134    let mut changes = Vec::new();
135    for &agent in &agents {
136        let home = opts.home;
137        match agent {
138            Agent::Claude => {
139                changes.push(json_server(
140                    agent,
141                    &home.join(".claude.json"),
142                    &command,
143                    opts,
144                    true,
145                )?);
146                changes.push(skill(agent, &home.join(".claude/skills").join(NAME), opts)?);
147            }
148            Agent::Codex => {
149                changes.push(codex_server(
150                    agent,
151                    &home.join(".codex/config.toml"),
152                    &command,
153                    opts,
154                )?);
155                changes.push(skill(agent, &home.join(".codex/skills").join(NAME), opts)?);
156            }
157            Agent::Cursor => {
158                changes.push(json_server(
159                    agent,
160                    &home.join(".cursor/mcp.json"),
161                    &command,
162                    opts,
163                    false,
164                )?);
165            }
166            Agent::Gemini => {
167                changes.push(json_server(
168                    agent,
169                    &home.join(".gemini/settings.json"),
170                    &command,
171                    opts,
172                    false,
173                )?);
174            }
175        }
176    }
177    Ok(Report {
178        command: opts.command.clone(),
179        agents,
180        changes,
181        dry_run: opts.dry_run,
182    })
183}
184
185/// Copies an existing settings file to `<file>.rust-anything.bak` before it is changed.
186fn backup(path: &Path) -> Result<Option<PathBuf>> {
187    if !path.is_file() {
188        return Ok(None);
189    }
190    let mut name = path.file_name().unwrap_or_default().to_os_string();
191    name.push(".rust-anything.bak");
192    let copy = path.with_file_name(name);
193    std::fs::copy(path, &copy).with_context(|| format!("backing up {}", path.display()))?;
194    Ok(Some(copy))
195}
196
197/// Writes `text` to `path` through a temporary file, so a failed write never leaves half a file.
198fn write(path: &Path, text: &str) -> Result<()> {
199    if let Some(dir) = path.parent() {
200        std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
201    }
202    let tmp = path.with_extension("rust-anything.tmp");
203    std::fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
204    std::fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))
205}
206
207/// The `mcpServers` entry of a JSON settings file (Claude Code, Cursor, Gemini CLI).
208fn json_server(
209    agent: Agent,
210    path: &Path,
211    command: &str,
212    opts: &Options,
213    stdio_type: bool,
214) -> Result<Change> {
215    let text = match std::fs::read_to_string(path) {
216        Ok(t) => Some(t),
217        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
218        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
219    };
220    let mut doc: Value = match text.as_deref().map(str::trim) {
221        None | Some("") => json!({}),
222        Some(t) => serde_json::from_str(t).with_context(|| {
223            format!(
224                "{} is not valid JSON; fix it or add the server by hand",
225                path.display()
226            )
227        })?,
228    };
229    let Some(root) = doc.as_object_mut() else {
230        bail!(
231            "{} is not a JSON object; add the server by hand",
232            path.display()
233        );
234    };
235    let mut entry = json!({ "command": command, "args": ["mcp"] });
236    if stdio_type {
237        entry = json!({ "type": "stdio", "command": command, "args": ["mcp"], "env": {} });
238    }
239    let servers = root.entry("mcpServers").or_insert_with(|| json!({}));
240    let Some(servers) = servers.as_object_mut() else {
241        bail!(
242            "`mcpServers` in {} is not an object; add the server by hand",
243            path.display()
244        );
245    };
246    let action = if opts.remove {
247        if servers.shift_remove(NAME).is_some() {
248            "removed"
249        } else {
250            "absent"
251        }
252    } else {
253        match servers.get(NAME) {
254            Some(old) if *old == entry => "unchanged",
255            Some(_) => {
256                servers.insert(NAME.into(), entry);
257                "updated"
258            }
259            None => {
260                servers.insert(NAME.into(), entry);
261                "added"
262            }
263        }
264    };
265    let mut saved = None;
266    if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
267        saved = backup(path)?;
268        write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
269    }
270    Ok(Change {
271        agent,
272        file: path.to_path_buf(),
273        action,
274        backup: saved,
275    })
276}
277
278/// `[mcp_servers.rust-anything]` in Codex's `config.toml`, keeping the rest of the file as is.
279fn codex_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
280    let text = match std::fs::read_to_string(path) {
281        Ok(t) => t,
282        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
283        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
284    };
285    let mut doc: toml_edit::DocumentMut = text.parse().with_context(|| {
286        format!(
287            "{} is not valid TOML; fix it or add the server by hand",
288            path.display()
289        )
290    })?;
291    let servers = doc
292        .entry("mcp_servers")
293        .or_insert_with(|| {
294            let mut t = toml_edit::Table::new();
295            t.set_implicit(true);
296            toml_edit::Item::Table(t)
297        })
298        .as_table_mut()
299        .with_context(|| format!("`mcp_servers` in {} is not a table", path.display()))?;
300    let mut entry = toml_edit::Table::new();
301    entry["command"] = toml_edit::value(command);
302    let mut args = toml_edit::Array::new();
303    args.push("mcp");
304    entry["args"] = toml_edit::value(args);
305    let same = servers
306        .get(NAME)
307        .and_then(|t| t.as_table())
308        .is_some_and(|t| {
309            t.get("command").and_then(|c| c.as_str()) == Some(command)
310                && t.get("args").and_then(|a| a.as_array()).is_some_and(|a| {
311                    a.iter().map(|v| v.as_str()).collect::<Vec<_>>() == [Some("mcp")]
312                })
313        });
314    let action = if opts.remove {
315        if servers.remove(NAME).is_some() {
316            "removed"
317        } else {
318            "absent"
319        }
320    } else if same {
321        "unchanged"
322    } else {
323        let had = servers.contains_key(NAME);
324        servers.insert(NAME, toml_edit::Item::Table(entry));
325        if had { "updated" } else { "added" }
326    };
327    let mut saved = None;
328    if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
329        saved = backup(path)?;
330        write(path, &doc.to_string())?;
331    }
332    Ok(Change {
333        agent,
334        file: path.to_path_buf(),
335        action,
336        backup: saved,
337    })
338}
339
340/// The workflow skill in an agent's skills folder.
341fn skill(agent: Agent, dir: &Path, opts: &Options) -> Result<Change> {
342    let current: Vec<Option<String>> = SKILL_FILES
343        .iter()
344        .map(|(name, _)| std::fs::read_to_string(dir.join(name)).ok())
345        .collect();
346    let action = if opts.remove {
347        if current.iter().any(Option::is_some) {
348            "removed"
349        } else {
350            "absent"
351        }
352    } else if current.iter().all(Option::is_none) {
353        "added"
354    } else if current
355        .iter()
356        .zip(SKILL_FILES)
357        .all(|(have, (_, want))| have.as_deref() == Some(*want))
358    {
359        "unchanged"
360    } else {
361        "updated"
362    };
363    if !opts.dry_run {
364        for (name, text) in SKILL_FILES {
365            let path = dir.join(name);
366            match action {
367                "added" | "updated" => write(&path, text)?,
368                "removed" if path.exists() => {
369                    std::fs::remove_file(&path)
370                        .with_context(|| format!("removing {}", path.display()))?;
371                }
372                _ => {}
373            }
374        }
375        if action == "removed" {
376            // The folder is ours; leave it only if someone put other files in it.
377            let _ = std::fs::remove_dir(dir);
378        }
379    }
380    Ok(Change {
381        agent,
382        file: dir.join("SKILL.md"),
383        action,
384        backup: None,
385    })
386}
387
388/// The report for people.
389pub fn text(r: &Report) -> String {
390    let mut out = String::new();
391    let verb = if r.dry_run { "Would set up" } else { "Set up" };
392    let names: Vec<&str> = r.agents.iter().map(|a| a.name()).collect();
393    out.push_str(&format!("{verb} rust-anything for {}\n", names.join(", ")));
394    for c in &r.changes {
395        out.push_str(&format!(
396            "  {:<10} {:<9} {}\n",
397            c.agent.name(),
398            c.action,
399            c.file.display()
400        ));
401        if let Some(b) = &c.backup {
402            out.push_str(&format!("  {:<10} {:<9} {}\n", "", "backup", b.display()));
403        }
404    }
405    if !r.dry_run
406        && r.changes
407            .iter()
408            .any(|c| c.action != "removed" && c.action != "absent")
409    {
410        out.push_str(&format!(
411            "\nThe agents run `{} mcp`. Restart them, then ask, for example:\n  \
412             \"Profile this repo's slowest workflow with rust-anything and move the hot loop to Rust.\"\n",
413            r.command.display()
414        ));
415    }
416    out
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    fn temp_home(name: &str) -> PathBuf {
424        let dir =
425            std::env::temp_dir().join(format!("rust-anything-setup-{name}-{}", std::process::id()));
426        let _ = std::fs::remove_dir_all(&dir);
427        std::fs::create_dir_all(&dir).unwrap();
428        dir
429    }
430
431    fn opts(home: &Path, agents: Vec<Agent>) -> Options<'_> {
432        Options {
433            home,
434            agents,
435            command: PathBuf::from("/opt/bin/rust-anything"),
436            remove: false,
437            dry_run: false,
438        }
439    }
440
441    #[test]
442    fn adds_keeps_and_removes_entries() {
443        let home = temp_home("all");
444        // Existing settings that must survive, in their own order.
445        std::fs::write(
446            home.join(".claude.json"),
447            r#"{"zeta": 1, "mcpServers": {"other": {"command": "x"}}, "alpha": true}"#,
448        )
449        .unwrap();
450        std::fs::create_dir_all(home.join(".codex")).unwrap();
451        std::fs::write(
452            home.join(".codex/config.toml"),
453            "model = \"o4\"\n\n[mcp_servers.other]\ncommand = \"x\"\n",
454        )
455        .unwrap();
456
457        let all = Agent::ALL.to_vec();
458        let r = setup(&opts(&home, all.clone())).unwrap();
459        assert!(
460            r.changes.iter().all(|c| c.action == "added"),
461            "{:?}",
462            r.changes
463        );
464
465        let claude: Value =
466            serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
467                .unwrap();
468        assert_eq!(
469            claude["mcpServers"]["rust-anything"]["args"],
470            json!(["mcp"])
471        );
472        assert_eq!(claude["mcpServers"]["other"]["command"], "x");
473        // The existing file was copied before the change; new files need no copy.
474        let saved = r.changes[0]
475            .backup
476            .clone()
477            .expect("an existing file is backed up");
478        assert!(
479            std::fs::read_to_string(saved)
480                .unwrap()
481                .starts_with(r#"{"zeta": 1"#)
482        );
483        assert!(r.changes.iter().any(|c| c.backup.is_none()));
484        let keys: Vec<&String> = claude.as_object().unwrap().keys().collect();
485        assert_eq!(keys, ["zeta", "mcpServers", "alpha"], "key order kept");
486        let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
487        assert!(codex.starts_with("model = \"o4\""), "{codex}");
488        assert!(codex.contains("[mcp_servers.rust-anything]\ncommand = \"/opt/bin/rust-anything\"\nargs = [\"mcp\"]"), "{codex}");
489        assert!(codex.contains("[mcp_servers.other]"));
490        assert_eq!(
491            std::fs::read_to_string(home.join(".claude/skills/rust-anything/SKILL.md")).unwrap(),
492            SKILL
493        );
494        assert!(
495            home.join(".codex/skills/rust-anything/whole-app.md")
496                .exists()
497        );
498        let cursor: Value =
499            serde_json::from_str(&std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap())
500                .unwrap();
501        assert_eq!(
502            cursor["mcpServers"]["rust-anything"]["command"],
503            "/opt/bin/rust-anything"
504        );
505        assert!(home.join(".gemini/settings.json").exists());
506
507        // Running again changes nothing.
508        let again = setup(&opts(&home, all.clone())).unwrap();
509        assert!(
510            again.changes.iter().all(|c| c.action == "unchanged"),
511            "{:?}",
512            again.changes
513        );
514
515        // A moved binary updates the entries.
516        let mut moved = opts(&home, vec![Agent::Codex]);
517        moved.command = PathBuf::from("/usr/local/bin/rust-anything");
518        let r = setup(&moved).unwrap();
519        assert_eq!(r.changes[0].action, "updated");
520
521        // Remove takes out only our entries.
522        let mut remove = opts(&home, all);
523        remove.remove = true;
524        setup(&remove).unwrap();
525        let claude: Value =
526            serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
527                .unwrap();
528        assert!(claude["mcpServers"].get("rust-anything").is_none());
529        assert_eq!(claude["mcpServers"]["other"]["command"], "x");
530        assert!(!home.join(".claude/skills/rust-anything").exists());
531        let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
532        assert!(
533            !codex.contains("rust-anything") && codex.contains("[mcp_servers.other]"),
534            "{codex}"
535        );
536        std::fs::remove_dir_all(&home).unwrap();
537    }
538
539    #[test]
540    fn finds_agents_and_never_breaks_a_bad_file() {
541        let home = temp_home("detect");
542        std::fs::create_dir_all(home.join(".cursor")).unwrap();
543        std::fs::write(home.join(".cursor/mcp.json"), "{ not json").unwrap();
544        // Only Cursor's folder exists (the commands may be on PATH on a developer machine).
545        let found: Vec<Agent> = Agent::ALL
546            .into_iter()
547            .filter(|a| a.present(&home))
548            .collect();
549        assert!(found.contains(&Agent::Cursor));
550        let err = setup(&opts(&home, vec![Agent::Cursor])).unwrap_err();
551        assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
552        assert_eq!(
553            std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap(),
554            "{ not json"
555        );
556
557        // A dry run writes nothing.
558        let mut dry = opts(&home, vec![Agent::Gemini]);
559        dry.dry_run = true;
560        let r = setup(&dry).unwrap();
561        assert_eq!(r.changes[0].action, "added");
562        assert!(!home.join(".gemini").exists());
563        std::fs::remove_dir_all(&home).unwrap();
564    }
565}