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