lean-ctx-server 3.12.1

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// SPDX-License-Identifier: Apache-2.0
use lean_ctx::core::call_graph::{CallEdge, CallGraph, CallGraphInputs, RiskLevel};
use lean_ctx::core::index_paths;

const MAX_BFS_DEPTH: usize = 5;

pub fn handle(
    action: &str,
    symbol: Option<&str>,
    file: Option<&str>,
    project_root: &str,
    depth: usize,
    from: Option<&str>,
    to: Option<&str>,
) -> String {
    match action {
        "callers" | "callees" => {
            let Some(sym) = symbol else {
                return "symbol is required for callers/callees action".to_string();
            };
            with_handle_hint(handle_direction(sym, file, project_root, action, depth))
        }
        "trace" => with_handle_hint(handle_trace(from, to, project_root)),
        "risk" => {
            let Some(sym) = symbol else {
                return "symbol is required for risk action".to_string();
            };
            handle_risk(sym, project_root)
        }
        _ => format!("Unknown action '{action}'. Use: callers|callees|trace|risk"),
    }
}

fn load_graph(project_root: &str) -> CallGraph {
    load_graph_with_inputs(project_root).0
}

fn load_graph_with_inputs(project_root: &str) -> (CallGraph, CallGraphInputs) {
    let inputs = CallGraphInputs::open(project_root);
    let graph = CallGraph::load_or_build(project_root, &inputs);
    let _ = graph.save();
    (graph, inputs)
}

/// Where each listed call goes, with the evidence behind it:
/// `⇒ src/repo.rs [verified]`. Structurally uncertain edges are escalated to
/// a semantic backend on the spot (cached; `semantic_mode` rules apply).
/// Unknown callees (std, dependencies) get no annotation.
fn target_annotations(
    edges: &[&CallEdge],
    graph: &CallGraph,
    inputs: &CallGraphInputs,
    project_root: &str,
) -> Vec<String> {
    use lean_ctx::core::call_graph::{StructuralTarget, resolve_edge_callee_targets};
    use lean_ctx::core::semantic::{EvidenceGrade, SemanticVerdict, escalate_calls};

    let owned: Vec<CallEdge> = edges.iter().map(|e| (*e).clone()).collect();
    let structural = resolve_edge_callee_targets(inputs, &owned);
    let store = lean_ctx::core::property_graph::CodeGraph::open(project_root).ok();
    let verdicts = match &store {
        Some(store) => {
            let mode = lean_ctx::core::config::SemanticMode::for_project(project_root);
            escalate_calls(
                store,
                project_root,
                inputs,
                &owned,
                &structural,
                &graph.file_hashes,
                mode,
                lean_ctx::core::semantic::EscalationBudget::INTERACTIVE,
            )
            .verdicts
        }
        None => vec![None; owned.len()],
    };
    // A target file is named only while the graph serves it now (G04); a
    // call into a withdrawn file gets no annotation, like an unknown callee.
    let served = |file: &str| store.as_ref().is_none_or(|store| store.serves_file(file));
    structural
        .iter()
        .zip(verdicts)
        .map(|(target, verdict)| {
            let named = match (&verdict, target) {
                (Some(SemanticVerdict::Verified { file, .. }), _)
                | (None, StructuralTarget::Resolved { file, .. }) => Some(file.as_str()),
                _ => None,
            };
            if named.is_some_and(|file| !served(file)) {
                return String::new();
            }
            match (verdict, target) {
                (Some(SemanticVerdict::Verified { file, .. }), _) => {
                    format!("  ⇒ {file} [verified]")
                }
                (Some(SemanticVerdict::NotInProject), _) => "  ⇒ external [verified]".to_string(),
                (None, StructuralTarget::Resolved { file, via }) => {
                    format!("  ⇒ {file} [{}]", EvidenceGrade::from_scope(*via).as_str())
                }
                (None, StructuralTarget::Ambiguous) => "  ⇒ ? [ambiguous]".to_string(),
                (None, StructuralTarget::Unknown) => String::new(),
            }
        })
        .collect()
}

fn handle_direction(
    symbol: &str,
    file: Option<&str>,
    project_root: &str,
    direction: &str,
    depth: usize,
) -> String {
    let clamped_depth = depth.clamp(1, MAX_BFS_DEPTH);

    if clamped_depth == 1 {
        let (graph, inputs) = load_graph_with_inputs(project_root);
        let filter = file.map(|f| graph_file_filter(f, project_root));
        let annotate =
            |edges: &[&CallEdge]| target_annotations(edges, &graph, &inputs, project_root);
        match direction {
            "callers" => format_callers(symbol, &graph, filter.as_deref(), annotate),
            "callees" => format_callees(symbol, &graph, filter.as_deref(), annotate),
            _ => unreachable!(),
        }
    } else {
        let graph = load_graph(project_root);
        let filter = file.map(|f| graph_file_filter(f, project_root));
        match direction {
            "callers" => format_bfs_callers(symbol, &graph, clamped_depth, filter.as_deref()),
            "callees" => format_bfs_callees(symbol, &graph, clamped_depth, filter.as_deref()),
            _ => unreachable!(),
        }
    }
}

