lean_ctx/tools/registered/
ctx_prefetch.rs1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6 McpTool, ToolContext, ToolOutput, get_int, get_str, get_str_array,
7};
8use crate::tool_defs::tool_def;
9
10pub struct CtxPrefetchTool;
11
12impl McpTool for CtxPrefetchTool {
13 fn name(&self) -> &'static str {
14 "ctx_prefetch"
15 }
16
17 fn tool_def(&self) -> Tool {
18 tool_def(
19 "ctx_prefetch",
20 "WORKFLOW: call BEFORE context-heavy operations to minimize latency.\n\
21 ANTIPATTERN: NOT for normal reads — only for proactive cache warming.\n\
22 Prewarms cache for blast radius files via graph + task signals.\n\
23 task=description; changed_files=paths for blast radius;\n\
24 budget_tokens=soft budget (default 3000); max_files=limit (default 10).\n\
25 Saves latency (not tokens): preloads files before needed.",
26 json!({
27 "type": "object",
28 "properties": {
29 "root": { "type": "string", "description": "Project root directory" },
30 "task": { "type": "string", "description": "Task description for relevance scoring" },
31 "changed_files": { "type": "array", "items": { "type": "string" }, "description": "Changed file paths for computing blast radius" },
32 "budget_tokens": { "type": "integer", "description": "Soft token budget (default: 3000)" },
33 "max_files": { "type": "integer", "description": "Max files to prefetch (default: 10)" }
34 }
35 }),
36 )
37 }
38
39 fn handle(
40 &self,
41 args: &Map<String, Value>,
42 ctx: &ToolContext,
43 ) -> Result<ToolOutput, ErrorData> {
44 let root = if get_str(args, "root").is_some() {
45 if let Some(p) = ctx.resolved_path("root") {
46 p.to_string()
47 } else if let Some(err) = ctx.path_error("root") {
48 return Err(ErrorData::invalid_params(format!("root: {err}"), None));
49 } else {
50 ctx.project_root.clone()
51 }
52 } else if let Some(ref session) = ctx.session {
53 let guard = tokio::task::block_in_place(|| session.blocking_read());
54 guard
55 .project_root
56 .clone()
57 .unwrap_or_else(|| ".".to_string())
58 } else {
59 ".".to_string()
60 };
61
62 let task = get_str(args, "task");
63 let changed_files = get_str_array(args, "changed_files");
64 let budget_tokens = get_int(args, "budget_tokens").map_or(3000, |n| n.max(0) as usize);
65 let max_files = get_int(args, "max_files").map(|n| n.max(1) as usize);
66
67 let resolved_changed: Option<Vec<String>> = changed_files.map(|files| {
68 files
69 .iter()
70 .map(|p| ctx.resolve_path_sync(p).unwrap_or_else(|_| p.clone()))
71 .collect()
72 });
73
74 let cache = ctx
75 .cache
76 .as_ref()
77 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
78 let Some(mut guard) = crate::server::bounded_lock::write(cache, "ctx_prefetch") else {
79 return Ok(ToolOutput::simple(
80 "[prefetch skipped — cache busy, retry in a moment]".to_string(),
81 ));
82 };
83 let result = crate::tools::ctx_prefetch::handle(
84 &mut guard,
85 &root,
86 task.as_deref(),
87 resolved_changed.as_deref(),
88 budget_tokens,
89 max_files,
90 ctx.crp_mode,
91 );
92
93 Ok(ToolOutput {
94 text: result,
95 original_tokens: 0,
96 saved_tokens: 0,
97 mode: Some("prefetch".to_string()),
98 path: None,
99 changed: false,
100 shell_outcome: None,
101 content_blocks: None,
102 })
103 }
104}