Skip to main content

lean_ctx/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        // Security and final turn-budget enforcement still run in the pipeline.
17        crate::server::native_receipts::requested("ctx_read", args)
18    }
19
20    fn tool_def(&self) -> Tool {
21        super::schema::ctx_read_tool_def()
22    }
23
24    fn handle(
25        &self,
26        args: &Map<String, Value>,
27        ctx: &ToolContext,
28    ) -> Result<ToolOutput, ErrorData> {
29        let engine_interface_v1 = engine::interface_v1_requested(args)?;
30        engine::validate_v1_request_shape(args, engine_interface_v1)?;
31        // #509: ctx_read absorbs multi-file batch reads (supersedes ctx_multi_read).
32        // A non-empty `paths` array routes to the one shared batch implementation.
33        if args
34            .get("paths")
35            .and_then(|v| v.as_array())
36            .is_some_and(|a| !a.is_empty())
37        {
38            let result = super::super::ctx_read_batch::batch_read(args, ctx);
39            if let Ok(output) = &result {
40                record_attribution_result(ctx, "ctx_read batch".to_string(), output);
41            }
42            return result;
43        }
44
45        let path = if let Some(repo) = get_str(args, "repo") {
46            let root = crate::core::multi_repo::resolve_repo_root(&repo).ok_or_else(|| {
47                let known = crate::core::multi_repo::known_aliases().join(", ");
48                let known = if known.is_empty() {
49                    "none registered — use ctx_multi_repo add_root".to_string()
50                } else {
51                    known
52                };
53                ErrorData::invalid_params(
54                    format!("unknown repo alias: {repo} (known: {known})"),
55                    None,
56                )
57            })?;
58            let rel = get_str(args, "path").unwrap_or_else(|| ".".to_string());
59            crate::core::path_resolve::resolve_tool_path(Some(&root), None, &rel)
60                .map_err(|e| ErrorData::invalid_params(e, None))?
61        } else {
62            require_resolved_path(ctx, args, "path")?
63        };
64
65        // "File not found" is the most frequent read failure, and often the
66        // path is one mechanical slip from a real file (other case, wrong
67        // prefix). When exactly one file fits and the jail admits it, read it
68        // and say so instead of failing. Byte-exact reads (the engine view,
69        // `raw`) never substitute: their output must be the file and nothing else.
70        let byte_exact = engine_interface_v1
71            || get_str(args, "mode").as_deref() == Some("raw")
72            || args.get("raw").and_then(Value::as_bool) == Some(true);
73        let (path, substituted) = match (!byte_exact)
74            .then(|| crate::core::path_suggest::unambiguous_match(std::path::Path::new(&path)))
75            .flatten()
76            .and_then(|found| ctx.resolve_path_sync(&found.to_string_lossy()).ok())
77        {
78            Some(found) => (found, Some(path)),
79            None => (path, None),
80        };
81
82        let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
83            self.handle_inner(args, ctx, &path, engine_interface_v1)
84        })) {
85            Ok(result) => result,
86            Err(_) => Err(ErrorData::internal_error(
87                format!(
88                    "ctx_read panicked while processing '{path}'. This is a bug — please report it."
89                ),
90                None,
91            )),
92        };
93        // A trailing service line: the header stays the first line, as every
94        // reader of ctx_read output (and the Claude Code plugin) expects.
95        let result = result.map(|mut output| {
96            if let Some(requested) = &substituted {
97                output.text = format!(
98                    "{}\n[lean-ctx: {requested} does not exist — read {path} instead]",
99                    output.text.trim_end_matches('\n')
100                );
101            }
102            output
103        });
104        if let Ok(output) = &result {
105            record_attribution_result(ctx, format!("ctx_read {path}"), output);
106        }
107        result
108    }
109
110    /// Single reads and batches share one implementation per file,
111    /// `handle_inner_prepared`, and that is where the lineage is settled:
112    ///
113    /// - the requested file is published on every path — fresh reads through
114    ///   `tools::ctx_read::read_file_*` (handler thread or
115    ///   `TaskSpine::spawn_thread` workers), and cache hits, `[unchanged]`
116    ///   stubs and deltas through `publish_requested_source`, bound to what
117    ///   is on disk now;
118    /// - whenever the reply carries content from anywhere else — graph
119    ///   neighbours, cross-source hints, rule files, proactively expanded
120    ///   content, the kernel supplement of a batch — the capture is marked
121    ///   incomplete there, so that reply's lineage is unknown;
122    /// - a source that cannot be bound (another repository via `repo`, an
123    ///   image, a path outside the root) marks it incomplete as well.
124    ///
125    /// So a captured set that is still complete at the end IS the whole set,
126    /// for every mode (the modes differ in rendering, not in what they read).
127    fn publishes_every_source(&self, _args: Option<&Map<String, Value>>) -> bool {
128        true
129    }
130}