Skip to main content

gadk_engine/workflow/nodes/
tool.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! `ToolNode`: a graph node that runs a directly runnable tool.
17
18use std::any::Any;
19use std::collections::BTreeMap;
20use std::sync::Arc;
21
22use gadk_agent::{AgentError, Context, ContextDelta, EventStream, Tool};
23use gadk_genai::{Content, Part};
24use gadk_session::{Event, EventActions};
25use serde_json::{Map, Value, json};
26
27use crate::error::{WorkflowError, WorkflowErrorKind};
28use crate::tool::utils::CompiledSchema;
29use crate::workflow::route::go_quote;
30use crate::workflow::{BaseNode, Node, NodeConfig};
31
32/// The node's state, shared with the `'static` run stream.
33struct ToolInner {
34    base: BaseNode,
35    tool: Arc<dyn Tool>,
36}
37
38/// A graph node that runs a directly runnable tool.
39pub struct ToolNode {
40    inner: Arc<ToolInner>,
41}
42
43impl ToolNode {
44    /// A node running `tool`, with input and output schemas inferred as `any` (the empty schema
45    /// `{}`).
46    pub fn new(tool: Arc<dyn Tool>, cfg: NodeConfig) -> Result<Arc<ToolNode>, WorkflowError> {
47        Self::build("", tool, None, None, cfg)
48    }
49
50    /// As [`ToolNode::new`] with an explicit node name.
51    pub fn named(
52        name: &str,
53        tool: Arc<dyn Tool>,
54        cfg: NodeConfig,
55    ) -> Result<Arc<ToolNode>, WorkflowError> {
56        Self::build(name, tool, None, None, cfg)
57    }
58
59    /// A node with the given schemas: a `None` schema is inferred as `any` (`{}`).
60    pub fn with_schemas(
61        tool: Arc<dyn Tool>,
62        input: Option<Value>,
63        output: Option<Value>,
64        cfg: NodeConfig,
65    ) -> Result<Arc<ToolNode>, WorkflowError> {
66        Self::build("", tool, input, output, cfg)
67    }
68
69    /// Builds the node from the resolved schemas.
70    fn build(
71        name: &str,
72        tool: Arc<dyn Tool>,
73        input: Option<Value>,
74        output: Option<Value>,
75        cfg: NodeConfig,
76    ) -> Result<Arc<ToolNode>, WorkflowError> {
77        let name = if name.is_empty() {
78            tool.name().to_string()
79        } else {
80            name.to_string()
81        };
82        let input = input.unwrap_or_else(|| json!({}));
83        let output = output.unwrap_or_else(|| json!({}));
84        let err = |what: &str, e: String| {
85            WorkflowError::new(
86                WorkflowErrorKind::Other,
87                format!(
88                    "resolving {what} schema for tool {}: {e}",
89                    go_quote(tool.name())
90                ),
91            )
92        };
93        CompiledSchema::new(input.clone()).map_err(|e| err("input", e))?;
94        CompiledSchema::new(output.clone()).map_err(|e| err("output", e))?;
95        if tool.as_runnable().is_none() {
96            return Err(not_runnable(tool.name()));
97        }
98        let base =
99            BaseNode::with_schemas(&name, tool.description(), Some(input), Some(output), cfg)?;
100        Ok(Arc::new(ToolNode {
101            inner: Arc::new(ToolInner { base, tool }),
102        }))
103    }
104}
105
106/// The error for a tool that cannot run directly: `tool "<name>" (type dyn Tool) is not directly
107/// runnable in workflow node`.
108fn not_runnable(tool_name: &str) -> WorkflowError {
109    WorkflowError::new(
110        WorkflowErrorKind::Other,
111        format!(
112            "tool {} (type dyn Tool) is not directly runnable in workflow node",
113            go_quote(tool_name)
114        ),
115    )
116}
117
118impl ToolInner {
119    /// Runs the tool: a JSON-object string input is decoded into a map first
120    /// (upstream LLM nodes often produce serialized arguments), then validated and run.
121    async fn run_tool(&self, tool_ctx: Context, input: Value) -> Result<Value, AgentError> {
122        let input = match input {
123            Value::String(s) => match serde_json::from_str::<Map<String, Value>>(&s) {
124                Ok(m) => Value::Object(m),
125                Err(_) => Value::String(s),
126            },
127            v => v,
128        };
129        let name = self.tool.name();
130        let tool_input = self.base.validate_input(input).map_err(|e| {
131            AgentError::from(
132                WorkflowError::new(
133                    e.kind(),
134                    format!("converting input for tool {}: {e}", go_quote(name)),
135                )
136                .with_source(e.into()),
137            )
138        })?;
139        let Some(runnable) = self.tool.as_runnable() else {
140            return Err(not_runnable(name).into());
141        };
142        match runnable.run(tool_ctx, tool_input).await {
143            Ok(out) => Ok(Value::Object(out)),
144            Err(e) => {
145                let msg = format!("tool {} execution failed: {e}", go_quote(name));
146                Err(WorkflowError::new(WorkflowErrorKind::Other, msg)
147                    .with_source(AgentError::Tool {
148                        tool: name.to_string(),
149                        source: e,
150                    })
151                    .into())
152            }
153        }
154    }
155
156    /// Direct validation, then the FunctionTool `{"result": X}` unwrap; when both fail, the
157    /// original output's error wins.
158    fn validate_output(&self, out: Value) -> Result<Value, WorkflowError> {
159        if self.base.output_schema().is_none() {
160            return Ok(out);
161        }
162        if let Ok(v) = self.base.validate_output(out.clone()) {
163            return Ok(v);
164        }
165        if let Some(inner) = out.as_object().and_then(|m| m.get("result"))
166            && let Ok(v) = self.base.validate_output(inner.clone())
167        {
168            return Ok(v);
169        }
170        self.base.validate_output(out)
171    }
172}
173
174impl Node for ToolNode {
175    fn name(&self) -> &str {
176        self.inner.base.name()
177    }
178    fn description(&self) -> &str {
179        self.inner.base.description()
180    }
181    fn config(&self) -> &NodeConfig {
182        self.inner.base.config()
183    }
184    fn input_schema(&self) -> Option<&Value> {
185        self.inner.base.input_schema()
186    }
187    fn output_schema(&self) -> Option<&Value> {
188        self.inner.base.output_schema()
189    }
190    fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
191        self.inner.base.validate_input(v)
192    }
193    fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
194        self.inner.validate_output(v)
195    }
196    /// Runs the tool under a tool context with its own call id and
197    /// actions, and emits one event carrying the tool's actions (minus any compaction) and its
198    /// output; a string output is also the event's content.
199    fn run(&self, ctx: Context, input: Value) -> EventStream {
200        let inner = Arc::clone(&self.inner);
201        Box::pin(async_stream::stream! {
202            let actions = Arc::new(parking_lot::Mutex::new(EventActions {
203                state_delta: Some(Map::new()),
204                artifact_delta: Some(BTreeMap::new()),
205                ..EventActions::default()
206            }));
207            // A tool context with a fresh call id, its own actions and no confirmation.
208            let tool_ctx = ctx.with_delta(ContextDelta {
209                function_call_id: Some(ctx.platform().new_uuid()),
210                actions: Some(Arc::clone(&actions)),
211                tool_confirmation: Some(None),
212                ..ContextDelta::default()
213            });
214            let output = match inner.run_tool(tool_ctx, input).await {
215                Ok(o) => o,
216                Err(e) => {
217                    yield Err(e);
218                    return;
219                }
220            };
221            let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
222            let mut acts = actions.lock().clone();
223            // Compaction is the framework's to write, not the tool's.
224            acts.compaction = None;
225            ev.actions = acts;
226            if let Value::String(s) = &output {
227                ev.response.content = Some(Content {
228                    parts: vec![Part::from_text(s.clone())],
229                    ..Content::default()
230                });
231            }
232            ev.output = Some(output);
233            yield Ok(ev);
234        })
235    }
236    fn as_any(&self) -> &dyn Any {
237        self
238    }
239}