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
47fn suppress_initialize_instructions(client_id: &str) -> bool {
48    let cfg = crate::core::config::Config::load();
49
50    cfg.declines_rule_steering() || matches!(client_id, "antigravity" | "gemini-cli")
51}
52impl ServerHandler for LeanCtxServer {
53    fn get_info(&self) -> ServerInfo {
54        let capabilities = server_capabilities(true, true);
55
56        let instructions = crate::instructions::build_instructions(CrpMode::effective());
57
58        InitializeResult::new(capabilities)
59            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
60            .with_instructions(instructions)
61    }
62
63    async fn initialize(
64        &self,
65        request: InitializeRequestParams,
66        context: RequestContext<RoleServer>,
67    ) -> Result<InitializeResult, ErrorData> {
68        let name = request.client_info.name.clone();
69        tracing::info!("MCP client connected: {:?}", name);
70        *self.client_name.write().await = name.clone();
71        *self.peer.write().await = Some(context.peer.clone());
72
73        if self.session_mode != crate::tools::SessionMode::Shared {
74            crate::core::budget_tracker::BudgetTracker::global().reset();
75            if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
76                let radar = data_dir.join("context_radar.jsonl");
77                if radar.exists() {
78                    let prev = data_dir.join("context_radar.prev.jsonl");
79                    let _ = std::fs::rename(&radar, &prev);
80                }
81            }
82        }
83
84        let has_roots = request.capabilities.roots.is_some();
85        self.has_client_roots
86            .store(has_roots, std::sync::atomic::Ordering::Relaxed);
87        if has_roots {
88            tracing::info!("Client supports MCP roots/list — will resolve on first tool call");
89        }
90
91        let env_root = roots::root_from_env().or_else(roots::root_from_workspace_env);
92        let derived_root = derive_project_root_from_cwd();
93        let effective_root = env_root.or(derived_root);
94
95        let cwd_str = std::env::current_dir()
96            .ok()
97            .map(|p| p.to_string_lossy().to_string())
98            .unwrap_or_default();
99        {
100            let mut session = self.session.write().await;
101            if !cwd_str.is_empty() {
102                session.shell_cwd = Some(cwd_str.clone());
103            }
104            if let Some(ref root) = effective_root {
105                session.project_root = Some(root.clone());
106                tracing::info!("Project root set to: {root}");
107                // Cursor multi-root: register sibling workspace folders as extra
108                // trusted roots so explicit cross-folder paths are not rejected
109                // by the path jail (#699).
110                for other in roots::workspace_roots_from_env() {
111                    if &other != root && !session.extra_roots.contains(&other) {
112                        session.extra_roots.push(other);
113                    }
114                }
115            } else if let Some(ref root) = session.project_root {
116                // A previously persisted session may carry a contaminated root
117                // (e.g. HOME from an older build or a client that reported HOME
118                // as its workspace). Drop it unless it is a real, safe project
119                // dir — otherwise PROJECT MEMORY leaks across projects.
120                let root_path = std::path::Path::new(root);
121                let root_has_marker = has_project_marker(root_path);
122                let root_str = root_path.to_string_lossy();
123                let root_suspicious = crate::core::pathutil::is_broad_or_unsafe_root(root_path)
124                    || root_str.contains("/var/folders/")
125                    || root_str.contains("/tmp/")
126                    || root_str.contains("/.lmstudio")
127                    || root_str.contains("\\AppData\\Local\\Temp")
128                    || root_str.contains("\\Temp\\")
129                    || root_str.contains("\\.lmstudio");
130                if root_suspicious && !root_has_marker {
131                    tracing::info!("Dropping suspicious persisted project root: {root}");
132                    session.project_root = None;
133                }
134            }
135            let cfg_extra = crate::core::config::Config::load().extra_roots;
136            if !cfg_extra.is_empty() {
137                let existing: std::collections::HashSet<_> =
138                    session.extra_roots.iter().cloned().collect();
139                for r in cfg_extra {
140                    if !existing.contains(&r) {
141                        session.extra_roots.push(r);
142                    }
143                }
144            }
145            session.refresh_handoff_context();
146
147            if self.session_mode == crate::tools::SessionMode::Shared {
148                if let Some(ref root) = session.project_root
149                    && let Some(ref rt) = self.context_os
150                {
151                    rt.shared_sessions.persist_best_effort(
152                        root,
153                        &self.workspace_id,
154                        &self.channel_id,
155                        &session,
156                    );
157                    rt.metrics.record_session_persisted();
158                }
159            } else if let Err(e) = session.save() {
160                tracing::warn!("lean-ctx: failed to persist session state: {e}");
161            }
162        }
163
164        // Indices are warmed lazily on first use of a tool that needs them
165        // (issue #152), not eagerly here — a session that only uses
166        // ctx_read/ctx_shell/ctx_tree must not pay a full graph + BM25 scan.
167        // See `index_orchestrator::ensure_warm_for_tool`, driven from dispatch.
168
169        let agent_name = name.clone();
170        let agent_root = effective_root.clone().unwrap_or_default();
171        let agent_id_handle = self.agent_id.clone();
172        let presence_agent_id_handle = self.presence_agent_id.clone();
173        let presence_role_handle = self.presence_role.clone();
174        let presence_read_only_handle = self.presence_read_only.clone();
175        tokio::task::spawn_blocking(move || {
176            if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
177                return;
178            }
179
180            // Avoid startup stampedes when multiple agent sessions initialize at once.
181            // These are best-effort maintenance tasks; it's fine to skip if another
182            // lean-ctx instance is already doing them.
183            let maintenance = crate::core::startup_guard::try_acquire_lock(
184                "startup-maintenance",
185                std::time::Duration::from_secs(2),
186                std::time::Duration::from_mins(2),
187            );
188            if maintenance.is_some() {
189                if let Some(home) = dirs::home_dir() {
190                    startup_rule_maintenance_at_home(&home);
191                    // The on-demand SKILL.md belongs to the same steering surface
192                    // as the rules block: the session-start heal writes rules for
193                    // every detected client, so a fresh machine that never ran
194                    // `lean-ctx setup` otherwise carries a permanent doctor
195                    // warning ("SKILL.md not installed"). Idempotent + gated on
196                    // the same opt-outs as setup (rules_injection=off inside,
197                    // auto_inject_skills=Some(false) here).
198                    if crate::core::config::Config::load()
199                        .setup
200                        .should_inject_skills()
201                    {
202                        let _ = crate::rules_inject::install_all_skills(&home);
203                    }
204                }
205                crate::hooks::refresh_installed_hooks();
206                crate::core::version_check::check_background();
207                // Enforce the on-disk budget: prune accumulated quarantined BM25
208                // indexes and cap the archive FTS DB (#2364). Silent (tracing
209                // only) so it never corrupts the MCP stdio protocol.
210                let _ = crate::core::storage_maintenance::run_quiet();
211            }
212            drop(maintenance);
213
214            if !agent_root.is_empty() {
215                let heuristic_role = match agent_name.to_lowercase().as_str() {
216                    n if n.contains("cursor") => Some("coder"),
217                    n if n.contains("claude") => Some("coder"),
218                    n if n.contains("codebuddy") => Some("coder"),
219                    n if n.contains("codex") => Some("coder"),
220                    n if n.contains("antigravity") || n.contains("gemini") => Some("coder"),
221                    n if n.contains("review") => Some("reviewer"),
222                    n if n.contains("test") => Some("debugger"),
223                    _ => None,
224                };
225                let env_role = std::env::var("LEAN_CTX_ROLE")
226                    .or_else(|_| std::env::var("LEAN_CTX_AGENT_ROLE"))
227                    .ok();
228                let effective_role = env_role.as_deref().or(heuristic_role).unwrap_or("coder");
229
230                let _ = crate::core::roles::set_active_role_with_source(effective_role, true);
231                // #1766: remember the resolved role so the fail-closed presence
232                // retry re-registers with it, not the `context-engine` placeholder.
233                if let Ok(mut guard) = presence_role_handle.try_write() {
234                    *guard = Some(effective_role.to_string());
235                }
236
237                let registration = crate::core::agents::AgentRegistry::mutate_locked(|registry| {
238                    registry.cleanup_stale(24);
239                    registry.register("mcp", Some(effective_role), &agent_root)
240                })
241                .and_then(|(_, id)| id);
242                let id = match registration {
243                    Ok(id) => {
244                        presence_read_only_handle
245                            .store(false, std::sync::atomic::Ordering::Relaxed);
246                        Some(id)
247                    }
248                    // #1765: over the mutating cap the session is admitted
249                    // read-only instead of losing every tool — reads included —
250                    // until an unrelated session's lease lapses.
251                    Err(error)
252                        if crate::core::agents::AgentRegistry::is_mutating_capacity_error(
253                            &error,
254                        ) =>
255                    {
256                        tracing::warn!(
257                            "lean-ctx: {error}; admitting {effective_role} session read-only"
258                        );
259                        match crate::core::agents::AgentRegistry::admit_read_only_presence(
260                            &agent_root,
261                            effective_role,
262                        ) {
263                            Ok(id) => {
264                                presence_read_only_handle
265                                    .store(true, std::sync::atomic::Ordering::Relaxed);
266                                Some(id)
267                            }
268                            Err(error) => {
269                                tracing::warn!("lean-ctx: read-only admission failed: {error}");
270                                None
271                            }
272                        }
273                    }
274                    Err(error) => {
275                        tracing::warn!("lean-ctx: agent registration failed: {error}");
276                        None
277                    }
278                };
279                if let (Some(id), Ok(mut guard)) = (id.as_ref(), agent_id_handle.try_write()) {
280                    *guard = Some(id.clone());
281                }
282                if let (Some(id), Ok(mut guard)) = (id, presence_agent_id_handle.try_write()) {
283                    *guard = Some(id);
284                }
285            }
286        });
287
288        let client_caps = crate::core::client_capabilities::ClientMcpCapabilities::detect(&name);
289        tracing::info!("Client capabilities: {}", client_caps.format_summary());
290
291        {
292            let cfg = crate::core::config::Config::load();
293            let cats = cfg.default_tool_categories_effective();
294            dynamic_tools::init_from_config(&cats);
295        }
296
297        if let Some(max) = client_caps.max_tools
298            && let Ok(mut dt) = dynamic_tools::global().lock()
299        {
300            dt.set_supports_list_changed(true);
301            if max < 100 {
302                dt.unload_category(dynamic_tools::ToolCategory::Debug);
303                dt.unload_category(dynamic_tools::ToolCategory::Memory);
304            }
305        } else if client_caps.dynamic_tools
306            && let Ok(mut dt) = dynamic_tools::global().lock()
307        {
308            dt.set_supports_list_changed(true);
309        }
310
311        crate::core::client_capabilities::set_detected(&client_caps);
312
313        let session = self.session.read().await.clone();
314
315        let capabilities = server_capabilities(client_caps.resources, client_caps.prompts);
316
317        let result = InitializeResult::new(capabilities)
318            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")));
319
320        // GH #1447: Antigravity/Gemini CLI disconnect when the initialize
321        // response contains `instructions`. The MCP spec marks it optional,
322        // but these clients fail on any unexpected field in the JSON envelope.
323        //
324        // GH #1599/#1758: both `rules_injection = "off"` and an explicit
325        // `setup.auto_inject_rules = false` decline lean-ctx rule steering.
326        // The initialize `instructions` field is that same steering block
327        // delivered over a different channel, so the central policy predicate
328        // must govern this surface too.
329        if suppress_initialize_instructions(client_caps.client_id.as_str()) {
330            Ok(result)
331        } else {
332            let instructions = crate::instructions::build_instructions_with_client_and_session(
333                CrpMode::effective(),
334                &name,
335                &session,
336            );
337            Ok(result.with_instructions(instructions))
338        }
339    }
340
341    async fn list_tools(
342        &self,
343        _request: Option<PaginatedRequestParams>,
344        _context: RequestContext<RoleServer>,
345    ) -> Result<ListToolsResult, ErrorData> {
346        use crate::server::tool_visibility::CandidateSet;
347        // Panic guard (mirrors call_tool): a panic while filtering the registry /
348        // touching the dynamic-tools mutex must not kill the rmcp request task.
349        use std::panic::AssertUnwindSafe;
350        let computed = AssertUnwindSafe(async {
351            let cfg = crate::core::config::Config::load();
352            let disabled = cfg.disabled_tools_effective();
353            let raw_profile = cfg.tool_profile_effective();
354            let tool_profile = crate::server::tool_visibility::resolve_auto_profile(&raw_profile);
355            crate::server::tool_visibility::record_auto_turn();
356            // A profile is "explicit" when the user opted into one (config field,
357            // env var, or a custom tools list). Without an explicit choice we keep
358            // the token-lean lazy core set as the default. With one, the profile is
359            // authoritative and resolves against the full registry, so e.g.
360            // `standard` advertises its full balanced set instead of the accidental
361            // `core ∩ standard` intersection.
362            let explicit_profile = crate::server::tool_visibility::explicit_profile(&cfg);
363
364            let client = self.client_name.read().await.clone();
365            let hook_covered = is_client_hook_covered(&client);
366
367            let candidate = crate::server::tool_visibility::candidate_set(
368                &crate::server::tool_visibility::CandidateInputs {
369                    full_mode: crate::tool_defs::is_full_mode(),
370                    unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
371                    explicit_profile,
372                    hook_covered,
373                },
374            );
375            let all_tools = match candidate {
376                CandidateSet::Full | CandidateSet::ProfileAuthoritative => {
377                    if let Some(ref reg) = self.registry {
378                        reg.tool_defs()
379                    } else {
380                        // Unreachable in production: every constructor sets a registry
381                        // (locked by `production_server_always_has_registry`). If it
382                        // ever fires, the advertised static defs can drift from what
383                        // dispatch (which needs the registry) can execute — make it loud.
384                        tracing::error!(
385                            "list_tools served WITHOUT a tool registry (full mode) — advertising \
386                             static granular defs that dispatch cannot run; tools may drift from handlers."
387                        );
388                        crate::tool_defs::granular_tool_defs()
389                    }
390                }
391                CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
392                // GH #1474: ShadowOnly is never returned anymore; treat as LazyCore.
393                CandidateSet::ShadowOnly |
394                CandidateSet::LazyCore => {
395                    if let Some(ref reg) = self.registry {
396                        let core_names = crate::tool_defs::core_tool_names();
397                        reg.tool_defs()
398                            .into_iter()
399                            .filter(|t| core_names.contains(&t.name.as_ref()))
400                            .collect()
401                    } else {
402                        // Unreachable in production (see above); loud if it ever fires.
403                        tracing::error!(
404                            "list_tools served WITHOUT a tool registry (lazy mode) — advertising \
405                             static lazy defs that dispatch cannot run; tools may drift from handlers."
406                        );
407                        crate::tool_defs::lazy_tool_defs()
408                    }
409                }
410            };
411            let quirks = crate::server::tool_visibility::ClientQuirks::resolve(&client, candidate);
412
413            let active_role = crate::core::roles::active_role();
414            let tools: Vec<_> = all_tools
415                .into_iter()
416                .filter(|t| {
417                    let name = t.name.as_ref();
418                    crate::server::tool_visibility::is_tool_visible(
419                        name,
420                        &tool_profile,
421                        &disabled,
422                        quirks,
423                        active_role.is_tool_allowed(name),
424                    )
425                })
426                .collect();
427
428            // Guarantee the universal invoker is advertised in non-full mode. Lazy
429            // and profile filtering hide most tools; without ctx_call a static-list
430            // client (one that only calls advertised tools) could not reach them.
431            // ctx_call enforces the same role/workflow gates on the inner tool.
432            let tools = {
433                use crate::server::tool_visibility::INVOKER;
434                let mut tools = tools;
435                let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
436                if crate::server::tool_visibility::needs_invoker(
437                    crate::tool_defs::is_full_mode(),
438                    already,
439                    active_role.is_tool_allowed(INVOKER),
440                    &disabled,
441                ) && let Some(def) = self.registry.as_ref().and_then(|reg| {
442                    reg.tool_defs()
443                        .into_iter()
444                        .find(|t| t.name.as_ref() == INVOKER)
445                }) {
446                    tools.push(def);
447                }
448                tools
449            };
450
451            let tools = {
452                let Ok(dyn_state) = dynamic_tools::global().lock() else {
453                    tracing::warn!(
454                        "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
455                    );
456                    return Ok(ListToolsResult {
457                        tools,
458                        ..Default::default()
459                    });
460                };
461                // The lazy category gate (load tools on demand for dynamic_tools
462                // clients) only applies to the *default* lean-core surface. When the
463                // user opted into an explicit profile, that profile IS the
464                // authoritative surface — gating it by category would silently drop
465                // profile-enabled tools like Standard's ctx_architecture /
466                // ctx_semantic_search for Codex et al. (#358), so the advertised set
467                // would no longer match `lean-ctx tools show`.
468                if crate::server::tool_visibility::category_gate_applies(
469                    dyn_state.supports_list_changed(),
470                    explicit_profile,
471                ) {
472                    tools
473                        .into_iter()
474                        .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
475                        .collect()
476                } else {
477                    tools
478                }
479            };
480
481            let tools = {
482                let active = self.workflow.read().await.clone();
483                if let Some(run) = active {
484                    if run.current == "done" || is_workflow_stale(&run) {
485                        let mut wf = self.workflow.write().await;
486                        *wf = None;
487                        let _ = crate::core::workflow::clear_active();
488                    } else if let Some(state) = run.spec.state(&run.current)
489                        && let Some(allowed) = &state.allowed_tools
490                    {
491                        let mut allow: std::collections::HashSet<&str> =
492                            allowed.iter().map(std::string::String::as_str).collect();
493                        for passthrough in WORKFLOW_PASSTHROUGH_TOOLS {
494                            allow.insert(passthrough);
495                        }
496                        return Ok(ListToolsResult {
497                            tools: tools
498                                .into_iter()
499                                .filter(|t| allow.contains(t.name.as_ref()))
500                                .collect(),
501                            ..Default::default()
502                        });
503                    }
504                }
505                tools
506            };
507
508            let tools = {
509                let cfg = crate::core::config::Config::load();
510                let level = crate::core::config::CompressionLevel::effective(&cfg);
511                let mode =
512                    crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(
513                        &level,
514                    );
515                if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
516                    tools
517                } else {
518                    tools
519                        .into_iter()
520                        .map(|mut t| {
521                            let compressed = crate::core::terse::mcp_compress::compress_description(
522                                t.name.as_ref(),
523                                t.description.as_deref().unwrap_or(""),
524                                mode,
525                            );
526                            t.description = Some(compressed.into());
527                            t
528                        })
529                        .collect()
530                }
531            };
532
533
534            // R28: Kernel schema optimization — budget-aware description compression.
535            let tools = crate::server::schema_hook::optimize_tools(tools, &client);
536            // #1008: When ctx_patch is hidden for this client, scrub references
537            // from other tools' descriptions so the LLM never sees the name and
538            // won't attempt to call it. Replace with ctx_edit (visible alternative).
539            let tools = if quirks.hide_ctx_patch {
540                tools
541                    .into_iter()
542                    .map(|mut t| {
543                        if let Some(ref desc) = t.description
544                            && desc.contains("ctx_patch")
545                        {
546                            t.description =
547                                Some(desc.replace("ctx_patch", "ctx_edit").into());
548                        }
549                        t
550                    })
551                    .collect()
552            } else {
553                tools
554            };
555
556            // Plan mode: restrict advertised tools to the curated read-only set.
557            let tools = {
558                use crate::tools::InteractionMode;
559                let mode = InteractionMode::from_u8(
560                    self.interaction_mode
561                        .load(std::sync::atomic::Ordering::Relaxed),
562                );
563                if mode == InteractionMode::Plan {
564                    let plan_set =
565                        crate::core::editor_registry::plan_mode::plan_mode_tools();
566                    tools
567                        .into_iter()
568                        .filter(|t| {
569                            let n = t.name.as_ref();
570                            plan_set.contains(&n) || n == "ctx_call"
571                        })
572                        .collect()
573                } else {
574                    tools
575                }
576            };
577
578            Ok(ListToolsResult {
579                tools,
580                ..Default::default()
581            })
582        })
583        .catch_unwind()
584        .await;
585        computed.unwrap_or_else(|_| {
586            // A panic here must NOT leave the agent tool-less — that is
587            // indistinguishable from "MCP totally failed" and gives the user no
588            // recovery path. Fall back to the static lazy-core defs (a pure,
589            // panic-free function) so ctx_read/ctx_shell/ctx_call stay available
590            // even if the dynamic/registry path blew up.
591            tracing::error!(
592                "list_tools panicked; serving the static lazy-core tool set as a fallback"
593            );
594            Ok(ListToolsResult {
595                tools: crate::tool_defs::lazy_tool_defs(),
596                ..Default::default()
597            })
598        })
599    }
600
601    fn list_prompts(
602        &self,
603        _request: Option<PaginatedRequestParams>,
604        _context: RequestContext<RoleServer>,
605    ) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, ErrorData>> {
606        std::future::ready(Ok(rmcp::model::ListPromptsResult::with_all_items(
607            prompts::list_prompts(),
608        )))
609    }
610
611    async fn get_prompt(
612        &self,
613        request: rmcp::model::GetPromptRequestParams,
614        _context: RequestContext<RoleServer>,
615    ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
616        let ledger = self.ledger.read().await;
617        match prompts::get_prompt(&request, &ledger) {
618            Some(result) => Ok(result),
619            None => Err(ErrorData::invalid_params(
620                format!("Unknown prompt: {}", request.name),
621                None,
622            )),
623        }
624    }
625
626    fn list_resources(
627        &self,
628        _request: Option<PaginatedRequestParams>,
629        _context: RequestContext<RoleServer>,
630    ) -> impl Future<Output = Result<rmcp::model::ListResourcesResult, rmcp::ErrorData>> {
631        std::future::ready(Ok(rmcp::model::ListResourcesResult::with_all_items(
632            resources::list_resources(),
633        )))
634    }
635
636    async fn read_resource(
637        &self,
638        request: rmcp::model::ReadResourceRequestParams,
639        _context: RequestContext<RoleServer>,
640    ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
641        let ledger = self.ledger.read().await;
642        if let Some(contents) = resources::read_resource(&request.uri, &ledger) {
643            return Ok(rmcp::model::ReadResourceResult::new(contents));
644        }
645
646        // GH #1418: agents sometimes call resources/read with file:// URIs
647        // instead of ctx_read — serve the file directly rather than erroring.
648        let session = self.session.read().await;
649        let root = session.project_root.as_deref();
650        match file_resource::read_file_resource(&request.uri, root, &session.extra_roots) {
651            Ok(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
652            Err(file_resource::FileResourceError::NotAFilePath) => {
653                Err(rmcp::ErrorData::resource_not_found(
654                    resources::unknown_resource_message(&request.uri),
655                    None,
656                ))
657            }
658            Err(e) => Err(rmcp::ErrorData::resource_not_found(e.to_string(), None)),
659        }
660    }
661
662    async fn call_tool(
663        &self,
664        request: CallToolRequestParams,
665        context: RequestContext<RoleServer>,
666    ) -> Result<CallToolResult, ErrorData> {
667        use std::panic::AssertUnwindSafe;
668
669        let progress_token = request
670            .meta
671            .as_ref()
672            .and_then(rmcp::model::Meta::get_progress_token);
673        if let Some(ref token) = progress_token {
674            let sender =
675                crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
676            *self
677                .progress_sender
678                .lock()
679                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
680        }
681
682        let tool_name_for_panic = request.name.as_ref().to_string();
683        let args_fp_for_panic = request
684            .arguments
685            .as_ref()
686            .map(|a| {
687                crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
688                    a.clone(),
689                ))
690            })
691            .unwrap_or_default();
692
693        let loop_detector = self.loop_detector.clone();
694        let ct = context.ct.clone();
695
696        // #1781: scope the request's cancellation token for the whole dispatch
697        // so a tool that waits on a child process can observe an abandoned call
698        // instead of holding its blocking-pool slot until its own soft cap.
699        match AssertUnwindSafe(
700            crate::server::tool_trait::REQUEST_CT
701                .scope(ct.clone(), self.call_tool_guarded(request)),
702        )
703        .catch_unwind()
704        .await
705        {
706            Ok(result) => {
707                // #1265: If the client cancelled this request while the tool was
708                // executing, drop the result instead of replying to a stale ID.
709                if ct.is_cancelled() {
710                    tracing::warn!(
711                        "tool '{tool_name_for_panic}' completed after client cancellation — dropping result"
712                    );
713                    return Err(ErrorData::internal_error(
714                        "request was cancelled by client",
715                        None,
716                    ));
717                }
718                result
719            }
720            Err(panic_payload) => {
721                let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
722                    (*s).to_string()
723                } else if let Some(s) = panic_payload.downcast_ref::<String>() {
724                    s.clone()
725                } else {
726                    "unknown".to_string()
727                };
728                tracing::error!("call_tool panicked: {detail}");
729
730                if let Ok(mut detector) =
731                    tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
732                        .await
733                {
734                    detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
735                }
736
737                Ok(CallToolResult::error(vec![ContentBlock::text(
738                    "ERROR: lean-ctx internal error. The MCP server is still running. \
739                     Please retry or use a different approach."
740                        .to_string(),
741                )]))
742            }
743        }
744    }
745
746    async fn on_roots_list_changed(
747        &self,
748        _context: rmcp::service::NotificationContext<RoleServer>,
749    ) {
750        tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
751        self.roots_resolved
752            .store(false, std::sync::atomic::Ordering::Relaxed);
753        // Fresh client signal — restore the transient-failure retry budget.
754        self.roots_list_attempts
755            .store(0, std::sync::atomic::Ordering::Relaxed);
756    }
757}
758
759fn startup_rule_maintenance_at_home(home: &std::path::Path) {
760    let cfg = crate::core::config::Config::load();
761    if cfg.declines_rule_steering() {
762        return;
763    }
764    let _ = crate::rules_inject::inject_all_rules(home);
765}
766
767#[cfg(test)]
768mod tests {
769    use super::*;
770
771    #[test]
772    fn initialize_instructions_respect_explicit_auto_inject_false() {
773        let _guard = crate::core::data_dir::test_env_lock();
774        let tmp = tempfile::tempdir().expect("tempdir");
775        let config_dir = tmp.path().join("config");
776
777        std::fs::create_dir_all(&config_dir).unwrap();
778        std::fs::write(
779            config_dir.join("config.toml"),
780            "[setup]\nauto_inject_rules = false\n",
781        )
782        .unwrap();
783
784        let _config_guard = crate::setup::EnvVarGuard::set(
785            "LEAN_CTX_CONFIG_DIR",
786            config_dir.to_string_lossy().as_ref(),
787        );
788        let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
789
790        assert!(
791            suppress_initialize_instructions("cursor"),
792            "explicit auto_inject_rules=false declines rule steering and must suppress MCP initialize instructions"
793        );
794    }
795
796    #[test]
797    fn initialize_instructions_preserve_default_auto_behavior() {
798        let _guard = crate::core::data_dir::test_env_lock();
799        let tmp = tempfile::tempdir().expect("tempdir");
800        let config_dir = tmp.path().join("config");
801
802        std::fs::create_dir_all(&config_dir).unwrap();
803
804        let _config_guard = crate::setup::EnvVarGuard::set(
805            "LEAN_CTX_CONFIG_DIR",
806            config_dir.to_string_lossy().as_ref(),
807        );
808        let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
809
810        assert!(
811            !suppress_initialize_instructions("cursor"),
812            "default auto_inject_rules=None must preserve initialize instructions"
813        );
814    }
815
816    #[test]
817    fn initialize_instructions_preserve_explicit_true_behavior() {
818        let _guard = crate::core::data_dir::test_env_lock();
819        let tmp = tempfile::tempdir().expect("tempdir");
820        let config_dir = tmp.path().join("config");
821
822        std::fs::create_dir_all(&config_dir).unwrap();
823        std::fs::write(
824            config_dir.join("config.toml"),
825            "[setup]\nauto_inject_rules = true\n",
826        )
827        .unwrap();
828
829        let _config_guard = crate::setup::EnvVarGuard::set(
830            "LEAN_CTX_CONFIG_DIR",
831            config_dir.to_string_lossy().as_ref(),
832        );
833        let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
834
835        assert!(
836            !suppress_initialize_instructions("cursor"),
837            "explicit auto_inject_rules=true must preserve initialize instructions"
838        );
839    }
840
841    #[test]
842    fn initialize_instructions_respect_rules_injection_off() {
843        let _guard = crate::core::data_dir::test_env_lock();
844        let tmp = tempfile::tempdir().expect("tempdir");
845        let config_dir = tmp.path().join("config");
846
847        std::fs::create_dir_all(&config_dir).unwrap();
848
849        let _config_guard = crate::setup::EnvVarGuard::set(
850            "LEAN_CTX_CONFIG_DIR",
851            config_dir.to_string_lossy().as_ref(),
852        );
853        let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "off");
854
855        assert!(
856            suppress_initialize_instructions("cursor"),
857            "rules_injection=off must continue suppressing initialize instructions"
858        );
859    }
860
861    #[test]
862    fn initialize_instructions_keep_client_compatibility_exceptions() {
863        let _guard = crate::core::data_dir::test_env_lock();
864        let tmp = tempfile::tempdir().expect("tempdir");
865        let config_dir = tmp.path().join("config");
866
867        std::fs::create_dir_all(&config_dir).unwrap();
868
869        let _config_guard = crate::setup::EnvVarGuard::set(
870            "LEAN_CTX_CONFIG_DIR",
871            config_dir.to_string_lossy().as_ref(),
872        );
873        let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
874
875        assert!(suppress_initialize_instructions("antigravity"));
876        assert!(suppress_initialize_instructions("gemini-cli"));
877    }
878    #[test]
879    fn startup_maintenance_respects_explicit_auto_inject_false() {
880        let _guard = crate::core::data_dir::test_env_lock();
881        let tmp = tempfile::tempdir().expect("tempdir");
882        let home = tmp.path().join("home");
883        let config_dir = tmp.path().join("config");
884
885        std::fs::create_dir_all(home.join(".cursor")).unwrap();
886        std::fs::create_dir_all(&config_dir).unwrap();
887
888        std::fs::write(
889            home.join(".cursor/mcp.json"),
890            r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
891        )
892        .unwrap();
893
894        std::fs::write(
895            config_dir.join("config.toml"),
896            "[setup]\nauto_inject_rules = false\n",
897        )
898        .unwrap();
899
900        let _config_guard = crate::setup::EnvVarGuard::set(
901            "LEAN_CTX_CONFIG_DIR",
902            config_dir.to_string_lossy().as_ref(),
903        );
904        let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
905        let _scope_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
906
907        startup_rule_maintenance_at_home(&home);
908
909        let rules = home.join(".cursor/rules/lean-ctx.mdc");
910
911        assert!(
912            !rules.exists(),
913            "startup maintenance must not write Cursor rules when setup.auto_inject_rules=false"
914        );
915    }
916
917    #[test]
918    fn automatic_rule_maintenance_allows_default_startup_write() {
919        let _guard = crate::core::data_dir::test_env_lock();
920        let tmp = tempfile::tempdir().expect("tempdir");
921        let home = tmp.path().join("home");
922        let config_dir = tmp.path().join("config");
923
924        std::fs::create_dir_all(home.join(".cursor")).unwrap();
925        std::fs::create_dir_all(&config_dir).unwrap();
926
927        std::fs::write(
928            home.join(".cursor/mcp.json"),
929            r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
930        )
931        .unwrap();
932
933        let _config_guard = crate::setup::EnvVarGuard::set(
934            "LEAN_CTX_CONFIG_DIR",
935            config_dir.to_string_lossy().as_ref(),
936        );
937        let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
938        let _scope_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
939
940        startup_rule_maintenance_at_home(&home);
941
942        assert!(
943            home.join(".cursor/rules/lean-ctx.mdc").exists(),
944            "default auto_inject_rules=None must preserve zero-config startup rule maintenance"
945        );
946    }
947
948    #[test]
949    fn automatic_rule_maintenance_allows_explicit_true_startup_write() {
950        let _guard = crate::core::data_dir::test_env_lock();
951        let tmp = tempfile::tempdir().expect("tempdir");
952        let home = tmp.path().join("home");
953        let config_dir = tmp.path().join("config");
954
955        std::fs::create_dir_all(home.join(".cursor")).unwrap();
956        std::fs::create_dir_all(&config_dir).unwrap();
957
958        std::fs::write(
959            home.join(".cursor/mcp.json"),
960            r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
961        )
962        .unwrap();
963
964        std::fs::write(
965            config_dir.join("config.toml"),
966            "[setup]\nauto_inject_rules = true\n",
967        )
968        .unwrap();
969
970        let _config_guard = crate::setup::EnvVarGuard::set(
971            "LEAN_CTX_CONFIG_DIR",
972            config_dir.to_string_lossy().as_ref(),
973        );
974        let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
975        let _scope_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
976
977        startup_rule_maintenance_at_home(&home);
978
979        assert!(
980            home.join(".cursor/rules/lean-ctx.mdc").exists(),
981            "explicit auto_inject_rules=true must preserve startup rule maintenance"
982        );
983    }
984    /// lean-ctx emits `notifications/tools/list_changed` whenever a tool call
985    /// mutates the dynamic tool set. The capability MUST be advertised on every
986    /// client surface (resources/prompts on or off) — otherwise a strict client
987    /// such as Claude Code rejects the undeclared notification and drops the whole
988    /// tool set ("connected, but tools not registered"). Regression guard for #688.
989    #[test]
990    fn server_capabilities_always_declare_tool_list_changed() {
991        for (resources, prompts) in [(true, true), (true, false), (false, true), (false, false)] {
992            let caps = server_capabilities(resources, prompts);
993            let tools = caps.tools.expect("tools capability must be advertised");
994            assert_eq!(
995                tools.list_changed,
996                Some(true),
997                "listChanged must be Some(true) for (resources={resources}, prompts={prompts})"
998            );
999        }
1000    }
1001
1002    /// The `list_tools` panic guard serves `lazy_tool_defs()`; it must contain the
1003    /// essentials so an internal panic never leaves the agent tool-less (which is
1004    /// indistinguishable from "MCP totally failed"). Regression guard for #688.
1005    #[test]
1006    fn lazy_core_fallback_is_never_empty() {
1007        let _guard = crate::core::data_dir::isolated_data_dir();
1008        let defs = crate::tool_defs::lazy_tool_defs();
1009        assert!(!defs.is_empty(), "lazy-core fallback must not be empty");
1010        for essential in ["ctx_read", "ctx_shell", "ctx_call"] {
1011            assert!(
1012                defs.iter().any(|t| t.name.as_ref() == essential),
1013                "lazy-core fallback must include {essential}"
1014            );
1015        }
1016    }
1017}