1use rmcp::ErrorData;
2use rmcp::model::{ContentBlock, Tool};
3use serde_json::{Map, Value};
4
5pub(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
14pub 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#[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct BackgroundLookupError {
79 pub job_id: String,
80 pub code: String,
81 pub reason: String,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum ShellOutcome {
90 Exit(i32),
92 Blocked,
95 Background(BackgroundShellOutcome),
98 BackgroundLookupError(BackgroundLookupError),
100}
101
102impl ShellOutcome {
103 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 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 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
189pub struct ToolOutput {
191 pub text: String,
192 pub original_tokens: usize,
193 pub saved_tokens: usize,
194 pub mode: Option<String>,
195 pub path: Option<String>,
197 pub changed: bool,
200 pub shell_outcome: Option<ShellOutcome>,
204 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 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 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
265pub trait McpTool: Send + Sync {
276 fn name(&self) -> &'static str;
278
279 fn tool_def(&self) -> Tool;
282
283 fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
286 -> Result<ToolOutput, ErrorData>;
287
288 fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
296 false
297 }
298
299 fn attests_source_free(&self, _args: Option<&Map<String, Value>>) -> bool {
307 false
308 }
309
310 fn publishes_every_source(&self, _args: Option<&Map<String, Value>>) -> bool {
323 false
324 }
325}
326
327tokio::task_local! {
328 pub static REQUEST_CT: tokio_util::sync::CancellationToken;
336}
337
338#[derive(Clone)]
346pub struct ToolContext {
347 pub project_root: String,
348 pub extra_roots: Vec<String>,
352 pub minimal: bool,
353 pub resolved_paths: std::collections::HashMap<String, String>,
355 pub crp_mode: crate::tools::CrpMode,
357 pub cache: Option<crate::tools::SharedCache>,
359 pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
361 pub tool_calls:
363 Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
364 pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
366 pub workflow:
368 Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
369 pub ledger:
371 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
372 pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
374 pub client_role: Option<String>,
377 pub shell_access: Option<bool>,
380 pub pipeline_stats:
382 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
383 pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
385 pub autonomy: Option<std::sync::Arc<crate::core::autonomy::AutonomyState>>,
387 pub path_errors: std::collections::HashMap<String, String>,
390 pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
392 pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
394 pub cancel: Option<tokio_util::sync::CancellationToken>,
402}
403
404impl Default for ToolContext {
405 fn default() -> Self {
409 Self {
410 project_root: String::new(),
411 extra_roots: Vec::new(),
412 minimal: false,
413 resolved_paths: std::collections::HashMap::new(),
414 crp_mode: crate::tools::CrpMode::Off,
415 cache: None,
416 session: None,
417 tool_calls: None,
418 agent_id: None,
419 workflow: None,
420 ledger: None,
421 client_name: None,
422 client_role: None,
423 shell_access: None,
424 pipeline_stats: None,
425 call_count: None,
426 autonomy: None,
427 path_errors: std::collections::HashMap::new(),
428 bm25_cache: None,
429 progress_sender: None,
430 cancel: None,
431 }
432 }
433}
434
435impl ToolContext {
436 pub fn resolved_path(&self, arg: &str) -> Option<&str> {
437 self.resolved_paths.get(arg).map(String::as_str)
438 }
439
440 pub fn path_error(&self, key: &str) -> Option<&str> {
442 self.path_errors.get(key).map(String::as_str)
443 }
444
445 pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
449 crate::core::path_resolve::resolve_tool_path_with_roots(
450 Some(&self.project_root),
451 None,
452 path,
453 &self.extra_roots,
454 )
455 }
456
457 pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
466 crate::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
467 }
468}
469
470pub fn require_resolved_path(
475 ctx: &ToolContext,
476 args: &Map<String, Value>,
477 key: &str,
478) -> Result<String, ErrorData> {
479 if let Some(path) = ctx.resolved_path(key) {
480 return Ok(path.to_string());
481 }
482 if let Some(err) = ctx.path_error(key) {
483 return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
484 }
485 if let Some(val) = args.get(key)
486 && !val.is_string()
487 {
488 let type_name = match val {
489 Value::Number(_) => "number",
490 Value::Bool(_) => "boolean",
491 Value::Array(_) => "array",
492 Value::Object(_) => "object",
493 Value::Null => "null",
494 Value::String(_) => unreachable!(),
495 };
496 return Err(ErrorData::invalid_params(
497 format!("{key} must be a string, got {type_name}"),
498 None,
499 ));
500 }
501 Err(ErrorData::invalid_params(
502 format!("{key} is required"),
503 None,
504 ))
505}
506
507pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
508 args.get(key).and_then(|v| v.as_str()).map(String::from)
509}
510
511pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
512 args.get(key)
513 .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
514}
515
516pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
523 get_int(args, key).and_then(|n| usize::try_from(n).ok())
524}
525
526pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
527 args.get(key).and_then(serde_json::Value::as_bool)
528}
529
530pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
531 args.get(key).and_then(serde_json::Value::as_f64)
532}
533
534pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
535 args.get(key).and_then(|v| v.as_array()).map(|arr| {
536 arr.iter()
537 .filter_map(|v| v.as_str().map(String::from))
538 .collect()
539 })
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545 use serde_json::json;
546
547 fn empty_ctx() -> ToolContext {
548 ToolContext::default()
549 }
550
551 #[test]
552 fn require_resolved_path_returns_resolved() {
553 let mut ctx = empty_ctx();
554 ctx.resolved_paths
555 .insert("path".to_string(), "/abs/file.rs".to_string());
556 let args: Map<String, Value> = Map::new();
557 let result = require_resolved_path(&ctx, &args, "path");
558 assert_eq!(result.unwrap(), "/abs/file.rs");
559 }
560
561 #[test]
562 fn require_resolved_path_surfaces_jail_error() {
563 let mut ctx = empty_ctx();
564 ctx.path_errors.insert(
565 "path".to_string(),
566 "path escapes project root /project".to_string(),
567 );
568 let args: Map<String, Value> = Map::new();
569 let result = require_resolved_path(&ctx, &args, "path");
570 assert!(result.is_err());
571 let err = result.unwrap_err();
572 let msg = format!("{err:?}");
573 assert!(msg.contains("escapes project root"), "got: {msg}");
574 }
575
576 #[test]
577 fn require_resolved_path_detects_non_string() {
578 let ctx = empty_ctx();
579 let mut args: Map<String, Value> = Map::new();
580 args.insert("path".to_string(), json!(42));
581 let result = require_resolved_path(&ctx, &args, "path");
582 assert!(result.is_err());
583 let err = result.unwrap_err();
584 let msg = format!("{err:?}");
585 assert!(msg.contains("must be a string, got number"), "got: {msg}");
586 }
587
588 #[test]
589 fn require_resolved_path_missing_param() {
590 let ctx = empty_ctx();
591 let args: Map<String, Value> = Map::new();
592 let result = require_resolved_path(&ctx, &args, "path");
593 assert!(result.is_err());
594 let err = result.unwrap_err();
595 let msg = format!("{err:?}");
596 assert!(msg.contains("path is required"), "got: {msg}");
597 }
598
599 #[test]
600 fn get_int_coerces_string_to_number() {
601 let mut args = Map::new();
602 args.insert("n".into(), json!("42"));
603 assert_eq!(super::get_int(&args, "n"), Some(42));
604 }
605
606 #[test]
607 fn get_int_native_number_still_works() {
608 let mut args = Map::new();
609 args.insert("n".into(), json!(7));
610 assert_eq!(super::get_int(&args, "n"), Some(7));
611 }
612
613 #[test]
614 fn get_int_invalid_string_returns_none() {
615 let mut args = Map::new();
616 args.insert("n".into(), json!("not_a_number"));
617 assert_eq!(super::get_int(&args, "n"), None);
618 }
619
620 #[test]
621 fn get_usize_coerces_string() {
622 let mut args = Map::new();
623 args.insert("n".into(), json!("100"));
624 assert_eq!(super::get_usize(&args, "n"), Some(100));
625 }
626
627 #[test]
628 fn get_usize_negative_string_returns_none() {
629 let mut args = Map::new();
630 args.insert("n".into(), json!("-5"));
631 assert_eq!(super::get_usize(&args, "n"), None);
632 }
633}