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