Skip to main content

graphrt_core/
tool_node.rs

1//! The generic `tool` node and [`NativeTools`], a [`ToolRuntime`] built from
2//! Rust closures.
3//!
4//! The `tool` node calls one tool of a provider registered in the
5//! [`ToolRegistry`] service:
6//!
7//! ```yaml
8//! - id: weather
9//!   type: tool
10//!   provider_id: builtin          # or e.g. "mcp:github"
11//!   tool_name: get_weather
12//!   tool_parameters:
13//!     city:  { type: variable, value: [start, city] }
14//!     units: { type: constant, value: metric }
15//!     note:  { type: mixed,    value: "asked by {{#sys.user_id#}}" }
16//! ```
17//!
18//! A simpler `arguments` map is also accepted: string values are templates
19//! (a lone `{{#a.b#}}` placeholder keeps its typed value), other values are
20//! constants.
21//!
22//! `tool_context` sends per-run values to the tool beside the arguments, for
23//! providers that accept them (the workspace tools take the user's directory
24//! this way with `--workspace-per-user`):
25//!
26//! ```yaml
27//!   tool_context:
28//!     scope: "{{#sys.user_id#}}"
29//! ```
30//!
31//! A tool with a price (`image/generate` with a `per_image` price) gets what
32//! the run's cost budget leaves and reports what the call cost: the node
33//! charges it to the budget and reports it as `usage.cost_micros`.
34//!
35//! Outputs: `text` (string), `json` (structured result, or `null`; when the text
36//! looks like JSON but does not parse, metadata `json_error` says why), `files`
37//! (array, currently always empty), `is_error` (bool) and `error` (the tool's error
38//! text, or `null`). A tool-reported error fails the node unless
39//! `ignore_tool_errors` is set, in which case `is_error` / `error` let a downstream
40//! branch react. `variable` arguments that do not resolve are sent as `null` and
41//! listed in metadata `missing_arguments`.
42
43use std::fmt;
44use std::future::Future;
45use std::sync::Arc;
46
47use futures::future::BoxFuture;
48use indexmap::IndexMap;
49use serde::Deserialize;
50
51use crate::dsl::NodeDoc;
52use crate::node::{ConfigError, Node, NodeContext, NodeError, NodeOutput, NodeResult, Registry, parse_config};
53use crate::pool::{Selector, VariablePool};
54use crate::template::Template;
55use crate::tool::{ToolCallContext, ToolError, ToolOutput, ToolRegistry, ToolRuntime, ToolSpec};
56use crate::value::Value;
57
58/// Node kind handled by [`ToolNode`].
59pub const KIND: &str = "tool";
60
61/// Register the `tool` node kind.
62pub fn register(registry: &mut Registry) {
63    registry.register_lazily_described(KIND, descriptor, |doc| {
64        ToolNode::from_doc(doc).map(|n| Arc::new(n) as Arc<dyn Node>)
65    });
66}
67
68/// Catalog descriptor of the `tool` node.
69pub fn descriptor() -> crate::catalog::NodeDescriptor {
70    use crate::catalog::schema::{nested, object, selector};
71    use crate::catalog::{NodeCategory, NodeDescriptor, OutputDescriptor};
72    use crate::value::ValueType;
73
74    let parameter = serde_json::json!({
75        "oneOf": [
76            nested(serde_json::json!({ "type": { "const": "mixed" }, "value": { "type": "string" } }), &["type", "value"]),
77            nested(serde_json::json!({ "type": { "const": "variable" }, "value": selector() }), &["type", "value"]),
78            nested(serde_json::json!({ "type": { "const": "constant" }, "value": {} }), &["type"])
79        ]
80    });
81    #[allow(unused_mut)]
82    let mut properties = serde_json::json!({
83        "provider_id": { "type": "string", "minLength": 1 },
84        "provider": { "type": "string", "minLength": 1 },
85        "provider_name": { "type": "string", "minLength": 1 },
86        "tool_name": { "type": "string", "minLength": 1 },
87        "tool_parameters": { "type": "object", "additionalProperties": parameter },
88        "tool_configurations": { "type": "object" },
89        "arguments": { "type": "object" },
90        "ignore_tool_errors": { "type": "boolean", "default": false }
91    });
92    #[cfg(feature = "tool-context")]
93    if let Some(fields) = properties.as_object_mut() {
94        fields.insert(
95            "tool_context".to_owned(),
96            serde_json::json!({ "type": "object", "additionalProperties": { "type": "string" } }),
97        );
98    }
99    NodeDescriptor::new(KIND, "Tool", NodeCategory::Integration)
100        .describe(
101            "Calls one tool from a registered tool provider (native tools, MCP servers, plugins). \
102             Arguments: `tool_parameters` (mixed template / variable / constant) override `arguments` \
103             (strings are templates) which override `tool_configurations` (constants).",
104        )
105        .icon("wrench")
106        .source("builtin")
107        .schema(object(properties, &["tool_name"]))
108        .output(OutputDescriptor::new("text", ValueType::String).describe("Text result"))
109        .output(OutputDescriptor::new("json", ValueType::Any).describe("Structured result, or the text parsed as JSON"))
110        .output(OutputDescriptor::new("files", ValueType::ArrayFile))
111        .output(OutputDescriptor::new("is_error", ValueType::Boolean))
112        .output(OutputDescriptor::new("error", ValueType::String).describe("Error text when the tool reported one"))
113}
114
115/// How one tool argument is produced.
116#[derive(Clone, Debug, PartialEq, Deserialize)]
117#[serde(tag = "type", rename_all = "lowercase")]
118enum ArgSource {
119    /// Text template, rendered against the pool.
120    Mixed { value: Template },
121    /// Value read from a selector (typed).
122    Variable { value: Selector },
123    /// Literal value.
124    Constant {
125        #[serde(default)]
126        value: Value,
127    },
128}
129
130#[derive(Debug, Deserialize)]
131struct ToolNodeConfig {
132    #[serde(alias = "provider", alias = "provider_name")]
133    provider_id: String,
134    tool_name: String,
135    #[serde(default)]
136    tool_parameters: IndexMap<String, ArgSource>,
137    /// Constant configuration parameters; lowest precedence.
138    #[serde(default)]
139    tool_configurations: IndexMap<String, Value>,
140    /// Shorthand: strings are templates, everything else a constant.
141    #[serde(default)]
142    arguments: IndexMap<String, Value>,
143    /// Per-run values for the tool (name -> template), never shown in events.
144    #[cfg(feature = "tool-context")]
145    #[serde(default)]
146    tool_context: IndexMap<String, Template>,
147    /// When true, a tool-reported error becomes a normal output instead of a node failure.
148    #[serde(default)]
149    ignore_tool_errors: bool,
150}
151
152/// Calls one tool from the [`ToolRegistry`] service.
153#[derive(Debug, Clone)]
154pub struct ToolNode {
155    provider: String,
156    tool: String,
157    /// Arguments in precedence order (later entries override earlier ones).
158    args: Vec<(String, ArgSource)>,
159    #[cfg(feature = "tool-context")]
160    tool_context: IndexMap<String, Template>,
161    ignore_tool_errors: bool,
162}
163
164impl ToolNode {
165    /// Build from a node document.
166    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
167        let cfg: ToolNodeConfig = parse_config(doc)?;
168        if cfg.provider_id.trim().is_empty() {
169            return Err(ConfigError::new(doc, "`provider_id` must not be empty"));
170        }
171        if cfg.tool_name.trim().is_empty() {
172            return Err(ConfigError::new(doc, "`tool_name` must not be empty"));
173        }
174        let mut args: Vec<(String, ArgSource)> = Vec::new();
175        for (k, v) in cfg.tool_configurations {
176            args.push((k, ArgSource::Constant { value: v }));
177        }
178        for (k, v) in cfg.arguments {
179            let source = match v {
180                Value::String(s) => ArgSource::Mixed { value: Template::parse(&s) },
181                other => ArgSource::Constant { value: other },
182            };
183            args.push((k, source));
184        }
185        for (k, v) in cfg.tool_parameters {
186            args.push((k, v));
187        }
188        Ok(Self {
189            provider: cfg.provider_id,
190            tool: cfg.tool_name,
191            args,
192            #[cfg(feature = "tool-context")]
193            tool_context: cfg.tool_context,
194            ignore_tool_errors: cfg.ignore_tool_errors,
195        })
196    }
197
198    /// Resolve arguments. Returns `(plaintext arguments for the call, masked copy for observability)`.
199    fn resolve_args(&self, pool: &VariablePool) -> (serde_json::Value, Value) {
200        let mut exposed = serde_json::Map::new();
201        let mut masked: IndexMap<String, Value> = IndexMap::new();
202        for (name, source) in &self.args {
203            match source {
204                // Text templates: render twice so the observable copy keeps secrets masked.
205                ArgSource::Mixed { value } if !matches!(value.parts(), [crate::template::Part::Var(_)]) => {
206                    exposed.insert(name.clone(), serde_json::Value::String(value.render_exposed(pool)));
207                    masked.insert(name.clone(), Value::from(value.render(pool)));
208                }
209                _ => {
210                    let value = match source {
211                        // A lone placeholder keeps the typed value (numbers stay numbers).
212                        ArgSource::Mixed { value } => value.resolve(pool),
213                        ArgSource::Variable { value } => pool.get_or_null(value),
214                        ArgSource::Constant { value } => value.clone(),
215                    };
216                    exposed.insert(name.clone(), value.to_json_exposed());
217                    masked.insert(name.clone(), value);
218                }
219            }
220        }
221        (serde_json::Value::Object(exposed), Value::from(masked))
222    }
223
224    async fn execute(&self, ctx: NodeContext) -> NodeResult {
225        let registry = ctx.require_service::<ToolRegistry>("tool registry")?;
226        let runtime = registry
227            .get(&self.provider)
228            .ok_or_else(|| NodeError::fatal("tool", format!("unknown tool provider `{}`", self.provider)))?
229            .clone();
230        let (arguments, masked_args) = self.resolve_args(&ctx.pool);
231        let missing = self.missing_variables(&ctx.pool);
232        #[cfg(feature = "tool-context")]
233        let owned_context = self.call_context(&ctx, runtime.accepts_secrets())?;
234        #[cfg(feature = "tool-context")]
235        let context = &owned_context;
236        // Arguments already carry rendered secrets here: the node config is written by the
237        // workflow author, not a model.
238        #[cfg(not(feature = "tool-context"))]
239        let context = ToolCallContext::empty();
240        let output =
241            runtime.call(&self.tool, arguments, context).await.map_err(|e| NodeError::new("tool", e.to_string()))?;
242        // A call the run's budget does not afford stops the run, as a model call
243        // would, even with `ignore_tool_errors`.
244        #[cfg(feature = "tool-error-types")]
245        if output.is_limit_exceeded() {
246            return Err(match ctx.budget() {
247                Some(budget) => budget.refuse(output.text),
248                None => NodeError::fatal(crate::tool::LIMIT_EXCEEDED, output.text),
249            });
250        }
251        if output.is_error && !self.ignore_tool_errors {
252            #[cfg(feature = "tool-error-types")]
253            let error_type = output.error_type.as_deref().unwrap_or("tool_error");
254            #[cfg(not(feature = "tool-error-types"))]
255            let error_type = "tool_error";
256            return Err(NodeError::fatal(error_type, output.text));
257        }
258        // Files a native tool returned in its structured result (plugins and MCP servers
259        // cannot create file values).
260        #[cfg(feature = "tool-files")]
261        let files: Vec<Value> = crate::tool::collect_files(&output.data).into_iter().map(Value::File).collect();
262        #[cfg(not(feature = "tool-files"))]
263        let files: Vec<Value> = Vec::new();
264        let (json, json_error) =
265            if output.data.is_null() { parse_json_text(&output.text) } else { (output.data, None) };
266        // With `ignore_tool_errors`, the failure stays visible to the graph through the
267        // `is_error` / `error` outputs so a downstream branch can react to it.
268        let error = if output.is_error { Value::from(output.text.as_str()) } else { Value::Null };
269        let mut result = NodeOutput::new()
270            .with("text", output.text)
271            .with("json", json)
272            .with("files", Value::array(files))
273            .with("is_error", output.is_error)
274            .with("error", error)
275            .meta("provider", self.provider.as_str())
276            .meta("tool", self.tool.as_str())
277            .meta("arguments", masked_args);
278        if let Some(e) = json_error {
279            result = result.meta("json_error", e);
280        }
281        if !missing.is_empty() {
282            result = result.meta("missing_arguments", Value::array(missing.into_iter().map(Value::from)));
283        }
284        // The engine charges a node's reported usage to the run's budget when it completes.
285        #[cfg(feature = "tool-context")]
286        if output.cost_micros > 0 {
287            result.usage = Some(crate::event::Usage { cost_micros: output.cost_micros, ..Default::default() });
288        }
289        Ok(result.into())
290    }
291
292    /// The per-call context: the rendered `tool_context`, and what the run's
293    /// cost budget leaves.
294    #[cfg(feature = "tool-context")]
295    ///
296    /// @throws NodeError - `tool_context_denied` (fatal) when the node sets a
297    ///   `tool_context` and the provider does not accept one.
298    fn call_context(&self, ctx: &NodeContext, accepts_secrets: bool) -> Result<ToolCallContext, NodeError> {
299        let mut context = ToolCallContext {
300            remaining_cost_micros: ctx.budget().and_then(crate::budget::RunBudget::remaining_cost_micros),
301            ..ToolCallContext::default()
302        };
303        if self.tool_context.is_empty() {
304            return Ok(context);
305        }
306        if !accepts_secrets {
307            return Err(NodeError::fatal(
308                "tool_context_denied",
309                format!("tool provider `{}` does not accept a tool context", self.provider),
310            ));
311        }
312        for (name, template) in &self.tool_context {
313            let value = template.render_exposed(&ctx.pool);
314            // A missing variable renders empty: leave the name out so the tool can refuse.
315            if value.is_empty() {
316                continue;
317            }
318            ctx.observe_secret(&value);
319            context.secrets.insert(name.clone(), value);
320        }
321        Ok(context)
322    }
323
324    /// Selectors of `variable` arguments that do not resolve (sent to the tool as `null`).
325    fn missing_variables(&self, pool: &VariablePool) -> Vec<String> {
326        self.args
327            .iter()
328            .filter_map(|(_, source)| match source {
329                ArgSource::Variable { value } if pool.get(value).is_none() => Some(value.to_string()),
330                _ => None,
331            })
332            .collect()
333    }
334}
335
336/// Structured view of a text result when it looks like a JSON object or array.
337/// Returns the parse error when it looks like JSON but is not valid.
338fn parse_json_text(text: &str) -> (Value, Option<String>) {
339    let trimmed = text.trim_start();
340    if trimmed.starts_with('{') || trimmed.starts_with('[') {
341        return match serde_json::from_slice::<serde_json::Value>(text.as_bytes()) {
342            Ok(json) => (Value::from_json(json), None),
343            Err(e) => (Value::Null, Some(e.to_string())),
344        };
345    }
346    (Value::Null, None)
347}
348
349impl Node for ToolNode {
350    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
351        Box::pin(self.execute(ctx))
352    }
353
354    fn inputs(&self) -> Vec<Selector> {
355        let mut out = Vec::new();
356        for (_, source) in &self.args {
357            match source {
358                ArgSource::Mixed { value } => out.extend(value.selectors().cloned()),
359                ArgSource::Variable { value } => out.push(value.clone()),
360                ArgSource::Constant { .. } => {}
361            }
362        }
363        #[cfg(feature = "tool-context")]
364        for template in self.tool_context.values() {
365            out.extend(template.selectors().cloned());
366        }
367        out
368    }
369}
370
371type ToolFn = Arc<dyn Fn(serde_json::Value) -> BoxFuture<'static, Result<ToolOutput, ToolError>> + Send + Sync>;
372
373/// A [`ToolRuntime`] whose tools are Rust closures.
374///
375/// ```
376/// use graphrt_core::tool::{ToolOutput, ToolSpec};
377/// use graphrt_core::tool_node::NativeTools;
378///
379/// let tools = NativeTools::new().with(
380///     ToolSpec {
381///         name: "echo".into(),
382///         description: "Echo the `text` argument".into(),
383///         parameters: serde_json::json!({
384///             "type": "object",
385///             "properties": { "text": { "type": "string" } },
386///             "required": ["text"]
387///         }),
388///         effects: Vec::new(),
389///     },
390///     |args| async move { Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default())) },
391/// );
392/// ```
393#[derive(Clone, Default)]
394pub struct NativeTools {
395    tools: IndexMap<String, (ToolSpec, ToolFn)>,
396}
397
398impl fmt::Debug for NativeTools {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        f.debug_struct("NativeTools").field("tools", &self.tools.keys().collect::<Vec<_>>()).finish()
401    }
402}
403
404impl NativeTools {
405    pub fn new() -> Self {
406        Self::default()
407    }
408
409    /// Add (or replace) a tool.
410    pub fn add<F, Fut>(&mut self, spec: ToolSpec, handler: F) -> &mut Self
411    where
412        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
413        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
414    {
415        let handler: ToolFn = Arc::new(move |args| Box::pin(handler(args)));
416        self.tools.insert(spec.name.clone(), (spec, handler));
417        self
418    }
419
420    /// Builder-style [`NativeTools::add`].
421    pub fn with<F, Fut>(mut self, spec: ToolSpec, handler: F) -> Self
422    where
423        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
424        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
425    {
426        self.add(spec, handler);
427        self
428    }
429
430    pub fn len(&self) -> usize {
431        self.tools.len()
432    }
433
434    pub fn is_empty(&self) -> bool {
435        self.tools.is_empty()
436    }
437}
438
439impl ToolRuntime for NativeTools {
440    fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
441        let specs = self.tools.values().map(|(spec, _)| spec.clone()).collect();
442        Box::pin(futures::future::ready(Ok(specs)))
443    }
444
445    /// Native handlers take only arguments; the context is not forwarded
446    /// (`accepts_secrets` stays `false`).
447    fn call<'a>(
448        &'a self,
449        name: &'a str,
450        arguments: serde_json::Value,
451        _context: &'a ToolCallContext,
452    ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
453        let Some((spec, handler)) = self.tools.get(name) else {
454            return Box::pin(futures::future::ready(Err(ToolError {
455                tool: name.to_owned(),
456                message: "unknown tool".to_owned(),
457            })));
458        };
459        if let Err(message) = check_required(&spec.parameters, &arguments) {
460            return Box::pin(futures::future::ready(Err(ToolError { tool: name.to_owned(), message })));
461        }
462        handler(arguments)
463    }
464}
465
466/// Lightweight argument check: the arguments must be an object containing every
467/// property listed in the schema's `required` array. Full JSON Schema validation
468/// is left to the tool itself.
469fn check_required(schema: &serde_json::Value, arguments: &serde_json::Value) -> Result<(), String> {
470    let Some(args) = arguments.as_object() else {
471        return Err("arguments must be a JSON object".to_owned());
472    };
473    let required = schema.get("required").and_then(serde_json::Value::as_array);
474    let missing: Vec<&str> = required
475        .into_iter()
476        .flatten()
477        .filter_map(serde_json::Value::as_str)
478        .filter(|key| args.get(*key).is_none_or(serde_json::Value::is_null))
479        .collect();
480    if missing.is_empty() { Ok(()) } else { Err(format!("missing required arguments: {}", missing.join(", "))) }
481}
482
483#[cfg(test)]
484mod tests {
485    use std::sync::Mutex;
486
487    use super::*;
488    use crate::node::{NodeOutcome, Services};
489
490    #[derive(Debug, Default)]
491    struct Recorder {
492        calls: Mutex<Vec<(String, serde_json::Value)>>,
493        reply: Option<ToolOutput>,
494    }
495
496    impl ToolRuntime for Recorder {
497        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
498            Box::pin(futures::future::ready(Ok(Vec::new())))
499        }
500        fn call<'a>(
501            &'a self,
502            name: &'a str,
503            arguments: serde_json::Value,
504            _context: &'a ToolCallContext,
505        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
506            self.calls.lock().unwrap().push((name.to_owned(), arguments));
507            let reply = self.reply.clone().unwrap_or_else(|| ToolOutput::text("{\"ok\":true}"));
508            Box::pin(futures::future::ready(Ok(reply)))
509        }
510    }
511
512    fn doc(config: serde_json::Value) -> NodeDoc {
513        NodeDoc::new("t", KIND, config)
514    }
515
516    fn pool() -> VariablePool {
517        let mut p = VariablePool::new();
518        p.insert("start", "city", Value::from("Jakarta"));
519        p.insert("start", "days", Value::Int(3));
520        p.insert("env", "TOKEN", Value::Secret(Arc::from("s3cret")));
521        p
522    }
523
524    fn ctx_with(runtime: Arc<dyn ToolRuntime>) -> NodeContext {
525        let mut reg = ToolRegistry::new();
526        reg.add("mock", runtime);
527        NodeContext::for_test("t", pool()).with_services(Arc::new(Services::new().with(reg)))
528    }
529
530    fn completed(r: NodeResult) -> NodeOutput {
531        match r {
532            Ok(NodeOutcome::Completed(o)) => o,
533            other => panic!("unexpected {other:?}"),
534        }
535    }
536
537    #[tokio::test]
538    async fn resolves_all_argument_kinds() {
539        let rec = Arc::new(Recorder::default());
540        let node = ToolNode::from_doc(&doc(serde_json::json!({
541            "provider_id": "mock",
542            "tool_name": "weather",
543            "tool_configurations": {"units": "imperial", "lang": "en"},
544            "arguments": {"note": "for {{#start.city#}}", "raw": 5},
545            "tool_parameters": {
546                "city": {"type": "variable", "value": ["start", "city"]},
547                "days": {"type": "mixed", "value": "{{#start.days#}}"},
548                "units": {"type": "constant", "value": "metric"},
549                "auth": {"type": "mixed", "value": "Bearer {{#env.TOKEN#}}"}
550            }
551        })))
552        .unwrap();
553        let out = completed(node.run(ctx_with(rec.clone())).await);
554        let calls = rec.calls.lock().unwrap();
555        let (name, args) = &calls[0];
556        assert_eq!(name, "weather");
557        assert_eq!(args["city"], "Jakarta");
558        assert_eq!(args["days"], 3);
559        assert_eq!(args["units"], "metric", "tool_parameters override configurations");
560        assert_eq!(args["lang"], "en");
561        assert_eq!(args["note"], "for Jakarta");
562        assert_eq!(args["raw"], 5);
563        assert_eq!(args["auth"], "Bearer s3cret", "tool receives the plaintext secret");
564        // Observability metadata never contains the secret.
565        let meta = serde_json::to_string(&out.metadata).unwrap();
566        assert!(!meta.contains("s3cret"));
567        assert_eq!(out.outputs["text"], Value::from("{\"ok\":true}"));
568        assert_eq!(out.outputs["json"].get_path(&["ok"]), Some(Value::Bool(true)));
569        assert_eq!(out.outputs["files"], Value::array([]));
570        assert_eq!(node.inputs().len(), 4); // note, city, days, auth
571    }
572
573    #[tokio::test]
574    async fn tool_error_fails_unless_ignored() {
575        let rec = Arc::new(Recorder { reply: Some(ToolOutput::error("boom")), ..Recorder::default() });
576        let cfg = serde_json::json!({"provider": "mock", "tool_name": "x"});
577        let node = ToolNode::from_doc(&doc(cfg)).unwrap();
578        let err = node.run(ctx_with(rec.clone())).await.unwrap_err();
579        assert_eq!(err.kind, "tool_error");
580        assert!(!err.retryable);
581
582        let cfg = serde_json::json!({"provider": "mock", "tool_name": "x", "ignore_tool_errors": true});
583        let node = ToolNode::from_doc(&doc(cfg)).unwrap();
584        let out = completed(node.run(ctx_with(rec)).await);
585        assert_eq!(out.outputs["text"], Value::from("boom"));
586        assert_eq!(out.outputs["is_error"], Value::Bool(true));
587        assert_eq!(out.outputs["error"], Value::from("boom"));
588    }
589
590    #[tokio::test]
591    async fn successful_call_has_no_error_output() {
592        let rec = Arc::new(Recorder { reply: Some(ToolOutput::text("{\"a\": 1")), ..Recorder::default() });
593        let node = ToolNode::from_doc(&doc(serde_json::json!({
594            "provider": "mock", "tool_name": "x",
595            "tool_parameters": {"city": {"type": "variable", "value": ["start", "nope"]}}
596        })))
597        .unwrap();
598        let out = completed(node.run(ctx_with(rec)).await);
599        assert_eq!(out.outputs["is_error"], Value::Bool(false));
600        assert_eq!(out.outputs["error"], Value::Null);
601        // Looks like JSON but is truncated: `json` is null and the reason is recorded.
602        assert_eq!(out.outputs["json"], Value::Null);
603        assert!(out.metadata.contains_key("json_error"));
604        assert_eq!(out.metadata["missing_arguments"], Value::array([Value::from("start.nope")]));
605    }
606
607    #[tokio::test]
608    async fn missing_provider_or_registry_is_fatal() {
609        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "nope", "tool_name": "x"}))).unwrap();
610        let err = node.run(ctx_with(Arc::new(Recorder::default()))).await.unwrap_err();
611        assert!(!err.retryable);
612        let err = node.run(NodeContext::for_test("t", pool())).await.unwrap_err();
613        assert_eq!(err.kind, "missing_service");
614    }
615
616    /// Keeps the context of every call and answers with a cost.
617    #[cfg(feature = "tool-context")]
618    #[derive(Debug, Default)]
619    struct Priced {
620        accepts: bool,
621        cost_micros: u64,
622        /// Refuse every call with an error of this type.
623        #[cfg(feature = "tool-error-types")]
624        refusal: Option<&'static str>,
625        contexts: Mutex<Vec<ToolCallContext>>,
626    }
627
628    #[cfg(feature = "tool-context")]
629    impl ToolRuntime for Priced {
630        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
631            Box::pin(futures::future::ready(Ok(Vec::new())))
632        }
633        fn call<'a>(
634            &'a self,
635            _name: &'a str,
636            _arguments: serde_json::Value,
637            context: &'a ToolCallContext,
638        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
639            self.contexts.lock().unwrap().push(context.clone());
640            #[cfg(feature = "tool-error-types")]
641            if let Some(error_type) = self.refusal {
642                return Box::pin(futures::future::ready(Ok(ToolOutput::typed_error(error_type, "refused"))));
643            }
644            let output = ToolOutput { cost_micros: self.cost_micros, ..ToolOutput::text("made") };
645            Box::pin(futures::future::ready(Ok(output)))
646        }
647        fn accepts_secrets(&self) -> bool {
648            self.accepts
649        }
650    }
651
652    #[cfg(feature = "tool-context")]
653    #[tokio::test]
654    async fn tool_context_reaches_a_tool_that_accepts_it_and_never_the_events() {
655        let priced = Arc::new(Priced { accepts: true, ..Priced::default() });
656        let node = ToolNode::from_doc(&doc(serde_json::json!({
657            "provider_id": "mock", "tool_name": "x",
658            "tool_context": {"scope": "{{#env.TOKEN#}}", "region": "{{#start.city#}}", "empty": "{{#start.nope#}}"}
659        })))
660        .unwrap();
661        let out = completed(node.run(ctx_with(priced.clone())).await);
662        let context = priced.contexts.lock().unwrap().pop().unwrap();
663        assert_eq!(context.secret("scope"), Some("s3cret"));
664        assert_eq!(context.secret("region"), Some("Jakarta"));
665        assert_eq!(context.secret("empty"), None, "a value that does not resolve is left out");
666        assert_eq!(context.remaining_cost_micros, None, "no budget outside an engine");
667        assert!(!serde_json::to_string(&out.metadata).unwrap().contains("s3cret"));
668        assert!(out.usage.is_none(), "a free tool reports no usage");
669        assert_eq!(node.inputs().len(), 3);
670
671        // A provider that does not take a context is told so, not silently skipped.
672        let closed = Arc::new(Priced::default());
673        let err = node.run(ctx_with(closed.clone())).await.unwrap_err();
674        assert_eq!(err.kind, "tool_context_denied");
675        assert!(closed.contexts.lock().unwrap().is_empty());
676    }
677
678    #[cfg(feature = "tool-context")]
679    #[tokio::test]
680    async fn a_priced_tool_learns_the_budget_left_and_reports_its_cost() {
681        let priced = Arc::new(Priced { cost_micros: 40_000, ..Priced::default() });
682        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "mock", "tool_name": "x"}))).unwrap();
683        let budget = Arc::new(crate::budget::RunBudget::limited(None, Some(100_000)));
684        budget.charge(&crate::event::Usage::default(), 30_000).unwrap();
685        let out = completed(node.run(ctx_with(priced.clone()).with_budget(budget, None)).await);
686        assert_eq!(priced.contexts.lock().unwrap()[0].remaining_cost_micros, Some(70_000));
687        assert_eq!(out.usage.map(|usage| usage.cost_micros), Some(40_000));
688    }
689
690    #[cfg(all(feature = "tool-context", feature = "tool-error-types"))]
691    #[tokio::test]
692    async fn a_typed_tool_error_fails_the_node_with_its_type() {
693        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "mock", "tool_name": "x"}))).unwrap();
694        let pricing = Arc::new(Priced { refusal: Some("price_missing"), ..Priced::default() });
695        let err = node.run(ctx_with(pricing)).await.unwrap_err();
696        assert_eq!((err.kind.as_str(), err.message.as_str(), err.retryable), ("price_missing", "refused", false));
697
698        // A call the budget does not afford stops the run, even with `ignore_tool_errors`.
699        let ignoring = ToolNode::from_doc(&doc(serde_json::json!({
700            "provider_id": "mock", "tool_name": "x", "ignore_tool_errors": true
701        })))
702        .unwrap();
703        let stopped = Arc::new(std::sync::atomic::AtomicBool::new(false));
704        let flag = Arc::clone(&stopped);
705        let budget = Arc::new(crate::budget::RunBudget::new(
706            None,
707            Some(100),
708            (0, 0),
709            Box::new(move |_| flag.store(true, std::sync::atomic::Ordering::Release)),
710        ));
711        let refusing = Arc::new(Priced { refusal: Some("limit_exceeded"), ..Priced::default() });
712        let err = ignoring.run(ctx_with(refusing.clone()).with_budget(budget, None)).await.unwrap_err();
713        assert_eq!(err.kind, "limit_exceeded");
714        assert!(stopped.load(std::sync::atomic::Ordering::Acquire), "the run's budget stops the run");
715        let err = ignoring.run(ctx_with(refusing)).await.unwrap_err();
716        assert_eq!(err.kind, "limit_exceeded", "outside an engine too");
717
718        // Other typed errors are ignored like any tool error.
719        let pricing = Arc::new(Priced { refusal: Some("price_missing"), ..Priced::default() });
720        let out = completed(ignoring.run(ctx_with(pricing)).await);
721        assert_eq!(out.outputs["is_error"], Value::Bool(true));
722    }
723
724    #[test]
725    fn rejects_invalid_config() {
726        assert!(ToolNode::from_doc(&doc(serde_json::json!({"tool_name": "x"}))).is_err());
727        assert!(ToolNode::from_doc(&doc(serde_json::json!({"provider_id": " ", "tool_name": "x"}))).is_err());
728        let bad_param = serde_json::json!({"provider_id": "p", "tool_name": "x",
729            "tool_parameters": {"a": {"type": "variable", "value": ["only"]}}});
730        assert!(ToolNode::from_doc(&doc(bad_param)).is_err());
731    }
732
733    #[test]
734    fn registers_kind() {
735        let mut r = Registry::new();
736        register(&mut r);
737        assert!(r.contains(KIND));
738    }
739
740    fn echo_spec() -> ToolSpec {
741        ToolSpec {
742            name: "echo".into(),
743            description: "echo".into(),
744            parameters: serde_json::json!({"type": "object", "required": ["text"]}),
745            effects: Vec::new(),
746        }
747    }
748
749    #[tokio::test]
750    async fn native_tools_dispatch_and_validate() {
751        let tools = NativeTools::new().with(echo_spec(), |args| async move {
752            Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default().to_uppercase()))
753        });
754        assert_eq!(tools.len(), 1);
755        assert_eq!(tools.list().await.unwrap()[0].name, "echo");
756        let out = tools.call("echo", serde_json::json!({"text": "hi"}), ToolCallContext::empty()).await.unwrap();
757        assert_eq!(out.text, "HI");
758        let err = tools.call("echo", serde_json::json!({}), ToolCallContext::empty()).await.unwrap_err();
759        assert!(err.message.contains("text"));
760        assert!(tools.call("echo", serde_json::json!("str"), ToolCallContext::empty()).await.is_err());
761        assert!(tools.call("nope", serde_json::json!({}), ToolCallContext::empty()).await.is_err());
762    }
763
764    #[tokio::test]
765    async fn tool_node_with_native_tools() {
766        let tools = NativeTools::new().with(echo_spec(), |args| async move {
767            Ok(ToolOutput {
768                text: "done".into(),
769                data: Value::from_json(args),
770                is_error: false,
771                ..ToolOutput::default()
772            })
773        });
774        let node = ToolNode::from_doc(&doc(serde_json::json!({
775            "provider_id": "mock", "tool_name": "echo", "arguments": {"text": "{{#start.city#}}"}
776        })))
777        .unwrap();
778        let out = completed(node.run(ctx_with(Arc::new(tools))).await);
779        assert_eq!(out.outputs["json"].get_path(&["text"]), Some(Value::from("Jakarta")));
780    }
781}