1use rmcp::ErrorData;
2use rmcp::model::{ContentBlock, Tool};
3use serde_json::{Map, Value};
4
5#[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct BackgroundLookupError {
49 pub job_id: String,
50 pub code: String,
51 pub reason: String,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum ShellOutcome {
60 Exit(i32),
62 Blocked,
65 Background(BackgroundShellOutcome),
68 BackgroundLookupError(BackgroundLookupError),
70}
71
72impl ShellOutcome {
73 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 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 pub fn is_background_status(&self) -> bool {
136 matches!(
137 self,
138 ShellOutcome::Background(BackgroundShellOutcome {
139 display: Some(_),
140 ..
141 })
142 )
143 }
144}
145
146pub struct ToolOutput {
148 pub text: String,
149 pub original_tokens: usize,
150 pub saved_tokens: usize,
151 pub mode: Option<String>,
152 pub path: Option<String>,
154 pub changed: bool,
157 pub shell_outcome: Option<ShellOutcome>,
161 pub content_blocks: Option<Vec<ContentBlock>>,
164}
165
166impl ToolOutput {
167 pub fn simple(text: String) -> Self {
168 Self {
169 text,
170 original_tokens: 0,
171 saved_tokens: 0,
172 mode: None,
173 path: None,
174 changed: false,
175 shell_outcome: None,
176 content_blocks: None,
177 }
178 }
179
180 pub fn to_header_line(&self, tool_name: &str) -> String {
182 let path_str = self.path.as_deref().unwrap_or("—");
183 let mode_str = self.mode.as_deref().unwrap_or("—");
184 let sent = self.original_tokens.saturating_sub(self.saved_tokens);
185 let pct = if self.original_tokens > 0 {
186 (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
187 } else {
188 0
189 };
190 format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
191 }
192
193 pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
194 Self {
195 text,
196 original_tokens: original,
197 saved_tokens: saved,
198 mode: None,
199 path: None,
200 changed: false,
201 shell_outcome: None,
202 content_blocks: None,
203 }
204 }
205
206 pub fn image(blocks: Vec<ContentBlock>, path: String) -> Self {
209 Self {
210 text: String::new(),
211 original_tokens: 0,
212 saved_tokens: 0,
213 mode: Some("image".to_string()),
214 path: Some(path),
215 changed: false,
216 shell_outcome: None,
217 content_blocks: Some(blocks),
218 }
219 }
220}
221
222pub trait McpTool: Send + Sync {
233 fn name(&self) -> &'static str;
235
236 fn tool_def(&self) -> Tool;
239
240 fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
243 -> Result<ToolOutput, ErrorData>;
244
245 fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
253 false
254 }
255}
256
257#[derive(Clone)]
265pub struct ToolContext {
266 pub project_root: String,
267 pub extra_roots: Vec<String>,
271 pub minimal: bool,
272 pub resolved_paths: std::collections::HashMap<String, String>,
274 pub crp_mode: crate::tools::CrpMode,
276 pub cache: Option<crate::tools::SharedCache>,
278 pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
280 pub tool_calls:
282 Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
283 pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
285 pub workflow:
287 Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
288 pub ledger:
290 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
291 pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
293 pub client_role: Option<String>,
296 pub shell_access: Option<bool>,
299 pub pipeline_stats:
301 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
302 pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
304 pub autonomy: Option<std::sync::Arc<crate::core::autonomy::AutonomyState>>,
306 pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
308 pub path_errors: std::collections::HashMap<String, String>,
311 pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
313 pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
315}
316
317impl Default for ToolContext {
318 fn default() -> Self {
322 Self {
323 project_root: String::new(),
324 extra_roots: Vec::new(),
325 minimal: false,
326 resolved_paths: std::collections::HashMap::new(),
327 crp_mode: crate::tools::CrpMode::Off,
328 cache: None,
329 session: None,
330 tool_calls: None,
331 agent_id: None,
332 workflow: None,
333 ledger: None,
334 client_name: None,
335 client_role: None,
336 shell_access: None,
337 pipeline_stats: None,
338 call_count: None,
339 autonomy: None,
340 pressure_snapshot: None,
341 path_errors: std::collections::HashMap::new(),
342 bm25_cache: None,
343 progress_sender: None,
344 }
345 }
346}
347
348impl ToolContext {
349 pub fn resolved_path(&self, arg: &str) -> Option<&str> {
350 self.resolved_paths.get(arg).map(String::as_str)
351 }
352
353 pub fn path_error(&self, key: &str) -> Option<&str> {
355 self.path_errors.get(key).map(String::as_str)
356 }
357
358 pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
362 crate::core::path_resolve::resolve_tool_path_with_roots(
363 Some(&self.project_root),
364 None,
365 path,
366 &self.extra_roots,
367 )
368 }
369
370 pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
379 crate::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
380 }
381}
382
383pub fn require_resolved_path(
388 ctx: &ToolContext,
389 args: &Map<String, Value>,
390 key: &str,
391) -> Result<String, ErrorData> {
392 if let Some(path) = ctx.resolved_path(key) {
393 return Ok(path.to_string());
394 }
395 if let Some(err) = ctx.path_error(key) {
396 return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
397 }
398 if let Some(val) = args.get(key)
399 && !val.is_string()
400 {
401 let type_name = match val {
402 Value::Number(_) => "number",
403 Value::Bool(_) => "boolean",
404 Value::Array(_) => "array",
405 Value::Object(_) => "object",
406 Value::Null => "null",
407 Value::String(_) => unreachable!(),
408 };
409 return Err(ErrorData::invalid_params(
410 format!("{key} must be a string, got {type_name}"),
411 None,
412 ));
413 }
414 Err(ErrorData::invalid_params(
415 format!("{key} is required"),
416 None,
417 ))
418}
419
420pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
421 args.get(key).and_then(|v| v.as_str()).map(String::from)
422}
423
424pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
425 args.get(key)
426 .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
427}
428
429pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
436 get_int(args, key).and_then(|n| usize::try_from(n).ok())
437}
438
439pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
440 args.get(key).and_then(serde_json::Value::as_bool)
441}
442
443pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
444 args.get(key).and_then(serde_json::Value::as_f64)
445}
446
447pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
448 args.get(key).and_then(|v| v.as_array()).map(|arr| {
449 arr.iter()
450 .filter_map(|v| v.as_str().map(String::from))
451 .collect()
452 })
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458 use serde_json::json;
459
460 fn empty_ctx() -> ToolContext {
461 ToolContext::default()
462 }
463
464 #[test]
465 fn require_resolved_path_returns_resolved() {
466 let mut ctx = empty_ctx();
467 ctx.resolved_paths
468 .insert("path".to_string(), "/abs/file.rs".to_string());
469 let args: Map<String, Value> = Map::new();
470 let result = require_resolved_path(&ctx, &args, "path");
471 assert_eq!(result.unwrap(), "/abs/file.rs");
472 }
473
474 #[test]
475 fn require_resolved_path_surfaces_jail_error() {
476 let mut ctx = empty_ctx();
477 ctx.path_errors.insert(
478 "path".to_string(),
479 "path escapes project root /project".to_string(),
480 );
481 let args: Map<String, Value> = Map::new();
482 let result = require_resolved_path(&ctx, &args, "path");
483 assert!(result.is_err());
484 let err = result.unwrap_err();
485 let msg = format!("{err:?}");
486 assert!(msg.contains("escapes project root"), "got: {msg}");
487 }
488
489 #[test]
490 fn require_resolved_path_detects_non_string() {
491 let ctx = empty_ctx();
492 let mut args: Map<String, Value> = Map::new();
493 args.insert("path".to_string(), json!(42));
494 let result = require_resolved_path(&ctx, &args, "path");
495 assert!(result.is_err());
496 let err = result.unwrap_err();
497 let msg = format!("{err:?}");
498 assert!(msg.contains("must be a string, got number"), "got: {msg}");
499 }
500
501 #[test]
502 fn require_resolved_path_missing_param() {
503 let ctx = empty_ctx();
504 let args: Map<String, Value> = Map::new();
505 let result = require_resolved_path(&ctx, &args, "path");
506 assert!(result.is_err());
507 let err = result.unwrap_err();
508 let msg = format!("{err:?}");
509 assert!(msg.contains("path is required"), "got: {msg}");
510 }
511
512 #[test]
513 fn get_int_coerces_string_to_number() {
514 let mut args = Map::new();
515 args.insert("n".into(), json!("42"));
516 assert_eq!(super::get_int(&args, "n"), Some(42));
517 }
518
519 #[test]
520 fn get_int_native_number_still_works() {
521 let mut args = Map::new();
522 args.insert("n".into(), json!(7));
523 assert_eq!(super::get_int(&args, "n"), Some(7));
524 }
525
526 #[test]
527 fn get_int_invalid_string_returns_none() {
528 let mut args = Map::new();
529 args.insert("n".into(), json!("not_a_number"));
530 assert_eq!(super::get_int(&args, "n"), None);
531 }
532
533 #[test]
534 fn get_usize_coerces_string() {
535 let mut args = Map::new();
536 args.insert("n".into(), json!("100"));
537 assert_eq!(super::get_usize(&args, "n"), Some(100));
538 }
539
540 #[test]
541 fn get_usize_negative_string_returns_none() {
542 let mut args = Map::new();
543 args.insert("n".into(), json!("-5"));
544 assert_eq!(super::get_usize(&args, "n"), None);
545 }
546}