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