Skip to main content

lean_ctx/tools/registered/
ctx_delta.rs

1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{json, Map, Value};
4
5use crate::server::tool_trait::{require_resolved_path, McpTool, ToolContext, ToolOutput};
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 — sends only changed lines since last read.",
19            json!({
20                "type": "object",
21                "properties": {
22                    "path": { "type": "string", "description": "Absolute file path" }
23                },
24                "required": ["path"]
25            }),
26        )
27    }
28
29    fn handle(
30        &self,
31        args: &Map<String, Value>,
32        ctx: &ToolContext,
33    ) -> Result<ToolOutput, ErrorData> {
34        let path = require_resolved_path(ctx, args, "path")?;
35
36        tokio::task::block_in_place(|| {
37            let cache_lock = ctx
38                .cache
39                .as_ref()
40                .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
41            let mut cache = cache_lock.blocking_write();
42            let output = crate::tools::ctx_delta::handle(&mut cache, &path);
43            let original = cache.get(&path).map_or(0, |e| e.original_tokens);
44            let tokens = crate::core::tokens::count_tokens(&output);
45            drop(cache);
46
47            if let Some(session_lock) = ctx.session.as_ref() {
48                let mut session = session_lock.blocking_write();
49                session.mark_modified(&path);
50            }
51
52            let saved = original.saturating_sub(tokens);
53            Ok(ToolOutput {
54                text: output,
55                original_tokens: original,
56                saved_tokens: saved,
57                mode: Some("delta".to_string()),
58                path: Some(path),
59                changed: false,
60            })
61        })
62    }
63}