Skip to main content

lean_ctx_server/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(
14    request: &mut CallToolRequestParams,
15    transport_meta: &rmcp::model::RequestMetaObject,
16) {
17    if !transport_meta.is_empty() {
18        request
19            .meta
20            .get_or_insert_with(rmcp::model::RequestMetaObject::new)
21            .extend(transport_meta.clone());
22    }
23}
24
25/// Builds the advertised MCP server capabilities.
26///
27/// `tools` is always enabled **and** always declares `listChanged`: lean-ctx
28/// emits `notifications/tools/list_changed` whenever a tool call mutates the
29/// dynamic tool set (see `dispatch::send_tools_list_changed`). The MCP spec only
30/// permits sending that notification when the matching capability was advertised
31/// — otherwise a strict client (e.g. Claude Code) treats it as a protocol
32/// violation and drops the entire tool set ("connected, but no tools"). The
33/// `resources`/`prompts` surfaces stay client-gated so we never advertise a
34/// surface the connected client cannot use.
35fn server_capabilities(resources: bool, prompts: bool) -> ServerCapabilities {
36    match (resources, prompts) {
37        (true, true) => ServerCapabilities::builder()
38            .enable_tools()
39            .enable_tool_list_changed()
40            .enable_resources()
41            .enable_resources_subscribe()
42            .enable_prompts()
43            .build(),
44        (true, false) => ServerCapabilities::builder()
45            .enable_tools()
46            .enable_tool_list_changed()
47            .enable_resources()
48            .enable_resources_subscribe()
49            .build(),
50        (false, true) => ServerCapabilities::builder()
51            .enable_tools()
52            .enable_tool_list_changed()
53            .enable_prompts()
54            .build(),
55        (false, false) => ServerCapabilities::builder()
56            .enable_tools()
57            .enable_tool_list_changed()
58            .build(),
59    }
60}
61
62fn suppress_initialize_instructions(client_id: &str) -> bool {
63    let cfg = lean_ctx::core::config::Config::load();
64
65    cfg.declines_rule_steering() || matches!(client_id, "antigravity" | "gemini-cli")
66}
67
68fn engine_server_info() -> Implementation {
69    Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION"))
70        .with_title("LeanCTX")
71        .with_description("Context Gateway for AI agents: task-relevant context, supported controls, local knowledge and observable evidence.")
72        .with_website_url("https://leanctx.com")
73}
74
75impl LeanCtxServer {
76    /// The client handshake: who connected, which roots and capabilities this
77    /// session uses. `initialize` runs it; a client on the stateless protocol
78    /// (2026-07-28, e.g. Claude Code >= 2.1.330) sends no `initialize`, so the
79    /// first request runs it from the client info in its `_meta` instead
80    /// (rc3-49: without it the session kept no project root and every store
81    /// was keyed by the empty root).
82    async fn apply_handshake(
83        &self,
84        name: &str,
85        version: &str,
86        has_roots: bool,
87        peer: rmcp::service::Peer<RoleServer>,
88    ) -> lean_ctx::core::client_capabilities::ClientMcpCapabilities {
89        tracing::info!("MCP client connected: {:?}", name);
90        *self.client_name.write().await = name.to_string();
91        *self.peer.write().await = Some(peer);
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            let handshake = lean_ctx::core::client_capabilities::record_handshake(name, version);
97            crate::server::client_sessions::started(&handshake.host);
98        }
99        // Per-agent savings attribution: a personal server serves exactly one
100        // client, so its ledger events can carry that client's identity. The
101        // shared (multi-client) mode keeps the process-level fallback.
102        if self.session_mode != crate::tools::SessionMode::Shared {
103            let bus_id = self.presence_agent_id.read().await.clone();
104            lean_ctx::core::agent_identity::set_session_attribution(name, bus_id.as_deref());
105        }
106
107        if self.session_mode != crate::tools::SessionMode::Shared {
108            if let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() {
109                let radar = data_dir.join("context_radar.jsonl");
110                if radar.exists() {
111                    let prev = data_dir.join("context_radar.prev.jsonl");
112                    let _ = std::fs::rename(&radar, &prev);
113                }
114            }
115        }
116
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            && !lean_ctx::core::workspace_authority::is_configured()
140            && let Some(selection) = workspace_selection
141                .filter(|selection| effective_root.as_ref() == Some(&selection.chosen_root))
142        {
143            lean_ctx::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 = lean_ctx::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 = lean_ctx::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 lean_ctx::core::workspace_authority::load_current() {
204                lean_ctx::core::workspace_authority::Authority::Legacy => {}
205                lean_ctx::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                lean_ctx::core::workspace_authority::Authority::Unavailable(reason) => {
217                    tracing::error!(
218                        "{}",
219                        lean_ctx::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.to_string();
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                lean_ctx::core::agents::AgentRegistry::record_transport_client_persistent(
279                    &lean_ctx::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 = lean_ctx::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 lean_ctx::core::config::Config::load()
304                        .setup
305                        .should_inject_skills()
306                    {
307                        let _ = lean_ctx::rules_inject::install_all_skills(&home);
308                    }
309                }
310                lean_ctx_hooks::hooks::refresh_installed_hooks();
311                lean_ctx::shell_hook::refresh_installed_shell_hooks();
312                lean_ctx::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 _ = lean_ctx::core::storage_maintenance::run_quiet();
317            }
318            drop(maintenance);
319
320            if !agent_root.is_empty() {
321                let (effective_role, role_source) = resolve_session_role(
322                    &agent_name,
323                    lean_ctx::core::agents::declared_session_role(),
324                );
325
326                // The active role is process-wide: a client of a shared server
327                // must not set it for every other client. Its own role is
328                // still remembered for its presence below. It is the
329                // permission role: `LEAN_CTX_ROLE` or the built-in role the
330                // client name suggests, never the bus name in
331                // `LEAN_CTX_AGENT_ROLE` (a worker label is no permission).
332                if process_roots_apply {
333                    let (permission_role, _) = resolve_session_role(
334                        &agent_name,
335                        lean_ctx::core::agents::declared_permission_role(),
336                    );
337                    let _ =
338                        lean_ctx::core::roles::set_active_role_with_source(&permission_role, true);
339                }
340                // #1766: remember the resolved role so the fail-closed presence
341                // retry re-registers with it, not the `context-engine` placeholder.
342                if let Ok(mut guard) = presence_role_handle.try_write() {
343                    *guard = Some(effective_role.clone());
344                }
345
346                let registration = lean_ctx::core::agents::AgentRegistry::register_mcp_process_as(
347                    &agent_root,
348                    &effective_role,
349                    role_source,
350                    None,
351                );
352                let id = match registration {
353                    Ok(id) => Some(id),
354                    Err(error) => {
355                        tracing::warn!("lean-ctx: agent registration failed: {error}");
356                        None
357                    }
358                };
359                if let (Some(id), Ok(mut guard)) = (id.as_ref(), agent_id_handle.try_write()) {
360                    *guard = Some(id.clone());
361                }
362                if let (Some(id), Ok(mut guard)) = (id, presence_agent_id_handle.try_write()) {
363                    *guard = Some(id);
364                }
365            }
366        });
367
368        let client_caps = lean_ctx::core::client_capabilities::ClientMcpCapabilities::detect(name);
369        tracing::info!("Client capabilities: {}", client_caps.format_summary());
370
371        {
372            let cfg = lean_ctx::core::config::Config::load();
373            let cats = cfg.default_tool_categories_effective();
374            dynamic_tools::init_from_config(&cats);
375        }
376
377        if let Some(max) = client_caps.max_tools
378            && let Ok(mut dt) = dynamic_tools::global().lock()
379        {
380            dt.set_supports_list_changed(true);
381            if max < 100 {
382                dt.unload_category(dynamic_tools::ToolCategory::Debug);
383                dt.unload_category(dynamic_tools::ToolCategory::Memory);
384            }
385        } else if client_caps.dynamic_tools
386            && let Ok(mut dt) = dynamic_tools::global().lock()
387        {
388            dt.set_supports_list_changed(true);
389        }
390
391        lean_ctx::core::client_capabilities::set_detected(&client_caps);
392        client_caps
393    }
394
395    /// Runs the handshake once for a stateless client, which never sends
396    /// `initialize`. A request on a protocol with `initialize` (a legacy
397    /// client probing `server/discover` before it falls back) and every
398    /// request after the handshake do nothing here.
399    pub(crate) async fn ensure_handshake(&self, context: &RequestContext<RoleServer>) {
400        if self.handshake.initialized() {
401            return;
402        }
403        let stateless = context
404            .meta
405            .protocol_version()
406            .is_some_and(|v| !v.has_initialize());
407        if !stateless {
408            return;
409        }
410        self.handshake
411            .get_or_init(|| async {
412                let (name, version) = context.meta.client_info().map_or_else(
413                    || ("unknown".to_string(), String::new()),
414                    |i| (i.name, i.version),
415                );
416                tracing::info!("No initialize from {name:?} — handshake from request metadata");
417                // A stateless client cannot answer a server-sent `roots/list`
418                // (has_roots = false); its project comes from the host env
419                // and the working directory.
420                self.apply_handshake(&name, &version, false, context.peer.clone())
421                    .await;
422            })
423            .await;
424    }
425
426    /// The handshake answer: capabilities and instructions for this client.
427    async fn handshake_result(
428        &self,
429        name: &str,
430        client_caps: &lean_ctx::core::client_capabilities::ClientMcpCapabilities,
431    ) -> InitializeResult {
432        let session = self.session.read().await.clone();
433        let capabilities = server_capabilities(client_caps.resources, client_caps.prompts);
434
435        let result = InitializeResult::new(capabilities).with_server_info(engine_server_info());
436
437        // GH #1447: Antigravity/Gemini CLI disconnect when the initialize
438        // response contains `instructions`. The MCP spec marks it optional,
439        // but these clients fail on any unexpected field in the JSON envelope.
440        //
441        // GH #1599/#1758: both `rules_injection = "off"` and an explicit
442        // `setup.auto_inject_rules = false` decline lean-ctx rule steering.
443        // The initialize `instructions` field is that same steering block
444        // delivered over a different channel, so the central policy predicate
445        // must govern this surface too.
446        if suppress_initialize_instructions(client_caps.client_id.as_str()) {
447            result
448        } else {
449            let instructions = lean_ctx::instructions::build_instructions_with_client_and_session(
450                CrpMode::effective(),
451                name,
452                &session,
453            );
454            result.with_instructions(instructions)
455        }
456    }
457}
458
459impl ServerHandler for LeanCtxServer {
460    fn get_info(&self) -> ServerConfig {
461        let capabilities = server_capabilities(true, true);
462
463        let instructions = lean_ctx::instructions::build_instructions(CrpMode::effective());
464
465        InitializeResult::new(capabilities)
466            .with_server_info(engine_server_info())
467            .with_instructions(instructions)
468    }
469
470    async fn initialize(
471        &self,
472        request: InitializeRequestParams,
473        context: RequestContext<RoleServer>,
474    ) -> Result<InitializeResult, ErrorData> {
475        // #2197: kept apart from tool completions in the request ledger.
476        let ledger_entry = lean_ctx::core::request_ledger::begin("initialize");
477        ledger_entry.stage(lean_ctx::core::request_ledger::Stage::Handler);
478        let name = request.client_info.name.clone();
479        let has_roots = request.capabilities.roots.is_some();
480        let client_caps = self
481            .apply_handshake(
482                &name,
483                &request.client_info.version,
484                has_roots,
485                context.peer.clone(),
486            )
487            .await;
488        // A later request must not run it again from its `_meta`.
489        let _ = self.handshake.set(());
490        let result = self.handshake_result(&name, &client_caps).await;
491        ledger_entry.finish(lean_ctx::core::request_ledger::Outcome::Completed);
492        Ok(result)
493    }
494
495    async fn discover(
496        &self,
497        context: RequestContext<RoleServer>,
498    ) -> Result<rmcp::model::DiscoverResult, ErrorData> {
499        self.ensure_handshake(&context).await;
500        let name = self.client_name.read().await.clone();
501        let client_caps = lean_ctx::core::client_capabilities::ClientMcpCapabilities::detect(&name);
502        let info = self.handshake_result(&name, &client_caps).await;
503        Ok(rmcp::model::DiscoverResult::from_server_info(
504            self.supported_protocol_versions().into_owned(),
505            info,
506        ))
507    }
508
509    /// Acknowledge `subscriptions/listen` (2026-07-28) with an empty filter
510    /// instead of -32601: the stream stays open and delivers nothing.
511    fn accepted_subscription_filter(
512        &self,
513        _requested: &rmcp::model::SubscriptionFilter,
514    ) -> Option<rmcp::model::SubscriptionFilter> {
515        Some(rmcp::model::SubscriptionFilter::new())
516    }
517
518    async fn list_tools(
519        &self,
520        _request: Option<PaginatedRequestParams>,
521        context: RequestContext<RoleServer>,
522    ) -> Result<ListToolsResult, ErrorData> {
523        self.ensure_handshake(&context).await;
524        use crate::server::tool_visibility::CandidateSet;
525        // Panic guard (mirrors call_tool): a panic while filtering the registry /
526        // touching the dynamic-tools mutex must not kill the rmcp request task.
527        use std::panic::AssertUnwindSafe;
528        let computed = AssertUnwindSafe(async {
529            let cfg = lean_ctx::core::config::Config::load();
530            let disabled = cfg.disabled_tools_effective();
531            let raw_profile = cfg.tool_profile_effective();
532            let tool_profile = crate::server::tool_visibility::resolve_auto_profile(&raw_profile);
533            crate::server::tool_visibility::record_auto_turn();
534            // A profile is "explicit" when the user opted into one (config field,
535            // env var, or a custom tools list). Without an explicit choice we keep
536            // the token-lean lazy core set as the default. With one, the profile is
537            // authoritative and resolves against the full registry, so e.g.
538            // `standard` advertises its full balanced set instead of the accidental
539            // `core ∩ standard` intersection.
540            let explicit_profile = crate::server::tool_visibility::explicit_profile(&cfg);
541
542            let client = self.client_name.read().await.clone();
543            let hook_covered = is_client_hook_covered(&client);
544
545            let candidate = crate::server::tool_visibility::candidate_set(
546                &crate::server::tool_visibility::CandidateInputs {
547                    full_mode: lean_ctx::tool_defs::is_full_mode(),
548                    unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
549                    explicit_profile,
550                    hook_covered,
551                },
552            );
553            let all_tools = match candidate {
554                CandidateSet::Full | CandidateSet::ProfileAuthoritative => {
555                    if let Some(ref reg) = self.registry {
556                        reg.tool_defs()
557                    } else {
558                        // Unreachable in production: every constructor sets a registry
559                        // (locked by `production_server_always_has_registry`). If it
560                        // ever fires, the advertised static defs can drift from what
561                        // dispatch (which needs the registry) can execute — make it loud.
562                        tracing::error!(
563                            "list_tools served WITHOUT a tool registry (full mode) — advertising \
564                             static granular defs that dispatch cannot run; tools may drift from handlers."
565                        );
566                        lean_ctx::tool_defs::granular_tool_defs()
567                    }
568                }
569                CandidateSet::Unified => lean_ctx::tool_defs::unified_tool_defs(),
570                // GH #1474: ShadowOnly is never returned anymore; treat as LazyCore.
571                CandidateSet::ShadowOnly |
572                CandidateSet::LazyCore => {
573                    if let Some(ref reg) = self.registry {
574                        let core_names = lean_ctx::tool_defs::core_tool_names();
575                        reg.tool_defs()
576                            .into_iter()
577                            .filter(|t| core_names.contains(&t.name.as_ref()))
578                            .collect()
579                    } else {
580                        // Unreachable in production (see above); loud if it ever fires.
581                        tracing::error!(
582                            "list_tools served WITHOUT a tool registry (lazy mode) — advertising \
583                             static lazy defs that dispatch cannot run; tools may drift from handlers."
584                        );
585                        lean_ctx::tool_defs::lazy_tool_defs()
586                    }
587                }
588            };
589            let quirks = crate::server::tool_visibility::ClientQuirks::resolve(&client, candidate);
590
591            let active_role = lean_ctx::core::roles::active_role();
592            let tools: Vec<_> = all_tools
593                .into_iter()
594                .filter(|t| {
595                    let name = t.name.as_ref();
596                    crate::server::tool_visibility::is_tool_visible(
597                        name,
598                        &tool_profile,
599                        &disabled,
600                        quirks,
601                        active_role.is_tool_allowed(name),
602                    )
603                })
604                .collect();
605
606            // Guarantee the universal invoker is advertised in non-full mode. Lazy
607            // and profile filtering hide most tools; without ctx_call a static-list
608            // client (one that only calls advertised tools) could not reach them.
609            // ctx_call enforces the same role/workflow gates on the inner tool.
610            let tools = {
611                use crate::server::tool_visibility::INVOKER;
612                let mut tools = tools;
613                let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
614                if crate::server::tool_visibility::needs_invoker(
615                    lean_ctx::tool_defs::is_full_mode(),
616                    already,
617                    active_role.is_tool_allowed(INVOKER),
618                    &disabled,
619                ) && let Some(def) = self.registry.as_ref().and_then(|reg| {
620                    reg.tool_defs()
621                        .into_iter()
622                        .find(|t| t.name.as_ref() == INVOKER)
623                }) {
624                    tools.push(def);
625                }
626                tools
627            };
628
629            let tools = {
630                let Ok(dyn_state) = dynamic_tools::global().lock() else {
631                    tracing::warn!(
632                        "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
633                    );
634                    return Ok(ListToolsResult {
635                        tools,
636                        ..Default::default()
637                    });
638                };
639                // The lazy category gate (load tools on demand for dynamic_tools
640                // clients) only applies to the *default* lean-core surface. When the
641                // user opted into an explicit profile, that profile IS the
642                // authoritative surface — gating it by category would silently drop
643                // profile-enabled tools like Standard's ctx_architecture /
644                // ctx_semantic_search for Codex et al. (#358), so the advertised set
645                // would no longer match `lean-ctx tools show`.
646                if crate::server::tool_visibility::category_gate_applies(
647                    dyn_state.supports_list_changed(),
648                    explicit_profile,
649                ) {
650                    tools
651                        .into_iter()
652                        .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
653                        .collect()
654                } else {
655                    tools
656                }
657            };
658
659            let tools = {
660                let active = self.workflow.read().await.clone();
661                if let Some(run) = active {
662                    if run.current == "done" || is_workflow_stale(&run) {
663                        let mut wf = self.workflow.write().await;
664                        *wf = None;
665                        let _ = lean_ctx::core::workflow::clear_active();
666                    } else if let Some(state) = run.spec.state(&run.current)
667                        && state.allowed_tools.is_some()
668                    {
669                        return Ok(ListToolsResult {
670                            tools: tools
671                                .into_iter()
672                                .filter(|t| workflow_lists(&run, t.name.as_ref()))
673                                .collect(),
674                            ..Default::default()
675                        });
676                    }
677                }
678                tools
679            };
680
681            let tools = {
682                let cfg = lean_ctx::core::config::Config::load();
683                let level = lean_ctx::core::config::CompressionLevel::effective(&cfg);
684                let mode =
685                    lean_ctx::core::terse::mcp_compress::DescriptionMode::from_compression_level(
686                        &level,
687                    );
688                if mode == lean_ctx::core::terse::mcp_compress::DescriptionMode::Full {
689                    tools
690                } else {
691                    tools
692                        .into_iter()
693                        .map(|mut t| {
694                            let compressed = lean_ctx::core::terse::mcp_compress::compress_description(
695                                t.name.as_ref(),
696                                t.description.as_deref().unwrap_or(""),
697                                mode,
698                            );
699                            t.description = Some(compressed.into());
700                            t
701                        })
702                        .collect()
703                }
704            };
705
706
707            // R28: Kernel schema optimization — budget-aware description compression.
708            let tools = crate::server::schema_hook::optimize_tools(tools, &client);
709            // #1008: When ctx_patch is hidden for this client, scrub references
710            // from other tools' descriptions so the LLM never sees the name and
711            // won't attempt to call it. Replace with ctx_edit (visible alternative).
712            let tools = if quirks.hide_ctx_patch {
713                tools
714                    .into_iter()
715                    .map(|mut t| {
716                        if let Some(ref desc) = t.description
717                            && desc.contains("ctx_patch")
718                        {
719                            t.description =
720                                Some(desc.replace("ctx_patch", "ctx_edit").into());
721                        }
722                        t
723                    })
724                    .collect()
725            } else {
726                tools
727            };
728
729            // Plan mode: restrict advertised tools to the curated read-only set.
730            let tools = {
731                use crate::tools::InteractionMode;
732                let mode = InteractionMode::from_u8(
733                    self.interaction_mode
734                        .load(std::sync::atomic::Ordering::Relaxed),
735                );
736                if mode == InteractionMode::Plan {
737                    let plan_set =
738                        lean_ctx::core::editor_registry::plan_mode::plan_mode_tools();
739                    tools
740                        .into_iter()
741                        .filter(|t| {
742                            let n = t.name.as_ref();
743                            plan_set.contains(&n) || n == "ctx_call"
744                        })
745                        .collect()
746                } else {
747                    tools
748                }
749            };
750
751            Ok(ListToolsResult {
752                tools,
753                ..Default::default()
754            })
755        })
756        .catch_unwind()
757        .await;
758        computed.unwrap_or_else(|_| {
759            // A panic here must NOT leave the agent tool-less — that is
760            // indistinguishable from "MCP totally failed" and gives the user no
761            // recovery path. Fall back to the static lazy-core defs (a pure,
762            // panic-free function) so ctx_read/ctx_shell/ctx_call stay available
763            // even if the dynamic/registry path blew up.
764            tracing::error!(
765                "list_tools panicked; serving the static lazy-core tool set as a fallback"
766            );
767            Ok(ListToolsResult {
768                tools: lean_ctx::tool_defs::lazy_tool_defs(),
769                ..Default::default()
770            })
771        })
772    }
773
774    fn list_prompts(
775        &self,
776        _request: Option<PaginatedRequestParams>,
777        _context: RequestContext<RoleServer>,
778    ) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, ErrorData>> {
779        std::future::ready(Ok(rmcp::model::ListPromptsResult::with_all_items(
780            prompts::list_prompts(),
781        )))
782    }
783
784    async fn get_prompt(
785        &self,
786        request: rmcp::model::GetPromptRequestParams,
787        _context: RequestContext<RoleServer>,
788    ) -> Result<rmcp::model::GetPromptResponse, ErrorData> {
789        let ledger = self.ledger.read().await;
790        match prompts::get_prompt(&request, &ledger) {
791            Some(result) => Ok(result.into()),
792            None => Err(ErrorData::invalid_params(
793                format!("Unknown prompt: {}", request.name),
794                None,
795            )),
796        }
797    }
798
799    fn list_resources(
800        &self,
801        _request: Option<PaginatedRequestParams>,
802        _context: RequestContext<RoleServer>,
803    ) -> impl Future<Output = Result<rmcp::model::ListResourcesResult, rmcp::ErrorData>> {
804        std::future::ready(Ok(rmcp::model::ListResourcesResult::with_all_items(
805            resources::list_resources(),
806        )))
807    }
808
809    async fn read_resource(
810        &self,
811        request: rmcp::model::ReadResourceRequestParams,
812        context: RequestContext<RoleServer>,
813    ) -> Result<rmcp::model::ReadResourceResponse, rmcp::ErrorData> {
814        self.ensure_handshake(&context).await;
815        let ledger = self.ledger.read().await;
816        if let Some(contents) = resources::read_resource(&request.uri, &ledger) {
817            return Ok(rmcp::model::ReadResourceResult::new(contents).into());
818        }
819
820        // GH #1418: agents sometimes call resources/read with file:// URIs
821        // instead of ctx_read — serve the file directly rather than erroring.
822        let session = self.session.read().await;
823        let root = session.project_root.as_deref();
824        match file_resource::read_file_resource(&request.uri, root, &session.extra_roots) {
825            Ok(contents) => Ok(rmcp::model::ReadResourceResult::new(contents).into()),
826            Err(file_resource::FileResourceError::NotAFilePath) => {
827                Err(rmcp::ErrorData::resource_not_found(
828                    resources::unknown_resource_message(&request.uri),
829                    None,
830                ))
831            }
832            Err(e) => Err(rmcp::ErrorData::resource_not_found(e.to_string(), None)),
833        }
834    }
835
836    async fn call_tool(
837        &self,
838        mut request: CallToolRequestParams,
839        context: RequestContext<RoleServer>,
840    ) -> Result<rmcp::model::CallToolResponse, ErrorData> {
841        use std::panic::AssertUnwindSafe;
842
843        self.ensure_handshake(&context).await;
844        // In flight until this call returns — the idle policy never releases
845        // or exits under a running call.
846        let _activity = crate::server::mcp_idle::begin_call();
847        // #2197: admitted until exactly one outcome is recorded; a future the
848        // client cancels drops this guard and counts as abandoned.
849        let ledger_entry =
850            lean_ctx::core::request_ledger::begin(&format!("tools/call:{}", request.name.as_ref()));
851        restore_tool_meta(&mut request, &context.meta);
852
853        let progress_token = request
854            .meta
855            .as_ref()
856            .and_then(rmcp::model::RequestMetaObject::get_progress_token);
857        // Scoped to this request only (see `REQUEST_PROGRESS`): progress never
858        // outlives its call or leaks into another one.
859        let progress = progress_token
860            .map(|token| crate::server::progress::ProgressSender::new(context.peer.clone(), token));
861
862        let tool_name_for_panic = request.name.as_ref().to_string();
863        let args_fp_for_panic = request
864            .arguments
865            .as_ref()
866            .map(|a| {
867                lean_ctx::core::loop_detection::LoopDetector::fingerprint(
868                    &serde_json::Value::Object(a.clone()),
869                )
870            })
871            .unwrap_or_default();
872
873        let loop_detector = self.loop_detector.clone();
874        let ct = context.ct.clone();
875        // The host's own id of this call, if it names one: noted with the
876        // delivery so the proxy can tell which call these bytes answered.
877        let host_call_id = crate::server::call_identity::host_call_id(request.meta.as_ref());
878        // Rights the shared daemon bound to this request in-process (§9);
879        // otherwise this process's own LEAN_CTX_RIGHTS_FILE.
880        let rights = context
881            .extensions
882            .get::<lean_ctx::core::session_rights::RequestRights>()
883            .map_or_else(lean_ctx::core::session_rights::current, |bound| {
884                bound.0.clone()
885            });
886
887        ledger_entry.stage(lean_ctx::core::request_ledger::Stage::Handler);
888        // The agent calls LeanCTX: this session is no "without a ctx call"
889        // session, also when the tool then panics or is cancelled.
890        crate::server::client_sessions::called();
891        // #1781: scope the request's cancellation token for the whole dispatch
892        // so a tool that waits on a child process can observe an abandoned call
893        // instead of holding its blocking-pool slot until its own soft cap.
894        let Ok(result) = AssertUnwindSafe(crate::server::tool_trait::REQUEST_CT.scope(
895            ct.clone(),
896            crate::server::tool_trait::REQUEST_PROGRESS.scope(
897                progress,
898                Box::pin(crate::server::call_identity::scoped(
899                    host_call_id,
900                    lean_ctx::core::session_rights::scope(rights, self.call_tool_guarded(request)),
901                )),
902            ),
903        ))
904        .catch_unwind()
905        .await
906        else {
907            // A panic message can quote the content it failed on (a slice
908            // boundary inside a string, a parse error): the log line names
909            // the event only (AP10-R4).
910            tracing::error!("call_tool panicked (tool_panic)");
911            ledger_entry.stage(lean_ctx::core::request_ledger::Stage::Finalizing);
912
913            if let Ok(mut detector) =
914                tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write()).await
915            {
916                detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
917            }
918
919            ledger_entry.finish(lean_ctx::core::request_ledger::Outcome::Errored);
920            return Ok(CallToolResult::error(vec![ContentBlock::text(
921                "ERROR: lean-ctx internal error. The MCP server is still running. \
922                 Please retry or use a different approach."
923                    .to_string(),
924            )])
925            .into());
926        };
927        ledger_entry.stage(lean_ctx::core::request_ledger::Stage::Finalizing);
928        // #1265: If the client cancelled this request while the tool was
929        // executing, drop the result instead of replying to a stale ID.
930        if ct.is_cancelled() {
931            tracing::warn!(
932                "tool '{tool_name_for_panic}' completed after client cancellation — dropping result"
933            );
934            ledger_entry.finish(lean_ctx::core::request_ledger::Outcome::Abandoned);
935            return Err(ErrorData::internal_error(
936                "request was cancelled by client",
937                None,
938            ));
939        }
940        ledger_entry.finish(match &result {
941            Ok(done) if done.is_error != Some(true) => {
942                lean_ctx::core::request_ledger::Outcome::Completed
943            }
944            _ => lean_ctx::core::request_ledger::Outcome::Errored,
945        });
946        result.map(Into::into)
947    }
948
949    async fn on_roots_list_changed(
950        &self,
951        _context: rmcp::service::NotificationContext<RoleServer>,
952    ) {
953        tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
954        self.roots_resolved
955            .store(false, std::sync::atomic::Ordering::Relaxed);
956        // Fresh client signal — restore the transient-failure retry budget.
957        self.roots_list_attempts
958            .store(0, std::sync::atomic::Ordering::Relaxed);
959    }
960}
961
962fn startup_rule_maintenance_at_home(home: &std::path::Path) {
963    let cfg = lean_ctx::core::config::Config::load();
964    if cfg.declines_rule_steering() {
965        return;
966    }
967    let _ = lean_ctx::rules_inject::inject_all_rules(home);
968}
969
970/// Whether the tool listing shows `tool` under the active `run` whose current
971/// state gates tools: exactly when the call gate (`workflow::tool_gate`) lets
972/// it through. For a real run that is its allowed tools plus the
973/// pass-through tools, as before. For the stand-in of a withheld workflow the
974/// pass-through tools are NOT added — every call to them is refused — so the
975/// listing is the workflow control tool and the wrappers that reach it.
976fn workflow_lists(run: &lean_ctx::core::workflow::WorkflowRun, tool: &str) -> bool {
977    lean_ctx::core::workflow::tool_gate(run, tool, WORKFLOW_PASSTHROUGH_TOOLS)
978        == lean_ctx::core::workflow::ToolGate::Pass
979}
980
981/// The session role and its provenance: a role stated through the
982/// environment is declared; the client-name heuristic and the `coder`
983/// fallback are assumptions and are reported as such.
984fn resolve_session_role(
985    client_name: &str,
986    declared: Option<String>,
987) -> (String, lean_ctx::core::agents::RoleSource) {
988    if let Some(role) = declared {
989        return (role, lean_ctx::core::agents::RoleSource::Declared);
990    }
991    let heuristic_role = match client_name.to_lowercase().as_str() {
992        n if n.contains("cursor") => "coder",
993        n if n.contains("claude") => "coder",
994        n if n.contains("codebuddy") => "coder",
995        n if n.contains("codex") => "coder",
996        n if n.contains("antigravity") || n.contains("gemini") => "coder",
997        n if n.contains("review") => "reviewer",
998        n if n.contains("test") => "debugger",
999        _ => "coder",
1000    };
1001    (
1002        heuristic_role.to_string(),
1003        lean_ctx::core::agents::RoleSource::Assumed,
1004    )
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009    use super::*;
1010
1011    #[test]
1012    fn session_role_reports_whether_it_was_assumed() {
1013        use lean_ctx::core::agents::RoleSource;
1014        assert_eq!(
1015            resolve_session_role("claude-code", None),
1016            ("coder".to_string(), RoleSource::Assumed)
1017        );
1018        assert_eq!(
1019            resolve_session_role("unknown-host", None),
1020            ("coder".to_string(), RoleSource::Assumed)
1021        );
1022        assert_eq!(
1023            resolve_session_role("code-review-bot", None),
1024            ("reviewer".to_string(), RoleSource::Assumed)
1025        );
1026        assert_eq!(
1027            resolve_session_role("claude-code", Some("reviewer".to_string())),
1028            ("reviewer".to_string(), RoleSource::Declared)
1029        );
1030    }
1031
1032    /// The listing under a workflow is what the call gate lets through: the
1033    /// stand-in for a withheld workflow lists no pass-through tool, a real
1034    /// run lists its allowed tools and the pass-through tools as before.
1035    #[test]
1036    fn the_workflow_listing_matches_the_call_gate() {
1037        use lean_ctx::core::context_admission::stored::lineage_support::{
1038            governed, project, scoped,
1039        };
1040        use lean_ctx::core::workflow::gate::test_support::review;
1041        use lean_ctx::core::workflow::{is_withheld_sentinel, load_active, save_active};
1042        let _data = governed();
1043        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
1044        let (_directory, root) = project();
1045        let (_other_directory, other) = project();
1046        scoped(&root, || save_active(&review())).expect("saved in its project");
1047        let closed = scoped(&other, load_active)
1048            .expect("load")
1049            .expect("a withheld workflow is still a workflow");
1050        assert!(is_withheld_sentinel(&closed));
1051        let listed = |run: &lean_ctx::core::workflow::WorkflowRun| -> Vec<&'static str> {
1052            WORKFLOW_PASSTHROUGH_TOOLS
1053                .iter()
1054                .chain(["ctx_call", "ctx_overview", "ctx_shell"].iter())
1055                .copied()
1056                .filter(|tool| workflow_lists(run, tool))
1057                .collect()
1058        };
1059        assert_eq!(
1060            listed(&closed),
1061            ["ctx", "ctx_workflow", "ctx_call"],
1062            "no pass-through tool is listed under the stand-in"
1063        );
1064        for refused in ["ctx_read", "ctx_search", "ctx_session", "ctx_ledger"] {
1065            assert!(WORKFLOW_PASSTHROUGH_TOOLS.contains(&refused));
1066            assert!(!workflow_lists(&closed, refused), "{refused}");
1067        }
1068
1069        let real = scoped(&root, load_active).expect("load").expect("active");
1070        let mut expected = WORKFLOW_PASSTHROUGH_TOOLS.to_vec();
1071        expected.push("ctx_overview");
1072        assert_eq!(listed(&real), expected, "a real run lists as before");
1073    }
1074
1075    #[test]
1076    fn initialize_instructions_respect_explicit_auto_inject_false() {
1077        let _guard = lean_ctx::core::data_dir::test_env_lock();
1078        let tmp = tempfile::tempdir().expect("tempdir");
1079        let config_dir = tmp.path().join("config");
1080
1081        std::fs::create_dir_all(&config_dir).unwrap();
1082        std::fs::write(
1083            config_dir.join("config.toml"),
1084            "[setup]\nauto_inject_rules = false\n",
1085        )
1086        .unwrap();
1087
1088        let _config_guard = lean_ctx::test_env::EnvVarGuard::set(
1089            "LEAN_CTX_CONFIG_DIR",
1090            config_dir.to_string_lossy().as_ref(),
1091        );
1092        let _injection_guard =
1093            lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
1094
1095        assert!(
1096            suppress_initialize_instructions("cursor"),
1097            "explicit auto_inject_rules=false declines rule steering and must suppress MCP initialize instructions"
1098        );
1099    }
1100
1101    #[test]
1102    fn initialize_instructions_preserve_default_auto_behavior() {
1103        let _guard = lean_ctx::core::data_dir::test_env_lock();
1104        let tmp = tempfile::tempdir().expect("tempdir");
1105        let config_dir = tmp.path().join("config");
1106
1107        std::fs::create_dir_all(&config_dir).unwrap();
1108
1109        let _config_guard = lean_ctx::test_env::EnvVarGuard::set(
1110            "LEAN_CTX_CONFIG_DIR",
1111            config_dir.to_string_lossy().as_ref(),
1112        );
1113        let _injection_guard =
1114            lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
1115
1116        assert!(
1117            !suppress_initialize_instructions("cursor"),
1118            "default auto_inject_rules=None must preserve initialize instructions"
1119        );
1120    }
1121
1122    #[test]
1123    fn initialize_instructions_preserve_explicit_true_behavior() {
1124        let _guard = lean_ctx::core::data_dir::test_env_lock();
1125        let tmp = tempfile::tempdir().expect("tempdir");
1126        let config_dir = tmp.path().join("config");
1127
1128        std::fs::create_dir_all(&config_dir).unwrap();
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 = lean_ctx::test_env::EnvVarGuard::set(
1136            "LEAN_CTX_CONFIG_DIR",
1137            config_dir.to_string_lossy().as_ref(),
1138        );
1139        let _injection_guard =
1140            lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
1141
1142        assert!(
1143            !suppress_initialize_instructions("cursor"),
1144            "explicit auto_inject_rules=true must preserve initialize instructions"
1145        );
1146    }
1147
1148    #[test]
1149    fn initialize_instructions_respect_rules_injection_off() {
1150        let _guard = lean_ctx::core::data_dir::test_env_lock();
1151        let tmp = tempfile::tempdir().expect("tempdir");
1152        let config_dir = tmp.path().join("config");
1153
1154        std::fs::create_dir_all(&config_dir).unwrap();
1155
1156        let _config_guard = lean_ctx::test_env::EnvVarGuard::set(
1157            "LEAN_CTX_CONFIG_DIR",
1158            config_dir.to_string_lossy().as_ref(),
1159        );
1160        let _injection_guard =
1161            lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "off");
1162
1163        assert!(
1164            suppress_initialize_instructions("cursor"),
1165            "rules_injection=off must continue suppressing initialize instructions"
1166        );
1167    }
1168
1169    #[test]
1170    fn initialize_instructions_keep_client_compatibility_exceptions() {
1171        let _guard = lean_ctx::core::data_dir::test_env_lock();
1172        let tmp = tempfile::tempdir().expect("tempdir");
1173        let config_dir = tmp.path().join("config");
1174
1175        std::fs::create_dir_all(&config_dir).unwrap();
1176
1177        let _config_guard = lean_ctx::test_env::EnvVarGuard::set(
1178            "LEAN_CTX_CONFIG_DIR",
1179            config_dir.to_string_lossy().as_ref(),
1180        );
1181        let _injection_guard =
1182            lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
1183
1184        assert!(suppress_initialize_instructions("antigravity"));
1185        assert!(suppress_initialize_instructions("gemini-cli"));
1186    }
1187    #[test]
1188    fn startup_maintenance_respects_explicit_auto_inject_false() {
1189        let _guard = lean_ctx::core::data_dir::test_env_lock();
1190        let tmp = tempfile::tempdir().expect("tempdir");
1191        let home = tmp.path().join("home");
1192        let config_dir = tmp.path().join("config");
1193
1194        std::fs::create_dir_all(home.join(".cursor")).unwrap();
1195        std::fs::create_dir_all(&config_dir).unwrap();
1196
1197        std::fs::write(
1198            home.join(".cursor/mcp.json"),
1199            r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
1200        )
1201        .unwrap();
1202
1203        std::fs::write(
1204            config_dir.join("config.toml"),
1205            "[setup]\nauto_inject_rules = false\n",
1206        )
1207        .unwrap();
1208
1209        let _config_guard = lean_ctx::test_env::EnvVarGuard::set(
1210            "LEAN_CTX_CONFIG_DIR",
1211            config_dir.to_string_lossy().as_ref(),
1212        );
1213        let _injection_guard =
1214            lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
1215        let _scope_guard = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
1216
1217        startup_rule_maintenance_at_home(&home);
1218
1219        let rules = home.join(".cursor/rules/lean-ctx.mdc");
1220
1221        assert!(
1222            !rules.exists(),
1223            "startup maintenance must not write Cursor rules when setup.auto_inject_rules=false"
1224        );
1225    }
1226
1227    #[test]
1228    fn automatic_rule_maintenance_allows_default_startup_write() {
1229        let _guard = lean_ctx::core::data_dir::test_env_lock();
1230        let tmp = tempfile::tempdir().expect("tempdir");
1231        let home = tmp.path().join("home");
1232        let config_dir = tmp.path().join("config");
1233
1234        std::fs::create_dir_all(home.join(".cursor")).unwrap();
1235        std::fs::create_dir_all(&config_dir).unwrap();
1236
1237        std::fs::write(
1238            home.join(".cursor/mcp.json"),
1239            r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
1240        )
1241        .unwrap();
1242
1243        let _config_guard = lean_ctx::test_env::EnvVarGuard::set(
1244            "LEAN_CTX_CONFIG_DIR",
1245            config_dir.to_string_lossy().as_ref(),
1246        );
1247        let _injection_guard =
1248            lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
1249        let _scope_guard = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
1250
1251        startup_rule_maintenance_at_home(&home);
1252
1253        assert!(
1254            home.join(".cursor/rules/lean-ctx.mdc").exists(),
1255            "default auto_inject_rules=None must preserve zero-config startup rule maintenance"
1256        );
1257    }
1258
1259    #[test]
1260    fn automatic_rule_maintenance_allows_explicit_true_startup_write() {
1261        let _guard = lean_ctx::core::data_dir::test_env_lock();
1262        let tmp = tempfile::tempdir().expect("tempdir");
1263        let home = tmp.path().join("home");
1264        let config_dir = tmp.path().join("config");
1265
1266        std::fs::create_dir_all(home.join(".cursor")).unwrap();
1267        std::fs::create_dir_all(&config_dir).unwrap();
1268
1269        std::fs::write(
1270            home.join(".cursor/mcp.json"),
1271            r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
1272        )
1273        .unwrap();
1274
1275        std::fs::write(
1276            config_dir.join("config.toml"),
1277            "[setup]\nauto_inject_rules = true\n",
1278        )
1279        .unwrap();
1280
1281        let _config_guard = lean_ctx::test_env::EnvVarGuard::set(
1282            "LEAN_CTX_CONFIG_DIR",
1283            config_dir.to_string_lossy().as_ref(),
1284        );
1285        let _injection_guard =
1286            lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
1287        let _scope_guard = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
1288
1289        startup_rule_maintenance_at_home(&home);
1290
1291        assert!(
1292            home.join(".cursor/rules/lean-ctx.mdc").exists(),
1293            "explicit auto_inject_rules=true must preserve startup rule maintenance"
1294        );
1295    }
1296
1297    #[test]
1298    fn host_task_scope_retains_wire_metadata_for_receipt_replay() {
1299        use rmcp::model::{CallToolRequest, RequestMetaObject};
1300        let mut wire: CallToolRequest = serde_json::from_value(serde_json::json!({
1301            "method":"tools/call", "params":{"name":"ctx_read", "arguments":{},
1302                "_meta":{"requestId":"wire-retry", "progressToken":19}}
1303        }))
1304        .unwrap();
1305        assert!(wire.params.meta.is_none());
1306        let transported = wire.extensions.get::<RequestMetaObject>().unwrap().clone();
1307        restore_tool_meta(&mut wire.params, &transported);
1308        assert_eq!(
1309            wire.params.meta.as_ref().unwrap().0["requestId"],
1310            "wire-retry"
1311        );
1312        assert_eq!(wire.params.meta.as_ref().unwrap().0["progressToken"], 19);
1313        assert!(
1314            wire.params
1315                .meta
1316                .as_ref()
1317                .unwrap()
1318                .get_progress_token()
1319                .is_some()
1320        );
1321        wire.params
1322            .meta
1323            .as_mut()
1324            .unwrap()
1325            .0
1326            .insert("requestId".into(), "local-conflict".into());
1327        wire.params
1328            .meta
1329            .as_mut()
1330            .unwrap()
1331            .0
1332            .insert("local-only".into(), true.into());
1333        restore_tool_meta(&mut wire.params, &transported);
1334        assert_eq!(
1335            wire.params.meta.as_ref().unwrap().0["requestId"],
1336            "wire-retry"
1337        );
1338        assert_eq!(wire.params.meta.as_ref().unwrap().0["local-only"], true);
1339        let before = wire.params.meta.clone();
1340        restore_tool_meta(&mut wire.params, &RequestMetaObject::new());
1341        assert_eq!(wire.params.meta, before);
1342    }
1343
1344    /// lean-ctx emits `notifications/tools/list_changed` whenever a tool call
1345    /// mutates the dynamic tool set. The capability MUST be advertised on every
1346    /// client surface (resources/prompts on or off) — otherwise a strict client
1347    /// such as Claude Code rejects the undeclared notification and drops the whole
1348    /// tool set ("connected, but tools not registered"). Regression guard for #688.
1349    #[test]
1350    fn server_capabilities_always_declare_tool_list_changed() {
1351        for (resources, prompts) in [(true, true), (true, false), (false, true), (false, false)] {
1352            let caps = server_capabilities(resources, prompts);
1353            let tools = caps.tools.expect("tools capability must be advertised");
1354            assert_eq!(
1355                tools.list_changed,
1356                Some(true),
1357                "listChanged must be Some(true) for (resources={resources}, prompts={prompts})"
1358            );
1359        }
1360    }
1361
1362    /// The `list_tools` panic guard serves `lazy_tool_defs()`; it must contain the
1363    /// essentials so an internal panic never leaves the agent tool-less (which is
1364    /// indistinguishable from "MCP totally failed"). Regression guard for #688.
1365    #[test]
1366    fn lazy_core_fallback_is_never_empty() {
1367        crate::server::registry::register_tool_catalog();
1368        let _guard = lean_ctx::core::data_dir::isolated_data_dir();
1369        let defs = lean_ctx::tool_defs::lazy_tool_defs();
1370        assert!(!defs.is_empty(), "lazy-core fallback must not be empty");
1371        for essential in ["ctx_read", "ctx_shell", "ctx_call"] {
1372            assert!(
1373                defs.iter().any(|t| t.name.as_ref() == essential),
1374                "lazy-core fallback must include {essential}"
1375            );
1376        }
1377    }
1378}