Skip to main content

lean_ctx_server/tools/registered/
ctx_prefetch.rs

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