Skip to main content

lean_ctx/server/
tool_trait.rs

1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{Map, Value};
4
5/// Result returned by an McpTool handler.
6pub struct ToolOutput {
7    pub text: String,
8    pub original_tokens: usize,
9    pub saved_tokens: usize,
10    pub mode: Option<String>,
11    /// Path associated with the tool call (for record_call_with_path).
12    pub path: Option<String>,
13    /// True when the tool mutated state that clients should know about
14    /// (e.g. dynamic tool categories changed).
15    pub changed: bool,
16}
17
18impl ToolOutput {
19    pub fn simple(text: String) -> Self {
20        Self {
21            text,
22            original_tokens: 0,
23            saved_tokens: 0,
24            mode: None,
25            path: None,
26            changed: false,
27        }
28    }
29
30    /// Compact one-line summary for headers_only response verbosity.
31    pub fn to_header_line(&self, tool_name: &str) -> String {
32        let path_str = self.path.as_deref().unwrap_or("—");
33        let mode_str = self.mode.as_deref().unwrap_or("—");
34        let sent = self.original_tokens.saturating_sub(self.saved_tokens);
35        let pct = if self.original_tokens > 0 {
36            (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
37        } else {
38            0
39        };
40        format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
41    }
42
43    pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
44        Self {
45            text,
46            original_tokens: original,
47            saved_tokens: saved,
48            mode: None,
49            path: None,
50            changed: false,
51        }
52    }
53}
54
55/// Trait for a self-contained MCP tool. Each tool provides its own schema
56/// definition and handler, eliminating the possibility of schema/handler drift.
57///
58/// This trait is the plugin interface for LcpTools: any implementation can be
59/// registered at runtime via `ToolRegistry::register()`. Future plugin system
60/// will load implementations from shared libraries or subprocess bridges.
61///
62/// Handlers are synchronous because all existing tool handlers are sync.
63/// The async boundary (cache locks, session reads) is handled by the dispatch
64/// layer before calling `handle`.
65pub trait McpTool: Send + Sync {
66    /// Tool name as registered in the MCP protocol (e.g. "ctx_tree").
67    fn name(&self) -> &'static str;
68
69    /// MCP tool definition including JSON schema. This replaces the
70    /// corresponding entry in `granular_tool_defs()`.
71    fn tool_def(&self) -> Tool;
72
73    /// Execute the tool. Args are the raw JSON-RPC arguments.
74    /// `ctx` provides access to resolved paths and project state.
75    fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
76        -> Result<ToolOutput, ErrorData>;
77}
78
79/// Context passed to tool handlers. Contains pre-resolved values that
80/// many tools need, avoiding repeated async lock acquisition inside
81/// handlers. Extended with shared server state for tools that need
82/// cache/session access.
83pub struct ToolContext {
84    pub project_root: String,
85    pub minimal: bool,
86    /// Pre-resolved paths keyed by argument name (e.g. "path" -> "/abs/dir").
87    pub resolved_paths: std::collections::HashMap<String, String>,
88    /// CRP mode for compression-aware tools.
89    pub crp_mode: crate::tools::CrpMode,
90    /// Shared cache handle for tools that need read/write access.
91    pub cache: Option<crate::tools::SharedCache>,
92    /// Shared session handle for tools that need session access.
93    pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
94    /// Tool call records for session-aware tools (e.g. ctx_session status).
95    pub tool_calls:
96        Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
97    /// Current agent identity for multi-agent tools.
98    pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
99    /// Active workflow run state.
100    pub workflow:
101        Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
102    /// Context ledger for handoff operations.
103    pub ledger:
104        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
105    /// Client name (cursor, claude, etc.).
106    pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
107    /// Pipeline stats for metrics/proof tools.
108    pub pipeline_stats:
109        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
110    /// Global call counter for context tools.
111    pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
112    /// Autonomy state for search repeat detection.
113    pub autonomy: Option<std::sync::Arc<crate::tools::autonomy::AutonomyState>>,
114    /// Pre-computed context pressure snapshot for synchronous gate decisions.
115    pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
116    /// Errors from path resolution (PathJail rejection, secret path, etc.).
117    /// Keyed by argument name (e.g. "path" -> "path escapes project root: ...").
118    pub path_errors: std::collections::HashMap<String, String>,
119    /// Shared in-memory BM25 index cache for semantic search.
120    pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
121    /// MCP progress notification sender for long-running operations.
122    pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
123}
124
125impl ToolContext {
126    pub fn resolved_path(&self, arg: &str) -> Option<&str> {
127        self.resolved_paths.get(arg).map(String::as_str)
128    }
129
130    /// Returns the path resolution error for a given key, if any.
131    pub fn path_error(&self, key: &str) -> Option<&str> {
132        self.path_errors.get(key).map(String::as_str)
133    }
134
135    /// Sync path resolution using `project_root`. Thin wrapper over
136    /// [`crate::core::path_resolve::resolve_tool_path`] for sync tool handlers.
137    pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
138        crate::core::path_resolve::resolve_tool_path(Some(&self.project_root), None, path)
139    }
140}
141
142// ── Arg extraction helpers (mirror server/helpers.rs for standalone use) ──
143
144/// Extract a resolved path from context with differentiated error messages.
145/// Returns descriptive errors for: missing param, PathJail rejection, wrong type.
146pub fn require_resolved_path(
147    ctx: &ToolContext,
148    args: &Map<String, Value>,
149    key: &str,
150) -> Result<String, ErrorData> {
151    if let Some(path) = ctx.resolved_path(key) {
152        return Ok(path.to_string());
153    }
154    if let Some(err) = ctx.path_error(key) {
155        return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
156    }
157    if let Some(val) = args.get(key) {
158        if !val.is_string() {
159            let type_name = match val {
160                Value::Number(_) => "number",
161                Value::Bool(_) => "boolean",
162                Value::Array(_) => "array",
163                Value::Object(_) => "object",
164                Value::Null => "null",
165                Value::String(_) => unreachable!(),
166            };
167            return Err(ErrorData::invalid_params(
168                format!("{key} must be a string, got {type_name}"),
169                None,
170            ));
171        }
172    }
173    Err(ErrorData::invalid_params(
174        format!("{key} is required"),
175        None,
176    ))
177}
178
179pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
180    args.get(key).and_then(|v| v.as_str()).map(String::from)
181}
182
183pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
184    args.get(key).and_then(serde_json::Value::as_i64)
185}
186
187pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
188    args.get(key).and_then(serde_json::Value::as_bool)
189}
190
191pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
192    args.get(key).and_then(|v| v.as_array()).map(|arr| {
193        arr.iter()
194            .filter_map(|v| v.as_str().map(String::from))
195            .collect()
196    })
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use serde_json::json;
203
204    fn empty_ctx() -> ToolContext {
205        ToolContext {
206            project_root: String::new(),
207            minimal: false,
208            resolved_paths: std::collections::HashMap::new(),
209            crp_mode: crate::tools::CrpMode::Off,
210            cache: None,
211            session: None,
212            tool_calls: None,
213            agent_id: None,
214            workflow: None,
215            ledger: None,
216            client_name: None,
217            pipeline_stats: None,
218            call_count: None,
219            autonomy: None,
220            pressure_snapshot: None,
221            path_errors: std::collections::HashMap::new(),
222            bm25_cache: None,
223            progress_sender: None,
224        }
225    }
226
227    #[test]
228    fn require_resolved_path_returns_resolved() {
229        let mut ctx = empty_ctx();
230        ctx.resolved_paths
231            .insert("path".to_string(), "/abs/file.rs".to_string());
232        let args: Map<String, Value> = Map::new();
233        let result = require_resolved_path(&ctx, &args, "path");
234        assert_eq!(result.unwrap(), "/abs/file.rs");
235    }
236
237    #[test]
238    fn require_resolved_path_surfaces_jail_error() {
239        let mut ctx = empty_ctx();
240        ctx.path_errors.insert(
241            "path".to_string(),
242            "path escapes project root /project".to_string(),
243        );
244        let args: Map<String, Value> = Map::new();
245        let result = require_resolved_path(&ctx, &args, "path");
246        assert!(result.is_err());
247        let err = result.unwrap_err();
248        let msg = format!("{err:?}");
249        assert!(msg.contains("escapes project root"), "got: {msg}");
250    }
251
252    #[test]
253    fn require_resolved_path_detects_non_string() {
254        let ctx = empty_ctx();
255        let mut args: Map<String, Value> = Map::new();
256        args.insert("path".to_string(), json!(42));
257        let result = require_resolved_path(&ctx, &args, "path");
258        assert!(result.is_err());
259        let err = result.unwrap_err();
260        let msg = format!("{err:?}");
261        assert!(msg.contains("must be a string, got number"), "got: {msg}");
262    }
263
264    #[test]
265    fn require_resolved_path_missing_param() {
266        let ctx = empty_ctx();
267        let args: Map<String, Value> = Map::new();
268        let result = require_resolved_path(&ctx, &args, "path");
269        assert!(result.is_err());
270        let err = result.unwrap_err();
271        let msg = format!("{err:?}");
272        assert!(msg.contains("path is required"), "got: {msg}");
273    }
274}