Skip to main content

lean_ctx/setup/
mcp.rs

1//! Per-agent MCP configuration (configure/disable, target resolution).
2//!
3//! Split out of `setup/mod.rs`; `use super::*` re-imports the parent module’s
4//! aliases and sibling helpers. Public fns are re-exported via `pub(crate) use`.
5
6#[allow(clippy::wildcard_imports)]
7use super::*;
8
9/// Result of setting up a single agent with all steps.
10#[derive(Debug, Default)]
11pub struct AgentSetupResult {
12    pub mcp_ok: bool,
13    /// MCP registration was intentionally skipped because `[setup]
14    /// auto_update_mcp = false` (#281), not because it failed.
15    pub mcp_skipped: bool,
16    pub rules: crate::rules_inject::InjectResult,
17    pub skill_installed: bool,
18    pub errors: Vec<String>,
19}
20
21/// Complete per-agent setup: MCP config + global rules + skill + hook.
22/// Single source of truth — called by both `init --agent` and `setup`.
23pub fn setup_single_agent(
24    agent_name: &str,
25    global: bool,
26    mode: crate::hooks::HookMode,
27) -> AgentSetupResult {
28    // Prefer HOME/USERPROFILE so tests and portable installs work on Windows
29    // (dirs::home_dir uses Known Folder API and ignores env overrides).
30    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
31    let mut result = AgentSetupResult::default();
32
33    crate::hooks::install_agent_hook_with_mode(agent_name, global, mode);
34
35    // #281: honor `[setup] auto_update_mcp = false` — skip MCP registration but
36    // still install the hook, rules and skill. Locked-down environments can keep
37    // the MCP server out of agent settings without losing the CLI integration.
38    if crate::core::config::Config::load()
39        .setup
40        .should_update_mcp()
41    {
42        match configure_agent_mcp(agent_name) {
43            Ok(()) => result.mcp_ok = true,
44            Err(e) => result.errors.push(format!("MCP config: {e}")),
45        }
46    } else {
47        result.mcp_skipped = true;
48    }
49
50    result.rules = crate::rules_inject::inject_rules_for_agent(&home, agent_name);
51
52    if let Ok(path) = crate::rules_inject::install_skill_for_agent(&home, agent_name) {
53        result.skill_installed = path.exists();
54    }
55
56    result
57}
58
59pub fn configure_agent_mcp(agent: &str) -> Result<(), String> {
60    // Prefer HOME/USERPROFILE (dirs::home_dir ignores env on Windows).
61    let home = crate::core::home::resolve_home_dir()
62        .ok_or_else(|| "Cannot determine home directory".to_string())?;
63    let binary = resolve_portable_binary();
64
65    let targets = agent_mcp_targets(agent, &home)?;
66
67    let mut errors = Vec::new();
68    for t in &targets {
69        if let Err(e) = crate::core::editor_registry::write_config_with_options(
70            t,
71            &binary,
72            WriteOptions {
73                overwrite_invalid: true,
74            },
75        ) {
76            eprintln!(
77                "\x1b[33m⚠\x1b[0m  Could not configure {}: {}",
78                t.config_path.display(),
79                e
80            );
81            errors.push(e);
82        }
83    }
84
85    if agent == "kiro" {
86        install_kiro_steering(&home);
87    }
88
89    if (agent == "vscode" || agent == "copilot")
90        && let Err(e) = crate::core::editor_registry::plan_mode::write_vscode_plan_settings()
91    {
92        eprintln!("\x1b[33m⚠\x1b[0m  VS Code plan mode: {e}");
93    }
94    if (agent == "claude" || agent == "claude-code")
95        && let Err(e) =
96            crate::core::editor_registry::plan_mode::write_claude_code_plan_permissions()
97    {
98        eprintln!("\x1b[33m⚠\x1b[0m  Claude Code plan mode: {e}");
99    }
100    if agent == "codebuddy"
101        && let Err(e) =
102            crate::core::editor_registry::plan_mode::write_claude_code_plan_permissions()
103    {
104        eprintln!("\x1b[33m⚠\x1b[0m  CodeBuddy plan mode: {e}");
105    }
106
107    if errors.is_empty() {
108        Ok(())
109    } else {
110        Err(format!(
111            "{} config(s) could not be written. See warnings above.",
112            errors.len()
113        ))
114    }
115}
116
117pub(crate) fn agent_mcp_targets(
118    agent: &str,
119    home: &std::path::Path,
120) -> Result<Vec<EditorTarget>, String> {
121    let mut targets = Vec::<EditorTarget>::new();
122
123    let push = |targets: &mut Vec<EditorTarget>,
124                name: &'static str,
125                config_path: PathBuf,
126                config_type: ConfigType| {
127        targets.push(EditorTarget {
128            name,
129            agent_key: agent.to_string(),
130            detect_path: PathBuf::from("/nonexistent"), // not used in direct agent config
131            config_path,
132            config_type,
133        });
134    };
135
136    match agent {
137        "cursor" => push(
138            &mut targets,
139            "Cursor",
140            home.join(".cursor/mcp.json"),
141            ConfigType::McpJson,
142        ),
143        "claude" | "claude-code" => push(
144            &mut targets,
145            "Claude Code",
146            crate::core::editor_registry::claude_mcp_json_path(home),
147            ConfigType::McpJson,
148        ),
149        "codebuddy" => push(
150            &mut targets,
151            "CodeBuddy",
152            crate::core::editor_registry::codebuddy_mcp_json_path(home),
153            ConfigType::McpJson,
154        ),
155        "commandcode" => push(
156            &mut targets,
157            "Command Code",
158            home.join(".commandcode/mcp.json"),
159            ConfigType::CommandCode,
160        ),
161        "augment" => {
162            push(
163                &mut targets,
164                "Augment CLI",
165                crate::core::editor_registry::augment_cli_settings_path(home),
166                ConfigType::McpJson,
167            );
168            push(
169                &mut targets,
170                "Augment (VS Code)",
171                crate::core::editor_registry::augment_vscode_mcp_path(home),
172                ConfigType::AugmentVsCode,
173            );
174        }
175        "windsurf" => push(
176            &mut targets,
177            "Windsurf",
178            home.join(".codeium/windsurf/mcp_config.json"),
179            ConfigType::McpJson,
180        ),
181        "codex" => push(
182            &mut targets,
183            "Codex CLI",
184            crate::core::home::resolve_codex_config_path()
185                .unwrap_or_else(|| home.join(".codex/config.toml")),
186            ConfigType::Codex,
187        ),
188        "grok" => push(
189            &mut targets,
190            "Grok",
191            home.join(".grok/config.toml"),
192            ConfigType::Codex,
193        ),
194        "gemini" => {
195            push(
196                &mut targets,
197                "Gemini CLI",
198                home.join(".gemini/settings.json"),
199                ConfigType::GeminiSettings,
200            );
201            push(
202                &mut targets,
203                "Antigravity IDE",
204                home.join(".gemini/antigravity/mcp_config.json"),
205                ConfigType::McpJson,
206            );
207            push(
208                &mut targets,
209                "Antigravity CLI",
210                home.join(".gemini/antigravity-cli/mcp_config.json"),
211                ConfigType::McpJson,
212            );
213        }
214        "antigravity" => push(
215            &mut targets,
216            "Antigravity IDE",
217            home.join(".gemini/antigravity/mcp_config.json"),
218            ConfigType::McpJson,
219        ),
220        "antigravity-cli" => push(
221            &mut targets,
222            "Antigravity CLI",
223            home.join(".gemini/antigravity-cli/mcp_config.json"),
224            ConfigType::McpJson,
225        ),
226        "copilot" => push(
227            &mut targets,
228            "Copilot CLI",
229            home.join(".copilot/mcp-config.json"),
230            ConfigType::CopilotCli,
231        ),
232        "crush" => push(
233            &mut targets,
234            "Crush",
235            home.join(".config/crush/crush.json"),
236            ConfigType::Crush,
237        ),
238        "qoder" => {
239            for path in crate::core::editor_registry::qoder_all_mcp_paths(home) {
240                push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
241            }
242        }
243        "qoderwork" => push(
244            &mut targets,
245            "QoderWork",
246            crate::core::editor_registry::qoderwork_mcp_path(home),
247            ConfigType::McpJson,
248        ),
249        "qodercli" => push(
250            &mut targets,
251            "Qoder CLI",
252            crate::core::editor_registry::qodercli_settings_path(home),
253            ConfigType::QoderSettings,
254        ),
255        "cline" => push(
256            &mut targets,
257            "Cline",
258            crate::core::editor_registry::cline_mcp_path(),
259            ConfigType::McpJson,
260        ),
261        "cline-cli" => push(
262            &mut targets,
263            "Cline CLI",
264            crate::core::editor_registry::cline_cli_mcp_settings_path(),
265            ConfigType::ClineCli,
266        ),
267        "roo" => push(
268            &mut targets,
269            "Roo Code",
270            crate::core::editor_registry::roo_mcp_path(),
271            ConfigType::McpJson,
272        ),
273        "kiro" => push(
274            &mut targets,
275            "AWS Kiro",
276            home.join(".kiro/settings/mcp.json"),
277            ConfigType::McpJson,
278        ),
279        "verdent" => push(
280            &mut targets,
281            "Verdent",
282            home.join(".verdent/mcp.json"),
283            ConfigType::McpJson,
284        ),
285        // pi: deliberately no MCP target. Pi has no native MCP adapter — a
286        // ~/.pi/agent/mcp.json entry is never served and made older pi-lean-ctx
287        // versions disable their embedded bridge (GitHub #361). Pi runs through
288        // the pi-lean-ctx npm package; install_pi_hook_with_mode removes stale
289        // entries instead.
290        "pi" | "jetbrains" | "amp" | "openclaw" => {
291            // jetbrains/amp/openclaw: handled by dedicated install hooks
292            // (servers[] array / amp.mcpServers / mcp.servers).
293        }
294        "qwen" => push(
295            &mut targets,
296            "Qwen Code",
297            home.join(".qwen/settings.json"),
298            ConfigType::McpJson,
299        ),
300        "trae" => push(
301            &mut targets,
302            "Trae",
303            home.join(".trae/mcp.json"),
304            ConfigType::McpJson,
305        ),
306        "amazonq" => push(
307            &mut targets,
308            "Amazon Q Developer",
309            home.join(".aws/amazonq/default.json"),
310            ConfigType::McpJson,
311        ),
312        "opencode" => {
313            // #1585: write into the user's existing opencode.jsonc when that is
314            // the file they have, instead of creating a competing opencode.json.
315            let opencode_path = crate::core::opencode_config::resolve(home).path;
316            push(
317                &mut targets,
318                "OpenCode",
319                opencode_path,
320                ConfigType::OpenCode,
321            );
322        }
323        "hermes" => push(
324            &mut targets,
325            "Hermes Agent",
326            home.join(".hermes/config.yaml"),
327            ConfigType::HermesYaml,
328        ),
329        "vscode" => push(
330            &mut targets,
331            "VS Code",
332            crate::core::editor_registry::vscode_mcp_path(),
333            ConfigType::VsCodeMcp,
334        ),
335        "vscode-insiders" => push(
336            &mut targets,
337            "VS Code Insiders",
338            crate::core::editor_registry::vscode_insiders_mcp_path(),
339            ConfigType::VsCodeMcp,
340        ),
341        "zed" => push(
342            &mut targets,
343            "Zed",
344            crate::core::editor_registry::zed_settings_path(home),
345            ConfigType::Zed,
346        ),
347        "aider" => push(
348            &mut targets,
349            "Aider",
350            home.join(".aider/mcp.json"),
351            ConfigType::McpJson,
352        ),
353        "continue" => push(
354            &mut targets,
355            "Continue",
356            home.join(".continue/mcp.json"),
357            ConfigType::McpJson,
358        ),
359        "neovim" => push(
360            &mut targets,
361            "Neovim (mcphub.nvim)",
362            home.join(".config/mcphub/servers.json"),
363            ConfigType::McpJson,
364        ),
365        "emacs" => push(
366            &mut targets,
367            "Emacs (mcp.el)",
368            home.join(".emacs.d/mcp.json"),
369            ConfigType::McpJson,
370        ),
371        "sublime" => push(
372            &mut targets,
373            "Sublime Text",
374            home.join(".config/sublime-text/mcp.json"),
375            ConfigType::McpJson,
376        ),
377        _ => {
378            return Err(format!("Unknown agent '{agent}'"));
379        }
380    }
381
382    Ok(targets)
383}
384
385pub fn disable_agent_mcp(agent: &str, overwrite_invalid: bool) -> Result<(), String> {
386    // Prefer HOME/USERPROFILE (dirs::home_dir ignores env on Windows).
387    let home = crate::core::home::resolve_home_dir()
388        .ok_or_else(|| "Cannot determine home directory".to_string())?;
389
390    let mut targets = Vec::<EditorTarget>::new();
391
392    let push = |targets: &mut Vec<EditorTarget>,
393                name: &'static str,
394                config_path: PathBuf,
395                config_type: ConfigType| {
396        targets.push(EditorTarget {
397            name,
398            agent_key: agent.to_string(),
399            detect_path: PathBuf::from("/nonexistent"),
400            config_path,
401            config_type,
402        });
403    };
404
405    let pi_cfg = home.join(".pi").join("agent").join("mcp.json");
406
407    match agent {
408        "cursor" => push(
409            &mut targets,
410            "Cursor",
411            home.join(".cursor/mcp.json"),
412            ConfigType::McpJson,
413        ),
414        "claude" | "claude-code" => push(
415            &mut targets,
416            "Claude Code",
417            crate::core::editor_registry::claude_mcp_json_path(&home),
418            ConfigType::McpJson,
419        ),
420        "codebuddy" => push(
421            &mut targets,
422            "CodeBuddy",
423            crate::core::editor_registry::codebuddy_mcp_json_path(&home),
424            ConfigType::McpJson,
425        ),
426        "commandcode" => push(
427            &mut targets,
428            "Command Code",
429            home.join(".commandcode/mcp.json"),
430            ConfigType::CommandCode,
431        ),
432        "augment" => {
433            push(
434                &mut targets,
435                "Augment CLI",
436                crate::core::editor_registry::augment_cli_settings_path(&home),
437                ConfigType::McpJson,
438            );
439            push(
440                &mut targets,
441                "Augment (VS Code)",
442                crate::core::editor_registry::augment_vscode_mcp_path(&home),
443                ConfigType::AugmentVsCode,
444            );
445        }
446        "windsurf" => push(
447            &mut targets,
448            "Windsurf",
449            home.join(".codeium/windsurf/mcp_config.json"),
450            ConfigType::McpJson,
451        ),
452        "codex" => push(
453            &mut targets,
454            "Codex CLI",
455            crate::core::home::resolve_codex_config_path()
456                .unwrap_or_else(|| home.join(".codex/config.toml")),
457            ConfigType::Codex,
458        ),
459        "grok" => push(
460            &mut targets,
461            "Grok",
462            home.join(".grok/config.toml"),
463            ConfigType::Codex,
464        ),
465        "gemini" => {
466            push(
467                &mut targets,
468                "Gemini CLI",
469                home.join(".gemini/settings.json"),
470                ConfigType::GeminiSettings,
471            );
472            push(
473                &mut targets,
474                "Antigravity IDE",
475                home.join(".gemini/antigravity/mcp_config.json"),
476                ConfigType::McpJson,
477            );
478            push(
479                &mut targets,
480                "Antigravity CLI",
481                home.join(".gemini/antigravity-cli/mcp_config.json"),
482                ConfigType::McpJson,
483            );
484        }
485        "antigravity" => push(
486            &mut targets,
487            "Antigravity IDE",
488            home.join(".gemini/antigravity/mcp_config.json"),
489            ConfigType::McpJson,
490        ),
491        "antigravity-cli" => push(
492            &mut targets,
493            "Antigravity CLI",
494            home.join(".gemini/antigravity-cli/mcp_config.json"),
495            ConfigType::McpJson,
496        ),
497        "copilot" => push(
498            &mut targets,
499            "Copilot CLI",
500            home.join(".copilot/mcp-config.json"),
501            ConfigType::CopilotCli,
502        ),
503        "crush" => push(
504            &mut targets,
505            "Crush",
506            home.join(".config/crush/crush.json"),
507            ConfigType::Crush,
508        ),
509        "pi" => push(&mut targets, "Pi Coding Agent", pi_cfg, ConfigType::McpJson),
510        "qoder" => {
511            for path in crate::core::editor_registry::qoder_all_mcp_paths(&home) {
512                push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
513            }
514        }
515        "qoderwork" => push(
516            &mut targets,
517            "QoderWork",
518            crate::core::editor_registry::qoderwork_mcp_path(&home),
519            ConfigType::McpJson,
520        ),
521        "qodercli" => push(
522            &mut targets,
523            "Qoder CLI",
524            crate::core::editor_registry::qodercli_settings_path(&home),
525            ConfigType::QoderSettings,
526        ),
527        "cline" => push(
528            &mut targets,
529            "Cline",
530            crate::core::editor_registry::cline_mcp_path(),
531            ConfigType::McpJson,
532        ),
533        "cline-cli" => push(
534            &mut targets,
535            "Cline CLI",
536            crate::core::editor_registry::cline_cli_mcp_settings_path(),
537            ConfigType::ClineCli,
538        ),
539        "roo" => push(
540            &mut targets,
541            "Roo Code",
542            crate::core::editor_registry::roo_mcp_path(),
543            ConfigType::McpJson,
544        ),
545        "kiro" => push(
546            &mut targets,
547            "AWS Kiro",
548            home.join(".kiro/settings/mcp.json"),
549            ConfigType::McpJson,
550        ),
551        "verdent" => push(
552            &mut targets,
553            "Verdent",
554            home.join(".verdent/mcp.json"),
555            ConfigType::McpJson,
556        ),
557        "jetbrains" | "amp" | "openclaw" => {
558            // Not supported for disable via this helper.
559        }
560        "qwen" => push(
561            &mut targets,
562            "Qwen Code",
563            home.join(".qwen/settings.json"),
564            ConfigType::McpJson,
565        ),
566        "trae" => push(
567            &mut targets,
568            "Trae",
569            home.join(".trae/mcp.json"),
570            ConfigType::McpJson,
571        ),
572        "amazonq" => push(
573            &mut targets,
574            "Amazon Q Developer",
575            home.join(".aws/amazonq/default.json"),
576            ConfigType::McpJson,
577        ),
578        "opencode" => {
579            // #1585: write into the user's existing opencode.jsonc when that is
580            // the file they have, instead of creating a competing opencode.json.
581            let opencode_path = crate::core::opencode_config::resolve(home.as_ref()).path;
582            push(
583                &mut targets,
584                "OpenCode",
585                opencode_path,
586                ConfigType::OpenCode,
587            );
588        }
589        "hermes" => push(
590            &mut targets,
591            "Hermes Agent",
592            home.join(".hermes/config.yaml"),
593            ConfigType::HermesYaml,
594        ),
595        "vscode" => push(
596            &mut targets,
597            "VS Code",
598            crate::core::editor_registry::vscode_mcp_path(),
599            ConfigType::VsCodeMcp,
600        ),
601        "vscode-insiders" => push(
602            &mut targets,
603            "VS Code Insiders",
604            crate::core::editor_registry::vscode_insiders_mcp_path(),
605            ConfigType::VsCodeMcp,
606        ),
607        "zed" => push(
608            &mut targets,
609            "Zed",
610            crate::core::editor_registry::zed_settings_path(&home),
611            ConfigType::Zed,
612        ),
613        "aider" => push(
614            &mut targets,
615            "Aider",
616            home.join(".aider/mcp.json"),
617            ConfigType::McpJson,
618        ),
619        "continue" => push(
620            &mut targets,
621            "Continue",
622            home.join(".continue/mcp.json"),
623            ConfigType::McpJson,
624        ),
625        "neovim" => push(
626            &mut targets,
627            "Neovim (mcphub.nvim)",
628            home.join(".config/mcphub/servers.json"),
629            ConfigType::McpJson,
630        ),
631        "emacs" => push(
632            &mut targets,
633            "Emacs (mcp.el)",
634            home.join(".emacs.d/mcp.json"),
635            ConfigType::McpJson,
636        ),
637        "sublime" => push(
638            &mut targets,
639            "Sublime Text",
640            home.join(".config/sublime-text/mcp.json"),
641            ConfigType::McpJson,
642        ),
643        _ => {
644            return Err(format!("Unknown agent '{agent}'"));
645        }
646    }
647
648    for t in &targets {
649        crate::core::editor_registry::remove_lean_ctx_server(
650            t,
651            WriteOptions { overwrite_invalid },
652        )?;
653    }
654
655    Ok(())
656}
657
658#[cfg(test)]
659mod qodercli_tests {
660    use super::*;
661
662    #[test]
663    fn commandcode_agent_target_uses_command_code_schema() {
664        let home = std::path::Path::new("/home/tester");
665        let targets = agent_mcp_targets("commandcode", home).unwrap();
666
667        assert_eq!(targets.len(), 1);
668        assert_eq!(targets[0].name, "Command Code");
669        assert_eq!(targets[0].config_path, home.join(".commandcode/mcp.json"));
670        assert_eq!(targets[0].config_type, ConfigType::CommandCode);
671    }
672
673    #[test]
674    fn cline_cli_agent_target_uses_cline_cli_schema() {
675        let home = std::path::Path::new("/home/tester");
676        let targets = agent_mcp_targets("cline-cli", home).unwrap();
677
678        assert_eq!(targets.len(), 1);
679        assert_eq!(targets[0].name, "Cline CLI");
680        assert_eq!(targets[0].config_type, ConfigType::ClineCli);
681    }
682
683    #[test]
684    fn qodercli_agent_target_uses_settings_json() {
685        let home = std::path::Path::new("/home/tester");
686        let targets = agent_mcp_targets("qodercli", home).unwrap();
687
688        assert_eq!(targets.len(), 1);
689        assert_eq!(targets[0].name, "Qoder CLI");
690        assert_eq!(targets[0].config_path, home.join(".qoder/settings.json"));
691    }
692
693    #[test]
694    fn qodercli_agent_target_uses_qoder_settings_writer() {
695        let home = std::path::Path::new("/home/tester");
696        let targets = agent_mcp_targets("qodercli", home).unwrap();
697
698        assert_eq!(targets[0].agent_key, "qodercli");
699        assert_eq!(targets[0].config_type, ConfigType::QoderSettings);
700    }
701
702    #[test]
703    fn qodercli_agent_target_is_separate_from_qoder_ide_targets() {
704        let home = std::path::Path::new("/home/tester");
705        let cli = agent_mcp_targets("qodercli", home).unwrap();
706        let ide = agent_mcp_targets("qoder", home).unwrap();
707
708        assert!(
709            ide.iter()
710                .all(|target| target.config_path != cli[0].config_path)
711        );
712    }
713}