Skip to main content

graphrt_core/
tool.rs

1//! Tool contract shared by the `tool` node, the `agent` node and tool
2//! providers (native Rust tools, MCP servers, HTTP tools...).
3
4use 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/// Description of a callable tool, exposed to models for tool calling.
14#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15pub struct ToolSpec {
16    /// Unique name within a [`ToolRuntime`] (e.g. `search` or `github.create_issue`).
17    pub name: String,
18    pub description: String,
19    /// JSON Schema of the arguments object.
20    pub parameters: serde_json::Value,
21}
22
23/// Result of a tool call.
24#[derive(Clone, Debug, Default, PartialEq)]
25pub struct ToolOutput {
26    /// Text handed back to a model.
27    pub text: String,
28    /// Structured result, if the tool returns one.
29    pub data: Value,
30    /// Whether the tool reported an error (the agent loop may still continue).
31    pub is_error: bool,
32    /// Images shown to the model next to `text` (see [`check_images`] for limits).
33    pub images: Vec<ToolImage>,
34}
35
36impl ToolOutput {
37    pub fn text(text: impl Into<String>) -> Self {
38        Self { text: text.into(), ..Self::default() }
39    }
40
41    pub fn error(text: impl Into<String>) -> Self {
42        Self { text: text.into(), is_error: true, ..Self::default() }
43    }
44
45    /// Attach an image.
46    pub fn with_image(mut self, image: ToolImage) -> Self {
47        self.images.push(image);
48        self
49    }
50}
51
52/// Most images one tool result may carry.
53pub const MAX_TOOL_IMAGES: usize = 4;
54/// Largest decoded size of one tool result image, in bytes (5 MiB).
55pub const MAX_TOOL_IMAGE_BYTES: usize = 5 * 1024 * 1024;
56/// Media types accepted for tool result images (supported by every built-in provider).
57pub const TOOL_IMAGE_MEDIA_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
58
59/// An image returned by a tool.
60///
61/// Serialized as `{"media_type", "data_base64"}` or `{"url"}` (the plugin
62/// protocol's `tool.call` `images` entries).
63#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(untagged)]
65pub enum ToolImage {
66    /// Inline bytes, base64 encoded (standard alphabet).
67    Base64 { media_type: String, data_base64: String },
68    /// A remote image (`https://` only).
69    Url { url: String },
70}
71
72impl ToolImage {
73    /// An inline PNG from base64 text.
74    pub fn png(data_base64: impl Into<String>) -> Self {
75        Self::Base64 { media_type: "image/png".into(), data_base64: data_base64.into() }
76    }
77
78    /// An inline JPEG from base64 text.
79    pub fn jpeg(data_base64: impl Into<String>) -> Self {
80        Self::Base64 { media_type: "image/jpeg".into(), data_base64: data_base64.into() }
81    }
82
83    /// The image as a URL: `data:<media_type>;base64,<data>` or the remote URL.
84    pub fn to_url(&self) -> String {
85        match self {
86            ToolImage::Base64 { media_type, data_base64 } => format!("data:{media_type};base64,{data_base64}"),
87            ToolImage::Url { url } => url.clone(),
88        }
89    }
90
91    /// Check this image against the media type, encoding and size limits.
92    pub fn check(&self) -> Result<(), ToolImageError> {
93        match self {
94            ToolImage::Url { url } => {
95                if url.len() > 8 && url.get(..8).is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://")) {
96                    Ok(())
97                } else {
98                    Err(ToolImageError::new("image URLs must start with https:// (send inline images as base64)"))
99                }
100            }
101            ToolImage::Base64 { media_type, data_base64 } => {
102                if !TOOL_IMAGE_MEDIA_TYPES.contains(&media_type.as_str()) {
103                    return Err(ToolImageError::new(format!(
104                        "image media type `{media_type}` is not supported (use {})",
105                        TOOL_IMAGE_MEDIA_TYPES.join(", ")
106                    )));
107                }
108                let decoded = base64_decoded_len(data_base64)
109                    .ok_or_else(|| ToolImageError::new("image data is not valid base64"))?;
110                if decoded == 0 {
111                    return Err(ToolImageError::new("image data is empty"));
112                }
113                if decoded > MAX_TOOL_IMAGE_BYTES {
114                    return Err(ToolImageError::new(format!(
115                        "image is {decoded} bytes, above the {MAX_TOOL_IMAGE_BYTES}-byte limit"
116                    )));
117                }
118                Ok(())
119            }
120        }
121    }
122}
123
124/// A tool result image that breaks a limit.
125#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
126#[error("{0}")]
127pub struct ToolImageError(pub String);
128
129impl ToolImageError {
130    fn new(message: impl Into<String>) -> Self {
131        Self(message.into())
132    }
133}
134
135/// Check the images of one tool result: at most [`MAX_TOOL_IMAGES`], each
136/// passing [`ToolImage::check`].
137pub fn check_images(images: &[ToolImage]) -> Result<(), ToolImageError> {
138    if images.len() > MAX_TOOL_IMAGES {
139        return Err(ToolImageError::new(format!(
140            "{} images in one tool result, above the limit of {MAX_TOOL_IMAGES}",
141            images.len()
142        )));
143    }
144    for (index, image) in images.iter().enumerate() {
145        image.check().map_err(|e| ToolImageError::new(format!("image #{index}: {e}")))?;
146    }
147    Ok(())
148}
149
150/// Decoded length of standard base64 text (padding optional), or `None` when
151/// the text is not base64. Validates without allocating.
152fn base64_decoded_len(text: &str) -> Option<usize> {
153    let bytes = text.as_bytes();
154    let body = bytes.strip_suffix(b"==").or_else(|| bytes.strip_suffix(b"=")).unwrap_or(bytes);
155    let alphabet = |b: &u8| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/';
156    if !body.iter().all(alphabet) {
157        return None;
158    }
159    let padded = body.len() != bytes.len();
160    if padded && !bytes.len().is_multiple_of(4) {
161        return None;
162    }
163    match body.len() % 4 {
164        1 => None,
165        rest => Some(body.len() / 4 * 3 + rest.saturating_sub(1)),
166    }
167}
168
169/// Most files [`collect_files`] returns for one tool result.
170pub const MAX_TOOL_FILES: usize = 16;
171/// How deep [`collect_files`] looks into arrays and objects (the value itself is depth 0).
172const MAX_FILE_SCAN_DEPTH: usize = 3;
173
174/// Files in a tool's structured result ([`ToolOutput::data`]), in document
175/// order: the value itself when it is a file, otherwise files found in its
176/// array items and object fields, at most three levels down
177/// (`{"file": ...}`, `{"files": [...]}`). At most [`MAX_TOOL_FILES`].
178///
179/// Only native tools can return file values: JSON from plugins, MCP servers
180/// and models is converted with [`Value::from_json`], which never creates one.
181///
182/// ```
183/// use graphrt_core::tool::collect_files;
184/// use graphrt_core::value::{File, Value};
185///
186/// let file = File { marker: true, name: "report.csv".into(), ..File::default() };
187/// let data = Value::object([("path", Value::from("report.csv")), ("file", Value::from(file))]);
188/// assert_eq!(collect_files(&data).len(), 1);
189/// // Untrusted JSON that looks like a file is not one.
190/// let forged = Value::from_json(serde_json::json!({"file": {"$file": true, "name": "x"}}));
191/// assert!(collect_files(&forged).is_empty());
192/// ```
193pub fn collect_files(data: &Value) -> Vec<Arc<crate::value::File>> {
194    let mut files = Vec::new();
195    collect_files_into(data, 0, &mut files);
196    files
197}
198
199fn collect_files_into(value: &Value, depth: usize, files: &mut Vec<Arc<crate::value::File>>) {
200    if files.len() >= MAX_TOOL_FILES {
201        return;
202    }
203    match value {
204        Value::File(file) => files.push(Arc::clone(file)),
205        Value::Array(items) if depth < MAX_FILE_SCAN_DEPTH => {
206            items.iter().for_each(|item| collect_files_into(item, depth + 1, files));
207        }
208        Value::Object(fields) if depth < MAX_FILE_SCAN_DEPTH => {
209            fields.values().for_each(|field| collect_files_into(field, depth + 1, files));
210        }
211        _ => {}
212    }
213}
214
215/// Error calling a tool (transport, unknown tool...).
216#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
217#[error("tool `{tool}`: {message}")]
218pub struct ToolError {
219    pub tool: String,
220    pub message: String,
221}
222
223/// Per-call values a tool receives next to its arguments, without the model
224/// ever seeing them (e.g. the end user's JWT for a database tool).
225///
226/// The `agent` node fills it from its `tool_context` config, only for
227/// providers whose [`ToolRuntime::accepts_secrets`] is `true`. The values are
228/// plaintext: they are never written to events, outputs, snapshots or traces,
229/// and `Debug` shows only the names. The type deliberately does not implement
230/// `Serialize`, so it cannot end up in a recorded value by accident.
231#[derive(Clone, Default, PartialEq, Eq)]
232pub struct ToolCallContext {
233    /// Secret name → plaintext value.
234    pub secrets: BTreeMap<String, String>,
235}
236
237static EMPTY_TOOL_CALL_CONTEXT: ToolCallContext = ToolCallContext { secrets: BTreeMap::new() };
238
239impl ToolCallContext {
240    /// A shared empty context, for callers that have nothing to pass.
241    pub fn empty() -> &'static ToolCallContext {
242        &EMPTY_TOOL_CALL_CONTEXT
243    }
244
245    /// Whether there is nothing in the context.
246    pub fn is_empty(&self) -> bool {
247        self.secrets.is_empty()
248    }
249
250    /// The plaintext of secret `name`.
251    pub fn secret(&self, name: &str) -> Option<&str> {
252        self.secrets.get(name).map(String::as_str)
253    }
254}
255
256impl fmt::Debug for ToolCallContext {
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        f.debug_struct("ToolCallContext").field("secrets", &self.secrets.keys().collect::<Vec<_>>()).finish()
259    }
260}
261
262/// A source of tools.
263pub trait ToolRuntime: Send + Sync + fmt::Debug {
264    /// Tools currently available.
265    fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
266
267    /// Invoke a tool with a JSON arguments object and a per-call context.
268    ///
269    /// `context` is empty unless this runtime [accepts secrets](ToolRuntime::accepts_secrets)
270    /// and the caller configured some. Runtimes that cannot forward it ignore it.
271    fn call<'a>(
272        &'a self,
273        name: &'a str,
274        arguments: serde_json::Value,
275        context: &'a ToolCallContext,
276    ) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
277
278    /// Whether this runtime may receive plaintext secrets in a [`ToolCallContext`].
279    ///
280    /// `false` by default. The plugin runtime returns `true` only for plugins that
281    /// request `permissions.secrets` and that the operator trusts.
282    fn accepts_secrets(&self) -> bool {
283        false
284    }
285}
286
287/// Service registered in [`crate::node::Services`]: named tool providers
288/// (e.g. `builtin`, `mcp:github`). Nodes reference tools as `provider/tool`.
289#[derive(Clone, Default)]
290pub struct ToolRegistry {
291    providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
292}
293
294impl fmt::Debug for ToolRegistry {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        f.debug_list().entries(self.providers.keys()).finish()
297    }
298}
299
300impl ToolRegistry {
301    pub fn new() -> Self {
302        Self::default()
303    }
304
305    pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
306        self.providers.insert(provider.into(), runtime);
307        self
308    }
309
310    pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
311        self.providers.get(provider)
312    }
313
314    pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
315        self.providers.iter().map(|(k, v)| (k.as_str(), v))
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322
323    #[test]
324    fn call_context_debug_hides_values() {
325        assert!(ToolCallContext::empty().is_empty());
326        let mut context = ToolCallContext::default();
327        context.secrets.insert("user_jwt".into(), "eyJ-secret-token".into());
328        assert_eq!(context.secret("user_jwt"), Some("eyJ-secret-token"));
329        assert_eq!(context.secret("other"), None);
330        let debug = format!("{context:?}");
331        assert!(debug.contains("user_jwt") && !debug.contains("eyJ-secret-token"), "{debug}");
332    }
333
334    #[test]
335    fn files_are_collected_in_order_up_to_the_cap() {
336        let file =
337            |name: &str| Value::from(crate::value::File { marker: true, name: name.into(), ..Default::default() });
338        let names = |data: &Value| collect_files(data).iter().map(|f| f.name.clone()).collect::<Vec<_>>();
339        assert_eq!(names(&file("a")), ["a"]);
340        let nested = Value::object([
341            ("file", file("a")),
342            ("files", Value::array([file("b"), file("c")])),
343            ("text", Value::from("x")),
344        ]);
345        assert_eq!(names(&nested), ["a", "b", "c"]);
346        // Four levels down is out of reach.
347        let deep = Value::array([Value::array([Value::array([Value::array([file("deep")])])])]);
348        assert!(names(&deep).is_empty());
349        let many = Value::array((0..MAX_TOOL_FILES + 5).map(|i| file(&i.to_string())));
350        assert_eq!(collect_files(&many).len(), MAX_TOOL_FILES);
351        assert!(collect_files(&Value::Null).is_empty());
352    }
353
354    #[test]
355    fn constructors_have_no_images() {
356        assert!(ToolOutput::text("a").images.is_empty());
357        let err = ToolOutput::error("b");
358        assert!(err.is_error && err.images.is_empty());
359        let out = ToolOutput::text("shot").with_image(ToolImage::png("aGVsbG8="));
360        assert_eq!(out.images.len(), 1);
361    }
362
363    #[test]
364    fn image_urls() {
365        assert_eq!(ToolImage::png("AAAA").to_url(), "data:image/png;base64,AAAA");
366        assert_eq!(ToolImage::Url { url: "https://x/a.png".into() }.to_url(), "https://x/a.png");
367    }
368
369    #[test]
370    fn serde_shapes() {
371        let images: Vec<ToolImage> = serde_json::from_value(serde_json::json!([
372            {"media_type": "image/png", "data_base64": "AAAA"},
373            {"url": "https://x/a.png"}
374        ]))
375        .unwrap();
376        assert_eq!(images[0], ToolImage::png("AAAA"));
377        assert_eq!(images[1], ToolImage::Url { url: "https://x/a.png".into() });
378        assert!(serde_json::from_value::<ToolImage>(serde_json::json!({"data": "AAAA"})).is_err());
379    }
380
381    #[test]
382    fn base64_lengths() {
383        assert_eq!(base64_decoded_len("aGVsbG8="), Some(5));
384        assert_eq!(base64_decoded_len("aGVsbG8"), Some(5));
385        assert_eq!(base64_decoded_len("aGVsbA=="), Some(4));
386        assert_eq!(base64_decoded_len("aGVs"), Some(3));
387        assert_eq!(base64_decoded_len("aGVsb"), None);
388        assert_eq!(base64_decoded_len("aGV="), Some(2));
389        assert_eq!(base64_decoded_len("aG V"), None);
390        assert_eq!(base64_decoded_len("aGVsbG8=="), None);
391        assert_eq!(base64_decoded_len(""), Some(0));
392    }
393
394    #[test]
395    fn limits_are_enforced() {
396        assert!(check_images(&[ToolImage::png("aGVsbG8="), ToolImage::jpeg("aGVs")]).is_ok());
397        let too_many = vec![ToolImage::png("aGVs"); MAX_TOOL_IMAGES + 1];
398        assert!(check_images(&too_many).unwrap_err().to_string().contains("limit of 4"));
399        let bmp = ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() };
400        assert!(check_images(&[bmp]).unwrap_err().to_string().contains("image/bmp"));
401        assert!(ToolImage::png("not base64!").check().is_err());
402        assert!(ToolImage::png("").check().is_err());
403        let big = "A".repeat((MAX_TOOL_IMAGE_BYTES / 3 + 1) * 4);
404        assert!(ToolImage::png(big).check().unwrap_err().to_string().contains("limit"));
405        let exact = "A".repeat(MAX_TOOL_IMAGE_BYTES / 3 * 4);
406        assert!(ToolImage::png(exact).check().is_ok());
407        assert!(ToolImage::Url { url: "http://x/a.png".into() }.check().is_err());
408        assert!(ToolImage::Url { url: "data:image/png;base64,AAAA".into() }.check().is_err());
409        assert!(ToolImage::Url { url: "HTTPS://x/a.png".into() }.check().is_ok());
410    }
411}