1use rmcp::ErrorData;
3use rmcp::model::{ContentBlock, Tool};
4use serde_json::{Map, Value};
5
6pub const TOOL_EXECUTION_ERROR: rmcp::model::ErrorCode = rmcp::model::ErrorCode(-32071);
10
11pub(crate) fn tool_execution_error(message: String) -> ErrorData {
12 ErrorData::new(TOOL_EXECUTION_ERROR, message, None)
13}
14
15pub const PATH_LIKE_KEYS: &[&str] = &[
17 "path",
18 "project_root",
19 "root",
20 "file",
21 "directory",
22 "dir",
23 "target",
24 "source",
25 "destination",
26 "old_path",
27 "new_path",
28 "file_path",
29 "from",
30 "to",
31 "base_path",
32 "config_path",
33 "output",
34];
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum BackgroundJobState {
39 Running,
40 Completed,
41 Failed,
42 Cancelled,
43}
44
45impl BackgroundJobState {
46 pub fn as_str(self) -> &'static str {
47 match self {
48 Self::Running => "running",
49 Self::Completed => "completed",
50 Self::Failed => "failed",
51 Self::Cancelled => "cancelled",
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct BackgroundDisplay {
58 pub header: String,
59 pub footer: Option<String>,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct BackgroundShellOutcome {
65 pub state: BackgroundJobState,
66 pub exit_code: Option<i32>,
67 pub job_id: String,
68 pub archive_id: Option<String>,
69 pub archive_truncated: Option<bool>,
70 pub captured_chars: Option<usize>,
71 pub archived_chars: Option<usize>,
72 pub summary: String,
73 pub is_error: bool,
74 pub display: Option<BackgroundDisplay>,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct BackgroundLookupError {
80 pub job_id: String,
81 pub code: String,
82 pub reason: String,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum ShellOutcome {
91 Exit(i32),
93 Blocked,
96 Background(BackgroundShellOutcome),
99 BackgroundLookupError(BackgroundLookupError),
101}
102
103impl ShellOutcome {
104 pub fn is_error(&self) -> bool {
106 match self {
107 ShellOutcome::Exit(code) => *code != 0,
108 ShellOutcome::Blocked | ShellOutcome::BackgroundLookupError(_) => true,
109 ShellOutcome::Background(outcome) => outcome.is_error,
110 }
111 }
112
113 pub fn structured(&self) -> Option<serde_json::Value> {
118 match self {
119 ShellOutcome::Exit(0) => None,
120 ShellOutcome::Exit(code) => Some(serde_json::json!({ "exitCode": code })),
121 ShellOutcome::Blocked => Some(serde_json::json!({ "blocked": true })),
122 ShellOutcome::Background(outcome) => {
123 let mut fields = serde_json::Map::new();
124 fields.insert(
125 "state".to_string(),
126 serde_json::json!(outcome.state.as_str()),
127 );
128 fields.insert("jobId".to_string(), serde_json::json!(outcome.job_id));
129 fields.insert("summary".to_string(), serde_json::json!(outcome.summary));
130 if let Some(exit_code) = outcome.exit_code {
131 fields.insert("exitCode".to_string(), serde_json::json!(exit_code));
132 }
133 if let Some(archive_id) = &outcome.archive_id {
134 fields.insert("archiveId".to_string(), serde_json::json!(archive_id));
135 }
136 if let Some(archive_truncated) = outcome.archive_truncated {
137 fields.insert(
138 "archiveTruncated".to_string(),
139 serde_json::json!(archive_truncated),
140 );
141 }
142 if let Some(captured_chars) = outcome.captured_chars {
143 fields.insert(
144 "capturedChars".to_string(),
145 serde_json::json!(captured_chars),
146 );
147 }
148 if let Some(archived_chars) = outcome.archived_chars {
149 fields.insert(
150 "archivedChars".to_string(),
151 serde_json::json!(archived_chars),
152 );
153 }
154 Some(serde_json::Value::Object(fields))
155 }
156 ShellOutcome::BackgroundLookupError(error) => Some(serde_json::json!({
157 "jobId": error.job_id,
158 "errorCode": error.code,
159 "reason": error.reason,
160 })),
161 }
162 }
163
164 pub fn is_background_status(&self) -> bool {
167 matches!(
168 self,
169 ShellOutcome::Background(BackgroundShellOutcome {
170 display: Some(_),
171 ..
172 })
173 )
174 }
175
176 pub fn is_terminal_background_status(&self) -> bool {
177 matches!(
178 self,
179 ShellOutcome::Background(BackgroundShellOutcome {
180 state: BackgroundJobState::Completed
181 | BackgroundJobState::Failed
182 | BackgroundJobState::Cancelled,
183 display: Some(_),
184 ..
185 })
186 )
187 }
188}
189
190pub struct ToolOutput {
192 pub text: String,
193 pub original_tokens: usize,
194 pub saved_tokens: usize,
195 pub mode: Option<String>,
196 pub path: Option<String>,
198 pub changed: bool,
201 pub shell_outcome: Option<ShellOutcome>,
205 pub content_blocks: Option<Vec<ContentBlock>>,
208}
209
210impl ToolOutput {
211 pub fn simple(text: String) -> Self {
212 Self {
213 text,
214 original_tokens: 0,
215 saved_tokens: 0,
216 mode: None,
217 path: None,
218 changed: false,
219 shell_outcome: None,
220 content_blocks: None,
221 }
222 }
223
224 pub fn to_header_line(&self, tool_name: &str) -> String {
226 let path_str = self.path.as_deref().unwrap_or("—");
227 let mode_str = self.mode.as_deref().unwrap_or("—");
228 let sent = self.original_tokens.saturating_sub(self.saved_tokens);
229 let pct = if self.original_tokens > 0 {
230 (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
231 } else {
232 0
233 };
234 format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
235 }
236
237 pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
238 Self {
239 text,
240 original_tokens: original,
241 saved_tokens: saved,
242 mode: None,
243 path: None,
244 changed: false,
245 shell_outcome: None,
246 content_blocks: None,
247 }
248 }
249
250 pub fn image(blocks: Vec<ContentBlock>, path: String) -> Self {
253 Self {
254 text: String::new(),
255 original_tokens: 0,
256 saved_tokens: 0,
257 mode: Some("image".to_string()),
258 path: Some(path),
259 changed: false,
260 shell_outcome: None,
261 content_blocks: Some(blocks),
262 }
263 }
264}
265
266pub trait McpTool: Send + Sync {
277 fn name(&self) -> &'static str;
279
280 fn rights_name(&self) -> &'static str {
284 self.name()
285 }
286
287 fn tool_def(&self) -> Tool;
290
291 fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
294 -> Result<ToolOutput, ErrorData>;
295
296 fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
304 false
305 }
306
307 fn attests_source_free(&self, _args: Option<&Map<String, Value>>) -> bool {
315 false
316 }
317
318 fn publishes_every_source(&self, _args: Option<&Map<String, Value>>) -> bool {
331 false
332 }
333}
334
335tokio::task_local! {
336 pub static REQUEST_CT: tokio_util::sync::CancellationToken;
344
345 pub static REQUEST_PROGRESS: Option<crate::server::progress::ProgressSender>;
355}
356
357#[derive(Clone)]
365pub struct ToolContext {
366 pub project_root: String,
367 pub extra_roots: Vec<String>,
371 pub minimal: bool,
372 pub resolved_paths: std::collections::HashMap<String, String>,
374 pub crp_mode: crate::tools::CrpMode,
376 pub cache: Option<crate::tools::SharedCache>,
378 pub session: Option<std::sync::Arc<tokio::sync::RwLock<lean_ctx::core::session::SessionState>>>,
380 pub tool_calls:
382 Option<std::sync::Arc<tokio::sync::RwLock<Vec<lean_ctx::core::protocol::ToolCallRecord>>>>,
383 pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
385 pub workflow:
387 Option<std::sync::Arc<tokio::sync::RwLock<Option<lean_ctx::core::workflow::WorkflowRun>>>>,
388 pub ledger:
390 Option<std::sync::Arc<tokio::sync::RwLock<lean_ctx::core::context_ledger::ContextLedger>>>,
391 pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
393 pub client_role: Option<String>,
396 pub shell_access: Option<bool>,
399 pub pipeline_stats:
401 Option<std::sync::Arc<tokio::sync::RwLock<lean_ctx::core::pipeline::PipelineStats>>>,
402 pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
404 pub autonomy: Option<std::sync::Arc<lean_ctx_ext::core::autonomy::AutonomyState>>,
406 pub path_errors: std::collections::HashMap<String, String>,
409 pub bm25_cache: Option<lean_ctx::core::bm25_cache::SharedBm25Cache>,
411 pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
413 pub cancel: Option<tokio_util::sync::CancellationToken>,
421}
422
423impl Default for ToolContext {
424 fn default() -> Self {
428 Self {
429 project_root: String::new(),
430 extra_roots: Vec::new(),
431 minimal: false,
432 resolved_paths: std::collections::HashMap::new(),
433 crp_mode: crate::tools::CrpMode::Off,
434 cache: None,
435 session: None,
436 tool_calls: None,
437 agent_id: None,
438 workflow: None,
439 ledger: None,
440 client_name: None,
441 client_role: None,
442 shell_access: None,
443 pipeline_stats: None,
444 call_count: None,
445 autonomy: None,
446 path_errors: std::collections::HashMap::new(),
447 bm25_cache: None,
448 progress_sender: None,
449 cancel: None,
450 }
451 }
452}
453
454impl ToolContext {
455 pub fn resolved_path(&self, arg: &str) -> Option<&str> {
456 self.resolved_paths.get(arg).map(String::as_str)
457 }
458
459 pub fn path_error(&self, key: &str) -> Option<&str> {
461 self.path_errors.get(key).map(String::as_str)
462 }
463
464 pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
468 lean_ctx::core::path_resolve::resolve_tool_path_with_roots(
469 Some(&self.project_root),
470 None,
471 path,
472 &self.extra_roots,
473 )
474 }
475
476 pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
485 lean_ctx::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
486 }
487}
488
489pub fn require_resolved_path(
494 ctx: &ToolContext,
495 args: &Map<String, Value>,
496 key: &str,
497) -> Result<String, ErrorData> {
498 if let Some(path) = ctx.resolved_path(key) {
499 return Ok(path.to_string());
500 }
501 if let Some(err) = ctx.path_error(key) {
502 return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
503 }
504 if let Some(val) = args.get(key)
505 && !val.is_string()
506 {
507 let type_name = match val {
508 Value::Number(_) => "number",
509 Value::Bool(_) => "boolean",
510 Value::Array(_) => "array",
511 Value::Object(_) => "object",
512 Value::Null => "null",
513 Value::String(_) => unreachable!(),
514 };
515 return Err(ErrorData::invalid_params(
516 format!("{key} must be a string, got {type_name}"),
517 None,
518 ));
519 }
520 Err(ErrorData::invalid_params(
521 format!("{key} is required"),
522 None,
523 ))
524}
525
526pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
527 args.get(key).and_then(|v| v.as_str()).map(String::from)
528}
529
530pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
531 args.get(key)
532 .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
533}
534
535pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
542 get_int(args, key).and_then(|n| usize::try_from(n).ok())
543}
544
545pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
546 args.get(key).and_then(serde_json::Value::as_bool)
547}
548
549pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
550 args.get(key).and_then(serde_json::Value::as_f64)
551}
552
553pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
554 args.get(key).and_then(|v| v.as_array()).map(|arr| {
555 arr.iter()
556 .filter_map(|v| v.as_str().map(String::from))
557 .collect()
558 })
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564 use serde_json::json;
565
566 fn empty_ctx() -> ToolContext {
567 ToolContext::default()
568 }
569
570 #[test]
571 fn require_resolved_path_returns_resolved() {
572 let mut ctx = empty_ctx();
573 ctx.resolved_paths
574 .insert("path".to_string(), "/abs/file.rs".to_string());
575 let args: Map<String, Value> = Map::new();
576 let result = require_resolved_path(&ctx, &args, "path");
577 assert_eq!(result.unwrap(), "/abs/file.rs");
578 }
579
580 #[test]
581 fn require_resolved_path_surfaces_jail_error() {
582 let mut ctx = empty_ctx();
583 ctx.path_errors.insert(
584 "path".to_string(),
585 "path escapes project root /project".to_string(),
586 );
587 let args: Map<String, Value> = Map::new();
588 let result = require_resolved_path(&ctx, &args, "path");
589 assert!(result.is_err());
590 let err = result.unwrap_err();
591 let msg = format!("{err:?}");
592 assert!(msg.contains("escapes project root"), "got: {msg}");
593 }
594
595 #[test]
596 fn require_resolved_path_detects_non_string() {
597 let ctx = empty_ctx();
598 let mut args: Map<String, Value> = Map::new();
599 args.insert("path".to_string(), json!(42));
600 let result = require_resolved_path(&ctx, &args, "path");
601 assert!(result.is_err());
602 let err = result.unwrap_err();
603 let msg = format!("{err:?}");
604 assert!(msg.contains("must be a string, got number"), "got: {msg}");
605 }
606
607 #[test]
608 fn require_resolved_path_missing_param() {
609 let ctx = empty_ctx();
610 let args: Map<String, Value> = Map::new();
611 let result = require_resolved_path(&ctx, &args, "path");
612 assert!(result.is_err());
613 let err = result.unwrap_err();
614 let msg = format!("{err:?}");
615 assert!(msg.contains("path is required"), "got: {msg}");
616 }
617
618 #[test]
619 fn get_int_coerces_string_to_number() {
620 let mut args = Map::new();
621 args.insert("n".into(), json!("42"));
622 assert_eq!(super::get_int(&args, "n"), Some(42));
623 }
624
625 #[test]
626 fn get_int_native_number_still_works() {
627 let mut args = Map::new();
628 args.insert("n".into(), json!(7));
629 assert_eq!(super::get_int(&args, "n"), Some(7));
630 }
631
632 #[test]
633 fn get_int_invalid_string_returns_none() {
634 let mut args = Map::new();
635 args.insert("n".into(), json!("not_a_number"));
636 assert_eq!(super::get_int(&args, "n"), None);
637 }
638
639 #[test]
640 fn get_usize_coerces_string() {
641 let mut args = Map::new();
642 args.insert("n".into(), json!("100"));
643 assert_eq!(super::get_usize(&args, "n"), Some(100));
644 }
645
646 #[test]
647 fn get_usize_negative_string_returns_none() {
648 let mut args = Map::new();
649 args.insert("n".into(), json!("-5"));
650 assert_eq!(super::get_usize(&args, "n"), None);
651 }
652}