Skip to main content

lean_ctx/server/
mod.rs

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