use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value, json};
use crate::http::{Failure, FailureKind, StatusCode, codes};
use crate::{Context, RuntimeError};
pub const INVALID_ARGUMENTS: &str = "ERROR_INVALID_ARGUMENTS";
pub(super) type Run<App, Scope> = Box<
dyn Fn(
Arc<App>,
Map<String, Value>,
Context<Scope>,
Option<String>,
) -> Pin<Box<dyn Future<Output = Result<Value, Failure>> + Send>>
+ Send
+ Sync,
>;
pub struct Tool<App, Scope> {
pub(super) definition: Value,
pub(super) run: Run<App, Scope>,
}
impl<App, Scope> Tool<App, Scope> {
#[must_use]
pub fn new<A, T, H, F>(
name: impl Into<String>,
description: impl Into<String>,
input_schema: Value,
handler: H,
) -> Self
where
A: DeserializeOwned,
T: Serialize,
H: Fn(Arc<App>, A, Context<Scope>) -> F + Send + Sync + 'static,
F: Future<Output = Result<T, Failure>> + Send + 'static,
{
let definition = json!({
"name": name.into(),
"description": description.into(),
"inputSchema": input_schema,
});
let run: Run<App, Scope> = Box::new(move |app, arguments, context, _authorization| {
match serde_json::from_value::<A>(Value::Object(arguments)) {
Ok(input) => {
let work = handler(app, input, context);
Box::pin(
async move { serde_json::to_value(work.await?).map_err(serialization) },
)
}
Err(error) => {
let failure = Failure::new(
StatusCode::BAD_REQUEST,
INVALID_ARGUMENTS,
format!("Invalid arguments: {error}"),
);
Box::pin(std::future::ready(Err(failure)))
}
}
});
Self { definition, run }
}
#[cfg(feature = "mcp-openapi")]
pub(super) fn from_parts(definition: Value, run: Run<App, Scope>) -> Self {
Self { definition, run }
}
#[must_use]
pub fn annotations(mut self, annotations: Value) -> Self {
self.definition["annotations"] = annotations;
self
}
pub fn name(&self) -> &str {
self.definition["name"].as_str().unwrap_or_default()
}
}
impl<App, Scope> fmt::Debug for Tool<App, Scope> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Tool")
.field("definition", &self.definition)
.finish_non_exhaustive()
}
}
fn serialization(error: serde_json::Error) -> Failure {
Failure::from_error(codes::SERIALIZATION, &error).with_kind(FailureKind::Serialization)
}
pub(super) fn result(
tool: &str,
outcome: Result<Result<Value, Failure>, RuntimeError>,
) -> Map<String, Value> {
match outcome
.map_err(Failure::from)
.and_then(std::convert::identity)
{
Ok(value) => {
let text = match &value {
Value::String(text) => text.clone(),
other => other.to_string(),
};
let mut result = content(text, false);
if value.is_object() {
result.insert("structuredContent".into(), value);
}
result
}
Err(failure) => {
log(tool, &failure);
let text = format!("{}: {}", failure.code(), failure.public_message());
content(text, true)
}
}
}
fn content(text: String, error: bool) -> Map<String, Value> {
let mut result = Map::new();
result.insert("content".into(), json!([{ "type": "text", "text": text }]));
result.insert("isError".into(), json!(error));
result
}
fn log(tool: &str, failure: &Failure) {
#[cfg(feature = "logs")]
{
if failure.is_server_error() {
tracing::error!(tool, code = failure.code(), kind = ?failure.kind(), "tool failed");
} else {
tracing::debug!(tool, code = failure.code(), "tool refused");
}
}
#[cfg(not(feature = "logs"))]
{
let _ = (tool, failure);
}
}