1use std::sync::Arc;
22use std::time::Duration;
23
24use futures::future::BoxFuture;
25use graphrt_core::Value;
26use graphrt_core::tool::{ToolCallContext, ToolEffect, ToolError, ToolOutput, ToolRuntime, ToolSpec};
27
28use crate::GraphrtError;
29
30pub const DEFAULT_TOOL_TIMEOUT_MS: u64 = 30_000;
32pub const MAX_TOOL_TIMEOUT_MS: u64 = 600_000;
34pub const MAX_RESULT_BYTES: usize = 1024 * 1024;
36pub const MAX_TOOLS_PER_PROVIDER: usize = 128;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]
42pub enum HostToolEffect {
43 Read,
45 Write,
47 Send,
49 Pay,
51}
52
53impl From<HostToolEffect> for ToolEffect {
54 fn from(effect: HostToolEffect) -> Self {
55 match effect {
56 HostToolEffect::Read => Self::Read,
57 HostToolEffect::Write => Self::Write,
58 HostToolEffect::Send => Self::Send,
59 HostToolEffect::Pay => Self::Pay,
60 }
61 }
62}
63
64#[derive(Clone, Debug, PartialEq, uniffi::Record)]
66pub struct HostToolSpec {
67 pub name: String,
69 pub description: String,
71 pub parameters_json: String,
74 #[uniffi(default)]
76 pub timeout_ms: Option<u64>,
77 #[uniffi(default)]
81 pub effects: Vec<HostToolEffect>,
82}
83
84#[derive(Clone, Debug, PartialEq, uniffi::Record)]
86pub struct HostToolCall {
87 pub provider: String,
89 pub name: String,
91 pub arguments_json: String,
93}
94
95#[derive(Clone, Debug, Default, PartialEq, uniffi::Record)]
97pub struct HostToolResult {
98 pub text: String,
100 #[uniffi(default)]
103 pub data_json: Option<String>,
104 #[uniffi(default)]
106 pub is_error: bool,
107}
108
109#[derive(Debug, thiserror::Error, uniffi::Error)]
111#[non_exhaustive]
112pub enum ToolCallError {
113 #[error("{reason}")]
115 Failed { reason: String },
116}
117
118impl From<uniffi::UnexpectedUniFFICallbackError> for ToolCallError {
119 fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self {
120 Self::Failed { reason: format!("the app's tool threw an exception: {}", e.reason) }
121 }
122}
123
124#[uniffi::export(with_foreign)]
130#[async_trait::async_trait]
131pub trait ToolProvider: Send + Sync {
132 async fn call_tool(&self, call: HostToolCall) -> Result<HostToolResult, ToolCallError>;
134}
135
136#[derive(Debug, Clone)]
138struct Declared {
139 spec: ToolSpec,
140 timeout: Duration,
141}
142
143pub(crate) struct HostTools {
145 provider: String,
146 tools: Vec<Declared>,
147 callback: Arc<dyn ToolProvider>,
148}
149
150impl std::fmt::Debug for HostTools {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 let names: Vec<&str> = self.tools.iter().map(|t| t.spec.name.as_str()).collect();
153 f.debug_struct("HostTools").field("provider", &self.provider).field("tools", &names).finish()
154 }
155}
156
157pub(crate) fn is_valid_name(name: &str) -> bool {
159 !name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
160}
161
162impl HostTools {
163 pub(crate) fn new(
165 provider: &str,
166 specs: Vec<HostToolSpec>,
167 callback: Arc<dyn ToolProvider>,
168 ) -> Result<Self, GraphrtError> {
169 let invalid = |message: String| GraphrtError::InvalidInput { message };
170 if !is_valid_name(provider) {
171 return Err(invalid(format!("tool provider `{provider}`: use 1 to 64 letters, digits, `_` or `-`")));
172 }
173 if specs.is_empty() {
174 return Err(invalid(format!("tool provider `{provider}` declares no tools")));
175 }
176 if specs.len() > MAX_TOOLS_PER_PROVIDER {
177 return Err(invalid(format!(
178 "tool provider `{provider}` declares {} tools; at most {MAX_TOOLS_PER_PROVIDER} are allowed",
179 specs.len()
180 )));
181 }
182 let mut tools: Vec<Declared> = Vec::with_capacity(specs.len());
183 for spec in specs {
184 let what = format!("tool `{provider}/{}`", spec.name);
185 if !is_valid_name(&spec.name) {
186 return Err(invalid(format!("{what}: use 1 to 64 letters, digits, `_` or `-` in the name")));
187 }
188 if tools.iter().any(|t| t.spec.name == spec.name) {
189 return Err(invalid(format!("{what} is declared twice")));
190 }
191 let parameters: serde_json::Value = serde_json::from_str(&spec.parameters_json)
192 .map_err(|e| invalid(format!("{what}: parameters_json is not JSON: {e}")))?;
193 check_schema(¶meters).map_err(|e| invalid(format!("{what}: {e}")))?;
194 let timeout_ms = spec.timeout_ms.unwrap_or(DEFAULT_TOOL_TIMEOUT_MS);
195 if timeout_ms == 0 || timeout_ms > MAX_TOOL_TIMEOUT_MS {
196 return Err(invalid(format!("{what}: timeout_ms must be between 1 and {MAX_TOOL_TIMEOUT_MS}")));
197 }
198 let mut effects: Vec<ToolEffect> = Vec::with_capacity(spec.effects.len());
199 for effect in spec.effects.into_iter().map(ToolEffect::from) {
200 if !effects.contains(&effect) {
201 effects.push(effect);
202 }
203 }
204 tools.push(Declared {
205 spec: ToolSpec::new(spec.name, spec.description, parameters).with_effects(effects),
206 timeout: Duration::from_millis(timeout_ms),
207 });
208 }
209 Ok(Self { provider: provider.to_owned(), tools, callback })
210 }
211
212 async fn call_declared(&self, tool: &Declared, arguments: serde_json::Value) -> ToolOutput {
213 if let Err(problem) = check_arguments(&tool.spec.parameters, &arguments) {
214 return ToolOutput::error(format!(
215 "invalid arguments: {problem}. Call the tool again with arguments that match its schema."
216 ));
217 }
218 let call = HostToolCall {
219 provider: self.provider.clone(),
220 name: tool.spec.name.clone(),
221 arguments_json: arguments.to_string(),
222 };
223 match tokio::time::timeout(tool.timeout, self.callback.call_tool(call)).await {
225 Err(_) => ToolOutput::error(format!(
226 "the tool did not answer within {} ms and was cancelled",
227 tool.timeout.as_millis()
228 )),
229 Ok(Err(ToolCallError::Failed { reason })) => ToolOutput::error(bounded(reason)),
230 Ok(Ok(result)) => output_of(result),
231 }
232 }
233}
234
235fn bounded(mut text: String) -> String {
237 if text.len() > MAX_RESULT_BYTES {
238 let mut end = MAX_RESULT_BYTES;
239 while !text.is_char_boundary(end) {
240 end -= 1;
241 }
242 text.truncate(end);
243 text.push_str(" [truncated]");
244 }
245 text
246}
247
248fn output_of(result: HostToolResult) -> ToolOutput {
249 let data = match result.data_json.as_deref().map(str::trim) {
250 None | Some("") => Value::Null,
251 Some(json) if json.len() > MAX_RESULT_BYTES => {
252 return ToolOutput::error(format!(
253 "the tool returned {} bytes of data; at most {MAX_RESULT_BYTES} are allowed",
254 json.len()
255 ));
256 }
257 Some(json) => match serde_json::from_str::<serde_json::Value>(json) {
258 Ok(value) => Value::from_json(value),
259 Err(e) => return ToolOutput::error(format!("the tool returned data that is not JSON: {e}")),
260 },
261 };
262 ToolOutput { text: bounded(result.text), data, is_error: result.is_error, images: Vec::new() }
263}
264
265impl ToolRuntime for HostTools {
266 fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
267 let specs = self.tools.iter().map(|t| t.spec.clone()).collect();
268 Box::pin(async move { Ok(specs) })
269 }
270
271 fn call<'a>(
272 &'a self,
273 name: &'a str,
274 arguments: serde_json::Value,
275 _context: &'a ToolCallContext,
276 ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
277 Box::pin(async move {
278 let Some(tool) = self.tools.iter().find(|t| t.spec.name == name) else {
279 return Err(ToolError {
280 tool: format!("{}/{name}", self.provider),
281 message: "no such tool in this provider".to_owned(),
282 });
283 };
284 Ok(self.call_declared(tool, arguments).await)
285 })
286 }
287}
288
289fn check_schema(schema: &serde_json::Value) -> Result<(), String> {
291 let fields = schema.as_object().ok_or("parameters_json must be a JSON Schema object")?;
292 match fields.get("type").and_then(serde_json::Value::as_str) {
293 Some("object") => {}
294 _ => return Err("parameters_json must have `\"type\": \"object\"`".to_owned()),
295 }
296 if let Some(properties) = fields.get("properties")
297 && !properties.is_object()
298 {
299 return Err("`properties` must be an object".to_owned());
300 }
301 if let Some(required) = fields.get("required") {
302 let names = required.as_array().ok_or("`required` must be an array of property names")?;
303 if names.iter().any(|n| !n.is_string()) {
304 return Err("`required` must be an array of property names".to_owned());
305 }
306 }
307 Ok(())
308}
309
310const MAX_SCHEMA_DEPTH: usize = 16;
312
313pub(crate) fn check_arguments(schema: &serde_json::Value, arguments: &serde_json::Value) -> Result<(), String> {
317 check_value(schema, arguments, "arguments", 0)
318}
319
320fn type_matches(expected: &str, value: &serde_json::Value) -> bool {
321 match expected {
322 "object" => value.is_object(),
323 "array" => value.is_array(),
324 "string" => value.is_string(),
325 "boolean" => value.is_boolean(),
326 "null" => value.is_null(),
327 "number" => value.is_number(),
328 "integer" => value.as_i64().is_some() || value.as_u64().is_some(),
329 _ => true,
330 }
331}
332
333fn check_value(schema: &serde_json::Value, value: &serde_json::Value, path: &str, depth: usize) -> Result<(), String> {
334 let Some(schema) = schema.as_object() else {
335 return Ok(());
336 };
337 if depth > MAX_SCHEMA_DEPTH {
338 return Ok(());
339 }
340 match schema.get("type") {
341 Some(serde_json::Value::String(expected)) if !type_matches(expected, value) => {
342 return Err(format!("`{path}` must be of type {expected}"));
343 }
344 Some(serde_json::Value::Array(options)) => {
345 let allowed: Vec<&str> = options.iter().filter_map(serde_json::Value::as_str).collect();
346 if !allowed.is_empty() && !allowed.iter().any(|t| type_matches(t, value)) {
347 return Err(format!("`{path}` must be of type {}", allowed.join(" or ")));
348 }
349 }
350 _ => {}
351 }
352 if let Some(serde_json::Value::Array(options)) = schema.get("enum")
353 && !options.contains(value)
354 {
355 return Err(format!("`{path}` must be one of {}", serde_json::Value::Array(options.clone())));
356 }
357 if let Some(fields) = value.as_object() {
358 if let Some(serde_json::Value::Array(required)) = schema.get("required") {
359 for name in required.iter().filter_map(serde_json::Value::as_str) {
360 if !fields.contains_key(name) {
361 return Err(format!("`{path}.{name}` is required"));
362 }
363 }
364 }
365 let properties = schema.get("properties").and_then(serde_json::Value::as_object);
366 for (name, field) in fields {
367 match properties.and_then(|p| p.get(name)) {
368 Some(property) => check_value(property, field, &format!("{path}.{name}"), depth + 1)?,
369 None if schema.get("additionalProperties") == Some(&serde_json::Value::Bool(false)) => {
370 return Err(format!("`{path}.{name}` is not a known property"));
371 }
372 None => {}
373 }
374 }
375 }
376 if let (Some(items), Some(elements)) = (schema.get("items"), value.as_array()) {
377 for (index, element) in elements.iter().enumerate() {
378 check_value(items, element, &format!("{path}[{index}]"), depth + 1)?;
379 }
380 }
381 Ok(())
382}
383
384#[cfg(test)]
385mod tests {
386 use super::*;
387 use serde_json::json;
388
389 #[test]
390 fn arguments_are_checked_against_the_schema() {
391 let schema = json!({
392 "type": "object",
393 "properties": {
394 "to": {"type": "string"},
395 "priority": {"type": "string", "enum": ["low", "high"]},
396 "count": {"type": "integer"},
397 "tags": {"type": "array", "items": {"type": "string"}},
398 },
399 "required": ["to"],
400 "additionalProperties": false,
401 });
402 assert_eq!(check_arguments(&schema, &json!({"to": "Ada", "count": 2, "tags": ["a"]})), Ok(()));
403 let problem = |args: serde_json::Value| check_arguments(&schema, &args).err().unwrap_or_default();
404 assert_eq!(problem(json!({})), "`arguments.to` is required");
405 assert_eq!(problem(json!({"to": 3})), "`arguments.to` must be of type string");
406 assert_eq!(problem(json!({"to": "a", "count": 1.5})), "`arguments.count` must be of type integer");
407 assert!(problem(json!({"to": "a", "priority": "urgent"})).contains("must be one of"));
408 assert_eq!(problem(json!({"to": "a", "tags": [1]})), "`arguments.tags[0]` must be of type string");
409 assert_eq!(problem(json!({"to": "a", "cc": "b"})), "`arguments.cc` is not a known property");
410 assert_eq!(problem(json!("text")), "`arguments` must be of type object");
411 }
412
413 #[test]
414 fn declarations_are_checked() {
415 struct Never;
416 #[async_trait::async_trait]
417 impl ToolProvider for Never {
418 async fn call_tool(&self, _call: HostToolCall) -> Result<HostToolResult, ToolCallError> {
419 Err(ToolCallError::Failed { reason: "never".into() })
420 }
421 }
422 let spec = |name: &str, parameters: &str, timeout_ms: Option<u64>| HostToolSpec {
423 name: name.into(),
424 description: "d".into(),
425 parameters_json: parameters.into(),
426 timeout_ms,
427 effects: Vec::new(),
428 };
429 let object = r#"{"type":"object"}"#;
430 let check = |provider: &str, specs: Vec<HostToolSpec>| HostTools::new(provider, specs, Arc::new(Never));
431 assert!(check("device", vec![spec("battery", object, None)]).is_ok());
432 assert!(check("bad name", vec![spec("battery", object, None)]).is_err());
433 assert!(check("device", vec![]).is_err());
434 assert!(check("device", vec![spec("bat tery", object, None)]).is_err());
435 assert!(check("device", vec![spec("a", object, None), spec("a", object, None)]).is_err());
436 assert!(check("device", vec![spec("a", "{", None)]).is_err());
437 assert!(check("device", vec![spec("a", r#"{"type":"string"}"#, None)]).is_err());
438 assert!(check("device", vec![spec("a", object, Some(0))]).is_err());
439 assert!(check("device", vec![spec("a", object, Some(MAX_TOOL_TIMEOUT_MS + 1))]).is_err());
440 }
441
442 #[test]
443 fn results_are_bounded_and_parsed() {
444 let big = "é".repeat(MAX_RESULT_BYTES);
445 let out = output_of(HostToolResult { text: big, data_json: None, is_error: false });
446 assert!(out.text.len() <= MAX_RESULT_BYTES + " [truncated]".len() && out.text.ends_with("[truncated]"));
447 let out = output_of(HostToolResult { text: "t".into(), data_json: Some("{x".into()), is_error: false });
448 assert!(out.is_error && out.text.contains("not JSON"));
449 let out = output_of(HostToolResult { text: "t".into(), data_json: Some(r#"{"a":1}"#.into()), is_error: false });
450 assert_eq!(out.data.to_json(), json!({"a": 1}));
451 }
452}