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/// Error calling a tool (transport, unknown tool...).
170#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
171#[error("tool `{tool}`: {message}")]
172pub struct ToolError {
173    pub tool: String,
174    pub message: String,
175}
176
177/// Per-call values a tool receives next to its arguments, without the model
178/// ever seeing them (e.g. the end user's JWT for a database tool).
179///
180/// The `agent` node fills it from its `tool_context` config, only for
181/// providers whose [`ToolRuntime::accepts_secrets`] is `true`. The values are
182/// plaintext: they are never written to events, outputs, snapshots or traces,
183/// and `Debug` shows only the names. The type deliberately does not implement
184/// `Serialize`, so it cannot end up in a recorded value by accident.
185#[derive(Clone, Default, PartialEq, Eq)]
186pub struct ToolCallContext {
187    /// Secret name → plaintext value.
188    pub secrets: BTreeMap<String, String>,
189}
190
191static EMPTY_TOOL_CALL_CONTEXT: ToolCallContext = ToolCallContext { secrets: BTreeMap::new() };
192
193impl ToolCallContext {
194    /// A shared empty context, for callers that have nothing to pass.
195    pub fn empty() -> &'static ToolCallContext {
196        &EMPTY_TOOL_CALL_CONTEXT
197    }
198
199    /// Whether there is nothing in the context.
200    pub fn is_empty(&self) -> bool {
201        self.secrets.is_empty()
202    }
203
204    /// The plaintext of secret `name`.
205    pub fn secret(&self, name: &str) -> Option<&str> {
206        self.secrets.get(name).map(String::as_str)
207    }
208}
209
210impl fmt::Debug for ToolCallContext {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.debug_struct("ToolCallContext").field("secrets", &self.secrets.keys().collect::<Vec<_>>()).finish()
213    }
214}
215
216/// A source of tools.
217pub trait ToolRuntime: Send + Sync + fmt::Debug {
218    /// Tools currently available.
219    fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
220
221    /// Invoke a tool with a JSON arguments object and a per-call context.
222    ///
223    /// `context` is empty unless this runtime [accepts secrets](ToolRuntime::accepts_secrets)
224    /// and the caller configured some. Runtimes that cannot forward it ignore it.
225    fn call<'a>(
226        &'a self,
227        name: &'a str,
228        arguments: serde_json::Value,
229        context: &'a ToolCallContext,
230    ) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
231
232    /// Whether this runtime may receive plaintext secrets in a [`ToolCallContext`].
233    ///
234    /// `false` by default. The plugin runtime returns `true` only for plugins that
235    /// request `permissions.secrets` and that the operator trusts.
236    fn accepts_secrets(&self) -> bool {
237        false
238    }
239}
240
241/// Service registered in [`crate::node::Services`]: named tool providers
242/// (e.g. `builtin`, `mcp:github`). Nodes reference tools as `provider/tool`.
243#[derive(Clone, Default)]
244pub struct ToolRegistry {
245    providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
246}
247
248impl fmt::Debug for ToolRegistry {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_list().entries(self.providers.keys()).finish()
251    }
252}
253
254impl ToolRegistry {
255    pub fn new() -> Self {
256        Self::default()
257    }
258
259    pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
260        self.providers.insert(provider.into(), runtime);
261        self
262    }
263
264    pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
265        self.providers.get(provider)
266    }
267
268    pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
269        self.providers.iter().map(|(k, v)| (k.as_str(), v))
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[test]
278    fn call_context_debug_hides_values() {
279        assert!(ToolCallContext::empty().is_empty());
280        let mut context = ToolCallContext::default();
281        context.secrets.insert("user_jwt".into(), "eyJ-secret-token".into());
282        assert_eq!(context.secret("user_jwt"), Some("eyJ-secret-token"));
283        assert_eq!(context.secret("other"), None);
284        let debug = format!("{context:?}");
285        assert!(debug.contains("user_jwt") && !debug.contains("eyJ-secret-token"), "{debug}");
286    }
287
288    #[test]
289    fn constructors_have_no_images() {
290        assert!(ToolOutput::text("a").images.is_empty());
291        let err = ToolOutput::error("b");
292        assert!(err.is_error && err.images.is_empty());
293        let out = ToolOutput::text("shot").with_image(ToolImage::png("aGVsbG8="));
294        assert_eq!(out.images.len(), 1);
295    }
296
297    #[test]
298    fn image_urls() {
299        assert_eq!(ToolImage::png("AAAA").to_url(), "data:image/png;base64,AAAA");
300        assert_eq!(ToolImage::Url { url: "https://x/a.png".into() }.to_url(), "https://x/a.png");
301    }
302
303    #[test]
304    fn serde_shapes() {
305        let images: Vec<ToolImage> = serde_json::from_value(serde_json::json!([
306            {"media_type": "image/png", "data_base64": "AAAA"},
307            {"url": "https://x/a.png"}
308        ]))
309        .unwrap();
310        assert_eq!(images[0], ToolImage::png("AAAA"));
311        assert_eq!(images[1], ToolImage::Url { url: "https://x/a.png".into() });
312        assert!(serde_json::from_value::<ToolImage>(serde_json::json!({"data": "AAAA"})).is_err());
313    }
314
315    #[test]
316    fn base64_lengths() {
317        assert_eq!(base64_decoded_len("aGVsbG8="), Some(5));
318        assert_eq!(base64_decoded_len("aGVsbG8"), Some(5));
319        assert_eq!(base64_decoded_len("aGVsbA=="), Some(4));
320        assert_eq!(base64_decoded_len("aGVs"), Some(3));
321        assert_eq!(base64_decoded_len("aGVsb"), None);
322        assert_eq!(base64_decoded_len("aGV="), Some(2));
323        assert_eq!(base64_decoded_len("aG V"), None);
324        assert_eq!(base64_decoded_len("aGVsbG8=="), None);
325        assert_eq!(base64_decoded_len(""), Some(0));
326    }
327
328    #[test]
329    fn limits_are_enforced() {
330        assert!(check_images(&[ToolImage::png("aGVsbG8="), ToolImage::jpeg("aGVs")]).is_ok());
331        let too_many = vec![ToolImage::png("aGVs"); MAX_TOOL_IMAGES + 1];
332        assert!(check_images(&too_many).unwrap_err().to_string().contains("limit of 4"));
333        let bmp = ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() };
334        assert!(check_images(&[bmp]).unwrap_err().to_string().contains("image/bmp"));
335        assert!(ToolImage::png("not base64!").check().is_err());
336        assert!(ToolImage::png("").check().is_err());
337        let big = "A".repeat((MAX_TOOL_IMAGE_BYTES / 3 + 1) * 4);
338        assert!(ToolImage::png(big).check().unwrap_err().to_string().contains("limit"));
339        let exact = "A".repeat(MAX_TOOL_IMAGE_BYTES / 3 * 4);
340        assert!(ToolImage::png(exact).check().is_ok());
341        assert!(ToolImage::Url { url: "http://x/a.png".into() }.check().is_err());
342        assert!(ToolImage::Url { url: "data:image/png;base64,AAAA".into() }.check().is_err());
343        assert!(ToolImage::Url { url: "HTTPS://x/a.png".into() }.check().is_ok());
344    }
345}