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