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