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