fn handle_trace(from: Option<&str>, to: Option<&str>, project_root: &str) -> String {
    let Some(from_sym) = from else {
        return "'from' is required for trace action".to_string();
    };
    let Some(to_sym) = to else {
        return "'to' is required for trace action".to_string();
    };

    let graph = load_graph(project_root);

    match graph.find_call_path(from_sym, to_sym) {
        Some(hops) => {
            let mut out = format!("Call path ({} hop(s)):\n", hops.len() - 1);
            for (i, hop) in hops.iter().enumerate() {
                let loc = if hop.file.is_empty() {
                    String::new()
                } else {
                    format!("  ({}:L{})", hop.file, hop.line)
                };
                if i == 0 {
                    out.push_str(&format!("  {}{loc}\n", hop.symbol));
                } else {
                    out.push_str(&format!("  → {}{loc}\n", hop.symbol));
                }
            }
            out
        }
        None => {
            format!("No call path found from '{from_sym}' to '{to_sym}' (searched up to depth 10)")
        }
    }
}

fn handle_risk(symbol: &str, project_root: &str) -> String {
    let graph = load_graph(project_root);
    let count = graph.transitive_caller_count(symbol, MAX_BFS_DEPTH);
    let level = RiskLevel::from_caller_count(count);
    let direct = graph.callers_of(symbol).len();

    let mut out = format!(
        "Risk: {} — {} transitive caller(s) of '{}' (depth≤{}, {} direct)\n\
         Thresholds: CRITICAL >10 | HIGH 5–10 | MEDIUM 2–4 | LOW 0–1",
        level.label(),
        count,
        symbol,
        MAX_BFS_DEPTH,
        direct,
    );

    // Fold in the code-health dimension (#1084): a symbol that is both
    // widely-called AND cognitively complex is the highest-leverage refactor.
    // Sourced from the persisted health fabric (best-effort, no parsing).
    if let Some(cc) = lean_ctx::core::code_health::fabric::hotspot_cc(project_root, symbol) {
        out.push_str(&format!(
            "\nComplexity: cc={cc} (over navigability threshold) — high blast-radius and hard to read."
        ));
    }
    out
}

// ---------------------------------------------------------------------------
// Single-hop formatters (existing behavior)
// ---------------------------------------------------------------------------

fn format_callers(
    symbol: &str,
    graph: &CallGraph,
    filter: Option<&str>,
    annotate: impl FnOnce(&[&CallEdge]) -> Vec<String>,
) -> String {
    let mut callers = graph.callers_of(symbol);
    if let Some(f) = filter {
        callers.retain(|e| index_paths::graph_match_key(&e.caller_file).contains(f));
    }
    // Several calls from one function render as the same line; show it once.
    let mut seen = std::collections::HashSet::new();
    callers.retain(|e| seen.insert((&e.caller_file, &e.caller_symbol, e.caller_line)));

    if callers.is_empty() {
        return format!(
            "No callers found for '{}' ({} edges in graph)",
            symbol,
            graph.edges.len()
        );
    }

    let mut out = format!("{} caller(s) of '{symbol}':\n", callers.len());
    for (edge, target) in callers.iter().zip(annotate(&callers)) {
        out.push_str(&format!(
            "  {} → {}  (L{}){target}\n",
            edge.caller_file, edge.caller_symbol, edge.caller_line
        ));
    }
    out
}

fn format_callees(
    symbol: &str,
    graph: &CallGraph,
    filter: Option<&str>,
    annotate: impl FnOnce(&[&CallEdge]) -> Vec<String>,
) -> String {
    let mut callees = graph.callees_of(symbol);
    if let Some(f) = filter {
        callees.retain(|e| index_paths::graph_match_key(&e.caller_file).contains(f));
    }
    let mut seen = std::collections::HashSet::new();
    callees.retain(|e| seen.insert((&e.callee_name, &e.caller_file, e.caller_line)));

    if callees.is_empty() {
        return format!(
            "No callees found for '{}' ({} edges in graph)",
            symbol,
            graph.edges.len()
        );
    }

    let mut out = format!("{} callee(s) of '{symbol}':\n", callees.len());
    for (edge, target) in callees.iter().zip(annotate(&callees)) {
        out.push_str(&format!(
            "  → {}  ({}:L{}){target}\n",
            edge.callee_name, edge.caller_file, edge.caller_line
        ));
    }
    out
}

// ---------------------------------------------------------------------------
// Multi-hop BFS formatters
// ---------------------------------------------------------------------------

