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    /// The same for every attempt of one tool call (`<run_id>:<exec_id>:<turn>:<call id>`
236    /// from an `agent` node), different for every other call, so a tool can
237    /// make its effect happen once even when the call is made again. Not a secret.
238    pub idempotency_key: Option<String>,
239}
240
241static EMPTY_TOOL_CALL_CONTEXT: ToolCallContext = ToolCallContext { secrets: BTreeMap::new(), idempotency_key: None };
242
243impl ToolCallContext {
244    /// A shared empty context, for callers that have nothing to pass.
245    pub fn empty() -> &'static ToolCallContext {
246        &EMPTY_TOOL_CALL_CONTEXT
247    }
248
249    /// Whether the context holds no secrets (the idempotency key is not one).
250    pub fn is_empty(&self) -> bool {
251        self.secrets.is_empty()
252    }
253
254    /// The plaintext of secret `name`.
255    pub fn secret(&self, name: &str) -> Option<&str> {
256        self.secrets.get(name).map(String::as_str)
257    }
258}
259
260impl fmt::Debug for ToolCallContext {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        f.debug_struct("ToolCallContext")
263            .field("secrets", &self.secrets.keys().collect::<Vec<_>>())
264            .field("idempotency_key", &self.idempotency_key)
265            .finish()
266    }
267}
268
269/// A source of tools.
270pub trait ToolRuntime: Send + Sync + fmt::Debug {
271    /// Tools currently available.
272    fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
273
274    /// Invoke a tool with a JSON arguments object and a per-call context.
275    ///
276    /// `context` is empty unless this runtime [accepts secrets](ToolRuntime::accepts_secrets)
277    /// and the caller configured some. Runtimes that cannot forward it ignore it.
278    fn call<'a>(
279        &'a self,
280        name: &'a str,
281        arguments: serde_json::Value,
282        context: &'a ToolCallContext,
283    ) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
284
285    /// Whether this runtime may receive plaintext secrets in a [`ToolCallContext`].
286    ///
287    /// `false` by default. The plugin runtime returns `true` only for plugins that
288    /// request `permissions.secrets` and that the operator trusts.
289    fn accepts_secrets(&self) -> bool {
290        false
291    }
292}
293
294/// Service registered in [`crate::node::Services`]: named tool providers
295/// (e.g. `builtin`, `mcp:github`). Nodes reference tools as `provider/tool`.
296#[derive(Clone, Default)]
297pub struct ToolRegistry {
298    providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
299}
300
301impl fmt::Debug for ToolRegistry {
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        f.debug_list().entries(self.providers.keys()).finish()
304    }
305}
306
307impl ToolRegistry {
308    pub fn new() -> Self {
309        Self::default()
310    }
311
312    pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
313        self.providers.insert(provider.into(), runtime);
314        self
315    }
316
317    pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
318        self.providers.get(provider)
319    }
320
321    pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
322        self.providers.iter().map(|(k, v)| (k.as_str(), v))
323    }
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn call_context_debug_hides_values() {
332        assert!(ToolCallContext::empty().is_empty());
333        let mut context = ToolCallContext::default();
334        context.secrets.insert("user_jwt".into(), "eyJ-secret-token".into());
335        assert_eq!(context.secret("user_jwt"), Some("eyJ-secret-token"));
336        assert_eq!(context.secret("other"), None);
337        let debug = format!("{context:?}");
338        assert!(debug.contains("user_jwt") && !debug.contains("eyJ-secret-token"), "{debug}");
339    }
340
341    #[test]
342    fn files_are_collected_in_order_up_to_the_cap() {
343        let file =
344            |name: &str| Value::from(crate::value::File { marker: true, name: name.into(), ..Default::default() });
345        let names = |data: &Value| collect_files(data).iter().map(|f| f.name.clone()).collect::<Vec<_>>();
346        assert_eq!(names(&file("a")), ["a"]);
347        let nested = Value::object([
348            ("file", file("a")),
349            ("files", Value::array([file("b"), file("c")])),
350            ("text", Value::from("x")),
351        ]);
352        assert_eq!(names(&nested), ["a", "b", "c"]);
353        // Four levels down is out of reach.
354        let deep = Value::array([Value::array([Value::array([Value::array([file("deep")])])])]);
355        assert!(names(&deep).is_empty());
356        let many = Value::array((0..MAX_TOOL_FILES + 5).map(|i| file(&i.to_string())));
357        assert_eq!(collect_files(&many).len(), MAX_TOOL_FILES);
358        assert!(collect_files(&Value::Null).is_empty());
359    }
360
361    #[test]
362    fn constructors_have_no_images() {
363        assert!(ToolOutput::text("a").images.is_empty());
364        let err = ToolOutput::error("b");
365        assert!(err.is_error && err.images.is_empty());
366        let out = ToolOutput::text("shot").with_image(ToolImage::png("aGVsbG8="));
367        assert_eq!(out.images.len(), 1);
368    }
369
370    #[test]
371    fn image_urls() {
372        assert_eq!(ToolImage::png("AAAA").to_url(), "data:image/png;base64,AAAA");
373        assert_eq!(ToolImage::Url { url: "https://x/a.png".into() }.to_url(), "https://x/a.png");
374    }
375
376    #[test]
377    fn serde_shapes() {
378        let images: Vec<ToolImage> = serde_json::from_value(serde_json::json!([
379            {"media_type": "image/png", "data_base64": "AAAA"},
380            {"url": "https://x/a.png"}
381        ]))
382        .unwrap();
383        assert_eq!(images[0], ToolImage::png("AAAA"));
384        assert_eq!(images[1], ToolImage::Url { url: "https://x/a.png".into() });
385        assert!(serde_json::from_value::<ToolImage>(serde_json::json!({"data": "AAAA"})).is_err());
386    }
387
388    #[test]
389    fn base64_lengths() {
390        assert_eq!(base64_decoded_len("aGVsbG8="), Some(5));
391        assert_eq!(base64_decoded_len("aGVsbG8"), Some(5));
392        assert_eq!(base64_decoded_len("aGVsbA=="), Some(4));
393        assert_eq!(base64_decoded_len("aGVs"), Some(3));
394        assert_eq!(base64_decoded_len("aGVsb"), None);
395        assert_eq!(base64_decoded_len("aGV="), Some(2));
396        assert_eq!(base64_decoded_len("aG V"), None);
397        assert_eq!(base64_decoded_len("aGVsbG8=="), None);
398        assert_eq!(base64_decoded_len(""), Some(0));
399    }
400
401    #[test]
402    fn limits_are_enforced() {
403        assert!(check_images(&[ToolImage::png("aGVsbG8="), ToolImage::jpeg("aGVs")]).is_ok());
404        let too_many = vec![ToolImage::png("aGVs"); MAX_TOOL_IMAGES + 1];
405        assert!(check_images(&too_many).unwrap_err().to_string().contains("limit of 4"));
406        let bmp = ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() };
407        assert!(check_images(&[bmp]).unwrap_err().to_string().contains("image/bmp"));
408        assert!(ToolImage::png("not base64!").check().is_err());
409        assert!(ToolImage::png("").check().is_err());
410        let big = "A".repeat((MAX_TOOL_IMAGE_BYTES / 3 + 1) * 4);
411        assert!(ToolImage::png(big).check().unwrap_err().to_string().contains("limit"));
412        let exact = "A".repeat(MAX_TOOL_IMAGE_BYTES / 3 * 4);
413        assert!(ToolImage::png(exact).check().is_ok());
414        assert!(ToolImage::Url { url: "http://x/a.png".into() }.check().is_err());
415        assert!(ToolImage::Url { url: "data:image/png;base64,AAAA".into() }.check().is_err());
416        assert!(ToolImage::Url { url: "HTTPS://x/a.png".into() }.check().is_ok());
417    }
418}