rust-sdk/crates/rmcp/tests/test_tool_routers.rs
4t145 1f7f4d3055
refactor: refactor tool macros and router implementation (#261)
* refactor: refactor tool macros and router implementation

- Updated the `#[tool(tool_box)]` macro to `#[tool_router]` across various modules for consistency.
- Enhanced the `Calculator`, `Counter`, and `GenericService` structs to utilize `ToolRouter` for handling tool calls.
- Introduced `Parameters` struct for better parameter handling in tool functions.
- Added new methods for listing tools and calling tools in server handlers.
- Improved test cases to reflect changes in tool routing and parameter handling.
- Updated documentation and examples to align with the new router structure.

* fix: fix fmt and build error

* fix: fix test failure

* docs: documents for macros, fix ci

* fix: fix ci

* fix: fix wrongly replaced documents

* fix: remove useless file

* fix: change the parameter format for tool_router

* fix: update extract_doc_line to handle existing documentation and clean up unused code in server handler

* doc: update document for macro and examples

* doc: update readme and add contribute guide

* fix: fix type
2025-06-24 04:01:22 +08:00

74 lines
1.9 KiB
Rust

use std::collections::HashMap;
use futures::future::BoxFuture;
use rmcp::{
ServerHandler,
handler::server::{
router::tool::ToolRouter,
tool::{CallToolHandler, Parameters},
},
};
#[derive(Debug, Default)]
pub struct TestHandler<T: 'static = ()> {
pub _marker: std::marker::PhantomData<fn(*const T)>,
}
impl<T: 'static> ServerHandler for TestHandler<T> {}
#[derive(Debug, schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
pub struct Request {
pub fields: HashMap<String, String>,
}
#[derive(Debug, schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
pub struct Sum {
pub a: i32,
pub b: i32,
}
#[rmcp::tool_router(router = test_router_1)]
impl<T> TestHandler<T> {
#[rmcp::tool]
async fn async_method(&self, Parameters(Request { fields }): Parameters<Request>) {
drop(fields)
}
}
#[rmcp::tool_router(router = test_router_2)]
impl<T> TestHandler<T> {
#[rmcp::tool]
fn sync_method(&self, Parameters(Request { fields }): Parameters<Request>) {
drop(fields)
}
}
#[rmcp::tool]
async fn async_function<T>(
_callee: &TestHandler<T>,
Parameters(Request { fields }): Parameters<Request>,
) {
drop(fields)
}
#[rmcp::tool]
fn async_function2<T>(_callee: &TestHandler<T>) -> BoxFuture<'_, ()> {
Box::pin(async move {})
}
#[test]
fn test_tool_router() {
let test_tool_router: ToolRouter<TestHandler<()>> = ToolRouter::<TestHandler<()>>::new()
.with_route((async_function_tool_attr(), async_function))
.with_route((async_function2_tool_attr(), async_function2))
+ TestHandler::<()>::test_router_1()
+ TestHandler::<()>::test_router_2();
let tools = test_tool_router.list_all();
assert_eq!(tools.len(), 4);
assert_handler(TestHandler::<()>::async_method);
}
fn assert_handler<S, H, A>(_handler: H)
where
H: CallToolHandler<S, A>,
{
}