lean_ctx/tools/registered/
ctx_fill.rs1use 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 {
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 Some(mut cache) =
81 crate::server::bounded_lock::write(cache_lock, "ctx_fill cache write")
82 else {
83 crate::core::io_health::record_freeze();
84 return Err(ErrorData::internal_error(
85 "cache busy (ctx_fill) — retry in a moment",
86 None,
87 ));
88 };
89 let output = crate::tools::ctx_fill::handle(
90 &mut cache,
91 &paths,
92 budget,
93 ctx.crp_mode,
94 task.as_deref(),
95 );
96 drop(cache);
97
98 Ok(ToolOutput {
99 text: output,
100 original_tokens: 0,
101 saved_tokens: 0,
102 mode: Some(format!("budget:{budget}")),
103 path: None,
104 changed: false,
105 shell_outcome: None,
106 content_blocks: None,
107 })
108 }
109 }
110}