Skip to main content

lean_ctx/server/
tool_trait.rs

1use rmcp::ErrorData;
2use rmcp::model::{ContentBlock, Tool};
3use serde_json::{Map, Value};
4
5/// Outcome of a shell execution, carried alongside the rendered text so the
6/// MCP dispatch layer can surface failures in protocol metadata instead of
7/// only as an `[exit:N]` text footer (GitHub #389: clients had no programmatic
8/// way to detect ctx_shell failures and resorted to fragile regex matching).
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ShellOutcome {
11    /// The command ran; carries its real exit code (0 = success).
12    Exit(i32),
13    /// The command never ran (allowlist/validation rejection, or a
14    /// precondition failure such as an unreadable/oversized input file).
15    Blocked,
16}
17
18impl ShellOutcome {
19    /// Whether this outcome must be reported as a tool error (`isError: true`).
20    pub fn is_error(self) -> bool {
21        match self {
22            ShellOutcome::Exit(code) => code != 0,
23            ShellOutcome::Blocked => true,
24        }
25    }
26
27    /// Structured payload for `CallToolResult.structuredContent`, so guards
28    /// can read `exitCode`/`blocked` instead of parsing output text. Success
29    /// (exit 0) intentionally returns `None` — the happy path stays
30    /// token-neutral for clients that render structured content.
31    pub fn structured(self) -> Option<serde_json::Value> {
32        match self {
33            ShellOutcome::Exit(0) => None,
34            ShellOutcome::Exit(code) => Some(serde_json::json!({ "exitCode": code })),
35            ShellOutcome::Blocked => Some(serde_json::json!({ "blocked": true })),
36        }
37    }
38}
39
40/// Result returned by an McpTool handler.
41pub struct ToolOutput {
42    pub text: String,
43    pub original_tokens: usize,
44    pub saved_tokens: usize,
45    pub mode: Option<String>,
46    /// Path associated with the tool call (for record_call_with_path).
47    pub path: Option<String>,
48    /// True when the tool mutated state that clients should know about
49    /// (e.g. dynamic tool categories changed).
50    pub changed: bool,
51    /// Set by shell-executing tools so dispatch can populate `isError` +
52    /// `structuredContent` on the MCP result (GitHub #389). `None` for tools
53    /// that don't run shell commands.
54    pub shell_outcome: Option<ShellOutcome>,
55    /// Override content blocks for non-text responses (e.g. images).
56    /// When set, dispatch uses these instead of wrapping `text` in TextContent.
57    pub content_blocks: Option<Vec<ContentBlock>>,
58}
59
60impl ToolOutput {
61    pub fn simple(text: String) -> Self {
62        Self {
63            text,
64            original_tokens: 0,
65            saved_tokens: 0,
66            mode: None,
67            path: None,
68            changed: false,
69            shell_outcome: None,
70            content_blocks: None,
71        }
72    }
73
74    /// Compact one-line summary for headers_only response verbosity.
75    pub fn to_header_line(&self, tool_name: &str) -> String {
76        let path_str = self.path.as_deref().unwrap_or("—");
77        let mode_str = self.mode.as_deref().unwrap_or("—");
78        let sent = self.original_tokens.saturating_sub(self.saved_tokens);
79        let pct = if self.original_tokens > 0 {
80            (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
81        } else {
82            0
83        };
84        format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
85    }
86
87    pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
88        Self {
89            text,
90            original_tokens: original,
91            saved_tokens: saved,
92            mode: None,
93            path: None,
94            changed: false,
95            shell_outcome: None,
96            content_blocks: None,
97        }
98    }
99
100    /// Construct a ToolOutput for image/binary content blocks.
101    /// Bypasses all text processing in the dispatch pipeline.
102    pub fn image(blocks: Vec<ContentBlock>, path: String) -> Self {
103        Self {
104            text: String::new(),
105            original_tokens: 0,
106            saved_tokens: 0,
107            mode: Some("image".to_string()),
108            path: Some(path),
109            changed: false,
110            shell_outcome: None,
111            content_blocks: Some(blocks),
112        }
113    }
114}
115
116/// Trait for a self-contained MCP tool. Each tool provides its own schema
117/// definition and handler, eliminating the possibility of schema/handler drift.
118///
119/// This trait is the plugin interface for LcpTools: any implementation can be
120/// registered at runtime via `ToolRegistry::register()`. Future plugin system
121/// will load implementations from shared libraries or subprocess bridges.
122///
123/// Handlers are synchronous because all existing tool handlers are sync.
124/// The async boundary (cache locks, session reads) is handled by the dispatch
125/// layer before calling `handle`.
126pub trait McpTool: Send + Sync {
127    /// Tool name as registered in the MCP protocol (e.g. "ctx_tree").
128    fn name(&self) -> &'static str;
129
130    /// MCP tool definition including JSON schema. This replaces the
131    /// corresponding entry in `granular_tool_defs()`.
132    fn tool_def(&self) -> Tool;
133
134    /// Execute the tool. Args are the raw JSON-RPC arguments.
135    /// `ctx` provides access to resolved paths and project state.
136    fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
137    -> Result<ToolOutput, ErrorData>;
138
139    /// Whether *this* invocation yields a machine-readable payload (e.g. JSON)
140    /// that must reach the client byte-exact and parseable. When `true`, the
141    /// dispatch pipeline suppresses every human-oriented decoration
142    /// (auto-context briefing, verify footer, hints, checkpoints, deprecation
143    /// notices) and terse compression for this call, returning the pure body.
144    /// Keyed on `args` because most tools emit machine-readable output only for
145    /// an opt-in format flag (e.g. `format=json`); defaults to `false` (#990).
146    fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
147        false
148    }
149}
150
151/// Context passed to tool handlers. Contains pre-resolved values that
152/// many tools need, avoiding repeated async lock acquisition inside
153/// handlers. Extended with shared server state for tools that need
154/// cache/session access.
155///
156/// `Clone` exists for per-op delegation (#1088): a batch op with its own
157/// `path` clones the ctx and swaps in that op's resolved path.
158#[derive(Clone)]
159pub struct ToolContext {
160    pub project_root: String,
161    /// Session-scoped trusted roots (MCP `roots/list`, config `extra_roots`),
162    /// snapshotted from the session so sync handlers can honor them without an
163    /// async lock. Empty = single-root jail behaviour (#403).
164    pub extra_roots: Vec<String>,
165    pub minimal: bool,
166    /// Pre-resolved paths keyed by argument name (e.g. "path" -> "/abs/dir").
167    pub resolved_paths: std::collections::HashMap<String, String>,
168    /// CRP mode for compression-aware tools.
169    pub crp_mode: crate::tools::CrpMode,
170    /// Shared cache handle for tools that need read/write access.
171    pub cache: Option<crate::tools::SharedCache>,
172    /// Shared session handle for tools that need session access.
173    pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
174    /// Tool call records for session-aware tools (e.g. ctx_session status).
175    pub tool_calls:
176        Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
177    /// Current agent identity for multi-agent tools.
178    pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
179    /// Active workflow run state.
180    pub workflow:
181        Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
182    /// Context ledger for handoff operations.
183    pub ledger:
184        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
185    /// Client name (cursor, claude, etc.).
186    pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
187    /// Pipeline stats for metrics/proof tools.
188    pub pipeline_stats:
189        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
190    /// Global call counter for context tools.
191    pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
192    /// Autonomy state for search repeat detection.
193    pub autonomy: Option<std::sync::Arc<crate::core::autonomy::AutonomyState>>,
194    /// Pre-computed context pressure snapshot for synchronous gate decisions.
195    pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
196    /// Errors from path resolution (PathJail rejection, secret path, etc.).
197    /// Keyed by argument name (e.g. "path" -> "path escapes project root: ...").
198    pub path_errors: std::collections::HashMap<String, String>,
199    /// Shared in-memory BM25 index cache for semantic search.
200    pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
201    /// MCP progress notification sender for long-running operations.
202    pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
203}
204
205impl Default for ToolContext {
206    /// Minimal context: `project_root` empty, all shared-state handles `None`.
207    /// Single source for the one-shot CLI ctx (`cli::call_cmd::oneshot_ctx`) and
208    /// the `empty_ctx` test helper — adding a field no longer breaks either.
209    fn default() -> Self {
210        Self {
211            project_root: String::new(),
212            extra_roots: Vec::new(),
213            minimal: false,
214            resolved_paths: std::collections::HashMap::new(),
215            crp_mode: crate::tools::CrpMode::Off,
216            cache: None,
217            session: None,
218            tool_calls: None,
219            agent_id: None,
220            workflow: None,
221            ledger: None,
222            client_name: None,
223            pipeline_stats: None,
224            call_count: None,
225            autonomy: None,
226            pressure_snapshot: None,
227            path_errors: std::collections::HashMap::new(),
228            bm25_cache: None,
229            progress_sender: None,
230        }
231    }
232}
233
234impl ToolContext {
235    pub fn resolved_path(&self, arg: &str) -> Option<&str> {
236        self.resolved_paths.get(arg).map(String::as_str)
237    }
238
239    /// Returns the path resolution error for a given key, if any.
240    pub fn path_error(&self, key: &str) -> Option<&str> {
241        self.path_errors.get(key).map(String::as_str)
242    }
243
244    /// Sync path resolution using `project_root` + session `extra_roots`. Thin
245    /// wrapper over [`crate::core::path_resolve::resolve_tool_path_with_roots`]
246    /// for sync tool handlers.
247    pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
248        crate::core::path_resolve::resolve_tool_path_with_roots(
249            Some(&self.project_root),
250            None,
251            path,
252            &self.extra_roots,
253        )
254    }
255
256    /// Default-deny write gate for the read-only tier (#475). Write-capable tool
257    /// handlers must call this with an already-resolved absolute path before
258    /// touching the filesystem; it errors if the path is inside a configured
259    /// `read_only_roots` subtree. A no-op (always `Ok`) when no read-only roots
260    /// are configured, so non-users pay nothing. Thin wrapper over the single
261    /// choke point [`crate::core::pathjail::enforce_writable`] — the low-level
262    /// atomic writers call the same function, so this is the ergonomic,
263    /// early-error layer, not the only line of defence.
264    pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
265        crate::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
266    }
267}
268
269// ── Arg extraction helpers (mirror server/helpers.rs for standalone use) ──
270
271/// Extract a resolved path from context with differentiated error messages.
272/// Returns descriptive errors for: missing param, PathJail rejection, wrong type.
273pub fn require_resolved_path(
274    ctx: &ToolContext,
275    args: &Map<String, Value>,
276    key: &str,
277) -> Result<String, ErrorData> {
278    if let Some(path) = ctx.resolved_path(key) {
279        return Ok(path.to_string());
280    }
281    if let Some(err) = ctx.path_error(key) {
282        return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
283    }
284    if let Some(val) = args.get(key)
285        && !val.is_string()
286    {
287        let type_name = match val {
288            Value::Number(_) => "number",
289            Value::Bool(_) => "boolean",
290            Value::Array(_) => "array",
291            Value::Object(_) => "object",
292            Value::Null => "null",
293            Value::String(_) => unreachable!(),
294        };
295        return Err(ErrorData::invalid_params(
296            format!("{key} must be a string, got {type_name}"),
297            None,
298        ));
299    }
300    Err(ErrorData::invalid_params(
301        format!("{key} is required"),
302        None,
303    ))
304}
305
306pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
307    args.get(key).and_then(|v| v.as_str()).map(String::from)
308}
309
310pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
311    args.get(key)
312        .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
313}
314
315/// Read a non-negative integer argument as `usize`.
316///
317/// Returns `None` for missing or negative values. This avoids the
318/// `negative_i64 as usize` wrap to `usize::MAX`, which previously let an agent
319/// trigger unbounded allocations (e.g. `top_k`, `limit`, `max_results`) → OOM.
320/// Callers should still apply a sensible upper cap on the result.
321pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
322    get_int(args, key).and_then(|n| usize::try_from(n).ok())
323}
324
325pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
326    args.get(key).and_then(serde_json::Value::as_bool)
327}
328
329pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
330    args.get(key).and_then(serde_json::Value::as_f64)
331}
332
333pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
334    args.get(key).and_then(|v| v.as_array()).map(|arr| {
335        arr.iter()
336            .filter_map(|v| v.as_str().map(String::from))
337            .collect()
338    })
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344    use serde_json::json;
345
346    fn empty_ctx() -> ToolContext {
347        ToolContext::default()
348    }
349
350    #[test]
351    fn require_resolved_path_returns_resolved() {
352        let mut ctx = empty_ctx();
353        ctx.resolved_paths
354            .insert("path".to_string(), "/abs/file.rs".to_string());
355        let args: Map<String, Value> = Map::new();
356        let result = require_resolved_path(&ctx, &args, "path");
357        assert_eq!(result.unwrap(), "/abs/file.rs");
358    }
359
360    #[test]
361    fn require_resolved_path_surfaces_jail_error() {
362        let mut ctx = empty_ctx();
363        ctx.path_errors.insert(
364            "path".to_string(),
365            "path escapes project root /project".to_string(),
366        );
367        let args: Map<String, Value> = Map::new();
368        let result = require_resolved_path(&ctx, &args, "path");
369        assert!(result.is_err());
370        let err = result.unwrap_err();
371        let msg = format!("{err:?}");
372        assert!(msg.contains("escapes project root"), "got: {msg}");
373    }
374
375    #[test]
376    fn require_resolved_path_detects_non_string() {
377        let ctx = empty_ctx();
378        let mut args: Map<String, Value> = Map::new();
379        args.insert("path".to_string(), json!(42));
380        let result = require_resolved_path(&ctx, &args, "path");
381        assert!(result.is_err());
382        let err = result.unwrap_err();
383        let msg = format!("{err:?}");
384        assert!(msg.contains("must be a string, got number"), "got: {msg}");
385    }
386
387    #[test]
388    fn require_resolved_path_missing_param() {
389        let ctx = empty_ctx();
390        let args: Map<String, Value> = Map::new();
391        let result = require_resolved_path(&ctx, &args, "path");
392        assert!(result.is_err());
393        let err = result.unwrap_err();
394        let msg = format!("{err:?}");
395        assert!(msg.contains("path is required"), "got: {msg}");
396    }
397
398    #[test]
399    fn get_int_coerces_string_to_number() {
400        let mut args = Map::new();
401        args.insert("n".into(), json!("42"));
402        assert_eq!(super::get_int(&args, "n"), Some(42));
403    }
404
405    #[test]
406    fn get_int_native_number_still_works() {
407        let mut args = Map::new();
408        args.insert("n".into(), json!(7));
409        assert_eq!(super::get_int(&args, "n"), Some(7));
410    }
411
412    #[test]
413    fn get_int_invalid_string_returns_none() {
414        let mut args = Map::new();
415        args.insert("n".into(), json!("not_a_number"));
416        assert_eq!(super::get_int(&args, "n"), None);
417    }
418
419    #[test]
420    fn get_usize_coerces_string() {
421        let mut args = Map::new();
422        args.insert("n".into(), json!("100"));
423        assert_eq!(super::get_usize(&args, "n"), Some(100));
424    }
425
426    #[test]
427    fn get_usize_negative_string_returns_none() {
428        let mut args = Map::new();
429        args.insert("n".into(), json!("-5"));
430        assert_eq!(super::get_usize(&args, "n"), None);
431    }
432}