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