1use rmcp::ErrorData;
2use rmcp::model::{ContentBlock, Tool};
3use serde_json::{Map, Value};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ShellOutcome {
11 Exit(i32),
13 Blocked,
16}
17
18impl ShellOutcome {
19 pub fn is_error(self) -> bool {
21 match self {
22 ShellOutcome::Exit(code) => code != 0,
23 ShellOutcome::Blocked => true,
24 }
25 }
26
27 pub fn structured(self) -> Option<serde_json::Value> {
32 match self {
33 ShellOutcome::Exit(0) => None,
34 ShellOutcome::Exit(code) => Some(serde_json::json!({ "exitCode": code })),
35 ShellOutcome::Blocked => Some(serde_json::json!({ "blocked": true })),
36 }
37 }
38}
39
40pub struct ToolOutput {
42 pub text: String,
43 pub original_tokens: usize,
44 pub saved_tokens: usize,
45 pub mode: Option<String>,
46 pub path: Option<String>,
48 pub changed: bool,
51 pub shell_outcome: Option<ShellOutcome>,
55 pub content_blocks: Option<Vec<ContentBlock>>,
58}
59
60impl ToolOutput {
61 pub fn simple(text: String) -> Self {
62 Self {
63 text,
64 original_tokens: 0,
65 saved_tokens: 0,
66 mode: None,
67 path: None,
68 changed: false,
69 shell_outcome: None,
70 content_blocks: None,
71 }
72 }
73
74 pub fn to_header_line(&self, tool_name: &str) -> String {
76 let path_str = self.path.as_deref().unwrap_or("—");
77 let mode_str = self.mode.as_deref().unwrap_or("—");
78 let sent = self.original_tokens.saturating_sub(self.saved_tokens);
79 let pct = if self.original_tokens > 0 {
80 (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
81 } else {
82 0
83 };
84 format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
85 }
86
87 pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
88 Self {
89 text,
90 original_tokens: original,
91 saved_tokens: saved,
92 mode: None,
93 path: None,
94 changed: false,
95 shell_outcome: None,
96 content_blocks: None,
97 }
98 }
99
100 pub fn image(blocks: Vec<ContentBlock>, path: String) -> Self {
103 Self {
104 text: String::new(),
105 original_tokens: 0,
106 saved_tokens: 0,
107 mode: Some("image".to_string()),
108 path: Some(path),
109 changed: false,
110 shell_outcome: None,
111 content_blocks: Some(blocks),
112 }
113 }
114}
115
116pub trait McpTool: Send + Sync {
127 fn name(&self) -> &'static str;
129
130 fn tool_def(&self) -> Tool;
133
134 fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
137 -> Result<ToolOutput, ErrorData>;
138
139 fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
147 false
148 }
149}
150
151#[derive(Clone)]
159pub struct ToolContext {
160 pub project_root: String,
161 pub extra_roots: Vec<String>,
165 pub minimal: bool,
166 pub resolved_paths: std::collections::HashMap<String, String>,
168 pub crp_mode: crate::tools::CrpMode,
170 pub cache: Option<crate::tools::SharedCache>,
172 pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
174 pub tool_calls:
176 Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
177 pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
179 pub workflow:
181 Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
182 pub ledger:
184 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
185 pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
187 pub pipeline_stats:
189 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
190 pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
192 pub autonomy: Option<std::sync::Arc<crate::core::autonomy::AutonomyState>>,
194 pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
196 pub path_errors: std::collections::HashMap<String, String>,
199 pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
201 pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
203}
204
205impl Default for ToolContext {
206 fn default() -> Self {
210 Self {
211 project_root: String::new(),
212 extra_roots: Vec::new(),
213 minimal: false,
214 resolved_paths: std::collections::HashMap::new(),
215 crp_mode: crate::tools::CrpMode::Off,
216 cache: None,
217 session: None,
218 tool_calls: None,
219 agent_id: None,
220 workflow: None,
221 ledger: None,
222 client_name: None,
223 pipeline_stats: None,
224 call_count: None,
225 autonomy: None,
226 pressure_snapshot: None,
227 path_errors: std::collections::HashMap::new(),
228 bm25_cache: None,
229 progress_sender: None,
230 }
231 }
232}
233
234impl ToolContext {
235 pub fn resolved_path(&self, arg: &str) -> Option<&str> {
236 self.resolved_paths.get(arg).map(String::as_str)
237 }
238
239 pub fn path_error(&self, key: &str) -> Option<&str> {
241 self.path_errors.get(key).map(String::as_str)
242 }
243
244 pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
248 crate::core::path_resolve::resolve_tool_path_with_roots(
249 Some(&self.project_root),
250 None,
251 path,
252 &self.extra_roots,
253 )
254 }
255
256 pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
265 crate::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
266 }
267}
268
269pub fn require_resolved_path(
274 ctx: &ToolContext,
275 args: &Map<String, Value>,
276 key: &str,
277) -> Result<String, ErrorData> {
278 if let Some(path) = ctx.resolved_path(key) {
279 return Ok(path.to_string());
280 }
281 if let Some(err) = ctx.path_error(key) {
282 return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
283 }
284 if let Some(val) = args.get(key)
285 && !val.is_string()
286 {
287 let type_name = match val {
288 Value::Number(_) => "number",
289 Value::Bool(_) => "boolean",
290 Value::Array(_) => "array",
291 Value::Object(_) => "object",
292 Value::Null => "null",
293 Value::String(_) => unreachable!(),
294 };
295 return Err(ErrorData::invalid_params(
296 format!("{key} must be a string, got {type_name}"),
297 None,
298 ));
299 }
300 Err(ErrorData::invalid_params(
301 format!("{key} is required"),
302 None,
303 ))
304}
305
306pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
307 args.get(key).and_then(|v| v.as_str()).map(String::from)
308}
309
310pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
311 args.get(key)
312 .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
313}
314
315pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
322 get_int(args, key).and_then(|n| usize::try_from(n).ok())
323}
324
325pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
326 args.get(key).and_then(serde_json::Value::as_bool)
327}
328
329pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
330 args.get(key).and_then(serde_json::Value::as_f64)
331}
332
333pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
334 args.get(key).and_then(|v| v.as_array()).map(|arr| {
335 arr.iter()
336 .filter_map(|v| v.as_str().map(String::from))
337 .collect()
338 })
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344 use serde_json::json;
345
346 fn empty_ctx() -> ToolContext {
347 ToolContext::default()
348 }
349
350 #[test]
351 fn require_resolved_path_returns_resolved() {
352 let mut ctx = empty_ctx();
353 ctx.resolved_paths
354 .insert("path".to_string(), "/abs/file.rs".to_string());
355 let args: Map<String, Value> = Map::new();
356 let result = require_resolved_path(&ctx, &args, "path");
357 assert_eq!(result.unwrap(), "/abs/file.rs");
358 }
359
360 #[test]
361 fn require_resolved_path_surfaces_jail_error() {
362 let mut ctx = empty_ctx();
363 ctx.path_errors.insert(
364 "path".to_string(),
365 "path escapes project root /project".to_string(),
366 );
367 let args: Map<String, Value> = Map::new();
368 let result = require_resolved_path(&ctx, &args, "path");
369 assert!(result.is_err());
370 let err = result.unwrap_err();
371 let msg = format!("{err:?}");
372 assert!(msg.contains("escapes project root"), "got: {msg}");
373 }
374
375 #[test]
376 fn require_resolved_path_detects_non_string() {
377 let ctx = empty_ctx();
378 let mut args: Map<String, Value> = Map::new();
379 args.insert("path".to_string(), json!(42));
380 let result = require_resolved_path(&ctx, &args, "path");
381 assert!(result.is_err());
382 let err = result.unwrap_err();
383 let msg = format!("{err:?}");
384 assert!(msg.contains("must be a string, got number"), "got: {msg}");
385 }
386
387 #[test]
388 fn require_resolved_path_missing_param() {
389 let ctx = empty_ctx();
390 let args: Map<String, Value> = Map::new();
391 let result = require_resolved_path(&ctx, &args, "path");
392 assert!(result.is_err());
393 let err = result.unwrap_err();
394 let msg = format!("{err:?}");
395 assert!(msg.contains("path is required"), "got: {msg}");
396 }
397
398 #[test]
399 fn get_int_coerces_string_to_number() {
400 let mut args = Map::new();
401 args.insert("n".into(), json!("42"));
402 assert_eq!(super::get_int(&args, "n"), Some(42));
403 }
404
405 #[test]
406 fn get_int_native_number_still_works() {
407 let mut args = Map::new();
408 args.insert("n".into(), json!(7));
409 assert_eq!(super::get_int(&args, "n"), Some(7));
410 }
411
412 #[test]
413 fn get_int_invalid_string_returns_none() {
414 let mut args = Map::new();
415 args.insert("n".into(), json!("not_a_number"));
416 assert_eq!(super::get_int(&args, "n"), None);
417 }
418
419 #[test]
420 fn get_usize_coerces_string() {
421 let mut args = Map::new();
422 args.insert("n".into(), json!("100"));
423 assert_eq!(super::get_usize(&args, "n"), Some(100));
424 }
425
426 #[test]
427 fn get_usize_negative_string_returns_none() {
428 let mut args = Map::new();
429 args.insert("n".into(), json!("-5"));
430 assert_eq!(super::get_usize(&args, "n"), None);
431 }
432}