Skip to main content

lean_ctx/server/
server_handler.rs

1//! `rmcp::ServerHandler` trait implementation for [`LeanCtxServer`].
2//!
3//! Split out of `server/mod.rs`; `use super::*` re-imports the parent module’s
4//! aliases and sibling submodules. Methods attach to `LeanCtxServer` regardless
5//! of which module the impl block lives in.
6
7#[allow(clippy::wildcard_imports)]
8use super::*;
9
10impl ServerHandler for LeanCtxServer {
11    fn get_info(&self) -> ServerInfo {
12        let capabilities = ServerCapabilities::builder()
13            .enable_tools()
14            .enable_resources()
15            .enable_resources_subscribe()
16            .enable_prompts()
17            .build();
18
19        let config = crate::core::config::Config::load();
20        let level = crate::core::config::CompressionLevel::effective(&config);
21        let _ = crate::core::terse::rules_inject::inject(&level);
22
23        let instructions = crate::instructions::build_instructions(CrpMode::effective());
24
25        InitializeResult::new(capabilities)
26            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
27            .with_instructions(instructions)
28    }
29
30    async fn initialize(
31        &self,
32        request: InitializeRequestParams,
33        context: RequestContext<RoleServer>,
34    ) -> Result<InitializeResult, ErrorData> {
35        let name = request.client_info.name.clone();
36        tracing::info!("MCP client connected: {:?}", name);
37        *self.client_name.write().await = name.clone();
38        *self.peer.write().await = Some(context.peer.clone());
39
40        if self.session_mode != crate::tools::SessionMode::Shared {
41            crate::core::budget_tracker::BudgetTracker::global().reset();
42            if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
43                let radar = data_dir.join("context_radar.jsonl");
44                if radar.exists() {
45                    let prev = data_dir.join("context_radar.prev.jsonl");
46                    let _ = std::fs::rename(&radar, &prev);
47                }
48            }
49        }
50
51        let has_roots = request.capabilities.roots.is_some();
52        self.has_client_roots
53            .store(has_roots, std::sync::atomic::Ordering::Relaxed);
54        if has_roots {
55            tracing::info!("Client supports MCP roots/list — will resolve on first tool call");
56        }
57
58        let env_root = roots::root_from_env();
59        let derived_root = derive_project_root_from_cwd();
60        let effective_root = env_root.or(derived_root);
61
62        let cwd_str = std::env::current_dir()
63            .ok()
64            .map(|p| p.to_string_lossy().to_string())
65            .unwrap_or_default();
66        {
67            let mut session = self.session.write().await;
68            if !cwd_str.is_empty() {
69                session.shell_cwd = Some(cwd_str.clone());
70            }
71            if let Some(ref root) = effective_root {
72                session.project_root = Some(root.clone());
73                tracing::info!("Project root set to: {root}");
74            } else if let Some(ref root) = session.project_root {
75                // A previously persisted session may carry a contaminated root
76                // (e.g. HOME from an older build or a client that reported HOME
77                // as its workspace). Drop it unless it is a real, safe project
78                // dir — otherwise PROJECT MEMORY leaks across projects.
79                let root_path = std::path::Path::new(root);
80                let root_has_marker = has_project_marker(root_path);
81                let root_str = root_path.to_string_lossy();
82                let root_suspicious = crate::core::pathutil::is_broad_or_unsafe_root(root_path)
83                    || root_str.contains("/var/folders/")
84                    || root_str.contains("/tmp/")
85                    || root_str.contains("\\AppData\\Local\\Temp")
86                    || root_str.contains("\\Temp\\");
87                if root_suspicious && !root_has_marker {
88                    tracing::info!("Dropping suspicious persisted project root: {root}");
89                    session.project_root = None;
90                }
91            }
92            let cfg_extra = crate::core::config::Config::load().extra_roots;
93            if !cfg_extra.is_empty() {
94                let existing: std::collections::HashSet<_> =
95                    session.extra_roots.iter().cloned().collect();
96                for r in cfg_extra {
97                    if !existing.contains(&r) {
98                        session.extra_roots.push(r);
99                    }
100                }
101            }
102            if self.session_mode == crate::tools::SessionMode::Shared {
103                if let Some(ref root) = session.project_root {
104                    if let Some(ref rt) = self.context_os {
105                        rt.shared_sessions.persist_best_effort(
106                            root,
107                            &self.workspace_id,
108                            &self.channel_id,
109                            &session,
110                        );
111                        rt.metrics.record_session_persisted();
112                    }
113                }
114            } else if let Err(e) = session.save() {
115                tracing::warn!("lean-ctx: failed to persist session state: {e}");
116            }
117        }
118
119        // Indices are warmed lazily on first use of a tool that needs them
120        // (issue #152), not eagerly here — a session that only uses
121        // ctx_read/ctx_shell/ctx_tree must not pay a full graph + BM25 scan.
122        // See `index_orchestrator::ensure_warm_for_tool`, driven from dispatch.
123
124        let agent_name = name.clone();
125        let agent_root = effective_root.clone().unwrap_or_default();
126        let agent_id_handle = self.agent_id.clone();
127        tokio::task::spawn_blocking(move || {
128            if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
129                return;
130            }
131
132            // Avoid startup stampedes when multiple agent sessions initialize at once.
133            // These are best-effort maintenance tasks; it's fine to skip if another
134            // lean-ctx instance is already doing them.
135            let maintenance = crate::core::startup_guard::try_acquire_lock(
136                "startup-maintenance",
137                std::time::Duration::from_secs(2),
138                std::time::Duration::from_mins(2),
139            );
140            if maintenance.is_some() {
141                if let Some(home) = dirs::home_dir() {
142                    let _ = crate::rules_inject::inject_all_rules(&home);
143                }
144                crate::hooks::refresh_installed_hooks();
145                crate::core::version_check::check_background();
146                // Enforce the on-disk budget: prune accumulated quarantined BM25
147                // indexes and cap the archive FTS DB (#2364). Silent (tracing
148                // only) so it never corrupts the MCP stdio protocol.
149                let _ = crate::core::storage_maintenance::run_quiet();
150            }
151            drop(maintenance);
152
153            if !agent_root.is_empty() {
154                let heuristic_role = match agent_name.to_lowercase().as_str() {
155                    n if n.contains("cursor") => Some("coder"),
156                    n if n.contains("claude") => Some("coder"),
157                    n if n.contains("codex") => Some("coder"),
158                    n if n.contains("antigravity") || n.contains("gemini") => Some("coder"),
159                    n if n.contains("review") => Some("reviewer"),
160                    n if n.contains("test") => Some("debugger"),
161                    _ => None,
162                };
163                let env_role = std::env::var("LEAN_CTX_ROLE")
164                    .or_else(|_| std::env::var("LEAN_CTX_AGENT_ROLE"))
165                    .ok();
166                let effective_role = env_role.as_deref().or(heuristic_role).unwrap_or("coder");
167
168                let _ = crate::core::roles::set_active_role_with_source(effective_role, true);
169
170                let mut registry = crate::core::agents::AgentRegistry::load_or_create();
171                registry.cleanup_stale(24);
172                let id = registry.register("mcp", Some(effective_role), &agent_root);
173                let _ = registry.save();
174                if let Ok(mut guard) = agent_id_handle.try_write() {
175                    *guard = Some(id);
176                }
177            }
178        });
179
180        let client_caps = crate::core::client_capabilities::ClientMcpCapabilities::detect(&name);
181        tracing::info!("Client capabilities: {}", client_caps.format_summary());
182
183        {
184            let cfg = crate::core::config::Config::load();
185            let cats = cfg.default_tool_categories_effective();
186            dynamic_tools::init_from_config(&cats);
187        }
188
189        if client_caps.dynamic_tools {
190            if let Ok(mut dt) = dynamic_tools::global().lock() {
191                dt.set_supports_list_changed(true);
192            }
193        }
194        if let Some(max) = client_caps.max_tools {
195            if let Ok(mut dt) = dynamic_tools::global().lock() {
196                dt.set_supports_list_changed(true);
197                if max < 100 {
198                    dt.unload_category(dynamic_tools::ToolCategory::Debug);
199                    dt.unload_category(dynamic_tools::ToolCategory::Memory);
200                }
201            }
202        }
203
204        crate::core::client_capabilities::set_detected(&client_caps);
205
206        let instructions =
207            crate::instructions::build_instructions_with_client(CrpMode::effective(), &name);
208
209        let capabilities = match (client_caps.resources, client_caps.prompts) {
210            (true, true) => ServerCapabilities::builder()
211                .enable_tools()
212                .enable_resources()
213                .enable_resources_subscribe()
214                .enable_prompts()
215                .build(),
216            (true, false) => ServerCapabilities::builder()
217                .enable_tools()
218                .enable_resources()
219                .enable_resources_subscribe()
220                .build(),
221            (false, true) => ServerCapabilities::builder()
222                .enable_tools()
223                .enable_prompts()
224                .build(),
225            (false, false) => ServerCapabilities::builder().enable_tools().build(),
226        };
227
228        Ok(InitializeResult::new(capabilities)
229            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
230            .with_instructions(instructions))
231    }
232
233    async fn list_tools(
234        &self,
235        _request: Option<PaginatedRequestParams>,
236        _context: RequestContext<RoleServer>,
237    ) -> Result<ListToolsResult, ErrorData> {
238        // Panic guard (mirrors call_tool): a panic while filtering the registry /
239        // touching the dynamic-tools mutex must not kill the rmcp request task.
240        use std::panic::AssertUnwindSafe;
241        let computed = AssertUnwindSafe(async {
242            let cfg = crate::core::config::Config::load();
243            let disabled = cfg.disabled_tools_effective();
244            let tool_profile = cfg.tool_profile_effective();
245            // A profile is "explicit" when the user opted into one (config field,
246            // env var, or a custom tools list). Without an explicit choice we keep
247            // the token-lean lazy core set as the default. With one, the profile is
248            // authoritative and resolves against the full registry, so e.g.
249            // `standard` advertises its full balanced set instead of the accidental
250            // `core ∩ standard` intersection.
251            let explicit_profile = crate::server::tool_visibility::explicit_profile(&cfg);
252
253            use crate::server::tool_visibility::CandidateSet;
254            let candidate = crate::server::tool_visibility::candidate_set(
255                crate::tool_defs::is_full_mode(),
256                std::env::var("LEAN_CTX_UNIFIED").is_ok(),
257                explicit_profile,
258            );
259            let all_tools = match candidate {
260                CandidateSet::Full | CandidateSet::ProfileAuthoritative => {
261                    if let Some(ref reg) = self.registry {
262                        reg.tool_defs()
263                    } else {
264                        crate::tool_defs::granular_tool_defs()
265                    }
266                }
267                CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
268                CandidateSet::LazyCore => {
269                    if let Some(ref reg) = self.registry {
270                        let core_names = crate::tool_defs::core_tool_names();
271                        reg.tool_defs()
272                            .into_iter()
273                            .filter(|t| core_names.contains(&t.name.as_ref()))
274                            .collect()
275                    } else {
276                        crate::tool_defs::lazy_tool_defs()
277                    }
278                }
279            };
280            let client = self.client_name.read().await.clone();
281            let is_zed = !client.is_empty() && client.to_lowercase().contains("zed");
282
283            let active_role = crate::core::roles::active_role();
284            let tools: Vec<_> = all_tools
285                .into_iter()
286                .filter(|t| {
287                    let name = t.name.as_ref();
288                    crate::server::tool_visibility::is_tool_visible(
289                        name,
290                        &tool_profile,
291                        &disabled,
292                        is_zed,
293                        active_role.is_tool_allowed(name),
294                    )
295                })
296                .collect();
297
298            // Guarantee the universal invoker is advertised in non-full mode. Lazy
299            // and profile filtering hide most tools; without ctx_call a static-list
300            // client (one that only calls advertised tools) could not reach them.
301            // ctx_call enforces the same role/workflow gates on the inner tool.
302            let tools = {
303                let mut tools = tools;
304                use crate::server::tool_visibility::INVOKER;
305                let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
306                if crate::server::tool_visibility::needs_invoker(
307                    crate::tool_defs::is_full_mode(),
308                    already,
309                    active_role.is_tool_allowed(INVOKER),
310                    &disabled,
311                ) {
312                    if let Some(def) = self.registry.as_ref().and_then(|reg| {
313                        reg.tool_defs()
314                            .into_iter()
315                            .find(|t| t.name.as_ref() == INVOKER)
316                    }) {
317                        tools.push(def);
318                    }
319                }
320                tools
321            };
322
323            let tools = {
324                let Ok(dyn_state) = dynamic_tools::global().lock() else {
325                    tracing::warn!(
326                        "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
327                    );
328                    return Ok(ListToolsResult {
329                        tools,
330                        ..Default::default()
331                    });
332                };
333                // The lazy category gate (load tools on demand for dynamic_tools
334                // clients) only applies to the *default* lean-core surface. When the
335                // user opted into an explicit profile, that profile IS the
336                // authoritative surface — gating it by category would silently drop
337                // profile-enabled tools like Standard's ctx_architecture /
338                // ctx_semantic_search for Codex et al. (#358), so the advertised set
339                // would no longer match `lean-ctx tools show`.
340                if crate::server::tool_visibility::category_gate_applies(
341                    dyn_state.supports_list_changed(),
342                    explicit_profile,
343                ) {
344                    tools
345                        .into_iter()
346                        .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
347                        .collect()
348                } else {
349                    tools
350                }
351            };
352
353            let tools = {
354                let active = self.workflow.read().await.clone();
355                if let Some(run) = active {
356                    if run.current == "done" || is_workflow_stale(&run) {
357                        let mut wf = self.workflow.write().await;
358                        *wf = None;
359                        let _ = crate::core::workflow::clear_active();
360                    } else if let Some(state) = run.spec.state(&run.current) {
361                        if let Some(allowed) = &state.allowed_tools {
362                            let mut allow: std::collections::HashSet<&str> =
363                                allowed.iter().map(std::string::String::as_str).collect();
364                            for passthrough in WORKFLOW_PASSTHROUGH_TOOLS {
365                                allow.insert(passthrough);
366                            }
367                            return Ok(ListToolsResult {
368                                tools: tools
369                                    .into_iter()
370                                    .filter(|t| allow.contains(t.name.as_ref()))
371                                    .collect(),
372                                ..Default::default()
373                            });
374                        }
375                    }
376                }
377                tools
378            };
379
380            let tools = {
381                let cfg = crate::core::config::Config::load();
382                let level = crate::core::config::CompressionLevel::effective(&cfg);
383                let mode =
384                    crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(
385                        &level,
386                    );
387                if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
388                    tools
389                } else {
390                    tools
391                        .into_iter()
392                        .map(|mut t| {
393                            let compressed = crate::core::terse::mcp_compress::compress_description(
394                                t.name.as_ref(),
395                                t.description.as_deref().unwrap_or(""),
396                                mode,
397                            );
398                            t.description = Some(compressed.into());
399                            t
400                        })
401                        .collect()
402                }
403            };
404
405            Ok(ListToolsResult {
406                tools,
407                ..Default::default()
408            })
409        })
410        .catch_unwind()
411        .await;
412        computed.unwrap_or_else(|_| {
413            tracing::error!(
414                "list_tools panicked; returning an empty tool list to keep the MCP server alive"
415            );
416            Ok(ListToolsResult::default())
417        })
418    }
419
420    async fn list_prompts(
421        &self,
422        _request: Option<PaginatedRequestParams>,
423        _context: RequestContext<RoleServer>,
424    ) -> Result<rmcp::model::ListPromptsResult, ErrorData> {
425        Ok(rmcp::model::ListPromptsResult::with_all_items(
426            prompts::list_prompts(),
427        ))
428    }
429
430    async fn get_prompt(
431        &self,
432        request: rmcp::model::GetPromptRequestParams,
433        _context: RequestContext<RoleServer>,
434    ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
435        let ledger = self.ledger.read().await;
436        match prompts::get_prompt(&request, &ledger) {
437            Some(result) => Ok(result),
438            None => Err(ErrorData::invalid_params(
439                format!("Unknown prompt: {}", request.name),
440                None,
441            )),
442        }
443    }
444
445    async fn list_resources(
446        &self,
447        _request: Option<PaginatedRequestParams>,
448        _context: RequestContext<RoleServer>,
449    ) -> Result<rmcp::model::ListResourcesResult, rmcp::ErrorData> {
450        Ok(rmcp::model::ListResourcesResult::with_all_items(
451            resources::list_resources(),
452        ))
453    }
454
455    async fn read_resource(
456        &self,
457        request: rmcp::model::ReadResourceRequestParams,
458        _context: RequestContext<RoleServer>,
459    ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
460        let ledger = self.ledger.read().await;
461        match resources::read_resource(&request.uri, &ledger) {
462            Some(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
463            None => Err(rmcp::ErrorData::resource_not_found(
464                format!("Unknown resource: {}", request.uri),
465                None,
466            )),
467        }
468    }
469
470    async fn call_tool(
471        &self,
472        request: CallToolRequestParams,
473        context: RequestContext<RoleServer>,
474    ) -> Result<CallToolResult, ErrorData> {
475        use std::panic::AssertUnwindSafe;
476
477        let progress_token = request
478            .meta
479            .as_ref()
480            .and_then(rmcp::model::Meta::get_progress_token);
481        if let Some(ref token) = progress_token {
482            let sender =
483                crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
484            *self
485                .progress_sender
486                .lock()
487                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
488        }
489
490        let tool_name_for_panic = request.name.as_ref().to_string();
491        let args_fp_for_panic = request
492            .arguments
493            .as_ref()
494            .map(|a| {
495                crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
496                    a.clone(),
497                ))
498            })
499            .unwrap_or_default();
500
501        let loop_detector = self.loop_detector.clone();
502
503        match AssertUnwindSafe(self.call_tool_guarded(request))
504            .catch_unwind()
505            .await
506        {
507            Ok(result) => result,
508            Err(panic_payload) => {
509                let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
510                    (*s).to_string()
511                } else if let Some(s) = panic_payload.downcast_ref::<String>() {
512                    s.clone()
513                } else {
514                    "unknown".to_string()
515                };
516                tracing::error!("call_tool panicked: {detail}");
517
518                if let Ok(mut detector) =
519                    tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
520                        .await
521                {
522                    detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
523                }
524
525                Ok(CallToolResult::error(vec![Content::text(
526                    "ERROR: lean-ctx internal error. The MCP server is still running. \
527                     Please retry or use a different approach."
528                        .to_string(),
529                )]))
530            }
531        }
532    }
533
534    async fn on_roots_list_changed(
535        &self,
536        _context: rmcp::service::NotificationContext<RoleServer>,
537    ) {
538        tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
539        self.roots_resolved
540            .store(false, std::sync::atomic::Ordering::Relaxed);
541    }
542}