use std::fmt;
use std::sync::Arc;
use rmcp::ErrorData;
use rmcp::handler::server::common::FromContextPart;
use rmcp::handler::server::tool::{IntoCallToolResult, ToolCallContext};
use rmcp::model::{CallToolResponse, CallToolResult, ContentBlock, JsonObject};
use serde_json::{Value, json};
use vld::error::VldError;
use vld::llm::{LlmFeedbackOptions, LlmSchema, Provider};
use vld::schema::VldParse;
const ARGS_ERROR_PREFIX: &str = "failed to deserialize parameters: ";
pub fn input_schema<T: LlmSchema>() -> Arc<JsonObject> {
match T::llm_schema(Provider::Generic) {
Ok(Value::Object(schema)) => Arc::new(schema),
other => panic!(
"vld: no MCP input schema for {}: {other:?}",
std::any::type_name::<T>()
),
}
}
#[derive(Debug, Clone)]
pub struct VldToolError {
pub error: VldError,
options: LlmFeedbackOptions,
}
impl VldToolError {
pub fn new<T: LlmSchema>(error: VldError) -> Self {
Self {
error,
options: LlmFeedbackOptions {
schema: T::llm_schema(Provider::Generic).ok(),
..Default::default()
},
}
}
pub fn feedback(&self) -> String {
self.error.llm_feedback_with(&self.options)
}
pub fn feedback_json(&self) -> Value {
self.error.llm_feedback_json_with(&self.options)
}
}
impl From<VldError> for VldToolError {
fn from(error: VldError) -> Self {
Self {
error,
options: LlmFeedbackOptions::default(),
}
}
}
impl fmt::Display for VldToolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.feedback())
}
}
impl std::error::Error for VldToolError {}
impl IntoCallToolResult for VldToolError {
fn into_call_tool_result(self) -> Result<CallToolResponse, ErrorData> {
let mut result = CallToolResult::error(vec![ContentBlock::text(self.feedback())]);
result.structured_content = Some(json!({ "issues": self.feedback_json() }));
Ok(result.into())
}
}
pub fn parse_args<T: VldParse + LlmSchema>(args: JsonObject) -> Result<T, VldToolError> {
T::vld_parse_value(&Value::Object(args)).map_err(VldToolError::new::<T>)
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct VldParameters<T>(pub T);
crate::impl_deref!(VldParameters);
impl<S, T: VldParse + LlmSchema> FromContextPart<ToolCallContext<'_, S>> for VldParameters<T> {
fn from_context_part(context: &mut ToolCallContext<'_, S>) -> Result<Self, ErrorData> {
let args = context.arguments.take().unwrap_or_default();
parse_args(args).map(Self).map_err(|e| {
ErrorData::invalid_params(
format!("{ARGS_ERROR_PREFIX}{}", e.feedback()),
Some(json!({ "issues": e.feedback_json() })),
)
})
}
}