mcp_server_rs/router/
service.rs

1use std::{
2    pin::Pin,
3    task::{Context, Poll},
4};
5
6use mcp_core_rs::protocol::{
7    constants::INVALID_REQUEST,
8    error::ErrorData,
9    message::{JsonRpcRequest, JsonRpcResponse},
10};
11use mcp_error_rs::BoxError;
12use tower_service::Service;
13
14use crate::router::traits::Router;
15
16pub struct RouterService<T>(pub T);
17
18impl<T> Service<JsonRpcRequest> for RouterService<T>
19where
20    T: Router + Clone + Send + Sync + 'static,
21{
22    type Response = JsonRpcResponse;
23    type Error = BoxError;
24    type Future =
25        Pin<Box<dyn Future<Output = core::result::Result<Self::Response, Self::Error>> + Send>>;
26
27    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<core::result::Result<(), Self::Error>> {
28        Poll::Ready(Ok(()))
29    }
30
31    fn call(&mut self, req: JsonRpcRequest) -> Self::Future {
32        let this = self.0.clone();
33
34        Box::pin(async move {
35            let result = match req.method.as_str() {
36                "initialize" => this.handle_initialize(req).await,
37                "tools/list" => this.handle_tools_list(req).await,
38                "tools/call" => this.handle_tools_call(req).await,
39                "resources/list" => this.handle_resources_list(req).await,
40                "resources/read" => this.handle_resources_read(req).await,
41                "prompts/list" => this.handle_prompts_list(req).await,
42                "prompts/get" => this.handle_prompts_get(req).await,
43                _ => {
44                    let mut response = this.create_response(req.id);
45                    let error_msg = format!("Method '{}' not found", req.method);
46                    let error_data = ErrorData {
47                        code: INVALID_REQUEST,
48                        message: error_msg,
49                        data: None,
50                    };
51                    response.error = Some(error_data);
52                    Ok(response)
53                }
54            };
55
56            result.map_err(BoxError::from)
57        })
58    }
59}