Skip to main content

lean_ctx/server/
server_handler.rs

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