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