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
17 changed files with 2658 additions and 41 deletions
|
|
@ -10,6 +10,8 @@ pub struct ToolAttribute {
|
|||
pub description: Option<String>,
|
||||
/// A JSON Schema object defining the expected parameters for the tool
|
||||
pub input_schema: Option<Expr>,
|
||||
/// An optional JSON Schema object defining the structure of the tool's output
|
||||
pub output_schema: Option<Expr>,
|
||||
/// Optional additional tool information.
|
||||
pub annotations: Option<ToolAnnotationsAttribute>,
|
||||
}
|
||||
|
|
@ -18,6 +20,7 @@ pub struct ResolvedToolAttribute {
|
|||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub input_schema: Expr,
|
||||
pub output_schema: Option<Expr>,
|
||||
pub annotations: Expr,
|
||||
}
|
||||
|
||||
|
|
@ -27,6 +30,7 @@ impl ResolvedToolAttribute {
|
|||
name,
|
||||
description,
|
||||
input_schema,
|
||||
output_schema,
|
||||
annotations,
|
||||
} = self;
|
||||
let description = if let Some(description) = description {
|
||||
|
|
@ -34,12 +38,18 @@ impl ResolvedToolAttribute {
|
|||
} else {
|
||||
quote! { None }
|
||||
};
|
||||
let output_schema = if let Some(output_schema) = output_schema {
|
||||
quote! { Some(#output_schema) }
|
||||
} else {
|
||||
quote! { None }
|
||||
};
|
||||
let tokens = quote! {
|
||||
pub fn #fn_ident() -> rmcp::model::Tool {
|
||||
rmcp::model::Tool {
|
||||
name: #name.into(),
|
||||
description: #description,
|
||||
input_schema: #input_schema,
|
||||
output_schema: #output_schema,
|
||||
annotations: #annotations,
|
||||
}
|
||||
}
|
||||
|
|
@ -89,6 +99,63 @@ fn none_expr() -> Expr {
|
|||
syn::parse2::<Expr>(quote! { None }).unwrap()
|
||||
}
|
||||
|
||||
/// Check if a type is Json<T> and extract the inner type T
|
||||
fn extract_json_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
|
||||
if let syn::Type::Path(type_path) = ty {
|
||||
if let Some(last_segment) = type_path.path.segments.last() {
|
||||
if last_segment.ident == "Json" {
|
||||
if let syn::PathArguments::AngleBracketed(args) = &last_segment.arguments {
|
||||
if let Some(syn::GenericArgument::Type(inner_type)) = args.args.first() {
|
||||
return Some(inner_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Extract schema expression from a function's return type
|
||||
/// Handles patterns like Json<T> and Result<Json<T>, E>
|
||||
fn extract_schema_from_return_type(ret_type: &syn::Type) -> Option<Expr> {
|
||||
// First, try direct Json<T>
|
||||
if let Some(inner_type) = extract_json_inner_type(ret_type) {
|
||||
return syn::parse2::<Expr>(quote! {
|
||||
rmcp::handler::server::tool::cached_schema_for_type::<#inner_type>()
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
// Then, try Result<Json<T>, E>
|
||||
let type_path = match ret_type {
|
||||
syn::Type::Path(path) => path,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let last_segment = type_path.path.segments.last()?;
|
||||
|
||||
if last_segment.ident != "Result" {
|
||||
return None;
|
||||
}
|
||||
|
||||
let args = match &last_segment.arguments {
|
||||
syn::PathArguments::AngleBracketed(args) => args,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let ok_type = match args.args.first()? {
|
||||
syn::GenericArgument::Type(ty) => ty,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let inner_type = extract_json_inner_type(ok_type)?;
|
||||
|
||||
syn::parse2::<Expr>(quote! {
|
||||
rmcp::handler::server::tool::cached_schema_for_type::<#inner_type>()
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
// extract doc line from attribute
|
||||
fn extract_doc_line(existing_docs: Option<String>, attr: &syn::Attribute) -> Option<String> {
|
||||
if !attr.path().is_ident("doc") {
|
||||
|
|
@ -192,12 +259,22 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
|
|||
} else {
|
||||
none_expr()
|
||||
};
|
||||
// Handle output_schema - either explicit or generated from return type
|
||||
let output_schema_expr = attribute.output_schema.or_else(|| {
|
||||
// Try to generate schema from return type
|
||||
match &fn_item.sig.output {
|
||||
syn::ReturnType::Type(_, ret_type) => extract_schema_from_return_type(ret_type),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
|
||||
let resolved_tool_attr = ResolvedToolAttribute {
|
||||
name: attribute.name.unwrap_or_else(|| fn_ident.to_string()),
|
||||
description: attribute
|
||||
.description
|
||||
.or_else(|| fn_item.attrs.iter().fold(None, extract_doc_line)),
|
||||
input_schema: input_schema_expr,
|
||||
output_schema: output_schema_expr,
|
||||
annotations: annotations_expr,
|
||||
};
|
||||
let tool_attr_fn = resolved_tool_attr.into_fn(tool_attr_fn_ident)?;
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,8 +48,52 @@
|
|||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! Next also implement [ServerHandler] for `Counter` and start the server inside
|
||||
//! `main` by calling `Counter::new().serve(...)`. See the examples directory in the repository for more information.
|
||||
//! ### Structured Output
|
||||
//!
|
||||
//! Tools can also return structured JSON data with schemas. Use the [`Json`] wrapper:
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use rmcp::{tool, tool_router, handler::server::tool::{ToolRouter, Parameters}, Json};
|
||||
//! # use schemars::JsonSchema;
|
||||
//! # use serde::{Serialize, Deserialize};
|
||||
//! #
|
||||
//! #[derive(Serialize, Deserialize, JsonSchema)]
|
||||
//! struct CalculationRequest {
|
||||
//! a: i32,
|
||||
//! b: i32,
|
||||
//! operation: String,
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Serialize, Deserialize, JsonSchema)]
|
||||
//! struct CalculationResult {
|
||||
//! result: i32,
|
||||
//! operation: String,
|
||||
//! }
|
||||
//!
|
||||
//! # #[derive(Clone)]
|
||||
//! # struct Calculator {
|
||||
//! # tool_router: ToolRouter<Self>,
|
||||
//! # }
|
||||
//! #
|
||||
//! # #[tool_router]
|
||||
//! # impl Calculator {
|
||||
//! #[tool(name = "calculate", description = "Perform a calculation")]
|
||||
//! async fn calculate(&self, params: Parameters<CalculationRequest>) -> Result<Json<CalculationResult>, String> {
|
||||
//! let result = match params.0.operation.as_str() {
|
||||
//! "add" => params.0.a + params.0.b,
|
||||
//! "multiply" => params.0.a * params.0.b,
|
||||
//! _ => return Err("Unknown operation".to_string()),
|
||||
//! };
|
||||
//!
|
||||
//! Ok(Json(CalculationResult { result, operation: params.0.operation }))
|
||||
//! }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! The `#[tool]` macro automatically generates an output schema from the `CalculationResult` type.
|
||||
//!
|
||||
//! Next also implement [ServerHandler] for your server type and start the server inside
|
||||
//! `main` by calling `.serve(...)`. See the examples directory in the repository for more information.
|
||||
//!
|
||||
//! ## Client
|
||||
//!
|
||||
|
|
@ -104,6 +148,9 @@ pub use handler::client::ClientHandler;
|
|||
#[cfg(feature = "server")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
|
||||
pub use handler::server::ServerHandler;
|
||||
#[cfg(feature = "server")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
|
||||
pub use handler::server::wrapper::Json;
|
||||
#[cfg(any(feature = "client", feature = "server"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "client", feature = "server"))))]
|
||||
pub use service::{Peer, Service, ServiceError, ServiceExt};
|
||||
|
|
|
|||
|
|
@ -1181,32 +1181,126 @@ pub type RootsListChangedNotification = NotificationNoParam<RootsListChangedNoti
|
|||
///
|
||||
/// Contains the content returned by the tool execution and an optional
|
||||
/// flag indicating whether the operation resulted in an error.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
|
||||
///
|
||||
/// Note: `content` and `structured_content` are mutually exclusive - exactly one must be provided.
|
||||
#[derive(Debug, Serialize, Clone, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
pub struct CallToolResult {
|
||||
/// The content returned by the tool (text, images, etc.)
|
||||
pub content: Vec<Content>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub content: Option<Vec<Content>>,
|
||||
/// An optional JSON object that represents the structured result of the tool call
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub structured_content: Option<Value>,
|
||||
/// Whether this result represents an error condition
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_error: Option<bool>,
|
||||
}
|
||||
|
||||
impl CallToolResult {
|
||||
/// Create a successful tool result
|
||||
/// Create a successful tool result with unstructured content
|
||||
pub fn success(content: Vec<Content>) -> Self {
|
||||
CallToolResult {
|
||||
content,
|
||||
content: Some(content),
|
||||
structured_content: None,
|
||||
is_error: Some(false),
|
||||
}
|
||||
}
|
||||
/// Create an error tool result
|
||||
/// Create an error tool result with unstructured content
|
||||
pub fn error(content: Vec<Content>) -> Self {
|
||||
CallToolResult {
|
||||
content,
|
||||
content: Some(content),
|
||||
structured_content: None,
|
||||
is_error: Some(true),
|
||||
}
|
||||
}
|
||||
/// Create a successful tool result with structured content
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// use rmcp::model::CallToolResult;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let result = CallToolResult::structured(json!({
|
||||
/// "temperature": 22.5,
|
||||
/// "humidity": 65,
|
||||
/// "description": "Partly cloudy"
|
||||
/// }));
|
||||
/// ```
|
||||
pub fn structured(value: Value) -> Self {
|
||||
CallToolResult {
|
||||
content: None,
|
||||
structured_content: Some(value),
|
||||
is_error: Some(false),
|
||||
}
|
||||
}
|
||||
/// Create an error tool result with structured content
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// use rmcp::model::CallToolResult;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let result = CallToolResult::structured_error(json!({
|
||||
/// "error_code": "INVALID_INPUT",
|
||||
/// "message": "Temperature value out of range",
|
||||
/// "details": {
|
||||
/// "min": -50,
|
||||
/// "max": 50,
|
||||
/// "provided": 100
|
||||
/// }
|
||||
/// }));
|
||||
/// ```
|
||||
pub fn structured_error(value: Value) -> Self {
|
||||
CallToolResult {
|
||||
content: None,
|
||||
structured_content: Some(value),
|
||||
is_error: Some(true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate that content and structured_content are mutually exclusive
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
match (&self.content, &self.structured_content) {
|
||||
(Some(_), Some(_)) => Err("content and structured_content are mutually exclusive"),
|
||||
(None, None) => Err("either content or structured_content must be provided"),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Custom deserialize implementation to validate mutual exclusivity
|
||||
impl<'de> Deserialize<'de> for CallToolResult {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct CallToolResultHelper {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
content: Option<Vec<Content>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
structured_content: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
is_error: Option<bool>,
|
||||
}
|
||||
|
||||
let helper = CallToolResultHelper::deserialize(deserializer)?;
|
||||
let result = CallToolResult {
|
||||
content: helper.content,
|
||||
structured_content: helper.structured_content,
|
||||
is_error: helper.is_error,
|
||||
};
|
||||
|
||||
// Validate mutual exclusivity
|
||||
result.validate().map_err(serde::de::Error::custom)?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
const_string!(ListToolsRequestMethod = "tools/list");
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
use std::{borrow::Cow, sync::Arc};
|
||||
|
||||
use schemars::JsonSchema;
|
||||
/// Tools represent a routine that a server can execute
|
||||
/// Tool calls represent requests from the client to execute one
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
@ -19,6 +20,9 @@ pub struct Tool {
|
|||
pub description: Option<Cow<'static, str>>,
|
||||
/// A JSON Schema object defining the expected parameters for the tool
|
||||
pub input_schema: Arc<JsonObject>,
|
||||
/// An optional JSON Schema object defining the structure of the tool's output
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub output_schema: Option<Arc<JsonObject>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
/// Optional additional tool information.
|
||||
pub annotations: Option<ToolAnnotations>,
|
||||
|
|
@ -136,6 +140,7 @@ impl Tool {
|
|||
name: name.into(),
|
||||
description: Some(description.into()),
|
||||
input_schema: input_schema.into(),
|
||||
output_schema: None,
|
||||
annotations: None,
|
||||
}
|
||||
}
|
||||
|
|
@ -147,6 +152,18 @@ impl Tool {
|
|||
}
|
||||
}
|
||||
|
||||
/// Set the output schema using a type that implements JsonSchema
|
||||
pub fn with_output_schema<T: JsonSchema + 'static>(mut self) -> Self {
|
||||
self.output_schema = Some(crate::handler::server::tool::cached_schema_for_type::<T>());
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the input schema using a type that implements JsonSchema
|
||||
pub fn with_input_schema<T: JsonSchema + 'static>(mut self) -> Self {
|
||||
self.input_schema = crate::handler::server::tool::cached_schema_for_type::<T>();
|
||||
self
|
||||
}
|
||||
|
||||
/// Get the schema as json value
|
||||
pub fn schema_as_json_value(&self) -> Value {
|
||||
Value::Object(self.input_schema.as_ref().clone())
|
||||
|
|
|
|||
114
crates/rmcp/tests/test_json_schema_detection.rs
Normal file
114
crates/rmcp/tests/test_json_schema_detection.rs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
//cargo test --test test_json_schema_detection --features "client server macros"
|
||||
use rmcp::{
|
||||
Json, ServerHandler, handler::server::router::tool::ToolRouter, tool, tool_handler, tool_router,
|
||||
};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||
pub struct TestData {
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[tool_handler(router = self.tool_router)]
|
||||
impl ServerHandler for TestServer {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TestServer {
|
||||
tool_router: ToolRouter<Self>,
|
||||
}
|
||||
|
||||
impl Default for TestServer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[tool_router(router = tool_router)]
|
||||
impl TestServer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tool_router: Self::tool_router(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool that returns Json<T> - should have output schema
|
||||
#[tool(name = "with-json")]
|
||||
pub async fn with_json(&self) -> Result<Json<TestData>, String> {
|
||||
Ok(Json(TestData {
|
||||
value: "test".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Tool that returns regular type - should NOT have output schema
|
||||
#[tool(name = "without-json")]
|
||||
pub async fn without_json(&self) -> Result<String, String> {
|
||||
Ok("test".to_string())
|
||||
}
|
||||
|
||||
/// Tool that returns Result with inner Json - should have output schema
|
||||
#[tool(name = "result-with-json")]
|
||||
pub async fn result_with_json(&self) -> Result<Json<TestData>, rmcp::ErrorData> {
|
||||
Ok(Json(TestData {
|
||||
value: "test".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Tool with explicit output_schema attribute - should have output schema
|
||||
#[tool(name = "explicit-schema", output_schema = rmcp::handler::server::tool::cached_schema_for_type::<TestData>())]
|
||||
pub async fn explicit_schema(&self) -> Result<String, String> {
|
||||
Ok("test".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_json_type_generates_schema() {
|
||||
let server = TestServer::new();
|
||||
let tools = server.tool_router.list_all();
|
||||
|
||||
// Find the with-json tool
|
||||
let json_tool = tools.iter().find(|t| t.name == "with-json").unwrap();
|
||||
assert!(
|
||||
json_tool.output_schema.is_some(),
|
||||
"Json<T> return type should generate output schema"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_non_json_type_no_schema() {
|
||||
let server = TestServer::new();
|
||||
let tools = server.tool_router.list_all();
|
||||
|
||||
// Find the without-json tool
|
||||
let non_json_tool = tools.iter().find(|t| t.name == "without-json").unwrap();
|
||||
assert!(
|
||||
non_json_tool.output_schema.is_none(),
|
||||
"Regular return type should NOT generate output schema"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_result_with_json_generates_schema() {
|
||||
let server = TestServer::new();
|
||||
let tools = server.tool_router.list_all();
|
||||
|
||||
// Find the result-with-json tool
|
||||
let result_json_tool = tools.iter().find(|t| t.name == "result-with-json").unwrap();
|
||||
assert!(
|
||||
result_json_tool.output_schema.is_some(),
|
||||
"Result<Json<T>, E> return type should generate output schema"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_explicit_schema_override() {
|
||||
let server = TestServer::new();
|
||||
let tools = server.tool_router.list_all();
|
||||
|
||||
// Find the explicit-schema tool
|
||||
let explicit_tool = tools.iter().find(|t| t.name == "explicit-schema").unwrap();
|
||||
assert!(
|
||||
explicit_tool.output_schema.is_some(),
|
||||
"Explicit output_schema attribute should work"
|
||||
);
|
||||
}
|
||||
|
|
@ -299,12 +299,15 @@
|
|||
}
|
||||
},
|
||||
"CallToolResult": {
|
||||
"description": "The result of a tool call operation.\n\nContains the content returned by the tool execution and an optional\nflag indicating whether the operation resulted in an error.",
|
||||
"description": "The result of a tool call operation.\n\nContains the content returned by the tool execution and an optional\nflag indicating whether the operation resulted in an error.\n\nNote: `content` and `structured_content` are mutually exclusive - exactly one must be provided.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"description": "The content returned by the tool (text, images, etc.)",
|
||||
"type": "array",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Annotated"
|
||||
}
|
||||
|
|
@ -315,11 +318,11 @@
|
|||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"structuredContent": {
|
||||
"description": "An optional JSON object that represents the structured result of the tool call"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"content"
|
||||
]
|
||||
}
|
||||
},
|
||||
"CancelledNotificationMethod": {
|
||||
"type": "string",
|
||||
|
|
@ -1580,6 +1583,14 @@
|
|||
"name": {
|
||||
"description": "The name of the tool",
|
||||
"type": "string"
|
||||
},
|
||||
"outputSchema": {
|
||||
"description": "An optional JSON Schema object defining the structure of the tool's output",
|
||||
"type": [
|
||||
"object",
|
||||
"null"
|
||||
],
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
233
crates/rmcp/tests/test_structured_output.rs
Normal file
233
crates/rmcp/tests/test_structured_output.rs
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
//cargo test --test test_structured_output --features "client server macros"
|
||||
use rmcp::{
|
||||
Json, ServerHandler,
|
||||
handler::server::{router::tool::ToolRouter, tool::Parameters},
|
||||
model::{CallToolResult, Content, Tool},
|
||||
tool, tool_handler, tool_router,
|
||||
};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CalculationRequest {
|
||||
pub a: i32,
|
||||
pub b: i32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CalculationResult {
|
||||
pub sum: i32,
|
||||
pub product: i32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||
pub struct UserInfo {
|
||||
pub name: String,
|
||||
pub age: u32,
|
||||
}
|
||||
|
||||
#[tool_handler(router = self.tool_router)]
|
||||
impl ServerHandler for TestServer {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TestServer {
|
||||
tool_router: ToolRouter<Self>,
|
||||
}
|
||||
|
||||
impl Default for TestServer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[tool_router(router = tool_router)]
|
||||
impl TestServer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tool_router: Self::tool_router(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool that returns structured output
|
||||
#[tool(name = "calculate", description = "Perform calculations")]
|
||||
pub async fn calculate(
|
||||
&self,
|
||||
params: Parameters<CalculationRequest>,
|
||||
) -> Result<Json<CalculationResult>, String> {
|
||||
Ok(Json(CalculationResult {
|
||||
sum: params.0.a + params.0.b,
|
||||
product: params.0.a * params.0.b,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Tool that returns regular string output
|
||||
#[tool(name = "get-greeting", description = "Get a greeting")]
|
||||
pub async fn get_greeting(&self, name: Parameters<String>) -> String {
|
||||
format!("Hello, {}!", name.0)
|
||||
}
|
||||
|
||||
/// Tool that returns structured user info
|
||||
#[tool(name = "get-user", description = "Get user info")]
|
||||
pub async fn get_user(&self, user_id: Parameters<String>) -> Result<Json<UserInfo>, String> {
|
||||
if user_id.0 == "123" {
|
||||
Ok(Json(UserInfo {
|
||||
name: "Alice".to_string(),
|
||||
age: 30,
|
||||
}))
|
||||
} else {
|
||||
Err("User not found".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_tool_with_output_schema() {
|
||||
let server = TestServer::new();
|
||||
let tools = server.tool_router.list_all();
|
||||
|
||||
// Find the calculate tool
|
||||
let calculate_tool = tools.iter().find(|t| t.name == "calculate").unwrap();
|
||||
|
||||
// Verify it has an output schema
|
||||
assert!(calculate_tool.output_schema.is_some());
|
||||
|
||||
let schema = calculate_tool.output_schema.as_ref().unwrap();
|
||||
|
||||
// Check that the schema contains expected fields
|
||||
let schema_str = serde_json::to_string(schema).unwrap();
|
||||
assert!(schema_str.contains("sum"));
|
||||
assert!(schema_str.contains("product"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_tool_without_output_schema() {
|
||||
let server = TestServer::new();
|
||||
let tools = server.tool_router.list_all();
|
||||
|
||||
// Find the get-greeting tool
|
||||
let greeting_tool = tools.iter().find(|t| t.name == "get-greeting").unwrap();
|
||||
|
||||
// Verify it doesn't have an output schema (returns String)
|
||||
assert!(greeting_tool.output_schema.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_structured_content_in_call_result() {
|
||||
// Test creating a CallToolResult with structured content
|
||||
let structured_data = json!({
|
||||
"sum": 7,
|
||||
"product": 12
|
||||
});
|
||||
|
||||
let result = CallToolResult::structured(structured_data.clone());
|
||||
|
||||
assert!(result.content.is_none());
|
||||
assert!(result.structured_content.is_some());
|
||||
assert_eq!(result.structured_content.unwrap(), structured_data);
|
||||
assert_eq!(result.is_error, Some(false));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_structured_error_in_call_result() {
|
||||
// Test creating a CallToolResult with structured error
|
||||
let error_data = json!({
|
||||
"error_code": "NOT_FOUND",
|
||||
"message": "User not found"
|
||||
});
|
||||
|
||||
let result = CallToolResult::structured_error(error_data.clone());
|
||||
|
||||
assert!(result.content.is_none());
|
||||
assert!(result.structured_content.is_some());
|
||||
assert_eq!(result.structured_content.unwrap(), error_data);
|
||||
assert_eq!(result.is_error, Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_mutual_exclusivity_validation() {
|
||||
// Test that content and structured_content are mutually exclusive
|
||||
let content_result = CallToolResult::success(vec![Content::text("Hello")]);
|
||||
let structured_result = CallToolResult::structured(json!({"message": "Hello"}));
|
||||
|
||||
// Verify the validation
|
||||
assert!(content_result.validate().is_ok());
|
||||
assert!(structured_result.validate().is_ok());
|
||||
|
||||
// Try to create an invalid result with both fields
|
||||
let invalid_json = json!({
|
||||
"content": [{"type": "text", "text": "Hello"}],
|
||||
"structuredContent": {"message": "Hello"}
|
||||
});
|
||||
|
||||
// The deserialization itself should fail due to validation
|
||||
let deserialized: Result<CallToolResult, _> = serde_json::from_value(invalid_json);
|
||||
assert!(deserialized.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_structured_return_conversion() {
|
||||
// Test that Json<T> converts to CallToolResult with structured_content
|
||||
let calc_result = CalculationResult {
|
||||
sum: 7,
|
||||
product: 12,
|
||||
};
|
||||
|
||||
let structured = Json(calc_result);
|
||||
let result: Result<CallToolResult, rmcp::ErrorData> =
|
||||
rmcp::handler::server::tool::IntoCallToolResult::into_call_tool_result(structured);
|
||||
|
||||
assert!(result.is_ok());
|
||||
let call_result = result.unwrap();
|
||||
|
||||
assert!(call_result.content.is_none());
|
||||
assert!(call_result.structured_content.is_some());
|
||||
|
||||
let structured_value = call_result.structured_content.unwrap();
|
||||
assert_eq!(structured_value["sum"], 7);
|
||||
assert_eq!(structured_value["product"], 12);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_tool_serialization_with_output_schema() {
|
||||
let server = TestServer::new();
|
||||
let tools = server.tool_router.list_all();
|
||||
|
||||
let calculate_tool = tools.iter().find(|t| t.name == "calculate").unwrap();
|
||||
|
||||
// Serialize the tool
|
||||
let serialized = serde_json::to_value(calculate_tool).unwrap();
|
||||
|
||||
// Check that outputSchema is included
|
||||
assert!(serialized["outputSchema"].is_object());
|
||||
|
||||
// Deserialize back
|
||||
let deserialized: Tool = serde_json::from_value(serialized).unwrap();
|
||||
assert!(deserialized.output_schema.is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_output_schema_requires_structured_content() {
|
||||
// Test that tools with output_schema must use structured_content
|
||||
let server = TestServer::new();
|
||||
let tools = server.tool_router.list_all();
|
||||
|
||||
// The calculate tool should have output_schema
|
||||
let calculate_tool = tools.iter().find(|t| t.name == "calculate").unwrap();
|
||||
assert!(calculate_tool.output_schema.is_some());
|
||||
|
||||
// Directly call the tool and verify its result structure
|
||||
let params = rmcp::handler::server::tool::Parameters(CalculationRequest { a: 5, b: 3 });
|
||||
let result = server.calculate(params).await.unwrap();
|
||||
|
||||
// Convert the Json<CalculationResult> to CallToolResult
|
||||
let call_result: Result<CallToolResult, rmcp::ErrorData> =
|
||||
rmcp::handler::server::tool::IntoCallToolResult::into_call_tool_result(result);
|
||||
|
||||
assert!(call_result.is_ok());
|
||||
let call_result = call_result.unwrap();
|
||||
|
||||
// Verify it has structured_content and no content
|
||||
assert!(call_result.structured_content.is_some());
|
||||
assert!(call_result.content.is_none());
|
||||
}
|
||||
62
crates/rmcp/tests/test_tool_builder_methods.rs
Normal file
62
crates/rmcp/tests/test_tool_builder_methods.rs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
//cargo test --test test_tool_builder_methods --features "client server macros"
|
||||
use rmcp::model::{JsonObject, Tool};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||
pub struct InputData {
|
||||
pub name: String,
|
||||
pub age: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||
pub struct OutputData {
|
||||
pub greeting: String,
|
||||
pub is_adult: bool,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_output_schema() {
|
||||
let tool = Tool::new("test", "Test tool", JsonObject::new()).with_output_schema::<OutputData>();
|
||||
|
||||
assert!(tool.output_schema.is_some());
|
||||
|
||||
// Verify the schema contains expected fields
|
||||
let schema_str = serde_json::to_string(tool.output_schema.as_ref().unwrap()).unwrap();
|
||||
assert!(schema_str.contains("greeting"));
|
||||
assert!(schema_str.contains("is_adult"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_input_schema() {
|
||||
let tool = Tool::new("test", "Test tool", JsonObject::new()).with_input_schema::<InputData>();
|
||||
|
||||
// Verify the schema contains expected fields
|
||||
let schema_str = serde_json::to_string(&tool.input_schema).unwrap();
|
||||
assert!(schema_str.contains("name"));
|
||||
assert!(schema_str.contains("age"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chained_builder_methods() {
|
||||
let tool = Tool::new("test", "Test tool", JsonObject::new())
|
||||
.with_input_schema::<InputData>()
|
||||
.with_output_schema::<OutputData>()
|
||||
.annotate(rmcp::model::ToolAnnotations::new().read_only(true));
|
||||
|
||||
assert!(tool.output_schema.is_some());
|
||||
assert!(tool.annotations.is_some());
|
||||
assert_eq!(
|
||||
tool.annotations.as_ref().unwrap().read_only_hint,
|
||||
Some(true)
|
||||
);
|
||||
|
||||
// Verify both schemas are set correctly
|
||||
let input_schema_str = serde_json::to_string(&tool.input_schema).unwrap();
|
||||
assert!(input_schema_str.contains("name"));
|
||||
assert!(input_schema_str.contains("age"));
|
||||
|
||||
let output_schema_str = serde_json::to_string(tool.output_schema.as_ref().unwrap()).unwrap();
|
||||
assert!(output_schema_str.contains("greeting"));
|
||||
assert!(output_schema_str.contains("is_adult"));
|
||||
}
|
||||
|
|
@ -301,7 +301,8 @@ async fn test_optional_i64_field_with_null_input() -> anyhow::Result<()> {
|
|||
|
||||
let result_text = result
|
||||
.content
|
||||
.first()
|
||||
.as_ref()
|
||||
.and_then(|contents| contents.first())
|
||||
.and_then(|content| content.raw.as_text())
|
||||
.map(|text| text.text.as_str())
|
||||
.expect("Expected text content");
|
||||
|
|
@ -329,7 +330,8 @@ async fn test_optional_i64_field_with_null_input() -> anyhow::Result<()> {
|
|||
|
||||
let some_result_text = some_result
|
||||
.content
|
||||
.first()
|
||||
.as_ref()
|
||||
.and_then(|contents| contents.first())
|
||||
.and_then(|content| content.raw.as_text())
|
||||
.map(|text| text.text.as_str())
|
||||
.expect("Expected text content");
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ publish = false
|
|||
[dependencies]
|
||||
rmcp = { workspace = true, features = [
|
||||
"server",
|
||||
"macros",
|
||||
"transport-sse-server",
|
||||
"transport-io",
|
||||
"transport-streamable-http-server",
|
||||
|
|
@ -33,7 +34,7 @@ tracing-subscriber = { version = "0.3", features = [
|
|||
futures = "0.3"
|
||||
rand = { version = "0.9", features = ["std"] }
|
||||
axum = { version = "0.8", features = ["macros"] }
|
||||
schemars = { version = "1.0", optional = true }
|
||||
schemars = { version = "1.0" }
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
chrono = "0.4"
|
||||
uuid = { version = "1.6", features = ["v4", "serde"] }
|
||||
|
|
@ -82,3 +83,7 @@ path = "src/counter_hyper_streamable_http.rs"
|
|||
[[example]]
|
||||
name = "servers_sampling_stdio"
|
||||
path = "src/sampling_stdio.rs"
|
||||
|
||||
[[example]]
|
||||
name = "servers_structured_output"
|
||||
path = "src/structured_output.rs"
|
||||
|
|
|
|||
|
|
@ -119,6 +119,7 @@ impl ServerHandler for SamplingDemoServer {
|
|||
}))
|
||||
.unwrap(),
|
||||
),
|
||||
output_schema: None,
|
||||
annotations: None,
|
||||
}],
|
||||
next_cursor: None,
|
||||
|
|
|
|||
158
examples/servers/src/structured_output.rs
Normal file
158
examples/servers/src/structured_output.rs
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
//! Example demonstrating structured output from tools
|
||||
//!
|
||||
//! This example shows how to:
|
||||
//! - Return structured data from tools using the Json<T> wrapper
|
||||
//! - Automatically generate output schemas from Rust types
|
||||
//! - Handle both structured and unstructured tool outputs
|
||||
|
||||
use rmcp::{
|
||||
Json, ServiceExt,
|
||||
handler::server::{router::tool::ToolRouter, tool::Parameters},
|
||||
tool, tool_handler, tool_router,
|
||||
transport::stdio,
|
||||
};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct WeatherRequest {
|
||||
pub city: String,
|
||||
pub units: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct WeatherResponse {
|
||||
pub temperature: f64,
|
||||
pub description: String,
|
||||
pub humidity: u8,
|
||||
pub wind_speed: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CalculationRequest {
|
||||
pub numbers: Vec<i32>,
|
||||
pub operation: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CalculationResult {
|
||||
pub result: f64,
|
||||
pub operation: String,
|
||||
pub input_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct StructuredOutputServer {
|
||||
tool_router: ToolRouter<Self>,
|
||||
}
|
||||
|
||||
#[tool_handler(router = self.tool_router)]
|
||||
impl rmcp::ServerHandler for StructuredOutputServer {}
|
||||
|
||||
impl Default for StructuredOutputServer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[tool_router(router = tool_router)]
|
||||
impl StructuredOutputServer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tool_router: Self::tool_router(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get weather information for a city (returns structured data)
|
||||
#[tool(name = "get_weather", description = "Get current weather for a city")]
|
||||
pub async fn get_weather(
|
||||
&self,
|
||||
params: Parameters<WeatherRequest>,
|
||||
) -> Result<Json<WeatherResponse>, String> {
|
||||
// Simulate weather API call
|
||||
let weather = WeatherResponse {
|
||||
temperature: match params.0.units.as_deref() {
|
||||
Some("fahrenheit") => 72.5,
|
||||
_ => 22.5, // celsius by default
|
||||
},
|
||||
description: "Partly cloudy".to_string(),
|
||||
humidity: 65,
|
||||
wind_speed: 12.5,
|
||||
};
|
||||
|
||||
Ok(Json(weather))
|
||||
}
|
||||
|
||||
/// Perform calculations on a list of numbers (returns structured data)
|
||||
#[tool(name = "calculate", description = "Perform calculations on numbers")]
|
||||
pub async fn calculate(
|
||||
&self,
|
||||
params: Parameters<CalculationRequest>,
|
||||
) -> Result<Json<CalculationResult>, String> {
|
||||
let numbers = ¶ms.0.numbers;
|
||||
if numbers.is_empty() {
|
||||
return Err("No numbers provided".to_string());
|
||||
}
|
||||
|
||||
let result = match params.0.operation.as_str() {
|
||||
"sum" => numbers.iter().sum::<i32>() as f64,
|
||||
"average" => numbers.iter().sum::<i32>() as f64 / numbers.len() as f64,
|
||||
"product" => numbers.iter().product::<i32>() as f64,
|
||||
_ => return Err(format!("Unknown operation: {}", params.0.operation)),
|
||||
};
|
||||
|
||||
Ok(Json(CalculationResult {
|
||||
result,
|
||||
operation: params.0.operation,
|
||||
input_count: numbers.len(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Get server info (returns unstructured text)
|
||||
#[tool(name = "get_info", description = "Get server information")]
|
||||
pub async fn get_info(&self) -> String {
|
||||
"Structured Output Example Server v1.0".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
eprintln!("Starting structured output example server...");
|
||||
eprintln!();
|
||||
eprintln!("This server demonstrates:");
|
||||
eprintln!("- Tools that return structured JSON data");
|
||||
eprintln!("- Automatic output schema generation");
|
||||
eprintln!("- Mixed structured and unstructured outputs");
|
||||
eprintln!();
|
||||
eprintln!("Tools available:");
|
||||
eprintln!("- get_weather: Returns structured weather data");
|
||||
eprintln!("- calculate: Returns structured calculation results");
|
||||
eprintln!("- get_info: Returns plain text");
|
||||
eprintln!();
|
||||
|
||||
let server = StructuredOutputServer::new();
|
||||
|
||||
// Print the tools with their schemas for demonstration
|
||||
eprintln!("Tool schemas:");
|
||||
for tool in server.tool_router.list_all() {
|
||||
eprintln!("\n{}: {}", tool.name, tool.description.unwrap_or_default());
|
||||
if let Some(output_schema) = &tool.output_schema {
|
||||
eprintln!(
|
||||
" Output schema: {}",
|
||||
serde_json::to_string_pretty(output_schema).unwrap()
|
||||
);
|
||||
} else {
|
||||
eprintln!(" Output: Unstructured text");
|
||||
}
|
||||
}
|
||||
eprintln!();
|
||||
|
||||
// Start the server
|
||||
eprintln!("Starting server. Connect with an MCP client to test the tools.");
|
||||
eprintln!("Press Ctrl+C to stop.");
|
||||
|
||||
let service = server.serve(stdio()).await?;
|
||||
service.waiting().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -85,8 +85,8 @@ impl ChatSession {
|
|||
if result.is_error.is_some_and(|b| b) {
|
||||
self.messages
|
||||
.push(Message::user("tool call failed, mcp call error"));
|
||||
} else {
|
||||
result.content.iter().for_each(|content| {
|
||||
} else if let Some(contents) = &result.content {
|
||||
contents.iter().for_each(|content| {
|
||||
if let Some(content_text) = content.as_text() {
|
||||
let json_result = serde_json::from_str::<serde_json::Value>(
|
||||
&content_text.text,
|
||||
|
|
|
|||
Loading…
Reference in a new issue