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/// Handlers are synchronous because all existing tool handlers are sync.
59/// The async boundary (cache locks, session reads) is handled by the dispatch
60/// layer before calling `handle`.
61pub trait McpTool: Send + Sync {
62    /// Tool name as registered in the MCP protocol (e.g. "ctx_tree").
63    fn name(&self) -> &'static str;
64
65    /// MCP tool definition including JSON schema. This replaces the
66    /// corresponding entry in `granular_tool_defs()`.
67    fn tool_def(&self) -> Tool;
68
69    /// Execute the tool. Args are the raw JSON-RPC arguments.
70    /// `ctx` provides access to resolved paths and project state.
71    fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
72        -> Result<ToolOutput, ErrorData>;
73}
74
75/// Context passed to tool handlers. Contains pre-resolved values that
76/// many tools need, avoiding repeated async lock acquisition inside
77/// handlers. Extended with shared server state for tools that need
78/// cache/session access.
79pub struct ToolContext {
80    pub project_root: String,
81    pub minimal: bool,
82    /// Pre-resolved paths keyed by argument name (e.g. "path" -> "/abs/dir").
83    pub resolved_paths: std::collections::HashMap<String, String>,
84    /// CRP mode for compression-aware tools.
85    pub crp_mode: crate::tools::CrpMode,
86    /// Shared cache handle for tools that need read/write access.
87    pub cache: Option<crate::tools::SharedCache>,
88    /// Shared session handle for tools that need session access.
89    pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
90    /// Tool call records for session-aware tools (e.g. ctx_session status).
91    pub tool_calls:
92        Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
93    /// Current agent identity for multi-agent tools.
94    pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
95    /// Active workflow run state.
96    pub workflow:
97        Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
98    /// Context ledger for handoff operations.
99    pub ledger:
100        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
101    /// Client name (cursor, claude, etc.).
102    pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
103    /// Pipeline stats for metrics/proof tools.
104    pub pipeline_stats:
105        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
106    /// Global call counter for context tools.
107    pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
108    /// Autonomy state for search repeat detection.
109    pub autonomy: Option<std::sync::Arc<crate::tools::autonomy::AutonomyState>>,
110    /// Pre-computed context pressure snapshot for synchronous gate decisions.
111    pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
112    /// Errors from path resolution (PathJail rejection, secret path, etc.).
113    /// Keyed by argument name (e.g. "path" -> "path escapes project root: ...").
114    pub path_errors: std::collections::HashMap<String, String>,
115}
116
117impl ToolContext {
118    pub fn resolved_path(&self, arg: &str) -> Option<&str> {
119        self.resolved_paths.get(arg).map(String::as_str)
120    }
121
122    /// Returns the path resolution error for a given key, if any.
123    pub fn path_error(&self, key: &str) -> Option<&str> {
124        self.path_errors.get(key).map(String::as_str)
125    }
126
127    /// Sync path resolution using project_root. Simplified version
128    /// of LeanCtxServer::resolve_path for use in sync tool handlers.
129    pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
130        let normalized = crate::core::pathutil::normalize_tool_path(path);
131        if normalized.is_empty() || normalized == "." {
132            return Ok(normalized);
133        }
134        let p = std::path::Path::new(&normalized);
135        let resolved = if p.is_absolute() || p.exists() {
136            std::path::PathBuf::from(&normalized)
137        } else {
138            let joined = std::path::Path::new(&self.project_root).join(&normalized);
139            if joined.exists() {
140                joined
141            } else {
142                std::path::Path::new(&self.project_root).join(&normalized)
143            }
144        };
145        let jail_root = std::path::Path::new(&self.project_root);
146        let jailed = crate::core::pathjail::jail_path(&resolved, jail_root)?;
147        crate::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)?;
148        Ok(crate::core::pathutil::normalize_tool_path(
149            &jailed.to_string_lossy().replace('\\', "/"),
150        ))
151    }
152}
153
154// ── Arg extraction helpers (mirror server/helpers.rs for standalone use) ──
155
156/// Extract a resolved path from context with differentiated error messages.
157/// Returns descriptive errors for: missing param, PathJail rejection, wrong type.
158pub fn require_resolved_path(
159    ctx: &ToolContext,
160    args: &Map<String, Value>,
161    key: &str,
162) -> Result<String, ErrorData> {
163    if let Some(path) = ctx.resolved_path(key) {
164        return Ok(path.to_string());
165    }
166    if let Some(err) = ctx.path_error(key) {
167        return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
168    }
169    if let Some(val) = args.get(key) {
170        if !val.is_string() {
171            let type_name = match val {
172                Value::Number(_) => "number",
173                Value::Bool(_) => "boolean",
174                Value::Array(_) => "array",
175                Value::Object(_) => "object",
176                Value::Null => "null",
177                Value::String(_) => unreachable!(),
178            };
179            return Err(ErrorData::invalid_params(
180                format!("{key} must be a string, got {type_name}"),
181                None,
182            ));
183        }
184    }
185    Err(ErrorData::invalid_params(
186        format!("{key} is required"),
187        None,
188    ))
189}
190
191pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
192    args.get(key).and_then(|v| v.as_str()).map(String::from)
193}
194
195pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
196    args.get(key).and_then(serde_json::Value::as_i64)
197}
198
199pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
200    args.get(key).and_then(serde_json::Value::as_bool)
201}
202
203pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
204    args.get(key).and_then(|v| v.as_array()).map(|arr| {
205        arr.iter()
206            .filter_map(|v| v.as_str().map(String::from))
207            .collect()
208    })
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use serde_json::json;
215
216    fn empty_ctx() -> ToolContext {
217        ToolContext {
218            project_root: String::new(),
219            minimal: false,
220            resolved_paths: std::collections::HashMap::new(),
221            crp_mode: crate::tools::CrpMode::Off,
222            cache: None,
223            session: None,
224            tool_calls: None,
225            agent_id: None,
226            workflow: None,
227            ledger: None,
228            client_name: None,
229            pipeline_stats: None,
230            call_count: None,
231            autonomy: None,
232            pressure_snapshot: None,
233            path_errors: std::collections::HashMap::new(),
234        }
235    }
236
237    #[test]
238    fn require_resolved_path_returns_resolved() {
239        let mut ctx = empty_ctx();
240        ctx.resolved_paths
241            .insert("path".to_string(), "/abs/file.rs".to_string());
242        let args: Map<String, Value> = Map::new();
243        let result = require_resolved_path(&ctx, &args, "path");
244        assert_eq!(result.unwrap(), "/abs/file.rs");
245    }
246
247    #[test]
248    fn require_resolved_path_surfaces_jail_error() {
249        let mut ctx = empty_ctx();
250        ctx.path_errors.insert(
251            "path".to_string(),
252            "path escapes project root /project".to_string(),
253        );
254        let args: Map<String, Value> = Map::new();
255        let result = require_resolved_path(&ctx, &args, "path");
256        assert!(result.is_err());
257        let err = result.unwrap_err();
258        let msg = format!("{err:?}");
259        assert!(msg.contains("escapes project root"), "got: {msg}");
260    }
261
262    #[test]
263    fn require_resolved_path_detects_non_string() {
264        let ctx = empty_ctx();
265        let mut args: Map<String, Value> = Map::new();
266        args.insert("path".to_string(), json!(42));
267        let result = require_resolved_path(&ctx, &args, "path");
268        assert!(result.is_err());
269        let err = result.unwrap_err();
270        let msg = format!("{err:?}");
271        assert!(msg.contains("must be a string, got number"), "got: {msg}");
272    }
273
274    #[test]
275    fn require_resolved_path_missing_param() {
276        let ctx = empty_ctx();
277        let args: Map<String, Value> = Map::new();
278        let result = require_resolved_path(&ctx, &args, "path");
279        assert!(result.is_err());
280        let err = result.unwrap_err();
281        let msg = format!("{err:?}");
282        assert!(msg.contains("path is required"), "got: {msg}");
283    }
284}