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//! Outputs: `text` (string), `json` (structured result, or `null`; when the text
23//! looks like JSON but does not parse, metadata `json_error` says why), `files`
24//! (array, currently always empty), `is_error` (bool) and `error` (the tool's error
25//! text, or `null`). A tool-reported error fails the node unless
26//! `ignore_tool_errors` is set, in which case `is_error` / `error` let a downstream
27//! branch react. `variable` arguments that do not resolve are sent as `null` and
28//! listed in metadata `missing_arguments`.
29
30use std::fmt;
31use std::future::Future;
32use std::sync::Arc;
33
34use futures::future::BoxFuture;
35use indexmap::IndexMap;
36use serde::Deserialize;
37
38use crate::dsl::NodeDoc;
39use crate::node::{ConfigError, Node, NodeContext, NodeError, NodeOutput, NodeResult, Registry, parse_config};
40use crate::pool::{Selector, VariablePool};
41use crate::template::Template;
42use crate::tool::{ToolCallContext, ToolError, ToolOutput, ToolRegistry, ToolRuntime, ToolSpec};
43use crate::value::Value;
44
45/// Node kind handled by [`ToolNode`].
46pub const KIND: &str = "tool";
47
48/// Register the `tool` node kind.
49pub fn register(registry: &mut Registry) {
50    registry.register_lazily_described(KIND, descriptor, |doc| {
51        ToolNode::from_doc(doc).map(|n| Arc::new(n) as Arc<dyn Node>)
52    });
53}
54
55/// Catalog descriptor of the `tool` node.
56pub fn descriptor() -> crate::catalog::NodeDescriptor {
57    use crate::catalog::schema::{nested, object, selector};
58    use crate::catalog::{NodeCategory, NodeDescriptor, OutputDescriptor};
59    use crate::value::ValueType;
60
61    let parameter = serde_json::json!({
62        "oneOf": [
63            nested(serde_json::json!({ "type": { "const": "mixed" }, "value": { "type": "string" } }), &["type", "value"]),
64            nested(serde_json::json!({ "type": { "const": "variable" }, "value": selector() }), &["type", "value"]),
65            nested(serde_json::json!({ "type": { "const": "constant" }, "value": {} }), &["type"])
66        ]
67    });
68    NodeDescriptor::new(KIND, "Tool", NodeCategory::Integration)
69        .describe(
70            "Calls one tool from a registered tool provider (native tools, MCP servers, plugins). \
71             Arguments: `tool_parameters` (mixed template / variable / constant) override `arguments` \
72             (strings are templates) which override `tool_configurations` (constants).",
73        )
74        .icon("wrench")
75        .source("builtin")
76        .schema(object(
77            serde_json::json!({
78                "provider_id": { "type": "string", "minLength": 1 },
79                "provider": { "type": "string", "minLength": 1 },
80                "provider_name": { "type": "string", "minLength": 1 },
81                "tool_name": { "type": "string", "minLength": 1 },
82                "tool_parameters": { "type": "object", "additionalProperties": parameter },
83                "tool_configurations": { "type": "object" },
84                "arguments": { "type": "object" },
85                "ignore_tool_errors": { "type": "boolean", "default": false }
86            }),
87            &["tool_name"],
88        ))
89        .output(OutputDescriptor::new("text", ValueType::String).describe("Text result"))
90        .output(OutputDescriptor::new("json", ValueType::Any).describe("Structured result, or the text parsed as JSON"))
91        .output(OutputDescriptor::new("files", ValueType::ArrayFile))
92        .output(OutputDescriptor::new("is_error", ValueType::Boolean))
93        .output(OutputDescriptor::new("error", ValueType::String).describe("Error text when the tool reported one"))
94}
95
96/// How one tool argument is produced.
97#[derive(Clone, Debug, PartialEq, Deserialize)]
98#[serde(tag = "type", rename_all = "lowercase")]
99enum ArgSource {
100    /// Text template, rendered against the pool.
101    Mixed { value: Template },
102    /// Value read from a selector (typed).
103    Variable { value: Selector },
104    /// Literal value.
105    Constant {
106        #[serde(default)]
107        value: Value,
108    },
109}
110
111#[derive(Debug, Deserialize)]
112struct ToolNodeConfig {
113    #[serde(alias = "provider", alias = "provider_name")]
114    provider_id: String,
115    tool_name: String,
116    #[serde(default)]
117    tool_parameters: IndexMap<String, ArgSource>,
118    /// Constant configuration parameters; lowest precedence.
119    #[serde(default)]
120    tool_configurations: IndexMap<String, Value>,
121    /// Shorthand: strings are templates, everything else a constant.
122    #[serde(default)]
123    arguments: IndexMap<String, Value>,
124    /// When true, a tool-reported error becomes a normal output instead of a node failure.
125    #[serde(default)]
126    ignore_tool_errors: bool,
127}
128
129/// Calls one tool from the [`ToolRegistry`] service.
130#[derive(Debug, Clone)]
131pub struct ToolNode {
132    provider: String,
133    tool: String,
134    /// Arguments in precedence order (later entries override earlier ones).
135    args: Vec<(String, ArgSource)>,
136    ignore_tool_errors: bool,
137}
138
139impl ToolNode {
140    /// Build from a node document.
141    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
142        let cfg: ToolNodeConfig = parse_config(doc)?;
143        if cfg.provider_id.trim().is_empty() {
144            return Err(ConfigError::new(doc, "`provider_id` must not be empty"));
145        }
146        if cfg.tool_name.trim().is_empty() {
147            return Err(ConfigError::new(doc, "`tool_name` must not be empty"));
148        }
149        let mut args: Vec<(String, ArgSource)> = Vec::new();
150        for (k, v) in cfg.tool_configurations {
151            args.push((k, ArgSource::Constant { value: v }));
152        }
153        for (k, v) in cfg.arguments {
154            let source = match v {
155                Value::String(s) => ArgSource::Mixed { value: Template::parse(&s) },
156                other => ArgSource::Constant { value: other },
157            };
158            args.push((k, source));
159        }
160        for (k, v) in cfg.tool_parameters {
161            args.push((k, v));
162        }
163        Ok(Self { provider: cfg.provider_id, tool: cfg.tool_name, args, ignore_tool_errors: cfg.ignore_tool_errors })
164    }
165
166    /// Resolve arguments. Returns `(plaintext arguments for the call, masked copy for observability)`.
167    fn resolve_args(&self, pool: &VariablePool) -> (serde_json::Value, Value) {
168        let mut exposed = serde_json::Map::new();
169        let mut masked: IndexMap<String, Value> = IndexMap::new();
170        for (name, source) in &self.args {
171            match source {
172                // Text templates: render twice so the observable copy keeps secrets masked.
173                ArgSource::Mixed { value } if !matches!(value.parts(), [crate::template::Part::Var(_)]) => {
174                    exposed.insert(name.clone(), serde_json::Value::String(value.render_exposed(pool)));
175                    masked.insert(name.clone(), Value::from(value.render(pool)));
176                }
177                _ => {
178                    let value = match source {
179                        // A lone placeholder keeps the typed value (numbers stay numbers).
180                        ArgSource::Mixed { value } => value.resolve(pool),
181                        ArgSource::Variable { value } => pool.get_or_null(value),
182                        ArgSource::Constant { value } => value.clone(),
183                    };
184                    exposed.insert(name.clone(), value.to_json_exposed());
185                    masked.insert(name.clone(), value);
186                }
187            }
188        }
189        (serde_json::Value::Object(exposed), Value::from(masked))
190    }
191
192    async fn execute(&self, ctx: NodeContext) -> NodeResult {
193        let registry = ctx.require_service::<ToolRegistry>("tool registry")?;
194        let runtime = registry
195            .get(&self.provider)
196            .ok_or_else(|| NodeError::fatal("tool", format!("unknown tool provider `{}`", self.provider)))?
197            .clone();
198        let (arguments, masked_args) = self.resolve_args(&ctx.pool);
199        let missing = self.missing_variables(&ctx.pool);
200        // Arguments already carry rendered secrets here: the node config is written by the
201        // workflow author, not a model, so there is no separate context channel.
202        let output = runtime
203            .call(&self.tool, arguments, ToolCallContext::empty())
204            .await
205            .map_err(|e| NodeError::new("tool", e.to_string()))?;
206        if output.is_error && !self.ignore_tool_errors {
207            return Err(NodeError::fatal("tool_error", output.text));
208        }
209        // Files a native tool returned in its structured result (plugins and MCP servers
210        // cannot create file values).
211        #[cfg(feature = "tool-files")]
212        let files: Vec<Value> = crate::tool::collect_files(&output.data).into_iter().map(Value::File).collect();
213        #[cfg(not(feature = "tool-files"))]
214        let files: Vec<Value> = Vec::new();
215        let (json, json_error) =
216            if output.data.is_null() { parse_json_text(&output.text) } else { (output.data, None) };
217        // With `ignore_tool_errors`, the failure stays visible to the graph through the
218        // `is_error` / `error` outputs so a downstream branch can react to it.
219        let error = if output.is_error { Value::from(output.text.as_str()) } else { Value::Null };
220        let mut result = NodeOutput::new()
221            .with("text", output.text)
222            .with("json", json)
223            .with("files", Value::array(files))
224            .with("is_error", output.is_error)
225            .with("error", error)
226            .meta("provider", self.provider.as_str())
227            .meta("tool", self.tool.as_str())
228            .meta("arguments", masked_args);
229        if let Some(e) = json_error {
230            result = result.meta("json_error", e);
231        }
232        if !missing.is_empty() {
233            result = result.meta("missing_arguments", Value::array(missing.into_iter().map(Value::from)));
234        }
235        Ok(result.into())
236    }
237
238    /// Selectors of `variable` arguments that do not resolve (sent to the tool as `null`).
239    fn missing_variables(&self, pool: &VariablePool) -> Vec<String> {
240        self.args
241            .iter()
242            .filter_map(|(_, source)| match source {
243                ArgSource::Variable { value } if pool.get(value).is_none() => Some(value.to_string()),
244                _ => None,
245            })
246            .collect()
247    }
248}
249
250/// Structured view of a text result when it looks like a JSON object or array.
251/// Returns the parse error when it looks like JSON but is not valid.
252fn parse_json_text(text: &str) -> (Value, Option<String>) {
253    let trimmed = text.trim_start();
254    if trimmed.starts_with('{') || trimmed.starts_with('[') {
255        return match serde_json::from_slice::<serde_json::Value>(text.as_bytes()) {
256            Ok(json) => (Value::from_json(json), None),
257            Err(e) => (Value::Null, Some(e.to_string())),
258        };
259    }
260    (Value::Null, None)
261}
262
263impl Node for ToolNode {
264    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
265        Box::pin(self.execute(ctx))
266    }
267
268    fn inputs(&self) -> Vec<Selector> {
269        let mut out = Vec::new();
270        for (_, source) in &self.args {
271            match source {
272                ArgSource::Mixed { value } => out.extend(value.selectors().cloned()),
273                ArgSource::Variable { value } => out.push(value.clone()),
274                ArgSource::Constant { .. } => {}
275            }
276        }
277        out
278    }
279}
280
281type ToolFn = Arc<dyn Fn(serde_json::Value) -> BoxFuture<'static, Result<ToolOutput, ToolError>> + Send + Sync>;
282
283/// A [`ToolRuntime`] whose tools are Rust closures.
284///
285/// ```
286/// use graphrt_core::tool::{ToolOutput, ToolSpec};
287/// use graphrt_core::tool_node::NativeTools;
288///
289/// let tools = NativeTools::new().with(
290///     ToolSpec {
291///         name: "echo".into(),
292///         description: "Echo the `text` argument".into(),
293///         parameters: serde_json::json!({
294///             "type": "object",
295///             "properties": { "text": { "type": "string" } },
296///             "required": ["text"]
297///         }),
298///     },
299///     |args| async move { Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default())) },
300/// );
301/// ```
302#[derive(Clone, Default)]
303pub struct NativeTools {
304    tools: IndexMap<String, (ToolSpec, ToolFn)>,
305}
306
307impl fmt::Debug for NativeTools {
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        f.debug_struct("NativeTools").field("tools", &self.tools.keys().collect::<Vec<_>>()).finish()
310    }
311}
312
313impl NativeTools {
314    pub fn new() -> Self {
315        Self::default()
316    }
317
318    /// Add (or replace) a tool.
319    pub fn add<F, Fut>(&mut self, spec: ToolSpec, handler: F) -> &mut Self
320    where
321        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
322        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
323    {
324        let handler: ToolFn = Arc::new(move |args| Box::pin(handler(args)));
325        self.tools.insert(spec.name.clone(), (spec, handler));
326        self
327    }
328
329    /// Builder-style [`NativeTools::add`].
330    pub fn with<F, Fut>(mut self, spec: ToolSpec, handler: F) -> Self
331    where
332        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
333        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
334    {
335        self.add(spec, handler);
336        self
337    }
338
339    pub fn len(&self) -> usize {
340        self.tools.len()
341    }
342
343    pub fn is_empty(&self) -> bool {
344        self.tools.is_empty()
345    }
346}
347
348impl ToolRuntime for NativeTools {
349    fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
350        let specs = self.tools.values().map(|(spec, _)| spec.clone()).collect();
351        Box::pin(futures::future::ready(Ok(specs)))
352    }
353
354    /// Native handlers take only arguments; the context is not forwarded
355    /// (`accepts_secrets` stays `false`).
356    fn call<'a>(
357        &'a self,
358        name: &'a str,
359        arguments: serde_json::Value,
360        _context: &'a ToolCallContext,
361    ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
362        let Some((spec, handler)) = self.tools.get(name) else {
363            return Box::pin(futures::future::ready(Err(ToolError {
364                tool: name.to_owned(),
365                message: "unknown tool".to_owned(),
366            })));
367        };
368        if let Err(message) = check_required(&spec.parameters, &arguments) {
369            return Box::pin(futures::future::ready(Err(ToolError { tool: name.to_owned(), message })));
370        }
371        handler(arguments)
372    }
373}
374
375/// Lightweight argument check: the arguments must be an object containing every
376/// property listed in the schema's `required` array. Full JSON Schema validation
377/// is left to the tool itself.
378fn check_required(schema: &serde_json::Value, arguments: &serde_json::Value) -> Result<(), String> {
379    let Some(args) = arguments.as_object() else {
380        return Err("arguments must be a JSON object".to_owned());
381    };
382    let required = schema.get("required").and_then(serde_json::Value::as_array);
383    let missing: Vec<&str> = required
384        .into_iter()
385        .flatten()
386        .filter_map(serde_json::Value::as_str)
387        .filter(|key| args.get(*key).is_none_or(serde_json::Value::is_null))
388        .collect();
389    if missing.is_empty() { Ok(()) } else { Err(format!("missing required arguments: {}", missing.join(", "))) }
390}
391
392#[cfg(test)]
393mod tests {
394    use std::sync::Mutex;
395
396    use super::*;
397    use crate::node::{NodeOutcome, Services};
398
399    #[derive(Debug, Default)]
400    struct Recorder {
401        calls: Mutex<Vec<(String, serde_json::Value)>>,
402        reply: Option<ToolOutput>,
403    }
404
405    impl ToolRuntime for Recorder {
406        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
407            Box::pin(futures::future::ready(Ok(Vec::new())))
408        }
409        fn call<'a>(
410            &'a self,
411            name: &'a str,
412            arguments: serde_json::Value,
413            _context: &'a ToolCallContext,
414        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
415            self.calls.lock().unwrap().push((name.to_owned(), arguments));
416            let reply = self.reply.clone().unwrap_or_else(|| ToolOutput::text("{\"ok\":true}"));
417            Box::pin(futures::future::ready(Ok(reply)))
418        }
419    }
420
421    fn doc(config: serde_json::Value) -> NodeDoc {
422        NodeDoc::new("t", KIND, config)
423    }
424
425    fn pool() -> VariablePool {
426        let mut p = VariablePool::new();
427        p.insert("start", "city", Value::from("Jakarta"));
428        p.insert("start", "days", Value::Int(3));
429        p.insert("env", "TOKEN", Value::Secret(Arc::from("s3cret")));
430        p
431    }
432
433    fn ctx_with(runtime: Arc<dyn ToolRuntime>) -> NodeContext {
434        let mut reg = ToolRegistry::new();
435        reg.add("mock", runtime);
436        NodeContext::for_test("t", pool()).with_services(Arc::new(Services::new().with(reg)))
437    }
438
439    fn completed(r: NodeResult) -> NodeOutput {
440        match r {
441            Ok(NodeOutcome::Completed(o)) => o,
442            other => panic!("unexpected {other:?}"),
443        }
444    }
445
446    #[tokio::test]
447    async fn resolves_all_argument_kinds() {
448        let rec = Arc::new(Recorder::default());
449        let node = ToolNode::from_doc(&doc(serde_json::json!({
450            "provider_id": "mock",
451            "tool_name": "weather",
452            "tool_configurations": {"units": "imperial", "lang": "en"},
453            "arguments": {"note": "for {{#start.city#}}", "raw": 5},
454            "tool_parameters": {
455                "city": {"type": "variable", "value": ["start", "city"]},
456                "days": {"type": "mixed", "value": "{{#start.days#}}"},
457                "units": {"type": "constant", "value": "metric"},
458                "auth": {"type": "mixed", "value": "Bearer {{#env.TOKEN#}}"}
459            }
460        })))
461        .unwrap();
462        let out = completed(node.run(ctx_with(rec.clone())).await);
463        let calls = rec.calls.lock().unwrap();
464        let (name, args) = &calls[0];
465        assert_eq!(name, "weather");
466        assert_eq!(args["city"], "Jakarta");
467        assert_eq!(args["days"], 3);
468        assert_eq!(args["units"], "metric", "tool_parameters override configurations");
469        assert_eq!(args["lang"], "en");
470        assert_eq!(args["note"], "for Jakarta");
471        assert_eq!(args["raw"], 5);
472        assert_eq!(args["auth"], "Bearer s3cret", "tool receives the plaintext secret");
473        // Observability metadata never contains the secret.
474        let meta = serde_json::to_string(&out.metadata).unwrap();
475        assert!(!meta.contains("s3cret"));
476        assert_eq!(out.outputs["text"], Value::from("{\"ok\":true}"));
477        assert_eq!(out.outputs["json"].get_path(&["ok"]), Some(Value::Bool(true)));
478        assert_eq!(out.outputs["files"], Value::array([]));
479        assert_eq!(node.inputs().len(), 4); // note, city, days, auth
480    }
481
482    #[tokio::test]
483    async fn tool_error_fails_unless_ignored() {
484        let rec = Arc::new(Recorder { reply: Some(ToolOutput::error("boom")), ..Recorder::default() });
485        let cfg = serde_json::json!({"provider": "mock", "tool_name": "x"});
486        let node = ToolNode::from_doc(&doc(cfg)).unwrap();
487        let err = node.run(ctx_with(rec.clone())).await.unwrap_err();
488        assert_eq!(err.kind, "tool_error");
489        assert!(!err.retryable);
490
491        let cfg = serde_json::json!({"provider": "mock", "tool_name": "x", "ignore_tool_errors": true});
492        let node = ToolNode::from_doc(&doc(cfg)).unwrap();
493        let out = completed(node.run(ctx_with(rec)).await);
494        assert_eq!(out.outputs["text"], Value::from("boom"));
495        assert_eq!(out.outputs["is_error"], Value::Bool(true));
496        assert_eq!(out.outputs["error"], Value::from("boom"));
497    }
498
499    #[tokio::test]
500    async fn successful_call_has_no_error_output() {
501        let rec = Arc::new(Recorder { reply: Some(ToolOutput::text("{\"a\": 1")), ..Recorder::default() });
502        let node = ToolNode::from_doc(&doc(serde_json::json!({
503            "provider": "mock", "tool_name": "x",
504            "tool_parameters": {"city": {"type": "variable", "value": ["start", "nope"]}}
505        })))
506        .unwrap();
507        let out = completed(node.run(ctx_with(rec)).await);
508        assert_eq!(out.outputs["is_error"], Value::Bool(false));
509        assert_eq!(out.outputs["error"], Value::Null);
510        // Looks like JSON but is truncated: `json` is null and the reason is recorded.
511        assert_eq!(out.outputs["json"], Value::Null);
512        assert!(out.metadata.contains_key("json_error"));
513        assert_eq!(out.metadata["missing_arguments"], Value::array([Value::from("start.nope")]));
514    }
515
516    #[tokio::test]
517    async fn missing_provider_or_registry_is_fatal() {
518        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "nope", "tool_name": "x"}))).unwrap();
519        let err = node.run(ctx_with(Arc::new(Recorder::default()))).await.unwrap_err();
520        assert!(!err.retryable);
521        let err = node.run(NodeContext::for_test("t", pool())).await.unwrap_err();
522        assert_eq!(err.kind, "missing_service");
523    }
524
525    #[test]
526    fn rejects_invalid_config() {
527        assert!(ToolNode::from_doc(&doc(serde_json::json!({"tool_name": "x"}))).is_err());
528        assert!(ToolNode::from_doc(&doc(serde_json::json!({"provider_id": " ", "tool_name": "x"}))).is_err());
529        let bad_param = serde_json::json!({"provider_id": "p", "tool_name": "x",
530            "tool_parameters": {"a": {"type": "variable", "value": ["only"]}}});
531        assert!(ToolNode::from_doc(&doc(bad_param)).is_err());
532    }
533
534    #[test]
535    fn registers_kind() {
536        let mut r = Registry::new();
537        register(&mut r);
538        assert!(r.contains(KIND));
539    }
540
541    fn echo_spec() -> ToolSpec {
542        ToolSpec {
543            name: "echo".into(),
544            description: "echo".into(),
545            parameters: serde_json::json!({"type": "object", "required": ["text"]}),
546        }
547    }
548
549    #[tokio::test]
550    async fn native_tools_dispatch_and_validate() {
551        let tools = NativeTools::new().with(echo_spec(), |args| async move {
552            Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default().to_uppercase()))
553        });
554        assert_eq!(tools.len(), 1);
555        assert_eq!(tools.list().await.unwrap()[0].name, "echo");
556        let out = tools.call("echo", serde_json::json!({"text": "hi"}), ToolCallContext::empty()).await.unwrap();
557        assert_eq!(out.text, "HI");
558        let err = tools.call("echo", serde_json::json!({}), ToolCallContext::empty()).await.unwrap_err();
559        assert!(err.message.contains("text"));
560        assert!(tools.call("echo", serde_json::json!("str"), ToolCallContext::empty()).await.is_err());
561        assert!(tools.call("nope", serde_json::json!({}), ToolCallContext::empty()).await.is_err());
562    }
563
564    #[tokio::test]
565    async fn tool_node_with_native_tools() {
566        let tools = NativeTools::new().with(echo_spec(), |args| async move {
567            Ok(ToolOutput {
568                text: "done".into(),
569                data: Value::from_json(args),
570                is_error: false,
571                ..ToolOutput::default()
572            })
573        });
574        let node = ToolNode::from_doc(&doc(serde_json::json!({
575            "provider_id": "mock", "tool_name": "echo", "arguments": {"text": "{{#start.city#}}"}
576        })))
577        .unwrap();
578        let out = completed(node.run(ctx_with(Arc::new(tools))).await);
579        assert_eq!(out.outputs["json"].get_path(&["text"]), Some(Value::from("Jakarta")));
580    }
581}