1use rmcp::handler::server::ServerHandler;
2use rmcp::model::*;
3use rmcp::service::{RequestContext, RoleServer};
4use rmcp::ErrorData;
5use serde_json::Value;
6
7use crate::tools::{CrpMode, LeanCtxServer};
8
9impl ServerHandler for LeanCtxServer {
10 fn get_info(&self) -> ServerInfo {
11 let capabilities = ServerCapabilities::builder().enable_tools().build();
12
13 let instructions = crate::instructions::build_instructions(self.crp_mode);
14
15 InitializeResult::new(capabilities)
16 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
17 .with_instructions(instructions)
18 }
19
20 async fn initialize(
21 &self,
22 request: InitializeRequestParams,
23 _context: RequestContext<RoleServer>,
24 ) -> Result<InitializeResult, ErrorData> {
25 let name = request.client_info.name.clone();
26 tracing::info!("MCP client connected: {:?}", name);
27 *self.client_name.write().await = name.clone();
28
29 tokio::task::spawn_blocking(|| {
30 if let Some(home) = dirs::home_dir() {
31 let _ = crate::rules_inject::inject_all_rules(&home);
32 }
33 crate::hooks::refresh_installed_hooks();
34 crate::core::version_check::check_background();
35 });
36
37 let instructions =
38 crate::instructions::build_instructions_with_client(self.crp_mode, &name);
39 let capabilities = ServerCapabilities::builder().enable_tools().build();
40
41 Ok(InitializeResult::new(capabilities)
42 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
43 .with_instructions(instructions))
44 }
45
46 async fn list_tools(
47 &self,
48 _request: Option<PaginatedRequestParams>,
49 _context: RequestContext<RoleServer>,
50 ) -> Result<ListToolsResult, ErrorData> {
51 if std::env::var("LEAN_CTX_UNIFIED").is_ok()
52 && std::env::var("LEAN_CTX_FULL_TOOLS").is_err()
53 {
54 return Ok(ListToolsResult {
55 tools: crate::tool_defs::unified_tool_defs(),
56 ..Default::default()
57 });
58 }
59
60 Ok(ListToolsResult {
61 tools: crate::tool_defs::granular_tool_defs(),
62 ..Default::default()
63 })
64 }
65
66 async fn call_tool(
67 &self,
68 request: CallToolRequestParams,
69 _context: RequestContext<RoleServer>,
70 ) -> Result<CallToolResult, ErrorData> {
71 self.check_idle_expiry().await;
72
73 let original_name = request.name.as_ref().to_string();
74 let (resolved_name, resolved_args) = if original_name == "ctx" {
75 let sub = request
76 .arguments
77 .as_ref()
78 .and_then(|a| a.get("tool"))
79 .and_then(|v| v.as_str())
80 .map(|s| s.to_string())
81 .ok_or_else(|| {
82 ErrorData::invalid_params("'tool' is required for ctx meta-tool", None)
83 })?;
84 let tool_name = if sub.starts_with("ctx_") {
85 sub
86 } else {
87 format!("ctx_{sub}")
88 };
89 let mut args = request.arguments.unwrap_or_default();
90 args.remove("tool");
91 (tool_name, Some(args))
92 } else {
93 (original_name, request.arguments)
94 };
95 let name = resolved_name.as_str();
96 let args = &resolved_args;
97
98 let auto_context = {
99 let task = {
100 let session = self.session.read().await;
101 session.task.as_ref().map(|t| t.description.clone())
102 };
103 let project_root = {
104 let session = self.session.read().await;
105 session.project_root.clone()
106 };
107 let mut cache = self.cache.write().await;
108 crate::tools::autonomy::session_lifecycle_pre_hook(
109 &self.autonomy,
110 name,
111 &mut cache,
112 task.as_deref(),
113 project_root.as_deref(),
114 self.crp_mode,
115 )
116 };
117
118 let tool_start = std::time::Instant::now();
119 let result_text = match name {
120 "ctx_read" => {
121 let path = get_str(args, "path")
122 .map(|p| crate::hooks::normalize_tool_path(&p))
123 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
124 let current_task = {
125 let session = self.session.read().await;
126 session.task.as_ref().map(|t| t.description.clone())
127 };
128 let task_ref = current_task.as_deref();
129 let mut mode = match get_str(args, "mode") {
130 Some(m) => m,
131 None => {
132 let cache = self.cache.read().await;
133 crate::tools::ctx_smart_read::select_mode_with_task(&cache, &path, task_ref)
134 }
135 };
136 let fresh = get_bool(args, "fresh").unwrap_or(false);
137 let start_line = get_int(args, "start_line");
138 if let Some(sl) = start_line {
139 let sl = sl.max(1_i64);
140 mode = format!("lines:{sl}-999999");
141 }
142 let stale = self.is_prompt_cache_stale().await;
143 let effective_mode = LeanCtxServer::upgrade_mode_if_stale(&mode, stale).to_string();
144 let mut cache = self.cache.write().await;
145 let output = if fresh {
146 crate::tools::ctx_read::handle_fresh_with_task(
147 &mut cache,
148 &path,
149 &effective_mode,
150 self.crp_mode,
151 task_ref,
152 )
153 } else {
154 crate::tools::ctx_read::handle_with_task(
155 &mut cache,
156 &path,
157 &effective_mode,
158 self.crp_mode,
159 task_ref,
160 )
161 };
162 let stale_note = if effective_mode != mode {
163 format!("[cache stale, {mode}→{effective_mode}]\n")
164 } else {
165 String::new()
166 };
167 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
168 let output_tokens = crate::core::tokens::count_tokens(&output);
169 let saved = original.saturating_sub(output_tokens);
170 let is_cache_hit = output.contains(" cached ");
171 let output = format!("{stale_note}{output}");
172 let file_ref = cache.file_ref_map().get(&path).cloned();
173 drop(cache);
174 {
175 let mut session = self.session.write().await;
176 session.touch_file(&path, file_ref.as_deref(), &effective_mode, original);
177 if is_cache_hit {
178 session.record_cache_hit();
179 }
180 if session.project_root.is_none() {
181 if let Some(root) = detect_project_root(&path) {
182 session.project_root = Some(root.clone());
183 let mut current = self.agent_id.write().await;
184 if current.is_none() {
185 let mut registry =
186 crate::core::agents::AgentRegistry::load_or_create();
187 registry.cleanup_stale(24);
188 let id = registry.register("mcp", None, &root);
189 let _ = registry.save();
190 *current = Some(id);
191 }
192 }
193 }
194 }
195 self.record_call("ctx_read", original, saved, Some(mode.clone()))
196 .await;
197 {
198 let sig =
199 crate::core::mode_predictor::FileSignature::from_path(&path, original);
200 let density = if output_tokens > 0 {
201 original as f64 / output_tokens as f64
202 } else {
203 1.0
204 };
205 let outcome = crate::core::mode_predictor::ModeOutcome {
206 mode: mode.clone(),
207 tokens_in: original,
208 tokens_out: output_tokens,
209 density: density.min(1.0),
210 };
211 let mut predictor = crate::core::mode_predictor::ModePredictor::new();
212 predictor.record(sig, outcome);
213 predictor.save();
214
215 let ext = std::path::Path::new(&path)
216 .extension()
217 .and_then(|e| e.to_str())
218 .unwrap_or("")
219 .to_string();
220 let thresholds = crate::core::adaptive_thresholds::thresholds_for_path(&path);
221 let cache = self.cache.read().await;
222 let stats = cache.get_stats();
223 let feedback_outcome = crate::core::feedback::CompressionOutcome {
224 session_id: format!("{}", std::process::id()),
225 language: ext,
226 entropy_threshold: thresholds.bpe_entropy,
227 jaccard_threshold: thresholds.jaccard,
228 total_turns: stats.total_reads as u32,
229 tokens_saved: saved as u64,
230 tokens_original: original as u64,
231 cache_hits: stats.cache_hits as u32,
232 total_reads: stats.total_reads as u32,
233 task_completed: true,
234 timestamp: chrono::Local::now().to_rfc3339(),
235 };
236 drop(cache);
237 let mut store = crate::core::feedback::FeedbackStore::load();
238 store.record_outcome(feedback_outcome);
239 }
240 output
241 }
242 "ctx_multi_read" => {
243 let paths = get_str_array(args, "paths")
244 .ok_or_else(|| ErrorData::invalid_params("paths array is required", None))?
245 .into_iter()
246 .map(|p| crate::hooks::normalize_tool_path(&p))
247 .collect::<Vec<_>>();
248 let mode = get_str(args, "mode").unwrap_or_else(|| "full".to_string());
249 let current_task = {
250 let session = self.session.read().await;
251 session.task.as_ref().map(|t| t.description.clone())
252 };
253 let mut cache = self.cache.write().await;
254 let output = crate::tools::ctx_multi_read::handle_with_task(
255 &mut cache,
256 &paths,
257 &mode,
258 self.crp_mode,
259 current_task.as_deref(),
260 );
261 let mut total_original: usize = 0;
262 for path in &paths {
263 total_original = total_original
264 .saturating_add(cache.get(path).map(|e| e.original_tokens).unwrap_or(0));
265 }
266 let tokens = crate::core::tokens::count_tokens(&output);
267 drop(cache);
268 self.record_call(
269 "ctx_multi_read",
270 total_original,
271 total_original.saturating_sub(tokens),
272 Some(mode),
273 )
274 .await;
275 output
276 }
277 "ctx_tree" => {
278 let path = crate::hooks::normalize_tool_path(
279 &get_str(args, "path").unwrap_or_else(|| ".".to_string()),
280 );
281 let depth = get_int(args, "depth").unwrap_or(3) as usize;
282 let show_hidden = get_bool(args, "show_hidden").unwrap_or(false);
283 let (result, original) = crate::tools::ctx_tree::handle(&path, depth, show_hidden);
284 let sent = crate::core::tokens::count_tokens(&result);
285 let saved = original.saturating_sub(sent);
286 self.record_call("ctx_tree", original, saved, None).await;
287 let savings_note = if saved > 0 {
288 format!("\n[saved {saved} tokens vs native ls]")
289 } else {
290 String::new()
291 };
292 format!("{result}{savings_note}")
293 }
294 "ctx_shell" => {
295 let command = get_str(args, "command")
296 .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
297 let raw = get_bool(args, "raw").unwrap_or(false)
298 || std::env::var("LEAN_CTX_DISABLED").is_ok();
299 let cmd_clone = command.clone();
300 let output = tokio::task::spawn_blocking(move || execute_command(&cmd_clone))
301 .await
302 .unwrap_or_else(|e| format!("ERROR: shell task failed: {e}"));
303
304 if raw {
305 let original = crate::core::tokens::count_tokens(&output);
306 self.record_call("ctx_shell", original, 0, None).await;
307 output
308 } else {
309 let result = crate::tools::ctx_shell::handle(&command, &output, self.crp_mode);
310 let original = crate::core::tokens::count_tokens(&output);
311 let sent = crate::core::tokens::count_tokens(&result);
312 let saved = original.saturating_sub(sent);
313 self.record_call("ctx_shell", original, saved, None).await;
314
315 let cfg = crate::core::config::Config::load();
316 let tee_hint = match cfg.tee_mode {
317 crate::core::config::TeeMode::Always => {
318 crate::shell::save_tee(&command, &output)
319 .map(|p| format!("\n[full output: {p}]"))
320 .unwrap_or_default()
321 }
322 crate::core::config::TeeMode::Failures
323 if !output.trim().is_empty() && output.contains("error")
324 || output.contains("Error")
325 || output.contains("ERROR") =>
326 {
327 crate::shell::save_tee(&command, &output)
328 .map(|p| format!("\n[full output: {p}]"))
329 .unwrap_or_default()
330 }
331 _ => String::new(),
332 };
333
334 let savings_note = if saved > 0 {
335 format!("\n[saved {saved} tokens vs native Shell]")
336 } else {
337 String::new()
338 };
339 format!("{result}{savings_note}{tee_hint}")
340 }
341 }
342 "ctx_search" => {
343 let pattern = get_str(args, "pattern")
344 .ok_or_else(|| ErrorData::invalid_params("pattern is required", None))?;
345 let path = crate::hooks::normalize_tool_path(
346 &get_str(args, "path").unwrap_or_else(|| ".".to_string()),
347 );
348 let ext = get_str(args, "ext");
349 let max = get_int(args, "max_results").unwrap_or(20) as usize;
350 let no_gitignore = get_bool(args, "ignore_gitignore").unwrap_or(false);
351 let crp = self.crp_mode;
352 let respect = !no_gitignore;
353 let search_result = tokio::time::timeout(
354 std::time::Duration::from_secs(30),
355 tokio::task::spawn_blocking(move || {
356 crate::tools::ctx_search::handle(
357 &pattern,
358 &path,
359 ext.as_deref(),
360 max,
361 crp,
362 respect,
363 )
364 }),
365 )
366 .await;
367 let (result, original) = match search_result {
368 Ok(Ok(r)) => r,
369 Ok(Err(e)) => {
370 return Err(ErrorData::internal_error(
371 format!("search task failed: {e}"),
372 None,
373 ))
374 }
375 Err(_) => {
376 let msg = "ctx_search timed out after 30s. Try narrowing the search:\n\
377 • Use a more specific pattern\n\
378 • Specify ext= to limit file types\n\
379 • Specify a subdirectory in path=";
380 self.record_call("ctx_search", 0, 0, None).await;
381 return Ok(CallToolResult::success(vec![Content::text(msg)]));
382 }
383 };
384 let sent = crate::core::tokens::count_tokens(&result);
385 let saved = original.saturating_sub(sent);
386 self.record_call("ctx_search", original, saved, None).await;
387 let savings_note = if saved > 0 {
388 format!("\n[saved {saved} tokens vs native Grep]")
389 } else {
390 String::new()
391 };
392 format!("{result}{savings_note}")
393 }
394 "ctx_compress" => {
395 let include_sigs = get_bool(args, "include_signatures").unwrap_or(true);
396 let cache = self.cache.read().await;
397 let result =
398 crate::tools::ctx_compress::handle(&cache, include_sigs, self.crp_mode);
399 drop(cache);
400 self.record_call("ctx_compress", 0, 0, None).await;
401 result
402 }
403 "ctx_benchmark" => {
404 let path = get_str(args, "path")
405 .map(|p| crate::hooks::normalize_tool_path(&p))
406 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
407 let action = get_str(args, "action").unwrap_or_default();
408 let result = if action == "project" {
409 let fmt = get_str(args, "format").unwrap_or_default();
410 let bench = crate::core::benchmark::run_project_benchmark(&path);
411 match fmt.as_str() {
412 "json" => crate::core::benchmark::format_json(&bench),
413 "markdown" | "md" => crate::core::benchmark::format_markdown(&bench),
414 _ => crate::core::benchmark::format_terminal(&bench),
415 }
416 } else {
417 crate::tools::ctx_benchmark::handle(&path, self.crp_mode)
418 };
419 self.record_call("ctx_benchmark", 0, 0, None).await;
420 result
421 }
422 "ctx_metrics" => {
423 let cache = self.cache.read().await;
424 let calls = self.tool_calls.read().await;
425 let result = crate::tools::ctx_metrics::handle(&cache, &calls, self.crp_mode);
426 drop(cache);
427 drop(calls);
428 self.record_call("ctx_metrics", 0, 0, None).await;
429 result
430 }
431 "ctx_analyze" => {
432 let path = get_str(args, "path")
433 .map(|p| crate::hooks::normalize_tool_path(&p))
434 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
435 let result = crate::tools::ctx_analyze::handle(&path, self.crp_mode);
436 self.record_call("ctx_analyze", 0, 0, None).await;
437 result
438 }
439 "ctx_discover" => {
440 let limit = get_int(args, "limit").unwrap_or(15) as usize;
441 let history = crate::cli::load_shell_history_pub();
442 let result = crate::tools::ctx_discover::discover_from_history(&history, limit);
443 self.record_call("ctx_discover", 0, 0, None).await;
444 result
445 }
446 "ctx_smart_read" => {
447 let path = get_str(args, "path")
448 .map(|p| crate::hooks::normalize_tool_path(&p))
449 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
450 let mut cache = self.cache.write().await;
451 let output = crate::tools::ctx_smart_read::handle(&mut cache, &path, self.crp_mode);
452 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
453 let tokens = crate::core::tokens::count_tokens(&output);
454 drop(cache);
455 self.record_call(
456 "ctx_smart_read",
457 original,
458 original.saturating_sub(tokens),
459 Some("auto".to_string()),
460 )
461 .await;
462 output
463 }
464 "ctx_delta" => {
465 let path = get_str(args, "path")
466 .map(|p| crate::hooks::normalize_tool_path(&p))
467 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
468 let mut cache = self.cache.write().await;
469 let output = crate::tools::ctx_delta::handle(&mut cache, &path);
470 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
471 let tokens = crate::core::tokens::count_tokens(&output);
472 drop(cache);
473 {
474 let mut session = self.session.write().await;
475 session.mark_modified(&path);
476 }
477 self.record_call(
478 "ctx_delta",
479 original,
480 original.saturating_sub(tokens),
481 Some("delta".to_string()),
482 )
483 .await;
484 output
485 }
486 "ctx_edit" => {
487 let path = get_str(args, "path")
488 .map(|p| crate::hooks::normalize_tool_path(&p))
489 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
490 let old_string = get_str(args, "old_string").unwrap_or_default();
491 let new_string = get_str(args, "new_string")
492 .ok_or_else(|| ErrorData::invalid_params("new_string is required", None))?;
493 let replace_all = args
494 .as_ref()
495 .and_then(|a| a.get("replace_all"))
496 .and_then(|v| v.as_bool())
497 .unwrap_or(false);
498 let create = args
499 .as_ref()
500 .and_then(|a| a.get("create"))
501 .and_then(|v| v.as_bool())
502 .unwrap_or(false);
503
504 let mut cache = self.cache.write().await;
505 let output = crate::tools::ctx_edit::handle(
506 &mut cache,
507 crate::tools::ctx_edit::EditParams {
508 path: path.clone(),
509 old_string,
510 new_string,
511 replace_all,
512 create,
513 },
514 );
515 drop(cache);
516
517 {
518 let mut session = self.session.write().await;
519 session.mark_modified(&path);
520 }
521 self.record_call("ctx_edit", 0, 0, None).await;
522 output
523 }
524 "ctx_dedup" => {
525 let action = get_str(args, "action").unwrap_or_default();
526 if action == "apply" {
527 let mut cache = self.cache.write().await;
528 let result = crate::tools::ctx_dedup::handle_action(&mut cache, &action);
529 drop(cache);
530 self.record_call("ctx_dedup", 0, 0, None).await;
531 result
532 } else {
533 let cache = self.cache.read().await;
534 let result = crate::tools::ctx_dedup::handle(&cache);
535 drop(cache);
536 self.record_call("ctx_dedup", 0, 0, None).await;
537 result
538 }
539 }
540 "ctx_fill" => {
541 let paths = get_str_array(args, "paths")
542 .ok_or_else(|| ErrorData::invalid_params("paths array is required", None))?
543 .into_iter()
544 .map(|p| crate::hooks::normalize_tool_path(&p))
545 .collect::<Vec<_>>();
546 let budget = get_int(args, "budget")
547 .ok_or_else(|| ErrorData::invalid_params("budget is required", None))?
548 as usize;
549 let mut cache = self.cache.write().await;
550 let output =
551 crate::tools::ctx_fill::handle(&mut cache, &paths, budget, self.crp_mode);
552 drop(cache);
553 self.record_call("ctx_fill", 0, 0, Some(format!("budget:{budget}")))
554 .await;
555 output
556 }
557 "ctx_intent" => {
558 let query = get_str(args, "query")
559 .ok_or_else(|| ErrorData::invalid_params("query is required", None))?;
560 let root = get_str(args, "project_root").unwrap_or_else(|| ".".to_string());
561 let mut cache = self.cache.write().await;
562 let output =
563 crate::tools::ctx_intent::handle(&mut cache, &query, &root, self.crp_mode);
564 drop(cache);
565 {
566 let mut session = self.session.write().await;
567 session.set_task(&query, Some("intent"));
568 }
569 self.record_call("ctx_intent", 0, 0, Some("semantic".to_string()))
570 .await;
571 output
572 }
573 "ctx_response" => {
574 let text = get_str(args, "text")
575 .ok_or_else(|| ErrorData::invalid_params("text is required", None))?;
576 let output = crate::tools::ctx_response::handle(&text, self.crp_mode);
577 self.record_call("ctx_response", 0, 0, None).await;
578 output
579 }
580 "ctx_context" => {
581 let cache = self.cache.read().await;
582 let turn = self.call_count.load(std::sync::atomic::Ordering::Relaxed);
583 let result = crate::tools::ctx_context::handle_status(&cache, turn, self.crp_mode);
584 drop(cache);
585 self.record_call("ctx_context", 0, 0, None).await;
586 result
587 }
588 "ctx_graph" => {
589 let action = get_str(args, "action")
590 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
591 let path = get_str(args, "path").map(|p| crate::hooks::normalize_tool_path(&p));
592 let root = crate::hooks::normalize_tool_path(
593 &get_str(args, "project_root").unwrap_or_else(|| ".".to_string()),
594 );
595 let mut cache = self.cache.write().await;
596 let result = crate::tools::ctx_graph::handle(
597 &action,
598 path.as_deref(),
599 &root,
600 &mut cache,
601 self.crp_mode,
602 );
603 drop(cache);
604 self.record_call("ctx_graph", 0, 0, Some(action)).await;
605 result
606 }
607 "ctx_cache" => {
608 let action = get_str(args, "action")
609 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
610 let mut cache = self.cache.write().await;
611 let result = match action.as_str() {
612 "status" => {
613 let entries = cache.get_all_entries();
614 if entries.is_empty() {
615 "Cache empty — no files tracked.".to_string()
616 } else {
617 let mut lines = vec![format!("Cache: {} file(s)", entries.len())];
618 for (path, entry) in &entries {
619 let fref = cache
620 .file_ref_map()
621 .get(*path)
622 .map(|s| s.as_str())
623 .unwrap_or("F?");
624 lines.push(format!(
625 " {fref}={} [{}L, {}t, read {}x]",
626 crate::core::protocol::shorten_path(path),
627 entry.line_count,
628 entry.original_tokens,
629 entry.read_count
630 ));
631 }
632 lines.join("\n")
633 }
634 }
635 "clear" => {
636 let count = cache.clear();
637 format!("Cache cleared — {count} file(s) removed. Next ctx_read will return full content.")
638 }
639 "invalidate" => {
640 let path = get_str(args, "path")
641 .map(|p| crate::hooks::normalize_tool_path(&p))
642 .ok_or_else(|| {
643 ErrorData::invalid_params("path is required for invalidate", None)
644 })?;
645 if cache.invalidate(&path) {
646 format!(
647 "Invalidated cache for {}. Next ctx_read will return full content.",
648 crate::core::protocol::shorten_path(&path)
649 )
650 } else {
651 format!(
652 "{} was not in cache.",
653 crate::core::protocol::shorten_path(&path)
654 )
655 }
656 }
657 _ => "Unknown action. Use: status, clear, invalidate".to_string(),
658 };
659 drop(cache);
660 self.record_call("ctx_cache", 0, 0, Some(action)).await;
661 result
662 }
663 "ctx_session" => {
664 let action = get_str(args, "action")
665 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
666 let value = get_str(args, "value");
667 let sid = get_str(args, "session_id");
668 let mut session = self.session.write().await;
669 let result = crate::tools::ctx_session::handle(
670 &mut session,
671 &action,
672 value.as_deref(),
673 sid.as_deref(),
674 );
675 drop(session);
676 self.record_call("ctx_session", 0, 0, Some(action)).await;
677 result
678 }
679 "ctx_knowledge" => {
680 let action = get_str(args, "action")
681 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
682 let category = get_str(args, "category");
683 let key = get_str(args, "key");
684 let value = get_str(args, "value");
685 let query = get_str(args, "query");
686 let pattern_type = get_str(args, "pattern_type");
687 let examples = get_str_array(args, "examples");
688 let confidence: Option<f32> = args
689 .as_ref()
690 .and_then(|a| a.get("confidence"))
691 .and_then(|v| v.as_f64())
692 .map(|v| v as f32);
693
694 let session = self.session.read().await;
695 let session_id = session.id.clone();
696 let project_root = session.project_root.clone().unwrap_or_else(|| {
697 std::env::current_dir()
698 .map(|p| p.to_string_lossy().to_string())
699 .unwrap_or_else(|_| "unknown".to_string())
700 });
701 drop(session);
702
703 let result = crate::tools::ctx_knowledge::handle(
704 &project_root,
705 &action,
706 category.as_deref(),
707 key.as_deref(),
708 value.as_deref(),
709 query.as_deref(),
710 &session_id,
711 pattern_type.as_deref(),
712 examples,
713 confidence,
714 );
715 self.record_call("ctx_knowledge", 0, 0, Some(action)).await;
716 result
717 }
718 "ctx_agent" => {
719 let action = get_str(args, "action")
720 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
721 let agent_type = get_str(args, "agent_type");
722 let role = get_str(args, "role");
723 let message = get_str(args, "message");
724 let category = get_str(args, "category");
725 let to_agent = get_str(args, "to_agent");
726 let status = get_str(args, "status");
727
728 let session = self.session.read().await;
729 let project_root = session.project_root.clone().unwrap_or_else(|| {
730 std::env::current_dir()
731 .map(|p| p.to_string_lossy().to_string())
732 .unwrap_or_else(|_| "unknown".to_string())
733 });
734 drop(session);
735
736 let current_agent_id = self.agent_id.read().await.clone();
737 let result = crate::tools::ctx_agent::handle(
738 &action,
739 agent_type.as_deref(),
740 role.as_deref(),
741 &project_root,
742 current_agent_id.as_deref(),
743 message.as_deref(),
744 category.as_deref(),
745 to_agent.as_deref(),
746 status.as_deref(),
747 );
748
749 if action == "register" {
750 if let Some(id) = result.split(':').nth(1) {
751 let id = id.split_whitespace().next().unwrap_or("").to_string();
752 if !id.is_empty() {
753 *self.agent_id.write().await = Some(id);
754 }
755 }
756 }
757
758 self.record_call("ctx_agent", 0, 0, Some(action)).await;
759 result
760 }
761 "ctx_overview" => {
762 let task = get_str(args, "task");
763 let path = get_str(args, "path").map(|p| crate::hooks::normalize_tool_path(&p));
764 let cache = self.cache.read().await;
765 let result = crate::tools::ctx_overview::handle(
766 &cache,
767 task.as_deref(),
768 path.as_deref(),
769 self.crp_mode,
770 );
771 drop(cache);
772 self.record_call("ctx_overview", 0, 0, Some("overview".to_string()))
773 .await;
774 result
775 }
776 "ctx_preload" => {
777 let task = get_str(args, "task").unwrap_or_default();
778 let path = get_str(args, "path").map(|p| crate::hooks::normalize_tool_path(&p));
779 let mut cache = self.cache.write().await;
780 let result = crate::tools::ctx_preload::handle(
781 &mut cache,
782 &task,
783 path.as_deref(),
784 self.crp_mode,
785 );
786 drop(cache);
787 self.record_call("ctx_preload", 0, 0, Some("preload".to_string()))
788 .await;
789 result
790 }
791 "ctx_wrapped" => {
792 let period = get_str(args, "period").unwrap_or_else(|| "week".to_string());
793 let result = crate::tools::ctx_wrapped::handle(&period);
794 self.record_call("ctx_wrapped", 0, 0, Some(period)).await;
795 result
796 }
797 "ctx_semantic_search" => {
798 let query = get_str(args, "query")
799 .ok_or_else(|| ErrorData::invalid_params("query is required", None))?;
800 let path = crate::hooks::normalize_tool_path(
801 &get_str(args, "path").unwrap_or_else(|| ".".to_string()),
802 );
803 let top_k = get_int(args, "top_k").unwrap_or(10) as usize;
804 let action = get_str(args, "action").unwrap_or_default();
805 let result = if action == "reindex" {
806 crate::tools::ctx_semantic_search::handle_reindex(&path)
807 } else {
808 crate::tools::ctx_semantic_search::handle(&query, &path, top_k, self.crp_mode)
809 };
810 self.record_call("ctx_semantic_search", 0, 0, Some("semantic".to_string()))
811 .await;
812 result
813 }
814 _ => {
815 return Err(ErrorData::invalid_params(
816 format!("Unknown tool: {name}"),
817 None,
818 ));
819 }
820 };
821
822 let mut result_text = result_text;
823
824 if let Some(ctx) = auto_context {
825 result_text = format!("{ctx}\n\n{result_text}");
826 }
827
828 if name == "ctx_read" {
829 let read_path =
830 crate::hooks::normalize_tool_path(&get_str(args, "path").unwrap_or_default());
831 let project_root = {
832 let session = self.session.read().await;
833 session.project_root.clone()
834 };
835 let mut cache = self.cache.write().await;
836 let enrich = crate::tools::autonomy::enrich_after_read(
837 &self.autonomy,
838 &mut cache,
839 &read_path,
840 project_root.as_deref(),
841 );
842 if let Some(hint) = enrich.related_hint {
843 result_text = format!("{result_text}\n{hint}");
844 }
845
846 crate::tools::autonomy::maybe_auto_dedup(&self.autonomy, &mut cache);
847 }
848
849 if name == "ctx_shell" {
850 let cmd = get_str(args, "command").unwrap_or_default();
851 let output_tokens = crate::core::tokens::count_tokens(&result_text);
852 let calls = self.tool_calls.read().await;
853 let last_original = calls.last().map(|c| c.original_tokens).unwrap_or(0);
854 drop(calls);
855 if let Some(hint) = crate::tools::autonomy::shell_efficiency_hint(
856 &self.autonomy,
857 &cmd,
858 last_original,
859 output_tokens,
860 ) {
861 result_text = format!("{result_text}\n{hint}");
862 }
863 }
864
865 let skip_checkpoint = matches!(
866 name,
867 "ctx_compress"
868 | "ctx_metrics"
869 | "ctx_benchmark"
870 | "ctx_analyze"
871 | "ctx_cache"
872 | "ctx_discover"
873 | "ctx_dedup"
874 | "ctx_session"
875 | "ctx_knowledge"
876 | "ctx_agent"
877 | "ctx_wrapped"
878 | "ctx_overview"
879 | "ctx_preload"
880 );
881
882 if !skip_checkpoint && self.increment_and_check() {
883 if let Some(checkpoint) = self.auto_checkpoint().await {
884 let combined = format!(
885 "{result_text}\n\n--- AUTO CHECKPOINT (every {} calls) ---\n{checkpoint}",
886 self.checkpoint_interval
887 );
888 return Ok(CallToolResult::success(vec![Content::text(combined)]));
889 }
890 }
891
892 let tool_duration_ms = tool_start.elapsed().as_millis() as u64;
893 if tool_duration_ms > 100 {
894 LeanCtxServer::append_tool_call_log(
895 name,
896 tool_duration_ms,
897 0,
898 0,
899 None,
900 &chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
901 );
902 }
903
904 let current_count = self.call_count.load(std::sync::atomic::Ordering::Relaxed);
905 if current_count > 0 && current_count.is_multiple_of(100) {
906 std::thread::spawn(crate::cloud_sync::cloud_background_tasks);
907 }
908
909 Ok(CallToolResult::success(vec![Content::text(result_text)]))
910 }
911}
912
913pub fn build_instructions_for_test(crp_mode: CrpMode) -> String {
914 crate::instructions::build_instructions(crp_mode)
915}
916
917fn get_str_array(args: &Option<serde_json::Map<String, Value>>, key: &str) -> Option<Vec<String>> {
918 let arr = args.as_ref()?.get(key)?.as_array()?;
919 let mut out = Vec::with_capacity(arr.len());
920 for v in arr {
921 let s = v.as_str()?.to_string();
922 out.push(s);
923 }
924 Some(out)
925}
926
927fn get_str(args: &Option<serde_json::Map<String, Value>>, key: &str) -> Option<String> {
928 args.as_ref()?.get(key)?.as_str().map(|s| s.to_string())
929}
930
931fn get_int(args: &Option<serde_json::Map<String, Value>>, key: &str) -> Option<i64> {
932 args.as_ref()?.get(key)?.as_i64()
933}
934
935fn get_bool(args: &Option<serde_json::Map<String, Value>>, key: &str) -> Option<bool> {
936 args.as_ref()?.get(key)?.as_bool()
937}
938
939fn execute_command(command: &str) -> String {
940 let (shell, flag) = crate::shell::shell_and_flag();
941 let output = std::process::Command::new(&shell)
942 .arg(&flag)
943 .arg(command)
944 .env("LEAN_CTX_ACTIVE", "1")
945 .output();
946
947 match output {
948 Ok(out) => {
949 let stdout = String::from_utf8_lossy(&out.stdout);
950 let stderr = String::from_utf8_lossy(&out.stderr);
951 if stdout.is_empty() {
952 stderr.to_string()
953 } else if stderr.is_empty() {
954 stdout.to_string()
955 } else {
956 format!("{stdout}\n{stderr}")
957 }
958 }
959 Err(e) => format!("ERROR: {e}"),
960 }
961}
962
963fn detect_project_root(file_path: &str) -> Option<String> {
964 let mut dir = std::path::Path::new(file_path).parent()?;
965 loop {
966 if dir.join(".git").exists() {
967 return Some(dir.to_string_lossy().to_string());
968 }
969 dir = dir.parent()?;
970 }
971}
972
973pub fn tool_descriptions_for_test() -> Vec<(&'static str, &'static str)> {
974 crate::tool_defs::list_all_tool_defs()
975 .into_iter()
976 .map(|(name, desc, _)| (name, desc))
977 .collect()
978}
979
980pub fn tool_schemas_json_for_test() -> String {
981 crate::tool_defs::list_all_tool_defs()
982 .iter()
983 .map(|(name, _, schema)| format!("{}: {}", name, schema))
984 .collect::<Vec<_>>()
985 .join("\n")
986}
987
988#[cfg(test)]
989mod tests {
990 #[test]
991 fn test_unified_tool_count() {
992 let tools = crate::tool_defs::unified_tool_defs();
993 assert_eq!(tools.len(), 5, "Expected 5 unified tools");
994 }
995
996 #[test]
997 fn test_granular_tool_count() {
998 let tools = crate::tool_defs::granular_tool_defs();
999 assert!(tools.len() >= 25, "Expected at least 25 granular tools");
1000 }
1001}