lean_ctx_server/tools/registered/
ctx_index.rs1use std::path::Path;
3
4use rmcp::ErrorData;
5use rmcp::model::Tool;
6use serde_json::{Map, Value, json};
7
8use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_str};
9use lean_ctx::tool_defs::tool_def;
10
11pub struct CtxIndexTool;
12
13impl McpTool for CtxIndexTool {
14 fn name(&self) -> &'static str {
15 "ctx_index"
16 }
17
18 fn tool_def(&self) -> Tool {
19 tool_def(
20 "ctx_index",
21 "Index orchestration — manage code graph index.\n\
22 WORKFLOW: status → build → build-full (escalate if stale).\n\
23 ANTI-PATTERN: build-full is expensive — use incremental build first.\n\
24 Actions: status (state), build (incremental), build-full (rebuild),\n\
25 why (is `path` indexed? if not, the rule that dropped it).",
26 json!({
27 "type": "object",
28 "properties": {
29 "action": {
30 "type": "string",
31 "enum": ["status", "build", "build-full", "why"],
32 "description": "status|build|build-full|why"
33 },
34 "project_root": {
35 "type": "string",
36 "description": "Project root"
37 },
38 "path": {
39 "type": "string",
40 "description": "File to diagnose (action=why)"
41 }
42 },
43 "required": ["action"]
44 }),
45 )
46 }
47
48 fn handle(
49 &self,
50 args: &Map<String, Value>,
51 ctx: &ToolContext,
52 ) -> Result<ToolOutput, ErrorData> {
53 let action = get_str(args, "action")
54 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
55 let root = if let Some(p) = ctx
56 .resolved_path("project_root")
57 .or(ctx.resolved_path("root"))
58 {
59 p
60 } else if let Some(err) = ctx.path_error("project_root").or(ctx.path_error("root")) {
61 return Err(ErrorData::invalid_params(
62 format!("project_root: {err}"),
63 None,
64 ));
65 } else {
66 &ctx.project_root
67 };
68
69 if action == "why" {
70 let file = if let Some(p) = ctx.resolved_path("path") {
73 p.to_string()
74 } else if let Some(err) = ctx.path_error("path") {
75 return Err(ErrorData::invalid_params(format!("path: {err}"), None));
76 } else {
77 get_str(args, "path").ok_or_else(|| {
78 ErrorData::invalid_params("path is required for action=why", None)
79 })?
80 };
81 let coverage = lean_ctx::core::bm25_index::coverage::explain(Path::new(root), &file);
82 return Ok(ToolOutput::simple(
83 lean_ctx::core::bm25_index::coverage::render(&coverage),
84 ));
85 }
86
87 let result = crate::tools::ctx_index::handle(&action, Path::new(root));
88
89 if action == "build-full"
95 && let Some(cache) = ctx.cache.as_ref()
96 && let Some(mut guard) = crate::server::bounded_lock::write(cache, "ctx_index")
97 {
98 guard.clear();
99 }
100
101 Ok(ToolOutput::simple(result))
102 }
103}