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