lean-ctx 3.9.16

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! `rmcp::ServerHandler` trait implementation for [`LeanCtxServer`].
//!
//! Split out of `server/mod.rs`; `use super::*` re-imports the parent module’s
//! aliases and sibling submodules. Methods attach to `LeanCtxServer` regardless
//! of which module the impl block lives in.

#[allow(clippy::wildcard_imports)]
use super::*;

/// Builds the advertised MCP server capabilities.
///
/// `tools` is always enabled **and** always declares `listChanged`: lean-ctx
/// emits `notifications/tools/list_changed` whenever a tool call mutates the
/// dynamic tool set (see `dispatch::send_tools_list_changed`). The MCP spec only
/// permits sending that notification when the matching capability was advertised
/// — otherwise a strict client (e.g. Claude Code) treats it as a protocol
/// violation and drops the entire tool set ("connected, but no tools"). The
/// `resources`/`prompts` surfaces stay client-gated so we never advertise a
/// surface the connected client cannot use.
fn server_capabilities(resources: bool, prompts: bool) -> ServerCapabilities {
    match (resources, prompts) {
        (true, true) => ServerCapabilities::builder()
            .enable_tools()
            .enable_tool_list_changed()
            .enable_resources()
            .enable_resources_subscribe()
            .enable_prompts()
            .build(),
        (true, false) => ServerCapabilities::builder()
            .enable_tools()
            .enable_tool_list_changed()
            .enable_resources()
            .enable_resources_subscribe()
            .build(),
        (false, true) => ServerCapabilities::builder()
            .enable_tools()
            .enable_tool_list_changed()
            .enable_prompts()
            .build(),
        (false, false) => ServerCapabilities::builder()
            .enable_tools()
            .enable_tool_list_changed()
            .build(),
    }
}

impl ServerHandler for LeanCtxServer {
    fn get_info(&self) -> ServerInfo {
        let capabilities = server_capabilities(true, true);

        let instructions = crate::instructions::build_instructions(CrpMode::effective());

        InitializeResult::new(capabilities)
            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
            .with_instructions(instructions)
    }

