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 {
41 let cache_lock = ctx
42 .cache
43 .as_ref()
44 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
45 let Some(mut cache) =
46 crate::server::bounded_lock::write(cache_lock, "ctx_delta cache write")
47 else {
48 crate::core::io_health::record_freeze();
49 return Err(ErrorData::internal_error(
50 "cache busy (ctx_delta) — retry in a moment",
51 None,
52 ));
53 };
54 let output = crate::tools::ctx_delta::handle(&mut cache, &path);
55 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
56 let tokens = crate::core::tokens::count_tokens(&output);
57 drop(cache);
58
59 if let Some(session_lock) = ctx.session.as_ref() {
60 let mut session = session_lock.blocking_write();
61 session.mark_modified(&path);
62 }
63
64 let saved = original.saturating_sub(tokens);
65 Ok(ToolOutput {
66 text: output,
67 original_tokens: original,
68 saved_tokens: saved,
69 mode: Some("delta".to_string()),
70 path: Some(path),
71 changed: false,
72 shell_outcome: None,
73 content_blocks: None,
74 })
75 }
76 }
77}