Skip to main content

lean_ctx_server/tools/registered/
ctx_read_dispatch.rs

1// SPDX-License-Identifier: Apache-2.0
2//! MCP schema and dispatch for the single ctx_read implementation.
3
4use super::{
5    CtxReadTool, ErrorData, Map, McpTool, Tool, ToolContext, ToolOutput, Value, engine, get_str,
6    record_attribution_result, require_resolved_path,
7};
8
9impl McpTool for CtxReadTool {
10    fn name(&self) -> &'static str {
11        "ctx_read"
12    }
13
14    fn produces_machine_readable(&self, args: Option<&Map<String, Value>>) -> bool {
15        // The explicit Engine view is a byte-exact payload, even when it is text.
16        // So is a raw read (#1316): consumers compare it with the disk bytes,
17        // so no tip, nudge, footer or hint may ride on it, and it consumes no
18        // once-per-session slot. Security and final turn-budget enforcement
19        // still run in the pipeline.
20        crate::server::native_receipts::requested("ctx_read", args)
21            || args.is_some_and(raw_requested)
22    }
23
24    fn tool_def(&self) -> Tool {
25        super::schema::ctx_read_tool_def()
26    }
27
28    fn handle(
29        &self,
30        args: &Map<String, Value>,
31        ctx: &ToolContext,
32    ) -> Result<ToolOutput, ErrorData> {
33        let engine_interface_v1 = engine::interface_v1_requested(args)?;
34        engine::validate_v1_request_shape(args, engine_interface_v1)?;
35        // #509: ctx_read absorbs multi-file batch reads (supersedes ctx_multi_read).
36        // A non-empty `paths` array routes to the one shared batch implementation.
37        if args
38            .get("paths")
39            .and_then(|v| v.as_array())
40            .is_some_and(|a| !a.is_empty())
41        {
42            let result = super::super::ctx_read_batch::batch_read(args, ctx);
43            if let Ok(output) = &result {
44                record_attribution_result(ctx, "ctx_read batch".to_string(), output);
45            }
46            return result;
47        }
48
49        let path = if let Some(repo) = get_str(args, "repo") {
50            let root = lean_ctx::core::multi_repo::resolve_repo_root(&repo).ok_or_else(|| {
51                let known = lean_ctx::core::multi_repo::known_aliases().join(", ");
52                let known = if known.is_empty() {
53                    "none registered — use ctx_multi_repo add_root".to_string()
54                } else {
55                    known
56                };
57                ErrorData::invalid_params(
58                    format!("unknown repo alias: {repo} (known: {known})"),
59                    None,
60                )
61            })?;
62            let rel = get_str(args, "path").unwrap_or_else(|| ".".to_string());
63            lean_ctx::core::path_resolve::resolve_tool_path(Some(&root), None, &rel)
64                .map_err(|e| ErrorData::invalid_params(e, None))?
65        } else {
66            require_resolved_path(ctx, args, "path")?
67        };
68
69        // "File not found" is the most frequent read failure, and often the
70        // path is one mechanical slip from a real file (other case, wrong
71        // prefix). When exactly one file fits and the jail admits it, read it
72        // and say so instead of failing. Byte-exact reads (the engine view,
73        // `raw`) never substitute: their output must be the file and nothing else.
74        let byte_exact = engine_interface_v1 || raw_requested(args);
75        let (path, substituted) = match (!byte_exact)
76            .then(|| {
77                lean_ctx::core::path_suggest::unambiguous_match_in(
78                    std::path::Path::new(&path),
79                    std::path::Path::new(&ctx.project_root),
80                )
81            })
82            .flatten()
83            .and_then(|found| ctx.resolve_path_sync(&found.to_string_lossy()).ok())
84        {
85            Some(found) => (found, Some(path)),
86            None => (path, None),
87        };
88
89        let alias_args = super::window::apply_lines_alias(args);
90        let args = alias_args.as_ref().unwrap_or(args);
91
92        // `symbol=` narrows the read to one definition's lines; the content then
93        // flows through the ordinary `lines:`/`anchored:` path.
94        let symbol_args;
95        let mut symbol_note = None;
96        let args = match get_str(args, "symbol").filter(|s| !s.trim().is_empty()) {
97            None => args,
98            Some(symbol) => {
99                if byte_exact {
100                    return Err(ErrorData::invalid_params(
101                        "symbol= cannot combine with raw or engine_interface",
102                        None,
103                    ));
104                }
105                let (rewritten, note) = symbol_request(args, &path, &symbol)?;
106                symbol_args = rewritten;
107                symbol_note = note;
108                &symbol_args
109            }
110        };
111
112        let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
113            self.handle_inner(args, ctx, &path, engine_interface_v1)
114        })) {
115            Ok(result) => result,
116            Err(_) => Err(ErrorData::internal_error(
117                format!(
118                    "ctx_read panicked while processing '{path}'. This is a bug — please report it."
119                ),
120                None,
121            )),
122        };
123        // A trailing service line: the header stays the first line, as every
124        // reader of ctx_read output (and the Claude Code plugin) expects.
125        let result = result.map(|mut output| {
126            if let Some(requested) = &substituted {
127                output.text = format!(
128                    "{}\n[lean-ctx: {requested} does not exist — read {path} instead]",
129                    output.text.trim_end_matches('\n'),
130                );
131            }
132            if let Some(note) = &symbol_note {
133                output.text = format!("{}\n{note}", output.text.trim_end_matches('\n'));
134            }
135            output
136        });
137        if let Ok(output) = &result {
138            record_attribution_result(ctx, format!("ctx_read {path}"), output);
139        }
140        result
141    }
142
143    /// Single reads and batches share one implementation per file,
144    /// `handle_inner_prepared`, and that is where the lineage is settled:
145    ///
146    /// - the requested file is published on every path — fresh reads through
147    ///   `tools::ctx_read::read_file_*` (handler thread or
148    ///   `TaskSpine::spawn_thread` workers), and cache hits, `[unchanged]`
149    ///   stubs and deltas through `publish_requested_source`, bound to what
150    ///   is on disk now;
151    /// - whenever the reply carries content from anywhere else — graph
152    ///   neighbours, cross-source hints, rule files, proactively expanded
153    ///   content, the kernel supplement of a batch — the capture is marked
154    ///   incomplete there, so that reply's lineage is unknown;
155    /// - a source that cannot be bound (another repository via `repo`, an
156    ///   image, a path outside the root) marks it incomplete as well.
157    ///
158    /// So a captured set that is still complete at the end IS the whole set,
159    /// for every mode (the modes differ in rendering, not in what they read).
160    fn publishes_every_source(&self, _args: Option<&Map<String, Value>>) -> bool {
161        true
162    }
163}
164
165/// Rewrite a `symbol=` request into the window read that serves it. Under an
166/// active context policy the lookup is refused: resolving names before
167/// admission would answer "does this symbol exist" for a withheld file.
168fn symbol_request(
169    args: &Map<String, Value>,
170    path: &str,
171    symbol: &str,
172) -> Result<(Map<String, Value>, Option<String>), ErrorData> {
173    if lean_ctx::core::policy::runtime::is_active() {
174        return Err(ErrorData::invalid_params(
175            "symbol= is unavailable under an active context policy; use mode=\"lines:N-M\"",
176            None,
177        ));
178    }
179    let content = std::fs::read_to_string(path)
180        .map_err(|e| ErrorData::invalid_params(format!("cannot read {path}: {e}"), None))?;
181    let anchored = get_str(args, "mode").is_some_and(|m| m.starts_with("anchored"));
182    let (mode, note) = match super::symbol::resolve(&content, path, symbol, anchored)
183        .map_err(|e| ErrorData::invalid_params(e, None))?
184    {
185        super::symbol::SymbolRead::Window { mode, note } => (mode, note),
186        // A miss serves the lines that mention the name (or the one-line
187        // reference view when none does) through the ordinary read path, so
188        // admission, redaction and lineage stay the same as for any window.
189        super::symbol::SymbolRead::NotFound { note, hits } if hits.is_empty() => {
190            ("reference".to_string(), Some(note))
191        }
192        super::symbol::SymbolRead::NotFound { note, hits } => {
193            let lines: Vec<String> = hits.iter().map(usize::to_string).collect();
194            (format!("lines:{}", lines.join(",")), Some(note))
195        }
196    };
197    let mut rewritten = args.clone();
198    for key in ["symbol", "start_line", "offset", "limit"] {
199        rewritten.remove(key);
200    }
201    rewritten.insert("mode".into(), Value::String(mode));
202    Ok((rewritten, note))
203}
204
205/// `raw: true` or `mode: "raw"`: the caller asked for the file's bytes.
206fn raw_requested(args: &Map<String, Value>) -> bool {
207    get_str(args, "mode").as_deref() == Some("raw")
208        || args.get("raw").and_then(Value::as_bool) == Some(true)
209}