    async fn initialize(
        &self,
        request: InitializeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<InitializeResult, ErrorData> {
        let name = request.client_info.name.clone();
        tracing::info!("MCP client connected: {:?}", name);
        *self.client_name.write().await = name.clone();
        *self.peer.write().await = Some(context.peer.clone());

        if self.session_mode != crate::tools::SessionMode::Shared {
            crate::core::budget_tracker::BudgetTracker::global().reset();
            if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
                let radar = data_dir.join("context_radar.jsonl");
                if radar.exists() {
                    let prev = data_dir.join("context_radar.prev.jsonl");
                    let _ = std::fs::rename(&radar, &prev);
                }
            }
        }

        let has_roots = request.capabilities.roots.is_some();
        self.has_client_roots
            .store(has_roots, std::sync::atomic::Ordering::Relaxed);
        if has_roots {
            tracing::info!("Client supports MCP roots/list — will resolve on first tool call");
        }

        let env_root = roots::root_from_env().or_else(roots::root_from_workspace_env);
        let derived_root = derive_project_root_from_cwd();
        let effective_root = env_root.or(derived_root);

        let cwd_str = std::env::current_dir()
            .ok()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        {
            let mut session = self.session.write().await;
            if !cwd_str.is_empty() {
                session.shell_cwd = Some(cwd_str.clone());
            }
            if let Some(ref root) = effective_root {
                session.project_root = Some(root.clone());
                tracing::info!("Project root set to: {root}");
                // Cursor multi-root: register sibling workspace folders as extra
                // trusted roots so explicit cross-folder paths are not rejected
                // by the path jail (#699).
                for other in roots::workspace_roots_from_env() {
                    if &other != root && !session.extra_roots.contains(&other) {
                        session.extra_roots.push(other);
                    }
                }
            } else if let Some(ref root) = session.project_root {
                // A previously persisted session may carry a contaminated root
                // (e.g. HOME from an older build or a client that reported HOME
                // as its workspace). Drop it unless it is a real, safe project
                // dir — otherwise PROJECT MEMORY leaks across projects.
                let root_path = std::path::Path::new(root);
                let root_has_marker = has_project_marker(root_path);
                let root_str = root_path.to_string_lossy();
                let root_suspicious = crate::core::pathutil::is_broad_or_unsafe_root(root_path)
                    || root_str.contains("/var/folders/")
                    || root_str.contains("/tmp/")
                    || root_str.contains("/.lmstudio")
                    || root_str.contains("\\AppData\\Local\\Temp")
                    || root_str.contains("\\Temp\\")
                    || root_str.contains("\\.lmstudio");
                if root_suspicious && !root_has_marker {
                    tracing::info!("Dropping suspicious persisted project root: {root}");
                    session.project_root = None;
                }
            }
            let cfg_extra = crate::core::config::Config::load().extra_roots;
            if !cfg_extra.is_empty() {
                let existing: std::collections::HashSet<_> =
                    session.extra_roots.iter().cloned().collect();
                for r in cfg_extra {
                    if !existing.contains(&r) {
                        session.extra_roots.push(r);
                    }
                }
            }
            if self.session_mode == crate::tools::SessionMode::Shared {
                if let Some(ref root) = session.project_root
                    && let Some(ref rt) = self.context_os
                {
                    rt.shared_sessions.persist_best_effort(
                        root,
                        &self.workspace_id,
                        &self.channel_id,
                        &session,
                    );
                    rt.metrics.record_session_persisted();
                }
            } else if let Err(e) = session.save() {
                tracing::warn!("lean-ctx: failed to persist session state: {e}");
            }
        }

        // Indices are warmed lazily on first use of a tool that needs them
        // (issue #152), not eagerly here — a session that only uses
        // ctx_read/ctx_shell/ctx_tree must not pay a full graph + BM25 scan.
        // See `index_orchestrator::ensure_warm_for_tool`, driven from dispatch.

        let agent_name = name.clone();
        let agent_root = effective_root.clone().unwrap_or_default();
        let agent_id_handle = self.agent_id.clone();
        tokio::task::spawn_blocking(move || {
            if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
                return;
            }

            // Avoid startup stampedes when multiple agent sessions initialize at once.
            // These are best-effort maintenance tasks; it's fine to skip if another
            // lean-ctx instance is already doing them.
            let maintenance = crate::core::startup_guard::try_acquire_lock(
                "startup-maintenance",
                std::time::Duration::from_secs(2),
                std::time::Duration::from_mins(2),
            );
            if maintenance.is_some() {
                if let Some(home) = dirs::home_dir() {
                    let _ = crate::rules_inject::inject_all_rules(&home);
                    // The on-demand SKILL.md belongs to the same steering surface
                    // as the rules block: the session-start heal writes rules for
                    // every detected client, so a fresh machine that never ran
                    // `lean-ctx setup` otherwise carries a permanent doctor
                    // warning ("SKILL.md not installed"). Idempotent + gated on
                    // the same opt-outs as setup (rules_injection=off inside,
                    // auto_inject_skills=Some(false) here).
                    if crate::core::config::Config::load()
                        .setup
                        .should_inject_skills()
                    {
                        let _ = crate::rules_inject::install_all_skills(&home);
                    }
                }
                crate::hooks::refresh_installed_hooks();
                crate::core::version_check::check_background();
                // Enforce the on-disk budget: prune accumulated quarantined BM25
                // indexes and cap the archive FTS DB (#2364). Silent (tracing
                // only) so it never corrupts the MCP stdio protocol.
                let _ = crate::core::storage_maintenance::run_quiet();
            }
            drop(maintenance);

            if !agent_root.is_empty() {
                let heuristic_role = match agent_name.to_lowercase().as_str() {
                    n if n.contains("cursor") => Some("coder"),
                    n if n.contains("claude") => Some("coder"),
                    n if n.contains("codebuddy") => Some("coder"),
                    n if n.contains("codex") => Some("coder"),
                    n if n.contains("antigravity") || n.contains("gemini") => Some("coder"),
                    n if n.contains("review") => Some("reviewer"),
                    n if n.contains("test") => Some("debugger"),
                    _ => None,
                };
                let env_role = std::env::var("LEAN_CTX_ROLE")
                    .or_else(|_| std::env::var("LEAN_CTX_AGENT_ROLE"))
                    .ok();
                let effective_role = env_role.as_deref().or(heuristic_role).unwrap_or("coder");

                let _ = crate::core::roles::set_active_role_with_source(effective_role, true);

                let id = crate::core::agents::AgentRegistry::mutate_locked(|registry| {
                    registry.cleanup_stale(24);
                    registry.register("mcp", Some(effective_role), &agent_root)
                })
                .map(|(_, id)| id)
                .ok();
                if let (Some(id), Ok(mut guard)) = (id, agent_id_handle.try_write()) {
                    *guard = Some(id);
                }
            }
        });

