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 => "5 surgical tools — each irreplaceable (recommended)",
45            Self::Standard => "15 balanced tools (adds compose, explore, callgraph, execute, 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*
129/// sentinel that clears any pin so the default returns (lazy core advertised,
130/// everything callable via `ctx_call`). Empty/whitespace is the documented
131/// default of `tool_profile` (#613); treating it as unpinned avoids a spurious
132/// `Unknown tool_profile ''` warning on the documented default. Centralised so
133/// the config loader, the CLI (`lean-ctx profile lean`) and the dashboard all
134/// agree on the same set (#431).
135pub fn is_unpinned_alias(name: &str) -> bool {
136    matches!(
137        name.trim().to_ascii_lowercase().as_str(),
138        "" | "lean" | "lazy" | "reset"
139    )
140}
141
142/// Surgical core — each tool is irreplaceable. Agent learns <10 tools,
143/// reliably picks the right one for every intent.
144///
145/// #509: symbol lookup folded into `ctx_search` (action="symbol"), so the
146/// former `ctx_symbol` entry is gone — one search entry, not two.
147const MINIMAL_TOOLS: &[&str] = &[
148    "ctx_read",
149    "ctx_shell",
150    "ctx_search",
151    "ctx_glob",
152    "ctx_tree",
153];
154
155/// Balanced set. Adds power-user tools the agent picks regularly but
156/// are not essential for every session.
157///
158/// #509: `ctx_semantic_search` and `ctx_symbol` are folded into `ctx_search`
159/// (action="semantic"/"symbol") and dropped from the advertised set.
160const STANDARD_TOOLS: &[&str] = &[
161    "ctx_read",
162    "ctx_shell",
163    "ctx_search",
164    "ctx_glob",
165    "ctx_tree",
166    "ctx_compose",
167    "ctx_explore",
168    "ctx_knowledge",
169    "ctx_callgraph",
170    "ctx_graph",
171    "ctx_delta",
172    "ctx_execute",
173    "ctx_expand",
174    "ctx_overview",
175    "ctx_url_read",
176];
177
178/// Available built-in profile names.
179pub const PROFILE_NAMES: &[&str] = &["minimal", "standard", "power"];
180
181pub struct ProfileInfo {
182    pub name: &'static str,
183    pub tool_count: &'static str,
184    pub description: &'static str,
185}
186
187pub fn list_profiles() -> Vec<ProfileInfo> {
188    vec![
189        ProfileInfo {
190            name: "minimal",
191            tool_count: "5",
192            description: "Surgical core — each tool irreplaceable (recommended)",
193        },
194        ProfileInfo {
195            name: "standard",
196            tool_count: "15",
197            description: "Balanced set — adds compose, explore, callgraph, execute, delta, more",
198        },
199        ProfileInfo {
200            name: "power",
201            tool_count: "all",
202            description: "Every tool exposed (backward compatible)",
203        },
204    ]
205}
206
207/// Writes the `tool_profile` setting to config.toml, preserving all comments,
208/// formatting, and unrelated keys (robust against substring/comment matches).
209pub fn set_profile_in_config(profile_name: &str) -> Result<(), String> {
210    // Canonical config location (RO-safe config category, GH #408). Writing it
211    // anywhere else than `Config::load` reads would split-brain once the data
212    // default flips to `$XDG_DATA_HOME`.
213    let config_path = crate::core::config::Config::path()
214        .ok_or_else(|| "Cannot determine config dir".to_string())?;
215
216    let mut doc = crate::config_io::load_toml_document(&config_path);
217    doc["tool_profile"] = toml_edit::value(profile_name);
218    crate::config_io::write_toml_document(&config_path, &doc)?;
219    Ok(())
220}
221
222/// Removes the `tool_profile` key from config.toml, restoring the lean
223/// default: only the lazy core set is advertised in `tools/list`,
224/// while every registered tool stays reachable through `ctx_call`. This is
225/// the recommended low-overhead mode (#575).
226pub fn clear_profile_in_config() -> Result<(), String> {
227    let config_path = crate::core::config::Config::path()
228        .ok_or_else(|| "Cannot determine config dir".to_string())?;
229    if !config_path.exists() {
230        return Ok(());
231    }
232
233    let mut doc = crate::config_io::load_toml_document(&config_path);
234    if doc.remove("tool_profile").is_none() {
235        return Ok(());
236    }
237    crate::config_io::write_toml_document(&config_path, &doc)?;
238    Ok(())
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn parse_known_profiles() {
247        assert_eq!(ToolProfile::parse("minimal"), Some(ToolProfile::Minimal));
248        assert_eq!(ToolProfile::parse("min"), Some(ToolProfile::Minimal));
249        assert_eq!(ToolProfile::parse("standard"), Some(ToolProfile::Standard));
250        assert_eq!(ToolProfile::parse("std"), Some(ToolProfile::Standard));
251        assert_eq!(ToolProfile::parse("default"), Some(ToolProfile::Standard));
252        assert_eq!(ToolProfile::parse("power"), Some(ToolProfile::Power));
253        assert_eq!(ToolProfile::parse("full"), Some(ToolProfile::Power));
254        assert_eq!(ToolProfile::parse("all"), Some(ToolProfile::Power));
255    }
256
257    #[test]
258    fn parse_case_insensitive() {
259        assert_eq!(ToolProfile::parse("MINIMAL"), Some(ToolProfile::Minimal));
260        assert_eq!(ToolProfile::parse("Standard"), Some(ToolProfile::Standard));
261        assert_eq!(ToolProfile::parse("POWER"), Some(ToolProfile::Power));
262    }
263
264    #[test]
265    fn parse_unknown_returns_none() {
266        assert_eq!(ToolProfile::parse("unknown"), None);
267        assert_eq!(ToolProfile::parse(""), None);
268    }
269
270    #[test]
271    fn minimal_profile_schema_budget() {
272        // tool_profile=minimal advertises the 9-tool surgical set; the schemas
273        // they re-send every turn (description + input schema) must stay small.
274        // This is the tool-side of the faithful-arm per-turn prefix tax (#361).
275        const MINIMAL_SCHEMA_BUDGET_TOKENS: usize = 2800;
276        let defs = crate::server::registry::build_registry().tool_defs();
277        let total: usize = defs
278            .iter()
279            .filter(|t| MINIMAL_TOOLS.contains(&t.name.as_ref()))
280            .map(crate::core::context_overhead::tool_tokens)
281            .sum();
282        assert!(total > 0, "minimal tools must exist in the registry");
283        assert!(
284            total <= MINIMAL_SCHEMA_BUDGET_TOKENS,
285            "minimal-profile tool schemas = {total} tok, budget {MINIMAL_SCHEMA_BUDGET_TOKENS}"
286        );
287    }
288
289    #[test]
290    fn minimal_is_subset_of_standard() {
291        for tool in MINIMAL_TOOLS {
292            assert!(
293                STANDARD_TOOLS.contains(tool),
294                "minimal tool {tool} missing from standard"
295            );
296        }
297    }
298
299    #[test]
300    fn power_enables_everything() {
301        let profile = ToolProfile::Power;
302        assert!(profile.is_tool_enabled("ctx_read"));
303        assert!(profile.is_tool_enabled("ctx_anything"));
304        assert!(profile.is_tool_enabled("nonexistent_tool"));
305    }
306
307    #[test]
308    fn minimal_filters_correctly() {
309        let profile = ToolProfile::Minimal;
310        assert!(profile.is_tool_enabled("ctx_read"));
311        assert!(profile.is_tool_enabled("ctx_shell"));
312        assert!(profile.is_tool_enabled("ctx_search"));
313        assert!(profile.is_tool_enabled("ctx_glob"));
314        assert!(profile.is_tool_enabled("ctx_tree"));
315        // #509: symbol/semantic lookups are now ctx_search actions, not their
316        // own minimal tools.
317        assert!(!profile.is_tool_enabled("ctx_symbol"));
318        assert!(!profile.is_tool_enabled("ctx_semantic_search"));
319        assert!(!profile.is_tool_enabled("ctx_callgraph"));
320        assert!(!profile.is_tool_enabled("ctx_benchmark"));
321    }
322
323    #[test]
324    fn standard_filters_correctly() {
325        let profile = ToolProfile::Standard;
326        assert!(profile.is_tool_enabled("ctx_read"));
327        assert!(profile.is_tool_enabled("ctx_compose"));
328        assert!(profile.is_tool_enabled("ctx_explore"));
329        assert!(profile.is_tool_enabled("ctx_glob"));
330        assert!(profile.is_tool_enabled("ctx_callgraph"));
331        assert!(profile.is_tool_enabled("ctx_graph"));
332        assert!(profile.is_tool_enabled("ctx_delta"));
333        assert!(profile.is_tool_enabled("ctx_expand"));
334        assert!(profile.is_tool_enabled("ctx_execute"));
335        assert!(profile.is_tool_enabled("ctx_overview"));
336        // #509: ctx_symbol + ctx_semantic_search folded into ctx_search (action=…),
337        // ctx_multi_read into ctx_read (paths=…) — all dropped from Standard.
338        assert!(!profile.is_tool_enabled("ctx_symbol"));
339        assert!(!profile.is_tool_enabled("ctx_semantic_search"));
340        assert!(!profile.is_tool_enabled("ctx_multi_read"));
341        assert!(profile.is_tool_enabled("ctx_url_read"));
342        assert!(!profile.is_tool_enabled("ctx_benchmark"));
343        assert!(!profile.is_tool_enabled("ctx_analyze"));
344        assert!(!profile.is_tool_enabled("ctx_refactor"));
345        assert!(!profile.is_tool_enabled("ctx_edit"));
346    }
347
348    #[test]
349    fn custom_profile_uses_provided_list() {
350        let profile = ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()]);
351        assert!(profile.is_tool_enabled("ctx_read"));
352        assert!(profile.is_tool_enabled("ctx_shell"));
353        assert!(!profile.is_tool_enabled("ctx_search"));
354    }
355
356    #[test]
357    fn profile_display_counts_match_tool_arrays() {
358        // The numbers shown by `lean-ctx tools` must equal the actual array
359        // lengths, so adding/removing a profile tool (e.g. the `shell` alias)
360        // can never silently desync the advertised count from reality.
361        let profiles = list_profiles();
362        assert_eq!(
363            profiles[0].tool_count.parse::<usize>().unwrap(),
364            MINIMAL_TOOLS.len(),
365            "minimal count must match MINIMAL_TOOLS length",
366        );
367        assert_eq!(
368            profiles[1].tool_count.parse::<usize>().unwrap(),
369            STANDARD_TOOLS.len(),
370            "standard count must match STANDARD_TOOLS length",
371        );
372        assert_eq!(profiles[2].tool_count, "all");
373    }
374
375    #[test]
376    fn custom_empty_enables_nothing() {
377        let profile = ToolProfile::Custom(vec![]);
378        assert!(!profile.is_tool_enabled("ctx_read"));
379    }
380
381    #[test]
382    fn display_matches_as_str() {
383        assert_eq!(format!("{}", ToolProfile::Minimal), "minimal");
384        assert_eq!(format!("{}", ToolProfile::Standard), "standard");
385        assert_eq!(format!("{}", ToolProfile::Power), "power");
386        assert_eq!(
387            format!("{}", ToolProfile::Custom(vec!["ctx_read".into()])),
388            "custom"
389        );
390    }
391
392    #[test]
393    fn tool_count_matches_list_length() {
394        assert_eq!(ToolProfile::Minimal.tool_count(), MINIMAL_TOOLS.len());
395        assert_eq!(ToolProfile::Standard.tool_count(), STANDARD_TOOLS.len());
396        assert_eq!(ToolProfile::Power.tool_count(), 0);
397    }
398
399    #[test]
400    fn from_config_defaults_to_power_for_backward_compat() {
401        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
402            return;
403        }
404        let cfg = crate::core::config::Config {
405            tool_profile: None,
406            tools_enabled: vec![],
407            ..Default::default()
408        };
409        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Power);
410    }
411
412    #[test]
413    fn from_config_respects_tool_profile_field() {
414        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
415            return;
416        }
417        let cfg = crate::core::config::Config {
418            tool_profile: Some("minimal".to_string()),
419            tools_enabled: vec![],
420            ..Default::default()
421        };
422        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Minimal);
423    }
424
425    #[test]
426    fn from_config_tools_enabled_creates_custom() {
427        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
428            return;
429        }
430        let cfg = crate::core::config::Config {
431            tool_profile: None,
432            tools_enabled: vec!["ctx_read".to_string(), "ctx_shell".to_string()],
433            ..Default::default()
434        };
435        let profile = ToolProfile::from_config(&cfg);
436        assert_eq!(
437            profile,
438            ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()])
439        );
440    }
441
442    #[test]
443    fn tool_profile_takes_precedence_over_tools_enabled() {
444        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
445            return;
446        }
447        let cfg = crate::core::config::Config {
448            tool_profile: Some("standard".to_string()),
449            tools_enabled: vec!["ctx_read".to_string()],
450            ..Default::default()
451        };
452        assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Standard);
453    }
454
455    #[test]
456    fn empty_tool_profile_is_unpinned_so_tools_enabled_applies() {
457        // #613: `tool_profile = ""` is the documented default ("unpin"), not a
458        // bogus profile. It must resolve silently via the unpinned path (so an
459        // explicit `tools_enabled` takes effect) instead of warning
460        // "Unknown tool_profile ''".
461        assert!(is_unpinned_alias(""));
462        assert!(is_unpinned_alias("   "));
463
464        if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
465            return;
466        }
467        let cfg = crate::core::config::Config {
468            tool_profile: Some(String::new()),
469            tools_enabled: vec!["ctx_read".to_string()],
470            ..Default::default()
471        };
472        assert_eq!(
473            ToolProfile::from_config(&cfg),
474            ToolProfile::Custom(vec!["ctx_read".to_string()]),
475            "empty tool_profile must unpin so tools_enabled takes effect"
476        );
477    }
478
479    #[test]
480    fn all_profile_names_are_parseable() {
481        for name in PROFILE_NAMES {
482            assert!(
483                ToolProfile::parse(name).is_some(),
484                "profile name '{name}' should be parseable"
485            );
486        }
487    }
488
489    #[test]
490    fn list_profiles_returns_three_entries() {
491        let profiles = list_profiles();
492        assert_eq!(profiles.len(), 3);
493    }
494
495    #[test]
496    fn standard_includes_all_core_tools() {
497        let profile = ToolProfile::Standard;
498        assert!(
499            profile.is_tool_enabled("ctx_graph"),
500            "ctx_graph must be in standard"
501        );
502        assert!(
503            profile.is_tool_enabled("ctx_delta"),
504            "ctx_delta must be in standard"
505        );
506        assert!(
507            profile.is_tool_enabled("ctx_expand"),
508            "ctx_expand must be in standard"
509        );
510        assert!(
511            profile.is_tool_enabled("ctx_execute"),
512            "ctx_execute must be in standard (sandboxed code execution)"
513        );
514        // ctx_edit is power-only — native Edit tool is preferred
515        assert!(
516            !profile.is_tool_enabled("ctx_edit"),
517            "ctx_edit must NOT be in standard (native Edit preferred)"
518        );
519    }
520
521    #[test]
522    fn standard_includes_url_read() {
523        let profile = ToolProfile::Standard;
524        assert!(
525            profile.is_tool_enabled("ctx_url_read"),
526            "ctx_url_read must be in standard (web/research context)"
527        );
528    }
529
530    #[test]
531    fn clear_profile_removes_key_and_is_idempotent() {
532        let iso = crate::core::data_dir::isolated_data_dir();
533        set_profile_in_config("power").unwrap();
534        let config_path = iso.path().join("config.toml");
535        assert!(
536            std::fs::read_to_string(&config_path)
537                .unwrap()
538                .contains("tool_profile"),
539            "set_profile_in_config must write the key"
540        );
541
542        clear_profile_in_config().unwrap();
543        assert!(
544            !std::fs::read_to_string(&config_path)
545                .unwrap()
546                .contains("tool_profile"),
547            "clear_profile_in_config must remove the key (lean default, #575)"
548        );
549
550        // Idempotent: clearing again (and on a missing file) must not fail.
551        clear_profile_in_config().unwrap();
552    }
553
554    #[test]
555    fn clear_profile_on_missing_config_is_ok() {
556        let _iso = crate::core::data_dir::isolated_data_dir();
557        clear_profile_in_config().unwrap();
558    }
559}