Skip to main content

lean_ctx_server/tools/registered/
ctx_preload.rs

1// SPDX-License-Identifier: Apache-2.0
2use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_str};
7use lean_ctx::tool_defs::tool_def;
8
9pub struct CtxPreloadTool;
10
11impl McpTool for CtxPreloadTool {
12    fn name(&self) -> &'static str {
13        "ctx_preload"
14    }
15
16    fn tool_def(&self) -> Tool {
17        tool_def(
18            "ctx_preload",
19            "Caches task-relevant files, returns L-curve-optimized summary.\n\
20             WORKFLOW: call at session start or when switching tasks, before ctx_read.\n\
21             ANTIPATTERN: not for reading individual files — use ctx_read instead.\n\
22             ~50-100 tokens vs ~5000 for individual reads (~50x savings).",
23            json!({
24                "type": "object",
25                "properties": {
26                    "task": {
27                        "type": "string",
28                        "description": "Task description (short English)"
29                    },
30                    "path": {
31                        "type": "string",
32                        "description": "Project root"
33                    }
34                },
35                "required": ["task"]
36            }),
37        )
38    }
39
40    fn handle(
41        &self,
42        args: &Map<String, Value>,
43        ctx: &ToolContext,
44    ) -> Result<ToolOutput, ErrorData> {
45        let task = get_str(args, "task").unwrap_or_default();
46
47        let resolved_path = if get_str(args, "path").is_some() {
48            if let Some(p) = ctx.resolved_path("path") {
49                Some(p.to_string())
50            } else if let Some(err) = ctx.path_error("path") {
51                return Err(ErrorData::invalid_params(format!("path: {err}"), None));
52            } else {
53                None
54            }
55        } else if let Some(ref session) = ctx.session {
56            let guard = crate::server::bounded_lock::read(session, "ctx_preload:session_root");
57            guard.as_ref().and_then(|g| g.project_root.clone())
58        } else {
59            None
60        };
61
62        // Never let `handle` fall back to "." (the daemon CWD, which is not the
63        // project): resolve against the dispatch-provided root so graph-relative
64        // preload candidates (e.g. `rust/src/core/foo.rs`) jail against the real
65        // project root in every IDE, even when no explicit `path` was passed.
66        let resolved_path = resolved_path.or_else(|| {
67            let root = ctx.project_root.trim();
68            (!root.is_empty()).then(|| root.to_string())
69        });
70
71        let cache = ctx
72            .cache
73            .as_ref()
74            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
75        let Some(mut cache_guard) = crate::server::bounded_lock::write(cache, "ctx_preload:cache")
76        else {
77            return Ok(ToolOutput::simple(
78                "[preload skipped — cache temporarily unavailable]".to_string(),
79            ));
80        };
81        let (mut result, _usable) = crate::tools::ctx_preload::handle(
82            &mut cache_guard,
83            &task,
84            resolved_path.as_deref(),
85            ctx.crp_mode,
86        );
87
88        let provider_hints = predict_and_prefetch(&task, &mut cache_guard, &ctx.project_root);
89        if !provider_hints.is_empty() {
90            result.push_str(&provider_hints);
91        }
92
93        drop(cache_guard);
94
95        if let Some(ref session_lock) = ctx.session {
96            if let Some(mut session_guard) =
97                crate::server::bounded_lock::write(session_lock, "ctx_preload:session_write")
98                && (session_guard.active_structured_intent.is_none()
99                    || session_guard
100                        .active_structured_intent
101                        .as_ref()
102                        .is_none_or(|i| i.confidence < 0.6))
103            {
104                session_guard.set_task(&task, Some("preload"));
105            }
106
107            if let Some(session_guard) =
108                crate::server::bounded_lock::read(session_lock, "ctx_preload:session_read")
109                && let Some(ref intent) = session_guard.active_structured_intent
110                && let Some(ref ledger_lock) = ctx.ledger
111            {
112                let Some(ledger) =
113                    crate::server::bounded_lock::read(ledger_lock, "ctx_preload:ledger")
114                else {
115                    return Ok(ToolOutput::simple(result));
116                };
117                if !ledger.entries.is_empty() {
118                    let known: Vec<String> = session_guard
119                        .files_touched
120                        .iter()
121                        .map(|f| f.path.clone())
122                        .collect();
123                    let deficit = lean_ctx_ext::core::context_deficit::detect_deficit(
124                        &ledger, intent, &known,
125                    );
126                    if !deficit.suggested_files.is_empty() {
127                        result.push_str("\n\n--- SUGGESTED FILES ---");
128                        for s in &deficit.suggested_files {
129                            result.push_str(&format!(
130                                "\n  {} ({:?}, ~{} tok, mode: {})",
131                                s.path, s.reason, s.estimated_tokens, s.recommended_mode
132                            ));
133                        }
134                    }
135
136                    let pressure = ledger.pressure();
137                    if pressure.utilization > 0.7 {
138                        let plan = ledger.reinjection_plan(intent, 0.6);
139                        if !plan.actions.is_empty() {
140                            result.push_str("\n\n--- REINJECTION PLAN ---");
141                            result.push_str(&format!(
142                                "\n  Context pressure: {:.0}% -> target: 60%",
143                                pressure.utilization * 100.0
144                            ));
145                            for a in &plan.actions {
146                                result.push_str(&format!(
147                                    "\n  {} : {} -> {} (frees ~{} tokens)",
148                                    a.path, a.current_mode, a.new_mode, a.tokens_freed
149                                ));
150                            }
151                            result.push_str(&format!(
152                                "\n  Total freeable: {} tokens",
153                                plan.total_tokens_freed
154                            ));
155                        }
156                    }
157                }
158            }
159        }
160
161        Ok(ToolOutput {
162            text: result,
163            original_tokens: 0,
164            saved_tokens: 0,
165            mode: Some("preload".to_string()),
166            path: None,
167            changed: false,
168            shell_outcome: None,
169            content_blocks: None,
170        })
171    }
172}
173
174/// Use Active Inference to predict useful provider data and prefetch it.
175/// Stores results in session cache (synchronous) and triggers deep
176/// indexing (BM25, Graph, Knowledge) in a background thread when
177/// `providers.auto_index` is enabled.
178fn predict_and_prefetch(
179    task: &str,
180    cache: &mut lean_ctx::core::cache::SessionCache,
181    project_root: &str,
182) -> String {
183    // GHSA-jhf9-3pv4-m469: prefetch is provider egress without a model tool
184    // call, so it must honour the same gate as an explicit `ctx_provider`.
185    let policy = lean_ctx::core::policy::runtime::active();
186    if !provider_prefetch_permitted(policy.as_deref())
187        || !lean_ctx::core::roles::active_role().is_tool_allowed("ctx_provider")
188    {
189        return String::new();
190    }
191    lean_ctx::core::providers::init::init_with_project_root(Some(std::path::Path::new(
192        project_root,
193    )));
194    let registry = lean_ctx::core::providers::registry::global_registry();
195    let available = registry.available_provider_ids();
196    if available.is_empty() {
197        return String::new();
198    }
199
200    let mut bandit = lean_ctx::core::provider_bandit::ProviderBandit::load(project_root);
201    let predictions =
202        lean_ctx::core::active_inference::predict_preloads(task, &available, &mut bandit, 2);
203
204    if predictions.is_empty() {
205        return String::new();
206    }
207    let task_type = lean_ctx::core::active_inference::infer_task_type(&task.to_lowercase());
208
209    let cfg = lean_ctx::core::config::Config::load();
210    let auto_index = cfg.providers.auto_index;
211    let mut all_artifacts = Vec::new();
212
213    let mut out = String::from("\n\n--- PROVIDER PRELOAD ---");
214    let mut prefetched = 0usize;
215
216    for pred in &predictions {
217        let params = lean_ctx::core::providers::provider_trait::ProviderParams {
218            limit: Some(5),
219            ..Default::default()
220        };
221
222        match registry.execute_as_chunks(&pred.provider_id, &pred.action, &params) {
223            Ok(chunks) => {
224                // Active-inference feedback: a provider that actually returned
225                // context for this task type is a positive prediction error.
226                bandit.update(&task_type, &pred.provider_id, !chunks.is_empty());
227                let artifacts = lean_ctx::core::consolidation::consolidate(&chunks);
228                for entry in &artifacts.cache_entries {
229                    cache.store(&entry.uri, &entry.content);
230                    prefetched += 1;
231                }
232                if auto_index && !artifacts.is_empty() {
233                    all_artifacts.push(artifacts);
234                }
235                out.push_str(&format!(
236                    "\n  {} {} → {} items cached (confidence: {:.0}%)",
237                    pred.provider_id,
238                    pred.action,
239                    chunks.len(),
240                    pred.confidence * 100.0,
241                ));
242            }
243            Err(e) => {
244                // A failed/empty provider is a negative prediction error — learn
245                // not to bet on it for this task type next time.
246                bandit.update(&task_type, &pred.provider_id, false);
247                tracing::debug!(
248                    "[preload] provider {}/{} failed: {e}",
249                    pred.provider_id,
250                    pred.action,
251                );
252            }
253        }
254    }
255
256    // Persist the learning even when nothing prefetched — negative outcomes are
257    // exactly what we want the bandit to remember.
258    let _ = bandit.save(project_root);
259
260    if prefetched == 0 {
261        return String::new();
262    }
263
264    if !all_artifacts.is_empty() {
265        let root = project_root.to_string();
266        std::thread::spawn(move || {
267            let merged = merge_preload_artifacts(&all_artifacts);
268            crate::tools::ctx_provider::apply_artifacts_to_stores(&merged, &root);
269        });
270    }
271
272    out
273}
274
275/// Provider prefetch is allowed only when the active policy pack (if any)
276/// permits `ctx_provider`.
277fn provider_prefetch_permitted(
278    active: Option<&lean_ctx::core::policy::runtime::ActivePolicy>,
279) -> bool {
280    active.is_none_or(|policy| policy.tool_allowed("ctx_provider"))
281}
282
283fn merge_preload_artifacts(
284    all: &[lean_ctx::core::consolidation::ConsolidationArtifacts],
285) -> lean_ctx::core::consolidation::ConsolidationArtifacts {
286    let mut merged = lean_ctx::core::consolidation::ConsolidationArtifacts::default();
287    for a in all {
288        merged.bm25_chunks.extend(a.bm25_chunks.clone());
289        merged.edges.extend(a.edges.clone());
290        merged.facts.extend(a.facts.clone());
291        merged.cache_entries.extend(a.cache_entries.clone());
292    }
293    merged
294}
295
296#[cfg(test)]
297mod prefetch_policy_tests {
298    use super::provider_prefetch_permitted;
299    use lean_ctx::core::policy::runtime::ActivePolicy;
300
301    fn builtin(name: &str) -> ActivePolicy {
302        let pack = lean_ctx::core::policy::builtin::get(name).expect("built-in pack");
303        ActivePolicy::from_resolved(lean_ctx::core::policy::resolve(&pack).expect("resolves"))
304    }
305
306    /// A user-authored pack denying `deny` (the regulated packs ship with the
307    /// paid intelligence packs on this line).
308    fn denying(deny: &str) -> ActivePolicy {
309        let pack = lean_ctx::core::policy::parse(&format!(
310            "name = \"no-egress-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
311             extends = \"baseline\"\n\n[context]\ndeny_tools = [{deny}]\n"
312        ))
313        .expect("parses");
314        ActivePolicy::from_resolved(lean_ctx::core::policy::resolve(&pack).expect("resolves"))
315    }
316
317    /// GHSA-jhf9-3pv4-m469: packs that say "no web fetches" stop the
318    /// implicit provider prefetch, permissive packs keep it.
319    #[test]
320    fn no_egress_packs_block_provider_prefetch() {
321        assert!(provider_prefetch_permitted(None));
322        let no_egress = denying(r#""ctx_url_read", "ctx_provider", "ctx_tools""#);
323        assert!(
324            !provider_prefetch_permitted(Some(&no_egress)),
325            "a no-egress pack must block provider prefetch"
326        );
327        assert!(provider_prefetch_permitted(Some(&denying(
328            r#""ctx_url_read""#
329        ))));
330        assert!(provider_prefetch_permitted(Some(&builtin("baseline"))));
331    }
332}