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