lean_ctx/server/
resources.rs1use rmcp::model::{Resource, ResourceContents};
2
3const URI_SUMMARY: &str = "lean-ctx://context/summary";
4const URI_PINNED: &str = "lean-ctx://context/pinned";
5const URI_PRESSURE: &str = "lean-ctx://context/pressure";
6const URI_PLAN: &str = "lean-ctx://context/plan";
7const URI_BOUNCE: &str = "lean-ctx://context/bounce";
8
9pub fn list_resources() -> Vec<Resource> {
10 vec![
11 make_resource(
12 URI_SUMMARY,
13 "Context Summary",
14 "Ledger compact: items, pressure, budget",
15 ),
16 make_resource(
17 URI_PINNED,
18 "Pinned Items",
19 "Pinned context items with compressed content",
20 ),
21 make_resource(
22 URI_PRESSURE,
23 "Context Pressure",
24 "Budget utilization and recommendations",
25 ),
26 make_resource(
27 URI_PLAN,
28 "Context Plan",
29 "Current context plan with modes per file",
30 ),
31 make_resource(
32 URI_BOUNCE,
33 "Bounce Stats",
34 "Bounce detection statistics and wasted tokens",
35 ),
36 ]
37}
38
39pub(super) fn text_resource(text: &str, uri: &str) -> ResourceContents {
40 ResourceContents::text(crate::server::policy_guard::redact_model_text(text), uri)
41}
42
43pub fn read_resource(
44 uri: &str,
45 ledger: &crate::core::context_ledger::ContextLedger,
46) -> Option<Vec<ResourceContents>> {
47 match uri {
48 URI_SUMMARY => Some(vec![text_resource(&build_summary(ledger), uri)]),
49 URI_PRESSURE => Some(vec![text_resource(&build_pressure(ledger), uri)]),
50 URI_PLAN => Some(vec![text_resource(&build_plan(ledger), uri)]),
51 URI_PINNED => Some(vec![text_resource(&build_pinned(ledger), uri)]),
52 URI_BOUNCE => Some(vec![text_resource(&build_bounce(), uri)]),
53 _ => None,
54 }
55}
56
57pub fn unknown_resource_message(uri: &str) -> String {
63 let looks_like_file = uri.starts_with("file:")
64 || uri.starts_with('/')
65 || (uri.len() > 2 && uri.as_bytes()[1] == b':' && uri.as_bytes()[0].is_ascii_alphabetic())
66 || uri.contains("/.claude/projects/")
67 || uri.contains("\\memory\\")
68 || uri.contains("/memory/");
69
70 if looks_like_file {
71 format!(
72 "Unknown resource: {uri}. File not readable — it may not exist, \
73 be outside the project root, or be too large (>2 MiB). \
74 For project files use ctx_read / ctx_patch. \
75 For Claude auto memory (~/.claude/projects/<slug>/memory/) use native Read/Edit."
76 )
77 } else {
78 format!("Unknown resource: {uri}")
79 }
80}
81
82fn make_resource(uri: &str, name: &str, desc: &str) -> Resource {
83 Resource::new(uri, name)
84 .with_description(desc)
85 .with_mime_type("text/plain")
86}
87
88fn build_summary(ledger: &crate::core::context_ledger::ContextLedger) -> String {
89 let pressure = ledger.pressure();
90 let adjusted = ledger.adjusted_total_saved();
91 format!(
92 "files:{} | sent:{} | saved:{} (adj:{}) | pressure:{:.0}% | action:{:?}",
93 ledger.entries.len(),
94 ledger.total_tokens_sent,
95 ledger.total_tokens_saved,
96 adjusted,
97 pressure.utilization * 100.0,
98 pressure.recommendation,
99 )
100}
101
102fn build_pressure(ledger: &crate::core::context_ledger::ContextLedger) -> String {
103 let p = ledger.pressure();
104 let mut lines = vec![
105 format!("utilization: {:.1}%", p.utilization * 100.0),
106 format!("remaining: {} tokens", p.remaining_tokens),
107 format!("entries: {}", p.entries_count),
108 format!("action: {:?}", p.recommendation),
109 ];
110
111 if p.utilization > 0.8 {
112 let evict = ledger.eviction_candidates_by_phi(3);
113 if !evict.is_empty() {
114 let names: Vec<_> = evict
115 .iter()
116 .take(5)
117 .map(|p| crate::core::protocol::shorten_path(p))
118 .collect();
119 lines.push(format!("eviction_candidates: {}", names.join(", ")));
120 }
121 }
122
123 lines.join("\n")
124}
125
126fn build_plan(ledger: &crate::core::context_ledger::ContextLedger) -> String {
127 let mut lines = Vec::new();
128 for entry in &ledger.entries {
129 let short = crate::core::protocol::shorten_path(&entry.path);
130 let phi_str = entry.phi.map_or("?".to_string(), |p| format!("{p:.2}"));
131 let state_str = entry.state.as_ref().map_or("?", |s| match s {
132 crate::core::context_field::ContextState::Included => "incl",
133 crate::core::context_field::ContextState::Pinned => "pin",
134 crate::core::context_field::ContextState::Excluded => "excl",
135 crate::core::context_field::ContextState::Candidate => "cand",
136 crate::core::context_field::ContextState::Stale => "stale",
137 crate::core::context_field::ContextState::Shadowed => "shadow",
138 });
139 lines.push(format!(
140 "{short} mode={} tok={} phi={phi_str} state={state_str}",
141 entry.mode, entry.sent_tokens,
142 ));
143 }
144 if lines.is_empty() {
145 "No context items tracked yet.".to_string()
146 } else {
147 lines.join("\n")
148 }
149}
150
151fn build_pinned(ledger: &crate::core::context_ledger::ContextLedger) -> String {
152 let pinned: Vec<_> = ledger
153 .entries
154 .iter()
155 .filter(|e| e.state == Some(crate::core::context_field::ContextState::Pinned))
156 .collect();
157 if pinned.is_empty() {
158 return "No pinned items.".to_string();
159 }
160 let mut lines = Vec::new();
161 for entry in pinned {
162 let short = crate::core::protocol::shorten_path(&entry.path);
163 lines.push(format!(
164 "{short} mode={} tok={}",
165 entry.mode, entry.sent_tokens
166 ));
167 }
168 lines.join("\n")
169}
170
171fn build_bounce() -> String {
172 match crate::core::bounce_tracker::global().lock() {
173 Ok(bt) => bt.format_summary(),
174 _ => "Bounce tracker unavailable.".to_string(),
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 #[test]
183 fn list_returns_five_resources() {
184 let resources = list_resources();
185 assert_eq!(resources.len(), 5);
186 }
187
188 #[test]
189 fn read_summary_returns_content() {
190 let ledger = crate::core::context_ledger::ContextLedger::new();
191 let result = read_resource(URI_SUMMARY, &ledger);
192 assert!(result.is_some());
193 }
194
195 #[test]
196 fn read_unknown_uri_returns_none() {
197 let ledger = crate::core::context_ledger::ContextLedger::new();
198 let result = read_resource("lean-ctx://unknown", &ledger);
199 assert!(result.is_none());
200 }
201
202 #[test]
203 fn read_pressure_returns_content() {
204 let ledger = crate::core::context_ledger::ContextLedger::new();
205 let result = read_resource(URI_PRESSURE, &ledger);
206 assert!(result.is_some());
207 }
208
209 #[test]
210 fn read_bounce_returns_content() {
211 let ledger = crate::core::context_ledger::ContextLedger::new();
212 let result = read_resource(URI_BOUNCE, &ledger);
213 assert!(result.is_some());
214 }
215
216 #[test]
217 fn unknown_file_uri_message_guides_to_ctx_read_and_native_memory() {
218 let msg = unknown_resource_message(
219 "file:///home/jules/.claude/projects/-home-jules-Projects-blockposters/memory/MEMORY.md",
220 );
221 assert!(msg.contains("ctx_read"), "{msg}");
222 assert!(msg.contains("native Read/Edit"), "{msg}");
223 assert!(msg.contains("auto memory"), "{msg}");
224 }
225
226 #[test]
227 fn unknown_lean_ctx_uri_stays_short() {
228 let msg = unknown_resource_message("lean-ctx://unknown");
229 assert_eq!(msg, "Unknown resource: lean-ctx://unknown");
230 }
231}