lean_ctx/tools/registered/
ctx_prefetch.rs1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{json, Map, Value};
4
5use crate::server::tool_trait::{
6 get_int, get_str, get_str_array, McpTool, ToolContext, ToolOutput,
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 "Predictive prefetch — prewarm cache for blast radius files (graph + task signals) within budgets.",
21 json!({
22 "type": "object",
23 "properties": {
24 "root": { "type": "string", "description": "Project root (default: .)" },
25 "task": { "type": "string", "description": "Optional task for relevance scoring" },
26 "changed_files": { "type": "array", "items": { "type": "string" }, "description": "Optional changed files (paths) to compute blast radius" },
27 "budget_tokens": { "type": "integer", "description": "Soft budget hint for mode selection (default: 3000)" },
28 "max_files": { "type": "integer", "description": "Max files to prefetch (default: 10)" }
29 }
30 }),
31 )
32 }
33
34 fn handle(
35 &self,
36 args: &Map<String, Value>,
37 ctx: &ToolContext,
38 ) -> Result<ToolOutput, ErrorData> {
39 let root = if get_str(args, "root").is_some() {
40 if let Some(p) = ctx.resolved_path("root") {
41 p.to_string()
42 } else if let Some(err) = ctx.path_error("root") {
43 return Err(ErrorData::invalid_params(format!("root: {err}"), None));
44 } else {
45 ctx.project_root.clone()
46 }
47 } else if let Some(ref session) = ctx.session {
48 let guard = tokio::task::block_in_place(|| session.blocking_read());
49 guard
50 .project_root
51 .clone()
52 .unwrap_or_else(|| ".".to_string())
53 } else {
54 ".".to_string()
55 };
56
57 let task = get_str(args, "task");
58 let changed_files = get_str_array(args, "changed_files");
59 let budget_tokens = get_int(args, "budget_tokens").map_or(3000, |n| n.max(0) as usize);
60 let max_files = get_int(args, "max_files").map(|n| n.max(1) as usize);
61
62 let resolved_changed: Option<Vec<String>> = changed_files.map(|files| {
63 files
64 .iter()
65 .map(|p| ctx.resolve_path_sync(p).unwrap_or_else(|_| p.clone()))
66 .collect()
67 });
68
69 let cache = ctx.cache.as_ref().unwrap();
70 let mut guard = tokio::task::block_in_place(|| cache.blocking_write());
71 let result = crate::tools::ctx_prefetch::handle(
72 &mut guard,
73 &root,
74 task.as_deref(),
75 resolved_changed.as_deref(),
76 budget_tokens,
77 max_files,
78 ctx.crp_mode,
79 );
80
81 Ok(ToolOutput {
82 text: result,
83 original_tokens: 0,
84 saved_tokens: 0,
85 mode: Some("prefetch".to_string()),
86 path: None,
87 changed: false,
88 })
89 }
90}