1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{Map, Value};
4
5pub struct ToolOutput {
7 pub text: String,
8 pub original_tokens: usize,
9 pub saved_tokens: usize,
10 pub mode: Option<String>,
11 pub path: Option<String>,
13 pub changed: bool,
16}
17
18impl ToolOutput {
19 pub fn simple(text: String) -> Self {
20 Self {
21 text,
22 original_tokens: 0,
23 saved_tokens: 0,
24 mode: None,
25 path: None,
26 changed: false,
27 }
28 }
29
30 pub fn to_header_line(&self, tool_name: &str) -> String {
32 let path_str = self.path.as_deref().unwrap_or("—");
33 let mode_str = self.mode.as_deref().unwrap_or("—");
34 let sent = self.original_tokens.saturating_sub(self.saved_tokens);
35 let pct = if self.original_tokens > 0 {
36 (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
37 } else {
38 0
39 };
40 format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
41 }
42
43 pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
44 Self {
45 text,
46 original_tokens: original,
47 saved_tokens: saved,
48 mode: None,
49 path: None,
50 changed: false,
51 }
52 }
53}
54
55pub trait McpTool: Send + Sync {
66 fn name(&self) -> &'static str;
68
69 fn tool_def(&self) -> Tool;
72
73 fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
76 -> Result<ToolOutput, ErrorData>;
77}
78
79pub struct ToolContext {
84 pub project_root: String,
85 pub minimal: bool,
86 pub resolved_paths: std::collections::HashMap<String, String>,
88 pub crp_mode: crate::tools::CrpMode,
90 pub cache: Option<crate::tools::SharedCache>,
92 pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
94 pub tool_calls:
96 Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
97 pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
99 pub workflow:
101 Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
102 pub ledger:
104 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
105 pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
107 pub pipeline_stats:
109 Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
110 pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
112 pub autonomy: Option<std::sync::Arc<crate::tools::autonomy::AutonomyState>>,
114 pub pressure_snapshot: Option<crate::core::context_ledger::ContextPressure>,
116 pub path_errors: std::collections::HashMap<String, String>,
119 pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
121 pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
123}
124
125impl ToolContext {
126 pub fn resolved_path(&self, arg: &str) -> Option<&str> {
127 self.resolved_paths.get(arg).map(String::as_str)
128 }
129
130 pub fn path_error(&self, key: &str) -> Option<&str> {
132 self.path_errors.get(key).map(String::as_str)
133 }
134
135 pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
138 crate::core::path_resolve::resolve_tool_path(Some(&self.project_root), None, path)
139 }
140}
141
142pub fn require_resolved_path(
147 ctx: &ToolContext,
148 args: &Map<String, Value>,
149 key: &str,
150) -> Result<String, ErrorData> {
151 if let Some(path) = ctx.resolved_path(key) {
152 return Ok(path.to_string());
153 }
154 if let Some(err) = ctx.path_error(key) {
155 return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
156 }
157 if let Some(val) = args.get(key) {
158 if !val.is_string() {
159 let type_name = match val {
160 Value::Number(_) => "number",
161 Value::Bool(_) => "boolean",
162 Value::Array(_) => "array",
163 Value::Object(_) => "object",
164 Value::Null => "null",
165 Value::String(_) => unreachable!(),
166 };
167 return Err(ErrorData::invalid_params(
168 format!("{key} must be a string, got {type_name}"),
169 None,
170 ));
171 }
172 }
173 Err(ErrorData::invalid_params(
174 format!("{key} is required"),
175 None,
176 ))
177}
178
179pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
180 args.get(key).and_then(|v| v.as_str()).map(String::from)
181}
182
183pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
184 args.get(key).and_then(serde_json::Value::as_i64)
185}
186
187pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
188 args.get(key).and_then(serde_json::Value::as_bool)
189}
190
191pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
192 args.get(key).and_then(|v| v.as_array()).map(|arr| {
193 arr.iter()
194 .filter_map(|v| v.as_str().map(String::from))
195 .collect()
196 })
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202 use serde_json::json;
203
204 fn empty_ctx() -> ToolContext {
205 ToolContext {
206 project_root: String::new(),
207 minimal: false,
208 resolved_paths: std::collections::HashMap::new(),
209 crp_mode: crate::tools::CrpMode::Off,
210 cache: None,
211 session: None,
212 tool_calls: None,
213 agent_id: None,
214 workflow: None,
215 ledger: None,
216 client_name: None,
217 pipeline_stats: None,
218 call_count: None,
219 autonomy: None,
220 pressure_snapshot: None,
221 path_errors: std::collections::HashMap::new(),
222 bm25_cache: None,
223 progress_sender: None,
224 }
225 }
226
227 #[test]
228 fn require_resolved_path_returns_resolved() {
229 let mut ctx = empty_ctx();
230 ctx.resolved_paths
231 .insert("path".to_string(), "/abs/file.rs".to_string());
232 let args: Map<String, Value> = Map::new();
233 let result = require_resolved_path(&ctx, &args, "path");
234 assert_eq!(result.unwrap(), "/abs/file.rs");
235 }
236
237 #[test]
238 fn require_resolved_path_surfaces_jail_error() {
239 let mut ctx = empty_ctx();
240 ctx.path_errors.insert(
241 "path".to_string(),
242 "path escapes project root /project".to_string(),
243 );
244 let args: Map<String, Value> = Map::new();
245 let result = require_resolved_path(&ctx, &args, "path");
246 assert!(result.is_err());
247 let err = result.unwrap_err();
248 let msg = format!("{err:?}");
249 assert!(msg.contains("escapes project root"), "got: {msg}");
250 }
251
252 #[test]
253 fn require_resolved_path_detects_non_string() {
254 let ctx = empty_ctx();
255 let mut args: Map<String, Value> = Map::new();
256 args.insert("path".to_string(), json!(42));
257 let result = require_resolved_path(&ctx, &args, "path");
258 assert!(result.is_err());
259 let err = result.unwrap_err();
260 let msg = format!("{err:?}");
261 assert!(msg.contains("must be a string, got number"), "got: {msg}");
262 }
263
264 #[test]
265 fn require_resolved_path_missing_param() {
266 let ctx = empty_ctx();
267 let args: Map<String, Value> = Map::new();
268 let result = require_resolved_path(&ctx, &args, "path");
269 assert!(result.is_err());
270 let err = result.unwrap_err();
271 let msg = format!("{err:?}");
272 assert!(msg.contains("path is required"), "got: {msg}");
273 }
274}