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 pub fn is_terminal_background_status(&self) -> bool {
146 matches!(
147 self,
148 ShellOutcome::Background(BackgroundShellOutcome {
149 state: BackgroundJobState::Completed
150 | BackgroundJobState::Failed
151 | BackgroundJobState::Cancelled,
152 display: Some(_),
153 ..
154 })
155 )
156 }
157}
158
159pub struct ToolOutput {
161 pub text: String,
162 pub original_tokens: usize,
163 pub saved_tokens: usize,
164 pub mode: Option<String>,
165 pub path: Option<String>,
167 pub changed: bool,
170 pub shell_outcome: Option<ShellOutcome>,
174 pub content_blocks: Option<Vec<ContentBlock>>,
177}
178
179impl ToolOutput {
180 pub fn simple(text: String) -> Self {
181 Self {
182 text,
183 original_tokens: 0,
184 saved_tokens: 0,
185 mode: None,
186 path: None,
187 changed: false,
188 shell_outcome: None,
189 content_blocks: None,
190 }
191 }
192
193 pub fn to_header_line(&self, tool_name: &str) -> String {
195 let path_str = self.path.as_deref().unwrap_or("—");
196 let mode_str = self.mode.as_deref().unwrap_or("—");
197 let sent = self.original_tokens.saturating_sub(self.saved_tokens);
198 let pct = if self.original_tokens > 0 {
199 (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
200 } else {
201 0
202 };
203 format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
204 }
205
206 pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
207 Self {
208 text,
209 original_tokens: original,
210 saved_tokens: saved,
211 mode: None,
212 path: None,
213 changed: false,
214 shell_outcome: None,
215 content_blocks: None,
216 }
217 }
218
219 pub fn image(blocks: Vec<ContentBlock>, path: String) -> Self {
222 Self {
223 text: String::new(),
224 original_tokens: 0,
225 saved_tokens: 0,
226 mode: Some("image".to_string()),
227 path: Some(path),
228 changed: false,
229 shell_outcome: None,
230 content_blocks: Some(blocks),
231 }
232 }
233}
234
235pub trait McpTool: Send + Sync {
246 fn name(&self) -> &'static str;
248
249 fn tool_def(&self) -> Tool;
252
253 fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
256 -> Result<ToolOutput, ErrorData>;
257
258 fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
266 false
267 }
268}
269
270tokio::task_local! {
271 pub static REQUEST_CT: tokio_util::sync::CancellationToken;
279}
280
281#[derive(Clone)]
289pub struct ToolContext {
290 pub project_root: String,
291 pub extra_roots: Vec<String>,
295 pub minimal: bool,
296 pub resolved_paths: std::collections::HashMap<String, String>,
298 pub crp_mode: crate::tools::CrpMode,
300 pub cache: Option<crate::tools::SharedCache>,
302 pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
304 pub tool_calls:
306 Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
307 pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
309 pub workflow:
311 Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
312 pub ledger:
314 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
315 pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
317 pub client_role: Option<String>,
320 pub shell_access: Option<bool>,
323 pub pipeline_stats:
325 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
326 pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
328 pub autonomy: Option<std::sync::Arc<crate::core::autonomy::AutonomyState>>,
330 pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
332 pub path_errors: std::collections::HashMap<String, String>,
335 pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
337 pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
339 pub cancel: Option<tokio_util::sync::CancellationToken>,
347}
348
349impl Default for ToolContext {
350 fn default() -> Self {
354 Self {
355 project_root: String::new(),
356 extra_roots: Vec::new(),
357 minimal: false,
358 resolved_paths: std::collections::HashMap::new(),
359 crp_mode: crate::tools::CrpMode::Off,
360 cache: None,
361 session: None,
362 tool_calls: None,
363 agent_id: None,
364 workflow: None,
365 ledger: None,
366 client_name: None,
367 client_role: None,
368 shell_access: None,
369 pipeline_stats: None,
370 call_count: None,
371 autonomy: None,
372 pressure_snapshot: None,
373 path_errors: std::collections::HashMap::new(),
374 bm25_cache: None,
375 progress_sender: None,
376 cancel: None,
377 }
378 }
379}
380
381impl ToolContext {
382 pub fn resolved_path(&self, arg: &str) -> Option<&str> {
383 self.resolved_paths.get(arg).map(String::as_str)
384 }
385
386 pub fn path_error(&self, key: &str) -> Option<&str> {
388 self.path_errors.get(key).map(String::as_str)
389 }
390
391 pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
395 crate::core::path_resolve::resolve_tool_path_with_roots(
396 Some(&self.project_root),
397 None,
398 path,
399 &self.extra_roots,
400 )
401 }
402
403 pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
412 crate::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
413 }
414}
415
416pub fn require_resolved_path(
421 ctx: &ToolContext,
422 args: &Map<String, Value>,
423 key: &str,
424) -> Result<String, ErrorData> {
425 if let Some(path) = ctx.resolved_path(key) {
426 return Ok(path.to_string());
427 }
428 if let Some(err) = ctx.path_error(key) {
429 return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
430 }
431 if let Some(val) = args.get(key)
432 && !val.is_string()
433 {
434 let type_name = match val {
435 Value::Number(_) => "number",
436 Value::Bool(_) => "boolean",
437 Value::Array(_) => "array",
438 Value::Object(_) => "object",
439 Value::Null => "null",
440 Value::String(_) => unreachable!(),
441 };
442 return Err(ErrorData::invalid_params(
443 format!("{key} must be a string, got {type_name}"),
444 None,
445 ));
446 }
447 Err(ErrorData::invalid_params(
448 format!("{key} is required"),
449 None,
450 ))
451}
452
453pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
454 args.get(key).and_then(|v| v.as_str()).map(String::from)
455}
456
457pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
458 args.get(key)
459 .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
460}
461
462pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
469 get_int(args, key).and_then(|n| usize::try_from(n).ok())
470}
471
472pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
473 args.get(key).and_then(serde_json::Value::as_bool)
474}
475
476pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
477 args.get(key).and_then(serde_json::Value::as_f64)
478}
479
480pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
481 args.get(key).and_then(|v| v.as_array()).map(|arr| {
482 arr.iter()
483 .filter_map(|v| v.as_str().map(String::from))
484 .collect()
485 })
486}
487
488#[cfg(test)]
489mod tests {
490 use super::*;
491 use serde_json::json;
492
493 fn empty_ctx() -> ToolContext {
494 ToolContext::default()
495 }
496
497 #[test]
498 fn require_resolved_path_returns_resolved() {
499 let mut ctx = empty_ctx();
500 ctx.resolved_paths
501 .insert("path".to_string(), "/abs/file.rs".to_string());
502 let args: Map<String, Value> = Map::new();
503 let result = require_resolved_path(&ctx, &args, "path");
504 assert_eq!(result.unwrap(), "/abs/file.rs");
505 }
506
507 #[test]
508 fn require_resolved_path_surfaces_jail_error() {
509 let mut ctx = empty_ctx();
510 ctx.path_errors.insert(
511 "path".to_string(),
512 "path escapes project root /project".to_string(),
513 );
514 let args: Map<String, Value> = Map::new();
515 let result = require_resolved_path(&ctx, &args, "path");
516 assert!(result.is_err());
517 let err = result.unwrap_err();
518 let msg = format!("{err:?}");
519 assert!(msg.contains("escapes project root"), "got: {msg}");
520 }
521
522 #[test]
523 fn require_resolved_path_detects_non_string() {
524 let ctx = empty_ctx();
525 let mut args: Map<String, Value> = Map::new();
526 args.insert("path".to_string(), json!(42));
527 let result = require_resolved_path(&ctx, &args, "path");
528 assert!(result.is_err());
529 let err = result.unwrap_err();
530 let msg = format!("{err:?}");
531 assert!(msg.contains("must be a string, got number"), "got: {msg}");
532 }
533
534 #[test]
535 fn require_resolved_path_missing_param() {
536 let ctx = empty_ctx();
537 let args: Map<String, Value> = Map::new();
538 let result = require_resolved_path(&ctx, &args, "path");
539 assert!(result.is_err());
540 let err = result.unwrap_err();
541 let msg = format!("{err:?}");
542 assert!(msg.contains("path is required"), "got: {msg}");
543 }
544
545 #[test]
546 fn get_int_coerces_string_to_number() {
547 let mut args = Map::new();
548 args.insert("n".into(), json!("42"));
549 assert_eq!(super::get_int(&args, "n"), Some(42));
550 }
551
552 #[test]
553 fn get_int_native_number_still_works() {
554 let mut args = Map::new();
555 args.insert("n".into(), json!(7));
556 assert_eq!(super::get_int(&args, "n"), Some(7));
557 }
558
559 #[test]
560 fn get_int_invalid_string_returns_none() {
561 let mut args = Map::new();
562 args.insert("n".into(), json!("not_a_number"));
563 assert_eq!(super::get_int(&args, "n"), None);
564 }
565
566 #[test]
567 fn get_usize_coerces_string() {
568 let mut args = Map::new();
569 args.insert("n".into(), json!("100"));
570 assert_eq!(super::get_usize(&args, "n"), Some(100));
571 }
572
573 #[test]
574 fn get_usize_negative_string_returns_none() {
575 let mut args = Map::new();
576 args.insert("n".into(), json!("-5"));
577 assert_eq!(super::get_usize(&args, "n"), None);
578 }
579}