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            session.refresh_handoff_context();
141
142            if self.session_mode == crate::tools::SessionMode::Shared {
143                if let Some(ref root) = session.project_root
144                    && let Some(ref rt) = self.context_os
145                {
146                    rt.shared_sessions.persist_best_effort(
147                        root,
148                        &self.workspace_id,
149                        &self.channel_id,
150                        &session,
151                    );
152                    rt.metrics.record_session_persisted();
153                }
154            } else if let Err(e) = session.save() {
155                tracing::warn!("lean-ctx: failed to persist session state: {e}");
156            }
157        }
158
159        // Indices are warmed lazily on first use of a tool that needs them
160        // (issue #152), not eagerly here — a session that only uses
161        // ctx_read/ctx_shell/ctx_tree must not pay a full graph + BM25 scan.
162        // See `index_orchestrator::ensure_warm_for_tool`, driven from dispatch.
163
164        let agent_name = name.clone();
165        let agent_root = effective_root.clone().unwrap_or_default();
166        let agent_id_handle = self.agent_id.clone();
167        tokio::task::spawn_blocking(move || {
168            if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
169                return;
170            }
171
172            // Avoid startup stampedes when multiple agent sessions initialize at once.
173            // These are best-effort maintenance tasks; it's fine to skip if another
174            // lean-ctx instance is already doing them.
175            let maintenance = crate::core::startup_guard::try_acquire_lock(
176                "startup-maintenance",
177                std::time::Duration::from_secs(2),
178                std::time::Duration::from_mins(2),
179            );
180            if maintenance.is_some() {
181                if let Some(home) = dirs::home_dir() {
182                    let _ = crate::rules_inject::inject_all_rules(&home);
183                    // The on-demand SKILL.md belongs to the same steering surface
184                    // as the rules block: the session-start heal writes rules for
185                    // every detected client, so a fresh machine that never ran
186                    // `lean-ctx setup` otherwise carries a permanent doctor
187                    // warning ("SKILL.md not installed"). Idempotent + gated on
188                    // the same opt-outs as setup (rules_injection=off inside,
189                    // auto_inject_skills=Some(false) here).
190                    if crate::core::config::Config::load()
191                        .setup
192                        .should_inject_skills()
193                    {
194                        let _ = crate::rules_inject::install_all_skills(&home);
195                    }
196                }
197                crate::hooks::refresh_installed_hooks();
198                crate::core::version_check::check_background();
199                // Enforce the on-disk budget: prune accumulated quarantined BM25
200                // indexes and cap the archive FTS DB (#2364). Silent (tracing
201                // only) so it never corrupts the MCP stdio protocol.
202                let _ = crate::core::storage_maintenance::run_quiet();
203            }
204            drop(maintenance);
205
206            if !agent_root.is_empty() {
207                let heuristic_role = match agent_name.to_lowercase().as_str() {
208                    n if n.contains("cursor") => Some("coder"),
209                    n if n.contains("claude") => Some("coder"),
210                    n if n.contains("codebuddy") => Some("coder"),
211                    n if n.contains("codex") => Some("coder"),
212                    n if n.contains("antigravity") || n.contains("gemini") => Some("coder"),
213                    n if n.contains("review") => Some("reviewer"),
214                    n if n.contains("test") => Some("debugger"),
215                    _ => None,
216                };
217                let env_role = std::env::var("LEAN_CTX_ROLE")
218                    .or_else(|_| std::env::var("LEAN_CTX_AGENT_ROLE"))
219                    .ok();
220                let effective_role = env_role.as_deref().or(heuristic_role).unwrap_or("coder");
221
222                let _ = crate::core::roles::set_active_role_with_source(effective_role, true);
223
224                let id = crate::core::agents::AgentRegistry::mutate_locked(|registry| {
225                    registry.cleanup_stale(24);
226                    registry.register("mcp", Some(effective_role), &agent_root)
227                })
228                .and_then(|(_, id)| id)
229                .ok();
230                if let (Some(id), Ok(mut guard)) = (id, agent_id_handle.try_write()) {
231                    *guard = Some(id);
232                }
233            }
234        });
235
236        let client_caps = crate::core::client_capabilities::ClientMcpCapabilities::detect(&name);
237        tracing::info!("Client capabilities: {}", client_caps.format_summary());
238
239        {
240            let cfg = crate::core::config::Config::load();
241            let cats = cfg.default_tool_categories_effective();
242            dynamic_tools::init_from_config(&cats);
243        }
244
245        if let Some(max) = client_caps.max_tools
246            && let Ok(mut dt) = dynamic_tools::global().lock()
247        {
248            dt.set_supports_list_changed(true);
249            if max < 100 {
250                dt.unload_category(dynamic_tools::ToolCategory::Debug);
251                dt.unload_category(dynamic_tools::ToolCategory::Memory);
252            }
253        } else if client_caps.dynamic_tools
254            && let Ok(mut dt) = dynamic_tools::global().lock()
255        {
256            dt.set_supports_list_changed(true);
257        }
258
259        crate::core::client_capabilities::set_detected(&client_caps);
260
261        let session = self.session.read().await.clone();
262        let instructions = crate::instructions::build_instructions_with_client_and_session(
263            CrpMode::effective(),
264            &name,
265            &session,
266        );
267
268        let capabilities = server_capabilities(client_caps.resources, client_caps.prompts);
269
270        let result = InitializeResult::new(capabilities)
271            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")));
272
273        // GH #1447: Antigravity/Gemini CLI disconnect when the initialize
274        // response contains `instructions`. The MCP spec marks it optional,
275        // but these clients fail on any unexpected field in the JSON envelope.
276        if matches!(client_caps.client_id.as_str(), "antigravity" | "gemini-cli") {
277            Ok(result)
278        } else {
279            Ok(result.with_instructions(instructions))
280        }
281    }
282
283    async fn list_tools(
284        &self,
285        _request: Option<PaginatedRequestParams>,
286        _context: RequestContext<RoleServer>,
287    ) -> Result<ListToolsResult, ErrorData> {
288        use crate::server::tool_visibility::CandidateSet;
289        // Panic guard (mirrors call_tool): a panic while filtering the registry /
290        // touching the dynamic-tools mutex must not kill the rmcp request task.
291        use std::panic::AssertUnwindSafe;
292        let computed = AssertUnwindSafe(async {
293            let cfg = crate::core::config::Config::load();
294            let disabled = cfg.disabled_tools_effective();
295            let raw_profile = cfg.tool_profile_effective();
296            let tool_profile = crate::server::tool_visibility::resolve_auto_profile(&raw_profile);
297            crate::server::tool_visibility::record_auto_turn();
298            // A profile is "explicit" when the user opted into one (config field,
299            // env var, or a custom tools list). Without an explicit choice we keep
300            // the token-lean lazy core set as the default. With one, the profile is
301            // authoritative and resolves against the full registry, so e.g.
302            // `standard` advertises its full balanced set instead of the accidental
303            // `core ∩ standard` intersection.
304            let explicit_profile = crate::server::tool_visibility::explicit_profile(&cfg);
305
306            let client = self.client_name.read().await.clone();
307            let hook_covered = is_client_hook_covered(&client);
308
309            let candidate = crate::server::tool_visibility::candidate_set(
310                &crate::server::tool_visibility::CandidateInputs {
311                    full_mode: crate::tool_defs::is_full_mode(),
312                    unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
313                    explicit_profile,
314                    hook_covered,
315                },
316            );
317            let all_tools = match candidate {
318                CandidateSet::Full | CandidateSet::ProfileAuthoritative => {
319                    if let Some(ref reg) = self.registry {
320                        reg.tool_defs()
321                    } else {
322                        // Unreachable in production: every constructor sets a registry
323                        // (locked by `production_server_always_has_registry`). If it
324                        // ever fires, the advertised static defs can drift from what
325                        // dispatch (which needs the registry) can execute — make it loud.
326                        tracing::error!(
327                            "list_tools served WITHOUT a tool registry (full mode) — advertising \
328                             static granular defs that dispatch cannot run; tools may drift from handlers."
329                        );
330                        crate::tool_defs::granular_tool_defs()
331                    }
332                }
333                CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
334                // GH #1474: ShadowOnly is never returned anymore; treat as LazyCore.
335                CandidateSet::ShadowOnly |
336                CandidateSet::LazyCore => {
337                    if let Some(ref reg) = self.registry {
338                        let core_names = crate::tool_defs::core_tool_names();
339                        reg.tool_defs()
340                            .into_iter()
341                            .filter(|t| core_names.contains(&t.name.as_ref()))
342                            .collect()
343                    } else {
344                        // Unreachable in production (see above); loud if it ever fires.
345                        tracing::error!(
346                            "list_tools served WITHOUT a tool registry (lazy mode) — advertising \
347                             static lazy defs that dispatch cannot run; tools may drift from handlers."
348                        );
349                        crate::tool_defs::lazy_tool_defs()
350                    }
351                }
352            };
353            let quirks = crate::server::tool_visibility::ClientQuirks::resolve(&client, candidate);
354
355            let active_role = crate::core::roles::active_role();
356            let tools: Vec<_> = all_tools
357                .into_iter()
358                .filter(|t| {
359                    let name = t.name.as_ref();
360                    crate::server::tool_visibility::is_tool_visible(
361                        name,
362                        &tool_profile,
363                        &disabled,
364                        quirks,
365                        active_role.is_tool_allowed(name),
366                    )
367                })
368                .collect();
369
370            // Guarantee the universal invoker is advertised in non-full mode. Lazy
371            // and profile filtering hide most tools; without ctx_call a static-list
372            // client (one that only calls advertised tools) could not reach them.
373            // ctx_call enforces the same role/workflow gates on the inner tool.
374            let tools = {
375                use crate::server::tool_visibility::INVOKER;
376                let mut tools = tools;
377                let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
378                if crate::server::tool_visibility::needs_invoker(
379                    crate::tool_defs::is_full_mode(),
380                    already,
381                    active_role.is_tool_allowed(INVOKER),
382                    &disabled,
383                ) && let Some(def) = self.registry.as_ref().and_then(|reg| {
384                    reg.tool_defs()
385                        .into_iter()
386                        .find(|t| t.name.as_ref() == INVOKER)
387                }) {
388                    tools.push(def);
389                }
390                tools
391            };
392
393            let tools = {
394                let Ok(dyn_state) = dynamic_tools::global().lock() else {
395                    tracing::warn!(
396                        "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
397                    );
398                    return Ok(ListToolsResult {
399                        tools,
400                        ..Default::default()
401                    });
402                };
403                // The lazy category gate (load tools on demand for dynamic_tools
404                // clients) only applies to the *default* lean-core surface. When the
405                // user opted into an explicit profile, that profile IS the
406                // authoritative surface — gating it by category would silently drop
407                // profile-enabled tools like Standard's ctx_architecture /
408                // ctx_semantic_search for Codex et al. (#358), so the advertised set
409                // would no longer match `lean-ctx tools show`.
410                if crate::server::tool_visibility::category_gate_applies(
411                    dyn_state.supports_list_changed(),
412                    explicit_profile,
413                ) {
414                    tools
415                        .into_iter()
416                        .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
417                        .collect()
418                } else {
419                    tools
420                }
421            };
422
423            let tools = {
424                let active = self.workflow.read().await.clone();
425                if let Some(run) = active {
426                    if run.current == "done" || is_workflow_stale(&run) {
427                        let mut wf = self.workflow.write().await;
428                        *wf = None;
429                        let _ = crate::core::workflow::clear_active();
430                    } else if let Some(state) = run.spec.state(&run.current)
431                        && let Some(allowed) = &state.allowed_tools
432                    {
433                        let mut allow: std::collections::HashSet<&str> =
434                            allowed.iter().map(std::string::String::as_str).collect();
435                        for passthrough in WORKFLOW_PASSTHROUGH_TOOLS {
436                            allow.insert(passthrough);
437                        }
438                        return Ok(ListToolsResult {
439                            tools: tools
440                                .into_iter()
441                                .filter(|t| allow.contains(t.name.as_ref()))
442                                .collect(),
443                            ..Default::default()
444                        });
445                    }
446                }
447                tools
448            };
449
450            let tools = {
451                let cfg = crate::core::config::Config::load();
452                let level = crate::core::config::CompressionLevel::effective(&cfg);
453                let mode =
454                    crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(
455                        &level,
456                    );
457                if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
458                    tools
459                } else {
460                    tools
461                        .into_iter()
462                        .map(|mut t| {
463                            let compressed = crate::core::terse::mcp_compress::compress_description(
464                                t.name.as_ref(),
465                                t.description.as_deref().unwrap_or(""),
466                                mode,
467                            );
468                            t.description = Some(compressed.into());
469                            t
470                        })
471                        .collect()
472                }
473            };
474
475
476            // R28: Kernel schema optimization — budget-aware description compression.
477            let tools = crate::server::schema_hook::optimize_tools(tools, &client);
478            // #1008: When ctx_patch is hidden for this client, scrub references
479            // from other tools' descriptions so the LLM never sees the name and
480            // won't attempt to call it. Replace with ctx_edit (visible alternative).
481            let tools = if quirks.hide_ctx_patch {
482                tools
483                    .into_iter()
484                    .map(|mut t| {
485                        if let Some(ref desc) = t.description
486                            && desc.contains("ctx_patch")
487                        {
488                            t.description =
489                                Some(desc.replace("ctx_patch", "ctx_edit").into());
490                        }
491                        t
492                    })
493                    .collect()
494            } else {
495                tools
496            };
497
498            // Plan mode: restrict advertised tools to the curated read-only set.
499            let tools = {
500                use crate::tools::InteractionMode;
501                let mode = InteractionMode::from_u8(
502                    self.interaction_mode
503                        .load(std::sync::atomic::Ordering::Relaxed),
504                );
505                if mode == InteractionMode::Plan {
506                    let plan_set =
507                        crate::core::editor_registry::plan_mode::plan_mode_tools();
508                    tools
509                        .into_iter()
510                        .filter(|t| {
511                            let n = t.name.as_ref();
512                            plan_set.contains(&n) || n == "ctx_call"
513                        })
514                        .collect()
515                } else {
516                    tools
517                }
518            };
519
520            Ok(ListToolsResult {
521                tools,
522                ..Default::default()
523            })
524        })
525        .catch_unwind()
526        .await;
527        computed.unwrap_or_else(|_| {
528            // A panic here must NOT leave the agent tool-less — that is
529            // indistinguishable from "MCP totally failed" and gives the user no
530            // recovery path. Fall back to the static lazy-core defs (a pure,
531            // panic-free function) so ctx_read/ctx_shell/ctx_call stay available
532            // even if the dynamic/registry path blew up.
533            tracing::error!(
534                "list_tools panicked; serving the static lazy-core tool set as a fallback"
535            );
536            Ok(ListToolsResult {
537                tools: crate::tool_defs::lazy_tool_defs(),
538                ..Default::default()
539            })
540        })
541    }
542
543    fn list_prompts(
544        &self,
545        _request: Option<PaginatedRequestParams>,
546        _context: RequestContext<RoleServer>,
547    ) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, ErrorData>> {
548        std::future::ready(Ok(rmcp::model::ListPromptsResult::with_all_items(
549            prompts::list_prompts(),
550        )))
551    }
552
553    async fn get_prompt(
554        &self,
555        request: rmcp::model::GetPromptRequestParams,
556        _context: RequestContext<RoleServer>,
557    ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
558        let ledger = self.ledger.read().await;
559        match prompts::get_prompt(&request, &ledger) {
560            Some(result) => Ok(result),
561            None => Err(ErrorData::invalid_params(
562                format!("Unknown prompt: {}", request.name),
563                None,
564            )),
565        }
566    }
567
568    fn list_resources(
569        &self,
570        _request: Option<PaginatedRequestParams>,
571        _context: RequestContext<RoleServer>,
572    ) -> impl Future<Output = Result<rmcp::model::ListResourcesResult, rmcp::ErrorData>> {
573        std::future::ready(Ok(rmcp::model::ListResourcesResult::with_all_items(
574            resources::list_resources(),
575        )))
576    }
577
578    async fn read_resource(
579        &self,
580        request: rmcp::model::ReadResourceRequestParams,
581        _context: RequestContext<RoleServer>,
582    ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
583        let ledger = self.ledger.read().await;
584        if let Some(contents) = resources::read_resource(&request.uri, &ledger) {
585            return Ok(rmcp::model::ReadResourceResult::new(contents));
586        }
587
588        // GH #1418: agents sometimes call resources/read with file:// URIs
589        // instead of ctx_read — serve the file directly rather than erroring.
590        let session = self.session.read().await;
591        let root = session.project_root.as_deref();
592        match file_resource::read_file_resource(&request.uri, root, &session.extra_roots) {
593            Ok(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
594            Err(file_resource::FileResourceError::NotAFilePath) => {
595                Err(rmcp::ErrorData::resource_not_found(
596                    resources::unknown_resource_message(&request.uri),
597                    None,
598                ))
599            }
600            Err(e) => Err(rmcp::ErrorData::resource_not_found(e.to_string(), None)),
601        }
602    }
603
604    async fn call_tool(
605        &self,
606        request: CallToolRequestParams,
607        context: RequestContext<RoleServer>,
608    ) -> Result<CallToolResult, ErrorData> {
609        use std::panic::AssertUnwindSafe;
610
611        let progress_token = request
612            .meta
613            .as_ref()
614            .and_then(rmcp::model::Meta::get_progress_token);
615        if let Some(ref token) = progress_token {
616            let sender =
617                crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
618            *self
619                .progress_sender
620                .lock()
621                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
622        }
623
624        let tool_name_for_panic = request.name.as_ref().to_string();
625        let args_fp_for_panic = request
626            .arguments
627            .as_ref()
628            .map(|a| {
629                crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
630                    a.clone(),
631                ))
632            })
633            .unwrap_or_default();
634
635        let loop_detector = self.loop_detector.clone();
636        let ct = context.ct.clone();
637
638        match AssertUnwindSafe(self.call_tool_guarded(request))
639            .catch_unwind()
640            .await
641        {
642            Ok(result) => {
643                // #1265: If the client cancelled this request while the tool was
644                // executing, drop the result instead of replying to a stale ID.
645                if ct.is_cancelled() {
646                    tracing::warn!(
647                        "tool '{tool_name_for_panic}' completed after client cancellation — dropping result"
648                    );
649                    return Err(ErrorData::internal_error(
650                        "request was cancelled by client",
651                        None,
652                    ));
653                }
654                result
655            }
656            Err(panic_payload) => {
657                let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
658                    (*s).to_string()
659                } else if let Some(s) = panic_payload.downcast_ref::<String>() {
660                    s.clone()
661                } else {
662                    "unknown".to_string()
663                };
664                tracing::error!("call_tool panicked: {detail}");
665
666                if let Ok(mut detector) =
667                    tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
668                        .await
669                {
670                    detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
671                }
672
673                Ok(CallToolResult::error(vec![ContentBlock::text(
674                    "ERROR: lean-ctx internal error. The MCP server is still running. \
675                     Please retry or use a different approach."
676                        .to_string(),
677                )]))
678            }
679        }
680    }
681
682    async fn on_roots_list_changed(
683        &self,
684        _context: rmcp::service::NotificationContext<RoleServer>,
685    ) {
686        tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
687        self.roots_resolved
688            .store(false, std::sync::atomic::Ordering::Relaxed);
689        // Fresh client signal — restore the transient-failure retry budget.
690        self.roots_list_attempts
691            .store(0, std::sync::atomic::Ordering::Relaxed);
692    }
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698
699    /// lean-ctx emits `notifications/tools/list_changed` whenever a tool call
700    /// mutates the dynamic tool set. The capability MUST be advertised on every
701    /// client surface (resources/prompts on or off) — otherwise a strict client
702    /// such as Claude Code rejects the undeclared notification and drops the whole
703    /// tool set ("connected, but tools not registered"). Regression guard for #688.
704    #[test]
705    fn server_capabilities_always_declare_tool_list_changed() {
706        for (resources, prompts) in [(true, true), (true, false), (false, true), (false, false)] {
707            let caps = server_capabilities(resources, prompts);
708            let tools = caps.tools.expect("tools capability must be advertised");
709            assert_eq!(
710                tools.list_changed,
711                Some(true),
712                "listChanged must be Some(true) for (resources={resources}, prompts={prompts})"
713            );
714        }
715    }
716
717    /// The `list_tools` panic guard serves `lazy_tool_defs()`; it must contain the
718    /// essentials so an internal panic never leaves the agent tool-less (which is
719    /// indistinguishable from "MCP totally failed"). Regression guard for #688.
720    #[test]
721    fn lazy_core_fallback_is_never_empty() {
722        let _guard = crate::core::data_dir::isolated_data_dir();
723        let defs = crate::tool_defs::lazy_tool_defs();
724        assert!(!defs.is_empty(), "lazy-core fallback must not be empty");
725        for essential in ["ctx_read", "ctx_shell", "ctx_call"] {
726            assert!(
727                defs.iter().any(|t| t.name.as_ref() == essential),
728                "lazy-core fallback must include {essential}"
729            );
730        }
731    }
732}