fn format_bfs_callers(
    symbol: &str,
    graph: &CallGraph,
    depth: usize,
    filter: Option<&str>,
) -> String {
    let mut nodes = graph.bfs_callers(symbol, depth);
    if let Some(f) = filter {
        nodes.retain(|n| index_paths::graph_match_key(&n.file).contains(f));
    }

    if nodes.is_empty() {
        return format!(
            "No callers found for '{}' (depth≤{}, {} edges in graph)",
            symbol,
            depth,
            graph.edges.len()
        );
    }

    let mut out = format!(
        "{} caller(s) of '{}' (depth≤{}):\n",
        nodes.len(),
        symbol,
        depth
    );
    for node in &nodes {
        let indent = "  ".repeat(node.depth);
        out.push_str(&format!(
            "{indent}{} ← {}  ({}:L{})\n",
            node.from_symbol, node.symbol, node.file, node.line
        ));
    }
    out
}

fn format_bfs_callees(
    symbol: &str,
    graph: &CallGraph,
    depth: usize,
    filter: Option<&str>,
) -> String {
    let mut nodes = graph.bfs_callees(symbol, depth);
    if let Some(f) = filter {
        nodes.retain(|n| index_paths::graph_match_key(&n.file).contains(f));
    }

    if nodes.is_empty() {
        return format!(
            "No callees found for '{}' (depth≤{}, {} edges in graph)",
            symbol,
            depth,
            graph.edges.len()
        );
    }

    let mut out = format!(
        "{} callee(s) of '{}' (depth≤{}):\n",
        nodes.len(),
        symbol,
        depth
    );
    for node in &nodes {
        let indent = "  ".repeat(node.depth);
        out.push_str(&format!(
            "{indent}{} → {}  ({}:L{})\n",
            node.from_symbol, node.symbol, node.file, node.line
        ));
    }
    out
}

/// Append the stable-handle usage hint (#607) to a non-empty result so the
/// agent can re-target any listed symbol via `ctx_search(action="symbol",
/// handle=…)`. Skips error/empty messages (which start with "No ") so failures
/// stay clean.
fn with_handle_hint(out: String) -> String {
    if out.starts_with("No ") || out.trim().is_empty() {
        out
    } else {
        format!("{out}{}\n", lean_ctx::core::handle::USAGE_HINT)
    }
}

fn graph_file_filter(file: &str, project_root: &str) -> String {
    let rel = index_paths::graph_relative_key(file, project_root);
    let rel_key = index_paths::graph_match_key(&rel);
    if rel_key.is_empty() {
        index_paths::graph_match_key(file)
    } else {
        rel_key
    }
}

#[cfg(test)]
mod tests {
    use super::graph_file_filter;

    #[test]
    fn graph_file_filter_normalizes_windows_styles() {
        let filter = graph_file_filter(r"C:/repo/src/main/kotlin/Example.kt", r"C:\repo");
        let expected = if cfg!(windows) {
            "src/main/kotlin/Example.kt"
        } else {
            "C:/repo/src/main/kotlin/Example.kt"
        };
        assert_eq!(filter, expected);
    }

    #[test]
    fn invalid_action_returns_helpful_error() {
        let output = super::handle("unknown", Some("foo"), None, "/tmp", 1, None, None);
        assert!(output.contains("Unknown action"));
        assert!(output.contains("callers|callees|trace|risk"));
    }

    #[test]
    fn callers_action_without_symbol_returns_error() {
        let output = super::handle("callers", None, None, "/tmp", 1, None, None);
        assert!(output.contains("symbol is required"));
    }

    #[test]
    fn trace_without_from_returns_error() {
        let output = super::handle("trace", None, None, "/tmp", 1, None, Some("b"));
        assert!(output.contains("'from' is required"));
    }

    #[test]
    fn trace_without_to_returns_error() {
        let output = super::handle("trace", None, None, "/tmp", 1, Some("a"), None);
        assert!(output.contains("'to' is required"));
    }

    #[test]
    fn risk_without_symbol_returns_error() {
        let output = super::handle("risk", None, None, "/tmp", 1, None, None);
        assert!(output.contains("symbol is required"));
    }

    #[test]
    fn two_calls_from_one_function_render_one_caller_line() {
        use lean_ctx::core::call_graph::{CallEdge, CallGraph};
        let mut graph = CallGraph::new("/p");
        for _ in 0..2 {
            graph.edges.push(CallEdge {
                caller_file: "vat.py".to_string(),
                caller_symbol: "gross_from_net".to_string(),
                caller_line: 16,
                callee_name: "to_amount".to_string(),
                ..Default::default()
            });
        }
        let out = super::format_callers("to_amount", &graph, None, |edges| {
            vec![String::new(); edges.len()]
        });
        assert_eq!(out.matches("gross_from_net").count(), 1, "{out}");
        assert!(out.starts_with("1 caller(s)"), "{out}");
    }

    #[test]
    fn handle_hint_appended_to_results_only() {
        use super::with_handle_hint;
        let ok = with_handle_hint("1 caller(s) of 'x':\n  a → b  (L1)\n".to_string());
        assert!(
            ok.contains("handle=\""),
            "success output gets the hint: {ok}"
        );
        let empty = with_handle_hint("No callers found for 'x' (0 edges in graph)".to_string());
        assert!(
            !empty.contains("handle=\""),
            "empty result stays clean: {empty}"
        );
    }
}