lean_ctx_server/tools/registered/
ctx_read_dispatch.rs1use 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 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 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 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 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 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 fn publishes_every_source(&self, _args: Option<&Map<String, Value>>) -> bool {
161 true
162 }
163}
164
165fn 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 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
205fn 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}