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 Ok(ListToolsResult {
451 tools,
452 ..Default::default()
453 })
454 })
455 .catch_unwind()
456 .await;
457 computed.unwrap_or_else(|_| {
458 tracing::error!(
464 "list_tools panicked; serving the static lazy-core tool set as a fallback"
465 );
466 Ok(ListToolsResult {
467 tools: crate::tool_defs::lazy_tool_defs(),
468 ..Default::default()
469 })
470 })
471 }
472
473 fn list_prompts(
474 &self,
475 _request: Option<PaginatedRequestParams>,
476 _context: RequestContext<RoleServer>,
477 ) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, ErrorData>> {
478 std::future::ready(Ok(rmcp::model::ListPromptsResult::with_all_items(
479 prompts::list_prompts(),
480 )))
481 }
482
483 async fn get_prompt(
484 &self,
485 request: rmcp::model::GetPromptRequestParams,
486 _context: RequestContext<RoleServer>,
487 ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
488 let ledger = self.ledger.read().await;
489 match prompts::get_prompt(&request, &ledger) {
490 Some(result) => Ok(result),
491 None => Err(ErrorData::invalid_params(
492 format!("Unknown prompt: {}", request.name),
493 None,
494 )),
495 }
496 }
497
498 fn list_resources(
499 &self,
500 _request: Option<PaginatedRequestParams>,
501 _context: RequestContext<RoleServer>,
502 ) -> impl Future<Output = Result<rmcp::model::ListResourcesResult, rmcp::ErrorData>> {
503 std::future::ready(Ok(rmcp::model::ListResourcesResult::with_all_items(
504 resources::list_resources(),
505 )))
506 }
507
508 async fn read_resource(
509 &self,
510 request: rmcp::model::ReadResourceRequestParams,
511 _context: RequestContext<RoleServer>,
512 ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
513 let ledger = self.ledger.read().await;
514 match resources::read_resource(&request.uri, &ledger) {
515 Some(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
516 None => Err(rmcp::ErrorData::resource_not_found(
517 format!("Unknown resource: {}", request.uri),
518 None,
519 )),
520 }
521 }
522
523 async fn call_tool(
524 &self,
525 request: CallToolRequestParams,
526 context: RequestContext<RoleServer>,
527 ) -> Result<CallToolResult, ErrorData> {
528 use std::panic::AssertUnwindSafe;
529
530 let progress_token = request
531 .meta
532 .as_ref()
533 .and_then(rmcp::model::Meta::get_progress_token);
534 if let Some(ref token) = progress_token {
535 let sender =
536 crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
537 *self
538 .progress_sender
539 .lock()
540 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
541 }
542
543 let tool_name_for_panic = request.name.as_ref().to_string();
544 let args_fp_for_panic = request
545 .arguments
546 .as_ref()
547 .map(|a| {
548 crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
549 a.clone(),
550 ))
551 })
552 .unwrap_or_default();
553
554 let loop_detector = self.loop_detector.clone();
555
556 match AssertUnwindSafe(self.call_tool_guarded(request))
557 .catch_unwind()
558 .await
559 {
560 Ok(result) => result,
561 Err(panic_payload) => {
562 let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
563 (*s).to_string()
564 } else if let Some(s) = panic_payload.downcast_ref::<String>() {
565 s.clone()
566 } else {
567 "unknown".to_string()
568 };
569 tracing::error!("call_tool panicked: {detail}");
570
571 if let Ok(mut detector) =
572 tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
573 .await
574 {
575 detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
576 }
577
578 Ok(CallToolResult::error(vec![ContentBlock::text(
579 "ERROR: lean-ctx internal error. The MCP server is still running. \
580 Please retry or use a different approach."
581 .to_string(),
582 )]))
583 }
584 }
585 }
586
587 async fn on_roots_list_changed(
588 &self,
589 _context: rmcp::service::NotificationContext<RoleServer>,
590 ) {
591 tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
592 self.roots_resolved
593 .store(false, std::sync::atomic::Ordering::Relaxed);
594 self.roots_list_attempts
596 .store(0, std::sync::atomic::Ordering::Relaxed);
597 }
598}
599
600#[cfg(test)]
601mod tests {
602 use super::*;
603
604 #[test]
610 fn server_capabilities_always_declare_tool_list_changed() {
611 for (resources, prompts) in [(true, true), (true, false), (false, true), (false, false)] {
612 let caps = server_capabilities(resources, prompts);
613 let tools = caps.tools.expect("tools capability must be advertised");
614 assert_eq!(
615 tools.list_changed,
616 Some(true),
617 "listChanged must be Some(true) for (resources={resources}, prompts={prompts})"
618 );
619 }
620 }
621
622 #[test]
626 fn lazy_core_fallback_is_never_empty() {
627 let _guard = crate::core::data_dir::isolated_data_dir();
628 let defs = crate::tool_defs::lazy_tool_defs();
629 assert!(!defs.is_empty(), "lazy-core fallback must not be empty");
630 for essential in ["ctx_read", "ctx_shell", "ctx_call"] {
631 assert!(
632 defs.iter().any(|t| t.name.as_ref() == essential),
633 "lazy-core fallback must include {essential}"
634 );
635 }
636 }
637}