feat: Add support for Tool.outputSchema and CallToolResult.structuredContent (#316)
* feat: add output_schema field to Tool struct - Add optional output_schema field to Tool struct for defining tool output structure - Update Tool::new() to initialize output_schema as None * feat: add structured_content field to CallToolResult - Add optional structured_content field for JSON object results - Make content field optional to support either structured or unstructured results - Add CallToolResult::structured() and structured_error() constructor methods * feat: implement validation for mutually exclusive content/structuredContent - Add validate() method to ensure content and structured_content are mutually exclusive - Implement custom Deserialize to enforce validation during deserialization - Update documentation to clarify the mutual exclusivity requirement * feat: add output_schema support to #[tool] macro - Add output_schema field to ToolAttribute and ResolvedToolAttribute structs - Implement automatic output schema generation from return types - Support explicit output_schema attribute for manual specification - Generate schemas for Result<T, E> where T is not CallToolResult - Update tool generation to include output_schema in Tool struct * feat: implement IntoCallToolResult for structured content - Add Structured<T> wrapper type for explicit structured content - Implement IntoCallToolResult for Structured<T> with JSON serialization - Add support for Result<Structured<T>, E> conversions - Enable tools to return structured content through the trait system * fix: update simple-chat-client example for optional content field - Handle Option<Vec<Content>> in CallToolResult.content - Add proper unwrapping for the optional content field - Fix compilation error in chat.rs * fix: update examples and tests for optional content field - Add output_schema field to Tool initialization in sampling_stdio example - Update test_tool_macros tests to handle Option<Vec<Content>> - Use as_ref() before calling first() on optional content field * feat: implement basic schema validation in conversion logic - Add validate_against_schema function for basic type validation - Add note that full JSON Schema validation requires dedicated library - Document that actual validation should happen in tool handler * feat: add structured output support for tools - Add output_schema field to Tool struct for defining output JSON schemas - Add structured_content field to CallToolResult (mutually exclusive with content) - Implement Structured<T> wrapper for type-safe structured outputs - Update #[tool] macro to automatically generate output schemas from return types - Add validation of structured outputs against their schemas - Update all examples and tests for breaking change (CallToolResult.content now Option) - Add comprehensive documentation and rustdoc - Add structured_output example demonstrating the feature BREAKING CHANGE: CallToolResult.content is now Option<Vec<Content>> instead of Vec<Content> Closes #312 * fix: correct structured output doctest to use Parameters wrapper The #[tool] macro requires Parameters<T> wrapper for tool inputs. This fixes the pre-existing broken doctest in the structured output documentation example. * feat: replace Structured<T> with Json<T> for structured output - Remove Structured<T> type definition and implementations - Reuse existing Json<T> wrapper for structured content - Update IntoCallToolResult implementations to use Json<T> - Add JsonSchema implementation for Json<T> delegating to T - Update all examples and tests to use Json<T> instead of Structured<T> - Update documentation and exports BREAKING CHANGE: Structured<T> has been replaced with Json<T>. Users must update their code to use Json<T> for structured tool outputs. * feat: add output_schema() method to IntoCallToolResult trait - Add output_schema() method with default None implementation - Implement output_schema() for Json<T> to return cached schema - Implement output_schema() for Result<Json<T>, E> delegating to Json<T> - Enable trait-based schema generation for structured outputs * feat: update macro to detect Json<T> wrapper for output schemas - Add extract_json_inner_type() helper to detect Json<T> types - Update schema generation to only occur for Json<T> wrapped types - Remove generic Result<T, E> detection in favor of specific Json<T> detection - Add comprehensive tests to verify schema generation behavior * feat: add builder methods to Tool struct for setting schemas - Add with_output_schema<T>() method to set output schema from type - Add with_input_schema<T>() method to set input schema from type - Both methods use cached_schema_for_type internally - Add comprehensive tests for builder methods * fix: address clippy warnings - Add Default implementation for StructuredOutputServer - Fix collapsible else-if in simple-chat-client - No functional changes * style: apply cargo fmt Apply automatic formatting changes to: - examples/simple-chat-client/src/chat.rs - fix line wrapping - crates/rmcp-macros/src/tool.rs - format method chaining - examples/servers/src/structured_output.rs - reorder imports and format function signatures * chore: fix formatting * chore: fix rustdoc redundant link warning * refactor: validate_against_schema * feat: enforce structured_content usage when output_schema is defined This commit implements strict validation to ensure tools with output_schema consistently use structured_content for both success and error responses. Changes: - Enhanced ToolRouter::call() validation to require structured_content when output_schema is present - Added validation that tools with output_schema cannot use regular content field - Added comprehensive tests covering the new strict validation behavior - Created example demonstrating proper structured output usage - Updated TODO.md to track validation improvements This ensures consistent response format and better type safety for MCP clients. * chore: remove TODO.md * refactor: simplify output schema extraction logic in tool macro - Extract complex nested logic into dedicated helper function - Replace deeply nested if-else chains with functional approach - Use early returns and ? operator for cleaner code flow - Reduce 46 lines to 7 lines in main logic while improving readability * chore: run cargo fmt * fix: enforce structured_content usage when output_schema is defined Structured content is returned as a JSON object in the structuredContent field of a result.For backwards compatibility, a tool that returns structured content SHOULD also return the serialized JSON in a TextContent block. https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content Tools may also provide an output schema for validation of structured results. If an output schema is provided: - Servers MUST provide structured results that conform to this schema. - Clients SHOULD validate structured results against this schema. https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema * chore: cargo fmt
This commit is contained in:
parent
b1da5e8969
commit
fbc7ab70ca
3 changed files with 2658 additions and 41 deletions
|
|
@ -6,6 +6,7 @@ use schemars::JsonSchema;
|
|||
use crate::{
|
||||
handler::server::tool::{
|
||||
CallToolHandler, DynCallToolHandler, ToolCallContext, schema_for_type,
|
||||
validate_against_schema,
|
||||
},
|
||||
model::{CallToolResult, Tool, ToolAnnotations},
|
||||
};
|
||||
|
|
@ -242,7 +243,23 @@ where
|
|||
.map
|
||||
.get(context.name())
|
||||
.ok_or_else(|| crate::ErrorData::invalid_params("tool not found", None))?;
|
||||
(item.call)(context).await
|
||||
|
||||
let result = (item.call)(context).await?;
|
||||
|
||||
// Validate structured content against output schema if present
|
||||
if let Some(ref output_schema) = item.attr.output_schema {
|
||||
// When output_schema is defined, structured_content is required
|
||||
if result.structured_content.is_none() {
|
||||
return Err(crate::ErrorData::invalid_params(
|
||||
"Tool with output_schema must return structured_content",
|
||||
None,
|
||||
));
|
||||
}
|
||||
// Validate the structured content against the schema
|
||||
validate_against_schema(result.structured_content.as_ref().unwrap(), output_schema)?;
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn list_all(&self) -> Vec<crate::model::Tool> {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,39 @@
|
|||
//! Tool handler traits and types for MCP servers.
|
||||
//!
|
||||
//! This module provides the infrastructure for implementing tools that can be called
|
||||
//! by MCP clients. Tools can return either unstructured content (text, images) or
|
||||
//! structured JSON data with schemas.
|
||||
//!
|
||||
//! # Structured Output
|
||||
//!
|
||||
//! Tools can return structured JSON data using the [`Json`] wrapper type.
|
||||
//! When using `Json<T>`, the framework will:
|
||||
//! - Automatically generate a JSON schema for the output type
|
||||
//! - Validate the output against the schema
|
||||
//! - Return the data in the `structured_content` field of [`CallToolResult`]
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! use rmcp::{tool, Json};
|
||||
//! use schemars::JsonSchema;
|
||||
//! use serde::{Serialize, Deserialize};
|
||||
//!
|
||||
//! #[derive(Serialize, Deserialize, JsonSchema)]
|
||||
//! struct AnalysisResult {
|
||||
//! score: f64,
|
||||
//! summary: String,
|
||||
//! }
|
||||
//!
|
||||
//! #[tool(name = "analyze")]
|
||||
//! async fn analyze(&self, text: String) -> Result<Json<AnalysisResult>, String> {
|
||||
//! Ok(Json(AnalysisResult {
|
||||
//! score: 0.95,
|
||||
//! summary: "Positive sentiment".to_string(),
|
||||
//! }))
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use std::{
|
||||
any::TypeId, borrow::Cow, collections::HashMap, future::Ready, marker::PhantomData, sync::Arc,
|
||||
};
|
||||
|
|
@ -10,6 +46,7 @@ use tokio_util::sync::CancellationToken;
|
|||
pub use super::router::tool::{ToolRoute, ToolRouter};
|
||||
use crate::{
|
||||
RoleServer,
|
||||
handler::server::wrapper::Json,
|
||||
model::{CallToolRequestParam, CallToolResult, IntoContents, JsonObject},
|
||||
schemars::generate::SchemaSettings,
|
||||
service::RequestContext,
|
||||
|
|
@ -30,6 +67,43 @@ pub fn schema_for_type<T: JsonSchema>() -> JsonObject {
|
|||
}
|
||||
}
|
||||
|
||||
/// Validate that a JSON value conforms to basic type constraints from a schema.
|
||||
///
|
||||
/// Note: This is a basic validation that only checks type compatibility.
|
||||
/// For full JSON Schema validation, a dedicated validation library would be needed.
|
||||
pub fn validate_against_schema(
|
||||
value: &serde_json::Value,
|
||||
schema: &JsonObject,
|
||||
) -> Result<(), crate::ErrorData> {
|
||||
// Basic type validation
|
||||
if let Some(schema_type) = schema.get("type").and_then(|t| t.as_str()) {
|
||||
let value_type = get_json_value_type(value);
|
||||
|
||||
if schema_type != value_type {
|
||||
return Err(crate::ErrorData::invalid_params(
|
||||
format!(
|
||||
"Value type does not match schema. Expected '{}', got '{}'",
|
||||
schema_type, value_type
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_json_value_type(value: &serde_json::Value) -> &'static str {
|
||||
match value {
|
||||
serde_json::Value::Null => "null",
|
||||
serde_json::Value::Bool(_) => "boolean",
|
||||
serde_json::Value::Number(_) => "number",
|
||||
serde_json::Value::String(_) => "string",
|
||||
serde_json::Value::Array(_) => "array",
|
||||
serde_json::Value::Object(_) => "object",
|
||||
}
|
||||
}
|
||||
|
||||
/// Call [`schema_for_type`] with a cache
|
||||
pub fn cached_schema_for_type<T: JsonSchema + std::any::Any>() -> Arc<JsonObject> {
|
||||
thread_local! {
|
||||
|
|
@ -97,8 +171,26 @@ pub trait FromToolCallContextPart<S>: Sized {
|
|||
) -> Result<Self, crate::ErrorData>;
|
||||
}
|
||||
|
||||
/// Trait for converting tool return values into [`CallToolResult`].
|
||||
///
|
||||
/// This trait is automatically implemented for:
|
||||
/// - Types implementing [`IntoContents`] (returns unstructured content)
|
||||
/// - `Result<T, E>` where both `T` and `E` implement [`IntoContents`]
|
||||
/// - [`Json<T>`](crate::handler::server::wrapper::Json) where `T` implements [`Serialize`] (returns structured content)
|
||||
/// - `Result<Json<T>, E>` for structured results with errors
|
||||
///
|
||||
/// The `#[tool]` macro uses this trait to convert tool function return values
|
||||
/// into the appropriate [`CallToolResult`] format.
|
||||
pub trait IntoCallToolResult {
|
||||
fn into_call_tool_result(self) -> Result<CallToolResult, crate::ErrorData>;
|
||||
|
||||
/// Returns the output schema for this type, if any.
|
||||
///
|
||||
/// This is used by the macro to automatically generate output schemas
|
||||
/// for tool functions that return structured data.
|
||||
fn output_schema() -> Option<Arc<JsonObject>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoContents> IntoCallToolResult for T {
|
||||
|
|
@ -125,6 +217,40 @@ impl<T: IntoCallToolResult> IntoCallToolResult for Result<T, crate::ErrorData> {
|
|||
}
|
||||
}
|
||||
|
||||
// Implementation for Json<T> to create structured content
|
||||
impl<T: Serialize + JsonSchema + 'static> IntoCallToolResult for Json<T> {
|
||||
fn into_call_tool_result(self) -> Result<CallToolResult, crate::ErrorData> {
|
||||
let value = serde_json::to_value(self.0).map_err(|e| {
|
||||
crate::ErrorData::internal_error(
|
||||
format!("Failed to serialize structured content: {}", e),
|
||||
None,
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(CallToolResult::structured(value))
|
||||
}
|
||||
|
||||
fn output_schema() -> Option<Arc<JsonObject>> {
|
||||
Some(cached_schema_for_type::<T>())
|
||||
}
|
||||
}
|
||||
|
||||
// Implementation for Result<Json<T>, E>
|
||||
impl<T: Serialize + JsonSchema + 'static, E: IntoContents> IntoCallToolResult
|
||||
for Result<Json<T>, E>
|
||||
{
|
||||
fn into_call_tool_result(self) -> Result<CallToolResult, crate::ErrorData> {
|
||||
match self {
|
||||
Ok(value) => value.into_call_tool_result(),
|
||||
Err(error) => Ok(CallToolResult::error(error.into_contents())),
|
||||
}
|
||||
}
|
||||
|
||||
fn output_schema() -> Option<Arc<JsonObject>> {
|
||||
Json::<T>::output_schema()
|
||||
}
|
||||
}
|
||||
|
||||
pin_project_lite::pin_project! {
|
||||
#[project = IntoCallToolResultFutProj]
|
||||
pub enum IntoCallToolResultFut<F, R> {
|
||||
|
|
|
|||
|
|
@ -1,28 +1,22 @@
|
|||
use serde::Serialize;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::model::IntoContents;
|
||||
use schemars::JsonSchema;
|
||||
|
||||
/// Json wrapper
|
||||
/// Json wrapper for structured output
|
||||
///
|
||||
/// This is used to tell the SDK to serialize the inner value into json
|
||||
/// When used with tools, this wrapper indicates that the value should be
|
||||
/// serialized as structured JSON content with an associated schema.
|
||||
/// The framework will place the JSON in the `structured_content` field
|
||||
/// of the tool result rather than the regular `content` field.
|
||||
pub struct Json<T>(pub T);
|
||||
|
||||
impl<T> IntoContents for Json<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
fn into_contents(self) -> Vec<crate::model::Content> {
|
||||
let result = crate::model::Content::json(self.0);
|
||||
debug_assert!(
|
||||
result.is_ok(),
|
||||
"Json wrapped content should be able to serialized into json"
|
||||
);
|
||||
match result {
|
||||
Ok(content) => vec![content],
|
||||
Err(e) => {
|
||||
tracing::error!("failed to convert json content: {e}");
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
// Implement JsonSchema for Json<T> to delegate to T's schema
|
||||
impl<T: JsonSchema> JsonSchema for Json<T> {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
T::schema_name()
|
||||
}
|
||||
|
||||
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
T::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue