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 = cfg.tool_profile.is_some()
252                || !cfg.tools_enabled.is_empty()
253                || std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok();
254
255            let all_tools = if crate::tool_defs::is_full_mode() {
256                if let Some(ref reg) = self.registry {
257                    reg.tool_defs()
258                } else {
259                    crate::tool_defs::granular_tool_defs()
260                }
261            } else if std::env::var("LEAN_CTX_UNIFIED").is_ok() {
262                crate::tool_defs::unified_tool_defs()
263            } else if let Some(ref reg) = self.registry {
264                if explicit_profile {
265                    reg.tool_defs()
266                } else {
267                    let core_names = crate::tool_defs::core_tool_names();
268                    reg.tool_defs()
269                        .into_iter()
270                        .filter(|t| core_names.contains(&t.name.as_ref()))
271                        .collect()
272                }
273            } else {
274                crate::tool_defs::lazy_tool_defs()
275            };
276            let client = self.client_name.read().await.clone();
277            let is_zed = !client.is_empty() && client.to_lowercase().contains("zed");
278
279            let active_role = crate::core::roles::active_role();
280            let tools: Vec<_> = all_tools
281                .into_iter()
282                .filter(|t| {
283                    let name = t.name.as_ref();
284                    crate::server::tool_visibility::is_tool_visible(
285                        name,
286                        &tool_profile,
287                        &disabled,
288                        is_zed,
289                        active_role.is_tool_allowed(name),
290                    )
291                })
292                .collect();
293
294            // Guarantee the universal invoker is advertised in non-full mode. Lazy
295            // and profile filtering hide most tools; without ctx_call a static-list
296            // client (one that only calls advertised tools) could not reach them.
297            // ctx_call enforces the same role/workflow gates on the inner tool.
298            let tools = {
299                let mut tools = tools;
300                use crate::server::tool_visibility::INVOKER;
301                let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
302                if crate::server::tool_visibility::needs_invoker(
303                    crate::tool_defs::is_full_mode(),
304                    already,
305                    active_role.is_tool_allowed(INVOKER),
306                    &disabled,
307                ) {
308                    if let Some(def) = self.registry.as_ref().and_then(|reg| {
309                        reg.tool_defs()
310                            .into_iter()
311                            .find(|t| t.name.as_ref() == INVOKER)
312                    }) {
313                        tools.push(def);
314                    }
315                }
316                tools
317            };
318
319            let tools = {
320                let Ok(dyn_state) = dynamic_tools::global().lock() else {
321                    tracing::warn!(
322                        "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
323                    );
324                    return Ok(ListToolsResult {
325                        tools,
326                        ..Default::default()
327                    });
328                };
329                // The lazy category gate (load tools on demand for dynamic_tools
330                // clients) only applies to the *default* lean-core surface. When the
331                // user opted into an explicit profile, that profile IS the
332                // authoritative surface — gating it by category would silently drop
333                // profile-enabled tools like Standard's ctx_architecture /
334                // ctx_semantic_search for Codex et al. (#358), so the advertised set
335                // would no longer match `lean-ctx tools show`.
336                if crate::server::tool_visibility::category_gate_applies(
337                    dyn_state.supports_list_changed(),
338                    explicit_profile,
339                ) {
340                    tools
341                        .into_iter()
342                        .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
343                        .collect()
344                } else {
345                    tools
346                }
347            };
348
349            let tools = {
350                let active = self.workflow.read().await.clone();
351                if let Some(run) = active {
352                    if run.current == "done" || is_workflow_stale(&run) {
353                        let mut wf = self.workflow.write().await;
354                        *wf = None;
355                        let _ = crate::core::workflow::clear_active();
356                    } else if let Some(state) = run.spec.state(&run.current) {
357                        if let Some(allowed) = &state.allowed_tools {
358                            let mut allow: std::collections::HashSet<&str> =
359                                allowed.iter().map(std::string::String::as_str).collect();
360                            for passthrough in WORKFLOW_PASSTHROUGH_TOOLS {
361                                allow.insert(passthrough);
362                            }
363                            return Ok(ListToolsResult {
364                                tools: tools
365                                    .into_iter()
366                                    .filter(|t| allow.contains(t.name.as_ref()))
367                                    .collect(),
368                                ..Default::default()
369                            });
370                        }
371                    }
372                }
373                tools
374            };
375
376            let tools = {
377                let cfg = crate::core::config::Config::load();
378                let level = crate::core::config::CompressionLevel::effective(&cfg);
379                let mode =
380                    crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(
381                        &level,
382                    );
383                if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
384                    tools
385                } else {
386                    tools
387                        .into_iter()
388                        .map(|mut t| {
389                            let compressed = crate::core::terse::mcp_compress::compress_description(
390                                t.name.as_ref(),
391                                t.description.as_deref().unwrap_or(""),
392                                mode,
393                            );
394                            t.description = Some(compressed.into());
395                            t
396                        })
397                        .collect()
398                }
399            };
400
401            Ok(ListToolsResult {
402                tools,
403                ..Default::default()
404            })
405        })
406        .catch_unwind()
407        .await;
408        computed.unwrap_or_else(|_| {
409            tracing::error!(
410                "list_tools panicked; returning an empty tool list to keep the MCP server alive"
411            );
412            Ok(ListToolsResult::default())
413        })
414    }
415
416    async fn list_prompts(
417        &self,
418        _request: Option<PaginatedRequestParams>,
419        _context: RequestContext<RoleServer>,
420    ) -> Result<rmcp::model::ListPromptsResult, ErrorData> {
421        Ok(rmcp::model::ListPromptsResult::with_all_items(
422            prompts::list_prompts(),
423        ))
424    }
425
426    async fn get_prompt(
427        &self,
428        request: rmcp::model::GetPromptRequestParams,
429        _context: RequestContext<RoleServer>,
430    ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
431        let ledger = self.ledger.read().await;
432        match prompts::get_prompt(&request, &ledger) {
433            Some(result) => Ok(result),
434            None => Err(ErrorData::invalid_params(
435                format!("Unknown prompt: {}", request.name),
436                None,
437            )),
438        }
439    }
440
441    async fn list_resources(
442        &self,
443        _request: Option<PaginatedRequestParams>,
444        _context: RequestContext<RoleServer>,
445    ) -> Result<rmcp::model::ListResourcesResult, rmcp::ErrorData> {
446        Ok(rmcp::model::ListResourcesResult::with_all_items(
447            resources::list_resources(),
448        ))
449    }
450
451    async fn read_resource(
452        &self,
453        request: rmcp::model::ReadResourceRequestParams,
454        _context: RequestContext<RoleServer>,
455    ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
456        let ledger = self.ledger.read().await;
457        match resources::read_resource(&request.uri, &ledger) {
458            Some(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
459            None => Err(rmcp::ErrorData::resource_not_found(
460                format!("Unknown resource: {}", request.uri),
461                None,
462            )),
463        }
464    }
465
466    async fn call_tool(
467        &self,
468        request: CallToolRequestParams,
469        context: RequestContext<RoleServer>,
470    ) -> Result<CallToolResult, ErrorData> {
471        use std::panic::AssertUnwindSafe;
472
473        let progress_token = request
474            .meta
475            .as_ref()
476            .and_then(rmcp::model::Meta::get_progress_token);
477        if let Some(ref token) = progress_token {
478            let sender =
479                crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
480            *self
481                .progress_sender
482                .lock()
483                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
484        }
485
486        let tool_name_for_panic = request.name.as_ref().to_string();
487        let args_fp_for_panic = request
488            .arguments
489            .as_ref()
490            .map(|a| {
491                crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
492                    a.clone(),
493                ))
494            })
495            .unwrap_or_default();
496
497        let loop_detector = self.loop_detector.clone();
498
499        match AssertUnwindSafe(self.call_tool_guarded(request))
500            .catch_unwind()
501            .await
502        {
503            Ok(result) => result,
504            Err(panic_payload) => {
505                let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
506                    (*s).to_string()
507                } else if let Some(s) = panic_payload.downcast_ref::<String>() {
508                    s.clone()
509                } else {
510                    "unknown".to_string()
511                };
512                tracing::error!("call_tool panicked: {detail}");
513
514                if let Ok(mut detector) =
515                    tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
516                        .await
517                {
518                    detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
519                }
520
521                Ok(CallToolResult::error(vec![Content::text(
522                    "ERROR: lean-ctx internal error. The MCP server is still running. \
523                     Please retry or use a different approach."
524                        .to_string(),
525                )]))
526            }
527        }
528    }
529
530    async fn on_roots_list_changed(
531        &self,
532        _context: rmcp::service::NotificationContext<RoleServer>,
533    ) {
534        tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
535        self.roots_resolved
536            .store(false, std::sync::atomic::Ordering::Relaxed);
537    }
538}