use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;
use serde_json::{Value, json};
use crate::CancellationToken;
pub(crate) type Answer = Result<Value, Box<dyn StdError + Send + Sync>>;
pub(crate) type Blocking = Arc<dyn Fn(&Value, &CancellationToken) -> Answer + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mark {
Reads,
Writes,
Removes,
}
impl Mark {
pub(crate) fn verb(self) -> &'static str {
match self {
Mark::Reads => "reads",
Mark::Writes => "writes",
Mark::Removes => "removes",
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct Card {
pub(crate) name: String,
description: String,
schema: Value,
pub(crate) mark: Mark,
}
impl Card {
pub(crate) fn new(mark: Mark, name: &str, description: &str, schema: Value) -> Card {
Card { name: name.to_owned(), description: description.to_owned(), schema, mark }
}
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,
})
}
}
#[derive(Clone)]
pub struct Tool {
pub(crate) card: Card,
pub(crate) handler: Blocking,
}
impl Tool {
pub fn reads(
name: &str,
description: &str,
schema: Value,
handler: impl Fn(&Value, &CancellationToken) -> Answer + Send + Sync + 'static,
) -> Tool {
Tool { card: Card::new(Mark::Reads, name, description, schema), handler: Arc::new(handler) }
}
pub fn writes(
name: &str,
description: &str,
schema: Value,
handler: impl Fn(&Value, &CancellationToken) -> Answer + Send + Sync + 'static,
) -> Tool {
Tool { card: Card::new(Mark::Writes, name, description, schema), handler: Arc::new(handler) }
}
pub fn removes(
name: &str,
description: &str,
schema: Value,
handler: impl Fn(&Value, &CancellationToken) -> Answer + Send + Sync + 'static,
) -> Tool {
Tool { card: Card::new(Mark::Removes, name, description, schema), handler: Arc::new(handler) }
}
}
impl fmt::Debug for Tool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Tool").field("name", &self.card.name).field("mark", &self.card.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 {
let prefixed = |mut tool: Tool| {
tool.card.name = format!("{prefix}{}", tool.card.name);
tool
};
Tools(self.0.into_iter().map(prefixed).collect())
}
}
impl IntoIterator for Tools {
type Item = Tool;
type IntoIter = std::vec::IntoIter<Tool>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}