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 => "6 essential tools for new users",
37            Self::Standard => "21 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: "6",
159            description: "Essential tools for new users / skeptics",
160        },
161        ProfileInfo {
162            name: "standard",
163            tool_count: "21",
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 profile_display_counts_match_tool_arrays() {
278        // The numbers shown by `lean-ctx tools` must equal the actual array
279        // lengths, so adding/removing a profile tool (e.g. the `shell` alias)
280        // can never silently desync the advertised count from reality.
281        let profiles = list_profiles();
282        assert_eq!(
283            profiles[0].tool_count.parse::<usize>().unwrap(),
284            MINIMAL_TOOLS.len(),
285            "minimal count must match MINIMAL_TOOLS length",
286        );
287        assert_eq!(
288            profiles[1].tool_count.parse::<usize>().unwrap(),
289            STANDARD_TOOLS.len(),
290            "standard count must match STANDARD_TOOLS length",
291        );
292        assert_eq!(profiles[2].tool_count, "all");
293    }
294
295    #[test]
296    fn custom_empty_enables_nothing() {
297        let profile = ToolProfile::Custom(vec![]);
298        assert!(!profile.is_tool_enabled("ctx_read"));
299    }
300
301    #[test]
302    fn display_matches_as_str() {
303        assert_eq!(format!("{}", ToolProfile::Minimal), "minimal");
304        assert_eq!(format!("{}", ToolProfile::Standard), "standard");
305        assert_eq!(format!("{}", ToolProfile::Power), "power");
306        assert_eq!(
307            format!("{}", ToolProfile::Custom(vec!["ctx_read".into()])),
308            "custom"
309        );
310    }
311
312    #[test]
313    fn tool_count_matches_list_length() {
314        assert_eq!(ToolProfile::Minimal.tool_count(), MINIMAL_TOOLS.len());
315        assert_eq!(ToolProfile::Standard.tool_count(), STANDARD_TOOLS.len());
316        assert_eq!(ToolProfile::Power.tool_count(), 0);
317    }
318
319    #[test]
320    fn from_config_defaults_to_power_for_backward_compat() {
321        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
322            return;
323        }
324        let cfg = crate::core::config::Config {
325            tool_profile: None,
326            tools_enabled: vec![],
327            ..Default::default()
328        };
329        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Power);
330    }
331
332    #[test]
333    fn from_config_respects_tool_profile_field() {
334        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
335            return;
336        }
337        let cfg = crate::core::config::Config {
338            tool_profile: Some("minimal".to_string()),
339            tools_enabled: vec![],
340            ..Default::default()
341        };
342        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Minimal);
343    }
344
345    #[test]
346    fn from_config_tools_enabled_creates_custom() {
347        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
348            return;
349        }
350        let cfg = crate::core::config::Config {
351            tool_profile: None,
352            tools_enabled: vec!["ctx_read".to_string(), "ctx_shell".to_string()],
353            ..Default::default()
354        };
355        let profile = ToolProfile::from_config(&cfg);
356        assert_eq!(
357            profile,
358            ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()])
359        );
360    }
361
362    #[test]
363    fn tool_profile_takes_precedence_over_tools_enabled() {
364        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
365            return;
366        }
367        let cfg = crate::core::config::Config {
368            tool_profile: Some("standard".to_string()),
369            tools_enabled: vec!["ctx_read".to_string()],
370            ..Default::default()
371        };
372        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Standard);
373    }
374
375    #[test]
376    fn all_profile_names_are_parseable() {
377        for name in PROFILE_NAMES {
378            assert!(
379                ToolProfile::parse(name).is_some(),
380                "profile name '{name}' should be parseable"
381            );
382        }
383    }
384
385    #[test]
386    fn list_profiles_returns_three_entries() {
387        let profiles = list_profiles();
388        assert_eq!(profiles.len(), 3);
389    }
390
391    #[test]
392    fn standard_includes_edit_and_delta() {
393        let profile = ToolProfile::Standard;
394        assert!(
395            profile.is_tool_enabled("ctx_edit"),
396            "ctx_edit must be in standard"
397        );
398        assert!(
399            profile.is_tool_enabled("ctx_delta"),
400            "ctx_delta must be in standard"
401        );
402    }
403}