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