Skip to main content

lean_ctx/server/
mod.rs

1pub mod background_shell;
2pub mod bounded_lock;
3pub mod bypass_hint;
4pub mod compaction_sync;
5pub mod context_gate;
6mod dispatch;
7pub(crate) use dispatch::canonicalize_arg_aliases;
8pub mod dynamic_tools;
9pub mod elicitation;
10pub(crate) mod execute;
11mod file_resource;
12pub mod helpers;
13pub(crate) mod mcp_idle;
14pub mod multi_path;
15pub(crate) mod native_receipts;
16pub mod notifications;
17pub mod permission_inheritance;
18pub mod policy_guard;
19pub mod predictive_preload;
20pub mod progress;
21pub mod prompts;
22pub mod reference_store;
23pub mod registry;
24pub mod resources;
25pub mod role_guard;
26pub mod roots;
27pub mod schema_hook;
28use roots::has_project_marker;
29pub mod tool_trait;
30pub mod tool_visibility;
31pub mod tools_config_watch;
32pub(crate) mod walk_hint;
33
34use futures::FutureExt;
35use rmcp::ErrorData;
36use rmcp::handler::server::ServerHandler;
37use rmcp::model::{
38    CallToolRequestParams, CallToolResult, ContentBlock, Implementation, InitializeRequestParams,
39    InitializeResult, ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerInfo,
40};
41use rmcp::service::{RequestContext, RoleServer};
42use std::path::PathBuf;
43
44use crate::tools::{CrpMode, LeanCtxServer};
45mod call_tool;
46mod post_dispatch;
47mod post_process;
48mod server_handler;
49
50pub fn build_instructions_for_test(crp_mode: CrpMode) -> String {
51    crate::instructions::build_instructions_for_test(crp_mode)
52}
53
54pub fn build_claude_code_instructions_for_test() -> String {
55    crate::instructions::claude_code_instructions()
56}
57
58/// Deterministic STATIC Claude Code instructions (cold first-contact, no dynamic
59/// session/knowledge/gotcha payload) for the char-budget benchmark.
60pub fn build_claude_code_static_instructions_for_test() -> String {
61    crate::instructions::claude_code_static_instructions_for_test()
62}
63
64fn git_toplevel_from(dir: &std::path::Path) -> Option<String> {
65    std::process::Command::new("git")
66        .args(["rev-parse", "--show-toplevel"])
67        .current_dir(dir)
68        .stdout(std::process::Stdio::piped())
69        .stderr(std::process::Stdio::null())
70        .output()
71        .ok()
72        .and_then(|o| {
73            if o.status.success() {
74                String::from_utf8(o.stdout)
75                    .ok()
76                    .map(|s| s.trim().to_string())
77            } else {
78                None
79            }
80        })
81}
82
83pub fn derive_project_root_from_cwd() -> Option<String> {
84    let cwd = std::env::current_dir().ok()?;
85    let canonical = crate::core::pathutil::safe_canonicalize_or_self(&cwd);
86
87    if crate::core::pathutil::is_broad_or_unsafe_root(&canonical) {
88        return git_toplevel_from(&canonical);
89    }
90
91    if has_project_marker(&canonical) {
92        return Some(canonical.to_string_lossy().to_string());
93    }
94
95    if let Some(git_root) = git_toplevel_from(&canonical) {
96        return Some(git_root);
97    }
98
99    if let Some(root) = detect_multi_root_workspace(&canonical) {
100        return Some(root);
101    }
102
103    // Fallback: use CWD as project root if it's a specific, safe directory.
104    // This ensures bare directories (no .git, no markers) still work.
105    // Guard: reject home dir, filesystem root, and agent sandbox dirs.
106    if !crate::core::pathutil::is_broad_or_unsafe_root(&canonical) {
107        tracing::info!(
108            "No project markers found — using CWD as project root: {}",
109            canonical.display()
110        );
111        return Some(canonical.to_string_lossy().to_string());
112    }
113
114    None
115}
116
117// Delegated to crate::core::pathutil::is_broad_or_unsafe_root
118#[cfg(test)]
119use crate::core::pathutil::is_broad_or_unsafe_root;
120
121/// Detect a multi-root workspace: a directory that has no project markers
122/// itself, but contains child directories that do. In this case, use the
123/// parent as jail root and auto-allow all child projects via LEAN_CTX_ALLOW_PATH.
124fn detect_multi_root_workspace(dir: &std::path::Path) -> Option<String> {
125    // Never enumerate broad roots or macOS TCC-protected dirs: read_dir there
126    // can scan an entire user profile or trigger a macOS privacy prompt.
127    if crate::core::pathutil::is_broad_or_unsafe_root(dir)
128        || crate::core::pathutil::is_tcc_sensitive_home_dir(dir)
129    {
130        return None;
131    }
132    let entries = std::fs::read_dir(dir).ok()?;
133    let mut child_projects: Vec<String> = Vec::new();
134
135    for entry in entries.flatten() {
136        let path = entry.path();
137        if path.is_dir() && has_project_marker(&path) {
138            let canonical = crate::core::pathutil::safe_canonicalize_or_self(&path);
139            child_projects.push(canonical.to_string_lossy().to_string());
140        }
141    }
142
143    if child_projects.len() >= 2 {
144        crate::core::runtime_flags::add_allow_paths(
145            child_projects.iter().map(PathBuf::from).collect(),
146        );
147        tracing::info!(
148            "Multi-root workspace detected at {}: auto-allowing {} child projects",
149            dir.display(),
150            child_projects.len()
151        );
152        return Some(dir.to_string_lossy().to_string());
153    }
154
155    None
156}
157
158pub fn tool_descriptions_for_test() -> Vec<(String, String)> {
159    crate::server::registry::build_registry()
160        .tool_defs()
161        .into_iter()
162        .map(|t| {
163            (
164                t.name.to_string(),
165                t.description.as_deref().unwrap_or("").to_string(),
166            )
167        })
168        .collect()
169}
170
171pub fn tool_schemas_json_for_test() -> String {
172    crate::server::registry::build_registry()
173        .tool_defs()
174        .iter()
175        .map(|t| {
176            format!(
177                "{}: {}",
178                t.name,
179                serde_json::to_string(&t.input_schema).unwrap_or_default()
180            )
181        })
182        .collect::<Vec<_>>()
183        .join("\n")
184}
185
186/// Tools that always pass through the workflow gate regardless of state.
187/// Read-only tools should never be blocked — agents need them for context
188/// recovery after crashes or session transitions.
189pub const WORKFLOW_PASSTHROUGH_TOOLS: &[&str] = &[
190    "ctx",
191    "ctx_workflow",
192    "ctx_read",
193    "ctx_multi_read",
194    "ctx_smart_read",
195    "ctx_search",
196    "ctx_tree",
197    "ctx_session",
198    "ctx_ledger",
199];
200
201/// A workflow is stale if it hasn't been updated in 30 minutes.
202/// This prevents dead workflows from blocking tools across sessions.
203pub fn is_workflow_stale(run: &crate::core::workflow::types::WorkflowRun) -> bool {
204    let elapsed = chrono::Utc::now()
205        .signed_duration_since(run.updated_at)
206        .num_minutes();
207    elapsed > 30
208}
209
210/// Whether the MCP client has lean-ctx hooks installed that compress native
211/// Read/Shell/Grep/Glob transparently. Used by `list_tools` to decide whether
212/// the shadow-only surface (just `ctx_call`) is safe.
213fn is_client_hook_covered(client_name: &str) -> bool {
214    crate::core::home::resolve_home_dir()
215        .is_some_and(|home| crate::core::rules_channel::client_hook_covered(client_name, &home))
216}
217
218fn is_shell_tool_name(name: &str) -> bool {
219    matches!(name, "ctx_shell" | "ctx_execute")
220}
221
222fn extract_file_read_from_shell(cmd: &str) -> Option<String> {
223    let trimmed = cmd.trim();
224    let parts: Vec<&str> = trimmed.split_whitespace().collect();
225    if parts.len() < 2 {
226        return None;
227    }
228    let bin = parts[0].rsplit('/').next().unwrap_or(parts[0]);
229    match bin {
230        "cat" | "head" | "tail" | "less" | "more" | "bat" | "batcat" => {
231            let file_arg = parts.iter().skip(1).find(|a| !a.starts_with('-'))?;
232            Some(file_arg.to_string())
233        }
234        _ => None,
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn project_markers_detected() {
244        let tmp = tempfile::tempdir().unwrap();
245        let root = tmp.path().join("myproject");
246        std::fs::create_dir_all(&root).unwrap();
247        assert!(!has_project_marker(&root));
248
249        std::fs::create_dir(root.join(".git")).unwrap();
250        assert!(has_project_marker(&root));
251    }
252
253    #[test]
254    fn home_dir_detected_as_broad_root() {
255        if let Some(home) = dirs::home_dir() {
256            assert!(is_broad_or_unsafe_root(&home));
257        }
258    }
259
260    #[test]
261    fn agent_dirs_detected() {
262        let claude = std::path::PathBuf::from("/home/user/.claude");
263        assert!(is_broad_or_unsafe_root(&claude));
264        let codex = std::path::PathBuf::from("/home/user/.codex");
265        assert!(is_broad_or_unsafe_root(&codex));
266        let project = std::path::PathBuf::from("/home/user/projects/myapp");
267        assert!(!is_broad_or_unsafe_root(&project));
268    }
269
270    #[test]
271    fn test_unified_tool_count() {
272        let tools = crate::tool_defs::unified_tool_defs();
273        assert_eq!(tools.len(), 5, "Expected 5 unified tools");
274    }
275
276    #[test]
277    fn test_granular_tool_count() {
278        let tools = crate::tool_defs::granular_tool_defs();
279        assert!(tools.len() >= 25, "Expected at least 25 granular tools");
280    }
281
282    #[test]
283    fn production_server_always_has_registry() {
284        // The list_tools fallback that serves static defs when `registry` is None
285        // must stay unreachable in production: every public constructor funnels
286        // through new_with_startup, which sets registry = Some. Lock that invariant
287        // so the advertised tool set can never silently drift from what dispatch
288        // (which requires the registry) can actually execute.
289        let server = crate::tools::create_server();
290        assert!(
291            server.registry.is_some(),
292            "production server must carry a tool registry"
293        );
294    }
295
296    #[test]
297    fn disabled_tools_filters_list() {
298        let all = crate::tool_defs::granular_tool_defs();
299        let total = all.len();
300        // `ctx_agent` is retained as a direct compatibility path but is no
301        // longer part of the advertised granular surface. Exercise filtering
302        // with one actual public tool instead of treating a hidden alias as
303        // visible inventory.
304        let disabled = ["ctx_graph".to_string()];
305        let filtered: Vec<_> = all
306            .into_iter()
307            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
308            .collect();
309        assert_eq!(filtered.len(), total - 1);
310        assert!(!filtered.iter().any(|t| t.name.as_ref() == "ctx_graph"));
311        assert!(!filtered.iter().any(|t| t.name.as_ref() == "ctx_agent"));
312    }
313
314    #[test]
315    fn empty_disabled_tools_returns_all() {
316        let all = crate::tool_defs::granular_tool_defs();
317        let total = all.len();
318        let disabled: Vec<String> = vec![];
319        let filtered: Vec<_> = all
320            .into_iter()
321            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
322            .collect();
323        assert_eq!(filtered.len(), total);
324    }
325
326    #[test]
327    fn misspelled_disabled_tool_is_silently_ignored() {
328        let all = crate::tool_defs::granular_tool_defs();
329        let total = all.len();
330        let disabled = ["ctx_nonexistent_tool".to_string()];
331        let filtered: Vec<_> = all
332            .into_iter()
333            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
334            .collect();
335        assert_eq!(filtered.len(), total);
336    }
337
338    #[test]
339    fn detect_multi_root_workspace_with_child_projects() {
340        // detect_multi_root_workspace SETS `LEAN_CTX_ALLOW_PATH` as a side
341        // effect (auto-allowing the child projects) — hold the global env
342        // lock so a parallel jail test never observes the transient value
343        // (the pre-existing full-suite flake reported in #695).
344        let _guard = crate::core::data_dir::test_env_lock();
345        let tmp = tempfile::tempdir().unwrap();
346        let workspace = tmp.path().join("workspace");
347        std::fs::create_dir_all(&workspace).unwrap();
348
349        let proj_a = workspace.join("project-a");
350        let proj_b = workspace.join("project-b");
351        std::fs::create_dir_all(proj_a.join(".git")).unwrap();
352        std::fs::create_dir_all(&proj_b).unwrap();
353        std::fs::write(proj_b.join("package.json"), "{}").unwrap();
354
355        let result = detect_multi_root_workspace(&workspace);
356        assert!(
357            result.is_some(),
358            "should detect workspace with 2 child projects"
359        );
360
361        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
362    }
363
364    #[test]
365    fn detect_multi_root_workspace_returns_none_for_single_project() {
366        let tmp = tempfile::tempdir().unwrap();
367        let workspace = tmp.path().join("workspace");
368        std::fs::create_dir_all(&workspace).unwrap();
369
370        let proj_a = workspace.join("project-a");
371        std::fs::create_dir_all(proj_a.join(".git")).unwrap();
372
373        let result = detect_multi_root_workspace(&workspace);
374        assert!(
375            result.is_none(),
376            "should not detect workspace with only 1 child project"
377        );
378    }
379
380    #[test]
381    fn is_broad_or_unsafe_root_rejects_home() {
382        if let Some(home) = dirs::home_dir() {
383            assert!(is_broad_or_unsafe_root(&home));
384        }
385    }
386
387    #[test]
388    fn is_broad_or_unsafe_root_rejects_filesystem_root() {
389        assert!(is_broad_or_unsafe_root(std::path::Path::new("/")));
390    }
391
392    #[test]
393    fn is_broad_or_unsafe_root_rejects_agent_dirs() {
394        assert!(is_broad_or_unsafe_root(std::path::Path::new(
395            "/home/user/.claude"
396        )));
397        assert!(is_broad_or_unsafe_root(std::path::Path::new(
398            "/home/user/.codex"
399        )));
400    }
401
402    #[test]
403    fn is_broad_or_unsafe_root_allows_project_subdir() {
404        let tmp = tempfile::tempdir().unwrap();
405        let subdir = tmp.path().join("my-project");
406        std::fs::create_dir_all(&subdir).unwrap();
407        assert!(!is_broad_or_unsafe_root(&subdir));
408    }
409
410    #[test]
411    fn is_broad_or_unsafe_root_allows_tmp_subdirs() {
412        assert!(!is_broad_or_unsafe_root(std::path::Path::new(
413            "/tmp/leanctx-test"
414        )));
415        assert!(!is_broad_or_unsafe_root(std::path::Path::new(
416            "/tmp/my-project"
417        )));
418    }
419
420    #[test]
421    fn is_broad_or_unsafe_root_allows_home_subdirs() {
422        if let Some(home) = dirs::home_dir() {
423            let subdir = home.join("projects").join("my-app");
424            assert!(!is_broad_or_unsafe_root(&subdir));
425        }
426    }
427
428    #[test]
429    fn derive_project_root_falls_back_to_bare_cwd() {
430        let tmp = tempfile::tempdir().unwrap();
431        let bare = tmp.path().join("bare-dir");
432        std::fs::create_dir_all(&bare).unwrap();
433
434        let original = std::env::current_dir().unwrap();
435        std::env::set_current_dir(&bare).unwrap();
436        let result = derive_project_root_from_cwd();
437        std::env::set_current_dir(original).unwrap();
438
439        assert!(result.is_some(), "bare dir should produce a project root");
440        let root = result.unwrap();
441        assert!(
442            root.contains("bare-dir"),
443            "fallback should use the bare dir path"
444        );
445    }
446}