Skip to main content

lean_ctx/tools/registered/
ctx_tree.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::core::ocla::cache_types::{CacheKeyBuilder, DirectoryWalkKey};
6use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_bool, get_int};
7use crate::tool_defs::tool_def;
8
9pub struct CtxTreeTool;
10
11impl McpTool for CtxTreeTool {
12    fn name(&self) -> &'static str {
13        "ctx_tree"
14    }
15
16    fn tool_def(&self) -> Tool {
17        tool_def(
18            "ctx_tree",
19            "Directory tree with file counts per directory. depth=N (default 3);\n\
20             show_hidden for dotfiles; paths for multi-root.\n\
21             respect_gitignore filters ignored files (default true).\n\
22             WORKFLOW: lightweight orientation before ctx_repomap or ctx_compose.",
23            json!({
24                "type": "object",
25                "properties": {
26                    "path": { "type": "string", "description": "Dir" },
27                    "paths": {
28                        "type": "array",
29                        "items": { "type": "string" },
30                        "description": "Multi-root (alternative to path)"
31                    },
32                    "depth": { "type": "integer", "description": "Max depth" },
33                    "show_hidden": { "type": "boolean", "description": "Include dotfiles" },
34                    "respect_gitignore": { "type": "boolean", "description": "Filter ignored" }
35                }
36            }),
37        )
38    }
39
40    fn handle(
41        &self,
42        args: &Map<String, Value>,
43        ctx: &ToolContext,
44    ) -> Result<ToolOutput, ErrorData> {
45        let resolved = crate::server::multi_path::resolve_tool_paths(args, ctx)
46            .map_err(|e| ErrorData::invalid_params(format!("ERROR: {e}"), None))?;
47        let depth = (get_int(args, "depth").unwrap_or(3) as usize).min(10);
48        let show_hidden = get_bool(args, "show_hidden").unwrap_or(false);
49        let respect_gitignore = get_bool(args, "respect_gitignore").unwrap_or(true);
50
51        let mut combined = String::new();
52        let mut total_original = 0;
53
54        for root in &resolved.roots {
55            let root_clone = root.clone();
56            let Ok((body, raw_tokens)) =
57                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
58                    cached_or_walk(&root_clone, depth, show_hidden, respect_gitignore)
59                }))
60            else {
61                combined.push_str(&format!("── {root} ──\nERROR: internal panic\n\n"));
62                continue;
63            };
64
65            if body.starts_with("ERROR:") {
66                combined.push_str(&format!("── {root} ──\n{body}\n\n"));
67                continue;
68            }
69
70            combined.push_str(&format!("── {root} ──\n{body}\n\n"));
71            total_original += raw_tokens;
72        }
73
74        let total_sent = crate::core::tokens::count_tokens(&combined);
75        let final_out = append_combined_footer(&combined, total_original, total_sent);
76        let saved = total_original.saturating_sub(total_sent);
77
78        Ok(ToolOutput {
79            text: final_out,
80            original_tokens: total_original,
81            saved_tokens: saved,
82            mode: None,
83            path: None,
84            changed: false,
85            shell_outcome: None,
86            content_blocks: None,
87        })
88    }
89}
90
91fn append_combined_footer(body: &str, raw_tokens: usize, sent_tokens: usize) -> String {
92    crate::core::protocol::append_savings(body, raw_tokens, sent_tokens)
93}
94
95fn directory_mtime_ns(path: &std::path::Path) -> Option<u128> {
96    std::fs::metadata(path)
97        .ok()?
98        .modified()
99        .ok()?
100        .duration_since(std::time::UNIX_EPOCH)
101        .ok()
102        .map(|duration| duration.as_nanos())
103}
104
105fn cached_or_walk(
106    path: &str,
107    depth: usize,
108    show_hidden: bool,
109    respect_gitignore: bool,
110) -> (String, usize) {
111    // GH #1461: The sandboxed LaunchAgent daemon cannot stat paths under
112    // ~/Documents, ~/Desktop, ~/Downloads (TCC). Bail early so the caller
113    // can fall through to a non-sandboxed process (CLI local or MCP server).
114    if crate::core::pathutil::process_is_tcc_standalone()
115        && crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
116    {
117        return (
118            format!("ERROR:TCC_RESTRICTED: daemon cannot access {path} (sandboxed)"),
119            0,
120        );
121    }
122    let builder = DirectoryWalkKey {
123        path: crate::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(path))
124            .to_string_lossy()
125            .into_owned(),
126        depth,
127        gitignore: respect_gitignore,
128        dir_mtime_ns: directory_mtime_ns(&crate::core::pathutil::safe_canonicalize_or_self(
129            std::path::Path::new(path),
130        ))
131        .unwrap_or_default(),
132        selector: format!("tree:depth={depth}"),
133    };
134    let key = builder.cache_key();
135    if let Some(entry) =
136        crate::core::ocla::cache_delivery::check(&key, &builder.validator(), "ctx_tree")
137    {
138        let stub = crate::core::ocla::cache_delivery::stub(&entry, "directory tree");
139        return (stub, entry.token_count as usize);
140    }
141    let (result, original) =
142        crate::tools::ctx_tree::handle(path, depth, show_hidden, respect_gitignore);
143    if !result.starts_with("ERROR:") {
144        crate::core::ocla::cache_delivery::record(
145            key,
146            crate::core::ocla::cache_types::DeliveryKind::DirectoryWalk,
147            builder.validator(),
148            Some(builder.path),
149            &result,
150            "ctx_tree",
151        );
152    }
153    (result, original)
154}
155
156#[cfg(test)]
157mod tests {
158    use super::{append_combined_footer, cached_or_walk};
159
160    #[test]
161    fn tree_adapter_appends_one_footer_after_combining_roots() {
162        let body = "── first ──\nfirst.rs\n\n── second ──\nsecond.rs\n";
163        let raw_tokens = 100;
164        let sent_tokens = crate::core::tokens::count_tokens(body);
165        // Footer is appended by append_combined_footer via protocol::append_savings
166
167        let output = append_combined_footer(body, raw_tokens, sent_tokens);
168
169        // Check exactly one savings line exists
170        let savings_lines = output
171            .lines()
172            .filter(|l| l.contains("[lean-ctx") || l.contains("savings:") || l.contains("saved"))
173            .count();
174        assert!(savings_lines <= 2, "too many footer lines: {savings_lines}");
175    }
176
177    #[test]
178    fn tree_adapter_records_then_serves_a_cross_agent_reference() {
179        let directory = tempfile::tempdir().unwrap();
180        std::fs::write(directory.path().join("cached.rs"), "fn cached() {}\n").unwrap();
181        let path = directory.path().to_string_lossy();
182
183        let (first_result, _first_orig) = cached_or_walk(&path, 3, false, true);
184        assert!(first_result.contains("cached.rs"));
185        let (second_result, _second_orig) = cached_or_walk(&path, 3, false, true);
186        assert!(second_result.contains("[cross-agent"), "{}", second_result);
187    }
188}