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