Skip to main content

lean_ctx/tools/registered/
ctx_cache.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_str, require_resolved_path};
6use crate::tool_defs::tool_def;
7
8pub struct CtxCacheTool;
9
10impl McpTool for CtxCacheTool {
11    fn name(&self) -> &'static str {
12        "ctx_cache"
13    }
14
15    fn tool_def(&self) -> Tool {
16        tool_def(
17            "ctx_cache",
18            "Cache operations — inspect, clear, or invalidate the read cache.\n\
19            Actions: status lists cached files; clear empties all (recover token budget);\n\
20            invalidate path=... refreshes a single entry.\n\
21            Use to diagnose stale content or recover budget after large reads.\n\
22            ANTIPATTERN: does NOT affect disk files — only cached read content.",
23            json!({
24                "type": "object",
25                "properties": {
26                    "action": {
27                        "type": "string",
28                        "enum": ["status", "clear", "invalidate"],
29                        "description": "status|clear|invalidate"
30                    },
31                    "path": {
32                        "type": "string",
33                        "description": "File path for invalidate action (only used with action=invalidate)"
34                    }
35                },
36                "required": ["action"]
37            }),
38        )
39    }
40
41    fn handle(
42        &self,
43        args: &Map<String, Value>,
44        ctx: &ToolContext,
45    ) -> Result<ToolOutput, ErrorData> {
46        let action = get_str(args, "action")
47            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
48
49        let invalidate_path = if action == "invalidate" {
50            Some(require_resolved_path(ctx, args, "path")?)
51        } else {
52            None
53        };
54
55        let cache = ctx
56            .cache
57            .as_ref()
58            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
59        let Some(mut guard) = crate::server::bounded_lock::write(cache, "ctx_cache") else {
60            return Ok(ToolOutput::simple(
61                "[cache lock temporarily unavailable — retry in a moment]".to_string(),
62            ));
63        };
64
65        let result = match action.as_str() {
66            "status" => {
67                let entries = guard.get_all_entries();
68                let mut lines = if entries.is_empty() {
69                    vec!["Cache empty — no files tracked.".to_string()]
70                } else {
71                    let mut lines = vec![format!("Cache: {} file(s)", entries.len())];
72                    for (path, entry) in &entries {
73                        let fref = guard
74                            .file_ref_map()
75                            .get(*path)
76                            .map_or("F?", std::string::String::as_str);
77                        lines.push(format!(
78                            "  {fref}={} [{}L, {}t, read {}x]",
79                            crate::core::protocol::shorten_path(path),
80                            entry.line_count,
81                            entry.original_tokens,
82                            entry.read_count()
83                        ));
84                    }
85                    lines
86                };
87                // Re-delivery telemetry: forced full re-sends grouped by cause
88                // (diagnostic only — never enters a cacheable body, #498).
89                let t = crate::core::cache_telemetry::snapshot();
90                if t.total() > 0 {
91                    lines.push(format!(
92                        "re-deliveries forced: compaction={} idle={} eviction={} conversation={} (total {})",
93                        t.compaction, t.idle, t.eviction, t.conversation, t.total()
94                    ));
95                }
96                lines.join("\n")
97            }
98            "clear" => {
99                let count = guard.clear();
100                format!(
101                    "Cache cleared — {count} file(s) removed. Next ctx_read will return full content."
102                )
103            }
104            "invalidate" => {
105                let Some(path) = invalidate_path else {
106                    return Ok(ToolOutput::simple(
107                        "Missing path for invalidate action.".to_string(),
108                    ));
109                };
110                if guard.invalidate(&path) {
111                    format!(
112                        "Invalidated cache for {}. Next ctx_read will return full content.",
113                        crate::core::protocol::shorten_path(&path)
114                    )
115                } else {
116                    format!(
117                        "{} was not in cache.",
118                        crate::core::protocol::shorten_path(&path)
119                    )
120                }
121            }
122            _ => "Unknown action. Use: status, clear, invalidate".to_string(),
123        };
124
125        Ok(ToolOutput {
126            text: result,
127            original_tokens: 0,
128            saved_tokens: 0,
129            mode: Some(action),
130            path: None,
131            changed: false,
132            shell_outcome: None,
133        })
134    }
135}