1use std::sync::Arc;
2
3use rmcp::handler::server::ServerHandler;
4use rmcp::model::*;
5use rmcp::service::{RequestContext, RoleServer};
6use rmcp::ErrorData;
7use serde_json::{json, Map, Value};
8
9use crate::tools::{CrpMode, LeanCtxServer};
10
11impl ServerHandler for LeanCtxServer {
15 fn get_info(&self) -> ServerInfo {
16 let capabilities = ServerCapabilities::builder().enable_tools().build();
17
18 let instructions = build_instructions(self.crp_mode);
19
20 InitializeResult::new(capabilities)
21 .with_server_info(Implementation::new("lean-ctx", "2.12.9"))
22 .with_instructions(instructions)
23 }
24
25 async fn initialize(
26 &self,
27 request: InitializeRequestParams,
28 _context: RequestContext<RoleServer>,
29 ) -> Result<InitializeResult, ErrorData> {
30 let name = request.client_info.name.clone();
31 tracing::info!("MCP client connected: {:?}", name);
32 *self.client_name.write().await = name.clone();
33
34 tokio::task::spawn_blocking(|| {
35 if let Some(home) = dirs::home_dir() {
36 let _ = crate::rules_inject::inject_all_rules(&home);
37 }
38 crate::hooks::refresh_installed_hooks();
39 crate::core::version_check::check_background();
40 });
41
42 let instructions = build_instructions_with_client(self.crp_mode, &name);
43 let capabilities = ServerCapabilities::builder().enable_tools().build();
44
45 Ok(InitializeResult::new(capabilities)
46 .with_server_info(Implementation::new("lean-ctx", "2.12.9"))
47 .with_instructions(instructions))
48 }
49
50 async fn list_tools(
51 &self,
52 _request: Option<PaginatedRequestParams>,
53 _context: RequestContext<RoleServer>,
54 ) -> Result<ListToolsResult, ErrorData> {
55 if should_use_unified(&self.client_name.read().await) {
56 return Ok(ListToolsResult {
57 tools: unified_tool_defs(),
58 ..Default::default()
59 });
60 }
61
62 Ok(ListToolsResult {
63 tools: vec![
64 tool_def(
65 "ctx_read",
66 "Read file (cached, compressed). Re-reads ~13 tok. Auto-selects optimal mode. \
67Modes: full|map|signatures|diff|aggressive|entropy|task|reference|lines:N-M. fresh=true re-reads.",
68 json!({
69 "type": "object",
70 "properties": {
71 "path": { "type": "string", "description": "Absolute file path to read" },
72 "mode": {
73 "type": "string",
74 "description": "Compression mode (default: full). Use 'map' for context-only files. For line ranges: 'lines:N-M' (e.g. 'lines:400-500')."
75 },
76 "start_line": {
77 "type": "integer",
78 "description": "Read from this line number to end of file. Bypasses cache stub — always returns actual content."
79 },
80 "fresh": {
81 "type": "boolean",
82 "description": "Bypass cache and force a full re-read. Use when running as a subagent that may not have the parent's context."
83 }
84 },
85 "required": ["path"]
86 }),
87 ),
88 tool_def(
89 "ctx_multi_read",
90 "Batch read files in one call. Same modes as ctx_read.",
91 json!({
92 "type": "object",
93 "properties": {
94 "paths": {
95 "type": "array",
96 "items": { "type": "string" },
97 "description": "Absolute file paths to read, in order"
98 },
99 "mode": {
100 "type": "string",
101 "enum": ["full", "signatures", "map", "diff", "aggressive", "entropy"],
102 "description": "Compression mode (default: full)"
103 }
104 },
105 "required": ["paths"]
106 }),
107 ),
108 tool_def(
109 "ctx_tree",
110 "Directory listing with file counts.",
111 json!({
112 "type": "object",
113 "properties": {
114 "path": { "type": "string", "description": "Directory path (default: .)" },
115 "depth": { "type": "integer", "description": "Max depth (default: 3)" },
116 "show_hidden": { "type": "boolean", "description": "Show hidden files" }
117 }
118 }),
119 ),
120 tool_def(
121 "ctx_shell",
122 "Run shell command (compressed output, 90+ patterns).",
123 json!({
124 "type": "object",
125 "properties": {
126 "command": { "type": "string", "description": "Shell command to execute" }
127 },
128 "required": ["command"]
129 }),
130 ),
131 tool_def(
132 "ctx_search",
133 "Regex code search (.gitignore aware, compact results).",
134 json!({
135 "type": "object",
136 "properties": {
137 "pattern": { "type": "string", "description": "Regex pattern" },
138 "path": { "type": "string", "description": "Directory to search" },
139 "ext": { "type": "string", "description": "File extension filter" },
140 "max_results": { "type": "integer", "description": "Max results (default: 20)" },
141 "ignore_gitignore": { "type": "boolean", "description": "Set true to scan ALL files including .gitignore'd paths (default: false)" }
142 },
143 "required": ["pattern"]
144 }),
145 ),
146 tool_def(
147 "ctx_compress",
148 "Context checkpoint for long conversations.",
149 json!({
150 "type": "object",
151 "properties": {
152 "include_signatures": { "type": "boolean", "description": "Include signatures (default: true)" }
153 }
154 }),
155 ),
156 tool_def(
157 "ctx_benchmark",
158 "Benchmark compression modes for a file or project.",
159 json!({
160 "type": "object",
161 "properties": {
162 "path": { "type": "string", "description": "File path (action=file) or project directory (action=project)" },
163 "action": { "type": "string", "description": "file (default) or project", "default": "file" },
164 "format": { "type": "string", "description": "Output format for project benchmark: terminal, markdown, json", "default": "terminal" }
165 },
166 "required": ["path"]
167 }),
168 ),
169 tool_def(
170 "ctx_metrics",
171 "Session token stats, cache rates, per-tool savings.",
172 json!({
173 "type": "object",
174 "properties": {}
175 }),
176 ),
177 tool_def(
178 "ctx_analyze",
179 "Entropy analysis — recommends optimal compression mode for a file.",
180 json!({
181 "type": "object",
182 "properties": {
183 "path": { "type": "string", "description": "File path to analyze" }
184 },
185 "required": ["path"]
186 }),
187 ),
188 tool_def(
189 "ctx_cache",
190 "Cache ops: status|clear|invalidate.",
191 json!({
192 "type": "object",
193 "properties": {
194 "action": {
195 "type": "string",
196 "enum": ["status", "clear", "invalidate"],
197 "description": "Cache operation to perform"
198 },
199 "path": {
200 "type": "string",
201 "description": "File path (required for 'invalidate' action)"
202 }
203 },
204 "required": ["action"]
205 }),
206 ),
207 tool_def(
208 "ctx_discover",
209 "Find missed compression opportunities in shell history.",
210 json!({
211 "type": "object",
212 "properties": {
213 "limit": {
214 "type": "integer",
215 "description": "Max number of command types to show (default: 15)"
216 }
217 }
218 }),
219 ),
220 tool_def(
221 "ctx_smart_read",
222 "Auto-select optimal read mode for a file.",
223 json!({
224 "type": "object",
225 "properties": {
226 "path": { "type": "string", "description": "Absolute file path to read" }
227 },
228 "required": ["path"]
229 }),
230 ),
231 tool_def(
232 "ctx_delta",
233 "Incremental diff — sends only changed lines since last read.",
234 json!({
235 "type": "object",
236 "properties": {
237 "path": { "type": "string", "description": "Absolute file path" }
238 },
239 "required": ["path"]
240 }),
241 ),
242 tool_def(
243 "ctx_dedup",
244 "Cross-file dedup: analyze or apply shared block references.",
245 json!({
246 "type": "object",
247 "properties": {
248 "action": {
249 "type": "string",
250 "description": "analyze (default) or apply (register shared blocks for auto-dedup in ctx_read)",
251 "default": "analyze"
252 }
253 }
254 }),
255 ),
256 tool_def(
257 "ctx_fill",
258 "Budget-aware context fill — auto-selects compression per file within token limit.",
259 json!({
260 "type": "object",
261 "properties": {
262 "paths": {
263 "type": "array",
264 "items": { "type": "string" },
265 "description": "File paths to consider"
266 },
267 "budget": {
268 "type": "integer",
269 "description": "Maximum token budget to fill"
270 }
271 },
272 "required": ["paths", "budget"]
273 }),
274 ),
275 tool_def(
276 "ctx_intent",
277 "Intent detection — auto-reads relevant files based on task description.",
278 json!({
279 "type": "object",
280 "properties": {
281 "query": { "type": "string", "description": "Natural language description of the task" },
282 "project_root": { "type": "string", "description": "Project root directory (default: .)" }
283 },
284 "required": ["query"]
285 }),
286 ),
287 tool_def(
288 "ctx_response",
289 "Compress LLM response text (remove filler, apply TDD).",
290 json!({
291 "type": "object",
292 "properties": {
293 "text": { "type": "string", "description": "Response text to compress" }
294 },
295 "required": ["text"]
296 }),
297 ),
298 tool_def(
299 "ctx_context",
300 "Session context overview — cached files, seen files, session state.",
301 json!({
302 "type": "object",
303 "properties": {}
304 }),
305 ),
306 tool_def(
307 "ctx_graph",
308 "Code dependency graph. Actions: build (index project), related (find files connected to path), \
309symbol (lookup definition/usages as file::name), impact (blast radius of changes to path), status (index stats).",
310 json!({
311 "type": "object",
312 "properties": {
313 "action": {
314 "type": "string",
315 "enum": ["build", "related", "symbol", "impact", "status"],
316 "description": "Graph operation: build, related, symbol, impact, status"
317 },
318 "path": {
319 "type": "string",
320 "description": "File path (related/impact) or file::symbol_name (symbol)"
321 },
322 "project_root": {
323 "type": "string",
324 "description": "Project root directory (default: .)"
325 }
326 },
327 "required": ["action"]
328 }),
329 ),
330 tool_def(
331 "ctx_session",
332 "Cross-session memory (CCP). Actions: load (restore previous session ~400 tok), \
333save, status, task (set current task), finding (record discovery), decision (record choice), \
334reset, list (show sessions), cleanup.",
335 json!({
336 "type": "object",
337 "properties": {
338 "action": {
339 "type": "string",
340 "enum": ["status", "load", "save", "task", "finding", "decision", "reset", "list", "cleanup"],
341 "description": "Session operation to perform"
342 },
343 "value": {
344 "type": "string",
345 "description": "Value for task/finding/decision actions"
346 },
347 "session_id": {
348 "type": "string",
349 "description": "Session ID for load action (default: latest)"
350 }
351 },
352 "required": ["action"]
353 }),
354 ),
355 tool_def(
356 "ctx_knowledge",
357 "Persistent project knowledge (survives sessions). Actions: remember (store fact with category+key+value), \
358recall (search by query), pattern (record naming/structure pattern), consolidate (extract session findings into knowledge), \
359status (list all), remove, export.",
360 json!({
361 "type": "object",
362 "properties": {
363 "action": {
364 "type": "string",
365 "enum": ["remember", "recall", "pattern", "consolidate", "status", "remove", "export"],
366 "description": "Knowledge operation to perform"
367 },
368 "category": {
369 "type": "string",
370 "description": "Fact category (architecture, api, testing, deployment, conventions, dependencies)"
371 },
372 "key": {
373 "type": "string",
374 "description": "Fact key/identifier (e.g. 'auth-method', 'db-engine', 'test-framework')"
375 },
376 "value": {
377 "type": "string",
378 "description": "Fact value or pattern description"
379 },
380 "query": {
381 "type": "string",
382 "description": "Search query for recall action (matches against category, key, and value)"
383 },
384 "pattern_type": {
385 "type": "string",
386 "description": "Pattern type for pattern action (naming, structure, testing, error-handling)"
387 },
388 "examples": {
389 "type": "array",
390 "items": { "type": "string" },
391 "description": "Examples for pattern action"
392 },
393 "confidence": {
394 "type": "number",
395 "description": "Confidence score 0.0-1.0 for remember action (default: 0.8)"
396 }
397 },
398 "required": ["action"]
399 }),
400 ),
401 tool_def(
402 "ctx_agent",
403 "Multi-agent coordination (shared message bus). Actions: register (join with agent_type+role), \
404post (broadcast or direct message with category), read (poll messages), status (update state: active|idle|finished), \
405list, info.",
406 json!({
407 "type": "object",
408 "properties": {
409 "action": {
410 "type": "string",
411 "enum": ["register", "list", "post", "read", "status", "info"],
412 "description": "Agent operation to perform"
413 },
414 "agent_type": {
415 "type": "string",
416 "description": "Agent type for register (cursor, claude, codex, gemini, subagent)"
417 },
418 "role": {
419 "type": "string",
420 "description": "Agent role (dev, review, test, plan)"
421 },
422 "message": {
423 "type": "string",
424 "description": "Message text for post action, or status detail for status action"
425 },
426 "category": {
427 "type": "string",
428 "description": "Message category for post (finding, warning, request, status)"
429 },
430 "to_agent": {
431 "type": "string",
432 "description": "Target agent ID for direct message (omit for broadcast)"
433 },
434 "status": {
435 "type": "string",
436 "enum": ["active", "idle", "finished"],
437 "description": "New status for status action"
438 }
439 },
440 "required": ["action"]
441 }),
442 ),
443 tool_def(
444 "ctx_overview",
445 "Task-relevant project map — use at session start.",
446 json!({
447 "type": "object",
448 "properties": {
449 "task": {
450 "type": "string",
451 "description": "Task description for relevance scoring (e.g. 'fix auth bug in login flow')"
452 },
453 "path": {
454 "type": "string",
455 "description": "Project root directory (default: .)"
456 }
457 }
458 }),
459 ),
460 tool_def(
461 "ctx_wrapped",
462 "Savings report card. Periods: week|month|all.",
463 json!({
464 "type": "object",
465 "properties": {
466 "period": {
467 "type": "string",
468 "enum": ["week", "month", "all"],
469 "description": "Report period (default: week)"
470 }
471 }
472 }),
473 ),
474 tool_def(
475 "ctx_semantic_search",
476 "BM25 code search by meaning. action=reindex to rebuild.",
477 json!({
478 "type": "object",
479 "properties": {
480 "query": { "type": "string", "description": "Natural language search query" },
481 "path": { "type": "string", "description": "Project root to search (default: .)" },
482 "top_k": { "type": "integer", "description": "Number of results (default: 10)" },
483 "action": { "type": "string", "description": "reindex to rebuild index" }
484 },
485 "required": ["query"]
486 }),
487 ),
488 ],
489 ..Default::default()
490 })
491 }
492
493 async fn call_tool(
494 &self,
495 request: CallToolRequestParams,
496 _context: RequestContext<RoleServer>,
497 ) -> Result<CallToolResult, ErrorData> {
498 self.check_idle_expiry().await;
499
500 let original_name = request.name.as_ref().to_string();
501 let (resolved_name, resolved_args) = if original_name == "ctx" {
502 let sub = request
503 .arguments
504 .as_ref()
505 .and_then(|a| a.get("tool"))
506 .and_then(|v| v.as_str())
507 .map(|s| s.to_string())
508 .ok_or_else(|| {
509 ErrorData::invalid_params("'tool' is required for ctx meta-tool", None)
510 })?;
511 let tool_name = if sub.starts_with("ctx_") {
512 sub
513 } else {
514 format!("ctx_{sub}")
515 };
516 let mut args = request.arguments.unwrap_or_default();
517 args.remove("tool");
518 (tool_name, Some(args))
519 } else {
520 (original_name, request.arguments)
521 };
522 let name = resolved_name.as_str();
523 let args = &resolved_args;
524
525 let result_text = match name {
526 "ctx_read" => {
527 let path = get_str(args, "path")
528 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
529 let current_task = {
530 let session = self.session.read().await;
531 session.task.as_ref().map(|t| t.description.clone())
532 };
533 let task_ref = current_task.as_deref();
534 let mut mode = match get_str(args, "mode") {
535 Some(m) => m,
536 None => {
537 let cache = self.cache.read().await;
538 crate::tools::ctx_smart_read::select_mode_with_task(&cache, &path, task_ref)
539 }
540 };
541 let fresh = get_bool(args, "fresh").unwrap_or(false);
542 let start_line = get_int(args, "start_line");
543 if let Some(sl) = start_line {
544 let sl = sl.max(1_i64);
545 mode = format!("lines:{sl}-999999");
546 }
547 let stale = self.is_prompt_cache_stale().await;
548 let effective_mode = LeanCtxServer::upgrade_mode_if_stale(&mode, stale).to_string();
549 let mut cache = self.cache.write().await;
550 let output = if fresh {
551 crate::tools::ctx_read::handle_fresh_with_task(
552 &mut cache,
553 &path,
554 &effective_mode,
555 self.crp_mode,
556 task_ref,
557 )
558 } else {
559 crate::tools::ctx_read::handle_with_task(
560 &mut cache,
561 &path,
562 &effective_mode,
563 self.crp_mode,
564 task_ref,
565 )
566 };
567 let stale_note = if effective_mode != mode {
568 format!("[cache stale, {mode}→{effective_mode}]\n")
569 } else {
570 String::new()
571 };
572 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
573 let output_tokens = crate::core::tokens::count_tokens(&output);
574 let saved = original.saturating_sub(output_tokens);
575 let output = format!("{stale_note}{output}");
576 let file_ref = cache.file_ref_map().get(&path).cloned();
577 drop(cache);
578 {
579 let mut session = self.session.write().await;
580 session.touch_file(&path, file_ref.as_deref(), &effective_mode, original);
581 if session.project_root.is_none() {
582 if let Some(root) = detect_project_root(&path) {
583 session.project_root = Some(root.clone());
584 let mut current = self.agent_id.write().await;
585 if current.is_none() {
586 let mut registry =
587 crate::core::agents::AgentRegistry::load_or_create();
588 registry.cleanup_stale(24);
589 let id = registry.register("mcp", None, &root);
590 let _ = registry.save();
591 *current = Some(id);
592 }
593 }
594 }
595 }
596 self.record_call("ctx_read", original, saved, Some(mode.clone()))
597 .await;
598 {
599 let sig =
600 crate::core::mode_predictor::FileSignature::from_path(&path, original);
601 let density = if output_tokens > 0 {
602 original as f64 / output_tokens as f64
603 } else {
604 1.0
605 };
606 let outcome = crate::core::mode_predictor::ModeOutcome {
607 mode: mode.clone(),
608 tokens_in: original,
609 tokens_out: output_tokens,
610 density: density.min(1.0),
611 };
612 let mut predictor = crate::core::mode_predictor::ModePredictor::new();
613 predictor.record(sig, outcome);
614 predictor.save();
615
616 let ext = std::path::Path::new(&path)
617 .extension()
618 .and_then(|e| e.to_str())
619 .unwrap_or("")
620 .to_string();
621 let thresholds = crate::core::adaptive_thresholds::thresholds_for_path(&path);
622 let cache = self.cache.read().await;
623 let stats = cache.get_stats();
624 let feedback_outcome = crate::core::feedback::CompressionOutcome {
625 session_id: format!("{}", std::process::id()),
626 language: ext,
627 entropy_threshold: thresholds.bpe_entropy,
628 jaccard_threshold: thresholds.jaccard,
629 total_turns: stats.total_reads as u32,
630 tokens_saved: saved as u64,
631 tokens_original: original as u64,
632 cache_hits: stats.cache_hits as u32,
633 total_reads: stats.total_reads as u32,
634 task_completed: true,
635 timestamp: chrono::Local::now().to_rfc3339(),
636 };
637 drop(cache);
638 let mut store = crate::core::feedback::FeedbackStore::load();
639 store.record_outcome(feedback_outcome);
640 }
641 output
642 }
643 "ctx_multi_read" => {
644 let paths = get_str_array(args, "paths")
645 .ok_or_else(|| ErrorData::invalid_params("paths array is required", None))?;
646 let mode = get_str(args, "mode").unwrap_or_else(|| "full".to_string());
647 let mut cache = self.cache.write().await;
648 let output =
649 crate::tools::ctx_multi_read::handle(&mut cache, &paths, &mode, self.crp_mode);
650 let mut total_original: usize = 0;
651 for path in &paths {
652 total_original = total_original
653 .saturating_add(cache.get(path).map(|e| e.original_tokens).unwrap_or(0));
654 }
655 let tokens = crate::core::tokens::count_tokens(&output);
656 drop(cache);
657 self.record_call(
658 "ctx_multi_read",
659 total_original,
660 total_original.saturating_sub(tokens),
661 Some(mode),
662 )
663 .await;
664 output
665 }
666 "ctx_tree" => {
667 let path = get_str(args, "path").unwrap_or_else(|| ".".to_string());
668 let depth = get_int(args, "depth").unwrap_or(3) as usize;
669 let show_hidden = get_bool(args, "show_hidden").unwrap_or(false);
670 let (result, original) = crate::tools::ctx_tree::handle(&path, depth, show_hidden);
671 let sent = crate::core::tokens::count_tokens(&result);
672 let saved = original.saturating_sub(sent);
673 self.record_call("ctx_tree", original, saved, None).await;
674 let savings_note = if saved > 0 {
675 format!("\n[saved {saved} tokens vs native ls]")
676 } else {
677 String::new()
678 };
679 format!("{result}{savings_note}")
680 }
681 "ctx_shell" => {
682 let command = get_str(args, "command")
683 .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
684 let output = execute_command(&command);
685 let result = crate::tools::ctx_shell::handle(&command, &output, self.crp_mode);
686 let original = crate::core::tokens::count_tokens(&output);
687 let sent = crate::core::tokens::count_tokens(&result);
688 let saved = original.saturating_sub(sent);
689 self.record_call("ctx_shell", original, saved, None).await;
690 let savings_note = if saved > 0 {
691 format!("\n[saved {saved} tokens vs native Shell]")
692 } else {
693 String::new()
694 };
695 format!("{result}{savings_note}")
696 }
697 "ctx_search" => {
698 let pattern = get_str(args, "pattern")
699 .ok_or_else(|| ErrorData::invalid_params("pattern is required", None))?;
700 let path = get_str(args, "path").unwrap_or_else(|| ".".to_string());
701 let ext = get_str(args, "ext");
702 let max = get_int(args, "max_results").unwrap_or(20) as usize;
703 let no_gitignore = get_bool(args, "ignore_gitignore").unwrap_or(false);
704 let (result, original) = crate::tools::ctx_search::handle(
705 &pattern,
706 &path,
707 ext.as_deref(),
708 max,
709 self.crp_mode,
710 !no_gitignore,
711 );
712 let sent = crate::core::tokens::count_tokens(&result);
713 let saved = original.saturating_sub(sent);
714 self.record_call("ctx_search", original, saved, None).await;
715 let savings_note = if saved > 0 {
716 format!("\n[saved {saved} tokens vs native Grep]")
717 } else {
718 String::new()
719 };
720 format!("{result}{savings_note}")
721 }
722 "ctx_compress" => {
723 let include_sigs = get_bool(args, "include_signatures").unwrap_or(true);
724 let cache = self.cache.read().await;
725 let result =
726 crate::tools::ctx_compress::handle(&cache, include_sigs, self.crp_mode);
727 drop(cache);
728 self.record_call("ctx_compress", 0, 0, None).await;
729 result
730 }
731 "ctx_benchmark" => {
732 let path = get_str(args, "path")
733 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
734 let action = get_str(args, "action").unwrap_or_default();
735 let result = if action == "project" {
736 let fmt = get_str(args, "format").unwrap_or_default();
737 let bench = crate::core::benchmark::run_project_benchmark(&path);
738 match fmt.as_str() {
739 "json" => crate::core::benchmark::format_json(&bench),
740 "markdown" | "md" => crate::core::benchmark::format_markdown(&bench),
741 _ => crate::core::benchmark::format_terminal(&bench),
742 }
743 } else {
744 crate::tools::ctx_benchmark::handle(&path, self.crp_mode)
745 };
746 self.record_call("ctx_benchmark", 0, 0, None).await;
747 result
748 }
749 "ctx_metrics" => {
750 let cache = self.cache.read().await;
751 let calls = self.tool_calls.read().await;
752 let result = crate::tools::ctx_metrics::handle(&cache, &calls, self.crp_mode);
753 drop(cache);
754 drop(calls);
755 self.record_call("ctx_metrics", 0, 0, None).await;
756 result
757 }
758 "ctx_analyze" => {
759 let path = get_str(args, "path")
760 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
761 let result = crate::tools::ctx_analyze::handle(&path, self.crp_mode);
762 self.record_call("ctx_analyze", 0, 0, None).await;
763 result
764 }
765 "ctx_discover" => {
766 let limit = get_int(args, "limit").unwrap_or(15) as usize;
767 let history = crate::cli::load_shell_history_pub();
768 let result = crate::tools::ctx_discover::discover_from_history(&history, limit);
769 self.record_call("ctx_discover", 0, 0, None).await;
770 result
771 }
772 "ctx_smart_read" => {
773 let path = get_str(args, "path")
774 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
775 let mut cache = self.cache.write().await;
776 let output = crate::tools::ctx_smart_read::handle(&mut cache, &path, self.crp_mode);
777 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
778 let tokens = crate::core::tokens::count_tokens(&output);
779 drop(cache);
780 self.record_call(
781 "ctx_smart_read",
782 original,
783 original.saturating_sub(tokens),
784 Some("auto".to_string()),
785 )
786 .await;
787 output
788 }
789 "ctx_delta" => {
790 let path = get_str(args, "path")
791 .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
792 let mut cache = self.cache.write().await;
793 let output = crate::tools::ctx_delta::handle(&mut cache, &path);
794 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
795 let tokens = crate::core::tokens::count_tokens(&output);
796 drop(cache);
797 {
798 let mut session = self.session.write().await;
799 session.mark_modified(&path);
800 }
801 self.record_call(
802 "ctx_delta",
803 original,
804 original.saturating_sub(tokens),
805 Some("delta".to_string()),
806 )
807 .await;
808 output
809 }
810 "ctx_dedup" => {
811 let action = get_str(args, "action").unwrap_or_default();
812 if action == "apply" {
813 let mut cache = self.cache.write().await;
814 let result = crate::tools::ctx_dedup::handle_action(&mut cache, &action);
815 drop(cache);
816 self.record_call("ctx_dedup", 0, 0, None).await;
817 result
818 } else {
819 let cache = self.cache.read().await;
820 let result = crate::tools::ctx_dedup::handle(&cache);
821 drop(cache);
822 self.record_call("ctx_dedup", 0, 0, None).await;
823 result
824 }
825 }
826 "ctx_fill" => {
827 let paths = get_str_array(args, "paths")
828 .ok_or_else(|| ErrorData::invalid_params("paths array is required", None))?;
829 let budget = get_int(args, "budget")
830 .ok_or_else(|| ErrorData::invalid_params("budget is required", None))?
831 as usize;
832 let mut cache = self.cache.write().await;
833 let output =
834 crate::tools::ctx_fill::handle(&mut cache, &paths, budget, self.crp_mode);
835 drop(cache);
836 self.record_call("ctx_fill", 0, 0, Some(format!("budget:{budget}")))
837 .await;
838 output
839 }
840 "ctx_intent" => {
841 let query = get_str(args, "query")
842 .ok_or_else(|| ErrorData::invalid_params("query is required", None))?;
843 let root = get_str(args, "project_root").unwrap_or_else(|| ".".to_string());
844 let mut cache = self.cache.write().await;
845 let output =
846 crate::tools::ctx_intent::handle(&mut cache, &query, &root, self.crp_mode);
847 drop(cache);
848 {
849 let mut session = self.session.write().await;
850 session.set_task(&query, Some("intent"));
851 }
852 self.record_call("ctx_intent", 0, 0, Some("semantic".to_string()))
853 .await;
854 output
855 }
856 "ctx_response" => {
857 let text = get_str(args, "text")
858 .ok_or_else(|| ErrorData::invalid_params("text is required", None))?;
859 let output = crate::tools::ctx_response::handle(&text, self.crp_mode);
860 self.record_call("ctx_response", 0, 0, None).await;
861 output
862 }
863 "ctx_context" => {
864 let cache = self.cache.read().await;
865 let turn = self.call_count.load(std::sync::atomic::Ordering::Relaxed);
866 let result = crate::tools::ctx_context::handle_status(&cache, turn, self.crp_mode);
867 drop(cache);
868 self.record_call("ctx_context", 0, 0, None).await;
869 result
870 }
871 "ctx_graph" => {
872 let action = get_str(args, "action")
873 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
874 let path = get_str(args, "path");
875 let root = get_str(args, "project_root").unwrap_or_else(|| ".".to_string());
876 let mut cache = self.cache.write().await;
877 let result = crate::tools::ctx_graph::handle(
878 &action,
879 path.as_deref(),
880 &root,
881 &mut cache,
882 self.crp_mode,
883 );
884 drop(cache);
885 self.record_call("ctx_graph", 0, 0, Some(action)).await;
886 result
887 }
888 "ctx_cache" => {
889 let action = get_str(args, "action")
890 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
891 let mut cache = self.cache.write().await;
892 let result = match action.as_str() {
893 "status" => {
894 let entries = cache.get_all_entries();
895 if entries.is_empty() {
896 "Cache empty — no files tracked.".to_string()
897 } else {
898 let mut lines = vec![format!("Cache: {} file(s)", entries.len())];
899 for (path, entry) in &entries {
900 let fref = cache
901 .file_ref_map()
902 .get(*path)
903 .map(|s| s.as_str())
904 .unwrap_or("F?");
905 lines.push(format!(
906 " {fref}={} [{}L, {}t, read {}x]",
907 crate::core::protocol::shorten_path(path),
908 entry.line_count,
909 entry.original_tokens,
910 entry.read_count
911 ));
912 }
913 lines.join("\n")
914 }
915 }
916 "clear" => {
917 let count = cache.clear();
918 format!("Cache cleared — {count} file(s) removed. Next ctx_read will return full content.")
919 }
920 "invalidate" => {
921 let path = get_str(args, "path").ok_or_else(|| {
922 ErrorData::invalid_params("path is required for invalidate", None)
923 })?;
924 if cache.invalidate(&path) {
925 format!(
926 "Invalidated cache for {}. Next ctx_read will return full content.",
927 crate::core::protocol::shorten_path(&path)
928 )
929 } else {
930 format!(
931 "{} was not in cache.",
932 crate::core::protocol::shorten_path(&path)
933 )
934 }
935 }
936 _ => "Unknown action. Use: status, clear, invalidate".to_string(),
937 };
938 drop(cache);
939 self.record_call("ctx_cache", 0, 0, Some(action)).await;
940 result
941 }
942 "ctx_session" => {
943 let action = get_str(args, "action")
944 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
945 let value = get_str(args, "value");
946 let sid = get_str(args, "session_id");
947 let mut session = self.session.write().await;
948 let result = crate::tools::ctx_session::handle(
949 &mut session,
950 &action,
951 value.as_deref(),
952 sid.as_deref(),
953 );
954 drop(session);
955 self.record_call("ctx_session", 0, 0, Some(action)).await;
956 result
957 }
958 "ctx_knowledge" => {
959 let action = get_str(args, "action")
960 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
961 let category = get_str(args, "category");
962 let key = get_str(args, "key");
963 let value = get_str(args, "value");
964 let query = get_str(args, "query");
965 let pattern_type = get_str(args, "pattern_type");
966 let examples = get_str_array(args, "examples");
967 let confidence: Option<f32> = args
968 .as_ref()
969 .and_then(|a| a.get("confidence"))
970 .and_then(|v| v.as_f64())
971 .map(|v| v as f32);
972
973 let session = self.session.read().await;
974 let session_id = session.id.clone();
975 let project_root = session.project_root.clone().unwrap_or_else(|| {
976 std::env::current_dir()
977 .map(|p| p.to_string_lossy().to_string())
978 .unwrap_or_else(|_| "unknown".to_string())
979 });
980 drop(session);
981
982 let result = crate::tools::ctx_knowledge::handle(
983 &project_root,
984 &action,
985 category.as_deref(),
986 key.as_deref(),
987 value.as_deref(),
988 query.as_deref(),
989 &session_id,
990 pattern_type.as_deref(),
991 examples,
992 confidence,
993 );
994 self.record_call("ctx_knowledge", 0, 0, Some(action)).await;
995 result
996 }
997 "ctx_agent" => {
998 let action = get_str(args, "action")
999 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
1000 let agent_type = get_str(args, "agent_type");
1001 let role = get_str(args, "role");
1002 let message = get_str(args, "message");
1003 let category = get_str(args, "category");
1004 let to_agent = get_str(args, "to_agent");
1005 let status = get_str(args, "status");
1006
1007 let session = self.session.read().await;
1008 let project_root = session.project_root.clone().unwrap_or_else(|| {
1009 std::env::current_dir()
1010 .map(|p| p.to_string_lossy().to_string())
1011 .unwrap_or_else(|_| "unknown".to_string())
1012 });
1013 drop(session);
1014
1015 let current_agent_id = self.agent_id.read().await.clone();
1016 let result = crate::tools::ctx_agent::handle(
1017 &action,
1018 agent_type.as_deref(),
1019 role.as_deref(),
1020 &project_root,
1021 current_agent_id.as_deref(),
1022 message.as_deref(),
1023 category.as_deref(),
1024 to_agent.as_deref(),
1025 status.as_deref(),
1026 );
1027
1028 if action == "register" {
1029 if let Some(id) = result.split(':').nth(1) {
1030 let id = id.split_whitespace().next().unwrap_or("").to_string();
1031 if !id.is_empty() {
1032 *self.agent_id.write().await = Some(id);
1033 }
1034 }
1035 }
1036
1037 self.record_call("ctx_agent", 0, 0, Some(action)).await;
1038 result
1039 }
1040 "ctx_overview" => {
1041 let task = get_str(args, "task");
1042 let path = get_str(args, "path");
1043 let cache = self.cache.read().await;
1044 let result = crate::tools::ctx_overview::handle(
1045 &cache,
1046 task.as_deref(),
1047 path.as_deref(),
1048 self.crp_mode,
1049 );
1050 drop(cache);
1051 self.record_call("ctx_overview", 0, 0, Some("overview".to_string()))
1052 .await;
1053 result
1054 }
1055 "ctx_wrapped" => {
1056 let period = get_str(args, "period").unwrap_or_else(|| "week".to_string());
1057 let result = crate::tools::ctx_wrapped::handle(&period);
1058 self.record_call("ctx_wrapped", 0, 0, Some(period)).await;
1059 result
1060 }
1061 "ctx_semantic_search" => {
1062 let query = get_str(args, "query")
1063 .ok_or_else(|| ErrorData::invalid_params("query is required", None))?;
1064 let path = get_str(args, "path").unwrap_or_else(|| ".".to_string());
1065 let top_k = get_int(args, "top_k").unwrap_or(10) as usize;
1066 let action = get_str(args, "action").unwrap_or_default();
1067 let result = if action == "reindex" {
1068 crate::tools::ctx_semantic_search::handle_reindex(&path)
1069 } else {
1070 crate::tools::ctx_semantic_search::handle(&query, &path, top_k, self.crp_mode)
1071 };
1072 self.record_call("ctx_semantic_search", 0, 0, Some("semantic".to_string()))
1073 .await;
1074 result
1075 }
1076 _ => {
1077 return Err(ErrorData::invalid_params(
1078 format!("Unknown tool: {name}"),
1079 None,
1080 ));
1081 }
1082 };
1083
1084 let skip_checkpoint = matches!(
1085 name,
1086 "ctx_compress"
1087 | "ctx_metrics"
1088 | "ctx_benchmark"
1089 | "ctx_analyze"
1090 | "ctx_cache"
1091 | "ctx_discover"
1092 | "ctx_dedup"
1093 | "ctx_session"
1094 | "ctx_knowledge"
1095 | "ctx_agent"
1096 | "ctx_wrapped"
1097 | "ctx_overview"
1098 );
1099
1100 if !skip_checkpoint && self.increment_and_check() {
1101 if let Some(checkpoint) = self.auto_checkpoint().await {
1102 let combined = format!(
1103 "{result_text}\n\n--- AUTO CHECKPOINT (every {} calls) ---\n{checkpoint}",
1104 self.checkpoint_interval
1105 );
1106 return Ok(CallToolResult::success(vec![Content::text(combined)]));
1107 }
1108 }
1109
1110 let current_count = self.call_count.load(std::sync::atomic::Ordering::Relaxed);
1111 if current_count > 0 && current_count.is_multiple_of(100) {
1112 std::thread::spawn(cloud_background_tasks);
1113 }
1114
1115 Ok(CallToolResult::success(vec![Content::text(result_text)]))
1116 }
1117}
1118
1119fn build_instructions(crp_mode: CrpMode) -> String {
1120 build_instructions_with_client(crp_mode, "")
1121}
1122
1123fn build_instructions_with_client(crp_mode: CrpMode, client_name: &str) -> String {
1124 let profile = crate::core::litm::LitmProfile::from_client_name(client_name);
1125 let session_block = match crate::core::session::SessionState::load_latest() {
1126 Some(ref session) => {
1127 let positioned = crate::core::litm::position_optimize(session);
1128 format!(
1129 "\n\n--- ACTIVE SESSION (LITM P1: begin position, profile: {}) ---\n{}\n---\n",
1130 profile.name, positioned.begin_block
1131 )
1132 }
1133 None => String::new(),
1134 };
1135
1136 let knowledge_block = {
1137 let project_root = crate::core::session::SessionState::load_latest()
1138 .and_then(|s| s.project_root)
1139 .or_else(|| {
1140 std::env::current_dir()
1141 .ok()
1142 .map(|p| p.to_string_lossy().to_string())
1143 });
1144 match project_root {
1145 Some(root) => {
1146 let knowledge = crate::core::knowledge::ProjectKnowledge::load(&root);
1147 match knowledge {
1148 Some(k) if !k.facts.is_empty() || !k.patterns.is_empty() => {
1149 format!("\n--- PROJECT KNOWLEDGE ---\n{}\n---\n", k.format_summary())
1150 }
1151 _ => String::new(),
1152 }
1153 }
1154 None => String::new(),
1155 }
1156 };
1157
1158 let mut base = format!("\
1161CRITICAL: NEVER use native Read, Shell, Grep, or ls tools. ALWAYS use ctx_read, ctx_shell, ctx_search, ctx_tree from this MCP server instead.\n\
1162\n\
1163lean-ctx MCP — tool replacement for reading, running commands, and searching.\n\
1164\n\
1165REPLACE these built-in tools with lean-ctx equivalents:\n\
1166• Read file → ctx_read(path, mode) — NEVER use Read tool\n\
1167• Run command → ctx_shell(command) — NEVER use Shell tool\n\
1168• Search code → ctx_search(pattern, path) — NEVER use Grep tool\n\
1169• List files → ctx_tree(path, depth) — NEVER use Shell with ls/find\n\
1170\n\
1171KEEP using these built-in tools normally (lean-ctx has NO replacement for them):\n\
1172• Write — create/overwrite files directly\n\
1173• StrReplace — edit files directly\n\
1174• Delete — delete files directly\n\
1175• Glob — find files by pattern\n\
1176You do NOT need to ctx_read a file before creating it with Write.\n\
1177\n\
1178ctx_read modes: full (cached, for files you edit), map (deps+API, context-only), \
1179signatures, diff, task (IB-filtered task-relevant lines), reference (one-line metadata), \
1180aggressive, entropy, lines:N-M (specific line ranges). \
1181Auto-selects optimal mode when none specified. Re-reads cost ~13 tokens. File refs F1,F2.. persist.\n\
1182IMPORTANT: If ctx_read returns 'cached Nt NL' and you need the actual file content, you MUST either:\n\
1183 1. Set fresh=true to force a full re-read, OR\n\
1184 2. Use start_line=N to read from a specific line, OR\n\
1185 3. Use mode='lines:N-M' to read a specific range.\n\
1186Do not fall back to native Read tools — always use fresh=true or start_line instead.\n\
1187\n\
1188PROACTIVE (use without being asked):\n\
1189• ctx_overview(task) — at session start, get task-relevant project map\n\
1190• ctx_compress — when context grows large, create checkpoint\n\
1191• ctx_session load — restore previous session on new chat\n\
1192\n\
1193ADDITIONAL TOOLS (see tool descriptions for parameters):\n\
1194• ctx_session — cross-session memory (load/save/status/task/finding/decision)\n\
1195• ctx_knowledge — persistent project facts (remember/recall/pattern/status/remove/consolidate)\n\
1196• ctx_agent — multi-agent coordination (register/list/post/read/status)\n\
1197• ctx_metrics — token savings stats\n\
1198• ctx_analyze/ctx_benchmark — compression analysis per file\n\
1199• ctx_cache — manage file cache (status/clear/invalidate)\n\
1200• ctx_wrapped — savings report card\n\
1201• ctx_compress — context checkpoint\n\
1202\n\
1203Auto-checkpoint runs every 15 tool calls. Cache auto-clears after 5 min idle.\n\
1204\n\
1205COMMUNICATION PROTOCOL (CEP v1):\n\
12061. ACT FIRST — Execute tool calls immediately, summarize after.\n\
12072. DELTA ONLY — Reference cached files by Fn ID, never repeat known context.\n\
12083. STRUCTURED OVER PROSE — Use notation: +line / -line / ~line, tool(args) → result.\n\
12094. ONE LINE PER ACTION — Summarize, don't explain.\n\
12105. QUALITY ANCHOR — Never skip edge case analysis to save tokens.\n\
1211\n\
1212{decoder_block}\n\
1213\n\
1214{decoder_block}\n\
1215\n\
1216{session_block}\
1217{knowledge_block}\
1218\n\
1219--- TOOL ENFORCEMENT (LITM-END) ---\n\
1220CRITICAL REMINDER: You MUST use lean-ctx MCP tools for ALL file reads, shell commands, and code searches.\n\
1221• Read/cat/head/tail → ctx_read | Shell/bash → ctx_shell | Grep/rg → ctx_search | ls/find → ctx_tree\n\
1222• Write, StrReplace, Delete, Glob → use normally (no lean-ctx replacement)\n\
1223NEVER use native Read, Shell, Grep, or ls. ALWAYS use ctx_read, ctx_shell, ctx_search, ctx_tree. Every single time.",
1224 decoder_block = crate::core::protocol::instruction_decoder_block()
1225 );
1226
1227 if should_use_unified(client_name) {
1228 base.push_str(
1229 "\n\n\
1230UNIFIED TOOL MODE (active):\n\
1231Additional tools are accessed via ctx() meta-tool: ctx(tool=\"<name>\", ...params).\n\
1232See the ctx() tool description for available sub-tools.\n",
1233 );
1234 }
1235
1236 let base = base;
1237 match crp_mode {
1238 CrpMode::Off => base,
1239 CrpMode::Compact => {
1240 format!(
1241 "{base}\n\n\
1242CRP MODE: compact\n\
1243Respond using Compact Response Protocol:\n\
1244• Omit filler words, articles, and redundant phrases\n\
1245• Use symbol shorthand: → ∴ ≈ ✓ ✗\n\
1246• Abbreviate: fn, cfg, impl, deps, req, res, ctx, err, ok, ret, arg, val, ty, mod\n\
1247• Use compact lists instead of prose\n\
1248• Prefer code blocks over natural language explanations\n\
1249• For code changes: show only diff lines (+/-), not full files\n\
1250• TARGET: ≤200 tokens per response unless code edits require more\n\
1251• THINK LESS: Tool outputs include pre-analyzed context (deps, API surface, file structure). \
1252Trust these summaries instead of re-analyzing from raw content."
1253 )
1254 }
1255 CrpMode::Tdd => {
1256 format!(
1257 "{base}\n\n\
1258CRP MODE: tdd (Token Dense Dialect)\n\
1259CRITICAL: Maximize information density. Every token must carry meaning.\n\
1260\n\
1261RESPONSE RULES:\n\
1262• Drop all articles (a, the, an), filler words, and pleasantries\n\
1263• Reference files by Fn refs only, never full paths\n\
1264• For code changes: show only diff lines, not full files\n\
1265• No explanations unless asked — just show the solution\n\
1266• Use tabular format for structured data\n\
1267• Abbreviations: fn, cfg, impl, deps, req, res, ctx, err, ok, ret, arg, val, ty, mod\n\
1268\n\
1269SYMBOLS (each = 1 token, replaces 5-10 tokens of prose):\n\
1270Structural: λ=function §=module/struct ∂=interface/trait τ=type ε=enum\n\
1271Actions: ⊕=add ⊖=remove ∆=modify →=returns ⇒=implies\n\
1272Status: ✓=ok ✗=fail ⚠=warning\n\
1273\n\
1274CHANGE NOTATION (use for all code modifications):\n\
1275⊕F1:42 param(timeout:Duration) — added parameter\n\
1276⊖F1:10-15 — removed lines\n\
1277∆F1:42 validate_token → verify_jwt — renamed/refactored\n\
1278\n\
1279STATUS NOTATION:\n\
1280ctx_read(F1) → 808L cached ✓\n\
1281cargo test → 82 passed ✓ 0 failed\n\
1282\n\
1283SYMBOL TABLE: Tool outputs include a §MAP section mapping long identifiers to short IDs.\n\
1284Use these short IDs in all subsequent references.\n\
1285\n\
1286TOKEN BUDGET: ≤150 tokens per response. Exceed only for multi-file code edits.\n\
1287THINK LESS: Tool outputs are pre-analyzed (deps extracted, API surfaces mapped, \
1288structure summarized). Trust compressed outputs directly — do not re-derive what is already provided.\n\
1289ZERO NARRATION: Never narrate tool calls ('Let me read...', 'I will now...'). Act, then report result in 1 line."
1290 )
1291 }
1292 }
1293}
1294
1295fn tool_def(name: &'static str, description: &'static str, schema_value: Value) -> Tool {
1296 let schema: Map<String, Value> = match schema_value {
1297 Value::Object(map) => map,
1298 _ => Map::new(),
1299 };
1300 Tool::new(name, description, Arc::new(schema))
1301}
1302
1303fn unified_tool_defs() -> Vec<Tool> {
1304 vec![
1305 tool_def(
1306 "ctx_read",
1307 "Read file (cached, compressed). Modes: full|map|signatures|diff|aggressive|entropy|task|reference|lines:N-M. fresh=true re-reads.",
1308 json!({
1309 "type": "object",
1310 "properties": {
1311 "path": { "type": "string", "description": "File path" },
1312 "mode": { "type": "string" },
1313 "start_line": { "type": "integer" },
1314 "fresh": { "type": "boolean" }
1315 },
1316 "required": ["path"]
1317 }),
1318 ),
1319 tool_def(
1320 "ctx_shell",
1321 "Run shell command (compressed output).",
1322 json!({
1323 "type": "object",
1324 "properties": {
1325 "command": { "type": "string", "description": "Shell command" }
1326 },
1327 "required": ["command"]
1328 }),
1329 ),
1330 tool_def(
1331 "ctx_search",
1332 "Regex code search (.gitignore aware).",
1333 json!({
1334 "type": "object",
1335 "properties": {
1336 "pattern": { "type": "string", "description": "Regex pattern" },
1337 "path": { "type": "string" },
1338 "ext": { "type": "string" },
1339 "max_results": { "type": "integer" },
1340 "ignore_gitignore": { "type": "boolean" }
1341 },
1342 "required": ["pattern"]
1343 }),
1344 ),
1345 tool_def(
1346 "ctx_tree",
1347 "Directory listing with file counts.",
1348 json!({
1349 "type": "object",
1350 "properties": {
1351 "path": { "type": "string" },
1352 "depth": { "type": "integer" },
1353 "show_hidden": { "type": "boolean" }
1354 }
1355 }),
1356 ),
1357 tool_def(
1358 "ctx",
1359 "Meta-tool: set tool= to sub-tool name. Sub-tools: compress (checkpoint), metrics (stats), \
1360analyze (entropy), cache (status|clear|invalidate), discover (missed patterns), smart_read (auto-mode), \
1361delta (incremental diff), dedup (cross-file), fill (budget-aware batch read), intent (auto-read by task), \
1362response (compress LLM text), context (session state), graph (build|related|symbol|impact|status), \
1363session (load|save|task|finding|decision|status|reset|list|cleanup), \
1364knowledge (remember|recall|pattern|consolidate|status|remove|export), \
1365agent (register|post|read|status|list|info), overview (project map), \
1366wrapped (savings report), benchmark (file|project), multi_read (batch), semantic_search (BM25).",
1367 json!({
1368 "type": "object",
1369 "properties": {
1370 "tool": {
1371 "type": "string",
1372 "description": "compress|metrics|analyze|cache|discover|smart_read|delta|dedup|fill|intent|response|context|graph|session|knowledge|agent|overview|wrapped|benchmark|multi_read|semantic_search"
1373 },
1374 "action": { "type": "string" },
1375 "path": { "type": "string" },
1376 "paths": { "type": "array", "items": { "type": "string" } },
1377 "query": { "type": "string" },
1378 "value": { "type": "string" },
1379 "category": { "type": "string" },
1380 "key": { "type": "string" },
1381 "budget": { "type": "integer" },
1382 "task": { "type": "string" },
1383 "mode": { "type": "string" },
1384 "text": { "type": "string" },
1385 "message": { "type": "string" },
1386 "session_id": { "type": "string" },
1387 "period": { "type": "string" },
1388 "format": { "type": "string" },
1389 "agent_type": { "type": "string" },
1390 "role": { "type": "string" },
1391 "status": { "type": "string" },
1392 "pattern_type": { "type": "string" },
1393 "examples": { "type": "array", "items": { "type": "string" } },
1394 "confidence": { "type": "number" },
1395 "project_root": { "type": "string" },
1396 "include_signatures": { "type": "boolean" },
1397 "limit": { "type": "integer" },
1398 "to_agent": { "type": "string" },
1399 "show_hidden": { "type": "boolean" }
1400 },
1401 "required": ["tool"]
1402 }),
1403 ),
1404 ]
1405}
1406
1407fn should_use_unified(client_name: &str) -> bool {
1408 if std::env::var("LEAN_CTX_FULL_TOOLS").is_ok() {
1409 return false;
1410 }
1411 if std::env::var("LEAN_CTX_UNIFIED").is_ok() {
1412 return true;
1413 }
1414 let _ = client_name;
1415 false
1416}
1417
1418fn get_str_array(args: &Option<serde_json::Map<String, Value>>, key: &str) -> Option<Vec<String>> {
1419 let arr = args.as_ref()?.get(key)?.as_array()?;
1420 let mut out = Vec::with_capacity(arr.len());
1421 for v in arr {
1422 let s = v.as_str()?.to_string();
1423 out.push(s);
1424 }
1425 Some(out)
1426}
1427
1428fn get_str(args: &Option<serde_json::Map<String, Value>>, key: &str) -> Option<String> {
1429 args.as_ref()?.get(key)?.as_str().map(|s| s.to_string())
1430}
1431
1432fn get_int(args: &Option<serde_json::Map<String, Value>>, key: &str) -> Option<i64> {
1433 args.as_ref()?.get(key)?.as_i64()
1434}
1435
1436fn get_bool(args: &Option<serde_json::Map<String, Value>>, key: &str) -> Option<bool> {
1437 args.as_ref()?.get(key)?.as_bool()
1438}
1439
1440fn execute_command(command: &str) -> String {
1441 let (shell, flag) = crate::shell::shell_and_flag();
1442 let output = std::process::Command::new(&shell)
1443 .arg(&flag)
1444 .arg(command)
1445 .env("LEAN_CTX_ACTIVE", "1")
1446 .output();
1447
1448 match output {
1449 Ok(out) => {
1450 let stdout = String::from_utf8_lossy(&out.stdout);
1451 let stderr = String::from_utf8_lossy(&out.stderr);
1452 if stdout.is_empty() {
1453 stderr.to_string()
1454 } else if stderr.is_empty() {
1455 stdout.to_string()
1456 } else {
1457 format!("{stdout}\n{stderr}")
1458 }
1459 }
1460 Err(e) => format!("ERROR: {e}"),
1461 }
1462}
1463
1464fn detect_project_root(file_path: &str) -> Option<String> {
1465 let mut dir = std::path::Path::new(file_path).parent()?;
1466 loop {
1467 if dir.join(".git").exists() {
1468 return Some(dir.to_string_lossy().to_string());
1469 }
1470 dir = dir.parent()?;
1471 }
1472}
1473
1474fn cloud_background_tasks() {
1475 use crate::core::config::Config;
1476
1477 let mut config = Config::load();
1478 let today = chrono::Local::now().format("%Y-%m-%d").to_string();
1479
1480 let already_contributed = config
1481 .cloud
1482 .last_contribute
1483 .as_deref()
1484 .map(|d| d == today)
1485 .unwrap_or(false);
1486 let already_synced = config
1487 .cloud
1488 .last_sync
1489 .as_deref()
1490 .map(|d| d == today)
1491 .unwrap_or(false);
1492 let already_pulled = config
1493 .cloud
1494 .last_model_pull
1495 .as_deref()
1496 .map(|d| d == today)
1497 .unwrap_or(false);
1498
1499 if config.cloud.contribute_enabled && !already_contributed {
1500 if let Some(home) = dirs::home_dir() {
1501 let mode_stats_path = home.join(".lean-ctx").join("mode_stats.json");
1502 if let Ok(data) = std::fs::read_to_string(&mode_stats_path) {
1503 if let Ok(predictor) = serde_json::from_str::<serde_json::Value>(&data) {
1504 let mut entries = Vec::new();
1505 if let Some(history) = predictor["history"].as_object() {
1506 for (_key, outcomes) in history {
1507 if let Some(arr) = outcomes.as_array() {
1508 for outcome in arr.iter().rev().take(3) {
1509 let ext = outcome["ext"].as_str().unwrap_or("unknown");
1510 let mode = outcome["mode"].as_str().unwrap_or("full");
1511 let t_in = outcome["tokens_in"].as_u64().unwrap_or(0);
1512 let t_out = outcome["tokens_out"].as_u64().unwrap_or(0);
1513 let ratio = if t_in > 0 {
1514 1.0 - t_out as f64 / t_in as f64
1515 } else {
1516 0.0
1517 };
1518 let bucket = match t_in {
1519 0..=500 => "0-500",
1520 501..=2000 => "500-2k",
1521 2001..=10000 => "2k-10k",
1522 _ => "10k+",
1523 };
1524 entries.push(serde_json::json!({
1525 "file_ext": format!(".{ext}"),
1526 "size_bucket": bucket,
1527 "best_mode": mode,
1528 "compression_ratio": (ratio * 100.0).round() / 100.0,
1529 }));
1530 if entries.len() >= 200 {
1531 break;
1532 }
1533 }
1534 }
1535 if entries.len() >= 200 {
1536 break;
1537 }
1538 }
1539 }
1540 if !entries.is_empty() && crate::cloud_client::contribute(&entries).is_ok() {
1541 config.cloud.last_contribute = Some(today.clone());
1542 }
1543 }
1544 }
1545 }
1546 }
1547
1548 if crate::cloud_client::check_pro() {
1549 if !already_synced {
1550 let stats_data = crate::core::stats::format_gain_json();
1551 if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stats_data) {
1552 let entry = serde_json::json!({
1553 "date": &today,
1554 "tokens_original": parsed["total_original_tokens"].as_i64().unwrap_or(0),
1555 "tokens_compressed": parsed["total_compressed_tokens"].as_i64().unwrap_or(0),
1556 "tokens_saved": parsed["total_saved_tokens"].as_i64().unwrap_or(0),
1557 "tool_calls": parsed["total_calls"].as_i64().unwrap_or(0),
1558 "cache_hits": parsed["cache_hits"].as_i64().unwrap_or(0),
1559 "cache_misses": parsed["cache_misses"].as_i64().unwrap_or(0),
1560 });
1561 if crate::cloud_client::sync_stats(&[entry]).is_ok() {
1562 config.cloud.last_sync = Some(today.clone());
1563 }
1564 }
1565 }
1566
1567 if !already_pulled {
1568 if let Ok(data) = crate::cloud_client::pull_pro_models() {
1569 let _ = crate::cloud_client::save_pro_models(&data);
1570 config.cloud.last_model_pull = Some(today.clone());
1571 }
1572 }
1573 }
1574
1575 let _ = config.save();
1576}
1577
1578pub fn build_instructions_for_test(crp_mode: CrpMode) -> String {
1579 build_instructions(crp_mode)
1580}
1581
1582pub fn tool_descriptions_for_test() -> Vec<(&'static str, &'static str)> {
1583 let mut result = Vec::new();
1584 let tools_json = list_all_tool_defs();
1585 for (name, desc, _) in tools_json {
1586 result.push((name, desc));
1587 }
1588 result
1589}
1590
1591pub fn tool_schemas_json_for_test() -> String {
1592 let tools_json = list_all_tool_defs();
1593 let schemas: Vec<String> = tools_json
1594 .iter()
1595 .map(|(name, _, schema)| format!("{}: {}", name, schema))
1596 .collect();
1597 schemas.join("\n")
1598}
1599
1600fn list_all_tool_defs() -> Vec<(&'static str, &'static str, Value)> {
1601 vec![
1602 ("ctx_read", "Read file (cached, compressed). Re-reads ~13 tok. Auto-selects optimal mode. \
1603Modes: full|map|signatures|diff|aggressive|entropy|task|reference|lines:N-M. fresh=true re-reads.", json!({"type": "object", "properties": {"path": {"type": "string"}, "mode": {"type": "string"}, "start_line": {"type": "integer"}, "fresh": {"type": "boolean"}}, "required": ["path"]})),
1604 ("ctx_multi_read", "Batch read files in one call. Same modes as ctx_read.", json!({"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "mode": {"type": "string"}}, "required": ["paths"]})),
1605 ("ctx_tree", "Directory listing with file counts.", json!({"type": "object", "properties": {"path": {"type": "string"}, "depth": {"type": "integer"}, "show_hidden": {"type": "boolean"}}})),
1606 ("ctx_shell", "Run shell command (compressed output, 90+ patterns).", json!({"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]})),
1607 ("ctx_search", "Regex code search (.gitignore aware, compact results).", json!({"type": "object", "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}, "ext": {"type": "string"}, "max_results": {"type": "integer"}}, "required": ["pattern"]})),
1608 ("ctx_compress", "Context checkpoint for long conversations.", json!({"type": "object", "properties": {"include_signatures": {"type": "boolean"}}})),
1609 ("ctx_benchmark", "Benchmark compression modes for a file or project.", json!({"type": "object", "properties": {"path": {"type": "string"}, "action": {"type": "string"}, "format": {"type": "string"}}, "required": ["path"]})),
1610 ("ctx_metrics", "Session token stats, cache rates, per-tool savings.", json!({"type": "object", "properties": {}})),
1611 ("ctx_analyze", "Entropy analysis — recommends optimal compression mode for a file.", json!({"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]})),
1612 ("ctx_cache", "Cache ops: status|clear|invalidate.", json!({"type": "object", "properties": {"action": {"type": "string"}, "path": {"type": "string"}}, "required": ["action"]})),
1613 ("ctx_discover", "Find missed compression opportunities in shell history.", json!({"type": "object", "properties": {"limit": {"type": "integer"}}})),
1614 ("ctx_smart_read", "Auto-select optimal read mode for a file.", json!({"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]})),
1615 ("ctx_delta", "Incremental diff — sends only changed lines since last read.", json!({"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]})),
1616 ("ctx_dedup", "Cross-file dedup: analyze or apply shared block references.", json!({"type": "object", "properties": {"action": {"type": "string"}}})),
1617 ("ctx_fill", "Budget-aware context fill — auto-selects compression per file within token limit.", json!({"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "budget": {"type": "integer"}}, "required": ["paths", "budget"]})),
1618 ("ctx_intent", "Intent detection — auto-reads relevant files based on task description.", json!({"type": "object", "properties": {"query": {"type": "string"}, "project_root": {"type": "string"}}, "required": ["query"]})),
1619 ("ctx_response", "Compress LLM response text (remove filler, apply TDD).", json!({"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]})),
1620 ("ctx_context", "Session context overview — cached files, seen files, session state.", json!({"type": "object", "properties": {}})),
1621 ("ctx_graph", "Code dependency graph. Actions: build (index project), related (find files connected to path), \
1622symbol (lookup definition/usages as file::name), impact (blast radius of changes to path), status (index stats).", json!({"type": "object", "properties": {"action": {"type": "string"}, "path": {"type": "string"}, "project_root": {"type": "string"}}, "required": ["action"]})),
1623 ("ctx_session", "Cross-session memory (CCP). Actions: load (restore previous session ~400 tok), \
1624save, status, task (set current task), finding (record discovery), decision (record choice), \
1625reset, list (show sessions), cleanup.", json!({"type": "object", "properties": {"action": {"type": "string"}, "value": {"type": "string"}, "session_id": {"type": "string"}}, "required": ["action"]})),
1626 ("ctx_knowledge", "Persistent project knowledge (survives sessions). Actions: remember (store fact with category+key+value), \
1627recall (search by query), pattern (record naming/structure pattern), consolidate (extract session findings into knowledge), \
1628status (list all), remove, export.", json!({"type": "object", "properties": {"action": {"type": "string"}, "category": {"type": "string"}, "key": {"type": "string"}, "value": {"type": "string"}, "query": {"type": "string"}}, "required": ["action"]})),
1629 ("ctx_agent", "Multi-agent coordination (shared message bus). Actions: register (join with agent_type+role), \
1630post (broadcast or direct message with category), read (poll messages), status (update state: active|idle|finished), \
1631list, info.", json!({"type": "object", "properties": {"action": {"type": "string"}, "agent_type": {"type": "string"}, "role": {"type": "string"}, "message": {"type": "string"}}, "required": ["action"]})),
1632 ("ctx_overview", "Task-relevant project map — use at session start.", json!({"type": "object", "properties": {"task": {"type": "string"}, "path": {"type": "string"}}})),
1633 ("ctx_wrapped", "Savings report card. Periods: week|month|all.", json!({"type": "object", "properties": {"period": {"type": "string"}}})),
1634 ("ctx_semantic_search", "BM25 code search by meaning. action=reindex to rebuild.", json!({"type": "object", "properties": {"query": {"type": "string"}, "path": {"type": "string"}, "top_k": {"type": "integer"}, "action": {"type": "string"}}, "required": ["query"]})),
1635 ]
1636}
1637
1638#[cfg(test)]
1639mod tests {
1640 use super::*;
1641
1642 #[test]
1643 fn test_should_use_unified_defaults_to_false() {
1644 assert!(!should_use_unified("cursor"));
1645 assert!(!should_use_unified("claude-code"));
1646 assert!(!should_use_unified("windsurf"));
1647 assert!(!should_use_unified(""));
1648 assert!(!should_use_unified("some-unknown-client"));
1649 }
1650
1651 #[test]
1652 fn test_unified_tool_count() {
1653 let tools = unified_tool_defs();
1654 assert_eq!(tools.len(), 5, "Expected 5 unified tools");
1655 }
1656}