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 if self.session_mode == crate::tools::SessionMode::Shared {
141 if let Some(ref root) = session.project_root
142 && let Some(ref rt) = self.context_os
143 {
144 rt.shared_sessions.persist_best_effort(
145 root,
146 &self.workspace_id,
147 &self.channel_id,
148 &session,
149 );
150 rt.metrics.record_session_persisted();
151 }
152 } else if let Err(e) = session.save() {
153 tracing::warn!("lean-ctx: failed to persist session state: {e}");
154 }
155 }
156
157 let agent_name = name.clone();
163 let agent_root = effective_root.clone().unwrap_or_default();
164 let agent_id_handle = self.agent_id.clone();
165 tokio::task::spawn_blocking(move || {
166 if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
167 return;
168 }
169
170 let maintenance = crate::core::startup_guard::try_acquire_lock(
174 "startup-maintenance",
175 std::time::Duration::from_secs(2),
176 std::time::Duration::from_mins(2),
177 );
178 if maintenance.is_some() {
179 if let Some(home) = dirs::home_dir() {
180 let _ = crate::rules_inject::inject_all_rules(&home);
181 if crate::core::config::Config::load()
189 .setup
190 .should_inject_skills()
191 {
192 let _ = crate::rules_inject::install_all_skills(&home);
193 }
194 }
195 crate::hooks::refresh_installed_hooks();
196 crate::core::version_check::check_background();
197 let _ = crate::core::storage_maintenance::run_quiet();
201 }
202 drop(maintenance);
203
204 if !agent_root.is_empty() {
205 let heuristic_role = match agent_name.to_lowercase().as_str() {
206 n if n.contains("cursor") => Some("coder"),
207 n if n.contains("claude") => Some("coder"),
208 n if n.contains("codebuddy") => Some("coder"),
209 n if n.contains("codex") => Some("coder"),
210 n if n.contains("antigravity") || n.contains("gemini") => Some("coder"),
211 n if n.contains("review") => Some("reviewer"),
212 n if n.contains("test") => Some("debugger"),
213 _ => None,
214 };
215 let env_role = std::env::var("LEAN_CTX_ROLE")
216 .or_else(|_| std::env::var("LEAN_CTX_AGENT_ROLE"))
217 .ok();
218 let effective_role = env_role.as_deref().or(heuristic_role).unwrap_or("coder");
219
220 let _ = crate::core::roles::set_active_role_with_source(effective_role, true);
221
222 let mut registry = crate::core::agents::AgentRegistry::load_or_create();
223 registry.cleanup_stale(24);
224 let id = registry.register("mcp", Some(effective_role), &agent_root);
225 let _ = registry.save();
226 if let Ok(mut guard) = agent_id_handle.try_write() {
227 *guard = Some(id);
228 }
229 }
230 });
231
232 let client_caps = crate::core::client_capabilities::ClientMcpCapabilities::detect(&name);
233 tracing::info!("Client capabilities: {}", client_caps.format_summary());
234
235 {
236 let cfg = crate::core::config::Config::load();
237 let cats = cfg.default_tool_categories_effective();
238 dynamic_tools::init_from_config(&cats);
239 }
240
241 if let Some(max) = client_caps.max_tools
242 && let Ok(mut dt) = dynamic_tools::global().lock()
243 {
244 dt.set_supports_list_changed(true);
245 if max < 100 {
246 dt.unload_category(dynamic_tools::ToolCategory::Debug);
247 dt.unload_category(dynamic_tools::ToolCategory::Memory);
248 }
249 } else if client_caps.dynamic_tools
250 && let Ok(mut dt) = dynamic_tools::global().lock()
251 {
252 dt.set_supports_list_changed(true);
253 }
254
255 crate::core::client_capabilities::set_detected(&client_caps);
256
257 let instructions =
258 crate::instructions::build_instructions_with_client(CrpMode::effective(), &name);
259
260 let capabilities = server_capabilities(client_caps.resources, client_caps.prompts);
261
262 Ok(InitializeResult::new(capabilities)
263 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
264 .with_instructions(instructions))
265 }
266
267 async fn list_tools(
268 &self,
269 _request: Option<PaginatedRequestParams>,
270 _context: RequestContext<RoleServer>,
271 ) -> Result<ListToolsResult, ErrorData> {
272 use crate::server::tool_visibility::CandidateSet;
273 use std::panic::AssertUnwindSafe;
276 let computed = AssertUnwindSafe(async {
277 let cfg = crate::core::config::Config::load();
278 let disabled = cfg.disabled_tools_effective();
279 let tool_profile = cfg.tool_profile_effective();
280 let explicit_profile = crate::server::tool_visibility::explicit_profile(&cfg);
287
288 let candidate = crate::server::tool_visibility::candidate_set(
289 crate::tool_defs::is_full_mode(),
290 std::env::var("LEAN_CTX_UNIFIED").is_ok(),
291 explicit_profile,
292 );
293 let all_tools = match candidate {
294 CandidateSet::Full | CandidateSet::ProfileAuthoritative => {
295 if let Some(ref reg) = self.registry {
296 reg.tool_defs()
297 } else {
298 tracing::error!(
303 "list_tools served WITHOUT a tool registry (full mode) — advertising \
304 static granular defs that dispatch cannot run; tools may drift from handlers."
305 );
306 crate::tool_defs::granular_tool_defs()
307 }
308 }
309 CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
310 CandidateSet::LazyCore => {
311 if let Some(ref reg) = self.registry {
312 let core_names = crate::tool_defs::core_tool_names();
313 reg.tool_defs()
314 .into_iter()
315 .filter(|t| core_names.contains(&t.name.as_ref()))
316 .collect()
317 } else {
318 tracing::error!(
320 "list_tools served WITHOUT a tool registry (lazy mode) — advertising \
321 static lazy defs that dispatch cannot run; tools may drift from handlers."
322 );
323 crate::tool_defs::lazy_tool_defs()
324 }
325 }
326 };
327 let client = self.client_name.read().await.clone();
328 let quirks = crate::server::tool_visibility::ClientQuirks::resolve(&client, candidate);
329
330 let active_role = crate::core::roles::active_role();
331 let tools: Vec<_> = all_tools
332 .into_iter()
333 .filter(|t| {
334 let name = t.name.as_ref();
335 crate::server::tool_visibility::is_tool_visible(
336 name,
337 &tool_profile,
338 &disabled,
339 quirks,
340 active_role.is_tool_allowed(name),
341 )
342 })
343 .collect();
344
345 let tools = {
350 use crate::server::tool_visibility::INVOKER;
351 let mut tools = tools;
352 let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
353 if crate::server::tool_visibility::needs_invoker(
354 crate::tool_defs::is_full_mode(),
355 already,
356 active_role.is_tool_allowed(INVOKER),
357 &disabled,
358 ) && let Some(def) = self.registry.as_ref().and_then(|reg| {
359 reg.tool_defs()
360 .into_iter()
361 .find(|t| t.name.as_ref() == INVOKER)
362 }) {
363 tools.push(def);
364 }
365 tools
366 };
367
368 let tools = {
369 let Ok(dyn_state) = dynamic_tools::global().lock() else {
370 tracing::warn!(
371 "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
372 );
373 return Ok(ListToolsResult {
374 tools,
375 ..Default::default()
376 });
377 };
378 if crate::server::tool_visibility::category_gate_applies(
386 dyn_state.supports_list_changed(),
387 explicit_profile,
388 ) {
389 tools
390 .into_iter()
391 .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
392 .collect()
393 } else {
394 tools
395 }
396 };
397
398 let tools = {
399 let active = self.workflow.read().await.clone();
400 if let Some(run) = active {
401 if run.current == "done" || is_workflow_stale(&run) {
402 let mut wf = self.workflow.write().await;
403 *wf = None;
404 let _ = crate::core::workflow::clear_active();
405 } else if let Some(state) = run.spec.state(&run.current)
406 && let Some(allowed) = &state.allowed_tools
407 {
408 let mut allow: std::collections::HashSet<&str> =
409 allowed.iter().map(std::string::String::as_str).collect();
410 for passthrough in WORKFLOW_PASSTHROUGH_TOOLS {
411 allow.insert(passthrough);
412 }
413 return Ok(ListToolsResult {
414 tools: tools
415 .into_iter()
416 .filter(|t| allow.contains(t.name.as_ref()))
417 .collect(),
418 ..Default::default()
419 });
420 }
421 }
422 tools
423 };
424
425 let tools = {
426 let cfg = crate::core::config::Config::load();
427 let level = crate::core::config::CompressionLevel::effective(&cfg);
428 let mode =
429 crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(
430 &level,
431 );
432 if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
433 tools
434 } else {
435 tools
436 .into_iter()
437 .map(|mut t| {
438 let compressed = crate::core::terse::mcp_compress::compress_description(
439 t.name.as_ref(),
440 t.description.as_deref().unwrap_or(""),
441 mode,
442 );
443 t.description = Some(compressed.into());
444 t
445 })
446 .collect()
447 }
448 };
449
450 let tools = if quirks.hide_ctx_patch {
454 tools
455 .into_iter()
456 .map(|mut t| {
457 if let Some(ref desc) = t.description
458 && desc.contains("ctx_patch")
459 {
460 t.description =
461 Some(desc.replace("ctx_patch", "ctx_edit").into());
462 }
463 t
464 })
465 .collect()
466 } else {
467 tools
468 };
469
470 Ok(ListToolsResult {
471 tools,
472 ..Default::default()
473 })
474 })
475 .catch_unwind()
476 .await;
477 computed.unwrap_or_else(|_| {
478 tracing::error!(
484 "list_tools panicked; serving the static lazy-core tool set as a fallback"
485 );
486 Ok(ListToolsResult {
487 tools: crate::tool_defs::lazy_tool_defs(),
488 ..Default::default()
489 })
490 })
491 }
492
493 fn list_prompts(
494 &self,
495 _request: Option<PaginatedRequestParams>,
496 _context: RequestContext<RoleServer>,
497 ) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, ErrorData>> {
498 std::future::ready(Ok(rmcp::model::ListPromptsResult::with_all_items(
499 prompts::list_prompts(),
500 )))
501 }
502
503 async fn get_prompt(
504 &self,
505 request: rmcp::model::GetPromptRequestParams,
506 _context: RequestContext<RoleServer>,
507 ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
508 let ledger = self.ledger.read().await;
509 match prompts::get_prompt(&request, &ledger) {
510 Some(result) => Ok(result),
511 None => Err(ErrorData::invalid_params(
512 format!("Unknown prompt: {}", request.name),
513 None,
514 )),
515 }
516 }
517
518 fn list_resources(
519 &self,
520 _request: Option<PaginatedRequestParams>,
521 _context: RequestContext<RoleServer>,
522 ) -> impl Future<Output = Result<rmcp::model::ListResourcesResult, rmcp::ErrorData>> {
523 std::future::ready(Ok(rmcp::model::ListResourcesResult::with_all_items(
524 resources::list_resources(),
525 )))
526 }
527
528 async fn read_resource(
529 &self,
530 request: rmcp::model::ReadResourceRequestParams,
531 _context: RequestContext<RoleServer>,
532 ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
533 let ledger = self.ledger.read().await;
534 match resources::read_resource(&request.uri, &ledger) {
535 Some(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
536 None => Err(rmcp::ErrorData::resource_not_found(
537 format!("Unknown resource: {}", request.uri),
538 None,
539 )),
540 }
541 }
542
543 async fn call_tool(
544 &self,
545 request: CallToolRequestParams,
546 context: RequestContext<RoleServer>,
547 ) -> Result<CallToolResult, ErrorData> {
548 use std::panic::AssertUnwindSafe;
549
550 let progress_token = request
551 .meta
552 .as_ref()
553 .and_then(rmcp::model::Meta::get_progress_token);
554 if let Some(ref token) = progress_token {
555 let sender =
556 crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
557 *self
558 .progress_sender
559 .lock()
560 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
561 }
562
563 let tool_name_for_panic = request.name.as_ref().to_string();
564 let args_fp_for_panic = request
565 .arguments
566 .as_ref()
567 .map(|a| {
568 crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
569 a.clone(),
570 ))
571 })
572 .unwrap_or_default();
573
574 let loop_detector = self.loop_detector.clone();
575
576 match AssertUnwindSafe(self.call_tool_guarded(request))
577 .catch_unwind()
578 .await
579 {
580 Ok(result) => result,
581 Err(panic_payload) => {
582 let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
583 (*s).to_string()
584 } else if let Some(s) = panic_payload.downcast_ref::<String>() {
585 s.clone()
586 } else {
587 "unknown".to_string()
588 };
589 tracing::error!("call_tool panicked: {detail}");
590
591 if let Ok(mut detector) =
592 tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
593 .await
594 {
595 detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
596 }
597
598 Ok(CallToolResult::error(vec![ContentBlock::text(
599 "ERROR: lean-ctx internal error. The MCP server is still running. \
600 Please retry or use a different approach."
601 .to_string(),
602 )]))
603 }
604 }
605 }
606
607 async fn on_roots_list_changed(
608 &self,
609 _context: rmcp::service::NotificationContext<RoleServer>,
610 ) {
611 tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
612 self.roots_resolved
613 .store(false, std::sync::atomic::Ordering::Relaxed);
614 self.roots_list_attempts
616 .store(0, std::sync::atomic::Ordering::Relaxed);
617 }
618}
619
620#[cfg(test)]
621mod tests {
622 use super::*;
623
624 #[test]
630 fn server_capabilities_always_declare_tool_list_changed() {
631 for (resources, prompts) in [(true, true), (true, false), (false, true), (false, false)] {
632 let caps = server_capabilities(resources, prompts);
633 let tools = caps.tools.expect("tools capability must be advertised");
634 assert_eq!(
635 tools.list_changed,
636 Some(true),
637 "listChanged must be Some(true) for (resources={resources}, prompts={prompts})"
638 );
639 }
640 }
641
642 #[test]
646 fn lazy_core_fallback_is_never_empty() {
647 let _guard = crate::core::data_dir::isolated_data_dir();
648 let defs = crate::tool_defs::lazy_tool_defs();
649 assert!(!defs.is_empty(), "lazy-core fallback must not be empty");
650 for essential in ["ctx_read", "ctx_shell", "ctx_call"] {
651 assert!(
652 defs.iter().any(|t| t.name.as_ref() == essential),
653 "lazy-core fallback must include {essential}"
654 );
655 }
656 }
657}