Skip to main content

lean_ctx_server/tools/registered/
ctx_graph.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, get_usize};
7use lean_ctx::tool_defs::tool_def;
8
9pub struct CtxGraphTool;
10
11impl McpTool for CtxGraphTool {
12    fn name(&self) -> &'static str {
13        "ctx_graph"
14    }
15
16    fn tool_def(&self) -> Tool {
17        tool_def(
18            "ctx_graph",
19            "File-level dependency graph queries.\n\
20             action=symbol path=\"file.rs::fnName\" returns the DEFINITION (not usages — \
21             use ctx_search for references). neighbors=imports±direction, \
22             impact=reverse-dep blast radius, path from→to=dependency chain, \
23             diff since=HEAD~1=git change impact, landing since=base head=ref \
24             [other=ref]=changed units, callers, affected tests, overlap, diagram kind=deps|calls (Mermaid).\n\
25             For understanding code use ctx_compose FIRST.",
26            json!({
27                "type": "object",
28                "properties": {
29                    "action": {
30                        "type": "string",
31                        "description": "build|related|symbol|impact|status|enrich|context|diagram|neighbors|path|explain|diff|landing"
32                    },
33                    "path": {
34                        "type": "string",
35                        "description": "Path; file::symbol for symbol action"
36                    },
37                    "to": { "type": "string", "description": "Target file (action=path)" },
38                    "depth": { "type": "integer" },
39                    "kind": { "type": "string", "description": "diagram: deps|calls" },
40                    "format": { "type": "string", "description": "text|json" },
41                    "since": { "type": "string", "description": "Git ref (default HEAD~1)" },
42                    "head": { "type": "string", "description": "landing: head ref (default HEAD)" },
43                    "other": { "type": "string", "description": "landing: second head for overlap" },
44                    "project_root": { "type": "string" }
45                },
46                "required": ["action"],
47                "allOf": [
48                    { "if": { "properties": { "action": { "enum": ["related", "symbol", "impact", "neighbors", "explain", "path"] } }, "required": ["action"] }, "then": { "required": ["path"] } },
49                    { "if": { "properties": { "action": { "const": "path" } }, "required": ["action"] }, "then": { "required": ["path", "to"] } }
50                ]
51            }),
52        )
53    }
54
55    fn handle(
56        &self,
57        args: &Map<String, Value>,
58        ctx: &ToolContext,
59    ) -> Result<ToolOutput, ErrorData> {
60        let action = get_str(args, "action")
61            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
62
63        let path = if action == "diagram" {
64            get_str(args, "path")
65        } else if let Some(p) = ctx.resolved_path("path") {
66            Some(p.to_string())
67        } else if let Some(err) = ctx
68            .path_error("path")
69            .filter(|_| get_str(args, "path").is_some())
70        {
71            return Err(ErrorData::invalid_params(format!("path: {err}"), None));
72        } else {
73            None
74        };
75
76        let root = if let Some(p) = ctx.resolved_path("project_root") {
77            p.to_string()
78        } else if let Some(err) = ctx.path_error("project_root") {
79            return Err(ErrorData::invalid_params(
80                format!("project_root: {err}"),
81                None,
82            ));
83        } else {
84            ctx.project_root.clone()
85        };
86        let depth = get_usize(args, "depth").map(|d| d.min(64));
87        let kind = get_str(args, "kind");
88        let format = get_str(args, "format");
89        // `since` is a git ref, not a filesystem path — read it raw (no PathJail).
90        let since = get_str(args, "since");
91        let to = if let Some(p) = ctx.resolved_path("to") {
92            Some(p.to_string())
93        } else if let Some(err) = ctx
94            .path_error("to")
95            .filter(|_| get_str(args, "to").is_some())
96        {
97            return Err(ErrorData::invalid_params(format!("to: {err}"), None));
98        } else {
99            None
100        };
101
102        if action == "landing" {
103            return Ok(ToolOutput::simple(crate::tools::ctx_graph_landing::handle(
104                since.as_deref(),
105                get_str(args, "head").as_deref(),
106                get_str(args, "other").as_deref(),
107                depth,
108                &root,
109                format.as_deref(),
110            )));
111        }
112
113        let cache = ctx
114            .cache
115            .as_ref()
116            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
117        let Some(mut guard) = crate::server::bounded_lock::write(cache, "ctx_graph") else {
118            return Ok(ToolOutput::simple(
119                "[graph cache temporarily unavailable — retry in a moment]".to_string(),
120            ));
121        };
122        let result = crate::tools::ctx_graph::handle(
123            &action,
124            path.as_deref(),
125            &root,
126            &mut guard,
127            ctx.crp_mode,
128            depth,
129            kind.as_deref(),
130            to.as_deref(),
131            format.as_deref(),
132            since.as_deref(),
133        );
134
135        Ok(ToolOutput {
136            text: result,
137            original_tokens: 0,
138            saved_tokens: 0,
139            mode: Some(action),
140            path: None,
141            changed: false,
142            shell_outcome: None,
143            content_blocks: None,
144        })
145    }
146}