1#[allow(clippy::wildcard_imports)]
8use super::*;
9
10fn server_capabilities(resources: bool, prompts: bool) -> ServerCapabilities {
21 match (resources, prompts) {
22 (true, true) => ServerCapabilities::builder()
23 .enable_tools()
24 .enable_tool_list_changed()
25 .enable_resources()
26 .enable_resources_subscribe()
27 .enable_prompts()
28 .build(),
29 (true, false) => ServerCapabilities::builder()
30 .enable_tools()
31 .enable_tool_list_changed()
32 .enable_resources()
33 .enable_resources_subscribe()
34 .build(),
35 (false, true) => ServerCapabilities::builder()
36 .enable_tools()
37 .enable_tool_list_changed()
38 .enable_prompts()
39 .build(),
40 (false, false) => ServerCapabilities::builder()
41 .enable_tools()
42 .enable_tool_list_changed()
43 .build(),
44 }
45}
46
47impl ServerHandler for LeanCtxServer {
48 fn get_info(&self) -> ServerInfo {
49 let capabilities = server_capabilities(true, true);
50
51 let instructions = crate::instructions::build_instructions(CrpMode::effective());
52
53 InitializeResult::new(capabilities)
54 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
55 .with_instructions(instructions)
56 }
57
58 async fn initialize(
59 &self,
60 request: InitializeRequestParams,
61 context: RequestContext<RoleServer>,
62 ) -> Result<InitializeResult, ErrorData> {
63 let name = request.client_info.name.clone();
64 tracing::info!("MCP client connected: {:?}", name);
65 *self.client_name.write().await = name.clone();
66 *self.peer.write().await = Some(context.peer.clone());
67
68 if self.session_mode != crate::tools::SessionMode::Shared {
69 crate::core::budget_tracker::BudgetTracker::global().reset();
70 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
71 let radar = data_dir.join("context_radar.jsonl");
72 if radar.exists() {
73 let prev = data_dir.join("context_radar.prev.jsonl");
74 let _ = std::fs::rename(&radar, &prev);
75 }
76 }
77 }
78
79 let has_roots = request.capabilities.roots.is_some();
80 self.has_client_roots
81 .store(has_roots, std::sync::atomic::Ordering::Relaxed);
82 if has_roots {
83 tracing::info!("Client supports MCP roots/list — will resolve on first tool call");
84 }
85
86 let env_root = roots::root_from_env().or_else(roots::root_from_workspace_env);
87 let derived_root = derive_project_root_from_cwd();
88 let effective_root = env_root.or(derived_root);
89
90 let cwd_str = std::env::current_dir()
91 .ok()
92 .map(|p| p.to_string_lossy().to_string())
93 .unwrap_or_default();
94 {
95 let mut session = self.session.write().await;
96 if !cwd_str.is_empty() {
97 session.shell_cwd = Some(cwd_str.clone());
98 }
99 if let Some(ref root) = effective_root {
100 session.project_root = Some(root.clone());
101 tracing::info!("Project root set to: {root}");
102 for other in roots::workspace_roots_from_env() {
106 if &other != root && !session.extra_roots.contains(&other) {
107 session.extra_roots.push(other);
108 }
109 }
110 } else if let Some(ref root) = session.project_root {
111 let root_path = std::path::Path::new(root);
116 let root_has_marker = has_project_marker(root_path);
117 let root_str = root_path.to_string_lossy();
118 let root_suspicious = crate::core::pathutil::is_broad_or_unsafe_root(root_path)
119 || root_str.contains("/var/folders/")
120 || root_str.contains("/tmp/")
121 || root_str.contains("/.lmstudio")
122 || root_str.contains("\\AppData\\Local\\Temp")
123 || root_str.contains("\\Temp\\")
124 || root_str.contains("\\.lmstudio");
125 if root_suspicious && !root_has_marker {
126 tracing::info!("Dropping suspicious persisted project root: {root}");
127 session.project_root = None;
128 }
129 }
130 let cfg_extra = crate::core::config::Config::load().extra_roots;
131 if !cfg_extra.is_empty() {
132 let existing: std::collections::HashSet<_> =
133 session.extra_roots.iter().cloned().collect();
134 for r in cfg_extra {
135 if !existing.contains(&r) {
136 session.extra_roots.push(r);
137 }
138 }
139 }
140 session.refresh_handoff_context();
141
142 if self.session_mode == crate::tools::SessionMode::Shared {
143 if let Some(ref root) = session.project_root
144 && let Some(ref rt) = self.context_os
145 {
146 rt.shared_sessions.persist_best_effort(
147 root,
148 &self.workspace_id,
149 &self.channel_id,
150 &session,
151 );
152 rt.metrics.record_session_persisted();
153 }
154 } else if let Err(e) = session.save() {
155 tracing::warn!("lean-ctx: failed to persist session state: {e}");
156 }
157 }
158
159 let agent_name = name.clone();
165 let agent_root = effective_root.clone().unwrap_or_default();
166 let agent_id_handle = self.agent_id.clone();
167 tokio::task::spawn_blocking(move || {
168 if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
169 return;
170 }
171
172 let maintenance = crate::core::startup_guard::try_acquire_lock(
176 "startup-maintenance",
177 std::time::Duration::from_secs(2),
178 std::time::Duration::from_mins(2),
179 );
180 if maintenance.is_some() {
181 if let Some(home) = dirs::home_dir() {
182 let _ = crate::rules_inject::inject_all_rules(&home);
183 if crate::core::config::Config::load()
191 .setup
192 .should_inject_skills()
193 {
194 let _ = crate::rules_inject::install_all_skills(&home);
195 }
196 }
197 crate::hooks::refresh_installed_hooks();
198 crate::core::version_check::check_background();
199 let _ = crate::core::storage_maintenance::run_quiet();
203 }
204 drop(maintenance);
205
206 if !agent_root.is_empty() {
207 let heuristic_role = match agent_name.to_lowercase().as_str() {
208 n if n.contains("cursor") => Some("coder"),
209 n if n.contains("claude") => Some("coder"),
210 n if n.contains("codebuddy") => Some("coder"),
211 n if n.contains("codex") => Some("coder"),
212 n if n.contains("antigravity") || n.contains("gemini") => Some("coder"),
213 n if n.contains("review") => Some("reviewer"),
214 n if n.contains("test") => Some("debugger"),
215 _ => None,
216 };
217 let env_role = std::env::var("LEAN_CTX_ROLE")
218 .or_else(|_| std::env::var("LEAN_CTX_AGENT_ROLE"))
219 .ok();
220 let effective_role = env_role.as_deref().or(heuristic_role).unwrap_or("coder");
221
222 let _ = crate::core::roles::set_active_role_with_source(effective_role, true);
223
224 let id = crate::core::agents::AgentRegistry::mutate_locked(|registry| {
225 registry.cleanup_stale(24);
226 registry.register("mcp", Some(effective_role), &agent_root)
227 })
228 .and_then(|(_, id)| id)
229 .ok();
230 if let (Some(id), Ok(mut guard)) = (id, agent_id_handle.try_write()) {
231 *guard = Some(id);
232 }
233 }
234 });
235
236 let client_caps = crate::core::client_capabilities::ClientMcpCapabilities::detect(&name);
237 tracing::info!("Client capabilities: {}", client_caps.format_summary());
238
239 {
240 let cfg = crate::core::config::Config::load();
241 let cats = cfg.default_tool_categories_effective();
242 dynamic_tools::init_from_config(&cats);
243 }
244
245 if let Some(max) = client_caps.max_tools
246 && let Ok(mut dt) = dynamic_tools::global().lock()
247 {
248 dt.set_supports_list_changed(true);
249 if max < 100 {
250 dt.unload_category(dynamic_tools::ToolCategory::Debug);
251 dt.unload_category(dynamic_tools::ToolCategory::Memory);
252 }
253 } else if client_caps.dynamic_tools
254 && let Ok(mut dt) = dynamic_tools::global().lock()
255 {
256 dt.set_supports_list_changed(true);
257 }
258
259 crate::core::client_capabilities::set_detected(&client_caps);
260
261 let session = self.session.read().await.clone();
262
263 let capabilities = server_capabilities(client_caps.resources, client_caps.prompts);
264
265 let result = InitializeResult::new(capabilities)
266 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")));
267
268 let injection_off = crate::core::config::Config::load().rules_injection_effective()
279 == crate::core::config::RulesInjection::Off;
280 if injection_off || matches!(client_caps.client_id.as_str(), "antigravity" | "gemini-cli") {
281 Ok(result)
282 } else {
283 let instructions = crate::instructions::build_instructions_with_client_and_session(
284 CrpMode::effective(),
285 &name,
286 &session,
287 );
288 Ok(result.with_instructions(instructions))
289 }
290 }
291
292 async fn list_tools(
293 &self,
294 _request: Option<PaginatedRequestParams>,
295 _context: RequestContext<RoleServer>,
296 ) -> Result<ListToolsResult, ErrorData> {
297 use crate::server::tool_visibility::CandidateSet;
298 use std::panic::AssertUnwindSafe;
301 let computed = AssertUnwindSafe(async {
302 let cfg = crate::core::config::Config::load();
303 let disabled = cfg.disabled_tools_effective();
304 let raw_profile = cfg.tool_profile_effective();
305 let tool_profile = crate::server::tool_visibility::resolve_auto_profile(&raw_profile);
306 crate::server::tool_visibility::record_auto_turn();
307 let explicit_profile = crate::server::tool_visibility::explicit_profile(&cfg);
314
315 let client = self.client_name.read().await.clone();
316 let hook_covered = is_client_hook_covered(&client);
317
318 let candidate = crate::server::tool_visibility::candidate_set(
319 &crate::server::tool_visibility::CandidateInputs {
320 full_mode: crate::tool_defs::is_full_mode(),
321 unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
322 explicit_profile,
323 hook_covered,
324 },
325 );
326 let all_tools = match candidate {
327 CandidateSet::Full | CandidateSet::ProfileAuthoritative => {
328 if let Some(ref reg) = self.registry {
329 reg.tool_defs()
330 } else {
331 tracing::error!(
336 "list_tools served WITHOUT a tool registry (full mode) — advertising \
337 static granular defs that dispatch cannot run; tools may drift from handlers."
338 );
339 crate::tool_defs::granular_tool_defs()
340 }
341 }
342 CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
343 CandidateSet::ShadowOnly |
345 CandidateSet::LazyCore => {
346 if let Some(ref reg) = self.registry {
347 let core_names = crate::tool_defs::core_tool_names();
348 reg.tool_defs()
349 .into_iter()
350 .filter(|t| core_names.contains(&t.name.as_ref()))
351 .collect()
352 } else {
353 tracing::error!(
355 "list_tools served WITHOUT a tool registry (lazy mode) — advertising \
356 static lazy defs that dispatch cannot run; tools may drift from handlers."
357 );
358 crate::tool_defs::lazy_tool_defs()
359 }
360 }
361 };
362 let quirks = crate::server::tool_visibility::ClientQuirks::resolve(&client, candidate);
363
364 let active_role = crate::core::roles::active_role();
365 let tools: Vec<_> = all_tools
366 .into_iter()
367 .filter(|t| {
368 let name = t.name.as_ref();
369 crate::server::tool_visibility::is_tool_visible(
370 name,
371 &tool_profile,
372 &disabled,
373 quirks,
374 active_role.is_tool_allowed(name),
375 )
376 })
377 .collect();
378
379 let tools = {
384 use crate::server::tool_visibility::INVOKER;
385 let mut tools = tools;
386 let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
387 if crate::server::tool_visibility::needs_invoker(
388 crate::tool_defs::is_full_mode(),
389 already,
390 active_role.is_tool_allowed(INVOKER),
391 &disabled,
392 ) && let Some(def) = self.registry.as_ref().and_then(|reg| {
393 reg.tool_defs()
394 .into_iter()
395 .find(|t| t.name.as_ref() == INVOKER)
396 }) {
397 tools.push(def);
398 }
399 tools
400 };
401
402 let tools = {
403 let Ok(dyn_state) = dynamic_tools::global().lock() else {
404 tracing::warn!(
405 "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
406 );
407 return Ok(ListToolsResult {
408 tools,
409 ..Default::default()
410 });
411 };
412 if crate::server::tool_visibility::category_gate_applies(
420 dyn_state.supports_list_changed(),
421 explicit_profile,
422 ) {
423 tools
424 .into_iter()
425 .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
426 .collect()
427 } else {
428 tools
429 }
430 };
431
432 let tools = {
433 let active = self.workflow.read().await.clone();
434 if let Some(run) = active {
435 if run.current == "done" || is_workflow_stale(&run) {
436 let mut wf = self.workflow.write().await;
437 *wf = None;
438 let _ = crate::core::workflow::clear_active();
439 } else if let Some(state) = run.spec.state(&run.current)
440 && let Some(allowed) = &state.allowed_tools
441 {
442 let mut allow: std::collections::HashSet<&str> =
443 allowed.iter().map(std::string::String::as_str).collect();
444 for passthrough in WORKFLOW_PASSTHROUGH_TOOLS {
445 allow.insert(passthrough);
446 }
447 return Ok(ListToolsResult {
448 tools: tools
449 .into_iter()
450 .filter(|t| allow.contains(t.name.as_ref()))
451 .collect(),
452 ..Default::default()
453 });
454 }
455 }
456 tools
457 };
458
459 let tools = {
460 let cfg = crate::core::config::Config::load();
461 let level = crate::core::config::CompressionLevel::effective(&cfg);
462 let mode =
463 crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(
464 &level,
465 );
466 if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
467 tools
468 } else {
469 tools
470 .into_iter()
471 .map(|mut t| {
472 let compressed = crate::core::terse::mcp_compress::compress_description(
473 t.name.as_ref(),
474 t.description.as_deref().unwrap_or(""),
475 mode,
476 );
477 t.description = Some(compressed.into());
478 t
479 })
480 .collect()
481 }
482 };
483
484
485 let tools = crate::server::schema_hook::optimize_tools(tools, &client);
487 let tools = if quirks.hide_ctx_patch {
491 tools
492 .into_iter()
493 .map(|mut t| {
494 if let Some(ref desc) = t.description
495 && desc.contains("ctx_patch")
496 {
497 t.description =
498 Some(desc.replace("ctx_patch", "ctx_edit").into());
499 }
500 t
501 })
502 .collect()
503 } else {
504 tools
505 };
506
507 let tools = {
509 use crate::tools::InteractionMode;
510 let mode = InteractionMode::from_u8(
511 self.interaction_mode
512 .load(std::sync::atomic::Ordering::Relaxed),
513 );
514 if mode == InteractionMode::Plan {
515 let plan_set =
516 crate::core::editor_registry::plan_mode::plan_mode_tools();
517 tools
518 .into_iter()
519 .filter(|t| {
520 let n = t.name.as_ref();
521 plan_set.contains(&n) || n == "ctx_call"
522 })
523 .collect()
524 } else {
525 tools
526 }
527 };
528
529 Ok(ListToolsResult {
530 tools,
531 ..Default::default()
532 })
533 })
534 .catch_unwind()
535 .await;
536 computed.unwrap_or_else(|_| {
537 tracing::error!(
543 "list_tools panicked; serving the static lazy-core tool set as a fallback"
544 );
545 Ok(ListToolsResult {
546 tools: crate::tool_defs::lazy_tool_defs(),
547 ..Default::default()
548 })
549 })
550 }
551
552 fn list_prompts(
553 &self,
554 _request: Option<PaginatedRequestParams>,
555 _context: RequestContext<RoleServer>,
556 ) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, ErrorData>> {
557 std::future::ready(Ok(rmcp::model::ListPromptsResult::with_all_items(
558 prompts::list_prompts(),
559 )))
560 }
561
562 async fn get_prompt(
563 &self,
564 request: rmcp::model::GetPromptRequestParams,
565 _context: RequestContext<RoleServer>,
566 ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
567 let ledger = self.ledger.read().await;
568 match prompts::get_prompt(&request, &ledger) {
569 Some(result) => Ok(result),
570 None => Err(ErrorData::invalid_params(
571 format!("Unknown prompt: {}", request.name),
572 None,
573 )),
574 }
575 }
576
577 fn list_resources(
578 &self,
579 _request: Option<PaginatedRequestParams>,
580 _context: RequestContext<RoleServer>,
581 ) -> impl Future<Output = Result<rmcp::model::ListResourcesResult, rmcp::ErrorData>> {
582 std::future::ready(Ok(rmcp::model::ListResourcesResult::with_all_items(
583 resources::list_resources(),
584 )))
585 }
586
587 async fn read_resource(
588 &self,
589 request: rmcp::model::ReadResourceRequestParams,
590 _context: RequestContext<RoleServer>,
591 ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
592 let ledger = self.ledger.read().await;
593 if let Some(contents) = resources::read_resource(&request.uri, &ledger) {
594 return Ok(rmcp::model::ReadResourceResult::new(contents));
595 }
596
597 let session = self.session.read().await;
600 let root = session.project_root.as_deref();
601 match file_resource::read_file_resource(&request.uri, root, &session.extra_roots) {
602 Ok(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
603 Err(file_resource::FileResourceError::NotAFilePath) => {
604 Err(rmcp::ErrorData::resource_not_found(
605 resources::unknown_resource_message(&request.uri),
606 None,
607 ))
608 }
609 Err(e) => Err(rmcp::ErrorData::resource_not_found(e.to_string(), None)),
610 }
611 }
612
613 async fn call_tool(
614 &self,
615 request: CallToolRequestParams,
616 context: RequestContext<RoleServer>,
617 ) -> Result<CallToolResult, ErrorData> {
618 use std::panic::AssertUnwindSafe;
619
620 let progress_token = request
621 .meta
622 .as_ref()
623 .and_then(rmcp::model::Meta::get_progress_token);
624 if let Some(ref token) = progress_token {
625 let sender =
626 crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
627 *self
628 .progress_sender
629 .lock()
630 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
631 }
632
633 let tool_name_for_panic = request.name.as_ref().to_string();
634 let args_fp_for_panic = request
635 .arguments
636 .as_ref()
637 .map(|a| {
638 crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
639 a.clone(),
640 ))
641 })
642 .unwrap_or_default();
643
644 let loop_detector = self.loop_detector.clone();
645 let ct = context.ct.clone();
646
647 match AssertUnwindSafe(self.call_tool_guarded(request))
648 .catch_unwind()
649 .await
650 {
651 Ok(result) => {
652 if ct.is_cancelled() {
655 tracing::warn!(
656 "tool '{tool_name_for_panic}' completed after client cancellation — dropping result"
657 );
658 return Err(ErrorData::internal_error(
659 "request was cancelled by client",
660 None,
661 ));
662 }
663 result
664 }
665 Err(panic_payload) => {
666 let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
667 (*s).to_string()
668 } else if let Some(s) = panic_payload.downcast_ref::<String>() {
669 s.clone()
670 } else {
671 "unknown".to_string()
672 };
673 tracing::error!("call_tool panicked: {detail}");
674
675 if let Ok(mut detector) =
676 tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
677 .await
678 {
679 detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
680 }
681
682 Ok(CallToolResult::error(vec![ContentBlock::text(
683 "ERROR: lean-ctx internal error. The MCP server is still running. \
684 Please retry or use a different approach."
685 .to_string(),
686 )]))
687 }
688 }
689 }
690
691 async fn on_roots_list_changed(
692 &self,
693 _context: rmcp::service::NotificationContext<RoleServer>,
694 ) {
695 tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
696 self.roots_resolved
697 .store(false, std::sync::atomic::Ordering::Relaxed);
698 self.roots_list_attempts
700 .store(0, std::sync::atomic::Ordering::Relaxed);
701 }
702}
703
704#[cfg(test)]
705mod tests {
706 use super::*;
707
708 #[test]
714 fn server_capabilities_always_declare_tool_list_changed() {
715 for (resources, prompts) in [(true, true), (true, false), (false, true), (false, false)] {
716 let caps = server_capabilities(resources, prompts);
717 let tools = caps.tools.expect("tools capability must be advertised");
718 assert_eq!(
719 tools.list_changed,
720 Some(true),
721 "listChanged must be Some(true) for (resources={resources}, prompts={prompts})"
722 );
723 }
724 }
725
726 #[test]
730 fn lazy_core_fallback_is_never_empty() {
731 let _guard = crate::core::data_dir::isolated_data_dir();
732 let defs = crate::tool_defs::lazy_tool_defs();
733 assert!(!defs.is_empty(), "lazy-core fallback must not be empty");
734 for essential in ["ctx_read", "ctx_shell", "ctx_call"] {
735 assert!(
736 defs.iter().any(|t| t.name.as_ref() == essential),
737 "lazy-core fallback must include {essential}"
738 );
739 }
740 }
741}