use crate::{json, Map, ToolReply, Value};
use serde::Serialize;
use std::fmt;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolAnnotations {
pub read_only_hint: Option<bool>,
pub destructive_hint: Option<bool>,
pub idempotent_hint: Option<bool>,
pub open_world_hint: Option<bool>,
}
impl ToolAnnotations {
#[must_use]
pub const fn is_empty(&self) -> bool {
self.read_only_hint.is_none()
&& self.destructive_hint.is_none()
&& self.idempotent_hint.is_none()
&& self.open_world_hint.is_none()
}
#[must_use]
pub fn to_value(&self) -> Option<Value> {
if self.is_empty() {
return None;
}
let mut object = Map::new();
if let Some(value) = self.read_only_hint {
object.insert("readOnlyHint".to_owned(), Value::Bool(value));
}
if let Some(value) = self.destructive_hint {
object.insert("destructiveHint".to_owned(), Value::Bool(value));
}
if let Some(value) = self.idempotent_hint {
object.insert("idempotentHint".to_owned(), Value::Bool(value));
}
if let Some(value) = self.open_world_hint {
object.insert("openWorldHint".to_owned(), Value::Bool(value));
}
Some(Value::Object(object))
}
}
#[derive(Debug, Clone)]
pub struct ToolDefinition {
pub name: String,
pub description: String,
pub title: Option<String>,
pub input_schema: Value,
pub output_schema: Option<Value>,
pub annotations: ToolAnnotations,
}
impl ToolDefinition {
#[must_use]
pub fn new(
name: impl Into<String>,
description: impl Into<String>,
input_schema: Value,
) -> Self {
Self {
name: name.into(),
description: description.into(),
title: None,
input_schema,
output_schema: None,
annotations: ToolAnnotations::default(),
}
}
}
pub(crate) enum PreparedInvoke<S> {
Stateless(fn(&str) -> ToolReply),
Stateful(fn(&mut S, &str) -> ToolReply),
}
pub struct PreparedTool<S> {
pub(crate) definition: ToolDefinition,
pub(crate) replace: bool,
pub(crate) invoke: PreparedInvoke<S>,
}
impl<S> PreparedTool<S> {
#[must_use]
pub fn stateless(definition: ToolDefinition, invoke: fn(&str) -> ToolReply) -> Self {
Self {
definition,
replace: false,
invoke: PreparedInvoke::Stateless(invoke),
}
}
#[must_use]
pub fn stateful(definition: ToolDefinition, invoke: fn(&mut S, &str) -> ToolReply) -> Self {
Self {
definition,
replace: false,
invoke: PreparedInvoke::Stateful(invoke),
}
}
pub(crate) fn stateless_fn(&self) -> Option<fn(&str) -> ToolReply> {
match self.invoke {
PreparedInvoke::Stateless(invoke) => Some(invoke),
PreparedInvoke::Stateful(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolError {
message: String,
}
impl ToolError {
#[must_use]
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for ToolError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for ToolError {}
impl From<String> for ToolError {
fn from(message: String) -> Self {
Self::new(message)
}
}
impl From<&str> for ToolError {
fn from(message: &str) -> Self {
Self::new(message)
}
}
pub struct Json<T>(pub T);
pub trait IntoToolReply {
fn into_tool_reply(self) -> ToolReply;
}
impl IntoToolReply for ToolReply {
fn into_tool_reply(self) -> ToolReply {
self
}
}
impl IntoToolReply for () {
fn into_tool_reply(self) -> ToolReply {
ToolReply::structured(json!({}))
}
}
impl IntoToolReply for String {
fn into_tool_reply(self) -> ToolReply {
ToolReply::literal_text(self)
}
}
impl IntoToolReply for &'static str {
fn into_tool_reply(self) -> ToolReply {
ToolReply::literal_text(self)
}
}
impl IntoToolReply for Value {
fn into_tool_reply(self) -> ToolReply {
ToolReply::structured(self)
}
}
impl<T: IntoToolReply> IntoToolReply for Result<T, ToolError> {
fn into_tool_reply(self) -> ToolReply {
match self {
Ok(value) => value.into_tool_reply(),
Err(error) => ToolReply::error(error.message),
}
}
}
impl<T: Serialize> IntoToolReply for Json<T> {
fn into_tool_reply(self) -> ToolReply {
ToolReply::structured(self.0)
}
}
macro_rules! impl_primitive_result {
($($ty:ty),+ $(,)?) => {$(
impl IntoToolReply for $ty {
fn into_tool_reply(self) -> ToolReply {
ToolReply::structured(json!({ "result": self }))
}
}
)+};
}
impl_primitive_result!(bool, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64);
impl<T: Serialize> IntoToolReply for Vec<T> {
fn into_tool_reply(self) -> ToolReply {
ToolReply::structured(json!({ "result": self }))
}
}
pub trait ToolSchema {
fn tool_schema() -> Value;
#[must_use]
fn is_required() -> bool {
true
}
}
macro_rules! impl_integer_schema {
($($ty:ty),+ $(,)?) => {$(
impl ToolSchema for $ty {
fn tool_schema() -> Value {
json!({"type": "integer"})
}
}
)+};
}
impl_integer_schema!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);
impl ToolSchema for f32 {
fn tool_schema() -> Value {
json!({"type": "number"})
}
}
impl ToolSchema for f64 {
fn tool_schema() -> Value {
json!({"type": "number"})
}
}
impl ToolSchema for bool {
fn tool_schema() -> Value {
json!({"type": "boolean"})
}
}
impl ToolSchema for String {
fn tool_schema() -> Value {
json!({"type": "string"})
}
}
impl ToolSchema for &str {
fn tool_schema() -> Value {
json!({"type": "string"})
}
}
impl<T: ToolSchema> ToolSchema for Option<T> {
fn tool_schema() -> Value {
T::tool_schema()
}
fn is_required() -> bool {
false
}
}
impl<T: ToolSchema> ToolSchema for Vec<T> {
fn tool_schema() -> Value {
json!({"type": "array", "items": T::tool_schema()})
}
}
impl<T: ToolSchema> ToolSchema for [T] {
fn tool_schema() -> Value {
json!({"type": "array", "items": T::tool_schema()})
}
}
#[must_use]
pub fn object_schema(properties: Map<String, Value>, required: Vec<String>) -> Value {
let required = required.into_iter().map(Value::String).collect::<Vec<_>>();
json!({
"type": "object",
"properties": Value::Object(properties),
"required": required,
"additionalProperties": false
})
}
#[must_use]
pub fn decorate_schema(
mut schema: Value,
description: Option<&str>,
default: Option<Value>,
minimum: Option<f64>,
maximum: Option<f64>,
) -> Value {
let Some(object) = schema.as_object_mut() else {
return schema;
};
if let Some(description) = description {
object.insert(
"description".to_owned(),
Value::String(description.to_owned()),
);
}
if let Some(default) = default {
object.insert("default".to_owned(), default);
}
if let Some(minimum) = minimum {
object.insert("minimum".to_owned(), json!(minimum));
}
if let Some(maximum) = maximum {
object.insert("maximum".to_owned(), json!(maximum));
}
schema
}
#[cfg(test)]
mod tests {
use super::{IntoToolReply, Json, ToolError};
use crate::ToolReply;
#[test]
fn literal_strings_do_not_take_the_json_quote_layer() {
let ToolReply::Literal { text } = "hello".into_tool_reply() else {
panic!("string results must use literal text");
};
assert_eq!(text, "hello");
}
#[test]
fn numbers_use_a_stable_object_wrapper() {
let ToolReply::Serialized { value, .. } = 42_i64.into_tool_reply() else {
panic!("numbers must serialize through structured output");
};
assert_eq!(value.get(), r#"{"result":42}"#);
}
#[test]
fn result_err_is_a_tool_error_not_an_ok_enum() {
let reply: ToolReply =
Result::<i32, ToolError>::Err(ToolError::new("overflow")).into_tool_reply();
assert!(matches!(reply, ToolReply::Error(message) if message == "overflow"));
}
#[test]
fn json_wrapper_serializes_the_inner_value() {
match Json(vec![1, 2]).into_tool_reply() {
ToolReply::Serialized { value, .. } | ToolReply::StructuredAny { value } => {
assert_eq!(value.get(), "[1,2]");
}
other => panic!("Json<T> must serialize T, got {other:?}"),
}
}
}