1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
//! Closure-based tool builder that implements [`AgentTool`] without requiring
//! a custom struct or trait implementation.
//!
//! # Example
//!
//! ```
//! use schemars::JsonSchema;
//! use serde::Deserialize;
//! use swink_agent::{AgentToolResult, FnTool};
//!
//! #[derive(Deserialize, JsonSchema)]
//! struct Params { city: String }
//!
//! let tool = FnTool::new("get_weather", "Weather", "Get weather for a city.")
//! .with_execute_typed(|params: Params, _cancel| async move {
//! AgentToolResult::text(format!("72F in {}", params.city))
//! });
//!
//! assert_eq!(swink_agent::AgentTool::name(&tool), "get_weather");
//! ```
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::tool::{
AgentTool, AgentToolResult, ToolFuture, debug_validated_schema, permissive_object_schema,
validated_schema_for,
};
// ─── Type aliases for stored closures ───────────────────────────────────────
type ExecuteFn = Arc<
dyn Fn(
String,
Value,
CancellationToken,
Option<Box<dyn Fn(AgentToolResult) + Send + Sync>>,
) -> ToolFuture<'static>
+ Send
+ Sync,
>;
type ApprovalContextFn = Arc<dyn Fn(&Value) -> Option<Value> + Send + Sync>;
// ─── FnTool ─────────────────────────────────────────────────────────────────
/// A tool built entirely from closures and configuration, implementing
/// [`AgentTool`] without requiring a custom struct.
///
/// Use the builder methods to configure the tool's schema, approval
/// requirements, and execution logic.
pub struct FnTool {
name: String,
label: String,
description: String,
schema: Value,
requires_approval: bool,
execution_root: Option<PathBuf>,
execute_fn: ExecuteFn,
approval_context_fn: Option<ApprovalContextFn>,
}
impl FnTool {
/// Create a new `FnTool` with the given name, label, and description.
///
/// The default schema accepts any object and the default execute returns
/// an error indicating the tool is not implemented.
#[must_use]
pub fn new(
name: impl Into<String>,
label: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self {
name: name.into(),
label: label.into(),
description: description.into(),
schema: permissive_object_schema(),
requires_approval: false,
execution_root: None,
execute_fn: Arc::new(|_, _, _, _| {
Box::pin(async { AgentToolResult::error("not implemented") })
}),
approval_context_fn: None,
}
}
/// Set the parameters schema from a type implementing
/// [`JsonSchema`](schemars::JsonSchema).
#[must_use]
pub fn with_schema_for<T: schemars::JsonSchema>(mut self) -> Self {
self.schema = validated_schema_for::<T>();
self
}
/// Set the parameters schema from a raw JSON value.
#[must_use]
pub fn with_schema(mut self, schema: Value) -> Self {
self.schema = debug_validated_schema(schema);
self
}
/// Set whether this tool requires user approval before execution.
#[must_use]
pub const fn with_requires_approval(mut self, requires: bool) -> Self {
self.requires_approval = requires;
self
}
/// Set the working directory used to resolve this tool's relative paths.
#[must_use]
pub fn with_execution_root(mut self, root: impl Into<PathBuf>) -> Self {
self.execution_root = Some(root.into());
self
}
/// Set the execution function using the full signature.
///
/// The closure receives `(tool_call_id, params, cancellation_token, on_update)`.
#[must_use]
pub fn with_execute<F, Fut>(mut self, f: F) -> Self
where
F: Fn(
String,
Value,
CancellationToken,
Option<Box<dyn Fn(AgentToolResult) + Send + Sync>>,
) -> Fut
+ Send
+ Sync
+ 'static,
Fut: Future<Output = AgentToolResult> + Send + 'static,
{
self.execute_fn = Arc::new(move |id, params, cancel, on_update| {
Box::pin(f(id, params, cancel, on_update))
});
self
}
/// Set the execution function using a simplified signature.
///
/// The closure receives only `(params, cancellation_token)`, ignoring the
/// tool call ID and update callback.
#[must_use]
pub fn with_execute_simple<F, Fut>(mut self, f: F) -> Self
where
F: Fn(Value, CancellationToken) -> Fut + Send + Sync + 'static,
Fut: Future<Output = AgentToolResult> + Send + 'static,
{
self.execute_fn =
Arc::new(move |_id, params, cancel, _on_update| Box::pin(f(params, cancel)));
self
}
/// Set the execution function using an explicit untyped async signature.
///
/// This is equivalent to [`Self::with_execute_simple`] and exists as a
/// discoverability alias for callers looking for an untyped async builder.
#[must_use]
pub fn with_execute_async<F, Fut>(self, f: F) -> Self
where
F: Fn(Value, CancellationToken) -> Fut + Send + Sync + 'static,
Fut: Future<Output = AgentToolResult> + Send + 'static,
{
self.with_execute_simple(f)
}
/// Set the execution function using a typed parameter struct.
///
/// This derives the schema from `T` and deserializes validated params into
/// `T` before calling the closure. On deserialization failure, execution
/// returns `AgentToolResult::error("invalid parameters: ...")`.
#[must_use]
pub fn with_execute_typed<T, F, Fut>(mut self, f: F) -> Self
where
T: DeserializeOwned + schemars::JsonSchema + Send + 'static,
F: Fn(T, CancellationToken) -> Fut + Send + Sync + 'static,
Fut: Future<Output = AgentToolResult> + Send + 'static,
{
self.schema = validated_schema_for::<T>();
self.execute_fn = Arc::new(move |_id, params, cancel, _on_update| {
let parsed: T = match serde_json::from_value(params) {
Ok(parsed) => parsed,
Err(err) => {
return Box::pin(async move {
AgentToolResult::error(format!("invalid parameters: {err}"))
});
}
};
Box::pin(f(parsed, cancel))
});
self
}
/// Set a closure that provides rich context for the approval UI.
///
/// When the tool requires approval, this closure is called to produce
/// context that is attached to the [`ToolApprovalRequest`](crate::ToolApprovalRequest).
#[must_use]
pub fn with_approval_context<F>(mut self, f: F) -> Self
where
F: Fn(&Value) -> Option<Value> + Send + Sync + 'static,
{
self.approval_context_fn = Some(Arc::new(f));
self
}
}
impl AgentTool for FnTool {
fn name(&self) -> &str {
&self.name
}
fn label(&self) -> &str {
&self.label
}
fn description(&self) -> &str {
&self.description
}
fn parameters_schema(&self) -> &Value {
&self.schema
}
fn requires_approval(&self) -> bool {
self.requires_approval
}
fn execution_root(&self) -> Option<&Path> {
self.execution_root.as_deref()
}
fn approval_context(&self, params: &Value) -> Option<Value> {
self.approval_context_fn.as_ref().and_then(|f| f(params))
}
fn execute(
&self,
tool_call_id: &str,
params: Value,
cancellation_token: CancellationToken,
on_update: Option<Box<dyn Fn(AgentToolResult) + Send + Sync>>,
_state: std::sync::Arc<std::sync::RwLock<crate::SessionState>>,
_credential: Option<crate::credential::ResolvedCredential>,
) -> ToolFuture<'_> {
let fut = (self.execute_fn)(
tool_call_id.to_owned(),
params,
cancellation_token,
on_update,
);
Box::pin(fut)
}
}
impl std::fmt::Debug for FnTool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FnTool")
.field("name", &self.name)
.field("label", &self.label)
.field("description", &self.description)
.field("requires_approval", &self.requires_approval)
.finish_non_exhaustive()
}
}
// ─── Compile-time Send + Sync assertion ─────────────────────────────────────
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<FnTool>();
};
#[cfg(test)]
#[path = "fn_tool_tests.rs"]
mod tests;