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