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        // #509 search consolidation: one ctx_search entry, `action` picks the
142        // engine. Aliases stay callable for one release so nothing breaks.
143        "ctx_semantic_search" => Some(DeprecatedAlias {
144            replacement: "ctx_search",
145            hint: "ctx_search with action=\"semantic\" (query=…); reindex/find_related are actions too",
146        }),
147        "ctx_symbol" => Some(DeprecatedAlias {
148            replacement: "ctx_search",
149            hint: "ctx_search with action=\"symbol\" (name=…, optional file/kind)",
150        }),
151        _ => None,
152    }
153}
154
155/// Whether `name` is a deprecated alias hidden from `tools/list` (#509).
156#[must_use]
157pub fn is_deprecated_alias(name: &str) -> bool {
158    deprecated_alias(name).is_some()
159}
160
161/// The one-line deprecation notice prepended to a deprecated alias's output.
162/// Stable per tool (no timestamps/counters) so provider-side prompt caching
163/// stays byte-stable (#498).
164#[must_use]
165pub fn deprecation_notice(name: &str) -> Option<String> {
166    deprecated_alias(name).map(|d| {
167        format!(
168            "[DEPRECATED] {name} is superseded by {} — {}. This alias is hidden from \
169             tools/list and will be removed in a future release.",
170            d.replacement, d.hint
171        )
172    })
173}
174
175pub fn is_readonly_tool(name: &str) -> bool {
176    matches!(
177        name,
178        "ctx_read"
179            | "ctx_search"
180            | "ctx_tree"
181            | "ctx_overview"
182            | "ctx_plan"
183            | "ctx_metrics"
184            | "ctx_compress"
185            | "ctx_session"
186            | "ctx_knowledge"
187            | "ctx_graph"
188            | "ctx_retrieve"
189            | "ctx_provider"
190            | "ctx_multi_read"
191            | "ctx_smart_read"
192            | "ctx_delta"
193            | "ctx_outline"
194            | "ctx_context"
195            | "ctx_call"
196            | "ctx_url_read"
197            | "ctx_git_read"
198            | "ctx_architecture"
199            | "ctx_impact"
200            | "ctx_callgraph"
201            | "ctx_symbol"
202            | "ctx_routes"
203            | "ctx_smells"
204            | "ctx_index"
205            | "ctx_semantic_search"
206            | "ctx_explore"
207            | "ctx_artifacts"
208            | "ctx_cost"
209            | "ctx_gain"
210            | "ctx_heatmap"
211    )
212}
213
214#[derive(Debug)]
215pub struct DynamicToolState {
216    active_categories: HashSet<ToolCategory>,
217    supports_list_changed: bool,
218}
219
220impl Default for DynamicToolState {
221    fn default() -> Self {
222        Self::new()
223    }
224}
225
226impl DynamicToolState {
227    pub fn new() -> Self {
228        let mut active = HashSet::new();
229        active.insert(ToolCategory::Core);
230        active.insert(ToolCategory::Session);
231        Self {
232            active_categories: active,
233            supports_list_changed: false,
234        }
235    }
236
237    /// Creates state with categories from config (env var > config.toml > default).
238    pub fn from_config(categories: &[String]) -> Self {
239        let mut active = HashSet::new();
240        active.insert(ToolCategory::Core);
241        for cat_str in categories {
242            if let Some(cat) = ToolCategory::parse(cat_str) {
243                active.insert(cat);
244            }
245        }
246        Self {
247            active_categories: active,
248            supports_list_changed: false,
249        }
250    }
251
252    pub fn all_enabled() -> Self {
253        let mut active = HashSet::new();
254        active.insert(ToolCategory::Core);
255        active.insert(ToolCategory::Arch);
256        active.insert(ToolCategory::Debug);
257        active.insert(ToolCategory::Memory);
258        active.insert(ToolCategory::Metrics);
259        active.insert(ToolCategory::Session);
260        Self {
261            active_categories: active,
262            supports_list_changed: false,
263        }
264    }
265
266    pub fn set_supports_list_changed(&mut self, val: bool) {
267        self.supports_list_changed = val;
268    }
269
270    pub fn supports_list_changed(&self) -> bool {
271        self.supports_list_changed
272    }
273
274    pub fn load_category(&mut self, cat: ToolCategory) -> bool {
275        self.active_categories.insert(cat)
276    }
277
278    pub fn unload_category(&mut self, cat: ToolCategory) -> bool {
279        if cat == ToolCategory::Core || cat == ToolCategory::Internal {
280            return false;
281        }
282        self.active_categories.remove(&cat)
283    }
284
285    pub fn is_tool_active(&self, name: &str) -> bool {
286        let cat = categorize_tool(name);
287        if cat == ToolCategory::Internal {
288            return false;
289        }
290        if !self.supports_list_changed {
291            return true;
292        }
293        self.active_categories.contains(&cat)
294    }
295
296    pub fn active_categories(&self) -> Vec<&'static str> {
297        let mut cats: Vec<_> = self
298            .active_categories
299            .iter()
300            .map(ToolCategory::as_str)
301            .collect();
302        cats.sort_unstable();
303        cats
304    }
305
306    pub fn all_categories() -> Vec<&'static str> {
307        vec!["core", "arch", "debug", "memory", "metrics", "session"]
308    }
309}
310
311static GLOBAL: OnceLock<Mutex<DynamicToolState>> = OnceLock::new();
312
313pub fn global() -> &'static Mutex<DynamicToolState> {
314    GLOBAL.get_or_init(|| Mutex::new(DynamicToolState::new()))
315}
316
317pub fn init_all_enabled() {
318    let _ = GLOBAL.set(Mutex::new(DynamicToolState::all_enabled()));
319}
320
321/// Initializes the global state from user config (env var > config.toml > default).
322/// Call once during server startup after config is loaded.
323/// If the global was already initialized (e.g. by a concurrent `global()` call),
324/// applies the categories to the existing state instead.
325pub fn init_from_config(categories: &[String]) {
326    if GLOBAL
327        .set(Mutex::new(DynamicToolState::from_config(categories)))
328        .is_err()
329        && let Ok(mut state) = global().lock()
330    {
331        let desired = DynamicToolState::from_config(categories);
332        *state = desired;
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    #[test]
341    fn core_tools_always_active() {
342        let state = DynamicToolState::new();
343        assert!(state.is_tool_active("ctx_read"));
344        assert!(state.is_tool_active("ctx_search"));
345    }
346
347    #[test]
348    fn deprecated_alias_maps_read_cluster_to_ctx_read() {
349        // #509: only the folded read-cluster tools are deprecated; everything
350        // else (incl. the primary) returns None.
351        assert_eq!(
352            deprecated_alias("ctx_smart_read").unwrap().replacement,
353            "ctx_read"
354        );
355        assert_eq!(
356            deprecated_alias("ctx_multi_read").unwrap().replacement,
357            "ctx_read"
358        );
359        assert!(deprecated_alias("ctx_read").is_none());
360        assert!(deprecated_alias("ctx_search").is_none());
361        assert!(is_deprecated_alias("ctx_multi_read"));
362        assert!(!is_deprecated_alias("ctx_read"));
363
364        // #509 search consolidation: the folded search tools point at ctx_search.
365        assert_eq!(
366            deprecated_alias("ctx_semantic_search").unwrap().replacement,
367            "ctx_search"
368        );
369        assert_eq!(
370            deprecated_alias("ctx_symbol").unwrap().replacement,
371            "ctx_search"
372        );
373        assert!(is_deprecated_alias("ctx_symbol"));
374    }
375
376    #[test]
377    fn deprecation_notice_is_stable_and_names_replacement() {
378        // Stable text (no timestamps/counters) for cache-byte-stability (#498),
379        // and it must point at the primary so agents know where to go.
380        let notice = deprecation_notice("ctx_multi_read").unwrap();
381        assert!(notice.starts_with("[DEPRECATED] ctx_multi_read is superseded by ctx_read"));
382        assert!(notice.contains("paths="));
383        assert_eq!(notice, deprecation_notice("ctx_multi_read").unwrap());
384        assert!(deprecation_notice("ctx_read").is_none());
385    }
386
387    #[test]
388    fn dynamic_tools_filtered_when_list_changed() {
389        let mut state = DynamicToolState::new();
390        state.set_supports_list_changed(true);
391        assert!(!state.is_tool_active("ctx_benchmark"));
392        assert!(!state.is_tool_active("ctx_architecture"));
393        assert!(state.is_tool_active("ctx_read"));
394    }
395
396    #[test]
397    fn load_category_enables_tools() {
398        let mut state = DynamicToolState::new();
399        state.set_supports_list_changed(true);
400        assert!(!state.is_tool_active("ctx_architecture"));
401        state.load_category(ToolCategory::Arch);
402        assert!(state.is_tool_active("ctx_architecture"));
403    }
404
405    #[test]
406    fn cannot_unload_core() {
407        let mut state = DynamicToolState::new();
408        assert!(!state.unload_category(ToolCategory::Core));
409    }
410
411    #[test]
412    fn all_tools_visible_without_list_changed() {
413        let state = DynamicToolState::new();
414        assert!(state.is_tool_active("ctx_graph"));
415        assert!(!state.is_tool_active("ctx_metrics")); // Internal tools never active
416    }
417
418    #[test]
419    fn internal_tools_never_active() {
420        let state = DynamicToolState::all_enabled();
421        assert!(!state.is_tool_active("ctx_metrics"));
422        assert!(!state.is_tool_active("ctx_cost"));
423        assert!(!state.is_tool_active("ctx_discover_tools"));
424        assert!(!state.is_tool_active("ctx_dedup"));
425    }
426
427    // --- from_config: basic scenarios ---
428
429    #[test]
430    fn from_config_core_arch_memory() {
431        let cats = vec!["core".to_string(), "arch".to_string(), "memory".to_string()];
432        let mut state = DynamicToolState::from_config(&cats);
433        state.set_supports_list_changed(true);
434        assert!(state.is_tool_active("ctx_read"));
435        assert!(state.is_tool_active("ctx_architecture"));
436        assert!(state.is_tool_active("ctx_artifacts"));
437        assert!(!state.is_tool_active("ctx_benchmark"));
438        assert!(!state.is_tool_active("ctx_fill"));
439    }
440
441    #[test]
442    fn from_config_empty_still_has_core() {
443        let mut state = DynamicToolState::from_config(&[]);
444        state.set_supports_list_changed(true);
445        assert!(state.is_tool_active("ctx_read"));
446        assert!(!state.is_tool_active("ctx_architecture"));
447        assert!(!state.is_tool_active("ctx_benchmark"));
448        assert!(!state.is_tool_active("ctx_artifacts"));
449    }
450
451    // --- from_config: all categories ---
452
453    #[test]
454    fn from_config_all_categories_enables_everything_except_internal() {
455        let cats = vec![
456            "core".to_string(),
457            "arch".to_string(),
458            "debug".to_string(),
459            "memory".to_string(),
460            "metrics".to_string(),
461            "session".to_string(),
462        ];
463        let mut state = DynamicToolState::from_config(&cats);
464        state.set_supports_list_changed(true);
465        assert!(state.is_tool_active("ctx_read"));
466        assert!(state.is_tool_active("ctx_architecture"));
467        assert!(state.is_tool_active("ctx_benchmark"));
468        assert!(state.is_tool_active("ctx_semantic_search"));
469        assert!(state.is_tool_active("ctx_fill"));
470        assert!(state.is_tool_active("ctx_workflow"));
471        assert!(!state.is_tool_active("ctx_metrics"));
472    }
473
474    // --- from_config: single category ---
475
476    #[test]
477    fn from_config_only_debug() {
478        let cats = vec!["debug".to_string()];
479        let mut state = DynamicToolState::from_config(&cats);
480        state.set_supports_list_changed(true);
481        assert!(state.is_tool_active("ctx_read"));
482        assert!(state.is_tool_active("ctx_benchmark"));
483        assert!(!state.is_tool_active("ctx_architecture"));
484        assert!(!state.is_tool_active("ctx_workflow"));
485    }
486
487    // --- from_config: invalid categories are silently ignored ---
488
489    #[test]
490    fn from_config_ignores_unknown_categories() {
491        let cats = vec![
492            "core".to_string(),
493            "nonexistent".to_string(),
494            "foobar".to_string(),
495        ];
496        let mut state = DynamicToolState::from_config(&cats);
497        state.set_supports_list_changed(true);
498        assert!(state.is_tool_active("ctx_read"));
499        assert!(!state.is_tool_active("ctx_architecture"));
500    }
501
502    #[test]
503    fn from_config_only_invalid_still_has_core() {
504        let cats = vec!["invalid".to_string(), "bogus".to_string()];
505        let mut state = DynamicToolState::from_config(&cats);
506        state.set_supports_list_changed(true);
507        assert!(state.is_tool_active("ctx_read"));
508        assert!(!state.is_tool_active("ctx_benchmark"));
509    }
510
511    // --- from_config: duplicate categories are idempotent ---
512
513    #[test]
514    fn from_config_duplicates_are_harmless() {
515        let cats = vec!["arch".to_string(), "arch".to_string(), "arch".to_string()];
516        let mut state = DynamicToolState::from_config(&cats);
517        state.set_supports_list_changed(true);
518        assert!(state.is_tool_active("ctx_architecture"));
519        let active = state.active_categories();
520        let arch_count = active.iter().filter(|&&c| c == "arch").count();
521        assert_eq!(arch_count, 1);
522    }
523
524    // --- from_config: internal category is never user-activatable ---
525
526    #[test]
527    fn from_config_internal_category_not_parseable() {
528        assert!(ToolCategory::parse("internal").is_none());
529    }
530
531    // --- from_config: category aliases work ---
532
533    #[test]
534    fn from_config_alias_architecture_maps_to_arch() {
535        let cats = vec!["architecture".to_string()];
536        let mut state = DynamicToolState::from_config(&cats);
537        state.set_supports_list_changed(true);
538        assert!(state.is_tool_active("ctx_architecture"));
539    }
540
541    #[test]
542    fn from_config_alias_profiling_maps_to_debug() {
543        let cats = vec!["profiling".to_string()];
544        let mut state = DynamicToolState::from_config(&cats);
545        state.set_supports_list_changed(true);
546        assert!(state.is_tool_active("ctx_benchmark"));
547    }
548
549    #[test]
550    fn from_config_alias_semantic_maps_to_memory() {
551        let cats = vec!["semantic".to_string()];
552        let mut state = DynamicToolState::from_config(&cats);
553        state.set_supports_list_changed(true);
554        assert!(state.is_tool_active("ctx_artifacts"));
555    }
556
557    // --- from_config: subsequent load/unload still works ---
558
559    #[test]
560    fn from_config_then_load_additional_category() {
561        let cats = vec!["core".to_string()];
562        let mut state = DynamicToolState::from_config(&cats);
563        state.set_supports_list_changed(true);
564        assert!(!state.is_tool_active("ctx_architecture"));
565        state.load_category(ToolCategory::Arch);
566        assert!(state.is_tool_active("ctx_architecture"));
567    }
568
569    #[test]
570    fn from_config_then_unload_non_core_category() {
571        let cats = vec!["core".to_string(), "arch".to_string()];
572        let mut state = DynamicToolState::from_config(&cats);
573        state.set_supports_list_changed(true);
574        assert!(state.is_tool_active("ctx_architecture"));
575        state.unload_category(ToolCategory::Arch);
576        assert!(!state.is_tool_active("ctx_architecture"));
577    }
578
579    #[test]
580    fn from_config_cannot_unload_core() {
581        let cats = vec!["core".to_string(), "arch".to_string()];
582        let mut state = DynamicToolState::from_config(&cats);
583        assert!(!state.unload_category(ToolCategory::Core));
584    }
585
586    // --- from_config: without list_changed, all tools visible ---
587
588    #[test]
589    fn from_config_without_list_changed_shows_all() {
590        let cats = vec!["core".to_string()];
591        let state = DynamicToolState::from_config(&cats);
592        assert!(state.is_tool_active("ctx_architecture"));
593        assert!(state.is_tool_active("ctx_benchmark"));
594        assert!(!state.is_tool_active("ctx_metrics"));
595    }
596
597    #[test]
598    fn lazy_core_tools_survive_default_category_gate() {
599        // Regression for #575: every advertised lazy-core tool must stay
600        // active under the default category gate (Core + Session) when the
601        // client supports list_changed — otherwise Cursor silently loses
602        // tools like ctx_expand from the 13-tool core set.
603        let mut state = DynamicToolState::new();
604        state.set_supports_list_changed(true);
605        for name in crate::tool_defs::core_tool_names() {
606            assert!(
607                state.is_tool_active(name),
608                "{name} is in CORE_TOOL_NAMES but dropped by the default category gate"
609            );
610        }
611    }
612
613    #[test]
614    fn categorize_known_tools() {
615        assert_eq!(categorize_tool("ctx_read"), ToolCategory::Core);
616        assert_eq!(categorize_tool("ctx_graph"), ToolCategory::Core);
617        assert_eq!(categorize_tool("ctx_benchmark"), ToolCategory::Debug);
618        assert_eq!(categorize_tool("ctx_semantic_search"), ToolCategory::Core);
619        assert_eq!(categorize_tool("ctx_artifacts"), ToolCategory::Memory);
620        assert_eq!(categorize_tool("ctx_metrics"), ToolCategory::Internal);
621        assert_eq!(categorize_tool("ctx_workflow"), ToolCategory::Session);
622    }
623
624    #[test]
625    fn readonly_classification() {
626        assert!(is_readonly_tool("ctx_read"));
627        assert!(is_readonly_tool("ctx_search"));
628        assert!(is_readonly_tool("ctx_tree"));
629        assert!(is_readonly_tool("ctx_overview"));
630        assert!(is_readonly_tool("ctx_provider"));
631
632        assert!(!is_readonly_tool("ctx_edit"));
633        assert!(!is_readonly_tool("ctx_shell"));
634        assert!(!is_readonly_tool("ctx_compile"));
635        assert!(!is_readonly_tool("ctx_execute"));
636        assert!(!is_readonly_tool("ctx_cache"));
637    }
638
639    #[test]
640    fn plan_mode_tools_are_all_readonly() {
641        for tool in crate::core::editor_registry::plan_mode::plan_mode_tools() {
642            assert!(
643                is_readonly_tool(tool),
644                "{tool} is listed as plan mode tool but not marked readonly"
645            );
646        }
647    }
648}