Skip to main content

lean_ctx/core/
tool_profiles.rs

1use std::fmt;
2
3/// Controls which MCP tools are exposed to agents.
4///
5/// Three built-in tiers reduce tool-list overwhelm for new users
6/// while letting power users keep everything.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum ToolProfile {
9    Minimal,
10    Standard,
11    Power,
12    Custom(Vec<String>),
13}
14
15impl ToolProfile {
16    pub fn parse(s: &str) -> Option<Self> {
17        match s.to_lowercase().as_str() {
18            "minimal" | "min" => Some(Self::Minimal),
19            "standard" | "std" | "default" => Some(Self::Standard),
20            "power" | "full" | "all" => Some(Self::Power),
21            _ => None,
22        }
23    }
24
25    pub fn as_str(&self) -> &str {
26        match self {
27            Self::Minimal => "minimal",
28            Self::Standard => "standard",
29            Self::Power => "power",
30            Self::Custom(_) => "custom",
31        }
32    }
33
34    pub fn description(&self) -> &str {
35        match self {
36            Self::Minimal => "5 essential tools for new users",
37            Self::Standard => "20 balanced tools (recommended)",
38            Self::Power => "All tools exposed",
39            Self::Custom(v) => {
40                if v.is_empty() {
41                    "Custom tool list (empty)"
42                } else {
43                    "Custom tool list"
44                }
45            }
46        }
47    }
48
49    pub fn is_tool_enabled(&self, tool_name: &str) -> bool {
50        match self {
51            Self::Power => true,
52            Self::Minimal => MINIMAL_TOOLS.contains(&tool_name),
53            Self::Standard => STANDARD_TOOLS.contains(&tool_name),
54            Self::Custom(list) => list.iter().any(|t| t == tool_name),
55        }
56    }
57
58    pub fn tool_count(&self) -> usize {
59        match self {
60            Self::Minimal => MINIMAL_TOOLS.len(),
61            Self::Standard => STANDARD_TOOLS.len(),
62            Self::Power => 0, // dynamic — caller should use registry count
63            Self::Custom(list) => list.len(),
64        }
65    }
66
67    pub fn tool_names(&self) -> Vec<&str> {
68        match self {
69            Self::Minimal => MINIMAL_TOOLS.to_vec(),
70            Self::Standard => STANDARD_TOOLS.to_vec(),
71            Self::Power | Self::Custom(_) => vec![],
72        }
73    }
74
75    /// Resolves the active tool profile from environment, then config.
76    ///
77    /// Priority: `LEAN_CTX_TOOL_PROFILE` env > config `tool_profile` > config `tools.enabled` > default.
78    /// Existing installs default to `power` (backward compat).
79    /// New installs set `standard` during setup.
80    pub fn from_config(cfg: &super::config::Config) -> Self {
81        if let Ok(val) = std::env::var("LEAN_CTX_TOOL_PROFILE") {
82            let trimmed = val.trim();
83            if let Some(profile) = Self::parse(trimmed) {
84                return profile;
85            }
86            tracing::warn!("Unknown LEAN_CTX_TOOL_PROFILE value '{trimmed}', using config");
87        }
88
89        if let Some(ref profile_name) = cfg.tool_profile {
90            if let Some(profile) = Self::parse(profile_name) {
91                return profile;
92            }
93            tracing::warn!("Unknown tool_profile '{profile_name}' in config, using default");
94        }
95
96        if !cfg.tools_enabled.is_empty() {
97            return Self::Custom(cfg.tools_enabled.clone());
98        }
99
100        Self::Power
101    }
102}
103
104impl fmt::Display for ToolProfile {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        write!(f, "{}", self.as_str())
107    }
108}
109
110const MINIMAL_TOOLS: &[&str] = &[
111    "ctx_read",
112    "ctx_shell",
113    "shell",
114    "ctx_search",
115    "ctx_tree",
116    "ctx_session",
117];
118
119const STANDARD_TOOLS: &[&str] = &[
120    // Everything in minimal
121    "ctx_read",
122    "ctx_shell",
123    "shell",
124    "ctx_search",
125    "ctx_tree",
126    "ctx_session",
127    // Plus balanced additions
128    "ctx_semantic_search",
129    "ctx_knowledge",
130    "ctx_overview",
131    "ctx_repomap",
132    "ctx_callgraph",
133    "ctx_impact",
134    "ctx_compress",
135    "ctx_multi_read",
136    "ctx_delta",
137    "ctx_edit",
138    "ctx_agent",
139    "ctx_architecture",
140    "ctx_pack",
141    "ctx_routes",
142    "ctx_refactor",
143];
144
145/// Available built-in profile names.
146pub const PROFILE_NAMES: &[&str] = &["minimal", "standard", "power"];
147
148pub struct ProfileInfo {
149    pub name: &'static str,
150    pub tool_count: &'static str,
151    pub description: &'static str,
152}
153
154pub fn list_profiles() -> Vec<ProfileInfo> {
155    vec![
156        ProfileInfo {
157            name: "minimal",
158            tool_count: "5",
159            description: "Essential tools for new users / skeptics",
160        },
161        ProfileInfo {
162            name: "standard",
163            tool_count: "20",
164            description: "Balanced set (recommended for most users)",
165        },
166        ProfileInfo {
167            name: "power",
168            tool_count: "all",
169            description: "Every tool exposed (backward compatible)",
170        },
171    ]
172}
173
174/// Writes the `tool_profile` setting to config.toml, preserving all comments,
175/// formatting, and unrelated keys (robust against substring/comment matches).
176pub fn set_profile_in_config(profile_name: &str) -> Result<(), String> {
177    let config_dir = crate::core::data_dir::lean_ctx_data_dir()
178        .map_err(|e| format!("Cannot determine config dir: {e}"))?;
179    let config_path = config_dir.join("config.toml");
180
181    let mut doc = crate::config_io::load_toml_document(&config_path);
182    doc["tool_profile"] = toml_edit::value(profile_name);
183    crate::config_io::write_toml_document(&config_path, &doc)?;
184    Ok(())
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn parse_known_profiles() {
193        assert_eq!(ToolProfile::parse("minimal"), Some(ToolProfile::Minimal));
194        assert_eq!(ToolProfile::parse("min"), Some(ToolProfile::Minimal));
195        assert_eq!(ToolProfile::parse("standard"), Some(ToolProfile::Standard));
196        assert_eq!(ToolProfile::parse("std"), Some(ToolProfile::Standard));
197        assert_eq!(ToolProfile::parse("default"), Some(ToolProfile::Standard));
198        assert_eq!(ToolProfile::parse("power"), Some(ToolProfile::Power));
199        assert_eq!(ToolProfile::parse("full"), Some(ToolProfile::Power));
200        assert_eq!(ToolProfile::parse("all"), Some(ToolProfile::Power));
201    }
202
203    #[test]
204    fn parse_case_insensitive() {
205        assert_eq!(ToolProfile::parse("MINIMAL"), Some(ToolProfile::Minimal));
206        assert_eq!(ToolProfile::parse("Standard"), Some(ToolProfile::Standard));
207        assert_eq!(ToolProfile::parse("POWER"), Some(ToolProfile::Power));
208    }
209
210    #[test]
211    fn parse_unknown_returns_none() {
212        assert_eq!(ToolProfile::parse("unknown"), None);
213        assert_eq!(ToolProfile::parse(""), None);
214    }
215
216    #[test]
217    fn minimal_has_6_tools() {
218        assert_eq!(MINIMAL_TOOLS.len(), 6);
219    }
220
221    #[test]
222    fn standard_has_21_tools() {
223        assert_eq!(STANDARD_TOOLS.len(), 21);
224    }
225
226    #[test]
227    fn minimal_is_subset_of_standard() {
228        for tool in MINIMAL_TOOLS {
229            assert!(
230                STANDARD_TOOLS.contains(tool),
231                "minimal tool {tool} missing from standard"
232            );
233        }
234    }
235
236    #[test]
237    fn power_enables_everything() {
238        let profile = ToolProfile::Power;
239        assert!(profile.is_tool_enabled("ctx_read"));
240        assert!(profile.is_tool_enabled("ctx_anything"));
241        assert!(profile.is_tool_enabled("nonexistent_tool"));
242    }
243
244    #[test]
245    fn minimal_filters_correctly() {
246        let profile = ToolProfile::Minimal;
247        assert!(profile.is_tool_enabled("ctx_read"));
248        assert!(profile.is_tool_enabled("ctx_shell"));
249        assert!(profile.is_tool_enabled("ctx_search"));
250        assert!(profile.is_tool_enabled("ctx_tree"));
251        assert!(profile.is_tool_enabled("ctx_session"));
252        assert!(!profile.is_tool_enabled("ctx_semantic_search"));
253        assert!(!profile.is_tool_enabled("ctx_architecture"));
254        assert!(!profile.is_tool_enabled("ctx_benchmark"));
255    }
256
257    #[test]
258    fn standard_filters_correctly() {
259        let profile = ToolProfile::Standard;
260        assert!(profile.is_tool_enabled("ctx_read"));
261        assert!(profile.is_tool_enabled("ctx_semantic_search"));
262        assert!(profile.is_tool_enabled("ctx_architecture"));
263        assert!(!profile.is_tool_enabled("ctx_benchmark"));
264        assert!(!profile.is_tool_enabled("ctx_analyze"));
265        assert!(!profile.is_tool_enabled("ctx_smells"));
266    }
267
268    #[test]
269    fn custom_profile_uses_provided_list() {
270        let profile = ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()]);
271        assert!(profile.is_tool_enabled("ctx_read"));
272        assert!(profile.is_tool_enabled("ctx_shell"));
273        assert!(!profile.is_tool_enabled("ctx_search"));
274    }
275
276    #[test]
277    fn custom_empty_enables_nothing() {
278        let profile = ToolProfile::Custom(vec![]);
279        assert!(!profile.is_tool_enabled("ctx_read"));
280    }
281
282    #[test]
283    fn display_matches_as_str() {
284        assert_eq!(format!("{}", ToolProfile::Minimal), "minimal");
285        assert_eq!(format!("{}", ToolProfile::Standard), "standard");
286        assert_eq!(format!("{}", ToolProfile::Power), "power");
287        assert_eq!(
288            format!("{}", ToolProfile::Custom(vec!["ctx_read".into()])),
289            "custom"
290        );
291    }
292
293    #[test]
294    fn tool_count_matches_list_length() {
295        assert_eq!(ToolProfile::Minimal.tool_count(), MINIMAL_TOOLS.len());
296        assert_eq!(ToolProfile::Standard.tool_count(), STANDARD_TOOLS.len());
297        assert_eq!(ToolProfile::Power.tool_count(), 0);
298    }
299
300    #[test]
301    fn from_config_defaults_to_power_for_backward_compat() {
302        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
303            return;
304        }
305        let cfg = crate::core::config::Config {
306            tool_profile: None,
307            tools_enabled: vec![],
308            ..Default::default()
309        };
310        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Power);
311    }
312
313    #[test]
314    fn from_config_respects_tool_profile_field() {
315        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
316            return;
317        }
318        let cfg = crate::core::config::Config {
319            tool_profile: Some("minimal".to_string()),
320            tools_enabled: vec![],
321            ..Default::default()
322        };
323        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Minimal);
324    }
325
326    #[test]
327    fn from_config_tools_enabled_creates_custom() {
328        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
329            return;
330        }
331        let cfg = crate::core::config::Config {
332            tool_profile: None,
333            tools_enabled: vec!["ctx_read".to_string(), "ctx_shell".to_string()],
334            ..Default::default()
335        };
336        let profile = ToolProfile::from_config(&cfg);
337        assert_eq!(
338            profile,
339            ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()])
340        );
341    }
342
343    #[test]
344    fn tool_profile_takes_precedence_over_tools_enabled() {
345        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
346            return;
347        }
348        let cfg = crate::core::config::Config {
349            tool_profile: Some("standard".to_string()),
350            tools_enabled: vec!["ctx_read".to_string()],
351            ..Default::default()
352        };
353        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Standard);
354    }
355
356    #[test]
357    fn all_profile_names_are_parseable() {
358        for name in PROFILE_NAMES {
359            assert!(
360                ToolProfile::parse(name).is_some(),
361                "profile name '{name}' should be parseable"
362            );
363        }
364    }
365
366    #[test]
367    fn list_profiles_returns_three_entries() {
368        let profiles = list_profiles();
369        assert_eq!(profiles.len(), 3);
370    }
371
372    #[test]
373    fn standard_includes_edit_and_delta() {
374        let profile = ToolProfile::Standard;
375        assert!(
376            profile.is_tool_enabled("ctx_edit"),
377            "ctx_edit must be in standard"
378        );
379        assert!(
380            profile.is_tool_enabled("ctx_delta"),
381            "ctx_delta must be in standard"
382        );
383    }
384}