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