Skip to main content

lean_ctx_server/server/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2pub(crate) mod activity;
3pub mod background_shell;
4pub use lean_ctx::core::bounded_lock;
5pub use lean_ctx::core::bypass_hint;
6mod call_identity;
7#[cfg(test)]
8mod catalog_tests;
9#[doc(hidden)]
10pub mod client_sessions;
11pub mod compaction_sync;
12pub mod context_gate;
13#[cfg(test)]
14mod decision_loop_integration_tests;
15mod dispatch;
16pub use dispatch::canonicalize_arg_aliases;
17pub mod dynamic_tools;
18pub mod elicitation;
19pub(crate) mod execute;
20#[cfg(unix)]
21pub use execute::register_protected_shell_runner;
22mod file_resource;
23pub mod helpers;
24#[cfg(any(test, feature = "test-support"))]
25pub mod isolation_fixture;
26pub mod mcp_idle;
27pub mod multi_path;
28pub mod native_receipts;
29pub mod notifications;
30pub mod permission_inheritance;
31pub mod policy_guard;
32pub mod predictive_preload;
33pub mod progress;
34pub mod prompts;
35pub use lean_ctx::core::reference_store;
36pub mod registry;
37pub mod resources;
38pub mod role_guard;
39pub use lean_ctx::core::mcp_roots as roots;
40pub mod schema_hook;
41pub(crate) mod shell_approval;
42pub use lean_ctx::core::mcp_roots::{derive_project_root_from, derive_project_root_from_cwd};
43use lean_ctx::core::pathutil::has_project_marker;
44pub mod tool_trait;
45pub mod tool_visibility;
46pub mod tools_config_watch;
47pub(crate) mod walk_hint;
48// Workspace authority verifies file ownership, which needs a Unix host.
49#[cfg(all(test, unix))]
50mod workspace_roots_tests;
51
52use futures::FutureExt;
53use rmcp::ErrorData;
54use rmcp::handler::server::ServerHandler;
55use rmcp::model::{
56    CallToolRequestParams, CallToolResult, ContentBlock, Implementation, InitializeRequestParams,
57    InitializeResult, ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig,
58};
59use rmcp::service::{RequestContext, RoleServer};
60
61use crate::tools::{CrpMode, LeanCtxServer};
62mod call_tool;
63pub(crate) use call_tool::SessionSwitch;
64mod post_dispatch;
65mod post_process;
66mod server_handler;
67
68pub fn build_instructions_for_test(crp_mode: CrpMode) -> String {
69    lean_ctx::instructions::build_instructions_for_test(crp_mode)
70}
71
72pub fn build_claude_code_instructions_for_test() -> String {
73    lean_ctx::instructions::claude_code_instructions()
74}
75
76/// Deterministic STATIC Claude Code instructions (cold first-contact, no dynamic
77/// session/knowledge/gotcha payload) for the char-budget benchmark.
78pub fn build_claude_code_static_instructions_for_test() -> String {
79    lean_ctx::instructions::claude_code_static_instructions_for_test()
80}
81
82// Delegated to lean_ctx::core::pathutil::is_broad_or_unsafe_root
83#[cfg(test)]
84use lean_ctx::core::pathutil::is_broad_or_unsafe_root;
85
86pub fn tool_descriptions_for_test() -> Vec<(String, String)> {
87    crate::server::registry::build_registry()
88        .tool_defs()
89        .into_iter()
90        .map(|t| {
91            (
92                t.name.to_string(),
93                t.description.as_deref().unwrap_or("").to_string(),
94            )
95        })
96        .collect()
97}
98
99pub fn tool_schemas_json_for_test() -> String {
100    crate::server::registry::build_registry()
101        .tool_defs()
102        .iter()
103        .map(|t| {
104            format!(
105                "{}: {}",
106                t.name,
107                serde_json::to_string(&t.input_schema).unwrap_or_default()
108            )
109        })
110        .collect::<Vec<_>>()
111        .join("\n")
112}
113
114pub use lean_ctx::core::workflow::WORKFLOW_PASSTHROUGH_TOOLS;
115
116/// A workflow is stale if it hasn't been updated in 30 minutes.
117/// This prevents dead workflows from blocking tools across sessions.
118///
119/// The rule itself is `core::workflow::is_run_stale` (shared with the store
120/// and the tool gate): the stand-in for a withheld workflow is never stale.
121pub fn is_workflow_stale(run: &lean_ctx::core::workflow::types::WorkflowRun) -> bool {
122    lean_ctx::core::workflow::is_run_stale(run)
123}
124
125/// Whether the MCP client has lean-ctx hooks installed that compress native
126/// Read/Shell/Grep/Glob transparently. Used by `list_tools` to decide whether
127/// the shadow-only surface (just `ctx_call`) is safe.
128fn is_client_hook_covered(client_name: &str) -> bool {
129    lean_ctx::core::home::resolve_home_dir()
130        .is_some_and(|home| lean_ctx::core::rules_channel::client_hook_covered(client_name, &home))
131}
132
133fn is_shell_tool_name(name: &str) -> bool {
134    matches!(name, "ctx_shell" | "ctx_execute")
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn home_dir_detected_as_broad_root() {
143        // HOME is read here and again inside the check: another test may move
144        // it in between (macOS release prebuild, 3.12.1).
145        let _env = lean_ctx::core::data_dir::test_env_lock();
146        if let Some(home) = dirs::home_dir() {
147            assert!(is_broad_or_unsafe_root(&home));
148        }
149    }
150
151    #[test]
152    fn agent_dirs_detected() {
153        let claude = std::path::PathBuf::from("/home/user/.claude");
154        assert!(is_broad_or_unsafe_root(&claude));
155        let codex = std::path::PathBuf::from("/home/user/.codex");
156        assert!(is_broad_or_unsafe_root(&codex));
157        let project = std::path::PathBuf::from("/home/user/projects/myapp");
158        assert!(!is_broad_or_unsafe_root(&project));
159    }
160
161    #[test]
162    fn test_unified_tool_count() {
163        let tools = lean_ctx::tool_defs::unified_tool_defs();
164        assert_eq!(tools.len(), 5, "Expected 5 unified tools");
165    }
166
167    #[test]
168    fn test_granular_tool_count() {
169        registry::register_tool_catalog();
170        let tools = lean_ctx::tool_defs::granular_tool_defs();
171        assert!(tools.len() >= 25, "Expected at least 25 granular tools");
172    }
173
174    #[test]
175    fn production_server_always_has_registry() {
176        // The list_tools fallback that serves static defs when `registry` is None
177        // must stay unreachable in production: every public constructor funnels
178        // through new_with_startup, which sets registry = Some. Lock that invariant
179        // so the advertised tool set can never silently drift from what dispatch
180        // (which requires the registry) can actually execute.
181        let server = crate::tools::create_server();
182        assert!(
183            server.registry.is_some(),
184            "production server must carry a tool registry"
185        );
186    }
187
188    #[test]
189    fn disabled_tools_filters_list() {
190        registry::register_tool_catalog();
191        let all = lean_ctx::tool_defs::granular_tool_defs();
192        let total = all.len();
193        // `ctx_agent` is retained as a direct compatibility path but is no
194        // longer part of the advertised granular surface. Exercise filtering
195        // with one actual public tool instead of treating a hidden alias as
196        // visible inventory.
197        let disabled = ["ctx_graph".to_string()];
198        let filtered: Vec<_> = all
199            .into_iter()
200            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
201            .collect();
202        assert_eq!(filtered.len(), total - 1);
203        assert!(!filtered.iter().any(|t| t.name.as_ref() == "ctx_graph"));
204        assert!(!filtered.iter().any(|t| t.name.as_ref() == "ctx_agent"));
205    }
206
207    #[test]
208    fn empty_disabled_tools_returns_all() {
209        let all = lean_ctx::tool_defs::granular_tool_defs();
210        let total = all.len();
211        let disabled: Vec<String> = vec![];
212        let filtered: Vec<_> = all
213            .into_iter()
214            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
215            .collect();
216        assert_eq!(filtered.len(), total);
217    }
218
219    #[test]
220    fn misspelled_disabled_tool_is_silently_ignored() {
221        let all = lean_ctx::tool_defs::granular_tool_defs();
222        let total = all.len();
223        let disabled = ["ctx_nonexistent_tool".to_string()];
224        let filtered: Vec<_> = all
225            .into_iter()
226            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
227            .collect();
228        assert_eq!(filtered.len(), total);
229    }
230
231    #[test]
232    fn is_broad_or_unsafe_root_rejects_home() {
233        // HOME is read here and again inside the check: another test may move
234        // it in between (macOS release prebuild, 3.12.1).
235        let _env = lean_ctx::core::data_dir::test_env_lock();
236        if let Some(home) = dirs::home_dir() {
237            assert!(is_broad_or_unsafe_root(&home));
238        }
239    }
240
241    #[test]
242    fn is_broad_or_unsafe_root_rejects_filesystem_root() {
243        assert!(is_broad_or_unsafe_root(std::path::Path::new("/")));
244    }
245
246    #[test]
247    fn is_broad_or_unsafe_root_rejects_agent_dirs() {
248        assert!(is_broad_or_unsafe_root(std::path::Path::new(
249            "/home/user/.claude"
250        )));
251        assert!(is_broad_or_unsafe_root(std::path::Path::new(
252            "/home/user/.codex"
253        )));
254    }
255
256    #[test]
257    fn is_broad_or_unsafe_root_allows_project_subdir() {
258        let tmp = tempfile::tempdir().unwrap();
259        let subdir = tmp.path().join("my-project");
260        std::fs::create_dir_all(&subdir).unwrap();
261        assert!(!is_broad_or_unsafe_root(&subdir));
262    }
263
264    #[test]
265    fn is_broad_or_unsafe_root_allows_tmp_subdirs() {
266        assert!(!is_broad_or_unsafe_root(std::path::Path::new(
267            "/tmp/leanctx-test"
268        )));
269        assert!(!is_broad_or_unsafe_root(std::path::Path::new(
270            "/tmp/my-project"
271        )));
272    }
273
274    #[test]
275    fn is_broad_or_unsafe_root_allows_home_subdirs() {
276        // HOME is read here and again inside the check: another test may move
277        // it in between (macOS release prebuild, 3.12.1).
278        let _env = lean_ctx::core::data_dir::test_env_lock();
279        if let Some(home) = dirs::home_dir() {
280            let subdir = home.join("projects").join("my-app");
281            assert!(!is_broad_or_unsafe_root(&subdir));
282        }
283    }
284}