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