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    /// What the call cost, in millionths of the price unit of the providers
99    /// file (a priced image generation). The calling node charges it to the
100    /// run's budget and reports it in its `usage`.
101    pub cost_micros: u64,
102    /// Machine readable type of an error (`is_error`), when the tool names
103    /// one, as a node error's type: `limit_exceeded` when the run's cost
104    /// budget does not afford the call, `price_missing` when the run has a
105    /// cost budget and the call has no price. A `tool` node fails with it in
106    /// place of `tool_error`; `limit_exceeded` stops the run in a `tool` or an
107    /// `agent` node, as a model call the budget cannot afford does. `None`: a
108    /// plain tool error.
109    #[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    /// An error of a machine readable type (see [`ToolOutput::error_type`]).
123    #[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    /// Whether the tool refused the call because the run's budget does not afford it.
129    #[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    /// Attach an image.
135    pub fn with_image(mut self, image: ToolImage) -> Self {
136        self.images.push(image);
137        self
138    }
139}
140
141/// The [`ToolOutput::error_type`] of a call the run's budget does not afford.
142#[cfg(feature = "tool-error-types")]
143pub const LIMIT_EXCEEDED: &str = "limit_exceeded";
144
145/// Most images one tool result may carry.
146pub const MAX_TOOL_IMAGES: usize = 4;
147/// Largest decoded size of one tool result image, in bytes (5 MiB).
148pub const MAX_TOOL_IMAGE_BYTES: usize = 5 * 1024 * 1024;
149/// Media types accepted for tool result images (supported by every built-in provider).
150pub const TOOL_IMAGE_MEDIA_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
151
152/// An image returned by a tool.
153///
154/// Serialized as `{"media_type", "data_base64"}` or `{"url"}` (the plugin
155/// protocol's `tool.call` `images` entries).
156#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
157#[serde(untagged)]
158pub enum ToolImage {
159    /// Inline bytes, base64 encoded (standard alphabet).
160    Base64 { media_type: String, data_base64: String },
161    /// A remote image (`https://` only).
162    Url { url: String },
163}
164
165impl ToolImage {
166    /// An inline PNG from base64 text.
167    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    /// An inline JPEG from base64 text.
172    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    /// The image as a URL: `data:<media_type>;base64,<data>` or the remote URL.
177    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    /// Check this image against the media type, encoding and size limits.
185    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/// A tool result image that breaks a limit.
218#[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
228/// Check the images of one tool result: at most [`MAX_TOOL_IMAGES`], each
229/// passing [`ToolImage::check`].
230pub 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
243/// Decoded length of standard base64 text (padding optional), or `None` when
244/// the text is not base64. Validates without allocating.
245fn 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
262/// Most files [`collect_files`] returns for one tool result.
263pub const MAX_TOOL_FILES: usize = 16;
264/// How deep [`collect_files`] looks into arrays and objects (the value itself is depth 0).
265const MAX_FILE_SCAN_DEPTH: usize = 3;
266
267/// Files in a tool's structured result ([`ToolOutput::data`]), in document
268/// order: the value itself when it is a file, otherwise files found in its
269/// array items and object fields, at most three levels down
270/// (`{"file": ...}`, `{"files": [...]}`). At most [`MAX_TOOL_FILES`].
271///
272/// Only native tools can return file values: JSON from plugins, MCP servers
273/// and models is converted with [`Value::from_json`], which never creates one.
274///
275/// ```
276/// use graphrt_core::tool::collect_files;
277/// use graphrt_core::value::{File, Value};
278///
279/// let file = File { marker: true, name: "report.csv".into(), ..File::default() };
280/// let data = Value::object([("path", Value::from("report.csv")), ("file", Value::from(file))]);
281/// assert_eq!(collect_files(&data).len(), 1);
282/// // Untrusted JSON that looks like a file is not one.
283/// let forged = Value::from_json(serde_json::json!({"file": {"$file": true, "name": "x"}}));
284/// assert!(collect_files(&forged).is_empty());
285/// ```
286pub 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/// Error calling a tool (transport, unknown tool...).
309#[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/// Per-call values a tool receives next to its arguments, without the model
317/// ever seeing them (e.g. the end user's JWT for a database tool).
318///
319/// The `agent` node fills it from its `tool_context` config, only for
320/// providers whose [`ToolRuntime::accepts_secrets`] is `true`. The values are
321/// plaintext: they are never written to events, outputs, snapshots or traces,
322/// and `Debug` shows only the names. The type deliberately does not implement
323/// `Serialize`, so it cannot end up in a recorded value by accident.
324#[derive(Clone, Default, PartialEq, Eq)]
325pub struct ToolCallContext {
326    /// Secret name → plaintext value.
327    pub secrets: BTreeMap<String, String>,
328    /// The same for every attempt of one tool call (`<run_id>:<exec_id>:<turn>:<call id>`
329    /// from an `agent` node), different for every other call, so a tool can
330    /// make its effect happen once even when the call is made again. Not a secret.
331    pub idempotency_key: Option<String>,
332    /// What the run may still spend, in the micro units of
333    /// [`ToolOutput::cost_micros`], when it has a cost budget. A tool with a
334    /// price refuses a call the run cannot afford before making it. Not a secret.
335    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    /// A shared empty context, for callers that have nothing to pass.
343    pub fn empty() -> &'static ToolCallContext {
344        &EMPTY_TOOL_CALL_CONTEXT
345    }
346
347    /// Whether the context holds no secrets (the idempotency key is not one).
348    pub fn is_empty(&self) -> bool {
349        self.secrets.is_empty()
350    }
351
352    /// The plaintext of secret `name`.
353    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
368/// A source of tools.
369pub trait ToolRuntime: Send + Sync + fmt::Debug {
370    /// Tools currently available.
371    fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
372
373    /// Invoke a tool with a JSON arguments object and a per-call context.
374    ///
375    /// `context` is empty unless this runtime [accepts secrets](ToolRuntime::accepts_secrets)
376    /// and the caller configured some. Runtimes that cannot forward it ignore it.
377    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    /// Whether this runtime may receive plaintext secrets in a [`ToolCallContext`].
385    ///
386    /// `false` by default. The plugin runtime returns `true` only for plugins that
387    /// request `permissions.secrets` and that the operator trusts.
388    fn accepts_secrets(&self) -> bool {
389        false
390    }
391}
392
393/// Service registered in [`crate::node::Services`]: named tool providers
394/// (e.g. `builtin`, `mcp:github`). Nodes reference tools as `provider/tool`.
395#[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        // Four levels down is out of reach.
453        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}