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