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
151pub struct ToolContext {
156 pub project_root: String,
157 pub extra_roots: Vec<String>,
161 pub minimal: bool,
162 pub resolved_paths: std::collections::HashMap<String, String>,
164 pub crp_mode: crate::tools::CrpMode,
166 pub cache: Option<crate::tools::SharedCache>,
168 pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
170 pub tool_calls:
172 Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
173 pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
175 pub workflow:
177 Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
178 pub ledger:
180 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
181 pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
183 pub pipeline_stats:
185 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
186 pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
188 pub autonomy: Option<std::sync::Arc<crate::tools::autonomy::AutonomyState>>,
190 pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
192 pub path_errors: std::collections::HashMap<String, String>,
195 pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
197 pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
199}
200
201impl Default for ToolContext {
202 fn default() -> Self {
206 Self {
207 project_root: String::new(),
208 extra_roots: Vec::new(),
209 minimal: false,
210 resolved_paths: std::collections::HashMap::new(),
211 crp_mode: crate::tools::CrpMode::Off,
212 cache: None,
213 session: None,
214 tool_calls: None,
215 agent_id: None,
216 workflow: None,
217 ledger: None,
218 client_name: None,
219 pipeline_stats: None,
220 call_count: None,
221 autonomy: None,
222 pressure_snapshot: None,
223 path_errors: std::collections::HashMap::new(),
224 bm25_cache: None,
225 progress_sender: None,
226 }
227 }
228}
229
230impl ToolContext {
231 pub fn resolved_path(&self, arg: &str) -> Option<&str> {
232 self.resolved_paths.get(arg).map(String::as_str)
233 }
234
235 pub fn path_error(&self, key: &str) -> Option<&str> {
237 self.path_errors.get(key).map(String::as_str)
238 }
239
240 pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
244 crate::core::path_resolve::resolve_tool_path_with_roots(
245 Some(&self.project_root),
246 None,
247 path,
248 &self.extra_roots,
249 )
250 }
251
252 pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
261 crate::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
262 }
263}
264
265pub fn require_resolved_path(
270 ctx: &ToolContext,
271 args: &Map<String, Value>,
272 key: &str,
273) -> Result<String, ErrorData> {
274 if let Some(path) = ctx.resolved_path(key) {
275 return Ok(path.to_string());
276 }
277 if let Some(err) = ctx.path_error(key) {
278 return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
279 }
280 if let Some(val) = args.get(key)
281 && !val.is_string()
282 {
283 let type_name = match val {
284 Value::Number(_) => "number",
285 Value::Bool(_) => "boolean",
286 Value::Array(_) => "array",
287 Value::Object(_) => "object",
288 Value::Null => "null",
289 Value::String(_) => unreachable!(),
290 };
291 return Err(ErrorData::invalid_params(
292 format!("{key} must be a string, got {type_name}"),
293 None,
294 ));
295 }
296 Err(ErrorData::invalid_params(
297 format!("{key} is required"),
298 None,
299 ))
300}
301
302pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
303 args.get(key).and_then(|v| v.as_str()).map(String::from)
304}
305
306pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
307 args.get(key)
308 .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
309}
310
311pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
318 get_int(args, key).and_then(|n| usize::try_from(n).ok())
319}
320
321pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
322 args.get(key).and_then(serde_json::Value::as_bool)
323}
324
325pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
326 args.get(key).and_then(serde_json::Value::as_f64)
327}
328
329pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
330 args.get(key).and_then(|v| v.as_array()).map(|arr| {
331 arr.iter()
332 .filter_map(|v| v.as_str().map(String::from))
333 .collect()
334 })
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340 use serde_json::json;
341
342 fn empty_ctx() -> ToolContext {
343 ToolContext::default()
344 }
345
346 #[test]
347 fn require_resolved_path_returns_resolved() {
348 let mut ctx = empty_ctx();
349 ctx.resolved_paths
350 .insert("path".to_string(), "/abs/file.rs".to_string());
351 let args: Map<String, Value> = Map::new();
352 let result = require_resolved_path(&ctx, &args, "path");
353 assert_eq!(result.unwrap(), "/abs/file.rs");
354 }
355
356 #[test]
357 fn require_resolved_path_surfaces_jail_error() {
358 let mut ctx = empty_ctx();
359 ctx.path_errors.insert(
360 "path".to_string(),
361 "path escapes project root /project".to_string(),
362 );
363 let args: Map<String, Value> = Map::new();
364 let result = require_resolved_path(&ctx, &args, "path");
365 assert!(result.is_err());
366 let err = result.unwrap_err();
367 let msg = format!("{err:?}");
368 assert!(msg.contains("escapes project root"), "got: {msg}");
369 }
370
371 #[test]
372 fn require_resolved_path_detects_non_string() {
373 let ctx = empty_ctx();
374 let mut args: Map<String, Value> = Map::new();
375 args.insert("path".to_string(), json!(42));
376 let result = require_resolved_path(&ctx, &args, "path");
377 assert!(result.is_err());
378 let err = result.unwrap_err();
379 let msg = format!("{err:?}");
380 assert!(msg.contains("must be a string, got number"), "got: {msg}");
381 }
382
383 #[test]
384 fn require_resolved_path_missing_param() {
385 let ctx = empty_ctx();
386 let args: Map<String, Value> = Map::new();
387 let result = require_resolved_path(&ctx, &args, "path");
388 assert!(result.is_err());
389 let err = result.unwrap_err();
390 let msg = format!("{err:?}");
391 assert!(msg.contains("path is required"), "got: {msg}");
392 }
393
394 #[test]
395 fn get_int_coerces_string_to_number() {
396 let mut args = Map::new();
397 args.insert("n".into(), json!("42"));
398 assert_eq!(super::get_int(&args, "n"), Some(42));
399 }
400
401 #[test]
402 fn get_int_native_number_still_works() {
403 let mut args = Map::new();
404 args.insert("n".into(), json!(7));
405 assert_eq!(super::get_int(&args, "n"), Some(7));
406 }
407
408 #[test]
409 fn get_int_invalid_string_returns_none() {
410 let mut args = Map::new();
411 args.insert("n".into(), json!("not_a_number"));
412 assert_eq!(super::get_int(&args, "n"), None);
413 }
414
415 #[test]
416 fn get_usize_coerces_string() {
417 let mut args = Map::new();
418 args.insert("n".into(), json!("100"));
419 assert_eq!(super::get_usize(&args, "n"), Some(100));
420 }
421
422 #[test]
423 fn get_usize_negative_string_returns_none() {
424 let mut args = Map::new();
425 args.insert("n".into(), json!("-5"));
426 assert_eq!(super::get_usize(&args, "n"), None);
427 }
428}