Skip to main content

lean_ctx/tools/registered/
ctx_fill.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6    McpTool, ToolContext, ToolOutput, get_str, get_str_array, get_usize,
7};
8use crate::tool_defs::tool_def;
9
10pub struct CtxFillTool;
11
12impl McpTool for CtxFillTool {
13    fn name(&self) -> &'static str {
14        "ctx_fill"
15    }
16
17    fn tool_def(&self) -> Tool {
18        tool_def(
19            "ctx_fill",
20            "Budget-aware context fill — compress N files to fit a token budget.\n\
21             WORKFLOW: pass paths[] + budget=N; task=\"...\" enables intent-driven pruning.\n\
22             ANTIPATTERN: does NOT decide which files to include — use ctx_plan for project-wide selection.\n\
23             Saves tokens vs per-file reads (for many files with a budget).",
24            json!({
25                "type": "object",
26                "properties": {
27                    "paths": {
28                        "type": "array",
29                        "items": { "type": "string" },
30                        "description": "File paths"
31                    },
32                    "budget": {
33                        "type": "integer",
34                        "description": "Max token budget"
35                    },
36                    "task": {
37                        "type": "string",
38                        "description": "Intent-driven pruning target"
39                    }
40                },
41                "required": ["paths", "budget"]
42            }),
43        )
44    }
45
46    fn handle(
47        &self,
48        args: &Map<String, Value>,
49        ctx: &ToolContext,
50    ) -> Result<ToolOutput, ErrorData> {
51        let raw_paths = get_str_array(args, "paths")
52            .ok_or_else(|| ErrorData::invalid_params("paths array is required", None))?;
53        let budget = get_usize(args, "budget")
54            .ok_or_else(|| ErrorData::invalid_params("budget is required (non-negative)", None))?;
55        let task = get_str(args, "task");
56
57        tokio::task::block_in_place(|| {
58            let session_lock = ctx
59                .session
60                .as_ref()
61                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
62            let cache_lock = ctx
63                .cache
64                .as_ref()
65                .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
66
67            let mut paths = Vec::with_capacity(raw_paths.len());
68            {
69                let session = session_lock.blocking_read();
70                for p in &raw_paths {
71                    match super::resolve_path_sync(&session, p) {
72                        Ok(resolved) => paths.push(resolved),
73                        Err(e) => {
74                            return Err(ErrorData::invalid_params(e, None));
75                        }
76                    }
77                }
78            }
79
80            let timeout_dur =
81                crate::core::io_health::adaptive_timeout(std::time::Duration::from_secs(10));
82            let Ok(mut cache) = tokio::runtime::Handle::current()
83                .block_on(tokio::time::timeout(timeout_dur, cache_lock.write()))
84            else {
85                crate::core::io_health::record_freeze();
86                return Err(ErrorData::internal_error(
87                    "cache busy (ctx_fill) — retry in a moment",
88                    None,
89                ));
90            };
91            let output = crate::tools::ctx_fill::handle(
92                &mut cache,
93                &paths,
94                budget,
95                ctx.crp_mode,
96                task.as_deref(),
97            );
98            drop(cache);
99
100            Ok(ToolOutput {
101                text: output,
102                original_tokens: 0,
103                saved_tokens: 0,
104                mode: Some(format!("budget:{budget}")),
105                path: None,
106                changed: false,
107                shell_outcome: None,
108            })
109        })
110    }
111}