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
47fn suppress_initialize_instructions(client_id: &str) -> bool {
48 let cfg = crate::core::config::Config::load();
49
50 cfg.declines_rule_steering() || matches!(client_id, "antigravity" | "gemini-cli")
51}
52impl ServerHandler for LeanCtxServer {
53 fn get_info(&self) -> ServerInfo {
54 let capabilities = server_capabilities(true, true);
55
56 let instructions = crate::instructions::build_instructions(CrpMode::effective());
57
58 InitializeResult::new(capabilities)
59 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
60 .with_instructions(instructions)
61 }
62
63 async fn initialize(
64 &self,
65 request: InitializeRequestParams,
66 context: RequestContext<RoleServer>,
67 ) -> Result<InitializeResult, ErrorData> {
68 let name = request.client_info.name.clone();
69 tracing::info!("MCP client connected: {:?}", name);
70 *self.client_name.write().await = name.clone();
71 *self.peer.write().await = Some(context.peer.clone());
72
73 if self.session_mode != crate::tools::SessionMode::Shared {
74 crate::core::budget_tracker::BudgetTracker::global().reset();
75 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
76 let radar = data_dir.join("context_radar.jsonl");
77 if radar.exists() {
78 let prev = data_dir.join("context_radar.prev.jsonl");
79 let _ = std::fs::rename(&radar, &prev);
80 }
81 }
82 }
83
84 let has_roots = request.capabilities.roots.is_some();
85 self.has_client_roots
86 .store(has_roots, std::sync::atomic::Ordering::Relaxed);
87 if has_roots {
88 tracing::info!("Client supports MCP roots/list — will resolve on first tool call");
89 }
90
91 let env_root = roots::root_from_env().or_else(roots::root_from_workspace_env);
92 let derived_root = derive_project_root_from_cwd();
93 let effective_root = env_root.or(derived_root);
94
95 let cwd_str = std::env::current_dir()
96 .ok()
97 .map(|p| p.to_string_lossy().to_string())
98 .unwrap_or_default();
99 {
100 let mut session = self.session.write().await;
101 if !cwd_str.is_empty() {
102 session.shell_cwd = Some(cwd_str.clone());
103 }
104 if let Some(ref root) = effective_root {
105 session.project_root = Some(root.clone());
106 tracing::info!("Project root set to: {root}");
107 for other in roots::workspace_roots_from_env() {
111 if &other != root && !session.extra_roots.contains(&other) {
112 session.extra_roots.push(other);
113 }
114 }
115 } else if let Some(ref root) = session.project_root {
116 let root_path = std::path::Path::new(root);
121 let root_has_marker = has_project_marker(root_path);
122 let root_str = root_path.to_string_lossy();
123 let root_suspicious = crate::core::pathutil::is_broad_or_unsafe_root(root_path)
124 || root_str.contains("/var/folders/")
125 || root_str.contains("/tmp/")
126 || root_str.contains("/.lmstudio")
127 || root_str.contains("\\AppData\\Local\\Temp")
128 || root_str.contains("\\Temp\\")
129 || root_str.contains("\\.lmstudio");
130 if root_suspicious && !root_has_marker {
131 tracing::info!("Dropping suspicious persisted project root: {root}");
132 session.project_root = None;
133 }
134 }
135 let cfg_extra = crate::core::config::Config::load().extra_roots;
136 if !cfg_extra.is_empty() {
137 let existing: std::collections::HashSet<_> =
138 session.extra_roots.iter().cloned().collect();
139 for r in cfg_extra {
140 if !existing.contains(&r) {
141 session.extra_roots.push(r);
142 }
143 }
144 }
145 session.refresh_handoff_context();
146
147 if self.session_mode == crate::tools::SessionMode::Shared {
148 if let Some(ref root) = session.project_root
149 && let Some(ref rt) = self.context_os
150 {
151 rt.shared_sessions.persist_best_effort(
152 root,
153 &self.workspace_id,
154 &self.channel_id,
155 &session,
156 );
157 rt.metrics.record_session_persisted();
158 }
159 } else if let Err(e) = session.save() {
160 tracing::warn!("lean-ctx: failed to persist session state: {e}");
165 }
166 }
167
168 let agent_name = name.clone();
174 let agent_root = effective_root.clone().unwrap_or_default();
175 let agent_id_handle = self.agent_id.clone();
176 let presence_agent_id_handle = self.presence_agent_id.clone();
177 let presence_role_handle = self.presence_role.clone();
178 let presence_read_only_handle = self.presence_read_only.clone();
179 tokio::task::spawn_blocking(move || {
180 if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
181 return;
182 }
183
184 let maintenance = crate::core::startup_guard::try_acquire_lock(
188 "startup-maintenance",
189 std::time::Duration::from_secs(2),
190 std::time::Duration::from_mins(2),
191 );
192 if maintenance.is_some() {
193 if let Some(home) = dirs::home_dir() {
194 startup_rule_maintenance_at_home(&home);
195 if crate::core::config::Config::load()
203 .setup
204 .should_inject_skills()
205 {
206 let _ = crate::rules_inject::install_all_skills(&home);
207 }
208 }
209 crate::hooks::refresh_installed_hooks();
210 crate::core::version_check::check_background();
211 let _ = crate::core::storage_maintenance::run_quiet();
215 }
216 drop(maintenance);
217
218 if !agent_root.is_empty() {
219 let heuristic_role = match agent_name.to_lowercase().as_str() {
220 n if n.contains("cursor") => Some("coder"),
221 n if n.contains("claude") => Some("coder"),
222 n if n.contains("codebuddy") => Some("coder"),
223 n if n.contains("codex") => Some("coder"),
224 n if n.contains("antigravity") || n.contains("gemini") => Some("coder"),
225 n if n.contains("review") => Some("reviewer"),
226 n if n.contains("test") => Some("debugger"),
227 _ => None,
228 };
229 let env_role = std::env::var("LEAN_CTX_ROLE")
230 .or_else(|_| std::env::var("LEAN_CTX_AGENT_ROLE"))
231 .ok();
232 let effective_role = env_role.as_deref().or(heuristic_role).unwrap_or("coder");
233
234 let _ = crate::core::roles::set_active_role_with_source(effective_role, true);
235 if let Ok(mut guard) = presence_role_handle.try_write() {
238 *guard = Some(effective_role.to_string());
239 }
240
241 let registration = crate::core::agents::AgentRegistry::mutate_locked(|registry| {
242 registry.cleanup_stale(24);
243 registry.register("mcp", Some(effective_role), &agent_root)
244 })
245 .and_then(|(_, id)| id);
246 let id = match registration {
247 Ok(id) => {
248 presence_read_only_handle
249 .store(false, std::sync::atomic::Ordering::Relaxed);
250 Some(id)
251 }
252 Err(error)
256 if crate::core::agents::AgentRegistry::is_mutating_capacity_error(
257 &error,
258 ) =>
259 {
260 tracing::warn!(
261 "lean-ctx: {error}; admitting {effective_role} session read-only"
262 );
263 match crate::core::agents::AgentRegistry::admit_read_only_presence(
264 &agent_root,
265 effective_role,
266 ) {
267 Ok(id) => {
268 presence_read_only_handle
269 .store(true, std::sync::atomic::Ordering::Relaxed);
270 Some(id)
271 }
272 Err(error) => {
273 tracing::warn!("lean-ctx: read-only admission failed: {error}");
274 None
275 }
276 }
277 }
278 Err(error) => {
279 tracing::warn!("lean-ctx: agent registration failed: {error}");
280 None
281 }
282 };
283 if let (Some(id), Ok(mut guard)) = (id.as_ref(), agent_id_handle.try_write()) {
284 *guard = Some(id.clone());
285 }
286 if let (Some(id), Ok(mut guard)) = (id, presence_agent_id_handle.try_write()) {
287 *guard = Some(id);
288 }
289 }
290 });
291
292 let client_caps = crate::core::client_capabilities::ClientMcpCapabilities::detect(&name);
293 tracing::info!("Client capabilities: {}", client_caps.format_summary());
294
295 {
296 let cfg = crate::core::config::Config::load();
297 let cats = cfg.default_tool_categories_effective();
298 dynamic_tools::init_from_config(&cats);
299 }
300
301 if let Some(max) = client_caps.max_tools
302 && let Ok(mut dt) = dynamic_tools::global().lock()
303 {
304 dt.set_supports_list_changed(true);
305 if max < 100 {
306 dt.unload_category(dynamic_tools::ToolCategory::Debug);
307 dt.unload_category(dynamic_tools::ToolCategory::Memory);
308 }
309 } else if client_caps.dynamic_tools
310 && let Ok(mut dt) = dynamic_tools::global().lock()
311 {
312 dt.set_supports_list_changed(true);
313 }
314
315 crate::core::client_capabilities::set_detected(&client_caps);
316
317 let session = self.session.read().await.clone();
318
319 let capabilities = server_capabilities(client_caps.resources, client_caps.prompts);
320
321 let result = InitializeResult::new(capabilities)
322 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")));
323
324 if suppress_initialize_instructions(client_caps.client_id.as_str()) {
334 Ok(result)
335 } else {
336 let instructions = crate::instructions::build_instructions_with_client_and_session(
337 CrpMode::effective(),
338 &name,
339 &session,
340 );
341 Ok(result.with_instructions(instructions))
342 }
343 }
344
345 async fn list_tools(
346 &self,
347 _request: Option<PaginatedRequestParams>,
348 _context: RequestContext<RoleServer>,
349 ) -> Result<ListToolsResult, ErrorData> {
350 use crate::server::tool_visibility::CandidateSet;
351 use std::panic::AssertUnwindSafe;
354 let computed = AssertUnwindSafe(async {
355 let cfg = crate::core::config::Config::load();
356 let disabled = cfg.disabled_tools_effective();
357 let raw_profile = cfg.tool_profile_effective();
358 let tool_profile = crate::server::tool_visibility::resolve_auto_profile(&raw_profile);
359 crate::server::tool_visibility::record_auto_turn();
360 let explicit_profile = crate::server::tool_visibility::explicit_profile(&cfg);
367
368 let client = self.client_name.read().await.clone();
369 let hook_covered = is_client_hook_covered(&client);
370
371 let candidate = crate::server::tool_visibility::candidate_set(
372 &crate::server::tool_visibility::CandidateInputs {
373 full_mode: crate::tool_defs::is_full_mode(),
374 unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
375 explicit_profile,
376 hook_covered,
377 },
378 );
379 let all_tools = match candidate {
380 CandidateSet::Full | CandidateSet::ProfileAuthoritative => {
381 if let Some(ref reg) = self.registry {
382 reg.tool_defs()
383 } else {
384 tracing::error!(
389 "list_tools served WITHOUT a tool registry (full mode) — advertising \
390 static granular defs that dispatch cannot run; tools may drift from handlers."
391 );
392 crate::tool_defs::granular_tool_defs()
393 }
394 }
395 CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
396 CandidateSet::ShadowOnly |
398 CandidateSet::LazyCore => {
399 if let Some(ref reg) = self.registry {
400 let core_names = crate::tool_defs::core_tool_names();
401 reg.tool_defs()
402 .into_iter()
403 .filter(|t| core_names.contains(&t.name.as_ref()))
404 .collect()
405 } else {
406 tracing::error!(
408 "list_tools served WITHOUT a tool registry (lazy mode) — advertising \
409 static lazy defs that dispatch cannot run; tools may drift from handlers."
410 );
411 crate::tool_defs::lazy_tool_defs()
412 }
413 }
414 };
415 let quirks = crate::server::tool_visibility::ClientQuirks::resolve(&client, candidate);
416
417 let active_role = crate::core::roles::active_role();
418 let tools: Vec<_> = all_tools
419 .into_iter()
420 .filter(|t| {
421 let name = t.name.as_ref();
422 crate::server::tool_visibility::is_tool_visible(
423 name,
424 &tool_profile,
425 &disabled,
426 quirks,
427 active_role.is_tool_allowed(name),
428 )
429 })
430 .collect();
431
432 let tools = {
437 use crate::server::tool_visibility::INVOKER;
438 let mut tools = tools;
439 let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
440 if crate::server::tool_visibility::needs_invoker(
441 crate::tool_defs::is_full_mode(),
442 already,
443 active_role.is_tool_allowed(INVOKER),
444 &disabled,
445 ) && let Some(def) = self.registry.as_ref().and_then(|reg| {
446 reg.tool_defs()
447 .into_iter()
448 .find(|t| t.name.as_ref() == INVOKER)
449 }) {
450 tools.push(def);
451 }
452 tools
453 };
454
455 let tools = {
456 let Ok(dyn_state) = dynamic_tools::global().lock() else {
457 tracing::warn!(
458 "dynamic_tools mutex poisoned in list_tools; returning unfiltered"
459 );
460 return Ok(ListToolsResult {
461 tools,
462 ..Default::default()
463 });
464 };
465 if crate::server::tool_visibility::category_gate_applies(
473 dyn_state.supports_list_changed(),
474 explicit_profile,
475 ) {
476 tools
477 .into_iter()
478 .filter(|t| dyn_state.is_tool_active(t.name.as_ref()))
479 .collect()
480 } else {
481 tools
482 }
483 };
484
485 let tools = {
486 let active = self.workflow.read().await.clone();
487 if let Some(run) = active {
488 if run.current == "done" || is_workflow_stale(&run) {
489 let mut wf = self.workflow.write().await;
490 *wf = None;
491 let _ = crate::core::workflow::clear_active();
492 } else if let Some(state) = run.spec.state(&run.current)
493 && let Some(allowed) = &state.allowed_tools
494 {
495 let mut allow: std::collections::HashSet<&str> =
496 allowed.iter().map(std::string::String::as_str).collect();
497 for passthrough in WORKFLOW_PASSTHROUGH_TOOLS {
498 allow.insert(passthrough);
499 }
500 return Ok(ListToolsResult {
501 tools: tools
502 .into_iter()
503 .filter(|t| allow.contains(t.name.as_ref()))
504 .collect(),
505 ..Default::default()
506 });
507 }
508 }
509 tools
510 };
511
512 let tools = {
513 let cfg = crate::core::config::Config::load();
514 let level = crate::core::config::CompressionLevel::effective(&cfg);
515 let mode =
516 crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(
517 &level,
518 );
519 if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
520 tools
521 } else {
522 tools
523 .into_iter()
524 .map(|mut t| {
525 let compressed = crate::core::terse::mcp_compress::compress_description(
526 t.name.as_ref(),
527 t.description.as_deref().unwrap_or(""),
528 mode,
529 );
530 t.description = Some(compressed.into());
531 t
532 })
533 .collect()
534 }
535 };
536
537
538 let tools = crate::server::schema_hook::optimize_tools(tools, &client);
540 let tools = if quirks.hide_ctx_patch {
544 tools
545 .into_iter()
546 .map(|mut t| {
547 if let Some(ref desc) = t.description
548 && desc.contains("ctx_patch")
549 {
550 t.description =
551 Some(desc.replace("ctx_patch", "ctx_edit").into());
552 }
553 t
554 })
555 .collect()
556 } else {
557 tools
558 };
559
560 let tools = {
562 use crate::tools::InteractionMode;
563 let mode = InteractionMode::from_u8(
564 self.interaction_mode
565 .load(std::sync::atomic::Ordering::Relaxed),
566 );
567 if mode == InteractionMode::Plan {
568 let plan_set =
569 crate::core::editor_registry::plan_mode::plan_mode_tools();
570 tools
571 .into_iter()
572 .filter(|t| {
573 let n = t.name.as_ref();
574 plan_set.contains(&n) || n == "ctx_call"
575 })
576 .collect()
577 } else {
578 tools
579 }
580 };
581
582 Ok(ListToolsResult {
583 tools,
584 ..Default::default()
585 })
586 })
587 .catch_unwind()
588 .await;
589 computed.unwrap_or_else(|_| {
590 tracing::error!(
596 "list_tools panicked; serving the static lazy-core tool set as a fallback"
597 );
598 Ok(ListToolsResult {
599 tools: crate::tool_defs::lazy_tool_defs(),
600 ..Default::default()
601 })
602 })
603 }
604
605 fn list_prompts(
606 &self,
607 _request: Option<PaginatedRequestParams>,
608 _context: RequestContext<RoleServer>,
609 ) -> impl Future<Output = Result<rmcp::model::ListPromptsResult, ErrorData>> {
610 std::future::ready(Ok(rmcp::model::ListPromptsResult::with_all_items(
611 prompts::list_prompts(),
612 )))
613 }
614
615 async fn get_prompt(
616 &self,
617 request: rmcp::model::GetPromptRequestParams,
618 _context: RequestContext<RoleServer>,
619 ) -> Result<rmcp::model::GetPromptResult, ErrorData> {
620 let ledger = self.ledger.read().await;
621 match prompts::get_prompt(&request, &ledger) {
622 Some(result) => Ok(result),
623 None => Err(ErrorData::invalid_params(
624 format!("Unknown prompt: {}", request.name),
625 None,
626 )),
627 }
628 }
629
630 fn list_resources(
631 &self,
632 _request: Option<PaginatedRequestParams>,
633 _context: RequestContext<RoleServer>,
634 ) -> impl Future<Output = Result<rmcp::model::ListResourcesResult, rmcp::ErrorData>> {
635 std::future::ready(Ok(rmcp::model::ListResourcesResult::with_all_items(
636 resources::list_resources(),
637 )))
638 }
639
640 async fn read_resource(
641 &self,
642 request: rmcp::model::ReadResourceRequestParams,
643 _context: RequestContext<RoleServer>,
644 ) -> Result<rmcp::model::ReadResourceResult, rmcp::ErrorData> {
645 let ledger = self.ledger.read().await;
646 if let Some(contents) = resources::read_resource(&request.uri, &ledger) {
647 return Ok(rmcp::model::ReadResourceResult::new(contents));
648 }
649
650 let session = self.session.read().await;
653 let root = session.project_root.as_deref();
654 match file_resource::read_file_resource(&request.uri, root, &session.extra_roots) {
655 Ok(contents) => Ok(rmcp::model::ReadResourceResult::new(contents)),
656 Err(file_resource::FileResourceError::NotAFilePath) => {
657 Err(rmcp::ErrorData::resource_not_found(
658 resources::unknown_resource_message(&request.uri),
659 None,
660 ))
661 }
662 Err(e) => Err(rmcp::ErrorData::resource_not_found(e.to_string(), None)),
663 }
664 }
665
666 async fn call_tool(
667 &self,
668 request: CallToolRequestParams,
669 context: RequestContext<RoleServer>,
670 ) -> Result<CallToolResult, ErrorData> {
671 use std::panic::AssertUnwindSafe;
672
673 let progress_token = request
674 .meta
675 .as_ref()
676 .and_then(rmcp::model::Meta::get_progress_token);
677 if let Some(ref token) = progress_token {
678 let sender =
679 crate::server::progress::ProgressSender::new(context.peer.clone(), token.clone());
680 *self
681 .progress_sender
682 .lock()
683 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sender);
684 }
685
686 let tool_name_for_panic = request.name.as_ref().to_string();
687 let args_fp_for_panic = request
688 .arguments
689 .as_ref()
690 .map(|a| {
691 crate::core::loop_detection::LoopDetector::fingerprint(&serde_json::Value::Object(
692 a.clone(),
693 ))
694 })
695 .unwrap_or_default();
696
697 let loop_detector = self.loop_detector.clone();
698 let ct = context.ct.clone();
699
700 match AssertUnwindSafe(
704 crate::server::tool_trait::REQUEST_CT
705 .scope(ct.clone(), self.call_tool_guarded(request)),
706 )
707 .catch_unwind()
708 .await
709 {
710 Ok(result) => {
711 if ct.is_cancelled() {
714 tracing::warn!(
715 "tool '{tool_name_for_panic}' completed after client cancellation — dropping result"
716 );
717 return Err(ErrorData::internal_error(
718 "request was cancelled by client",
719 None,
720 ));
721 }
722 result
723 }
724 Err(panic_payload) => {
725 let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
726 (*s).to_string()
727 } else if let Some(s) = panic_payload.downcast_ref::<String>() {
728 s.clone()
729 } else {
730 "unknown".to_string()
731 };
732 tracing::error!("call_tool panicked: {detail}");
733
734 if let Ok(mut detector) =
735 tokio::time::timeout(std::time::Duration::from_secs(1), loop_detector.write())
736 .await
737 {
738 detector.record_error_outcome(&tool_name_for_panic, &args_fp_for_panic);
739 }
740
741 Ok(CallToolResult::error(vec![ContentBlock::text(
742 "ERROR: lean-ctx internal error. The MCP server is still running. \
743 Please retry or use a different approach."
744 .to_string(),
745 )]))
746 }
747 }
748 }
749
750 async fn on_roots_list_changed(
751 &self,
752 _context: rmcp::service::NotificationContext<RoleServer>,
753 ) {
754 tracing::info!("Received roots/list_changed — will re-resolve on next tool call");
755 self.roots_resolved
756 .store(false, std::sync::atomic::Ordering::Relaxed);
757 self.roots_list_attempts
759 .store(0, std::sync::atomic::Ordering::Relaxed);
760 }
761}
762
763fn startup_rule_maintenance_at_home(home: &std::path::Path) {
764 let cfg = crate::core::config::Config::load();
765 if cfg.declines_rule_steering() {
766 return;
767 }
768 let _ = crate::rules_inject::inject_all_rules(home);
769}
770
771#[cfg(test)]
772mod tests {
773 use super::*;
774
775 #[test]
776 fn initialize_instructions_respect_explicit_auto_inject_false() {
777 let _guard = crate::core::data_dir::test_env_lock();
778 let tmp = tempfile::tempdir().expect("tempdir");
779 let config_dir = tmp.path().join("config");
780
781 std::fs::create_dir_all(&config_dir).unwrap();
782 std::fs::write(
783 config_dir.join("config.toml"),
784 "[setup]\nauto_inject_rules = false\n",
785 )
786 .unwrap();
787
788 let _config_guard = crate::setup::EnvVarGuard::set(
789 "LEAN_CTX_CONFIG_DIR",
790 config_dir.to_string_lossy().as_ref(),
791 );
792 let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
793
794 assert!(
795 suppress_initialize_instructions("cursor"),
796 "explicit auto_inject_rules=false declines rule steering and must suppress MCP initialize instructions"
797 );
798 }
799
800 #[test]
801 fn initialize_instructions_preserve_default_auto_behavior() {
802 let _guard = crate::core::data_dir::test_env_lock();
803 let tmp = tempfile::tempdir().expect("tempdir");
804 let config_dir = tmp.path().join("config");
805
806 std::fs::create_dir_all(&config_dir).unwrap();
807
808 let _config_guard = crate::setup::EnvVarGuard::set(
809 "LEAN_CTX_CONFIG_DIR",
810 config_dir.to_string_lossy().as_ref(),
811 );
812 let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
813
814 assert!(
815 !suppress_initialize_instructions("cursor"),
816 "default auto_inject_rules=None must preserve initialize instructions"
817 );
818 }
819
820 #[test]
821 fn initialize_instructions_preserve_explicit_true_behavior() {
822 let _guard = crate::core::data_dir::test_env_lock();
823 let tmp = tempfile::tempdir().expect("tempdir");
824 let config_dir = tmp.path().join("config");
825
826 std::fs::create_dir_all(&config_dir).unwrap();
827 std::fs::write(
828 config_dir.join("config.toml"),
829 "[setup]\nauto_inject_rules = true\n",
830 )
831 .unwrap();
832
833 let _config_guard = crate::setup::EnvVarGuard::set(
834 "LEAN_CTX_CONFIG_DIR",
835 config_dir.to_string_lossy().as_ref(),
836 );
837 let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
838
839 assert!(
840 !suppress_initialize_instructions("cursor"),
841 "explicit auto_inject_rules=true must preserve initialize instructions"
842 );
843 }
844
845 #[test]
846 fn initialize_instructions_respect_rules_injection_off() {
847 let _guard = crate::core::data_dir::test_env_lock();
848 let tmp = tempfile::tempdir().expect("tempdir");
849 let config_dir = tmp.path().join("config");
850
851 std::fs::create_dir_all(&config_dir).unwrap();
852
853 let _config_guard = crate::setup::EnvVarGuard::set(
854 "LEAN_CTX_CONFIG_DIR",
855 config_dir.to_string_lossy().as_ref(),
856 );
857 let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "off");
858
859 assert!(
860 suppress_initialize_instructions("cursor"),
861 "rules_injection=off must continue suppressing initialize instructions"
862 );
863 }
864
865 #[test]
866 fn initialize_instructions_keep_client_compatibility_exceptions() {
867 let _guard = crate::core::data_dir::test_env_lock();
868 let tmp = tempfile::tempdir().expect("tempdir");
869 let config_dir = tmp.path().join("config");
870
871 std::fs::create_dir_all(&config_dir).unwrap();
872
873 let _config_guard = crate::setup::EnvVarGuard::set(
874 "LEAN_CTX_CONFIG_DIR",
875 config_dir.to_string_lossy().as_ref(),
876 );
877 let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
878
879 assert!(suppress_initialize_instructions("antigravity"));
880 assert!(suppress_initialize_instructions("gemini-cli"));
881 }
882 #[test]
883 fn startup_maintenance_respects_explicit_auto_inject_false() {
884 let _guard = crate::core::data_dir::test_env_lock();
885 let tmp = tempfile::tempdir().expect("tempdir");
886 let home = tmp.path().join("home");
887 let config_dir = tmp.path().join("config");
888
889 std::fs::create_dir_all(home.join(".cursor")).unwrap();
890 std::fs::create_dir_all(&config_dir).unwrap();
891
892 std::fs::write(
893 home.join(".cursor/mcp.json"),
894 r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
895 )
896 .unwrap();
897
898 std::fs::write(
899 config_dir.join("config.toml"),
900 "[setup]\nauto_inject_rules = false\n",
901 )
902 .unwrap();
903
904 let _config_guard = crate::setup::EnvVarGuard::set(
905 "LEAN_CTX_CONFIG_DIR",
906 config_dir.to_string_lossy().as_ref(),
907 );
908 let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
909 let _scope_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
910
911 startup_rule_maintenance_at_home(&home);
912
913 let rules = home.join(".cursor/rules/lean-ctx.mdc");
914
915 assert!(
916 !rules.exists(),
917 "startup maintenance must not write Cursor rules when setup.auto_inject_rules=false"
918 );
919 }
920
921 #[test]
922 fn automatic_rule_maintenance_allows_default_startup_write() {
923 let _guard = crate::core::data_dir::test_env_lock();
924 let tmp = tempfile::tempdir().expect("tempdir");
925 let home = tmp.path().join("home");
926 let config_dir = tmp.path().join("config");
927
928 std::fs::create_dir_all(home.join(".cursor")).unwrap();
929 std::fs::create_dir_all(&config_dir).unwrap();
930
931 std::fs::write(
932 home.join(".cursor/mcp.json"),
933 r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
934 )
935 .unwrap();
936
937 let _config_guard = crate::setup::EnvVarGuard::set(
938 "LEAN_CTX_CONFIG_DIR",
939 config_dir.to_string_lossy().as_ref(),
940 );
941 let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
942 let _scope_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
943
944 startup_rule_maintenance_at_home(&home);
945
946 assert!(
947 home.join(".cursor/rules/lean-ctx.mdc").exists(),
948 "default auto_inject_rules=None must preserve zero-config startup rule maintenance"
949 );
950 }
951
952 #[test]
953 fn automatic_rule_maintenance_allows_explicit_true_startup_write() {
954 let _guard = crate::core::data_dir::test_env_lock();
955 let tmp = tempfile::tempdir().expect("tempdir");
956 let home = tmp.path().join("home");
957 let config_dir = tmp.path().join("config");
958
959 std::fs::create_dir_all(home.join(".cursor")).unwrap();
960 std::fs::create_dir_all(&config_dir).unwrap();
961
962 std::fs::write(
963 home.join(".cursor/mcp.json"),
964 r#"{"mcpServers":{"lean-ctx":{"command":"lean-ctx","args":["mcp"]}}}"#,
965 )
966 .unwrap();
967
968 std::fs::write(
969 config_dir.join("config.toml"),
970 "[setup]\nauto_inject_rules = true\n",
971 )
972 .unwrap();
973
974 let _config_guard = crate::setup::EnvVarGuard::set(
975 "LEAN_CTX_CONFIG_DIR",
976 config_dir.to_string_lossy().as_ref(),
977 );
978 let _injection_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
979 let _scope_guard = crate::setup::EnvVarGuard::set("LEAN_CTX_RULES_SCOPE", "global");
980
981 startup_rule_maintenance_at_home(&home);
982
983 assert!(
984 home.join(".cursor/rules/lean-ctx.mdc").exists(),
985 "explicit auto_inject_rules=true must preserve startup rule maintenance"
986 );
987 }
988 #[test]
994 fn server_capabilities_always_declare_tool_list_changed() {
995 for (resources, prompts) in [(true, true), (true, false), (false, true), (false, false)] {
996 let caps = server_capabilities(resources, prompts);
997 let tools = caps.tools.expect("tools capability must be advertised");
998 assert_eq!(
999 tools.list_changed,
1000 Some(true),
1001 "listChanged must be Some(true) for (resources={resources}, prompts={prompts})"
1002 );
1003 }
1004 }
1005
1006 #[test]
1010 fn lazy_core_fallback_is_never_empty() {
1011 let _guard = crate::core::data_dir::isolated_data_dir();
1012 let defs = crate::tool_defs::lazy_tool_defs();
1013 assert!(!defs.is_empty(), "lazy-core fallback must not be empty");
1014 for essential in ["ctx_read", "ctx_shell", "ctx_call"] {
1015 assert!(
1016 defs.iter().any(|t| t.name.as_ref() == essential),
1017 "lazy-core fallback must include {essential}"
1018 );
1019 }
1020 }
1021}