Skip to main content

lean_ctx/server/
dynamic_tools.rs

1use std::collections::HashSet;
2use std::sync::{Mutex, OnceLock};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5pub enum ToolCategory {
6    Core,
7    Internal,
8    Arch,
9    Debug,
10    Memory,
11    Metrics,
12    Session,
13}
14
15impl ToolCategory {
16    pub fn parse(s: &str) -> Option<Self> {
17        match s {
18            "core" => Some(Self::Core),
19            "arch" | "architecture" => Some(Self::Arch),
20            "debug" | "profiling" => Some(Self::Debug),
21            "memory" | "semantic" => Some(Self::Memory),
22            "metrics" | "stats" => Some(Self::Metrics),
23            "session" => Some(Self::Session),
24            _ => None,
25        }
26    }
27
28    pub fn as_str(&self) -> &'static str {
29        match self {
30            Self::Core => "core",
31            Self::Internal => "internal",
32            Self::Arch => "arch",
33            Self::Debug => "debug",
34            Self::Memory => "memory",
35            Self::Metrics => "metrics",
36            Self::Session => "session",
37        }
38    }
39}
40
41#[allow(clippy::match_same_arms)]
42pub fn categorize_tool(name: &str) -> ToolCategory {
43    match name {
44        // Internal: meta/self-referential + automated mechanisms (never exposed)
45        "ctx_metrics"
46        | "ctx_cost"
47        | "ctx_gain"
48        | "ctx_radar"
49        | "ctx_heatmap"
50        | "ctx_feedback"
51        | "ctx_intent"
52        | "ctx_response"
53        | "ctx_discover"
54        | "ctx_discover_tools"
55        | "ctx_load_tools"
56        | "ctx_dedup"
57        | "ctx_preload"
58        | "ctx_prefetch"
59        | "ctx_compress_memory" => ToolCategory::Internal,
60
61        // Core: always visible. Must cover every CORE_TOOL_NAMES entry —
62        // otherwise the category gate silently drops a lazy-core tool for
63        // list_changed-capable clients (ctx_expand was lost this way, #575).
64        "ctx_read" | "ctx_search" | "ctx_shell" | "shell" | "ctx_tree" | "ctx_edit"
65        | "ctx_session" | "ctx_checkpoint" | "ctx_knowledge" | "ctx_overview" | "ctx_graph"
66        | "ctx_call" | "ctx_compress" | "ctx_cache" | "ctx_retrieve" | "ctx_expand" => {
67            ToolCategory::Core
68        }
69
70        // Merged tools (redirects in registry, treated as Core for backward compat)
71        "ctx_multi_read" | "ctx_smart_read" | "ctx_delta" | "ctx_outline" | "ctx_context" => {
72            ToolCategory::Core
73        }
74
75        // Arch: on-demand architecture analysis
76        "ctx_architecture" | "ctx_impact" | "ctx_callgraph" | "ctx_refactor" | "ctx_symbol"
77        | "ctx_routes" | "ctx_smells" | "ctx_index" => ToolCategory::Arch,
78
79        // Debug/Verify: on-demand quality analysis
80        "ctx_benchmark" | "ctx_verify" | "ctx_analyze" | "ctx_profile" | "ctx_proof"
81        | "ctx_review" => ToolCategory::Debug,
82
83        // Provider + URL/Git readers + the MCP gateway are Core: gateways to
84        // external context (GitHub issues, Jira, Postgres, web pages, YouTube,
85        // remote git repos, downstream MCP servers) — always available.
86        // ctx_semantic_search is a first-class retrieval tool (advertised in the
87        // lean core, #422) — keep it Core so the default category gate never hides
88        // it, the very reason agents stopped reaching for it.
89        "ctx_provider" | "ctx_url_read" | "ctx_git_read" | "ctx_tools" | "ctx_semantic_search" => {
90            ToolCategory::Core
91        }
92
93        // Memory: on-demand artifact retrieval
94        "ctx_artifacts" => ToolCategory::Memory,
95
96        // Batch: on-demand batch/PR/sandbox tools
97        "ctx_fill" | "ctx_execute" | "ctx_pack" | "ctx_plan" | "ctx_control" | "ctx_compile" => {
98            ToolCategory::Metrics
99        }
100
101        // Multi-agent: on-demand collaboration
102        "ctx_agent" | "ctx_share" | "ctx_task" | "ctx_handoff" | "ctx_workflow" => {
103            ToolCategory::Session
104        }
105
106        _ => ToolCategory::Core,
107    }
108}
109
110/// A deprecated tool that has been folded into a primary tool (#509 Phase 1).
111///
112/// The alias stays **registered and callable** (directly and via `ctx_call`) for
113/// one release so nothing breaks, but it is hidden from `tools/list` and warns on
114/// use, steering agents to the consolidated primary. Removal happens in Phase 2.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct DeprecatedAlias {
117    /// The primary tool that supersedes this alias (e.g. `"ctx_read"`).
118    pub replacement: &'static str,
119    /// One-line migration hint (e.g. how the primary covers this use case).
120    pub hint: &'static str,
121}
122
123/// Single source of truth for read-cluster deprecations (#509). Returns the
124/// replacement + migration hint when `name` is a deprecated alias, else `None`.
125///
126/// Used by [`crate::server::tool_visibility::is_tool_visible`] to hide the alias
127/// from `tools/list`, and by the dispatch layer to prepend a one-line
128/// deprecation notice to the alias's output. Keeping both behaviours keyed off
129/// this one function guarantees "hidden" and "warned" can never drift apart.
130#[must_use]
131pub fn deprecated_alias(name: &str) -> Option<DeprecatedAlias> {
132    match name {
133        "ctx_smart_read" => Some(DeprecatedAlias {
134            replacement: "ctx_read",
135            hint: "ctx_read auto-selects the mode (omit `mode`, or pass mode=\"auto\")",
136        }),
137        "ctx_multi_read" => Some(DeprecatedAlias {
138            replacement: "ctx_read",
139            hint: "ctx_read now batch-reads via paths=[\"a.rs\",\"b.rs\"]",
140        }),
141        _ => None,
142    }
143}
144
145/// Whether `name` is a deprecated alias hidden from `tools/list` (#509).
146#[must_use]
147pub fn is_deprecated_alias(name: &str) -> bool {
148    deprecated_alias(name).is_some()
149}
150
151/// The one-line deprecation notice prepended to a deprecated alias's output.
152/// Stable per tool (no timestamps/counters) so provider-side prompt caching
153/// stays byte-stable (#498).
154#[must_use]
155pub fn deprecation_notice(name: &str) -> Option<String> {
156    deprecated_alias(name).map(|d| {
157        format!(
158            "[DEPRECATED] {name} is superseded by {} — {}. This alias is hidden from \
159             tools/list and will be removed in a future release.",
160            d.replacement, d.hint
161        )
162    })
163}
164
165pub fn is_readonly_tool(name: &str) -> bool {
166    matches!(
167        name,
168        "ctx_read"
169            | "ctx_search"
170            | "ctx_tree"
171            | "ctx_overview"
172            | "ctx_plan"
173            | "ctx_metrics"
174            | "ctx_compress"
175            | "ctx_session"
176            | "ctx_knowledge"
177            | "ctx_graph"
178            | "ctx_retrieve"
179            | "ctx_provider"
180            | "ctx_multi_read"
181            | "ctx_smart_read"
182            | "ctx_delta"
183            | "ctx_outline"
184            | "ctx_context"
185            | "ctx_call"
186            | "ctx_url_read"
187            | "ctx_git_read"
188            | "ctx_architecture"
189            | "ctx_impact"
190            | "ctx_callgraph"
191            | "ctx_symbol"
192            | "ctx_routes"
193            | "ctx_smells"
194            | "ctx_index"
195            | "ctx_semantic_search"
196            | "ctx_artifacts"
197            | "ctx_cost"
198            | "ctx_gain"
199            | "ctx_heatmap"
200    )
201}
202
203#[derive(Debug)]
204pub struct DynamicToolState {
205    active_categories: HashSet<ToolCategory>,
206    supports_list_changed: bool,
207}
208
209impl Default for DynamicToolState {
210    fn default() -> Self {
211        Self::new()
212    }
213}
214
215impl DynamicToolState {
216    pub fn new() -> Self {
217        let mut active = HashSet::new();
218        active.insert(ToolCategory::Core);
219        active.insert(ToolCategory::Session);
220        Self {
221            active_categories: active,
222            supports_list_changed: false,
223        }
224    }
225
226    /// Creates state with categories from config (env var > config.toml > default).
227    pub fn from_config(categories: &[String]) -> Self {
228        let mut active = HashSet::new();
229        active.insert(ToolCategory::Core);
230        for cat_str in categories {
231            if let Some(cat) = ToolCategory::parse(cat_str) {
232                active.insert(cat);
233            }
234        }
235        Self {
236            active_categories: active,
237            supports_list_changed: false,
238        }
239    }
240
241    pub fn all_enabled() -> Self {
242        let mut active = HashSet::new();
243        active.insert(ToolCategory::Core);
244        active.insert(ToolCategory::Arch);
245        active.insert(ToolCategory::Debug);
246        active.insert(ToolCategory::Memory);
247        active.insert(ToolCategory::Metrics);
248        active.insert(ToolCategory::Session);
249        Self {
250            active_categories: active,
251            supports_list_changed: false,
252        }
253    }
254
255    pub fn set_supports_list_changed(&mut self, val: bool) {
256        self.supports_list_changed = val;
257    }
258
259    pub fn supports_list_changed(&self) -> bool {
260        self.supports_list_changed
261    }
262
263    pub fn load_category(&mut self, cat: ToolCategory) -> bool {
264        self.active_categories.insert(cat)
265    }
266
267    pub fn unload_category(&mut self, cat: ToolCategory) -> bool {
268        if cat == ToolCategory::Core || cat == ToolCategory::Internal {
269            return false;
270        }
271        self.active_categories.remove(&cat)
272    }
273
274    pub fn is_tool_active(&self, name: &str) -> bool {
275        let cat = categorize_tool(name);
276        if cat == ToolCategory::Internal {
277            return false;
278        }
279        if !self.supports_list_changed {
280            return true;
281        }
282        self.active_categories.contains(&cat)
283    }
284
285    pub fn active_categories(&self) -> Vec<&'static str> {
286        let mut cats: Vec<_> = self
287            .active_categories
288            .iter()
289            .map(ToolCategory::as_str)
290            .collect();
291        cats.sort_unstable();
292        cats
293    }
294
295    pub fn all_categories() -> Vec<&'static str> {
296        vec!["core", "arch", "debug", "memory", "metrics", "session"]
297    }
298}
299
300static GLOBAL: OnceLock<Mutex<DynamicToolState>> = OnceLock::new();
301
302pub fn global() -> &'static Mutex<DynamicToolState> {
303    GLOBAL.get_or_init(|| Mutex::new(DynamicToolState::new()))
304}
305
306pub fn init_all_enabled() {
307    let _ = GLOBAL.set(Mutex::new(DynamicToolState::all_enabled()));
308}
309
310/// Initializes the global state from user config (env var > config.toml > default).
311/// Call once during server startup after config is loaded.
312/// If the global was already initialized (e.g. by a concurrent `global()` call),
313/// applies the categories to the existing state instead.
314pub fn init_from_config(categories: &[String]) {
315    if GLOBAL
316        .set(Mutex::new(DynamicToolState::from_config(categories)))
317        .is_err()
318        && let Ok(mut state) = global().lock()
319    {
320        let desired = DynamicToolState::from_config(categories);
321        *state = desired;
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn core_tools_always_active() {
331        let state = DynamicToolState::new();
332        assert!(state.is_tool_active("ctx_read"));
333        assert!(state.is_tool_active("ctx_search"));
334    }
335
336    #[test]
337    fn deprecated_alias_maps_read_cluster_to_ctx_read() {
338        // #509: only the folded read-cluster tools are deprecated; everything
339        // else (incl. the primary) returns None.
340        assert_eq!(
341            deprecated_alias("ctx_smart_read").unwrap().replacement,
342            "ctx_read"
343        );
344        assert_eq!(
345            deprecated_alias("ctx_multi_read").unwrap().replacement,
346            "ctx_read"
347        );
348        assert!(deprecated_alias("ctx_read").is_none());
349        assert!(deprecated_alias("ctx_search").is_none());
350        assert!(is_deprecated_alias("ctx_multi_read"));
351        assert!(!is_deprecated_alias("ctx_read"));
352    }
353
354    #[test]
355    fn deprecation_notice_is_stable_and_names_replacement() {
356        // Stable text (no timestamps/counters) for cache-byte-stability (#498),
357        // and it must point at the primary so agents know where to go.
358        let notice = deprecation_notice("ctx_multi_read").unwrap();
359        assert!(notice.starts_with("[DEPRECATED] ctx_multi_read is superseded by ctx_read"));
360        assert!(notice.contains("paths="));
361        assert_eq!(notice, deprecation_notice("ctx_multi_read").unwrap());
362        assert!(deprecation_notice("ctx_read").is_none());
363    }
364
365    #[test]
366    fn dynamic_tools_filtered_when_list_changed() {
367        let mut state = DynamicToolState::new();
368        state.set_supports_list_changed(true);
369        assert!(!state.is_tool_active("ctx_benchmark"));
370        assert!(!state.is_tool_active("ctx_architecture"));
371        assert!(state.is_tool_active("ctx_read"));
372    }
373
374    #[test]
375    fn load_category_enables_tools() {
376        let mut state = DynamicToolState::new();
377        state.set_supports_list_changed(true);
378        assert!(!state.is_tool_active("ctx_architecture"));
379        state.load_category(ToolCategory::Arch);
380        assert!(state.is_tool_active("ctx_architecture"));
381    }
382
383    #[test]
384    fn cannot_unload_core() {
385        let mut state = DynamicToolState::new();
386        assert!(!state.unload_category(ToolCategory::Core));
387    }
388
389    #[test]
390    fn all_tools_visible_without_list_changed() {
391        let state = DynamicToolState::new();
392        assert!(state.is_tool_active("ctx_graph"));
393        assert!(!state.is_tool_active("ctx_metrics")); // Internal tools never active
394    }
395
396    #[test]
397    fn internal_tools_never_active() {
398        let state = DynamicToolState::all_enabled();
399        assert!(!state.is_tool_active("ctx_metrics"));
400        assert!(!state.is_tool_active("ctx_cost"));
401        assert!(!state.is_tool_active("ctx_discover_tools"));
402        assert!(!state.is_tool_active("ctx_dedup"));
403    }
404
405    // --- from_config: basic scenarios ---
406
407    #[test]
408    fn from_config_core_arch_memory() {
409        let cats = vec!["core".to_string(), "arch".to_string(), "memory".to_string()];
410        let mut state = DynamicToolState::from_config(&cats);
411        state.set_supports_list_changed(true);
412        assert!(state.is_tool_active("ctx_read"));
413        assert!(state.is_tool_active("ctx_architecture"));
414        assert!(state.is_tool_active("ctx_artifacts"));
415        assert!(!state.is_tool_active("ctx_benchmark"));
416        assert!(!state.is_tool_active("ctx_fill"));
417    }
418
419    #[test]
420    fn from_config_empty_still_has_core() {
421        let mut state = DynamicToolState::from_config(&[]);
422        state.set_supports_list_changed(true);
423        assert!(state.is_tool_active("ctx_read"));
424        assert!(!state.is_tool_active("ctx_architecture"));
425        assert!(!state.is_tool_active("ctx_benchmark"));
426        assert!(!state.is_tool_active("ctx_artifacts"));
427    }
428
429    // --- from_config: all categories ---
430
431    #[test]
432    fn from_config_all_categories_enables_everything_except_internal() {
433        let cats = vec![
434            "core".to_string(),
435            "arch".to_string(),
436            "debug".to_string(),
437            "memory".to_string(),
438            "metrics".to_string(),
439            "session".to_string(),
440        ];
441        let mut state = DynamicToolState::from_config(&cats);
442        state.set_supports_list_changed(true);
443        assert!(state.is_tool_active("ctx_read"));
444        assert!(state.is_tool_active("ctx_architecture"));
445        assert!(state.is_tool_active("ctx_benchmark"));
446        assert!(state.is_tool_active("ctx_semantic_search"));
447        assert!(state.is_tool_active("ctx_fill"));
448        assert!(state.is_tool_active("ctx_workflow"));
449        assert!(!state.is_tool_active("ctx_metrics"));
450    }
451
452    // --- from_config: single category ---
453
454    #[test]
455    fn from_config_only_debug() {
456        let cats = vec!["debug".to_string()];
457        let mut state = DynamicToolState::from_config(&cats);
458        state.set_supports_list_changed(true);
459        assert!(state.is_tool_active("ctx_read"));
460        assert!(state.is_tool_active("ctx_benchmark"));
461        assert!(!state.is_tool_active("ctx_architecture"));
462        assert!(!state.is_tool_active("ctx_workflow"));
463    }
464
465    // --- from_config: invalid categories are silently ignored ---
466
467    #[test]
468    fn from_config_ignores_unknown_categories() {
469        let cats = vec![
470            "core".to_string(),
471            "nonexistent".to_string(),
472            "foobar".to_string(),
473        ];
474        let mut state = DynamicToolState::from_config(&cats);
475        state.set_supports_list_changed(true);
476        assert!(state.is_tool_active("ctx_read"));
477        assert!(!state.is_tool_active("ctx_architecture"));
478    }
479
480    #[test]
481    fn from_config_only_invalid_still_has_core() {
482        let cats = vec!["invalid".to_string(), "bogus".to_string()];
483        let mut state = DynamicToolState::from_config(&cats);
484        state.set_supports_list_changed(true);
485        assert!(state.is_tool_active("ctx_read"));
486        assert!(!state.is_tool_active("ctx_benchmark"));
487    }
488
489    // --- from_config: duplicate categories are idempotent ---
490
491    #[test]
492    fn from_config_duplicates_are_harmless() {
493        let cats = vec!["arch".to_string(), "arch".to_string(), "arch".to_string()];
494        let mut state = DynamicToolState::from_config(&cats);
495        state.set_supports_list_changed(true);
496        assert!(state.is_tool_active("ctx_architecture"));
497        let active = state.active_categories();
498        let arch_count = active.iter().filter(|&&c| c == "arch").count();
499        assert_eq!(arch_count, 1);
500    }
501
502    // --- from_config: internal category is never user-activatable ---
503
504    #[test]
505    fn from_config_internal_category_not_parseable() {
506        assert!(ToolCategory::parse("internal").is_none());
507    }
508
509    // --- from_config: category aliases work ---
510
511    #[test]
512    fn from_config_alias_architecture_maps_to_arch() {
513        let cats = vec!["architecture".to_string()];
514        let mut state = DynamicToolState::from_config(&cats);
515        state.set_supports_list_changed(true);
516        assert!(state.is_tool_active("ctx_architecture"));
517    }
518
519    #[test]
520    fn from_config_alias_profiling_maps_to_debug() {
521        let cats = vec!["profiling".to_string()];
522        let mut state = DynamicToolState::from_config(&cats);
523        state.set_supports_list_changed(true);
524        assert!(state.is_tool_active("ctx_benchmark"));
525    }
526
527    #[test]
528    fn from_config_alias_semantic_maps_to_memory() {
529        let cats = vec!["semantic".to_string()];
530        let mut state = DynamicToolState::from_config(&cats);
531        state.set_supports_list_changed(true);
532        assert!(state.is_tool_active("ctx_artifacts"));
533    }
534
535    // --- from_config: subsequent load/unload still works ---
536
537    #[test]
538    fn from_config_then_load_additional_category() {
539        let cats = vec!["core".to_string()];
540        let mut state = DynamicToolState::from_config(&cats);
541        state.set_supports_list_changed(true);
542        assert!(!state.is_tool_active("ctx_architecture"));
543        state.load_category(ToolCategory::Arch);
544        assert!(state.is_tool_active("ctx_architecture"));
545    }
546
547    #[test]
548    fn from_config_then_unload_non_core_category() {
549        let cats = vec!["core".to_string(), "arch".to_string()];
550        let mut state = DynamicToolState::from_config(&cats);
551        state.set_supports_list_changed(true);
552        assert!(state.is_tool_active("ctx_architecture"));
553        state.unload_category(ToolCategory::Arch);
554        assert!(!state.is_tool_active("ctx_architecture"));
555    }
556
557    #[test]
558    fn from_config_cannot_unload_core() {
559        let cats = vec!["core".to_string(), "arch".to_string()];
560        let mut state = DynamicToolState::from_config(&cats);
561        assert!(!state.unload_category(ToolCategory::Core));
562    }
563
564    // --- from_config: without list_changed, all tools visible ---
565
566    #[test]
567    fn from_config_without_list_changed_shows_all() {
568        let cats = vec!["core".to_string()];
569        let state = DynamicToolState::from_config(&cats);
570        assert!(state.is_tool_active("ctx_architecture"));
571        assert!(state.is_tool_active("ctx_benchmark"));
572        assert!(!state.is_tool_active("ctx_metrics"));
573    }
574
575    #[test]
576    fn lazy_core_tools_survive_default_category_gate() {
577        // Regression for #575: every advertised lazy-core tool must stay
578        // active under the default category gate (Core + Session) when the
579        // client supports list_changed — otherwise Cursor silently loses
580        // tools like ctx_expand from the 13-tool core set.
581        let mut state = DynamicToolState::new();
582        state.set_supports_list_changed(true);
583        for name in crate::tool_defs::core_tool_names() {
584            assert!(
585                state.is_tool_active(name),
586                "{name} is in CORE_TOOL_NAMES but dropped by the default category gate"
587            );
588        }
589    }
590
591    #[test]
592    fn categorize_known_tools() {
593        assert_eq!(categorize_tool("ctx_read"), ToolCategory::Core);
594        assert_eq!(categorize_tool("ctx_graph"), ToolCategory::Core);
595        assert_eq!(categorize_tool("ctx_benchmark"), ToolCategory::Debug);
596        assert_eq!(categorize_tool("ctx_semantic_search"), ToolCategory::Core);
597        assert_eq!(categorize_tool("ctx_artifacts"), ToolCategory::Memory);
598        assert_eq!(categorize_tool("ctx_metrics"), ToolCategory::Internal);
599        assert_eq!(categorize_tool("ctx_workflow"), ToolCategory::Session);
600    }
601
602    #[test]
603    fn readonly_classification() {
604        assert!(is_readonly_tool("ctx_read"));
605        assert!(is_readonly_tool("ctx_search"));
606        assert!(is_readonly_tool("ctx_tree"));
607        assert!(is_readonly_tool("ctx_overview"));
608        assert!(is_readonly_tool("ctx_provider"));
609
610        assert!(!is_readonly_tool("ctx_edit"));
611        assert!(!is_readonly_tool("ctx_shell"));
612        assert!(!is_readonly_tool("ctx_compile"));
613        assert!(!is_readonly_tool("ctx_execute"));
614        assert!(!is_readonly_tool("ctx_cache"));
615    }
616
617    #[test]
618    fn plan_mode_tools_are_all_readonly() {
619        for tool in crate::core::editor_registry::plan_mode::plan_mode_tools() {
620            assert!(
621                is_readonly_tool(tool),
622                "{tool} is listed as plan mode tool but not marked readonly"
623            );
624        }
625    }
626}