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 context = self.call_context(&ctx, runtime.accepts_secrets())?;
234        // Arguments already carry rendered secrets here: the node config is written by the
235        // workflow author, not a model.
236        #[cfg(not(feature = "tool-context"))]
237        let context = ToolCallContext::empty();
238        let output =
239            runtime.call(&self.tool, arguments, &context).await.map_err(|e| NodeError::new("tool", e.to_string()))?;
240        if output.is_error && !self.ignore_tool_errors {
241            return Err(NodeError::fatal("tool_error", output.text));
242        }
243        // Files a native tool returned in its structured result (plugins and MCP servers
244        // cannot create file values).
245        #[cfg(feature = "tool-files")]
246        let files: Vec<Value> = crate::tool::collect_files(&output.data).into_iter().map(Value::File).collect();
247        #[cfg(not(feature = "tool-files"))]
248        let files: Vec<Value> = Vec::new();
249        let (json, json_error) =
250            if output.data.is_null() { parse_json_text(&output.text) } else { (output.data, None) };
251        // With `ignore_tool_errors`, the failure stays visible to the graph through the
252        // `is_error` / `error` outputs so a downstream branch can react to it.
253        let error = if output.is_error { Value::from(output.text.as_str()) } else { Value::Null };
254        let mut result = NodeOutput::new()
255            .with("text", output.text)
256            .with("json", json)
257            .with("files", Value::array(files))
258            .with("is_error", output.is_error)
259            .with("error", error)
260            .meta("provider", self.provider.as_str())
261            .meta("tool", self.tool.as_str())
262            .meta("arguments", masked_args);
263        if let Some(e) = json_error {
264            result = result.meta("json_error", e);
265        }
266        if !missing.is_empty() {
267            result = result.meta("missing_arguments", Value::array(missing.into_iter().map(Value::from)));
268        }
269        // The engine charges a node's reported usage to the run's budget when it completes.
270        #[cfg(feature = "tool-context")]
271        if output.cost_micros > 0 {
272            result.usage = Some(crate::event::Usage { cost_micros: output.cost_micros, ..Default::default() });
273        }
274        Ok(result.into())
275    }
276
277    /// The per-call context: the rendered `tool_context`, and what the run's
278    /// cost budget leaves.
279    #[cfg(feature = "tool-context")]
280    ///
281    /// @throws NodeError - `tool_context_denied` (fatal) when the node sets a
282    ///   `tool_context` and the provider does not accept one.
283    fn call_context(&self, ctx: &NodeContext, accepts_secrets: bool) -> Result<ToolCallContext, NodeError> {
284        let mut context = ToolCallContext {
285            remaining_cost_micros: ctx.budget().and_then(crate::budget::RunBudget::remaining_cost_micros),
286            ..ToolCallContext::default()
287        };
288        if self.tool_context.is_empty() {
289            return Ok(context);
290        }
291        if !accepts_secrets {
292            return Err(NodeError::fatal(
293                "tool_context_denied",
294                format!("tool provider `{}` does not accept a tool context", self.provider),
295            ));
296        }
297        for (name, template) in &self.tool_context {
298            let value = template.render_exposed(&ctx.pool);
299            // A missing variable renders empty: leave the name out so the tool can refuse.
300            if value.is_empty() {
301                continue;
302            }
303            ctx.observe_secret(&value);
304            context.secrets.insert(name.clone(), value);
305        }
306        Ok(context)
307    }
308
309    /// Selectors of `variable` arguments that do not resolve (sent to the tool as `null`).
310    fn missing_variables(&self, pool: &VariablePool) -> Vec<String> {
311        self.args
312            .iter()
313            .filter_map(|(_, source)| match source {
314                ArgSource::Variable { value } if pool.get(value).is_none() => Some(value.to_string()),
315                _ => None,
316            })
317            .collect()
318    }
319}
320
321/// Structured view of a text result when it looks like a JSON object or array.
322/// Returns the parse error when it looks like JSON but is not valid.
323fn parse_json_text(text: &str) -> (Value, Option<String>) {
324    let trimmed = text.trim_start();
325    if trimmed.starts_with('{') || trimmed.starts_with('[') {
326        return match serde_json::from_slice::<serde_json::Value>(text.as_bytes()) {
327            Ok(json) => (Value::from_json(json), None),
328            Err(e) => (Value::Null, Some(e.to_string())),
329        };
330    }
331    (Value::Null, None)
332}
333
334impl Node for ToolNode {
335    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
336        Box::pin(self.execute(ctx))
337    }
338
339    fn inputs(&self) -> Vec<Selector> {
340        let mut out = Vec::new();
341        for (_, source) in &self.args {
342            match source {
343                ArgSource::Mixed { value } => out.extend(value.selectors().cloned()),
344                ArgSource::Variable { value } => out.push(value.clone()),
345                ArgSource::Constant { .. } => {}
346            }
347        }
348        #[cfg(feature = "tool-context")]
349        for template in self.tool_context.values() {
350            out.extend(template.selectors().cloned());
351        }
352        out
353    }
354}
355
356type ToolFn = Arc<dyn Fn(serde_json::Value) -> BoxFuture<'static, Result<ToolOutput, ToolError>> + Send + Sync>;
357
358/// A [`ToolRuntime`] whose tools are Rust closures.
359///
360/// ```
361/// use graphrt_core::tool::{ToolOutput, ToolSpec};
362/// use graphrt_core::tool_node::NativeTools;
363///
364/// let tools = NativeTools::new().with(
365///     ToolSpec {
366///         name: "echo".into(),
367///         description: "Echo the `text` argument".into(),
368///         parameters: serde_json::json!({
369///             "type": "object",
370///             "properties": { "text": { "type": "string" } },
371///             "required": ["text"]
372///         }),
373///         effects: Vec::new(),
374///     },
375///     |args| async move { Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default())) },
376/// );
377/// ```
378#[derive(Clone, Default)]
379pub struct NativeTools {
380    tools: IndexMap<String, (ToolSpec, ToolFn)>,
381}
382
383impl fmt::Debug for NativeTools {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        f.debug_struct("NativeTools").field("tools", &self.tools.keys().collect::<Vec<_>>()).finish()
386    }
387}
388
389impl NativeTools {
390    pub fn new() -> Self {
391        Self::default()
392    }
393
394    /// Add (or replace) a tool.
395    pub fn add<F, Fut>(&mut self, spec: ToolSpec, handler: F) -> &mut Self
396    where
397        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
398        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
399    {
400        let handler: ToolFn = Arc::new(move |args| Box::pin(handler(args)));
401        self.tools.insert(spec.name.clone(), (spec, handler));
402        self
403    }
404
405    /// Builder-style [`NativeTools::add`].
406    pub fn with<F, Fut>(mut self, spec: ToolSpec, handler: F) -> Self
407    where
408        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
409        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
410    {
411        self.add(spec, handler);
412        self
413    }
414
415    pub fn len(&self) -> usize {
416        self.tools.len()
417    }
418
419    pub fn is_empty(&self) -> bool {
420        self.tools.is_empty()
421    }
422}
423
424impl ToolRuntime for NativeTools {
425    fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
426        let specs = self.tools.values().map(|(spec, _)| spec.clone()).collect();
427        Box::pin(futures::future::ready(Ok(specs)))
428    }
429
430    /// Native handlers take only arguments; the context is not forwarded
431    /// (`accepts_secrets` stays `false`).
432    fn call<'a>(
433        &'a self,
434        name: &'a str,
435        arguments: serde_json::Value,
436        _context: &'a ToolCallContext,
437    ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
438        let Some((spec, handler)) = self.tools.get(name) else {
439            return Box::pin(futures::future::ready(Err(ToolError {
440                tool: name.to_owned(),
441                message: "unknown tool".to_owned(),
442            })));
443        };
444        if let Err(message) = check_required(&spec.parameters, &arguments) {
445            return Box::pin(futures::future::ready(Err(ToolError { tool: name.to_owned(), message })));
446        }
447        handler(arguments)
448    }
449}
450
451/// Lightweight argument check: the arguments must be an object containing every
452/// property listed in the schema's `required` array. Full JSON Schema validation
453/// is left to the tool itself.
454fn check_required(schema: &serde_json::Value, arguments: &serde_json::Value) -> Result<(), String> {
455    let Some(args) = arguments.as_object() else {
456        return Err("arguments must be a JSON object".to_owned());
457    };
458    let required = schema.get("required").and_then(serde_json::Value::as_array);
459    let missing: Vec<&str> = required
460        .into_iter()
461        .flatten()
462        .filter_map(serde_json::Value::as_str)
463        .filter(|key| args.get(*key).is_none_or(serde_json::Value::is_null))
464        .collect();
465    if missing.is_empty() { Ok(()) } else { Err(format!("missing required arguments: {}", missing.join(", "))) }
466}
467
468#[cfg(test)]
469mod tests {
470    use std::sync::Mutex;
471
472    use super::*;
473    use crate::node::{NodeOutcome, Services};
474
475    #[derive(Debug, Default)]
476    struct Recorder {
477        calls: Mutex<Vec<(String, serde_json::Value)>>,
478        reply: Option<ToolOutput>,
479    }
480
481    impl ToolRuntime for Recorder {
482        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
483            Box::pin(futures::future::ready(Ok(Vec::new())))
484        }
485        fn call<'a>(
486            &'a self,
487            name: &'a str,
488            arguments: serde_json::Value,
489            _context: &'a ToolCallContext,
490        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
491            self.calls.lock().unwrap().push((name.to_owned(), arguments));
492            let reply = self.reply.clone().unwrap_or_else(|| ToolOutput::text("{\"ok\":true}"));
493            Box::pin(futures::future::ready(Ok(reply)))
494        }
495    }
496
497    fn doc(config: serde_json::Value) -> NodeDoc {
498        NodeDoc::new("t", KIND, config)
499    }
500
501    fn pool() -> VariablePool {
502        let mut p = VariablePool::new();
503        p.insert("start", "city", Value::from("Jakarta"));
504        p.insert("start", "days", Value::Int(3));
505        p.insert("env", "TOKEN", Value::Secret(Arc::from("s3cret")));
506        p
507    }
508
509    fn ctx_with(runtime: Arc<dyn ToolRuntime>) -> NodeContext {
510        let mut reg = ToolRegistry::new();
511        reg.add("mock", runtime);
512        NodeContext::for_test("t", pool()).with_services(Arc::new(Services::new().with(reg)))
513    }
514
515    fn completed(r: NodeResult) -> NodeOutput {
516        match r {
517            Ok(NodeOutcome::Completed(o)) => o,
518            other => panic!("unexpected {other:?}"),
519        }
520    }
521
522    #[tokio::test]
523    async fn resolves_all_argument_kinds() {
524        let rec = Arc::new(Recorder::default());
525        let node = ToolNode::from_doc(&doc(serde_json::json!({
526            "provider_id": "mock",
527            "tool_name": "weather",
528            "tool_configurations": {"units": "imperial", "lang": "en"},
529            "arguments": {"note": "for {{#start.city#}}", "raw": 5},
530            "tool_parameters": {
531                "city": {"type": "variable", "value": ["start", "city"]},
532                "days": {"type": "mixed", "value": "{{#start.days#}}"},
533                "units": {"type": "constant", "value": "metric"},
534                "auth": {"type": "mixed", "value": "Bearer {{#env.TOKEN#}}"}
535            }
536        })))
537        .unwrap();
538        let out = completed(node.run(ctx_with(rec.clone())).await);
539        let calls = rec.calls.lock().unwrap();
540        let (name, args) = &calls[0];
541        assert_eq!(name, "weather");
542        assert_eq!(args["city"], "Jakarta");
543        assert_eq!(args["days"], 3);
544        assert_eq!(args["units"], "metric", "tool_parameters override configurations");
545        assert_eq!(args["lang"], "en");
546        assert_eq!(args["note"], "for Jakarta");
547        assert_eq!(args["raw"], 5);
548        assert_eq!(args["auth"], "Bearer s3cret", "tool receives the plaintext secret");
549        // Observability metadata never contains the secret.
550        let meta = serde_json::to_string(&out.metadata).unwrap();
551        assert!(!meta.contains("s3cret"));
552        assert_eq!(out.outputs["text"], Value::from("{\"ok\":true}"));
553        assert_eq!(out.outputs["json"].get_path(&["ok"]), Some(Value::Bool(true)));
554        assert_eq!(out.outputs["files"], Value::array([]));
555        assert_eq!(node.inputs().len(), 4); // note, city, days, auth
556    }
557
558    #[tokio::test]
559    async fn tool_error_fails_unless_ignored() {
560        let rec = Arc::new(Recorder { reply: Some(ToolOutput::error("boom")), ..Recorder::default() });
561        let cfg = serde_json::json!({"provider": "mock", "tool_name": "x"});
562        let node = ToolNode::from_doc(&doc(cfg)).unwrap();
563        let err = node.run(ctx_with(rec.clone())).await.unwrap_err();
564        assert_eq!(err.kind, "tool_error");
565        assert!(!err.retryable);
566
567        let cfg = serde_json::json!({"provider": "mock", "tool_name": "x", "ignore_tool_errors": true});
568        let node = ToolNode::from_doc(&doc(cfg)).unwrap();
569        let out = completed(node.run(ctx_with(rec)).await);
570        assert_eq!(out.outputs["text"], Value::from("boom"));
571        assert_eq!(out.outputs["is_error"], Value::Bool(true));
572        assert_eq!(out.outputs["error"], Value::from("boom"));
573    }
574
575    #[tokio::test]
576    async fn successful_call_has_no_error_output() {
577        let rec = Arc::new(Recorder { reply: Some(ToolOutput::text("{\"a\": 1")), ..Recorder::default() });
578        let node = ToolNode::from_doc(&doc(serde_json::json!({
579            "provider": "mock", "tool_name": "x",
580            "tool_parameters": {"city": {"type": "variable", "value": ["start", "nope"]}}
581        })))
582        .unwrap();
583        let out = completed(node.run(ctx_with(rec)).await);
584        assert_eq!(out.outputs["is_error"], Value::Bool(false));
585        assert_eq!(out.outputs["error"], Value::Null);
586        // Looks like JSON but is truncated: `json` is null and the reason is recorded.
587        assert_eq!(out.outputs["json"], Value::Null);
588        assert!(out.metadata.contains_key("json_error"));
589        assert_eq!(out.metadata["missing_arguments"], Value::array([Value::from("start.nope")]));
590    }
591
592    #[tokio::test]
593    async fn missing_provider_or_registry_is_fatal() {
594        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "nope", "tool_name": "x"}))).unwrap();
595        let err = node.run(ctx_with(Arc::new(Recorder::default()))).await.unwrap_err();
596        assert!(!err.retryable);
597        let err = node.run(NodeContext::for_test("t", pool())).await.unwrap_err();
598        assert_eq!(err.kind, "missing_service");
599    }
600
601    /// Keeps the context of every call and answers with a cost.
602    #[cfg(feature = "tool-context")]
603    #[derive(Debug, Default)]
604    struct Priced {
605        accepts: bool,
606        cost_micros: u64,
607        contexts: Mutex<Vec<ToolCallContext>>,
608    }
609
610    #[cfg(feature = "tool-context")]
611    impl ToolRuntime for Priced {
612        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
613            Box::pin(futures::future::ready(Ok(Vec::new())))
614        }
615        fn call<'a>(
616            &'a self,
617            _name: &'a str,
618            _arguments: serde_json::Value,
619            context: &'a ToolCallContext,
620        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
621            self.contexts.lock().unwrap().push(context.clone());
622            let output = ToolOutput { cost_micros: self.cost_micros, ..ToolOutput::text("made") };
623            Box::pin(futures::future::ready(Ok(output)))
624        }
625        fn accepts_secrets(&self) -> bool {
626            self.accepts
627        }
628    }
629
630    #[cfg(feature = "tool-context")]
631    #[tokio::test]
632    async fn tool_context_reaches_a_tool_that_accepts_it_and_never_the_events() {
633        let priced = Arc::new(Priced { accepts: true, ..Priced::default() });
634        let node = ToolNode::from_doc(&doc(serde_json::json!({
635            "provider_id": "mock", "tool_name": "x",
636            "tool_context": {"scope": "{{#env.TOKEN#}}", "region": "{{#start.city#}}", "empty": "{{#start.nope#}}"}
637        })))
638        .unwrap();
639        let out = completed(node.run(ctx_with(priced.clone())).await);
640        let context = priced.contexts.lock().unwrap().pop().unwrap();
641        assert_eq!(context.secret("scope"), Some("s3cret"));
642        assert_eq!(context.secret("region"), Some("Jakarta"));
643        assert_eq!(context.secret("empty"), None, "a value that does not resolve is left out");
644        assert_eq!(context.remaining_cost_micros, None, "no budget outside an engine");
645        assert!(!serde_json::to_string(&out.metadata).unwrap().contains("s3cret"));
646        assert!(out.usage.is_none(), "a free tool reports no usage");
647        assert_eq!(node.inputs().len(), 3);
648
649        // A provider that does not take a context is told so, not silently skipped.
650        let closed = Arc::new(Priced::default());
651        let err = node.run(ctx_with(closed.clone())).await.unwrap_err();
652        assert_eq!(err.kind, "tool_context_denied");
653        assert!(closed.contexts.lock().unwrap().is_empty());
654    }
655
656    #[cfg(feature = "tool-context")]
657    #[tokio::test]
658    async fn a_priced_tool_learns_the_budget_left_and_reports_its_cost() {
659        let priced = Arc::new(Priced { cost_micros: 40_000, ..Priced::default() });
660        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "mock", "tool_name": "x"}))).unwrap();
661        let budget = Arc::new(crate::budget::RunBudget::limited(None, Some(100_000)));
662        budget.charge(&crate::event::Usage::default(), 30_000).unwrap();
663        let out = completed(node.run(ctx_with(priced.clone()).with_budget(budget, None)).await);
664        assert_eq!(priced.contexts.lock().unwrap()[0].remaining_cost_micros, Some(70_000));
665        assert_eq!(out.usage.map(|usage| usage.cost_micros), Some(40_000));
666    }
667
668    #[test]
669    fn rejects_invalid_config() {
670        assert!(ToolNode::from_doc(&doc(serde_json::json!({"tool_name": "x"}))).is_err());
671        assert!(ToolNode::from_doc(&doc(serde_json::json!({"provider_id": " ", "tool_name": "x"}))).is_err());
672        let bad_param = serde_json::json!({"provider_id": "p", "tool_name": "x",
673            "tool_parameters": {"a": {"type": "variable", "value": ["only"]}}});
674        assert!(ToolNode::from_doc(&doc(bad_param)).is_err());
675    }
676
677    #[test]
678    fn registers_kind() {
679        let mut r = Registry::new();
680        register(&mut r);
681        assert!(r.contains(KIND));
682    }
683
684    fn echo_spec() -> ToolSpec {
685        ToolSpec {
686            name: "echo".into(),
687            description: "echo".into(),
688            parameters: serde_json::json!({"type": "object", "required": ["text"]}),
689            effects: Vec::new(),
690        }
691    }
692
693    #[tokio::test]
694    async fn native_tools_dispatch_and_validate() {
695        let tools = NativeTools::new().with(echo_spec(), |args| async move {
696            Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default().to_uppercase()))
697        });
698        assert_eq!(tools.len(), 1);
699        assert_eq!(tools.list().await.unwrap()[0].name, "echo");
700        let out = tools.call("echo", serde_json::json!({"text": "hi"}), ToolCallContext::empty()).await.unwrap();
701        assert_eq!(out.text, "HI");
702        let err = tools.call("echo", serde_json::json!({}), ToolCallContext::empty()).await.unwrap_err();
703        assert!(err.message.contains("text"));
704        assert!(tools.call("echo", serde_json::json!("str"), ToolCallContext::empty()).await.is_err());
705        assert!(tools.call("nope", serde_json::json!({}), ToolCallContext::empty()).await.is_err());
706    }
707
708    #[tokio::test]
709    async fn tool_node_with_native_tools() {
710        let tools = NativeTools::new().with(echo_spec(), |args| async move {
711            Ok(ToolOutput {
712                text: "done".into(),
713                data: Value::from_json(args),
714                is_error: false,
715                ..ToolOutput::default()
716            })
717        });
718        let node = ToolNode::from_doc(&doc(serde_json::json!({
719            "provider_id": "mock", "tool_name": "echo", "arguments": {"text": "{{#start.city#}}"}
720        })))
721        .unwrap();
722        let out = completed(node.run(ctx_with(Arc::new(tools))).await);
723        assert_eq!(out.outputs["json"].get_path(&["text"]), Some(Value::from("Jakarta")));
724    }
725}