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}
120
121impl ToolContext {
122 pub fn resolved_path(&self, arg: &str) -> Option<&str> {
123 self.resolved_paths.get(arg).map(String::as_str)
124 }
125
126 pub fn path_error(&self, key: &str) -> Option<&str> {
128 self.path_errors.get(key).map(String::as_str)
129 }
130
131 pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
134 let normalized = crate::core::pathutil::normalize_tool_path(path);
135 if normalized.is_empty() || normalized == "." {
136 return Ok(normalized);
137 }
138 let p = std::path::Path::new(&normalized);
139 let resolved = if p.is_absolute() || p.exists() {
140 std::path::PathBuf::from(&normalized)
141 } else {
142 let joined = std::path::Path::new(&self.project_root).join(&normalized);
143 if joined.exists() {
144 joined
145 } else {
146 std::path::Path::new(&self.project_root).join(&normalized)
147 }
148 };
149 let jail_root = std::path::Path::new(&self.project_root);
150 let jailed = crate::core::pathjail::jail_path(&resolved, jail_root)?;
151 crate::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)?;
152 Ok(crate::core::pathutil::normalize_tool_path(
153 &jailed.to_string_lossy().replace('\\', "/"),
154 ))
155 }
156}
157
158pub fn require_resolved_path(
163 ctx: &ToolContext,
164 args: &Map<String, Value>,
165 key: &str,
166) -> Result<String, ErrorData> {
167 if let Some(path) = ctx.resolved_path(key) {
168 return Ok(path.to_string());
169 }
170 if let Some(err) = ctx.path_error(key) {
171 return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
172 }
173 if let Some(val) = args.get(key) {
174 if !val.is_string() {
175 let type_name = match val {
176 Value::Number(_) => "number",
177 Value::Bool(_) => "boolean",
178 Value::Array(_) => "array",
179 Value::Object(_) => "object",
180 Value::Null => "null",
181 Value::String(_) => unreachable!(),
182 };
183 return Err(ErrorData::invalid_params(
184 format!("{key} must be a string, got {type_name}"),
185 None,
186 ));
187 }
188 }
189 Err(ErrorData::invalid_params(
190 format!("{key} is required"),
191 None,
192 ))
193}
194
195pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
196 args.get(key).and_then(|v| v.as_str()).map(String::from)
197}
198
199pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
200 args.get(key).and_then(serde_json::Value::as_i64)
201}
202
203pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
204 args.get(key).and_then(serde_json::Value::as_bool)
205}
206
207pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
208 args.get(key).and_then(|v| v.as_array()).map(|arr| {
209 arr.iter()
210 .filter_map(|v| v.as_str().map(String::from))
211 .collect()
212 })
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218 use serde_json::json;
219
220 fn empty_ctx() -> ToolContext {
221 ToolContext {
222 project_root: String::new(),
223 minimal: false,
224 resolved_paths: std::collections::HashMap::new(),
225 crp_mode: crate::tools::CrpMode::Off,
226 cache: None,
227 session: None,
228 tool_calls: None,
229 agent_id: None,
230 workflow: None,
231 ledger: None,
232 client_name: None,
233 pipeline_stats: None,
234 call_count: None,
235 autonomy: None,
236 pressure_snapshot: None,
237 path_errors: std::collections::HashMap::new(),
238 }
239 }
240
241 #[test]
242 fn require_resolved_path_returns_resolved() {
243 let mut ctx = empty_ctx();
244 ctx.resolved_paths
245 .insert("path".to_string(), "/abs/file.rs".to_string());
246 let args: Map<String, Value> = Map::new();
247 let result = require_resolved_path(&ctx, &args, "path");
248 assert_eq!(result.unwrap(), "/abs/file.rs");
249 }
250
251 #[test]
252 fn require_resolved_path_surfaces_jail_error() {
253 let mut ctx = empty_ctx();
254 ctx.path_errors.insert(
255 "path".to_string(),
256 "path escapes project root /project".to_string(),
257 );
258 let args: Map<String, Value> = Map::new();
259 let result = require_resolved_path(&ctx, &args, "path");
260 assert!(result.is_err());
261 let err = result.unwrap_err();
262 let msg = format!("{err:?}");
263 assert!(msg.contains("escapes project root"), "got: {msg}");
264 }
265
266 #[test]
267 fn require_resolved_path_detects_non_string() {
268 let ctx = empty_ctx();
269 let mut args: Map<String, Value> = Map::new();
270 args.insert("path".to_string(), json!(42));
271 let result = require_resolved_path(&ctx, &args, "path");
272 assert!(result.is_err());
273 let err = result.unwrap_err();
274 let msg = format!("{err:?}");
275 assert!(msg.contains("must be a string, got number"), "got: {msg}");
276 }
277
278 #[test]
279 fn require_resolved_path_missing_param() {
280 let ctx = empty_ctx();
281 let args: Map<String, Value> = Map::new();
282 let result = require_resolved_path(&ctx, &args, "path");
283 assert!(result.is_err());
284 let err = result.unwrap_err();
285 let msg = format!("{err:?}");
286 assert!(msg.contains("path is required"), "got: {msg}");
287 }
288}