-
Notifications
You must be signed in to change notification settings - Fork 572
Expand file tree
/
Copy pathjson.rs
More file actions
46 lines (39 loc) · 1.57 KB
/
Copy pathjson.rs
File metadata and controls
46 lines (39 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use std::borrow::Cow;
use schemars::JsonSchema;
use serde::Serialize;
use crate::{
handler::server::tool::IntoCallToolResult,
model::{CallToolResponse, CallToolResult},
};
/// Json wrapper for structured output
///
/// 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, and also mirror it into the regular `content` field
/// as serialized text for clients that do not read `structured_content`.
/// To skip that text mirror, use [`StructuredOnly`](crate::StructuredOnly)
/// instead.
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct Json<T>(pub T);
// 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)
}
}
// Implementation for Json<T> to create structured content
impl<T: Serialize + JsonSchema + 'static> IntoCallToolResult for Json<T> {
fn into_call_tool_result(self) -> Result<CallToolResponse, 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).into())
}
}