1use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::Arc;
7
8use futures::future::BoxFuture;
9use serde::{Deserialize, Serialize};
10
11use crate::value::Value;
12
13#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15pub struct ToolSpec {
16 pub name: String,
18 pub description: String,
19 pub parameters: serde_json::Value,
21 #[serde(default, skip_serializing_if = "Vec::is_empty")]
27 pub effects: Vec<ToolEffect>,
28}
29
30impl ToolSpec {
31 pub fn new(name: impl Into<String>, description: impl Into<String>, parameters: serde_json::Value) -> Self {
33 Self { name: name.into(), description: description.into(), parameters, effects: Vec::new() }
34 }
35
36 #[must_use]
38 pub fn with_effects(mut self, effects: Vec<ToolEffect>) -> Self {
39 self.effects = effects;
40 self
41 }
42
43 pub fn needs_approval(&self) -> bool {
46 self.effects.iter().any(|effect| effect.needs_approval())
47 }
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum ToolEffect {
55 Read,
57 Write,
59 Send,
62 Pay,
64}
65
66impl ToolEffect {
67 pub const ALL: [ToolEffect; 4] = [ToolEffect::Read, ToolEffect::Write, ToolEffect::Send, ToolEffect::Pay];
69
70 pub fn as_str(self) -> &'static str {
72 match self {
73 Self::Read => "read",
74 Self::Write => "write",
75 Self::Send => "send",
76 Self::Pay => "pay",
77 }
78 }
79
80 pub fn needs_approval(self) -> bool {
83 matches!(self, Self::Send | Self::Pay)
84 }
85}
86
87#[derive(Clone, Debug, Default, PartialEq)]
89pub struct ToolOutput {
90 pub text: String,
92 pub data: Value,
94 pub is_error: bool,
96 pub images: Vec<ToolImage>,
98 pub cost_micros: u64,
102 #[cfg(feature = "tool-error-types")]
110 pub error_type: Option<String>,
111}
112
113impl ToolOutput {
114 pub fn text(text: impl Into<String>) -> Self {
115 Self { text: text.into(), ..Self::default() }
116 }
117
118 pub fn error(text: impl Into<String>) -> Self {
119 Self { text: text.into(), is_error: true, ..Self::default() }
120 }
121
122 #[cfg(feature = "tool-error-types")]
124 pub fn typed_error(error_type: impl Into<String>, text: impl Into<String>) -> Self {
125 Self { error_type: Some(error_type.into()), ..Self::error(text) }
126 }
127
128 #[cfg(feature = "tool-error-types")]
130 pub fn is_limit_exceeded(&self) -> bool {
131 self.is_error && self.error_type.as_deref() == Some(LIMIT_EXCEEDED)
132 }
133
134 pub fn with_image(mut self, image: ToolImage) -> Self {
136 self.images.push(image);
137 self
138 }
139}
140
141#[cfg(feature = "tool-error-types")]
143pub const LIMIT_EXCEEDED: &str = "limit_exceeded";
144
145pub const MAX_TOOL_IMAGES: usize = 4;
147pub const MAX_TOOL_IMAGE_BYTES: usize = 5 * 1024 * 1024;
149pub const TOOL_IMAGE_MEDIA_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
151
152#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
157#[serde(untagged)]
158pub enum ToolImage {
159 Base64 { media_type: String, data_base64: String },
161 Url { url: String },
163}
164
165impl ToolImage {
166 pub fn png(data_base64: impl Into<String>) -> Self {
168 Self::Base64 { media_type: "image/png".into(), data_base64: data_base64.into() }
169 }
170
171 pub fn jpeg(data_base64: impl Into<String>) -> Self {
173 Self::Base64 { media_type: "image/jpeg".into(), data_base64: data_base64.into() }
174 }
175
176 pub fn to_url(&self) -> String {
178 match self {
179 ToolImage::Base64 { media_type, data_base64 } => format!("data:{media_type};base64,{data_base64}"),
180 ToolImage::Url { url } => url.clone(),
181 }
182 }
183
184 pub fn check(&self) -> Result<(), ToolImageError> {
186 match self {
187 ToolImage::Url { url } => {
188 if url.len() > 8 && url.get(..8).is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://")) {
189 Ok(())
190 } else {
191 Err(ToolImageError::new("image URLs must start with https:// (send inline images as base64)"))
192 }
193 }
194 ToolImage::Base64 { media_type, data_base64 } => {
195 if !TOOL_IMAGE_MEDIA_TYPES.contains(&media_type.as_str()) {
196 return Err(ToolImageError::new(format!(
197 "image media type `{media_type}` is not supported (use {})",
198 TOOL_IMAGE_MEDIA_TYPES.join(", ")
199 )));
200 }
201 let decoded = base64_decoded_len(data_base64)
202 .ok_or_else(|| ToolImageError::new("image data is not valid base64"))?;
203 if decoded == 0 {
204 return Err(ToolImageError::new("image data is empty"));
205 }
206 if decoded > MAX_TOOL_IMAGE_BYTES {
207 return Err(ToolImageError::new(format!(
208 "image is {decoded} bytes, above the {MAX_TOOL_IMAGE_BYTES}-byte limit"
209 )));
210 }
211 Ok(())
212 }
213 }
214 }
215}
216
217#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
219#[error("{0}")]
220pub struct ToolImageError(pub String);
221
222impl ToolImageError {
223 fn new(message: impl Into<String>) -> Self {
224 Self(message.into())
225 }
226}
227
228pub fn check_images(images: &[ToolImage]) -> Result<(), ToolImageError> {
231 if images.len() > MAX_TOOL_IMAGES {
232 return Err(ToolImageError::new(format!(
233 "{} images in one tool result, above the limit of {MAX_TOOL_IMAGES}",
234 images.len()
235 )));
236 }
237 for (index, image) in images.iter().enumerate() {
238 image.check().map_err(|e| ToolImageError::new(format!("image #{index}: {e}")))?;
239 }
240 Ok(())
241}
242
243fn base64_decoded_len(text: &str) -> Option<usize> {
246 let bytes = text.as_bytes();
247 let body = bytes.strip_suffix(b"==").or_else(|| bytes.strip_suffix(b"=")).unwrap_or(bytes);
248 let alphabet = |b: &u8| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/';
249 if !body.iter().all(alphabet) {
250 return None;
251 }
252 let padded = body.len() != bytes.len();
253 if padded && !bytes.len().is_multiple_of(4) {
254 return None;
255 }
256 match body.len() % 4 {
257 1 => None,
258 rest => Some(body.len() / 4 * 3 + rest.saturating_sub(1)),
259 }
260}
261
262pub const MAX_TOOL_FILES: usize = 16;
264const MAX_FILE_SCAN_DEPTH: usize = 3;
266
267pub fn collect_files(data: &Value) -> Vec<Arc<crate::value::File>> {
287 let mut files = Vec::new();
288 collect_files_into(data, 0, &mut files);
289 files
290}
291
292fn collect_files_into(value: &Value, depth: usize, files: &mut Vec<Arc<crate::value::File>>) {
293 if files.len() >= MAX_TOOL_FILES {
294 return;
295 }
296 match value {
297 Value::File(file) => files.push(Arc::clone(file)),
298 Value::Array(items) if depth < MAX_FILE_SCAN_DEPTH => {
299 items.iter().for_each(|item| collect_files_into(item, depth + 1, files));
300 }
301 Value::Object(fields) if depth < MAX_FILE_SCAN_DEPTH => {
302 fields.values().for_each(|field| collect_files_into(field, depth + 1, files));
303 }
304 _ => {}
305 }
306}
307
308#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
310#[error("tool `{tool}`: {message}")]
311pub struct ToolError {
312 pub tool: String,
313 pub message: String,
314}
315
316#[derive(Clone, Default, PartialEq, Eq)]
325pub struct ToolCallContext {
326 pub secrets: BTreeMap<String, String>,
328 pub idempotency_key: Option<String>,
332 pub remaining_cost_micros: Option<u64>,
336}
337
338static EMPTY_TOOL_CALL_CONTEXT: ToolCallContext =
339 ToolCallContext { secrets: BTreeMap::new(), idempotency_key: None, remaining_cost_micros: None };
340
341impl ToolCallContext {
342 pub fn empty() -> &'static ToolCallContext {
344 &EMPTY_TOOL_CALL_CONTEXT
345 }
346
347 pub fn is_empty(&self) -> bool {
349 self.secrets.is_empty()
350 }
351
352 pub fn secret(&self, name: &str) -> Option<&str> {
354 self.secrets.get(name).map(String::as_str)
355 }
356}
357
358impl fmt::Debug for ToolCallContext {
359 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
360 f.debug_struct("ToolCallContext")
361 .field("secrets", &self.secrets.keys().collect::<Vec<_>>())
362 .field("idempotency_key", &self.idempotency_key)
363 .field("remaining_cost_micros", &self.remaining_cost_micros)
364 .finish()
365 }
366}
367
368pub trait ToolRuntime: Send + Sync + fmt::Debug {
370 fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
372
373 fn call<'a>(
378 &'a self,
379 name: &'a str,
380 arguments: serde_json::Value,
381 context: &'a ToolCallContext,
382 ) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
383
384 fn accepts_secrets(&self) -> bool {
389 false
390 }
391}
392
393#[derive(Clone, Default)]
396pub struct ToolRegistry {
397 providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
398}
399
400impl fmt::Debug for ToolRegistry {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 f.debug_list().entries(self.providers.keys()).finish()
403 }
404}
405
406impl ToolRegistry {
407 pub fn new() -> Self {
408 Self::default()
409 }
410
411 pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
412 self.providers.insert(provider.into(), runtime);
413 self
414 }
415
416 pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
417 self.providers.get(provider)
418 }
419
420 pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
421 self.providers.iter().map(|(k, v)| (k.as_str(), v))
422 }
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428
429 #[test]
430 fn call_context_debug_hides_values() {
431 assert!(ToolCallContext::empty().is_empty());
432 let mut context = ToolCallContext::default();
433 context.secrets.insert("user_jwt".into(), "eyJ-secret-token".into());
434 assert_eq!(context.secret("user_jwt"), Some("eyJ-secret-token"));
435 assert_eq!(context.secret("other"), None);
436 let debug = format!("{context:?}");
437 assert!(debug.contains("user_jwt") && !debug.contains("eyJ-secret-token"), "{debug}");
438 }
439
440 #[test]
441 fn files_are_collected_in_order_up_to_the_cap() {
442 let file =
443 |name: &str| Value::from(crate::value::File { marker: true, name: name.into(), ..Default::default() });
444 let names = |data: &Value| collect_files(data).iter().map(|f| f.name.clone()).collect::<Vec<_>>();
445 assert_eq!(names(&file("a")), ["a"]);
446 let nested = Value::object([
447 ("file", file("a")),
448 ("files", Value::array([file("b"), file("c")])),
449 ("text", Value::from("x")),
450 ]);
451 assert_eq!(names(&nested), ["a", "b", "c"]);
452 let deep = Value::array([Value::array([Value::array([Value::array([file("deep")])])])]);
454 assert!(names(&deep).is_empty());
455 let many = Value::array((0..MAX_TOOL_FILES + 5).map(|i| file(&i.to_string())));
456 assert_eq!(collect_files(&many).len(), MAX_TOOL_FILES);
457 assert!(collect_files(&Value::Null).is_empty());
458 }
459
460 #[test]
461 fn constructors_have_no_images() {
462 assert!(ToolOutput::text("a").images.is_empty());
463 let err = ToolOutput::error("b");
464 assert!(err.is_error && err.images.is_empty());
465 let out = ToolOutput::text("shot").with_image(ToolImage::png("aGVsbG8="));
466 assert_eq!(out.images.len(), 1);
467 }
468
469 #[test]
470 fn image_urls() {
471 assert_eq!(ToolImage::png("AAAA").to_url(), "data:image/png;base64,AAAA");
472 assert_eq!(ToolImage::Url { url: "https://x/a.png".into() }.to_url(), "https://x/a.png");
473 }
474
475 #[test]
476 fn serde_shapes() {
477 let images: Vec<ToolImage> = serde_json::from_value(serde_json::json!([
478 {"media_type": "image/png", "data_base64": "AAAA"},
479 {"url": "https://x/a.png"}
480 ]))
481 .unwrap();
482 assert_eq!(images[0], ToolImage::png("AAAA"));
483 assert_eq!(images[1], ToolImage::Url { url: "https://x/a.png".into() });
484 assert!(serde_json::from_value::<ToolImage>(serde_json::json!({"data": "AAAA"})).is_err());
485 }
486
487 #[test]
488 fn base64_lengths() {
489 assert_eq!(base64_decoded_len("aGVsbG8="), Some(5));
490 assert_eq!(base64_decoded_len("aGVsbG8"), Some(5));
491 assert_eq!(base64_decoded_len("aGVsbA=="), Some(4));
492 assert_eq!(base64_decoded_len("aGVs"), Some(3));
493 assert_eq!(base64_decoded_len("aGVsb"), None);
494 assert_eq!(base64_decoded_len("aGV="), Some(2));
495 assert_eq!(base64_decoded_len("aG V"), None);
496 assert_eq!(base64_decoded_len("aGVsbG8=="), None);
497 assert_eq!(base64_decoded_len(""), Some(0));
498 }
499
500 #[test]
501 fn limits_are_enforced() {
502 assert!(check_images(&[ToolImage::png("aGVsbG8="), ToolImage::jpeg("aGVs")]).is_ok());
503 let too_many = vec![ToolImage::png("aGVs"); MAX_TOOL_IMAGES + 1];
504 assert!(check_images(&too_many).unwrap_err().to_string().contains("limit of 4"));
505 let bmp = ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() };
506 assert!(check_images(&[bmp]).unwrap_err().to_string().contains("image/bmp"));
507 assert!(ToolImage::png("not base64!").check().is_err());
508 assert!(ToolImage::png("").check().is_err());
509 let big = "A".repeat((MAX_TOOL_IMAGE_BYTES / 3 + 1) * 4);
510 assert!(ToolImage::png(big).check().unwrap_err().to_string().contains("limit"));
511 let exact = "A".repeat(MAX_TOOL_IMAGE_BYTES / 3 * 4);
512 assert!(ToolImage::png(exact).check().is_ok());
513 assert!(ToolImage::Url { url: "http://x/a.png".into() }.check().is_err());
514 assert!(ToolImage::Url { url: "data:image/png;base64,AAAA".into() }.check().is_err());
515 assert!(ToolImage::Url { url: "HTTPS://x/a.png".into() }.check().is_ok());
516 }
517}