        let client_caps = crate::core::client_capabilities::ClientMcpCapabilities::detect(&name);
        tracing::info!("Client capabilities: {}", client_caps.format_summary());

        {
            let cfg = crate::core::config::Config::load();
            let cats = cfg.default_tool_categories_effective();
            dynamic_tools::init_from_config(&cats);
        }

        if let Some(max) = client_caps.max_tools
            && let Ok(mut dt) = dynamic_tools::global().lock()
        {
            dt.set_supports_list_changed(true);
            if max < 100 {
                dt.unload_category(dynamic_tools::ToolCategory::Debug);
                dt.unload_category(dynamic_tools::ToolCategory::Memory);
            }
        } else if client_caps.dynamic_tools
            && let Ok(mut dt) = dynamic_tools::global().lock()
        {
            dt.set_supports_list_changed(true);
        }

        crate::core::client_capabilities::set_detected(&client_caps);

        let session = self.session.read().await.clone();
        let instructions = crate::instructions::build_instructions_with_client_and_session(
            CrpMode::effective(),
            &name,
            &session,
        );

        let capabilities = server_capabilities(client_caps.resources, client_caps.prompts);

        Ok(InitializeResult::new(capabilities)
            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
            .with_instructions(instructions))
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        use crate::server::tool_visibility::CandidateSet;
        // Panic guard (mirrors call_tool): a panic while filtering the registry /
        // touching the dynamic-tools mutex must not kill the rmcp request task.
        use std::panic::AssertUnwindSafe;
        let computed = AssertUnwindSafe(async {
            let cfg = crate::core::config::Config::load();
            let disabled = cfg.disabled_tools_effective();
            let raw_profile = cfg.tool_profile_effective();
            let tool_profile = crate::server::tool_visibility::resolve_auto_profile(&raw_profile);
            crate::server::tool_visibility::record_auto_turn();
            // A profile is "explicit" when the user opted into one (config field,
            // env var, or a custom tools list). Without an explicit choice we keep
            // the token-lean lazy core set as the default. With one, the profile is
            // authoritative and resolves against the full registry, so e.g.
            // `standard` advertises its full balanced set instead of the accidental
            // `core ∩ standard` intersection.
            let explicit_profile = crate::server::tool_visibility::explicit_profile(&cfg);

            let client = self.client_name.read().await.clone();
            let hook_covered = is_client_hook_covered(&client);

            let candidate = crate::server::tool_visibility::candidate_set(
                &crate::server::tool_visibility::CandidateInputs {
                    full_mode: crate::tool_defs::is_full_mode(),
                    unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
                    explicit_profile,
                    hook_covered,
                },
            );
            let all_tools = match candidate {
                CandidateSet::Full | CandidateSet::ProfileAuthoritative => {
                    if let Some(ref reg) = self.registry {
                        reg.tool_defs()
                    } else {
                        // Unreachable in production: every constructor sets a registry
                        // (locked by `production_server_always_has_registry`). If it
                        // ever fires, the advertised static defs can drift from what
                        // dispatch (which needs the registry) can execute — make it loud.
                        tracing::error!(
                            "list_tools served WITHOUT a tool registry (full mode) — advertising \
                             static granular defs that dispatch cannot run; tools may drift from handlers."
                        );
                        crate::tool_defs::granular_tool_defs()
                    }
                }
                CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
                CandidateSet::ShadowOnly => {
                    if let Some(ref reg) = self.registry {
                        reg.tool_defs()
                            .into_iter()
                            .filter(|t| t.name.as_ref() == "ctx_call")
                            .collect()
                    } else {
                        crate::tool_defs::lazy_tool_defs()
                            .into_iter()
                            .filter(|t| t.name.as_ref() == "ctx_call")
                            .collect()
                    }
                }
                CandidateSet::LazyCore => {
                    if let Some(ref reg) = self.registry {
                        let core_names = crate::tool_defs::core_tool_names();
                        reg.tool_defs()
                            .into_iter()
                            .filter(|t| core_names.contains(&t.name.as_ref()))
                            .collect()
                    } else {
                        // Unreachable in production (see above); loud if it ever fires.
                        tracing::error!(
                            "list_tools served WITHOUT a tool registry (lazy mode) — advertising \
                             static lazy defs that dispatch cannot run; tools may drift from handlers."
                        );
                        crate::tool_defs::lazy_tool_defs()
                    }
                }
            };
            let quirks = crate::server::tool_visibility::ClientQuirks::resolve(&client, candidate);

            let active_role = crate::core::roles::active_role();
            let tools: Vec<_> = all_tools
                .into_iter()
                .filter(|t| {
                    let name = t.name.as_ref();
                    crate::server::tool_visibility::is_tool_visible(
                        name,
                        &tool_profile,
                        &disabled,
                        quirks,
                        active_role.is_tool_allowed(name),
                    )
                })
                .collect();

            // Guarantee the universal invoker is advertised in non-full mode. Lazy
            // and profile filtering hide most tools; without ctx_call a static-list
            // client (one that only calls advertised tools) could not reach them.
            // ctx_call enforces the same role/workflow gates on the inner tool.
            let tools = {
                use crate::server::tool_visibility::INVOKER;
                let mut tools = tools;
                let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
                if crate::server::tool_visibility::needs_invoker(
                    crate::tool_defs::is_full_mode(),
                    already,
                    active_role.is_tool_allowed(INVOKER),
                    &disabled,
                ) && let Some(def) = self.registry.as_ref().and_then(|reg| {
                    reg.tool_defs()
                        .into_iter()
                        .find(|t| t.name.as_ref() == INVOKER)
                }) {
                    tools.push(def);
                }
                tools
            };

            let tools = {
                let Ok(dyn_state) = dynamic_tools::global().lock() else {
                    tracing::warn!(
                        "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
                    );
                    return Ok(ListToolsResult {
                        tools,
                        ..Default::default()
                    });
                };
                // The lazy category gate (load tools on demand for dynamic_tools
                // clients) only applies to the *default* lean-core surface. When the
                // user opted into an explicit profile, that profile IS the
                // authoritative surface — gating it by category would silently drop
                // profile-enabled tools like Standard's ctx_architecture /
                // ctx_semantic_search for Codex et al. (#358), so the advertised set
                // would no longer match `lean-ctx tools show`.
                if crate::server::tool_visibility::category_gate_applies(
                    dyn_state.supports_list_changed(),
                    explicit_profile,
                ) {
                    tools
                        .into_iter()
                        .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
                        .collect()
                } else {
                    tools
                }
            };

            let tools = {
                let active = self.workflow.read().await.clone();
                if let Some(run) = active {
                    if run.current == "done" || is_workflow_stale(&run) {
                        let mut wf = self.workflow.write().await;
                        *wf = None;
                        let _ = crate::core::workflow::clear_active();
                    } else if let Some(state) = run.spec.state(&run.current)
                        && let Some(allowed) = &state.allowed_tools
                    {
                        let mut allow: std::collections::HashSet<&str> =
                            allowed.iter().map(std::string::String::as_str).collect();
                        for passthrough in WORKFLOW_PASSTHROUGH_TOOLS {
                            allow.insert(passthrough);
                        }
                        return Ok(ListToolsResult {
                            tools: tools
                                .into_iter()
                                .filter(|t| allow.contains(t.name.as_ref()))
                                .collect(),
                            ..Default::default()
                        });
                    }
                }
                tools
            };

            let tools = {
                let cfg = crate::core::config::Config::load();
                let level = crate::core::config::CompressionLevel::effective(&cfg);
                let mode =
                    crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(
                        &level,
                    );
                if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
                    tools
                } else {
                    tools
                        .into_iter()
                        .map(|mut t| {
                            let compressed = crate::core::terse::mcp_compress::compress_description(
                                t.name.as_ref(),
                                t.description.as_deref().unwrap_or(""),
                                mode,
                            );
                            t.description = Some(compressed.into());
                            t
                        })
                        .collect()
                }
            };


            // R28: Kernel schema optimization — budget-aware description compression.
            let tools = crate::server::schema_hook::optimize_tools(tools, &client);
            // #1008: When ctx_patch is hidden for this client, scrub references
            // from other tools' descriptions so the LLM never sees the name and
            // won't attempt to call it. Replace with ctx_edit (visible alternative).
            let tools = if quirks.hide_ctx_patch {
                tools
                    .into_iter()
                    .map(|mut t| {
                        if let Some(ref desc) = t.description
                            && desc.contains("ctx_patch")
                        {
                            t.description =
                                Some(desc.replace("ctx_patch", "ctx_edit").into());
                        }
                        t
                    })
                    .collect()
            } else {
                tools
            };

            Ok(ListToolsResult {
                tools,
                ..Default::default()
            })
        })
        .catch_unwind()
        .await;
        computed.unwrap_or_else(|_| {
            // A panic here must NOT leave the agent tool-less — that is
            // indistinguishable from "MCP totally failed" and gives the user no
            // recovery path. Fall back to the static lazy-core defs (a pure,
            // panic-free function) so ctx_read/ctx_shell/ctx_call stay available
            // even if the dynamic/registry path blew up.
            tracing::error!(
                "list_tools panicked; serving the static lazy-core tool set as a fallback"
            );
            Ok(ListToolsResult {
                tools: crate::tool_defs::lazy_tool_defs(),
                ..Default::default()
            })
        })
    }

    fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, ErrorData>> {
        std::future::ready(Ok(rmcp::model::ListPromptsResult::with_all_items(
            prompts::list_prompts(),
        )))
    }

    async fn get_prompt(
        &self,
        request: rmcp::model::GetPromptRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
        let ledger = self.ledger.read().await;
        match prompts::get_prompt(&request, &ledger) {
            Some(result) => Ok(result),
            None => Err(ErrorData::invalid_params(
                format!("Unknown prompt: {}", request.name),
                None,
            )),
        }
    }

    fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl Future<Output = Result<rmcp::model::ListResourcesResult, rmcp::ErrorData>> {
        std::future::ready(Ok(rmcp::model::ListResourcesResult::with_all_items(
            resources::list_resources(),
        )))
    }

    async fn read_resource(
        &self,
        request: rmcp::model::ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
        let ledger = self.ledger.read().await;
        match resources::read_resource(&request.uri, &ledger) {
            Some(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
            None => Err(rmcp::ErrorData::resource_not_found(
                resources::unknown_resource_message(&request.uri),
                None,
            )),
        }
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, ErrorData> {
        use std::panic::AssertUnwindSafe;

        let progress_token = request
            .meta
            .as_ref()
            .and_then(rmcp::model::Meta::get_progress_token);
        if let Some(ref token) = progress_token {
            let sender =
                crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
            *self
                .progress_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
        }

        let tool_name_for_panic = request.name.as_ref().to_string();
        let args_fp_for_panic = request
            .arguments
            .as_ref()
            .map(|a| {
                crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
                    a.clone(),
                ))
            })
            .unwrap_or_default();

        let loop_detector = self.loop_detector.clone();
        let ct = context.ct.clone();

        match AssertUnwindSafe(self.call_tool_guarded(request))
            .catch_unwind()
            .await
        {
            Ok(result) => {
                // #1265: If the client cancelled this request while the tool was
                // executing, drop the result instead of replying to a stale ID.
                if ct.is_cancelled() {
                    tracing::warn!(
                        "tool '{tool_name_for_panic}' completed after client cancellation — dropping result"
                    );
                    return Err(ErrorData::internal_error(
                        "request was cancelled by client",
                        None,
                    ));
                }
                result
            }
            Err(panic_payload) => {
                let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
                    (*s).to_string()
                } else if let Some(s) = panic_payload.downcast_ref::<String>() {
                    s.clone()
                } else {
                    "unknown".to_string()
                };
                tracing::error!("call_tool panicked: {detail}");

                if let Ok(mut detector) =
                    tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
                        .await
                {
                    detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
                }

                Ok(CallToolResult::error(vec![ContentBlock::text(
                    "ERROR: lean-ctx internal error. The MCP server is still running. \
                     Please retry or use a different approach."
                        .to_string(),
                )]))
            }
        }
    }

    async fn on_roots_list_changed(
        &self,
        _context: rmcp::service::NotificationContext<RoleServer>,
    ) {
        tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
        self.roots_resolved
            .store(false, std::sync::atomic::Ordering::Relaxed);
        // Fresh client signal — restore the transient-failure retry budget.
        self.roots_list_attempts
            .store(0, std::sync::atomic::Ordering::Relaxed);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// lean-ctx emits `notifications/tools/list_changed` whenever a tool call
    /// mutates the dynamic tool set. The capability MUST be advertised on every
    /// client surface (resources/prompts on or off) — otherwise a strict client
    /// such as Claude Code rejects the undeclared notification and drops the whole
    /// tool set ("connected, but tools not registered"). Regression guard for #688.
    #[test]
    fn server_capabilities_always_declare_tool_list_changed() {
        for (resources, prompts) in [(true, true), (true, false), (false, true), (false, false)] {
            let caps = server_capabilities(resources, prompts);
            let tools = caps.tools.expect("tools capability must be advertised");
            assert_eq!(
                tools.list_changed,
                Some(true),
                "listChanged must be Some(true) for (resources={resources}, prompts={prompts})"
            );
        }
    }

    /// The `list_tools` panic guard serves `lazy_tool_defs()`; it must contain the
    /// essentials so an internal panic never leaves the agent tool-less (which is
    /// indistinguishable from "MCP totally failed"). Regression guard for #688.
    #[test]
    fn lazy_core_fallback_is_never_empty() {
        let _guard = crate::core::data_dir::isolated_data_dir();
        let defs = crate::tool_defs::lazy_tool_defs();
        assert!(!defs.is_empty(), "lazy-core fallback must not be empty");
        for essential in ["ctx_read", "ctx_shell", "ctx_call"] {
            assert!(
                defs.iter().any(|t| t.name.as_ref() == essential),
                "lazy-core fallback must include {essential}"
            );
        }
    }
}