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    pub fn is_terminal_background_status(&self) -> bool {
146        matches!(
147            self,
148            ShellOutcome::Background(BackgroundShellOutcome {
149                state: BackgroundJobState::Completed
150                    | BackgroundJobState::Failed
151                    | BackgroundJobState::Cancelled,
152                display: Some(_),
153                ..
154            })
155        )
156    }
157}
158
159/// Result returned by an McpTool handler.
160pub struct ToolOutput {
161    pub text: String,
162    pub original_tokens: usize,
163    pub saved_tokens: usize,
164    pub mode: Option<String>,
165    /// Path associated with the tool call (for record_call_with_path).
166    pub path: Option<String>,
167    /// True when the tool mutated state that clients should know about
168    /// (e.g. dynamic tool categories changed).
169    pub changed: bool,
170    /// Set by shell-executing tools so dispatch can populate `isError` +
171    /// `structuredContent` on the MCP result (GitHub #389). `None` for tools
172    /// that don't run shell commands.
173    pub shell_outcome: Option<ShellOutcome>,
174    /// Override content blocks for non-text responses (e.g. images).
175    /// When set, dispatch uses these instead of wrapping `text` in TextContent.
176    pub content_blocks: Option<Vec<ContentBlock>>,
177}
178
179impl ToolOutput {
180    pub fn simple(text: String) -> Self {
181        Self {
182            text,
183            original_tokens: 0,
184            saved_tokens: 0,
185            mode: None,
186            path: None,
187            changed: false,
188            shell_outcome: None,
189            content_blocks: None,
190        }
191    }
192
193    /// Compact one-line summary for headers_only response verbosity.
194    pub fn to_header_line(&self, tool_name: &str) -> String {
195        let path_str = self.path.as_deref().unwrap_or("—");
196        let mode_str = self.mode.as_deref().unwrap_or("—");
197        let sent = self.original_tokens.saturating_sub(self.saved_tokens);
198        let pct = if self.original_tokens > 0 {
199            (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
200        } else {
201            0
202        };
203        format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
204    }
205
206    pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
207        Self {
208            text,
209            original_tokens: original,
210            saved_tokens: saved,
211            mode: None,
212            path: None,
213            changed: false,
214            shell_outcome: None,
215            content_blocks: None,
216        }
217    }
218
219    /// Construct a ToolOutput for image/binary content blocks.
220    /// Bypasses all text processing in the dispatch pipeline.
221    pub fn image(blocks: Vec<ContentBlock>, path: String) -> Self {
222        Self {
223            text: String::new(),
224            original_tokens: 0,
225            saved_tokens: 0,
226            mode: Some("image".to_string()),
227            path: Some(path),
228            changed: false,
229            shell_outcome: None,
230            content_blocks: Some(blocks),
231        }
232    }
233}
234
235/// Trait for a self-contained MCP tool. Each tool provides its own schema
236/// definition and handler, eliminating the possibility of schema/handler drift.
237///
238/// This trait is the plugin interface for LcpTools: any implementation can be
239/// registered at runtime via `ToolRegistry::register()`. Future plugin system
240/// will load implementations from shared libraries or subprocess bridges.
241///
242/// Handlers are synchronous because all existing tool handlers are sync.
243/// The async boundary (cache locks, session reads) is handled by the dispatch
244/// layer before calling `handle`.
245pub trait McpTool: Send + Sync {
246    /// Tool name as registered in the MCP protocol (e.g. "ctx_tree").
247    fn name(&self) -> &'static str;
248
249    /// MCP tool definition including JSON schema. This replaces the
250    /// corresponding entry in `granular_tool_defs()`.
251    fn tool_def(&self) -> Tool;
252
253    /// Execute the tool. Args are the raw JSON-RPC arguments.
254    /// `ctx` provides access to resolved paths and project state.
255    fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
256    -> Result<ToolOutput, ErrorData>;
257
258    /// Whether *this* invocation yields a machine-readable payload (e.g. JSON)
259    /// that must reach the client byte-exact and parseable. When `true`, the
260    /// dispatch pipeline suppresses every human-oriented decoration
261    /// (auto-context briefing, verify footer, hints, checkpoints, deprecation
262    /// notices) and terse compression for this call, returning the pure body.
263    /// Keyed on `args` because most tools emit machine-readable output only for
264    /// an opt-in format flag (e.g. `format=json`); defaults to `false` (#990).
265    fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
266        false
267    }
268}
269
270tokio::task_local! {
271    /// #1781: the cancellation token of the request currently being served,
272    /// scoped by `call_tool` around the whole guarded dispatch.
273    ///
274    /// A task-local rather than a field on the shared server: rmcp spawns one
275    /// task per request and hands each its own `child_token`, so concurrent
276    /// calls would otherwise overwrite one another's token — and cancelling the
277    /// wrong command is worse than not cancelling at all.
278    pub static REQUEST_CT: tokio_util::sync::CancellationToken;
279}
280
281/// Context passed to tool handlers. Contains pre-resolved values that
282/// many tools need, avoiding repeated async lock acquisition inside
283/// handlers. Extended with shared server state for tools that need
284/// cache/session access.
285///
286/// `Clone` exists for per-op delegation (#1088): a batch op with its own
287/// `path` clones the ctx and swaps in that op's resolved path.
288#[derive(Clone)]
289pub struct ToolContext {
290    pub project_root: String,
291    /// Session-scoped trusted roots (MCP `roots/list`, config `extra_roots`),
292    /// snapshotted from the session so sync handlers can honor them without an
293    /// async lock. Empty = single-root jail behaviour (#403).
294    pub extra_roots: Vec<String>,
295    pub minimal: bool,
296    /// Pre-resolved paths keyed by argument name (e.g. "path" -> "/abs/dir").
297    pub resolved_paths: std::collections::HashMap<String, String>,
298    /// CRP mode for compression-aware tools.
299    pub crp_mode: crate::tools::CrpMode,
300    /// Shared cache handle for tools that need read/write access.
301    pub cache: Option<crate::tools::SharedCache>,
302    /// Shared session handle for tools that need session access.
303    pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
304    /// Tool call records for session-aware tools (e.g. ctx_session status).
305    pub tool_calls:
306        Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
307    /// Current agent identity for multi-agent tools.
308    pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
309    /// Active workflow run state.
310    pub workflow:
311        Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
312    /// Context ledger for handoff operations.
313    pub ledger:
314        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
315    /// Client name (cursor, claude, etc.).
316    pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
317    /// Optional MCP client role supplied by the session/request context.
318    /// Absent preserves the backward-compatible permissive default.
319    pub client_role: Option<String>,
320    /// Optional shell permission supplied by the session/request context.
321    /// `None` preserves the backward-compatible permissive default.
322    pub shell_access: Option<bool>,
323    /// Pipeline stats for metrics/proof tools.
324    pub pipeline_stats:
325        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
326    /// Global call counter for context tools.
327    pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
328    /// Autonomy state for search repeat detection.
329    pub autonomy: Option<std::sync::Arc<crate::core::autonomy::AutonomyState>>,
330    /// Pre-computed context pressure snapshot for synchronous gate decisions.
331    pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
332    /// Errors from path resolution (PathJail rejection, secret path, etc.).
333    /// Keyed by argument name (e.g. "path" -> "path escapes project root: ...").
334    pub path_errors: std::collections::HashMap<String, String>,
335    /// Shared in-memory BM25 index cache for semantic search.
336    pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
337    /// MCP progress notification sender for long-running operations.
338    pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
339    /// Cancellation token for this request, when the transport supplies one
340    /// (#1781).
341    ///
342    /// A synchronous tool that waits on a child process cannot observe an
343    /// aborted call without it: the host stops waiting, but the wait loop keeps
344    /// running and holds its thread until its own cap expires. Tools that block
345    /// should consult this and return promptly when it fires.
346    pub cancel: Option<tokio_util::sync::CancellationToken>,
347}
348
349impl Default for ToolContext {
350    /// Minimal context: `project_root` empty, all shared-state handles `None`.
351    /// Single source for the one-shot CLI ctx (`cli::call_cmd::oneshot_ctx`) and
352    /// the `empty_ctx` test helper — adding a field no longer breaks either.
353    fn default() -> Self {
354        Self {
355            project_root: String::new(),
356            extra_roots: Vec::new(),
357            minimal: false,
358            resolved_paths: std::collections::HashMap::new(),
359            crp_mode: crate::tools::CrpMode::Off,
360            cache: None,
361            session: None,
362            tool_calls: None,
363            agent_id: None,
364            workflow: None,
365            ledger: None,
366            client_name: None,
367            client_role: None,
368            shell_access: None,
369            pipeline_stats: None,
370            call_count: None,
371            autonomy: None,
372            pressure_snapshot: None,
373            path_errors: std::collections::HashMap::new(),
374            bm25_cache: None,
375            progress_sender: None,
376            cancel: None,
377        }
378    }
379}
380
381impl ToolContext {
382    pub fn resolved_path(&self, arg: &str) -> Option<&str> {
383        self.resolved_paths.get(arg).map(String::as_str)
384    }
385
386    /// Returns the path resolution error for a given key, if any.
387    pub fn path_error(&self, key: &str) -> Option<&str> {
388        self.path_errors.get(key).map(String::as_str)
389    }
390
391    /// Sync path resolution using `project_root` + session `extra_roots`. Thin
392    /// wrapper over [`crate::core::path_resolve::resolve_tool_path_with_roots`]
393    /// for sync tool handlers.
394    pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
395        crate::core::path_resolve::resolve_tool_path_with_roots(
396            Some(&self.project_root),
397            None,
398            path,
399            &self.extra_roots,
400        )
401    }
402
403    /// Default-deny write gate for the read-only tier (#475). Write-capable tool
404    /// handlers must call this with an already-resolved absolute path before
405    /// touching the filesystem; it errors if the path is inside a configured
406    /// `read_only_roots` subtree. A no-op (always `Ok`) when no read-only roots
407    /// are configured, so non-users pay nothing. Thin wrapper over the single
408    /// choke point [`crate::core::pathjail::enforce_writable`] — the low-level
409    /// atomic writers call the same function, so this is the ergonomic,
410    /// early-error layer, not the only line of defence.
411    pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
412        crate::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
413    }
414}
415
416// ── Arg extraction helpers (mirror server/helpers.rs for standalone use) ──
417
418/// Extract a resolved path from context with differentiated error messages.
419/// Returns descriptive errors for: missing param, PathJail rejection, wrong type.
420pub fn require_resolved_path(
421    ctx: &ToolContext,
422    args: &Map<String, Value>,
423    key: &str,
424) -> Result<String, ErrorData> {
425    if let Some(path) = ctx.resolved_path(key) {
426        return Ok(path.to_string());
427    }
428    if let Some(err) = ctx.path_error(key) {
429        return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
430    }
431    if let Some(val) = args.get(key)
432        && !val.is_string()
433    {
434        let type_name = match val {
435            Value::Number(_) => "number",
436            Value::Bool(_) => "boolean",
437            Value::Array(_) => "array",
438            Value::Object(_) => "object",
439            Value::Null => "null",
440            Value::String(_) => unreachable!(),
441        };
442        return Err(ErrorData::invalid_params(
443            format!("{key} must be a string, got {type_name}"),
444            None,
445        ));
446    }
447    Err(ErrorData::invalid_params(
448        format!("{key} is required"),
449        None,
450    ))
451}
452
453pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
454    args.get(key).and_then(|v| v.as_str()).map(String::from)
455}
456
457pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
458    args.get(key)
459        .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
460}
461
462/// Read a non-negative integer argument as `usize`.
463///
464/// Returns `None` for missing or negative values. This avoids the
465/// `negative_i64 as usize` wrap to `usize::MAX`, which previously let an agent
466/// trigger unbounded allocations (e.g. `top_k`, `limit`, `max_results`) → OOM.
467/// Callers should still apply a sensible upper cap on the result.
468pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
469    get_int(args, key).and_then(|n| usize::try_from(n).ok())
470}
471
472pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
473    args.get(key).and_then(serde_json::Value::as_bool)
474}
475
476pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
477    args.get(key).and_then(serde_json::Value::as_f64)
478}
479
480pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
481    args.get(key).and_then(|v| v.as_array()).map(|arr| {
482        arr.iter()
483            .filter_map(|v| v.as_str().map(String::from))
484            .collect()
485    })
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491    use serde_json::json;
492
493    fn empty_ctx() -> ToolContext {
494        ToolContext::default()
495    }
496
497    #[test]
498    fn require_resolved_path_returns_resolved() {
499        let mut ctx = empty_ctx();
500        ctx.resolved_paths
501            .insert("path".to_string(), "/abs/file.rs".to_string());
502        let args: Map<String, Value> = Map::new();
503        let result = require_resolved_path(&ctx, &args, "path");
504        assert_eq!(result.unwrap(), "/abs/file.rs");
505    }
506
507    #[test]
508    fn require_resolved_path_surfaces_jail_error() {
509        let mut ctx = empty_ctx();
510        ctx.path_errors.insert(
511            "path".to_string(),
512            "path escapes project root /project".to_string(),
513        );
514        let args: Map<String, Value> = Map::new();
515        let result = require_resolved_path(&ctx, &args, "path");
516        assert!(result.is_err());
517        let err = result.unwrap_err();
518        let msg = format!("{err:?}");
519        assert!(msg.contains("escapes project root"), "got: {msg}");
520    }
521
522    #[test]
523    fn require_resolved_path_detects_non_string() {
524        let ctx = empty_ctx();
525        let mut args: Map<String, Value> = Map::new();
526        args.insert("path".to_string(), json!(42));
527        let result = require_resolved_path(&ctx, &args, "path");
528        assert!(result.is_err());
529        let err = result.unwrap_err();
530        let msg = format!("{err:?}");
531        assert!(msg.contains("must be a string, got number"), "got: {msg}");
532    }
533
534    #[test]
535    fn require_resolved_path_missing_param() {
536        let ctx = empty_ctx();
537        let args: Map<String, Value> = Map::new();
538        let result = require_resolved_path(&ctx, &args, "path");
539        assert!(result.is_err());
540        let err = result.unwrap_err();
541        let msg = format!("{err:?}");
542        assert!(msg.contains("path is required"), "got: {msg}");
543    }
544
545    #[test]
546    fn get_int_coerces_string_to_number() {
547        let mut args = Map::new();
548        args.insert("n".into(), json!("42"));
549        assert_eq!(super::get_int(&args, "n"), Some(42));
550    }
551
552    #[test]
553    fn get_int_native_number_still_works() {
554        let mut args = Map::new();
555        args.insert("n".into(), json!(7));
556        assert_eq!(super::get_int(&args, "n"), Some(7));
557    }
558
559    #[test]
560    fn get_int_invalid_string_returns_none() {
561        let mut args = Map::new();
562        args.insert("n".into(), json!("not_a_number"));
563        assert_eq!(super::get_int(&args, "n"), None);
564    }
565
566    #[test]
567    fn get_usize_coerces_string() {
568        let mut args = Map::new();
569        args.insert("n".into(), json!("100"));
570        assert_eq!(super::get_usize(&args, "n"), Some(100));
571    }
572
573    #[test]
574    fn get_usize_negative_string_returns_none() {
575        let mut args = Map::new();
576        args.insert("n".into(), json!("-5"));
577        assert_eq!(super::get_usize(&args, "n"), None);
578    }
579}