Skip to main content

vld_web/
rmcp.rs

1//! [rmcp](https://docs.rs/rmcp) (the MCP Rust SDK) tool arguments validated
2//! by vld.
3//!
4//! rmcp deserializes tool arguments with serde and never checks them against
5//! the advertised schema. Here the arguments go through the vld schema, and a
6//! failure is returned as a tool result with `isError: true` whose text is
7//! [`VldError::llm_feedback`] (SEP-1303), so the model can correct the call.
8//!
9//! - [`input_schema::<T>()`](input_schema): the tool's `inputSchema`, from vld.
10//! - [`VldParameters<T>`]: a tool argument extractor (like rmcp's `Parameters`).
11//! - [`parse_args`] + [`VldToolError`]: parse inside the tool and return
12//!   `Result<_, VldToolError>`; the error carries the issues as structured
13//!   content too.
14//!
15//! ```ignore
16//! use rmcp::{handler::server::router::tool::ToolRouter, model::JsonObject, tool, tool_router};
17//! use vld_web::rmcp::{VldParameters, VldToolError, input_schema, parse_args};
18//!
19//! vld::schema! {
20//!     #[derive(Debug)]
21//!     pub struct Forecast {
22//!         pub city: String => vld::string().min(2),
23//!         pub days: u8 => vld::u8().min(1).max(14),
24//!     }
25//! }
26//!
27//! #[tool_router]
28//! impl Weather {
29//!     #[tool(description = "Weather forecast", input_schema = input_schema::<Forecast>())]
30//!     async fn forecast(&self, VldParameters(f): VldParameters<Forecast>) -> String {
31//!         format!("{} days in {}", f.days, f.city)
32//!     }
33//!
34//!     #[tool(description = "Same, parsed in the body", input_schema = input_schema::<Forecast>())]
35//!     async fn forecast2(&self, args: JsonObject) -> Result<String, VldToolError> {
36//!         let f: Forecast = parse_args(args)?;
37//!         Ok(format!("{} days in {}", f.days, f.city))
38//!     }
39//! }
40//! ```
41
42use std::fmt;
43use std::sync::Arc;
44
45use rmcp::ErrorData;
46use rmcp::handler::server::common::FromContextPart;
47use rmcp::handler::server::tool::{IntoCallToolResult, ToolCallContext};
48use rmcp::model::{CallToolResponse, CallToolResult, ContentBlock, JsonObject};
49use serde_json::{Value, json};
50use vld::error::VldError;
51use vld::llm::{LlmFeedbackOptions, LlmSchema, Provider};
52use vld::schema::VldParse;
53
54/// The message prefix rmcp's tool router turns into an `isError` result.
55const ARGS_ERROR_PREFIX: &str = "failed to deserialize parameters: ";
56
57/// The tool's `inputSchema`: `T`'s JSON Schema (draft 2020-12, nested types
58/// in `$defs`), for `#[tool(input_schema = input_schema::<T>())]` or
59/// `Tool::new`.
60///
61/// # Panics
62///
63/// If `T`'s schema has an unresolved `$ref` (a vld bug) or is not an object.
64pub fn input_schema<T: LlmSchema>() -> Arc<JsonObject> {
65    match T::llm_schema(Provider::Generic) {
66        Ok(Value::Object(schema)) => Arc::new(schema),
67        other => panic!(
68            "vld: no MCP input schema for {}: {other:?}",
69            std::any::type_name::<T>()
70        ),
71    }
72}
73
74/// Validation failure of tool arguments, returned to the client as a tool
75/// result with `isError: true`: the text is the feedback lines, the
76/// structured content `{"issues": [{path, expected, received, hint}]}`.
77#[derive(Debug, Clone)]
78pub struct VldToolError {
79    /// The validation issues.
80    pub error: VldError,
81    options: LlmFeedbackOptions,
82}
83
84impl VldToolError {
85    /// Wrap issues; unknown-key hints list the keys of `T`'s schema.
86    pub fn new<T: LlmSchema>(error: VldError) -> Self {
87        Self {
88            error,
89            options: LlmFeedbackOptions {
90                schema: T::llm_schema(Provider::Generic).ok(),
91                ..Default::default()
92            },
93        }
94    }
95
96    /// The text sent to the model.
97    pub fn feedback(&self) -> String {
98        self.error.llm_feedback_with(&self.options)
99    }
100
101    /// The issues as JSON.
102    pub fn feedback_json(&self) -> Value {
103        self.error.llm_feedback_json_with(&self.options)
104    }
105}
106
107impl From<VldError> for VldToolError {
108    fn from(error: VldError) -> Self {
109        Self {
110            error,
111            options: LlmFeedbackOptions::default(),
112        }
113    }
114}
115
116impl fmt::Display for VldToolError {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(&self.feedback())
119    }
120}
121
122impl std::error::Error for VldToolError {}
123
124impl IntoCallToolResult for VldToolError {
125    fn into_call_tool_result(self) -> Result<CallToolResponse, ErrorData> {
126        let mut result = CallToolResult::error(vec![ContentBlock::text(self.feedback())]);
127        result.structured_content = Some(json!({ "issues": self.feedback_json() }));
128        Ok(result.into())
129    }
130}
131
132/// Parse tool arguments as `T`.
133pub fn parse_args<T: VldParse + LlmSchema>(args: JsonObject) -> Result<T, VldToolError> {
134    T::vld_parse_value(&Value::Object(args)).map_err(VldToolError::new::<T>)
135}
136
137/// Tool arguments validated by vld; a failure becomes an `isError` result
138/// with the feedback text. Set the tool's schema with
139/// `#[tool(input_schema = input_schema::<T>())]` (rmcp derives it only for
140/// its own `Parameters`).
141#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
142pub struct VldParameters<T>(pub T);
143
144crate::impl_deref!(VldParameters);
145
146impl<S, T: VldParse + LlmSchema> FromContextPart<ToolCallContext<'_, S>> for VldParameters<T> {
147    fn from_context_part(context: &mut ToolCallContext<'_, S>) -> Result<Self, ErrorData> {
148        let args = context.arguments.take().unwrap_or_default();
149        parse_args(args).map(Self).map_err(|e| {
150            ErrorData::invalid_params(
151                format!("{ARGS_ERROR_PREFIX}{}", e.feedback()),
152                Some(json!({ "issues": e.feedback_json() })),
153            )
154        })
155    }
156}