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
300tokio::task_local! {
301 pub static REQUEST_CT: tokio_util::sync::CancellationToken;
309}
310
311#[derive(Clone)]
319pub struct ToolContext {
320 pub project_root: String,
321 pub extra_roots: Vec<String>,
325 pub minimal: bool,
326 pub resolved_paths: std::collections::HashMap<String, String>,
328 pub crp_mode: crate::tools::CrpMode,
330 pub cache: Option<crate::tools::SharedCache>,
332 pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
334 pub tool_calls:
336 Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
337 pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
339 pub workflow:
341 Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
342 pub ledger:
344 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
345 pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
347 pub client_role: Option<String>,
350 pub shell_access: Option<bool>,
353 pub pipeline_stats:
355 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
356 pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
358 pub autonomy: Option<std::sync::Arc<crate::core::autonomy::AutonomyState>>,
360 pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
362 pub path_errors: std::collections::HashMap<String, String>,
365 pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
367 pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
369 pub cancel: Option<tokio_util::sync::CancellationToken>,
377}
378
379impl Default for ToolContext {
380 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 pub fn path_error(&self, key: &str) -> Option<&str> {
418 self.path_errors.get(key).map(String::as_str)
419 }
420
421 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 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
446pub 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
492pub 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}