feat(tool): allow tool call return a serializable value in json format (#75) (#78)

This commit is contained in:
4t145 2025-04-01 15:53:01 +08:00 committed by GitHub
parent 923e87af4d
commit 2c0cafdde3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 34 additions and 3 deletions

View file

@ -6,7 +6,7 @@ use crate::{
mod resource;
pub mod tool;
pub mod wrapper;
impl<H: ServerHandler> Service<RoleServer> for H {
async fn handle_request(
&self,

View file

@ -0,0 +1,2 @@
mod json;
pub use json::*;

View file

@ -0,0 +1,28 @@
use serde::Serialize;
use crate::model::IntoContents;
/// Json wrapper
///
/// This is used to tell the SDK to serialize the inner value into json
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![]
}
}
}
}

View file

@ -1,5 +1,6 @@
use rmcp::{
ServerHandler,
handler::server::wrapper::Json,
model::{ServerCapabilities, ServerInfo},
schemars, tool,
};
@ -28,8 +29,8 @@ impl Calculator {
#[tool(param)]
#[schemars(description = "the left hand side number")]
b: i32,
) -> String {
(a - b).to_string()
) -> Json<i32> {
Json(a - b)
}
}