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 — auto-selects compression per file within token limit.",
21            json!({
22                "type": "object",
23                "properties": {
24                    "paths": {
25                        "type": "array",
26                        "items": { "type": "string" },
27                        "description": "File paths to consider"
28                    },
29                    "budget": {
30                        "type": "integer",
31                        "description": "Maximum token budget to fill"
32                    },
33                    "task": {
34                        "type": "string",
35                        "description": "Optional task (short English preferred) for intent-driven pruning"
36                    }
37                },
38                "required": ["paths", "budget"]
39            }),
40        )
41    }
42
43    fn handle(
44        &self,
45        args: &Map<String, Value>,
46        ctx: &ToolContext,
47    ) -> Result<ToolOutput, ErrorData> {
48        let raw_paths = get_str_array(args, "paths")
49            .ok_or_else(|| ErrorData::invalid_params("paths array is required", None))?;
50        let budget = get_usize(args, "budget")
51            .ok_or_else(|| ErrorData::invalid_params("budget is required (non-negative)", None))?;
52        let task = get_str(args, "task");
53
54        tokio::task::block_in_place(|| {
55            let session_lock = ctx
56                .session
57                .as_ref()
58                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
59            let cache_lock = ctx
60                .cache
61                .as_ref()
62                .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
63
64            let mut paths = Vec::with_capacity(raw_paths.len());
65            {
66                let session = session_lock.blocking_read();
67                for p in &raw_paths {
68                    match super::resolve_path_sync(&session, p) {
69                        Ok(resolved) => paths.push(resolved),
70                        Err(e) => {
71                            return Err(ErrorData::invalid_params(e, None));
72                        }
73                    }
74                }
75            }
76
77            let timeout_dur =
78                crate::core::io_health::adaptive_timeout(std::time::Duration::from_secs(10));
79            let Ok(mut cache) = tokio::runtime::Handle::current()
80                .block_on(tokio::time::timeout(timeout_dur, cache_lock.write()))
81            else {
82                crate::core::io_health::record_freeze();
83                return Err(ErrorData::internal_error(
84                    "cache busy (ctx_fill) — retry in a moment",
85                    None,
86                ));
87            };
88            let output = crate::tools::ctx_fill::handle(
89                &mut cache,
90                &paths,
91                budget,
92                ctx.crp_mode,
93                task.as_deref(),
94            );
95            drop(cache);
96
97            Ok(ToolOutput {
98                text: output,
99                original_tokens: 0,
100                saved_tokens: 0,
101                mode: Some(format!("budget:{budget}")),
102                path: None,
103                changed: false,
104                shell_outcome: None,
105            })
106        })
107    }
108}