Skip to main content

mcpkit_rs/handler/server/wrapper/
json.rs

1use std::borrow::Cow;
2
3use schemars::JsonSchema;
4use serde::Serialize;
5
6use crate::{
7    handler::server::tool::IntoCallToolResult,
8    model::{CallToolResult, IntoContents},
9};
10
11/// Json wrapper for structured output
12///
13/// When used with tools, this wrapper indicates that the value should be
14/// serialized as structured JSON content with an associated schema.
15/// The framework will place the JSON in the `structured_content` field
16/// of the tool result rather than the regular `content` field.
17pub struct Json<T>(pub T);
18
19// Implement JsonSchema for Json<T> to delegate to T's schema
20impl<T: JsonSchema> JsonSchema for Json<T> {
21    fn schema_name() -> Cow<'static, str> {
22        T::schema_name()
23    }
24
25    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
26        T::json_schema(generator)
27    }
28}
29
30// Implementation for Json<T> to create structured content
31impl<T: Serialize + JsonSchema + 'static> IntoCallToolResult for Json<T> {
32    fn into_call_tool_result(self) -> Result<CallToolResult, crate::ErrorData> {
33        let value = serde_json::to_value(self.0).map_err(|e| {
34            crate::ErrorData::internal_error(
35                format!("Failed to serialize structured content: {}", e),
36                None,
37            )
38        })?;
39
40        Ok(CallToolResult::structured(value))
41    }
42}
43
44// Implementation for Result<Json<T>, E>
45impl<T: Serialize + JsonSchema + 'static, E: IntoContents> IntoCallToolResult
46    for Result<Json<T>, E>
47{
48    fn into_call_tool_result(self) -> Result<CallToolResult, crate::ErrorData> {
49        match self {
50            Ok(value) => value.into_call_tool_result(),
51            Err(error) => Ok(CallToolResult::error(error.into_contents())),
52        }
53    }
54}