@@ -15,7 +15,7 @@ pub use extension::*;
1515pub use meta:: * ;
1616pub use prompt:: * ;
1717pub use resource:: * ;
18- use serde:: { Deserialize , Serialize } ;
18+ use serde:: { Deserialize , Serialize , de :: DeserializeOwned } ;
1919use serde_json:: Value ;
2020pub use tool:: * ;
2121
@@ -1260,12 +1260,32 @@ impl CallToolResult {
12601260 }
12611261 }
12621262
1263- /// Validate that content or structured content is provided
1264- pub fn validate ( & self ) -> Result < ( ) , & ' static str > {
1265- match ( & self . content , & self . structured_content ) {
1266- ( None , None ) => Err ( "either content or structured_content must be provided" ) ,
1267- _ => Ok ( ( ) ) ,
1263+ /// Convert the `structured_content` part of response into a certain type.
1264+ ///
1265+ /// # About json schema validation
1266+ /// Since rust is a strong type language, we don't need to do json schema validation here.
1267+ ///
1268+ /// But if you do have to validate the response data, you can use [`jsonschema`](https://crates.io/crates/jsonschema) crate.
1269+ pub fn into_typed < T > ( self ) -> Result < T , serde_json:: Error >
1270+ where
1271+ T : DeserializeOwned ,
1272+ {
1273+ let raw_text = match ( self . structured_content , & self . content ) {
1274+ ( Some ( value) , _) => return serde_json:: from_value ( value) ,
1275+ ( None , Some ( contents) ) => {
1276+ if let Some ( text) = contents. first ( ) . and_then ( |c| c. as_text ( ) ) {
1277+ let text = & text. text ;
1278+ Some ( text)
1279+ } else {
1280+ None
1281+ }
1282+ }
1283+ ( None , None ) => None ,
1284+ } ;
1285+ if let Some ( text) = raw_text {
1286+ return serde_json:: from_str ( text) ;
12681287 }
1288+ serde_json:: from_value ( serde_json:: Value :: Null )
12691289 }
12701290}
12711291
@@ -1294,7 +1314,11 @@ impl<'de> Deserialize<'de> for CallToolResult {
12941314 } ;
12951315
12961316 // Validate mutual exclusivity
1297- result. validate ( ) . map_err ( serde:: de:: Error :: custom) ?;
1317+ if result. content . is_none ( ) && result. structured_content . is_none ( ) {
1318+ return Err ( serde:: de:: Error :: custom (
1319+ "CallToolResult must have either content or structured_content" ,
1320+ ) ) ;
1321+ }
12981322
12991323 Ok ( result)
13001324 }
0 commit comments