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 = resolved
52            .note
53            .as_ref()
54            .map(|note| format!("{note}\n"))
55            .unwrap_or_default();
56        let mut total_original = 0;
57
58        for root in &resolved.roots {
59            let root_clone = root.clone();
60            let Ok((body, raw_tokens)) =
61                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
62                    cached_or_walk(&root_clone, depth, show_hidden, respect_gitignore)
63                }))
64            else {
65                combined.push_str(&format!("── {root} ──\nERROR: internal panic\n\n"));
66                continue;
67            };
68
69            if body.starts_with("ERROR:") {
70                combined.push_str(&format!("── {root} ──\n{body}\n\n"));
71                continue;
72            }
73
74            combined.push_str(&format!("── {root} ──\n{body}\n\n"));
75            total_original += raw_tokens;
76        }
77
78        let total_sent = crate::core::tokens::count_tokens(&combined);
79        let final_out = append_combined_footer(&combined, total_original, total_sent);
80        let saved = total_original.saturating_sub(total_sent);
81
82        Ok(ToolOutput {
83            text: final_out,
84            original_tokens: total_original,
85            saved_tokens: saved,
86            mode: None,
87            path: None,
88            changed: false,
89            shell_outcome: None,
90            content_blocks: None,
91        })
92    }
93}
94
95fn append_combined_footer(body: &str, raw_tokens: usize, sent_tokens: usize) -> String {
96    crate::core::protocol::append_savings(body, raw_tokens, sent_tokens)
97}
98
99fn directory_mtime_ns(path: &std::path::Path) -> Option<u128> {
100    std::fs::metadata(path)
101        .ok()?
102        .modified()
103        .ok()?
104        .duration_since(std::time::UNIX_EPOCH)
105        .ok()
106        .map(|duration| duration.as_nanos())
107}
108
109fn cached_or_walk(
110    path: &str,
111    depth: usize,
112    show_hidden: bool,
113    respect_gitignore: bool,
114) -> (String, usize) {
115    // GH #1461: The sandboxed LaunchAgent daemon cannot stat paths under
116    // ~/Documents, ~/Desktop, ~/Downloads (TCC). Bail early so the caller
117    // can fall through to a non-sandboxed process (CLI local or MCP server).
118    if crate::core::pathutil::process_is_tcc_standalone()
119        && crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
120    {
121        return (
122            format!("ERROR:TCC_RESTRICTED: daemon cannot access {path} (sandboxed)"),
123            0,
124        );
125    }
126    let builder = DirectoryWalkKey {
127        path: crate::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(path))
128            .to_string_lossy()
129            .into_owned(),
130        depth,
131        gitignore: respect_gitignore,
132        dir_mtime_ns: directory_mtime_ns(&crate::core::pathutil::safe_canonicalize_or_self(
133            std::path::Path::new(path),
134        ))
135        .unwrap_or_default(),
136        selector: format!("tree:depth={depth}"),
137    };
138    let key = builder.cache_key();
139    if let Some(entry) =
140        crate::core::ocla::cache_delivery::check(&key, &builder.validator(), "ctx_tree")
141    {
142        let stub = crate::core::ocla::cache_delivery::stub(&entry, "directory tree");
143        return (stub, entry.token_count as usize);
144    }
145    let (result, original) =
146        crate::tools::ctx_tree::handle(path, depth, show_hidden, respect_gitignore);
147    if !result.starts_with("ERROR:") {
148        crate::core::ocla::cache_delivery::record(
149            key,
150            crate::core::ocla::cache_types::DeliveryKind::DirectoryWalk,
151            builder.validator(),
152            Some(builder.path),
153            &result,
154            "ctx_tree",
155        );
156    }
157    (result, original)
158}
159
160#[cfg(test)]
161mod tests {
162    use super::{append_combined_footer, cached_or_walk};
163
164    #[test]
165    fn tree_adapter_appends_one_footer_after_combining_roots() {
166        let body = "── first ──\nfirst.rs\n\n── second ──\nsecond.rs\n";
167        let raw_tokens = 100;
168        let sent_tokens = crate::core::tokens::count_tokens(body);
169        // Footer is appended by append_combined_footer via protocol::append_savings
170
171        let output = append_combined_footer(body, raw_tokens, sent_tokens);
172
173        // Check exactly one savings line exists
174        let savings_lines = output
175            .lines()
176            .filter(|l| l.contains("[lean-ctx") || l.contains("savings:") || l.contains("saved"))
177            .count();
178        assert!(savings_lines <= 2, "too many footer lines: {savings_lines}");
179    }
180
181    #[test]
182    fn tree_adapter_records_then_serves_a_cross_agent_reference() {
183        let directory = tempfile::tempdir().unwrap();
184        std::fs::write(directory.path().join("cached.rs"), "fn cached() {}\n").unwrap();
185        let path = directory.path().to_string_lossy();
186
187        let (first_result, _first_orig) = cached_or_walk(&path, 3, false, true);
188        assert!(first_result.contains("cached.rs"));
189        let (second_result, _second_orig) = cached_or_walk(&path, 3, false, true);
190        assert!(second_result.contains("[cross-agent"), "{}", second_result);
191    }
192}