Skip to content

Commit 2c0cafd

Browse files
authored
feat(tool): allow tool call return a serializable value in json format (#75) (#78)
1 parent 923e87a commit 2c0cafd

File tree

4 files changed

+34
-3
lines changed

4 files changed

+34
-3
lines changed

crates/rmcp/src/handler/server.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::{
66

77
mod resource;
88
pub mod tool;
9-
9+
pub mod wrapper;
1010
impl<H: ServerHandler> Service<RoleServer> for H {
1111
async fn handle_request(
1212
&self,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
mod json;
2+
pub use json::*;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
use serde::Serialize;
2+
3+
use crate::model::IntoContents;
4+
5+
/// Json wrapper
6+
///
7+
/// This is used to tell the SDK to serialize the inner value into json
8+
pub struct Json<T>(pub T);
9+
10+
impl<T> IntoContents for Json<T>
11+
where
12+
T: Serialize,
13+
{
14+
fn into_contents(self) -> Vec<crate::model::Content> {
15+
let result = crate::model::Content::json(self.0);
16+
debug_assert!(
17+
result.is_ok(),
18+
"Json wrapped content should be able to serialized into json"
19+
);
20+
match result {
21+
Ok(content) => vec![content],
22+
Err(e) => {
23+
tracing::error!("failed to convert json content: {e}");
24+
vec![]
25+
}
26+
}
27+
}
28+
}

examples/servers/src/common/calculator.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use rmcp::{
22
ServerHandler,
3+
handler::server::wrapper::Json,
34
model::{ServerCapabilities, ServerInfo},
45
schemars, tool,
56
};
@@ -28,8 +29,8 @@ impl Calculator {
2829
#[tool(param)]
2930
#[schemars(description = "the left hand side number")]
3031
b: i32,
31-
) -> String {
32-
(a - b).to_string()
32+
) -> Json<i32> {
33+
Json(a - b)
3334
}
3435
}
3536

0 commit comments

Comments
 (0)