use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;
use serde_json::{Value, json};
pub(crate) type Answer = Result<Value, Box<dyn StdError + Send + Sync>>;
type Handler = Arc<dyn Fn(&Value) -> Answer + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mark {
Reads,
Writes,
Removes,
}
#[derive(Clone)]
pub struct Tool {
pub(crate) name: String,
description: String,
schema: Value,
pub(crate) mark: Mark,
handler: Handler,
}
impl Tool {
pub fn reads(
name: &str,
description: &str,
schema: Value,
handler: impl Fn(&Value) -> Answer + Send + Sync + 'static,
) -> Tool {
Tool::marked(Mark::Reads, name, description, schema, Arc::new(handler))
}
pub fn writes(
name: &str,
description: &str,
schema: Value,
handler: impl Fn(&Value) -> Answer + Send + Sync + 'static,
) -> Tool {
Tool::marked(Mark::Writes, name, description, schema, Arc::new(handler))
}
pub fn removes(
name: &str,
description: &str,
schema: Value,
handler: impl Fn(&Value) -> Answer + Send + Sync + 'static,
) -> Tool {
Tool::marked(Mark::Removes, name, description, schema, Arc::new(handler))
}
fn marked(mark: Mark, name: &str, description: &str, schema: Value, handler: Handler) -> Tool {
Tool { name: name.to_owned(), description: description.to_owned(), schema, mark, handler }
}
pub(crate) fn schema(&self) -> &Value {
&self.schema
}
pub(crate) fn listed(&self) -> Value {
let annotations = match self.mark {
Mark::Reads => json!({ "readOnlyHint": true, "openWorldHint": false }),
Mark::Writes => json!({ "readOnlyHint": false, "destructiveHint": false, "openWorldHint": false }),
Mark::Removes => json!({ "readOnlyHint": false, "destructiveHint": true, "openWorldHint": false }),
};
json!({
"name": self.name,
"description": self.description,
"inputSchema": self.schema,
"annotations": annotations,
})
}
pub(crate) fn call(&self, arguments: &Value) -> Answer {
(self.handler)(arguments)
}
}
impl fmt::Debug for Tool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Tool").field("name", &self.name).field("mark", &self.mark).finish_non_exhaustive()
}
}
#[derive(Debug)]
#[must_use = "tools are mounted with Server::tools"]
pub struct Tools(pub(crate) Vec<Tool>);
impl Tools {
pub fn prefix(self, prefix: &str) -> Tools {
Tools(self.0.into_iter().map(|tool| Tool { name: format!("{prefix}{}", tool.name), ..tool }).collect())
}
}
impl IntoIterator for Tools {
type Item = Tool;
type IntoIter = std::vec::IntoIter<Tool>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}