lean_ctx/tools/registered/
ctx_delta.rs1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, require_resolved_path};
6use crate::tool_defs::tool_def;
7
8pub struct CtxDeltaTool;
9
10impl McpTool for CtxDeltaTool {
11 fn name(&self) -> &'static str {
12 "ctx_delta"
13 }
14
15 fn tool_def(&self) -> Tool {
16 tool_def(
17 "ctx_delta",
18 "Incremental diff since last read — shows only changed lines after you edit.\n\
19 WORKFLOW: ctx_read(mode=full) -> edit -> ctx_delta (no re-read needed).\n\
20 Use INSTEAD of re-reading the whole file after modifications — saves 90%+ tokens\n\
21 on unchanged content. Path must have a prior ctx_read in this session\'s cache.\n\
22 For the full git diff against HEAD, use ctx_read(path, mode=diff) instead.",
23 json!({
24 "type": "object",
25 "properties": {
26 "path": { "type": "string", "description": "File path" }
27 },
28 "required": ["path"]
29 }),
30 )
31 }
32
33 fn handle(
34 &self,
35 args: &Map<String, Value>,
36 ctx: &ToolContext,
37 ) -> Result<ToolOutput, ErrorData> {
38 let path = require_resolved_path(ctx, args, "path")?;
39
40 tokio::task::block_in_place(|| {
41 let cache_lock = ctx
42 .cache
43 .as_ref()
44 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
45 let timeout_dur =
46 crate::core::io_health::adaptive_timeout(std::time::Duration::from_secs(10));
47 let Ok(mut cache) = tokio::runtime::Handle::current()
48 .block_on(tokio::time::timeout(timeout_dur, cache_lock.write()))
49 else {
50 crate::core::io_health::record_freeze();
51 return Err(ErrorData::internal_error(
52 "cache busy (ctx_delta) — retry in a moment",
53 None,
54 ));
55 };
56 let output = crate::tools::ctx_delta::handle(&mut cache, &path);
57 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
58 let tokens = crate::core::tokens::count_tokens(&output);
59 drop(cache);
60
61 if let Some(session_lock) = ctx.session.as_ref() {
62 let mut session = session_lock.blocking_write();
63 session.mark_modified(&path);
64 }
65
66 let saved = original.saturating_sub(tokens);
67 Ok(ToolOutput {
68 text: output,
69 original_tokens: original,
70 saved_tokens: saved,
71 mode: Some("delta".to_string()),
72 path: Some(path),
73 changed: false,
74 shell_outcome: None,
75 content_blocks: None,
76 })
77 })
78 }
79}