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///
8/// When NO profile is pinned (no config key, no env var), the server
9/// advertises only the lazy core set (`CORE_TOOL_NAMES`) and the
10/// effective profile falls back to `Power` — which acts as a pure call-gate
11/// ("everything reachable via ctx_call"), not as an advertisement list.
12/// Pinning a profile makes the advertised set explicit and authoritative
13/// (#358), which costs schema tokens: `standard` advertises 19 full schemas,
14/// `power` the whole registry (#575).
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum ToolProfile {
17    Minimal,
18    Standard,
19    Power,
20    Custom(Vec<String>),
21}
22
23impl ToolProfile {
24    pub fn parse(s: &str) -> Option<Self> {
25        match s.to_lowercase().as_str() {
26            "minimal" | "min" => Some(Self::Minimal),
27            "standard" | "std" | "default" => Some(Self::Standard),
28            "power" | "full" | "all" => Some(Self::Power),
29            _ => None,
30        }
31    }
32
33    pub fn as_str(&self) -> &str {
34        match self {
35            Self::Minimal => "minimal",
36            Self::Standard => "standard",
37            Self::Power => "power",
38            Self::Custom(_) => "custom",
39        }
40    }
41
42    pub fn description(&self) -> &str {
43        match self {
44            Self::Minimal => "6 surgical tools — each irreplaceable (recommended)",
45            Self::Standard => "17 balanced tools (adds callgraph, execute, semantics, delta, more)",
46            Self::Power => "All tools exposed",
47            Self::Custom(v) => {
48                if v.is_empty() {
49                    "Custom tool list (empty)"
50                } else {
51                    "Custom tool list"
52                }
53            }
54        }
55    }
56
57    pub fn is_tool_enabled(&self, tool_name: &str) -> bool {
58        match self {
59            Self::Power => true,
60            Self::Minimal => MINIMAL_TOOLS.contains(&tool_name),
61            Self::Standard => STANDARD_TOOLS.contains(&tool_name),
62            Self::Custom(list) => list.iter().any(|t| t == tool_name),
63        }
64    }
65
66    pub fn tool_count(&self) -> usize {
67        match self {
68            Self::Minimal => MINIMAL_TOOLS.len(),
69            Self::Standard => STANDARD_TOOLS.len(),
70            Self::Power => 0, // dynamic — caller should use registry count
71            Self::Custom(list) => list.len(),
72        }
73    }
74
75    pub fn tool_names(&self) -> Vec<&str> {
76        match self {
77            Self::Minimal => MINIMAL_TOOLS.to_vec(),
78            Self::Standard => STANDARD_TOOLS.to_vec(),
79            Self::Power | Self::Custom(_) => vec![],
80        }
81    }
82
83    /// Resolves the active tool profile from environment, then config.
84    ///
85    /// Priority: `LEAN_CTX_TOOL_PROFILE` env > config `tool_profile` > config `tools.enabled` > default.
86    /// Existing installs default to `power` (backward compat).
87    /// New installs set `standard` during setup.
88    pub fn from_config(cfg: &super::config::Config) -> Self {
89        if let Ok(val) = std::env::var("LEAN_CTX_TOOL_PROFILE") {
90            let trimmed = val.trim();
91            if let Some(profile) = Self::parse(trimmed) {
92                return profile;
93            }
94            // Same "unpin" sentinel handling as for the config key below (#431).
95            if !trimmed.is_empty() && !is_unpinned_alias(trimmed) {
96                tracing::warn!("Unknown LEAN_CTX_TOOL_PROFILE value '{trimmed}', using config");
97            }
98        }
99
100        if let Some(ref profile_name) = cfg.tool_profile {
101            if let Some(profile) = Self::parse(profile_name) {
102                return profile;
103            }
104            // `lean`/`lazy`/`reset` are the *unpinned* sentinel (lazy core
105            // advertised, everything reachable via ctx_call) — not a pinned
106            // tier. They can legitimately land in config (older versions, the
107            // dashboard's "Lean" button, manual edits), so resolve them
108            // silently to the default instead of warning + falling back (#431).
109            if !is_unpinned_alias(profile_name) {
110                tracing::warn!("Unknown tool_profile '{profile_name}' in config, using default");
111            }
112        }
113
114        if !cfg.tools_enabled.is_empty() {
115            return Self::Custom(cfg.tools_enabled.clone());
116        }
117
118        Self::Power
119    }
120}
121
122impl fmt::Display for ToolProfile {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        write!(f, "{}", self.as_str())
125    }
126}
127
128/// `lean`/`lazy`/`reset` are not pinned tiers — they are the *unpin* sentinel
129/// that clears any pin so the default returns (lazy core advertised, everything
130/// callable via `ctx_call`). Centralised so the config loader, the CLI
131/// (`lean-ctx profile lean`) and the dashboard all agree on the same set (#431).
132pub fn is_unpinned_alias(name: &str) -> bool {
133    matches!(
134        name.trim().to_ascii_lowercase().as_str(),
135        "lean" | "lazy" | "reset"
136    )
137}
138
139/// Surgical core — each tool is irreplaceable. Agent learns <10 tools,
140/// reliably picks the right one for every intent.
141const MINIMAL_TOOLS: &[&str] = &[
142    "ctx_read",
143    "ctx_shell",
144    "ctx_search",
145    "ctx_glob",
146    "ctx_tree",
147    "ctx_symbol",
148];
149
150/// Balanced set. Adds power-user tools the agent picks regularly but
151/// are not essential for every session.
152const STANDARD_TOOLS: &[&str] = &[
153    "ctx_read",
154    "ctx_shell",
155    "ctx_search",
156    "ctx_glob",
157    "ctx_tree",
158    "ctx_symbol",
159    "ctx_compose",
160    "ctx_knowledge",
161    "ctx_callgraph",
162    "ctx_graph",
163    "ctx_semantic_search",
164    "ctx_delta",
165    "ctx_execute",
166    "ctx_expand",
167    "ctx_overview",
168    "ctx_url_read",
169];
170
171/// Available built-in profile names.
172pub const PROFILE_NAMES: &[&str] = &["minimal", "standard", "power"];
173
174pub struct ProfileInfo {
175    pub name: &'static str,
176    pub tool_count: &'static str,
177    pub description: &'static str,
178}
179
180pub fn list_profiles() -> Vec<ProfileInfo> {
181    vec![
182        ProfileInfo {
183            name: "minimal",
184            tool_count: "6",
185            description: "Surgical core — each tool irreplaceable (recommended)",
186        },
187        ProfileInfo {
188            name: "standard",
189            tool_count: "16",
190            description: "Balanced set — adds callgraph, execute, semantics, delta, more",
191        },
192        ProfileInfo {
193            name: "power",
194            tool_count: "all",
195            description: "Every tool exposed (backward compatible)",
196        },
197    ]
198}
199
200/// Writes the `tool_profile` setting to config.toml, preserving all comments,
201/// formatting, and unrelated keys (robust against substring/comment matches).
202pub fn set_profile_in_config(profile_name: &str) -> Result<(), String> {
203    // Canonical config location (RO-safe config category, GH #408). Writing it
204    // anywhere else than `Config::load` reads would split-brain once the data
205    // default flips to `$XDG_DATA_HOME`.
206    let config_path = crate::core::config::Config::path()
207        .ok_or_else(|| "Cannot determine config dir".to_string())?;
208
209    let mut doc = crate::config_io::load_toml_document(&config_path);
210    doc["tool_profile"] = toml_edit::value(profile_name);
211    crate::config_io::write_toml_document(&config_path, &doc)?;
212    Ok(())
213}
214
215/// Removes the `tool_profile` key from config.toml, restoring the lean
216/// default: only the lazy core set is advertised in `tools/list`,
217/// while every registered tool stays reachable through `ctx_call`. This is
218/// the recommended low-overhead mode (#575).
219pub fn clear_profile_in_config() -> Result<(), String> {
220    let config_path = crate::core::config::Config::path()
221        .ok_or_else(|| "Cannot determine config dir".to_string())?;
222    if !config_path.exists() {
223        return Ok(());
224    }
225
226    let mut doc = crate::config_io::load_toml_document(&config_path);
227    if doc.remove("tool_profile").is_none() {
228        return Ok(());
229    }
230    crate::config_io::write_toml_document(&config_path, &doc)?;
231    Ok(())
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn parse_known_profiles() {
240        assert_eq!(ToolProfile::parse("minimal"), Some(ToolProfile::Minimal));
241        assert_eq!(ToolProfile::parse("min"), Some(ToolProfile::Minimal));
242        assert_eq!(ToolProfile::parse("standard"), Some(ToolProfile::Standard));
243        assert_eq!(ToolProfile::parse("std"), Some(ToolProfile::Standard));
244        assert_eq!(ToolProfile::parse("default"), Some(ToolProfile::Standard));
245        assert_eq!(ToolProfile::parse("power"), Some(ToolProfile::Power));
246        assert_eq!(ToolProfile::parse("full"), Some(ToolProfile::Power));
247        assert_eq!(ToolProfile::parse("all"), Some(ToolProfile::Power));
248    }
249
250    #[test]
251    fn parse_case_insensitive() {
252        assert_eq!(ToolProfile::parse("MINIMAL"), Some(ToolProfile::Minimal));
253        assert_eq!(ToolProfile::parse("Standard"), Some(ToolProfile::Standard));
254        assert_eq!(ToolProfile::parse("POWER"), Some(ToolProfile::Power));
255    }
256
257    #[test]
258    fn parse_unknown_returns_none() {
259        assert_eq!(ToolProfile::parse("unknown"), None);
260        assert_eq!(ToolProfile::parse(""), None);
261    }
262
263    #[test]
264    fn minimal_profile_schema_budget() {
265        // tool_profile=minimal advertises the 9-tool surgical set; the schemas
266        // they re-send every turn (description + input schema) must stay small.
267        // This is the tool-side of the faithful-arm per-turn prefix tax (#361).
268        const MINIMAL_SCHEMA_BUDGET_TOKENS: usize = 2800;
269        let defs = crate::server::registry::build_registry().tool_defs();
270        let total: usize = defs
271            .iter()
272            .filter(|t| MINIMAL_TOOLS.contains(&t.name.as_ref()))
273            .map(crate::core::context_overhead::tool_tokens)
274            .sum();
275        assert!(total > 0, "minimal tools must exist in the registry");
276        assert!(
277            total <= MINIMAL_SCHEMA_BUDGET_TOKENS,
278            "minimal-profile tool schemas = {total} tok, budget {MINIMAL_SCHEMA_BUDGET_TOKENS}"
279        );
280    }
281
282    #[test]
283    fn minimal_is_subset_of_standard() {
284        for tool in MINIMAL_TOOLS {
285            assert!(
286                STANDARD_TOOLS.contains(tool),
287                "minimal tool {tool} missing from standard"
288            );
289        }
290    }
291
292    #[test]
293    fn power_enables_everything() {
294        let profile = ToolProfile::Power;
295        assert!(profile.is_tool_enabled("ctx_read"));
296        assert!(profile.is_tool_enabled("ctx_anything"));
297        assert!(profile.is_tool_enabled("nonexistent_tool"));
298    }
299
300    #[test]
301    fn minimal_filters_correctly() {
302        let profile = ToolProfile::Minimal;
303        assert!(profile.is_tool_enabled("ctx_read"));
304        assert!(profile.is_tool_enabled("ctx_shell"));
305        assert!(profile.is_tool_enabled("ctx_search"));
306        assert!(profile.is_tool_enabled("ctx_glob"));
307        assert!(profile.is_tool_enabled("ctx_tree"));
308        assert!(profile.is_tool_enabled("ctx_symbol"));
309        assert!(!profile.is_tool_enabled("ctx_semantic_search"));
310        assert!(!profile.is_tool_enabled("ctx_callgraph"));
311        assert!(!profile.is_tool_enabled("ctx_benchmark"));
312    }
313
314    #[test]
315    fn standard_filters_correctly() {
316        let profile = ToolProfile::Standard;
317        assert!(profile.is_tool_enabled("ctx_read"));
318        assert!(profile.is_tool_enabled("ctx_compose"));
319        assert!(profile.is_tool_enabled("ctx_symbol"));
320        assert!(profile.is_tool_enabled("ctx_glob"));
321        assert!(profile.is_tool_enabled("ctx_semantic_search"));
322        assert!(profile.is_tool_enabled("ctx_callgraph"));
323        assert!(profile.is_tool_enabled("ctx_graph"));
324        assert!(profile.is_tool_enabled("ctx_delta"));
325        assert!(profile.is_tool_enabled("ctx_expand"));
326        assert!(profile.is_tool_enabled("ctx_execute"));
327        assert!(profile.is_tool_enabled("ctx_overview"));
328        // #509: ctx_multi_read is a deprecated alias folded into ctx_read (paths=…)
329        // and was removed from the Standard set.
330        assert!(!profile.is_tool_enabled("ctx_multi_read"));
331        assert!(profile.is_tool_enabled("ctx_url_read"));
332        assert!(!profile.is_tool_enabled("ctx_benchmark"));
333        assert!(!profile.is_tool_enabled("ctx_analyze"));
334        assert!(!profile.is_tool_enabled("ctx_refactor"));
335        assert!(!profile.is_tool_enabled("ctx_edit"));
336    }
337
338    #[test]
339    fn custom_profile_uses_provided_list() {
340        let profile = ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()]);
341        assert!(profile.is_tool_enabled("ctx_read"));
342        assert!(profile.is_tool_enabled("ctx_shell"));
343        assert!(!profile.is_tool_enabled("ctx_search"));
344    }
345
346    #[test]
347    fn profile_display_counts_match_tool_arrays() {
348        // The numbers shown by `lean-ctx tools` must equal the actual array
349        // lengths, so adding/removing a profile tool (e.g. the `shell` alias)
350        // can never silently desync the advertised count from reality.
351        let profiles = list_profiles();
352        assert_eq!(
353            profiles[0].tool_count.parse::<usize>().unwrap(),
354            MINIMAL_TOOLS.len(),
355            "minimal count must match MINIMAL_TOOLS length",
356        );
357        assert_eq!(
358            profiles[1].tool_count.parse::<usize>().unwrap(),
359            STANDARD_TOOLS.len(),
360            "standard count must match STANDARD_TOOLS length",
361        );
362        assert_eq!(profiles[2].tool_count, "all");
363    }
364
365    #[test]
366    fn custom_empty_enables_nothing() {
367        let profile = ToolProfile::Custom(vec![]);
368        assert!(!profile.is_tool_enabled("ctx_read"));
369    }
370
371    #[test]
372    fn display_matches_as_str() {
373        assert_eq!(format!("{}", ToolProfile::Minimal), "minimal");
374        assert_eq!(format!("{}", ToolProfile::Standard), "standard");
375        assert_eq!(format!("{}", ToolProfile::Power), "power");
376        assert_eq!(
377            format!("{}", ToolProfile::Custom(vec!["ctx_read".into()])),
378            "custom"
379        );
380    }
381
382    #[test]
383    fn tool_count_matches_list_length() {
384        assert_eq!(ToolProfile::Minimal.tool_count(), MINIMAL_TOOLS.len());
385        assert_eq!(ToolProfile::Standard.tool_count(), STANDARD_TOOLS.len());
386        assert_eq!(ToolProfile::Power.tool_count(), 0);
387    }
388
389    #[test]
390    fn from_config_defaults_to_power_for_backward_compat() {
391        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
392            return;
393        }
394        let cfg = crate::core::config::Config {
395            tool_profile: None,
396            tools_enabled: vec![],
397            ..Default::default()
398        };
399        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Power);
400    }
401
402    #[test]
403    fn from_config_respects_tool_profile_field() {
404        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
405            return;
406        }
407        let cfg = crate::core::config::Config {
408            tool_profile: Some("minimal".to_string()),
409            tools_enabled: vec![],
410            ..Default::default()
411        };
412        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Minimal);
413    }
414
415    #[test]
416    fn from_config_tools_enabled_creates_custom() {
417        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
418            return;
419        }
420        let cfg = crate::core::config::Config {
421            tool_profile: None,
422            tools_enabled: vec!["ctx_read".to_string(), "ctx_shell".to_string()],
423            ..Default::default()
424        };
425        let profile = ToolProfile::from_config(&cfg);
426        assert_eq!(
427            profile,
428            ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()])
429        );
430    }
431
432    #[test]
433    fn tool_profile_takes_precedence_over_tools_enabled() {
434        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
435            return;
436        }
437        let cfg = crate::core::config::Config {
438            tool_profile: Some("standard".to_string()),
439            tools_enabled: vec!["ctx_read".to_string()],
440            ..Default::default()
441        };
442        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Standard);
443    }
444
445    #[test]
446    fn all_profile_names_are_parseable() {
447        for name in PROFILE_NAMES {
448            assert!(
449                ToolProfile::parse(name).is_some(),
450                "profile name '{name}' should be parseable"
451            );
452        }
453    }
454
455    #[test]
456    fn list_profiles_returns_three_entries() {
457        let profiles = list_profiles();
458        assert_eq!(profiles.len(), 3);
459    }
460
461    #[test]
462    fn standard_includes_all_core_tools() {
463        let profile = ToolProfile::Standard;
464        assert!(
465            profile.is_tool_enabled("ctx_graph"),
466            "ctx_graph must be in standard"
467        );
468        assert!(
469            profile.is_tool_enabled("ctx_delta"),
470            "ctx_delta must be in standard"
471        );
472        assert!(
473            profile.is_tool_enabled("ctx_expand"),
474            "ctx_expand must be in standard"
475        );
476        assert!(
477            profile.is_tool_enabled("ctx_execute"),
478            "ctx_execute must be in standard (sandboxed code execution)"
479        );
480        // ctx_edit is power-only — native Edit tool is preferred
481        assert!(
482            !profile.is_tool_enabled("ctx_edit"),
483            "ctx_edit must NOT be in standard (native Edit preferred)"
484        );
485    }
486
487    #[test]
488    fn standard_includes_url_read() {
489        let profile = ToolProfile::Standard;
490        assert!(
491            profile.is_tool_enabled("ctx_url_read"),
492            "ctx_url_read must be in standard (web/research context)"
493        );
494    }
495
496    #[test]
497    fn clear_profile_removes_key_and_is_idempotent() {
498        let iso = crate::core::data_dir::isolated_data_dir();
499        set_profile_in_config("power").unwrap();
500        let config_path = iso.path().join("config.toml");
501        assert!(
502            std::fs::read_to_string(&config_path)
503                .unwrap()
504                .contains("tool_profile"),
505            "set_profile_in_config must write the key"
506        );
507
508        clear_profile_in_config().unwrap();
509        assert!(
510            !std::fs::read_to_string(&config_path)
511                .unwrap()
512                .contains("tool_profile"),
513            "clear_profile_in_config must remove the key (lean default, #575)"
514        );
515
516        // Idempotent: clearing again (and on a missing file) must not fail.
517        clear_profile_in_config().unwrap();
518    }
519
520    #[test]
521    fn clear_profile_on_missing_config_is_ok() {
522        let _iso = crate::core::data_dir::isolated_data_dir();
523        clear_profile_in_config().unwrap();
524    }
525}