use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use schemars::Schema;
#[macro_export]
macro_rules! extract_args {
($args:expr, $($name:ident),* $(,)?) => {
$(
let $name = match $crate::tools::tool::require_arg(&$args, stringify!($name)) {
Ok(v) => v,
Err(e) => return e,
};
)*
};
}
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolCategory {
ReadOnly,
Destructive,
Signal,
}
pub struct Tool {
pub name: String,
pub description: String,
pub parameters: Schema,
pub category: ToolCategory,
pub handler: Box<dyn Fn(HashMap<String, String>) -> BoxFuture<'static, String> + Send + Sync>,
}
impl Tool {
pub fn to_definition(&self) -> crate::provider::ToolDefinition {
crate::provider::ToolDefinition {
name: self.name.clone(),
description: self.description.clone(),
parameters: self.parameters.clone(),
}
}
}
pub async fn execute_tool_call(tool: &Tool, arguments: &serde_json::Value) -> String {
let args: HashMap<String, String> = arguments
.as_object()
.map(|obj| {
obj.iter()
.map(|(k, v)| {
let val = match v {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
};
(k.clone(), val)
})
.collect()
})
.unwrap_or_default();
(tool.handler)(args).await
}
pub fn require_arg(args: &HashMap<String, String>, name: &str) -> Result<String, String> {
args.get(name)
.cloned()
.ok_or_else(|| format!("Error: '{}' argument is required", name))
}
pub fn optional_arg<'a>(args: &'a HashMap<String, String>, name: &str) -> Option<&'a String> {
args.get(name)
}
pub fn build_string_params_schema(
required_params: &[(&str, &str)],
optional_params: &[(&str, &str, &str)],
) -> Schema {
let mut properties = serde_json::Map::new();
let mut required = Vec::new();
for (name, description) in required_params {
properties.insert(
name.to_string(),
serde_json::json!({
"type": "string",
"description": description
}),
);
required.push(name.to_string());
}
for (name, description, _default_val) in optional_params {
properties.insert(
name.to_string(),
serde_json::json!({
"type": "string",
"description": description
}),
);
}
let schema_value = serde_json::json!({
"type": "object",
"properties": properties,
"required": required,
"additionalProperties": false
});
serde_json::from_value(schema_value).unwrap()
}
pub fn make_tool(
name: &str,
description: &str,
category: ToolCategory,
parameters: Schema,
handler: impl Fn(HashMap<String, String>) -> BoxFuture<'static, String> + Send + Sync + 'static,
) -> Tool {
Tool {
name: name.to_string(),
description: description.to_string(),
parameters,
category,
handler: Box::new(handler),
}
}