repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_handlers/mcp_client_handler.rs
crates/rust-mcp-sdk/src/mcp_handlers/mcp_client_handler.rs
use crate::mcp_client::client_runtime::ClientInternalHandler; use crate::mcp_traits::McpClient; use crate::schema::schema_utils::{CustomNotification, CustomRequest}; use crate::schema::{ CancelTaskParams, CancelTaskRequest, CancelTaskResult, CancelledNotificationParams, CreateMessageRequest, CreateMessageRequestParams, CreateMessageResult, ElicitCompleteParams, ElicitRequest, ElicitRequestParams, ElicitResult, GenericResult, GetTaskParams, GetTaskPayloadParams, GetTaskPayloadRequest, GetTaskRequest, GetTaskResult, ListRootsRequest, ListRootsResult, ListTasksRequest, ListTasksResult, LoggingMessageNotificationParams, NotificationParams, PaginatedRequestParams, ProgressNotificationParams, RequestParams, ResourceUpdatedNotificationParams, Result, RpcError, TaskStatusNotificationParams, }; use crate::task_store::ClientTaskCreator; use crate::{McpClientHandler, ToMcpClientHandler}; use async_trait::async_trait; use rust_mcp_schema::CreateTaskResult; /// The `ClientHandler` trait defines how a client handles Model Context Protocol (MCP) operations. /// It includes default implementations for handling requests , notifications and errors and must be /// extended or overridden by developers to customize client behavior. #[allow(unused)] #[async_trait] pub trait ClientHandler: Send + Sync + 'static { //**********************// //** Request Handlers **// //**********************// /// Handles a ping, to check that the other party is still alive. /// The receiver must promptly respond, or else may be disconnected. async fn handle_ping_request( &self, params: Option<RequestParams>, runtime: &dyn McpClient, ) -> std::result::Result<Result, RpcError> { Ok(Result::default()) } /// Handles a request from the server to sample an LLM via the client. /// The client has full discretion over which model to select. /// The client should also inform the user before beginning sampling, /// to allow them to inspect the request (human in the loop) and decide whether to approve it. async fn handle_create_message_request( &self, params: CreateMessageRequestParams, runtime: &dyn McpClient, ) -> std::result::Result<CreateMessageResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", CreateMessageRequest::method_value() ))) } /// Handles requests to call a task-augmented sampling (sampling/createMessage). /// you need to returns a CreateTaskResult containing task data. /// The actual operation result becomes available later /// through tasks/result after the task completes. async fn handle_task_augmented_create_message( &self, params: CreateMessageRequestParams, runtime: &dyn McpClient, ) -> std::result::Result<CreateTaskResult, RpcError> { if !runtime.capabilities().can_accept_sampling_task() { return Err(RpcError::invalid_request() .with_message("Task-augmented sampling is not supported.".to_string())); } Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for task-augmented '{}'.", CreateMessageRequest::method_value() ))) } /// Handles a request from the server to request a list of root URIs from the client. Roots allow /// servers to ask for specific directories or files to operate on. /// This request is typically used when the server needs to understand the file system /// structure or access specific locations that the client has permission to read from. async fn handle_list_roots_request( &self, params: Option<RequestParams>, runtime: &dyn McpClient, ) -> std::result::Result<ListRootsResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", ListRootsRequest::method_value(), ))) } ///Handles a request from the server to elicit additional information from the user via the client. async fn handle_elicit_request( &self, params: ElicitRequestParams, runtime: &dyn McpClient, ) -> std::result::Result<ElicitResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", ElicitRequest::method_value() ))) } /// Handles task-augmented elicitation, to elicit additional information from the user via the client. /// you need to returns a CreateTaskResult containing task data. /// The actual operation result becomes available later /// through tasks/result after the task completes. async fn handle_task_augmented_elicit_request( &self, task_creator: ClientTaskCreator, params: ElicitRequestParams, runtime: &dyn McpClient, ) -> std::result::Result<CreateTaskResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", ElicitRequest::method_value() ))) } /// Handles a request to retrieve the state of a task. async fn handle_get_task_request( &self, params: GetTaskParams, runtime: &dyn McpClient, ) -> std::result::Result<GetTaskResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", GetTaskRequest::method_value() ))) } /// Handles a request to retrieve the result of a completed task. async fn handle_get_task_payload_request( &self, params: GetTaskPayloadParams, runtime: &dyn McpClient, ) -> std::result::Result<GenericResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", GetTaskPayloadRequest::method_value() ))) } /// Handles a request to cancel a task. async fn handle_cancel_task_request( &self, params: CancelTaskParams, runtime: &dyn McpClient, ) -> std::result::Result<CancelTaskResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", CancelTaskRequest::method_value() ))) } /// Handles a request to retrieve a list of tasks. async fn handle_list_tasks_request( &self, params: Option<PaginatedRequestParams>, runtime: &dyn McpClient, ) -> std::result::Result<ListTasksResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", ListTasksRequest::method_value() ))) } /// Handle a custom request async fn handle_custom_request( &self, request: CustomRequest, runtime: &dyn McpClient, ) -> std::result::Result<ListRootsResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler for custom request : \"{}\"", request.method ))) } //***************************// //** Notification Handlers **// //***************************// /// Handles a notification that indicates that it is cancelling a previously-issued request. /// it is always possible that this notification MAY arrive after the request has already finished. /// This notification indicates that the result will be unused, so any associated processing SHOULD cease. async fn handle_cancelled_notification( &self, params: CancelledNotificationParams, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles an out-of-band notification used to inform the receiver of a progress update for a long-running request. async fn handle_progress_notification( &self, params: ProgressNotificationParams, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles a notification from the server to the client, informing it that the list of resources it can read from has changed. async fn handle_resource_list_changed_notification( &self, params: Option<NotificationParams>, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } /// handles a notification from the server to the client, informing it that a resource has changed and may need to be read again. async fn handle_resource_updated_notification( &self, params: ResourceUpdatedNotificationParams, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } ///Handles a notification from the server to the client, informing it that the list of prompts it offers has changed. async fn handle_prompt_list_changed_notification( &self, params: Option<NotificationParams>, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles a notification from the server to the client, informing it that the list of tools it offers has changed. async fn handle_tool_list_changed_notification( &self, params: Option<NotificationParams>, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles notification of a log message passed from server to client. /// If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. async fn handle_logging_message_notification( &self, params: LoggingMessageNotificationParams, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles a notification from the receiver to the requestor, informing them that a task's status has changed. /// Receivers are not required to send these notifications. async fn handle_task_status_notification( &self, params: TaskStatusNotificationParams, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles a notification from the server to the client, informing it of a completion of a out-of-band elicitation request. async fn handle_elicitation_complete_notification( &self, params: ElicitCompleteParams, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles a custom notification message async fn handle_custom_notification( &self, notification: CustomNotification, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } //********************// //** Error Handlers **// //********************// async fn handle_error( &self, error: &RpcError, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Ok(()) } async fn handle_process_error( &self, error_message: String, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { if !runtime.is_shut_down().await { tracing::error!("Process error: {error_message}"); } Ok(()) } } impl<T: ClientHandler + 'static> ToMcpClientHandler for T { fn to_mcp_client_handler(self) -> Box<dyn McpClientHandler + 'static> { Box::new(ClientInternalHandler::new(Box::new(self))) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_handlers/mcp_server_handler_core.rs
crates/rust-mcp-sdk/src/mcp_handlers/mcp_server_handler_core.rs
use crate::mcp_server::server_runtime_core::RuntimeCoreInternalHandler; use crate::mcp_traits::McpServer; use crate::mcp_traits::{McpServerHandler, ToMcpServerHandlerCore}; use crate::schema::*; use async_trait::async_trait; use std::sync::Arc; /// Defines the `ServerHandlerCore` trait for handling Model Context Protocol (MCP) server operations. /// Unlike `ServerHandler`, this trait offers no default implementations, providing full control over MCP message handling /// while ensures type-safe processing of the messages through three distinct handlers for requests, notifications, and errors. #[async_trait] pub trait ServerHandlerCore: Send + Sync + 'static { /// Invoked when the server finishes initialization and receives an `initialized_notification` from the client. /// /// The `runtime` parameter provides access to the server's runtime environment, allowing /// interaction with the server's capabilities. /// The default implementation does nothing. async fn on_initialized(&self, _runtime: Arc<dyn McpServer>) {} /// Asynchronously handles an incoming request from the client. /// /// # Parameters /// - `request` – The request data received from the MCP client. /// /// # Returns /// A `ResultFromServer`, which represents the server's response to the client's request. async fn handle_request( &self, request: RequestFromClient, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ResultFromServer, RpcError>; /// Asynchronously handles an incoming notification from the client. /// /// # Parameters /// - `notification` – The notification data received from the MCP client. async fn handle_notification( &self, notification: NotificationFromClient, runtime: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError>; /// Asynchronously handles an error received from the client. /// /// # Parameters /// - `error` – The error data received from the MCP client. async fn handle_error( &self, error: &RpcError, runtime: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError>; } impl<T: ServerHandlerCore + 'static> ToMcpServerHandlerCore for T { fn to_mcp_server_handler(self) -> Arc<dyn McpServerHandler + 'static> { Arc::new(RuntimeCoreInternalHandler::new(Box::new(self))) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_handlers/mcp_client_handler_core.rs
crates/rust-mcp-sdk/src/mcp_handlers/mcp_client_handler_core.rs
use crate::{ mcp_client::client_runtime_core::ClientCoreInternalHandler, schema::*, McpClientHandler, ToMcpClientHandlerCore, }; use async_trait::async_trait; use crate::mcp_traits::McpClient; /// Defines the `ClientHandlerCore` trait for handling Model Context Protocol (MCP) client operations. /// Unlike `ClientHandler`, this trait offers no default implementations, providing full control over MCP message handling /// while ensures type-safe processing of the messages through three distinct handlers for requests, notifications, and errors. #[async_trait] pub trait ClientHandlerCore: Send + Sync + 'static { /// Asynchronously handles an incoming request from the server. /// /// # Parameters /// - `request` – The request data received from the MCP server. /// /// # Returns /// A `ResultFromClient`, which represents the client's response to the server's request. async fn handle_request( &self, request: ServerJsonrpcRequest, runtime: &dyn McpClient, ) -> std::result::Result<ResultFromClient, RpcError>; /// Asynchronously handles an incoming notification from the server. /// /// # Parameters /// - `notification` – The notification data received from the MCP server. async fn handle_notification( &self, notification: NotificationFromServer, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError>; /// Asynchronously handles an error received from the server. /// /// # Parameters /// - `error` – The error data received from the MCP server. async fn handle_error( &self, error: &RpcError, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError>; async fn handle_process_error( &self, error_message: String, runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { if !runtime.is_shut_down().await { tracing::error!("Process error: {error_message}"); } Ok(()) } } impl<T: ClientHandlerCore + 'static> ToMcpClientHandlerCore for T { fn to_mcp_client_handler(self) -> Box<dyn McpClientHandler + 'static> { Box::new(ClientCoreInternalHandler::new(Box::new(self))) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_handlers/mcp_server_handler.rs
crates/rust-mcp-sdk/src/mcp_handlers/mcp_server_handler.rs
use crate::{ mcp_server::server_runtime::ServerRuntimeInternalHandler, mcp_traits::{McpServerHandler, ToMcpServerHandler}, schema::{ schema_utils::{CallToolError, CustomNotification, CustomRequest}, *, }, task_store::ServerTaskCreator, }; use async_trait::async_trait; use std::sync::Arc; use crate::{mcp_traits::McpServer, utils::enforce_compatible_protocol_version}; /// The `ServerHandler` trait defines how a server handles Model Context Protocol (MCP) operations. /// It provides default implementations for request , notification and error handlers, and must be extended or /// overridden by developers to customize server behavior. #[allow(unused)] #[async_trait] pub trait ServerHandler: Send + Sync + 'static { /// Invoked when the server finishes initialization and receives an `initialized_notification` from the client. /// /// The `runtime` parameter provides access to the server's runtime environment, allowing /// interaction with the server's capabilities. /// The default implementation does nothing. async fn on_initialized(&self, runtime: Arc<dyn McpServer>) {} /// Handles the InitializeRequest from a client. /// /// # Arguments /// * `initialize_request` - The initialization request containing client parameters /// * `runtime` - Reference to the MCP server runtime /// /// # Returns /// Returns the server info as InitializeResult on success or a JSON-RPC error on failure /// Do not override this unless the standard initialization process doesn't work for you or you need to modify it. async fn handle_initialize_request( &self, params: InitializeRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<InitializeResult, RpcError> { let mut server_info = runtime.server_info().to_owned(); // Provide compatibility for clients using older MCP protocol versions. if let Some(updated_protocol_version) = enforce_compatible_protocol_version( &params.protocol_version, &server_info.protocol_version, ) .map_err(|err| { tracing::error!( "Incompatible protocol version : client: {} server: {}", &params.protocol_version, &server_info.protocol_version ); RpcError::internal_error().with_message(err.to_string()) })? { server_info.protocol_version = updated_protocol_version; } runtime .set_client_details(params) .await .map_err(|err| RpcError::internal_error().with_message(format!("{err}")))?; Ok(server_info) } /// Handles ping requests from clients. /// /// # Returns /// By default, it returns an empty result structure /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_ping_request( &self, _params: Option<RequestParams>, _runtime: Arc<dyn McpServer>, ) -> std::result::Result<Result, RpcError> { Ok(Result::default()) } /// Handles requests to list available resources. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_list_resources_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListResourcesResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &ListResourcesRequest::method_value(), ))) } /// Handles requests to list resource templates. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_list_resource_templates_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListResourceTemplatesResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &ListResourceTemplatesRequest::method_value(), ))) } /// Handles requests to read a specific resource. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_read_resource_request( &self, params: ReadResourceRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ReadResourceResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &ReadResourceRequest::method_value(), ))) } /// Handles subscription requests from clients. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_subscribe_request( &self, params: SubscribeRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<Result, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &SubscribeRequest::method_value(), ))) } /// Handles unsubscribe requests from clients. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_unsubscribe_request( &self, params: UnsubscribeRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<Result, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &UnsubscribeRequest::method_value(), ))) } /// Handles requests to list available prompts. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_list_prompts_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListPromptsResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &ListPromptsRequest::method_value(), ))) } /// Handles requests to get a specific prompt. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_get_prompt_request( &self, params: GetPromptRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<GetPromptResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &GetPromptRequest::method_value(), ))) } /// Handles requests to list available tools. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_list_tools_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListToolsResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &ListToolsRequest::method_value(), ))) } /// Handles requests to call a task-augmented tool. /// you need to returns a CreateTaskResult containing task data. /// The actual operation result becomes available later /// through tasks/result after the task completes. async fn handle_task_augmented_tool_call( &self, params: CallToolRequestParams, task_creator: ServerTaskCreator, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CreateTaskResult, CallToolError> { if !runtime.capabilities().can_run_task_augmented_tools() { return Err(CallToolError::unsupported_task_augmented_tool_call()); } Err(CallToolError::from_message( "No handler is implemented for 'task augmented tool call'.", )) } /// Handles requests to call a specific tool. /// /// Default implementation returns an unknown tool error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_call_tool_request( &self, params: CallToolRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CallToolResult, CallToolError> { Ok(CallToolError::unknown_tool(format!("Unknown tool: {}", params.name)).into()) } /// Handles requests to enable or adjust logging level. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_set_level_request( &self, params: SetLevelRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<Result, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &SetLevelRequest::method_value(), ))) } /// Handles completion requests from clients. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_complete_request( &self, params: CompleteRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CompleteResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &CompleteRequest::method_value(), ))) } ///Handles a request to retrieve the state of a task. async fn handle_get_task_request( &self, params: GetTaskParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CompleteResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &GetTaskRequest::method_value(), ))) } /// Handles a request to retrieve the result of a completed task. async fn handle_get_task_payload_request( &self, params: GetTaskPayloadParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CompleteResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &GetTaskPayloadRequest::method_value(), ))) } /// Handles a request to cancel a task. async fn handle_cancel_task_request( &self, params: CancelTaskParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CompleteResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &CancelTaskRequest::method_value(), ))) } /// Handles a request to retrieve a list of tasks. async fn handle_list_task_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CompleteResult, RpcError> { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", &ListTasksRequest::method_value(), ))) } /// Handles custom requests not defined in the standard protocol. /// /// Default implementation returns method not found error. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_custom_request( &self, request: CustomRequest, runtime: Arc<dyn McpServer>, ) -> std::result::Result<GenericResult, RpcError> { Err(RpcError::method_not_found() .with_message("No handler is implemented for custom requests.".to_string())) } // Notification Handlers /// Handles initialized notifications from clients. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_initialized_notification( &self, params: Option<NotificationParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles cancelled operation notifications. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_cancelled_notification( &self, params: CancelledNotificationParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles progress update notifications. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_progress_notification( &self, params: ProgressNotificationParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles notifications received from the client indicating that the list of roots has changed /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_roots_list_changed_notification( &self, params: Option<NotificationParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError> { Ok(()) } ///handles a notification from the receiver to the requestor, informing them that a task's status has changed. async fn handle_task_status_notification( &self, params: TaskStatusNotificationParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError> { Ok(()) } /// Handles custom notifications not defined in the standard protocol. /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_custom_notification( &self, notification: CustomNotification, ) -> std::result::Result<(), RpcError> { Ok(()) } // Error Handler /// Handles server errors that occur during operation. /// /// # Arguments /// * `error` - The error that occurred /// * `runtime` - Reference to the MCP server runtime /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_error( &self, error: &RpcError, runtime: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError> { Ok(()) } } impl<T: ServerHandler + 'static> ToMcpServerHandler for T { fn to_mcp_server_handler(self) -> Arc<dyn McpServerHandler + 'static> { Arc::new(ServerRuntimeInternalHandler::new(Box::new(self))) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_traits/mcp_server.rs
crates/rust-mcp-sdk/src/mcp_traits/mcp_server.rs
use crate::auth::AuthInfo; use crate::error::SdkResult; use crate::schema::{ schema_utils::{ ClientMessage, McpMessage, MessageFromServer, NotificationFromServer, RequestFromServer, ResultFromClient, ServerMessage, }, CreateMessageRequestParams, CreateMessageResult, ElicitRequestParams, ElicitResult, Implementation, InitializeRequestParams, InitializeResult, ListRootsResult, LoggingMessageNotificationParams, NotificationParams, RequestId, RequestParams, ResourceUpdatedNotificationParams, RpcError, ServerCapabilities, }; use crate::task_store::{ClientTaskStore, CreateTaskOptions, ServerTaskStore}; use async_trait::async_trait; use rust_mcp_schema::schema_utils::{ ClientTaskResult, CustomNotification, CustomRequest, ServerJsonrpcRequest, }; use rust_mcp_schema::{ CancelTaskParams, CancelTaskResult, CancelledNotificationParams, CreateTaskResult, ElicitCompleteParams, GenericResult, GetTaskParams, GetTaskPayloadParams, GetTaskResult, ListTasksResult, PaginatedRequestParams, ProgressNotificationParams, TaskStatusNotificationParams, }; use rust_mcp_transport::SessionId; use std::{sync::Arc, time::Duration}; use tokio::sync::RwLockReadGuard; #[async_trait] pub trait McpServer: Sync + Send { async fn start(self: Arc<Self>) -> SdkResult<()>; async fn set_client_details(&self, client_details: InitializeRequestParams) -> SdkResult<()>; fn server_info(&self) -> &InitializeResult; fn client_info(&self) -> Option<InitializeRequestParams>; async fn auth_info(&self) -> RwLockReadGuard<'_, Option<AuthInfo>>; async fn auth_info_cloned(&self) -> Option<AuthInfo>; async fn update_auth_info(&self, auth_info: Option<AuthInfo>); async fn wait_for_initialization(&self); /// Returns the server-side task store, if available. /// /// This store tracks tasks initiated by the client that are being processed by the server. fn task_store(&self) -> Option<Arc<ServerTaskStore>>; /// Returns the client-side task store, if available. /// /// This store tracks tasks initiated by the server that are processed by the client. /// It is responsible for polling task status until each task reaches a terminal state. fn client_task_store(&self) -> Option<Arc<ClientTaskStore>>; /// Checks if the client supports sampling. /// /// This function retrieves the client information and checks if the /// client has sampling capabilities listed. If the client info has /// not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if sampling is supported, or `Some(false)` if not. /// /// # Returns /// - `None` if client information is not yet available. /// - `Some(true)` if sampling is supported by the client. /// - `Some(false)` if sampling is not supported by the client. fn client_supports_sampling(&self) -> Option<bool> { self.client_info() .map(|client_details| client_details.capabilities.sampling.is_some()) } /// Checks if the client supports listing roots. /// /// This function retrieves the client information and checks if the /// client has listing roots capabilities listed. If the client info has /// not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if listing roots is supported, or `Some(false)` if not. /// /// # Returns /// - `None` if client information is not yet available. /// - `Some(true)` if listing roots is supported by the client. /// - `Some(false)` if listing roots is not supported by the client. fn client_supports_root_list(&self) -> Option<bool> { self.client_info() .map(|client_details| client_details.capabilities.roots.is_some()) } /// Checks if the client has experimental capabilities available. /// /// This function retrieves the client information and checks if the /// client has experimental listed in its capabilities. If the client info /// has not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if experimental is available, or `Some(false)` if not. /// /// # Returns /// - `None` if client information is not yet available. /// - `Some(true)` if experimental capabilities are available on the client. /// - `Some(false)` if no experimental capabilities are available on the client. fn client_supports_experimental(&self) -> Option<bool> { self.client_info() .map(|client_details| client_details.capabilities.experimental.is_some()) } /// Sends a message to the standard error output (stderr) asynchronously. async fn stderr_message(&self, message: String) -> SdkResult<()>; #[cfg(feature = "hyper-server")] fn session_id(&self) -> Option<SessionId>; async fn send( &self, message: MessageFromServer, request_id: Option<RequestId>, request_timeout: Option<Duration>, ) -> SdkResult<Option<ClientMessage>>; async fn send_batch( &self, messages: Vec<ServerMessage>, request_timeout: Option<Duration>, ) -> SdkResult<Option<Vec<ClientMessage>>>; /// Checks whether the server has been initialized with client fn is_initialized(&self) -> bool { self.client_info().is_some() } /// Returns the client's name and version information once initialization is complete. /// This method retrieves the client details, if available, after successful initialization. fn client_version(&self) -> Option<Implementation> { self.client_info() .map(|client_details| client_details.client_info) } /// Returns the server's capabilities. fn capabilities(&self) -> &ServerCapabilities { &self.server_info().capabilities } /******************* Requests *******************/ /// Sends a request to the client and processes the response. /// /// This function sends a `RequestFromServer` message to the client, waits for the response, /// and handles the result. If the response is empty or of an invalid type, an error is returned. /// Otherwise, it returns the result from the client. async fn request( &self, request: RequestFromServer, timeout: Option<Duration>, ) -> SdkResult<ResultFromClient> { // keep a clone of the request for the task store let request_clone = if request.is_task_augmented() { Some(request.clone()) } else { None }; // Send the request and receive the response. let response = self .send(MessageFromServer::RequestFromServer(request), None, timeout) .await?; let client_message = response.ok_or_else(|| { RpcError::internal_error() .with_message("An empty response was received from the client.".to_string()) })?; if client_message.is_error() { return Err(client_message.as_error()?.error.into()); } let client_response = client_message.as_response()?; // track awaiting tasks in the client_task_store // CreateTaskResult indicates that a task-augmented request was sent // we keep request tasks in client_task_store and poll until task is in terminal status if let ResultFromClient::CreateTaskResult(create_task_result) = &client_response.result { if let Some(request_to_store) = request_clone { if let Some(client_task_store) = self.client_task_store() { let session_id = { #[cfg(feature = "hyper-server")] { self.session_id() } #[cfg(not(feature = "hyper-server"))] None }; client_task_store .create_task( CreateTaskOptions { ttl: create_task_result.task.ttl, poll_interval: create_task_result.task.poll_interval, meta: create_task_result.meta.clone(), }, client_response.id.clone(), ServerJsonrpcRequest::new(client_response.id, request_to_store), session_id, ) .await; } } else { return Err(RpcError::internal_error() .with_message("No eligible request found for task storage.".to_string()) .into()); } } return Ok(client_response.result); } /// Sends an elicitation request to the client to prompt user input and returns the received response. /// /// The requested_schema argument allows servers to define the structure of the expected response using a restricted subset of JSON Schema. /// To simplify client user experience, elicitation schemas are limited to flat objects with primitive properties only async fn request_elicitation(&self, params: ElicitRequestParams) -> SdkResult<ElicitResult> { let response = self .request(RequestFromServer::ElicitRequest(params), None) .await?; ElicitResult::try_from(response).map_err(|err| err.into()) } async fn request_elicitation_task( &self, params: ElicitRequestParams, ) -> SdkResult<CreateTaskResult> { if !params.is_task_augmented() { return Err(RpcError::invalid_params() .with_message( "Invalid parameters: the request is not identified as task-augmented." .to_string(), ) .into()); } let response = self .request(RequestFromServer::ElicitRequest(params), None) .await?; let response = CreateTaskResult::try_from(response)?; Ok(response) } /// Request a list of root URIs from the client. Roots allow /// servers to ask for specific directories or files to operate on. A common example /// for roots is providing a set of repositories or directories a server should operate on. /// This request is typically used when the server needs to understand the file system /// structure or access specific locations that the client has permission to read from async fn request_root_list(&self, params: Option<RequestParams>) -> SdkResult<ListRootsResult> { let response = self .request(RequestFromServer::ListRootsRequest(params), None) .await?; ListRootsResult::try_from(response).map_err(|err| err.into()) } /// A ping request to check that the other party is still alive. /// The receiver must promptly respond, or else may be disconnected. /// /// This function creates a `PingRequest` with no specific parameters, sends the request and awaits the response /// Once the response is received, it attempts to convert it into the expected /// result type. /// /// # Returns /// A `SdkResult` containing the `rust_mcp_schema::Result` if the request is successful. /// If the request or conversion fails, an error is returned. async fn ping( &self, params: Option<RequestParams>, timeout: Option<Duration>, ) -> SdkResult<crate::schema::Result> { let response = self .request(RequestFromServer::PingRequest(params), timeout) .await?; Ok(response.try_into()?) } /// A request from the server to sample an LLM via the client. /// The client has full discretion over which model to select. /// The client should also inform the user before beginning sampling, /// to allow them to inspect the request (human in the loop) /// and decide whether to approve it. async fn request_message_creation( &self, params: CreateMessageRequestParams, ) -> SdkResult<CreateMessageResult> { let response = self .request(RequestFromServer::CreateMessageRequest(params), None) .await?; Ok(response.try_into()?) } ///Send a request to retrieve the state of a task. async fn request_get_task(&self, params: GetTaskParams) -> SdkResult<GetTaskResult> { let response = self .request(RequestFromServer::GetTaskRequest(params), None) .await?; Ok(response.try_into()?) } ///Send a request to retrieve the result of a completed task. async fn request_get_task_payload( &self, params: GetTaskPayloadParams, ) -> SdkResult<ClientTaskResult> { let response = self .request(RequestFromServer::GetTaskPayloadRequest(params), None) .await?; Ok(response.try_into()?) } ///Send a request to cancel a task. async fn request_task_cancellation( &self, params: CancelTaskParams, ) -> SdkResult<CancelTaskResult> { let response = self .request(RequestFromServer::CancelTaskRequest(params), None) .await?; Ok(response.try_into()?) } ///A request to retrieve a list of tasks. async fn request_task_list( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<ListTasksResult> { let response = self .request(RequestFromServer::ListTasksRequest(params), None) .await?; Ok(response.try_into()?) } ///Send a custom request with a custom method name and params async fn request_custom(&self, params: CustomRequest) -> SdkResult<GenericResult> { let response = self .request(RequestFromServer::CustomRequest(params), None) .await?; Ok(response.try_into()?) } /******************* Notifications *******************/ /// Sends a notification. This is a one-way message that is not expected /// to return any response. The method asynchronously sends the notification using /// the transport layer and does not wait for any acknowledgement or result. async fn send_notification(&self, notification: NotificationFromServer) -> SdkResult<()> { self.send( MessageFromServer::NotificationFromServer(notification), None, None, ) .await?; Ok(()) } /// Send log message notification from server to client. /// If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. async fn notify_log_message(&self, params: LoggingMessageNotificationParams) -> SdkResult<()> { self.send_notification(NotificationFromServer::LoggingMessageNotification(params)) .await } ///Send an optional notification from the server to the client, informing it that /// the list of prompts it offers has changed. /// This may be issued by servers without any previous subscription from the client. async fn notify_prompt_list_changed( &self, params: Option<NotificationParams>, ) -> SdkResult<()> { self.send_notification(NotificationFromServer::PromptListChangedNotification( params, )) .await } ///Send an optional notification from the server to the client, /// informing it that the list of resources it can read from has changed. /// This may be issued by servers without any previous subscription from the client. async fn notify_resource_list_changed( &self, params: Option<NotificationParams>, ) -> SdkResult<()> { self.send_notification(NotificationFromServer::ResourceListChangedNotification( params, )) .await } ///Send a notification from the server to the client, informing it that /// a resource has changed and may need to be read again. /// This should only be sent if the client previously sent a resources/subscribe request. async fn notify_resource_updated( &self, params: ResourceUpdatedNotificationParams, ) -> SdkResult<()> { self.send_notification(NotificationFromServer::ResourceUpdatedNotification(params)) .await } ///Send an optional notification from the server to the client, informing it that /// the list of tools it offers has changed. /// This may be issued by servers without any previous subscription from the client. async fn notify_tool_list_changed(&self, params: Option<NotificationParams>) -> SdkResult<()> { self.send_notification(NotificationFromServer::ToolListChangedNotification(params)) .await } /// This notification can be sent to indicate that it is cancelling a previously-issued request. /// The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. /// This notification indicates that the result will be unused, so any associated processing SHOULD cease. /// A client MUST NOT attempt to cancel its initialize request. /// For task cancellation, use the tasks/cancel request instead of this notification. async fn notify_cancellation(&self, params: CancelledNotificationParams) -> SdkResult<()> { self.send_notification(NotificationFromServer::CancelledNotification(params)) .await } ///Send an out-of-band notification used to inform the receiver of a progress update for a long-running request. async fn notify_progress(&self, params: ProgressNotificationParams) -> SdkResult<()> { self.send_notification(NotificationFromServer::ProgressNotification(params)) .await } /// Send an optional notification from the receiver to the requestor, informing them that a task's status has changed. /// Receivers are not required to send these notifications. async fn notify_task_status(&self, params: TaskStatusNotificationParams) -> SdkResult<()> { self.send_notification(NotificationFromServer::TaskStatusNotification(params)) .await } ///An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. async fn notify_elicitation_completed(&self, params: ElicitCompleteParams) -> SdkResult<()> { self.send_notification(NotificationFromServer::ElicitationCompleteNotification( params, )) .await } ///Send a custom notification async fn notify_custom(&self, params: CustomNotification) -> SdkResult<()> { self.send_notification(NotificationFromServer::CustomNotification(params)) .await } #[deprecated(since = "0.8.0", note = "Use `request_root_list()` instead.")] async fn list_roots(&self, params: Option<RequestParams>) -> SdkResult<ListRootsResult> { let response = self .request(RequestFromServer::ListRootsRequest(params), None) .await?; ListRootsResult::try_from(response).map_err(|err| err.into()) } #[deprecated(since = "0.8.0", note = "Use `request_elicitation()` instead.")] async fn elicit_input(&self, params: ElicitRequestParams) -> SdkResult<ElicitResult> { let response = self .request(RequestFromServer::ElicitRequest(params), None) .await?; ElicitResult::try_from(response).map_err(|err| err.into()) } #[deprecated(since = "0.8.0", note = "Use `request_message_creation()` instead.")] async fn create_message( &self, params: CreateMessageRequestParams, ) -> SdkResult<CreateMessageResult> { let response = self .request(RequestFromServer::CreateMessageRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `notify_tool_list_changed()` instead.")] async fn send_tool_list_changed(&self, params: Option<NotificationParams>) -> SdkResult<()> { self.send_notification(NotificationFromServer::ToolListChangedNotification(params)) .await } #[deprecated(since = "0.8.0", note = "Use `notify_resource_updated()` instead.")] async fn send_resource_updated( &self, params: ResourceUpdatedNotificationParams, ) -> SdkResult<()> { self.send_notification(NotificationFromServer::ResourceUpdatedNotification(params)) .await } #[deprecated( since = "0.8.0", note = "Use `notify_resource_list_changed()` instead." )] async fn send_resource_list_changed( &self, params: Option<NotificationParams>, ) -> SdkResult<()> { self.send_notification(NotificationFromServer::ResourceListChangedNotification( params, )) .await } #[deprecated(since = "0.8.0", note = "Use `notify_prompt_list_changed()` instead.")] async fn send_prompt_list_changed(&self, params: Option<NotificationParams>) -> SdkResult<()> { self.send_notification(NotificationFromServer::PromptListChangedNotification( params, )) .await } #[deprecated(since = "0.8.0", note = "Use `notify_log_message()` instead.")] async fn send_logging_message( &self, params: LoggingMessageNotificationParams, ) -> SdkResult<()> { self.send_notification(NotificationFromServer::LoggingMessageNotification(params)) .await } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_traits/mcp_client.rs
crates/rust-mcp-sdk/src/mcp_traits/mcp_client.rs
use crate::error::SdkResult; use crate::schema::{ schema_utils::{ ClientMessage, McpMessage, MessageFromClient, NotificationFromClient, RequestFromClient, ResultFromServer, ServerMessage, }, CallToolRequestParams, CallToolResult, CompleteRequestParams, GenericResult, GetPromptRequestParams, Implementation, InitializeRequestParams, InitializeResult, NotificationParams, PaginatedRequestParams, ReadResourceRequestParams, RequestId, RequestParams, RpcError, ServerCapabilities, SetLevelRequestParams, SubscribeRequestParams, UnsubscribeRequestParams, }; use crate::task_store::{ClientTaskStore, ServerTaskStore}; use async_trait::async_trait; use rust_mcp_schema::schema_utils::ServerTaskResult; use rust_mcp_schema::{ schema_utils::CustomNotification, CancelledNotificationParams, ProgressNotificationParams, TaskStatusNotificationParams, }; use rust_mcp_schema::{ CancelTaskParams, CancelTaskResult, ClientCapabilities, GetTaskParams, GetTaskPayloadParams, GetTaskResult, ListTasksResult, }; use rust_mcp_transport::SessionId; use std::{sync::Arc, time::Duration}; #[async_trait] pub trait McpClient: Sync + Send { async fn start(self: Arc<Self>) -> SdkResult<()>; fn set_server_details(&self, server_details: InitializeResult) -> SdkResult<()>; async fn terminate_session(&self); /// Returns the client-side task store, if available. /// /// This store tracks tasks initiated by the server that are being processed by the client. fn task_store(&self) -> Option<Arc<ClientTaskStore>>; /// Returns the server-side task store, if available. /// /// This store tracks tasks initiated by the client that are processed by the server. /// It is responsible for polling task status until each task reaches a terminal state. fn server_task_store(&self) -> Option<Arc<ServerTaskStore>>; async fn shut_down(&self) -> SdkResult<()>; async fn is_shut_down(&self) -> bool; fn client_info(&self) -> &InitializeRequestParams; fn server_info(&self) -> Option<InitializeResult>; /// Checks whether the server has been initialized with client fn is_initialized(&self) -> bool { self.server_info().is_some() } /// Returns the server's name and version information once initialization is complete. /// This method retrieves the server details, if available, after successful initialization. fn server_version(&self) -> Option<Implementation> { self.server_info() .map(|server_details| server_details.server_info) } /// Returns the server's capabilities. /// After initialization has completed, this will be populated with the server's reported capabilities. fn server_capabilities(&self) -> Option<ServerCapabilities> { self.server_info().map(|item| item.capabilities) } /// Checks if the server has tools available. /// /// This function retrieves the server information and checks if the /// server has tools listed in its capabilities. If the server info /// has not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if tools are available, or `Some(false)` if not. /// /// # Returns /// - `None` if server information is not yet available. /// - `Some(true)` if tools are available on the server. /// - `Some(false)` if no tools are available on the server. /// ```rust /// println!("{}",1); /// ``` fn server_has_tools(&self) -> Option<bool> { self.server_info() .map(|server_details| server_details.capabilities.tools.is_some()) } /// Checks if the server has prompts available. /// /// This function retrieves the server information and checks if the /// server has prompts listed in its capabilities. If the server info /// has not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if prompts are available, or `Some(false)` if not. /// /// # Returns /// - `None` if server information is not yet available. /// - `Some(true)` if prompts are available on the server. /// - `Some(false)` if no prompts are available on the server. fn server_has_prompts(&self) -> Option<bool> { self.server_info() .map(|server_details| server_details.capabilities.prompts.is_some()) } /// Checks if the server has experimental capabilities available. /// /// This function retrieves the server information and checks if the /// server has experimental listed in its capabilities. If the server info /// has not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if experimental is available, or `Some(false)` if not. /// /// # Returns /// - `None` if server information is not yet available. /// - `Some(true)` if experimental capabilities are available on the server. /// - `Some(false)` if no experimental capabilities are available on the server. fn server_has_experimental(&self) -> Option<bool> { self.server_info() .map(|server_details| server_details.capabilities.experimental.is_some()) } /// Checks if the server has resources available. /// /// This function retrieves the server information and checks if the /// server has resources listed in its capabilities. If the server info /// has not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if resources are available, or `Some(false)` if not. /// /// # Returns /// - `None` if server information is not yet available. /// - `Some(true)` if resources are available on the server. /// - `Some(false)` if no resources are available on the server. fn server_has_resources(&self) -> Option<bool> { self.server_info() .map(|server_details| server_details.capabilities.resources.is_some()) } /// Checks if the server supports logging. /// /// This function retrieves the server information and checks if the /// server has logging capabilities listed. If the server info has /// not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if logging is supported, or `Some(false)` if not. /// /// # Returns /// - `None` if server information is not yet available. /// - `Some(true)` if logging is supported by the server. /// - `Some(false)` if logging is not supported by the server. fn server_supports_logging(&self) -> Option<bool> { self.server_info() .map(|server_details| server_details.capabilities.logging.is_some()) } /// Checks if the server supports argument autocompletion suggestions. /// /// This function retrieves the server information and checks if the /// server has completions capabilities listed. If the server info has /// not been retrieved yet, it returns `None`. Otherwise, it returns /// `Some(true)` if completions is supported, or `Some(false)` if not. /// /// # Returns /// - `None` if server information is not yet available. /// - `Some(true)` if completions is supported by the server. /// - `Some(false)` if completions is not supported by the server. fn server_supports_completion(&self) -> Option<bool> { self.server_info() .map(|server_details| server_details.capabilities.completions.is_some()) } fn instructions(&self) -> Option<String> { self.server_info()?.instructions } async fn session_id(&self) -> Option<SessionId>; /// Returns the client's capabilities. fn capabilities(&self) -> &ClientCapabilities { &self.client_info().capabilities } /// Sends a request to the server and processes the response. /// /// This function sends a `RequestFromClient` message to the server, waits for the response, /// and handles the result. If the response is empty or of an invalid type, an error is returned. /// Otherwise, it returns the result from the server. async fn request( &self, request: RequestFromClient, timeout: Option<Duration>, ) -> SdkResult<ResultFromServer> { let response = self .send(MessageFromClient::RequestFromClient(request), None, timeout) .await?; let server_message = response.ok_or_else(|| { RpcError::internal_error() .with_message("An empty response was received from the client.".to_string()) })?; if server_message.is_error() { return Err(server_message.as_error()?.error.into()); } return Ok(server_message.as_response()?.result); } async fn send( &self, message: MessageFromClient, request_id: Option<RequestId>, request_timeout: Option<Duration>, ) -> SdkResult<Option<ServerMessage>>; async fn send_batch( &self, messages: Vec<ClientMessage>, timeout: Option<Duration>, ) -> SdkResult<Option<Vec<ServerMessage>>>; /// Sends a notification. This is a one-way message that is not expected /// to return any response. The method asynchronously sends the notification using /// the transport layer and does not wait for any acknowledgement or result. async fn send_notification(&self, notification: NotificationFromClient) -> SdkResult<()> { self.send(notification.into(), None, None).await?; Ok(()) } /******************* Requests *******************/ /// A ping request to check that the other party is still alive. /// The receiver must promptly respond, or else may be disconnected. /// /// This function creates a `PingRequest` with no specific parameters, sends the request and awaits the response /// Once the response is received, it attempts to convert it into the expected /// result type. /// /// # Returns /// A `SdkResult` containing the `rust_mcp_schema::Result` if the request is successful. /// If the request or conversion fails, an error is returned. async fn ping( &self, params: Option<RequestParams>, timeout: Option<Duration>, ) -> SdkResult<GenericResult> { let response = self .request(RequestFromClient::PingRequest(params), timeout) .await?; Ok(response.try_into()?) } ///send a request from the client to the server, to ask for completion options. async fn request_completion( &self, params: CompleteRequestParams, ) -> SdkResult<crate::schema::CompleteResult> { let response = self .request(RequestFromClient::CompleteRequest(params), None) .await?; Ok(response.try_into()?) } /// send a request from the client to the server, to enable or adjust logging. async fn request_set_logging_level( &self, params: SetLevelRequestParams, ) -> SdkResult<crate::schema::Result> { let response = self .request(RequestFromClient::SetLevelRequest(params), None) .await?; Ok(response.try_into()?) } /// send a request to get a prompt provided by the server. async fn request_prompt( &self, params: GetPromptRequestParams, ) -> SdkResult<crate::schema::GetPromptResult> { let response = self .request(RequestFromClient::GetPromptRequest(params), None) .await?; Ok(response.try_into()?) } ///Request a list of prompts and prompt templates the server has. async fn request_prompt_list( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<crate::schema::ListPromptsResult> { let response = self .request(RequestFromClient::ListPromptsRequest(params), None) .await?; Ok(response.try_into()?) } /// request a list of resources the server has. async fn request_resource_list( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<crate::schema::ListResourcesResult> { let response = self .request(RequestFromClient::ListResourcesRequest(params), None) .await?; Ok(response.try_into()?) } /// request a list of resource templates the server has. async fn request_resource_template_list( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<crate::schema::ListResourceTemplatesResult> { let response = self .request( RequestFromClient::ListResourceTemplatesRequest(params), None, ) .await?; Ok(response.try_into()?) } /// send a request to the server to to read a specific resource URI. async fn request_resource_read( &self, params: ReadResourceRequestParams, ) -> SdkResult<crate::schema::ReadResourceResult> { let response = self .request(RequestFromClient::ReadResourceRequest(params), None) .await?; Ok(response.try_into()?) } /// request resources/updated notifications from the server whenever a particular resource changes. async fn request_resource_subscription( &self, params: SubscribeRequestParams, ) -> SdkResult<crate::schema::Result> { let response = self .request(RequestFromClient::SubscribeRequest(params), None) .await?; Ok(response.try_into()?) } /// request cancellation of resources/updated notifications from the server. /// This should follow a previous resources/subscribe request. async fn request_resource_unsubscription( &self, params: UnsubscribeRequestParams, ) -> SdkResult<crate::schema::Result> { let response = self .request(RequestFromClient::UnsubscribeRequest(params), None) .await?; Ok(response.try_into()?) } /// invoke a tool provided by the server. async fn request_tool_call(&self, params: CallToolRequestParams) -> SdkResult<CallToolResult> { let response = self .request(RequestFromClient::CallToolRequest(params), None) .await?; Ok(response.try_into()?) } /// request a list of tools the server has. async fn request_tool_list( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<crate::schema::ListToolsResult> { let response = self .request(RequestFromClient::ListToolsRequest(params), None) .await?; Ok(response.try_into()?) } ///Send a request to retrieve the state of a task. async fn request_get_task(&self, params: GetTaskParams) -> SdkResult<GetTaskResult> { let response = self .request(RequestFromClient::GetTaskRequest(params), None) .await?; Ok(response.try_into()?) } ///Send a request to retrieve the result of a completed task. async fn request_get_task_payload( &self, params: GetTaskPayloadParams, ) -> SdkResult<ServerTaskResult> { let response = self .request(RequestFromClient::GetTaskPayloadRequest(params), None) .await?; Ok(response.try_into()?) } ///Send a request to cancel a task. async fn request_task_cancellation( &self, params: CancelTaskParams, ) -> SdkResult<CancelTaskResult> { let response = self .request(RequestFromClient::CancelTaskRequest(params), None) .await?; Ok(response.try_into()?) } ///A request to retrieve a list of tasks. async fn request_task_list( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<ListTasksResult> { let response = self .request(RequestFromClient::ListTasksRequest(params), None) .await?; Ok(response.try_into()?) } /******************* Notifications *******************/ /// A notification from the client to the server, informing it that the list of roots has changed. /// This notification should be sent whenever the client adds, removes, or modifies any root. async fn notify_roots_list_changed(&self, params: Option<NotificationParams>) -> SdkResult<()> { self.send_notification(NotificationFromClient::RootsListChangedNotification(params)) .await } /// This notification can be sent by either side to indicate that it is cancelling a previously-issued request. /// The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. /// This notification indicates that the result will be unused, so any associated processing SHOULD cease. /// A client MUST NOT attempt to cancel its initialize request. /// For task cancellation, use the tasks/cancel request instead of this notification async fn notify_cancellation(&self, params: CancelledNotificationParams) -> SdkResult<()> { self.send_notification(NotificationFromClient::CancelledNotification(params)) .await } ///Send an out-of-band notification used to inform the receiver of a progress update for a long-running request. async fn notify_progress(&self, params: ProgressNotificationParams) -> SdkResult<()> { self.send_notification(NotificationFromClient::ProgressNotification(params)) .await } /// Send an optional notification from the receiver to the requestor, informing them that a task's status has changed. /// Receivers are not required to send these notifications. async fn notify_task_status(&self, params: TaskStatusNotificationParams) -> SdkResult<()> { self.send_notification(NotificationFromClient::TaskStatusNotification(params)) .await } ///Send a custom notification async fn notify_custom(&self, params: CustomNotification) -> SdkResult<()> { self.send_notification(NotificationFromClient::CustomNotification(params)) .await } /******************* Deprecated *******************/ #[deprecated(since = "0.8.0", note = "Use `request_completion()` instead.")] async fn complete( &self, params: CompleteRequestParams, ) -> SdkResult<crate::schema::CompleteResult> { let response = self .request(RequestFromClient::CompleteRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `request_set_logging_level()` instead.")] async fn set_logging_level( &self, params: SetLevelRequestParams, ) -> SdkResult<crate::schema::Result> { let response = self .request(RequestFromClient::SetLevelRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `request_prompt()` instead.")] async fn get_prompt( &self, params: GetPromptRequestParams, ) -> SdkResult<crate::schema::GetPromptResult> { let response = self .request(RequestFromClient::GetPromptRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `request_prompt_list()` instead.")] async fn list_prompts( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<crate::schema::ListPromptsResult> { let response = self .request(RequestFromClient::ListPromptsRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `request_resource_list()` instead.")] async fn list_resources( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<crate::schema::ListResourcesResult> { let response = self .request(RequestFromClient::ListResourcesRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated( since = "0.8.0", note = "Use `request_resource_template_list()` instead." )] async fn list_resource_templates( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<crate::schema::ListResourceTemplatesResult> { let response = self .request( RequestFromClient::ListResourceTemplatesRequest(params), None, ) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `request_resource_read()` instead.")] async fn read_resource( &self, params: ReadResourceRequestParams, ) -> SdkResult<crate::schema::ReadResourceResult> { let response = self .request(RequestFromClient::ReadResourceRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated( since = "0.8.0", note = "Use `request_resource_subscription()` instead." )] async fn subscribe_resource( &self, params: SubscribeRequestParams, ) -> SdkResult<crate::schema::Result> { let response = self .request(RequestFromClient::SubscribeRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated( since = "0.8.0", note = "Use `request_resource_unsubscription()` instead." )] async fn unsubscribe_resource( &self, params: UnsubscribeRequestParams, ) -> SdkResult<crate::schema::Result> { let response = self .request(RequestFromClient::UnsubscribeRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `request_tool_call()` instead.")] async fn call_tool(&self, params: CallToolRequestParams) -> SdkResult<CallToolResult> { let response = self .request(RequestFromClient::CallToolRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `request_tool_list()` instead.")] async fn list_tools( &self, params: Option<PaginatedRequestParams>, ) -> SdkResult<crate::schema::ListToolsResult> { let response = self .request(RequestFromClient::ListToolsRequest(params), None) .await?; Ok(response.try_into()?) } #[deprecated(since = "0.8.0", note = "Use `notify_roots_list_changed()` instead.")] async fn send_roots_list_changed(&self, params: Option<NotificationParams>) -> SdkResult<()> { self.send_notification(NotificationFromClient::RootsListChangedNotification(params)) .await } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_traits/request_id_gen.rs
crates/rust-mcp-sdk/src/mcp_traits/request_id_gen.rs
use std::sync::atomic::AtomicI64; use crate::schema::{schema_utils::McpMessage, RequestId}; use async_trait::async_trait; /// A trait for generating and managing request IDs in a thread-safe manner. /// /// Implementors provide functionality to generate unique request IDs, retrieve the last /// generated ID, and reset the ID counter. #[async_trait] pub trait RequestIdGen: Send + Sync { fn next_request_id(&self) -> RequestId; #[allow(unused)] fn last_request_id(&self) -> Option<RequestId>; #[allow(unused)] fn reset_to(&self, id: u64); /// Determines the request ID for an outgoing MCP message. /// /// For requests, generates a new ID using the internal counter. For responses or errors, /// uses the provided `request_id`. Notifications receive no ID. /// /// # Arguments /// * `message` - The MCP message to evaluate. /// * `request_id` - An optional existing request ID (required for responses/errors). /// /// # Returns /// An `Option<RequestId>`: `Some` for requests or responses/errors, `None` for notifications. fn request_id_for_message( &self, message: &dyn McpMessage, request_id: Option<RequestId>, ) -> Option<RequestId> { // we need to produce next request_id for requests if message.is_request() { // request_id should be None for requests assert!(request_id.is_none()); Some(self.next_request_id()) } else if !message.is_notification() { // `request_id` must not be `None` for errors, notifications and responses assert!(request_id.is_some()); request_id } else { None } } } pub struct RequestIdGenNumeric { message_id_counter: AtomicI64, last_message_id: AtomicI64, } impl RequestIdGenNumeric { pub fn new(initial_id: Option<u64>) -> Self { Self { message_id_counter: AtomicI64::new(initial_id.unwrap_or(0) as i64), last_message_id: AtomicI64::new(-1), } } } impl RequestIdGen for RequestIdGenNumeric { /// Generates the next unique request ID as an integer. /// /// Increments the internal counter atomically and updates the last generated ID. /// Uses `Relaxed` ordering for performance, as the counter only needs to ensure unique IDs. fn next_request_id(&self) -> RequestId { let id = self .message_id_counter .fetch_add(1, std::sync::atomic::Ordering::Relaxed); // Store the new ID as the last generated ID self.last_message_id .store(id, std::sync::atomic::Ordering::Relaxed); RequestId::Integer(id) } /// Returns the last generated request ID, if any. /// /// Returns `None` if no ID has been generated (indicated by a sentinel value of -1). /// Uses `Relaxed` ordering since the read operation doesn’t require synchronization /// with other memory operations beyond atomicity. fn last_request_id(&self) -> Option<RequestId> { let last_id = self .last_message_id .load(std::sync::atomic::Ordering::Relaxed); if last_id == -1 { None } else { Some(RequestId::Integer(last_id)) } } /// Resets the internal counter to the specified ID. /// /// The provided `id` (u64) is converted to i64 and stored atomically. fn reset_to(&self, id: u64) { self.message_id_counter .store(id as i64, std::sync::atomic::Ordering::Relaxed); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_traits/mcp_handler.rs
crates/rust-mcp-sdk/src/mcp_traits/mcp_handler.rs
use async_trait::async_trait; use rust_mcp_schema::schema_utils::{ ClientJsonrpcNotification, ClientJsonrpcRequest, ServerJsonrpcRequest, }; #[cfg(feature = "server")] use crate::schema::schema_utils::ResultFromServer; #[cfg(feature = "client")] use crate::schema::schema_utils::{NotificationFromServer, ResultFromClient}; use crate::error::SdkResult; use crate::schema::RpcError; use std::sync::Arc; #[cfg(feature = "client")] use super::mcp_client::McpClient; #[cfg(feature = "server")] use super::mcp_server::McpServer; #[cfg(feature = "server")] #[async_trait] pub trait McpServerHandler: Send + Sync { async fn handle_request( &self, client_jsonrpc_request: ClientJsonrpcRequest, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ResultFromServer, RpcError>; async fn handle_error( &self, jsonrpc_error: &RpcError, runtime: Arc<dyn McpServer>, ) -> SdkResult<()>; async fn handle_notification( &self, client_jsonrpc_notification: ClientJsonrpcNotification, runtime: Arc<dyn McpServer>, ) -> SdkResult<()>; } // Custom trait for converting ServerHandler #[cfg(feature = "server")] pub trait ToMcpServerHandler { fn to_mcp_server_handler(self) -> Arc<dyn McpServerHandler + 'static>; } // Custom trait for converting ServerHandlerCore #[cfg(feature = "server")] pub trait ToMcpServerHandlerCore { fn to_mcp_server_handler(self) -> Arc<dyn McpServerHandler + 'static>; } #[cfg(feature = "client")] #[async_trait] pub trait McpClientHandler: Send + Sync { async fn handle_request( &self, server_jsonrpc_request: ServerJsonrpcRequest, runtime: &dyn McpClient, ) -> std::result::Result<ResultFromClient, RpcError>; async fn handle_error( &self, jsonrpc_error: &RpcError, runtime: &dyn McpClient, ) -> SdkResult<()>; async fn handle_notification( &self, server_jsonrpc_notification: NotificationFromServer, runtime: &dyn McpClient, ) -> SdkResult<()>; async fn handle_process_error( &self, error_message: String, runtime: &dyn McpClient, ) -> SdkResult<()>; } // Custom trait for converting ClientHandler #[cfg(feature = "client")] pub trait ToMcpClientHandler { fn to_mcp_client_handler(self) -> Box<dyn McpClientHandler + 'static>; } // Custom trait for converting ClientHandlerCore #[cfg(feature = "client")] pub trait ToMcpClientHandlerCore { fn to_mcp_client_handler(self) -> Box<dyn McpClientHandler + 'static>; }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_traits/id_generator.rs
crates/rust-mcp-sdk/src/mcp_traits/id_generator.rs
/// Trait for generating unique identifiers. /// /// This trait is generic over the target ID type, allowing it to be used for /// generating different kinds of identifiers such as `SessionId` or /// transport-scoped `StreamId`. /// pub trait IdGenerator<T>: Send + Sync where T: From<String>, { fn generate(&self) -> T; }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_macros/tool_box.rs
crates/rust-mcp-sdk/src/mcp_macros/tool_box.rs
#[macro_export] /// Generates an enum representing a toolbox with mcp tool variants and associated functionality. /// /// **Note:** The macro assumes that tool types provided are annotated with the mcp_tool() macro. /// /// This macro creates: /// - An enum with the specified name containing variants for each mcp tool /// - A `tools()` function returning a vector of supported tools /// - A `TryFrom<CallToolRequestParams>` implementation for converting requests to tool instances /// /// # Arguments /// * `$enum_name` - The name to give the generated enum /// * `[$($tool:ident),*]` - A comma-separated list of tool types to include in the enum /// /// /// # Example /// ```ignore /// tool_box!(FileSystemTools, [ReadFileTool, EditFileTool, SearchFilesTool]); /// // Creates: /// // pub enum FileSystemTools { /// // ReadFileTool(ReadFileTool), /// // EditFileTool(EditFileTool), /// // SearchFilesTool(SearchFilesTool), /// // } /// // pub fn tools() -> Vec<Tool> { /// // vec![ReadFileTool::tool(), EditFileTool::tool(), SearchFilesTool::tool()] /// // } /// /// // impl TryFrom<CallToolRequestParams> for FileSystemTools { /// // //....... /// // } macro_rules! tool_box { ($enum_name:ident, [$($tool:ident),* $(,)?]) => { #[derive(Debug)] pub enum $enum_name { $( // Just create enum variants for each tool $tool($tool), )* } /// Returns the name of the tool as a String impl $enum_name { pub fn tool_name(&self) -> String { match self { $( $enum_name::$tool(_) => $tool::tool_name(), )* } } /// Returns a vector containing instances of all supported tools pub fn tools() -> Vec<rust_mcp_sdk::schema::Tool> { vec![ $( $tool::tool(), )* ] } } impl TryFrom<rust_mcp_sdk::schema::CallToolRequestParams> for $enum_name { type Error = rust_mcp_sdk::schema::schema_utils::CallToolError; /// Attempts to convert a tool request into the appropriate tool variant fn try_from(value: rust_mcp_sdk::schema::CallToolRequestParams) -> Result<Self, Self::Error> { let arguments = value .arguments .ok_or(rust_mcp_sdk::schema::schema_utils::CallToolError::invalid_arguments( &value.name, Some("Missing 'arguments' field in the request".to_string()) ))?; let v = serde_json::to_value(arguments).map_err(|err| { rust_mcp_sdk::schema::schema_utils::CallToolError::invalid_arguments( &value.name, Some(format!("{err}")), ) })?; match value.name { $( name if name == $tool::tool_name().as_str() => { Ok(Self::$tool(serde_json::from_value(v).map_err(rust_mcp_sdk::schema::schema_utils::CallToolError::new)?)) } )* _ => { Err( rust_mcp_sdk::schema::schema_utils::CallToolError::unknown_tool(value.name.to_string()) ) } } } } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_macros/mcp_icon.rs
crates/rust-mcp-sdk/src/mcp_macros/mcp_icon.rs
#[macro_export] /// Macro to conveniently create an `Icon` instance using a shorthand syntax". /// /// # Syntax /// ```text /// mcp_icon!( /// src = "path_or_url", /// mime_type = "optional_mime_type", /// sizes = ["WxH", "WxH", ...], /// theme = "dark" | "light", /// ) /// ``` /// /// # Rules /// - `src` is **mandatory**. /// - `mime_type`, `sizes`, and `theme` are **optional**. /// - If `theme` is missing or invalid, it defaults to `IconTheme::Light`. /// - `sizes` uses a Rust array of string literals (DSL style), which are converted to `Vec<String>`. /// /// # Example /// ```rust /// let my_icon: rust_mcp_sdk::schema::Icon = rust_mcp_sdk::mcp_icon!( /// src = "/icons/dark.png", /// mime_type = "image/png", /// sizes = ["128x128", "256x256"], /// theme = "dark" /// ); /// ``` macro_rules! mcp_icon { ( src = $src:expr $(, mime_type = $mime_type:expr )? $(, sizes = [$($size:expr),* $(,)?] )? $(, theme = $theme:expr )? $(,)? ) => { $crate::schema::Icon { src: $src.into(), mime_type: None $(.or(Some($mime_type.into())))?, sizes: vec![$($($size.into()),*)?], theme: None $(.or(Some($theme.into())))?, } }; } #[cfg(test)] mod tests { use crate::schema::*; // Helper function to convert IconTheme to &str for easy comparisons fn theme_str(theme: Option<IconTheme>) -> &'static str { match theme { Some(IconTheme::Dark) => "dark", Some(IconTheme::Light) => "light", None => "none", } } #[test] fn test_minimal_icon() { // Only mandatory src let icon = mcp_icon!(src = "/icons/simple.png"); assert_eq!(icon.src, "/icons/simple.png"); assert!(icon.mime_type.is_none()); assert!(icon.sizes.is_empty()); assert!(icon.theme.is_none()); } #[test] fn test_icon_with_mime_type() { let icon = mcp_icon!(src = "/icons/simple.png", mime_type = "image/png"); assert_eq!(icon.src, "/icons/simple.png"); assert_eq!(icon.mime_type.as_deref(), Some("image/png")); assert!(icon.sizes.is_empty()); assert!(icon.theme.is_none()); } #[test] fn test_icon_with_sizes() { let icon = mcp_icon!(src = "/icons/simple.png", sizes = ["32x32", "64x64"]); assert_eq!(icon.src, "/icons/simple.png"); assert!(icon.mime_type.is_none()); assert_eq!(icon.sizes, vec!["32x32", "64x64"]); assert!(icon.theme.is_none()); } #[test] fn test_icon_with_theme_light() { let icon = mcp_icon!(src = "/icons/simple.png", theme = "light"); assert_eq!(icon.src, "/icons/simple.png"); assert!(icon.mime_type.is_none()); assert!(icon.sizes.is_empty()); assert_eq!(theme_str(icon.theme), "light"); } #[test] fn test_icon_with_theme_dark() { let icon = mcp_icon!(src = "/icons/simple.png", theme = "dark"); assert_eq!(theme_str(icon.theme), "dark"); } #[test] fn test_icon_with_invalid_theme_defaults_to_light() { let icon = mcp_icon!(src = "/icons/simple.png", theme = "foo"); // Invalid theme should default to Light assert_eq!(theme_str(icon.theme), "light"); } #[test] fn test_icon_full() { let icon = mcp_icon!( src = "/icons/full.png", mime_type = "image/png", sizes = ["16x16", "32x32", "64x64"], theme = "dark" ); assert_eq!(icon.src, "/icons/full.png"); assert_eq!(icon.mime_type.as_deref(), Some("image/png")); assert_eq!(icon.sizes, vec!["16x16", "32x32", "64x64"]); assert_eq!(theme_str(icon.theme), "dark"); } #[test] fn test_icon_sizes_empty_when_missing() { let icon = mcp_icon!(src = "/icons/empty.png"); assert!(icon.sizes.is_empty()); } #[test] fn test_icon_optional_fields_missing() { let icon = mcp_icon!(src = "/icons/missing.png"); assert!(icon.mime_type.is_none()); assert!(icon.sizes.is_empty()); assert!(icon.theme.is_none()); } #[test] fn test_icon_trailing_comma() { let icon = mcp_icon!( src = "/icons/comma.png", mime_type = "image/jpeg", sizes = ["48x48"], theme = "light", ); assert_eq!(icon.src, "/icons/comma.png"); assert_eq!(icon.mime_type.as_deref(), Some("image/jpeg")); assert_eq!(icon.sizes, vec!["48x48"]); assert_eq!(theme_str(icon.theme), "light"); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/http_utils.rs
crates/rust-mcp-sdk/src/mcp_http/http_utils.rs
use crate::auth::AuthInfo; use crate::mcp_http::types::GenericBody; use crate::schema::schema_utils::{ClientMessage, SdkError}; use crate::McpServer; use crate::{ error::SdkResult, hyper_servers::error::{TransportServerError, TransportServerResult}, mcp_http::McpAppState, mcp_runtimes::server_runtime::DEFAULT_STREAM_ID, mcp_server::{server_runtime, ServerRuntime}, mcp_traits::{IdGenerator, McpServerHandler}, utils::validate_mcp_protocol_version, }; use axum::http::HeaderValue; use bytes::Bytes; use futures::stream; use http::header::{ACCEPT, CONNECTION, CONTENT_TYPE}; use http_body::Frame; use http_body_util::{BodyExt, Full, StreamBody}; use hyper::{HeaderMap, StatusCode}; use rust_mcp_transport::{ EventId, McpDispatch, SessionId, SseEvent, SseTransport, StreamId, ID_SEPARATOR, MCP_PROTOCOL_VERSION_HEADER, MCP_SESSION_ID_HEADER, }; use serde_json::{Map, Value}; use std::sync::Arc; use tokio::io::{duplex, AsyncBufReadExt, BufReader}; use tokio_stream::StreamExt; // Default Server-Sent Events (SSE) endpoint path pub(crate) const DEFAULT_SSE_ENDPOINT: &str = "/sse"; // Default MCP Messages endpoint path pub(crate) const DEFAULT_MESSAGES_ENDPOINT: &str = "/messages"; // Default Streamable HTTP endpoint path pub(crate) const DEFAULT_STREAMABLE_HTTP_ENDPOINT: &str = "/mcp"; const DUPLEX_BUFFER_SIZE: usize = 8192; /// Creates an initial SSE event that returns the messages endpoint /// /// Constructs an SSE event containing the messages endpoint URL with the session ID. /// /// # Arguments /// * `session_id` - The session identifier for the client /// /// # Returns /// * `Result<Event, Infallible>` - The constructed SSE event, infallible fn initial_sse_event(endpoint: &str) -> Result<Bytes, TransportServerError> { Ok(SseEvent::default() .with_event("endpoint") .with_data(endpoint.to_string()) .as_bytes()) } #[cfg(feature = "auth")] pub fn url_base(url: &url::Url) -> String { format!("{}://{}", url.scheme(), url.host_str().unwrap_or_default()) } /// Remove the `Bearer` prefix from a `WWW-Authenticate` or `Authorization` header. /// /// This function performs a **case-insensitive** check for the `Bearer` /// authentication scheme. If present, the prefix is removed and the /// remaining parameter string is returned trimmed. fn strip_bearer_prefix(header: &str) -> &str { let lower = header.to_lowercase(); if lower.starts_with("bearer ") { header[7..].trim() } else if lower == "bearer" { "" } else { header.trim() } } /// Parse a `WWW-Authenticate` header with Bearer-style key/value parameters /// into a JSON object (`serde_json::Map`). #[cfg(feature = "auth")] pub fn parse_www_authenticate(header: &str) -> Option<Map<String, Value>> { let params_str = strip_bearer_prefix(header); let mut result: Option<Map<String, Value>> = None; for part in params_str.split(',') { let part = part.trim(); if let Some((key, value)) = part.split_once('=') { let cleaned = value.trim().trim_matches('"'); // Create the map only when first key=value is found let map = result.get_or_insert_with(Map::new); map.insert(key.to_string(), Value::String(cleaned.to_string())); } } result } /// Extract the most meaningful error message from an HTTP response. /// This is useful for handling OAuth2 / OpenID Connect Bearer errors /// /// Extraction order: /// 1. If the `WWW-Authenticate` header exists and contains a Bearer error: /// - Return `error_description` if present /// - Else return `error` if present /// - Else join all string values in the header /// 2. If no usable info is found in the header: /// - Return the response body text /// - If body cannot be read, return `default_message` #[cfg(feature = "auth")] pub async fn error_message_from_response( response: reqwest::Response, default_message: &str, ) -> String { if let Some(www_authenticate) = response .headers() .get(http::header::WWW_AUTHENTICATE) .and_then(|v| v.to_str().ok()) { if let Some(map) = parse_www_authenticate(www_authenticate) { if let Some(Value::String(s)) = map.get("error_description") { return s.clone(); } if let Some(Value::String(s)) = map.get("error") { return s.clone(); } // Fallback: join all string values let values: Vec<&str> = map .values() .filter_map(|v| match v { Value::String(s) => Some(s.as_str()), _ => None, }) .collect(); if !values.is_empty() { return values.join(", "); } } } response.text().await.unwrap_or(default_message.to_owned()) } async fn create_sse_stream( runtime: Arc<ServerRuntime>, session_id: SessionId, state: Arc<McpAppState>, payload: Option<&str>, standalone: bool, last_event_id: Option<EventId>, ) -> TransportServerResult<http::Response<GenericBody>> { let payload_string = payload.map(|p| p.to_string()); // TODO: this logic should be moved out after refactoing the mcp_stream.rs let payload_contains_request = payload_string .as_ref() .map(|json_str| contains_request(json_str)) .unwrap_or(Ok(false)); let Ok(payload_contains_request) = payload_contains_request else { return error_response(StatusCode::BAD_REQUEST, SdkError::parse_error()); }; // readable stream of string to be used in transport let (read_tx, read_rx) = duplex(DUPLEX_BUFFER_SIZE); // writable stream to deliver message to the client let (write_tx, write_rx) = duplex(DUPLEX_BUFFER_SIZE); let session_id = Arc::new(session_id); let stream_id: Arc<StreamId> = if standalone { Arc::new(DEFAULT_STREAM_ID.to_string()) } else { Arc::new(state.stream_id_gen.generate()) }; let event_store = state.event_store.as_ref().map(Arc::clone); let resumability_enabled = event_store.is_some(); let mut transport = SseTransport::<ClientMessage>::new( read_rx, write_tx, read_tx, Arc::clone(&state.transport_options), ) .map_err(|err| TransportServerError::TransportError(err.to_string()))?; if let Some(event_store) = event_store.clone() { transport.make_resumable((*session_id).clone(), (*stream_id).clone(), event_store); } let transport = Arc::new(transport); let ping_interval = state.ping_interval; let runtime_clone = Arc::clone(&runtime); let stream_id_clone = stream_id.clone(); let transport_clone = transport.clone(); //Start the server runtime tokio::spawn(async move { match runtime_clone .start_stream( transport_clone, &stream_id_clone, ping_interval, payload_string, ) .await { Ok(_) => tracing::trace!("stream {} exited gracefully.", &stream_id_clone), Err(err) => tracing::info!("stream {} exited with error : {}", &stream_id_clone, err), } let _ = runtime.remove_transport(&stream_id_clone).await; }); // Construct SSE stream let reader = BufReader::new(write_rx); // send outgoing messages from server to the client over the sse stream let message_stream = stream::unfold(reader, move |mut reader| { async move { let mut line = String::new(); match reader.read_line(&mut line).await { Ok(0) => None, // EOF Ok(_) => { let trimmed_line = line.trim_end_matches('\n').to_owned(); // empty sse comment to keep-alive if is_empty_sse_message(&trimmed_line) { return Some((Ok(SseEvent::default().as_bytes()), reader)); } let (event_id, message) = match ( resumability_enabled, trimmed_line.split_once(char::from(ID_SEPARATOR)), ) { (true, Some((id, msg))) => (Some(id.to_string()), msg.to_string()), _ => (None, trimmed_line), }; let event = match event_id { Some(id) => SseEvent::default() .with_data(message) .with_id(id) .as_bytes(), None => SseEvent::default().with_data(message).as_bytes(), }; Some((Ok(event), reader)) } Err(e) => Some((Err(e), reader)), } } }); // create a stream body let streaming_body: GenericBody = http_body_util::BodyExt::boxed(StreamBody::new(message_stream.map(|res| { res.map(Frame::data) .map_err(|err: std::io::Error| TransportServerError::HttpError(err.to_string())) }))); let session_id_value = HeaderValue::from_str(&session_id) .map_err(|err| TransportServerError::HttpError(err.to_string()))?; let status_code = if !payload_contains_request { StatusCode::ACCEPTED } else { StatusCode::OK }; let response = http::Response::builder() .status(status_code) .header(CONTENT_TYPE, "text/event-stream") .header(MCP_SESSION_ID_HEADER, session_id_value) .header(CONNECTION, "keep-alive") .body(streaming_body) .map_err(|err| TransportServerError::HttpError(err.to_string()))?; // if last_event_id exists we replay messages from the event-store tokio::spawn(async move { if let Some(last_event_id) = last_event_id { if let Some(event_store) = state.event_store.as_ref() { let events = event_store .events_after(last_event_id) .await .unwrap_or_else(|err| { tracing::error!("{err}"); None }); if let Some(events) = events { for message_payload in events.messages { // skip storing replay messages let error = transport.write_str(&message_payload, true).await; if let Err(error) = error { tracing::trace!("Error replaying message: {error}") } } } } } }); Ok(response) } // TODO: this function will be removed after refactoring the readable stream of the transports // so we would deserialize the string syncronousely and have more control over the flow // this function may incur a slight runtime cost which could be avoided after refactoring fn contains_request(json_str: &str) -> Result<bool, serde_json::Error> { let value: serde_json::Value = serde_json::from_str(json_str)?; match value { serde_json::Value::Object(obj) => Ok(obj.contains_key("id") && obj.contains_key("method")), serde_json::Value::Array(arr) => Ok(arr.iter().any(|item| { item.as_object() .map(|obj| obj.contains_key("id") && obj.contains_key("method")) .unwrap_or(false) })), _ => Ok(false), } } fn is_result(json_str: &str) -> Result<bool, serde_json::Error> { let value: serde_json::Value = serde_json::from_str(json_str)?; match value { serde_json::Value::Object(obj) => Ok(obj.contains_key("result")), serde_json::Value::Array(arr) => Ok(arr.iter().all(|item| { item.as_object() .map(|obj| obj.contains_key("result")) .unwrap_or(false) })), _ => Ok(false), } } pub(crate) async fn create_standalone_stream( session_id: SessionId, last_event_id: Option<EventId>, state: Arc<McpAppState>, auth_info: Option<AuthInfo>, ) -> TransportServerResult<http::Response<GenericBody>> { let runtime = state.session_store.get(&session_id).await.ok_or( TransportServerError::SessionIdInvalid(session_id.to_string()), )?; runtime.update_auth_info(auth_info).await; if runtime.default_stream_exists().await { let error = SdkError::bad_request().with_message("Only one SSE stream is allowed per session"); return error_response(StatusCode::CONFLICT, error) .map_err(|err| TransportServerError::HttpError(err.to_string())); } if let Some(last_event_id) = last_event_id.as_ref() { tracing::trace!( "SSE stream re-connected with last-event-id: {}", last_event_id ); } let mut response = create_sse_stream( runtime.clone(), session_id.clone(), state.clone(), None, true, last_event_id, ) .await?; *response.status_mut() = StatusCode::OK; Ok(response) } pub(crate) async fn start_new_session( state: Arc<McpAppState>, payload: &str, auth_info: Option<AuthInfo>, ) -> TransportServerResult<http::Response<GenericBody>> { let session_id: SessionId = state.id_generator.generate(); let h: Arc<dyn McpServerHandler> = state.handler.clone(); // create a new server instance with unique session_id and let runtime: Arc<ServerRuntime> = server_runtime::create_server_instance( Arc::clone(&state.server_details), h, session_id.to_owned(), auth_info, state.task_store.clone(), state.client_task_store.clone(), ); tracing::info!("a new client joined : {}", &session_id); let response = create_sse_stream( runtime.clone(), session_id.clone(), state.clone(), Some(payload), false, None, ) .await; if response.is_ok() { state .session_store .set(session_id.to_owned(), runtime.clone()) .await; } response } async fn single_shot_stream( runtime: Arc<ServerRuntime>, session_id: SessionId, state: Arc<McpAppState>, payload: Option<&str>, standalone: bool, ) -> TransportServerResult<http::Response<GenericBody>> { // readable stream of string to be used in transport let (read_tx, read_rx) = duplex(DUPLEX_BUFFER_SIZE); // writable stream to deliver message to the client let (write_tx, write_rx) = duplex(DUPLEX_BUFFER_SIZE); let transport = SseTransport::<ClientMessage>::new( read_rx, write_tx, read_tx, Arc::clone(&state.transport_options), ) .map_err(|err| TransportServerError::TransportError(err.to_string()))?; let stream_id = if standalone { DEFAULT_STREAM_ID.to_string() } else { state.id_generator.generate() }; let ping_interval = state.ping_interval; let runtime_clone = Arc::clone(&runtime); let payload_string = payload.map(|p| p.to_string()); tokio::spawn(async move { match runtime_clone .start_stream( Arc::new(transport), &stream_id, ping_interval, payload_string, ) .await { Ok(_) => tracing::info!("stream {} exited gracefully.", &stream_id), Err(err) => tracing::info!("stream {} exited with error : {}", &stream_id, err), } let _ = runtime.remove_transport(&stream_id).await; }); let mut reader = BufReader::new(write_rx); let mut line = String::new(); let response = match reader.read_line(&mut line).await { Ok(0) => None, // EOF Ok(_) => { let trimmed_line = line.trim_end_matches('\n').to_owned(); Some(Ok(trimmed_line)) } Err(e) => Some(Err(e)), }; let session_id_value = HeaderValue::from_str(&session_id) .map_err(|err| TransportServerError::HttpError(err.to_string()))?; match response { Some(response_result) => match response_result { Ok(response_str) => { let body = Full::new(Bytes::from(response_str)) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed(); http::Response::builder() .status(StatusCode::OK) .header(CONTENT_TYPE, "application/json") .header(MCP_SESSION_ID_HEADER, session_id_value) .body(body) .map_err(|err| TransportServerError::HttpError(err.to_string())) } Err(err) => { let body = Full::new(Bytes::from(err.to_string())) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed(); http::Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .header(CONTENT_TYPE, "application/json") .body(body) .map_err(|err| TransportServerError::HttpError(err.to_string())) } }, None => { let body = Full::new(Bytes::from( "End of the transport stream reached.".to_string(), )) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed(); http::Response::builder() .status(StatusCode::UNPROCESSABLE_ENTITY) .header(CONTENT_TYPE, "application/json") .body(body) .map_err(|err| TransportServerError::HttpError(err.to_string())) } } } pub(crate) async fn process_incoming_message_return( session_id: SessionId, state: Arc<McpAppState>, payload: &str, auth_info: Option<AuthInfo>, ) -> TransportServerResult<http::Response<GenericBody>> { match state.session_store.get(&session_id).await { Some(runtime) => { runtime.update_auth_info(auth_info).await; single_shot_stream( runtime.clone(), session_id, state.clone(), Some(payload), false, ) .await // Ok(StatusCode::OK.into_response()) } None => { let error = SdkError::session_not_found(); error_response(StatusCode::NOT_FOUND, error) .map_err(|err| TransportServerError::HttpError(err.to_string())) } } } pub(crate) async fn process_incoming_message( session_id: SessionId, state: Arc<McpAppState>, payload: &str, auth_info: Option<AuthInfo>, ) -> TransportServerResult<http::Response<GenericBody>> { match state.session_store.get(&session_id).await { Some(runtime) => { runtime.update_auth_info(auth_info).await; // when receiving a result in a streamable_http server, that means it was sent by the standalone sse transport // it should be processed by the same transport , therefore no need to call create_sse_stream let Ok(is_result) = is_result(payload) else { return error_response(StatusCode::BAD_REQUEST, SdkError::parse_error()); }; if is_result { match runtime.consume_payload_string(payload).await { Ok(()) => { let body = Full::new(Bytes::new()) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed(); http::Response::builder() .status(200) .header("Content-Type", "application/json") .body(body) .map_err(|err| TransportServerError::HttpError(err.to_string())) } Err(err) => { let error = SdkError::internal_error().with_message(err.to_string().as_ref()); error_response(StatusCode::BAD_REQUEST, error) } } } else { create_sse_stream( runtime.clone(), session_id.clone(), state.clone(), Some(payload), false, None, ) .await } } None => { let error = SdkError::session_not_found(); error_response(StatusCode::NOT_FOUND, error) } } } pub(crate) fn is_empty_sse_message(sse_payload: &str) -> bool { sse_payload.is_empty() || sse_payload.trim() == ":" } pub(crate) async fn delete_session( session_id: SessionId, state: Arc<McpAppState>, ) -> TransportServerResult<http::Response<GenericBody>> { match state.session_store.get(&session_id).await { Some(runtime) => { runtime.shutdown().await; state.session_store.delete(&session_id).await; tracing::info!("client disconnected : {}", &session_id); let body = Full::new(Bytes::from("ok")) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed(); http::Response::builder() .status(200) .header("Content-Type", "application/json") .body(body) .map_err(|err| TransportServerError::HttpError(err.to_string())) } None => { let error = SdkError::session_not_found(); error_response(StatusCode::NOT_FOUND, error) } } } pub(crate) fn acceptable_content_type(headers: &HeaderMap) -> bool { let accept_header = headers .get("content-type") .and_then(|val| val.to_str().ok()) .unwrap_or(""); accept_header .split(',') .any(|val| val.trim().starts_with("application/json")) } pub(crate) fn validate_mcp_protocol_version_header(headers: &HeaderMap) -> SdkResult<()> { let protocol_version_header = headers .get(MCP_PROTOCOL_VERSION_HEADER) .and_then(|val| val.to_str().ok()) .unwrap_or(""); // requests without protocol version header are acceptable if protocol_version_header.is_empty() { return Ok(()); } validate_mcp_protocol_version(protocol_version_header) } pub(crate) fn accepts_event_stream(headers: &HeaderMap) -> bool { let accept_header = headers .get(ACCEPT) .and_then(|val| val.to_str().ok()) .unwrap_or(""); accept_header .split(',') .any(|val| val.trim().starts_with("text/event-stream")) } pub(crate) fn valid_streaming_http_accept_header(headers: &HeaderMap) -> bool { let accept_header = headers .get(ACCEPT) .and_then(|val| val.to_str().ok()) .unwrap_or(""); let types: Vec<_> = accept_header.split(',').map(|v| v.trim()).collect(); let has_event_stream = types.iter().any(|v| v.starts_with("text/event-stream")); let has_json = types.iter().any(|v| v.starts_with("application/json")); has_event_stream && has_json } pub fn error_response( status_code: StatusCode, error: SdkError, ) -> TransportServerResult<http::Response<GenericBody>> { let error_string = serde_json::to_string(&error).unwrap_or_default(); let body = Full::new(Bytes::from(error_string)) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed(); http::Response::builder() .status(status_code) .header(CONTENT_TYPE, "application/json") .body(body) .map_err(|err| TransportServerError::HttpError(err.to_string())) } /// Extracts the value of a query parameter from an HTTP request by key. /// /// This function parses the query string from the request URI and searches /// for the specified key. If found, it returns the corresponding value as a `String`. /// /// # Arguments /// * `request` - The HTTP request containing the URI with the query string. /// * `key` - The name of the query parameter to retrieve. /// /// # Returns /// * `Some(String)` containing the value of the query parameter if found. /// * `None` if the query string is missing or the key is not present. /// pub(crate) fn query_param(request: &http::Request<&str>, key: &str) -> Option<String> { request.uri().query().and_then(|query| { for pair in query.split('&') { let mut split = pair.splitn(2, '='); let k = split.next()?; let v = split.next().unwrap_or(""); if k == key { return Some(v.to_string()); } } None }) } #[cfg(feature = "sse")] pub(crate) async fn handle_sse_connection( state: Arc<McpAppState>, sse_message_endpoint: Option<&str>, auth_info: Option<AuthInfo>, ) -> TransportServerResult<http::Response<GenericBody>> { let session_id: SessionId = state.id_generator.generate(); let sse_message_endpoint = sse_message_endpoint.unwrap_or(DEFAULT_MESSAGES_ENDPOINT); let messages_endpoint = SseTransport::<ClientMessage>::message_endpoint(sse_message_endpoint, &session_id); // readable stream of string to be used in transport // writing string to read_tx will be received as messages inside the transport and messages will be processed let (read_tx, read_rx) = duplex(DUPLEX_BUFFER_SIZE); // writable stream to deliver message to the client let (write_tx, write_rx) = duplex(DUPLEX_BUFFER_SIZE); // / create a transport for sending/receiving messages let Ok(transport) = SseTransport::new( read_rx, write_tx, read_tx, Arc::clone(&state.transport_options), ) else { return Err(TransportServerError::TransportError( "Failed to create SSE transport".to_string(), )); }; let h: Arc<dyn McpServerHandler> = state.handler.clone(); // create a new server instance with unique session_id and let server: Arc<ServerRuntime> = server_runtime::create_server_instance( Arc::clone(&state.server_details), h, session_id.to_owned(), auth_info, state.task_store.clone(), state.client_task_store.clone(), ); state .session_store .set(session_id.to_owned(), server.clone()) .await; tracing::info!("A new client joined : {}", session_id.to_owned()); // Start the server tokio::spawn(async move { match server .start_stream( Arc::new(transport), DEFAULT_STREAM_ID, state.ping_interval, None, ) .await { Ok(_) => tracing::info!("server {} exited gracefully.", session_id.to_owned()), Err(err) => tracing::info!( "server {} exited with error : {}", session_id.to_owned(), err ), }; state.session_store.delete(&session_id).await; }); // Initial SSE message to inform the client about the server's endpoint let initial_sse_event = stream::once(async move { initial_sse_event(&messages_endpoint) }); // Construct SSE stream let reader = BufReader::new(write_rx); let message_stream = stream::unfold(reader, |mut reader| async move { let mut line = String::new(); match reader.read_line(&mut line).await { Ok(0) => None, // EOF Ok(_) => { let trimmed_line = line.trim_end_matches('\n').to_owned(); Some(( Ok(SseEvent::default().with_data(trimmed_line).as_bytes()), reader, )) } Err(_) => None, // Err(e) => Some((Err(e), reader)), } }); let stream = initial_sse_event.chain(message_stream); // create a stream body let streaming_body: GenericBody = http_body_util::BodyExt::boxed(StreamBody::new(stream.map(|res| res.map(Frame::data)))); let response = http::Response::builder() .status(StatusCode::OK) .header(CONTENT_TYPE, "text/event-stream") .header(CONNECTION, "keep-alive") .body(streaming_body) .map_err(|err| TransportServerError::HttpError(err.to_string()))?; Ok(response) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/mcp_http_handler.rs
crates/rust-mcp-sdk/src/mcp_http/mcp_http_handler.rs
#[cfg(feature = "sse")] use super::http_utils::handle_sse_connection; use super::http_utils::{ accepts_event_stream, error_response, query_param, validate_mcp_protocol_version_header, }; use super::types::GenericBody; use crate::auth::AuthInfo; #[cfg(feature = "auth")] use crate::auth::AuthProvider; use crate::mcp_http::{middleware::compose, BoxFutureResponse, Middleware, RequestHandler}; use crate::mcp_http::{GenericBodyExt, RequestExt}; use crate::mcp_server::error::TransportServerError; use crate::schema::schema_utils::SdkError; #[cfg(any(feature = "sse", feature = "streamable-http"))] use crate::{ error::McpSdkError, mcp_http::{ http_utils::{ acceptable_content_type, create_standalone_stream, delete_session, process_incoming_message, process_incoming_message_return, start_new_session, valid_streaming_http_accept_header, }, McpAppState, }, mcp_server::error::TransportServerResult, utils::valid_initialize_method, }; use http::{self, HeaderMap, Method, StatusCode, Uri}; use rust_mcp_transport::{SessionId, MCP_LAST_EVENT_ID_HEADER, MCP_SESSION_ID_HEADER}; use std::sync::Arc; /// A helper macro to wrap an async handler method into a `RequestHandler` /// and compose it with middlewares. /// /// # Example /// ```ignore /// let handle = with_middlewares!(self, Self::internal_handle_sse_message); /// handle /// /// // OR /// let handler = with_middlewares!(self, Self::internal_handle_sse_message, extra_middlewares1, extra_middlewares2); /// ``` #[macro_export] macro_rules! with_middlewares { ($self:ident, $handler:path) => {{ let final_handler: RequestHandler = Box::new( move |req: http::Request<&str>, state: std::sync::Arc<McpAppState>| -> BoxFutureResponse<'_> { Box::pin(async move { $handler(req, state).await }) }, ); $crate::mcp_http::middleware::compose(&$self.middlewares, final_handler) }}; // Handler + extra middleware(s) ($self:ident, $handler:path, $($extra:expr),+ $(,)?) => {{ let final_handler: RequestHandler = Box::new( move |req: http::Request<&str>, state: std::sync::Arc<McpAppState>| -> BoxFutureResponse<'_> { Box::pin(async move { $handler(req, state).await }) }, ); // Chain $self.middlewares with any extra middleware iterators let all = $self.middlewares.iter() $(.chain($extra.iter()))+; $crate::mcp_http::middleware::compose(all, final_handler) }}; } #[derive(Clone)] pub struct McpHttpHandler { #[cfg(feature = "auth")] auth: Option<Arc<dyn AuthProvider>>, middlewares: Vec<Arc<dyn Middleware>>, } impl McpHttpHandler { #[cfg(feature = "auth")] pub fn new(auth: Option<Arc<dyn AuthProvider>>, middlewares: Vec<Arc<dyn Middleware>>) -> Self { McpHttpHandler { auth, middlewares } } #[cfg(not(feature = "auth"))] pub fn new(middlewares: Vec<Arc<dyn Middleware>>) -> Self { McpHttpHandler { middlewares } } pub fn add_middleware<M: Middleware + 'static>(&mut self, middleware: M) { let m: Arc<dyn Middleware> = Arc::new(middleware); self.middlewares.push(m); } /// An `http::Request<&str>` initialized with the specified method, URI, headers, and body. /// If the `body` is `None`, an empty string is used as the default. /// pub fn create_request( method: Method, uri: Uri, headers: HeaderMap, body: Option<&str>, ) -> http::Request<&str> { let mut request = http::Request::default(); *request.method_mut() = method; *request.uri_mut() = uri; *request.body_mut() = body.unwrap_or_default(); let req_headers = request.headers_mut(); for (key, value) in headers { if let Some(k) = key { req_headers.insert(k, value); } } request } } // auth related methods #[cfg(feature = "auth")] impl McpHttpHandler { pub fn oauth_endppoints(&self) -> Option<Vec<&String>> { self.auth .as_ref() .and_then(|a| a.auth_endpoints().map(|e| e.keys().collect::<Vec<_>>())) } pub async fn handle_auth_requests( &self, request: http::Request<&str>, state: Arc<McpAppState>, ) -> TransportServerResult<http::Response<GenericBody>> { let Some(auth_provider) = self.auth.as_ref() else { return Err(TransportServerError::HttpError( "Authentication is not supported by this server.".to_string(), )); }; let auth_provider = auth_provider.clone(); let final_handler: RequestHandler = Box::new(move |req, state| { Box::pin(async move { use futures::TryFutureExt; auth_provider .handle_request(req, state) .map_err(|e| e) .await }) }); let handle = compose(&[], final_handler); handle(request, state).await } } impl McpHttpHandler { /// Handles an MCP connection using the SSE (Server-Sent Events) transport. /// /// This function serves as the entry point for initializing and managing a client connection /// over SSE when the `sse` feature is enabled. /// /// # Arguments /// * `state` - Shared application state required to manage the MCP session. /// * `sse_message_endpoint` - Optional message endpoint to override the default SSE route (default: `/messages` ). /// /// /// # Features /// This function is only available when the `sse` feature is enabled. #[cfg(feature = "sse")] pub async fn handle_sse_connection( &self, request: http::Request<&str>, state: Arc<McpAppState>, sse_message_endpoint: Option<&str>, ) -> TransportServerResult<http::Response<GenericBody>> { use crate::auth::AuthInfo; use crate::mcp_http::RequestExt; let (request, auth_info) = request.take::<AuthInfo>(); let sse_endpoint = sse_message_endpoint.map(|s| s.to_string()); let final_handler: RequestHandler = Box::new(move |_req, state| { Box::pin(async move { handle_sse_connection(state, sse_endpoint.as_deref(), auth_info).await }) }); let handle = compose(&self.middlewares, final_handler); handle(request, state).await } /// Handles incoming MCP messages from the client after an SSE connection is established. /// /// This function processes a message sent by the client as part of an active SSE session. It: /// - Extracts the `sessionId` from the request query parameters. /// - Locates the corresponding session's transmit channel. /// - Forwards the incoming message payload to the MCP transport stream for consumption. /// # Arguments /// * `request` - The HTTP request containing the message body and query parameters (including `sessionId`). /// * `state` - Shared application state, including access to the session store. /// /// # Returns /// * `TransportServerResult<http::Response<GenericBody>>`: /// - Returns a `202 Accepted` HTTP response if the message is successfully forwarded. /// - Returns an error if the session ID is missing, invalid, or if any I/O issues occur while processing the message. /// /// # Errors /// - `SessionIdMissing`: if the `sessionId` query parameter is not present. /// - `SessionIdInvalid`: if the session ID does not map to a valid session in the session store. /// - `StreamIoError`: if an error occurs while writing to the stream. /// - `HttpError`: if constructing the HTTP response fails. #[cfg(feature = "sse")] pub async fn handle_sse_message( &self, request: http::Request<&str>, state: Arc<McpAppState>, ) -> TransportServerResult<http::Response<GenericBody>> { let handle = with_middlewares!(self, Self::internal_handle_sse_message); handle(request, state).await } /// Handles incoming MCP messages over the StreamableHTTP transport. /// /// It supports `GET`, `POST`, and `DELETE` methods for handling streaming operations, and performs optional /// DNS rebinding protection if it is configured. /// /// # Arguments /// * `request` - The HTTP request from the client, including method, headers, and optional body. /// * `state` - Shared application state, including configuration and session management. /// /// # Behavior /// - If DNS rebinding protection is enabled via the app state, the function checks the request headers. /// If dns protection fails, a `403 Forbidden` response is returned. /// - Dispatches the request to method-specific handlers based on the HTTP method: /// - `GET` → `handle_http_get` /// - `POST` → `handle_http_post` /// - `DELETE` → `handle_http_delete` /// - Returns `405 Method Not Allowed` for unsupported methods. /// /// # Returns /// * A `TransportServerResult` wrapping an HTTP response indicating success or failure of the operation. /// pub async fn handle_streamable_http( &self, request: http::Request<&str>, state: Arc<McpAppState>, ) -> TransportServerResult<http::Response<GenericBody>> { let handle = with_middlewares!(self, Self::internal_handle_streamable_http); handle(request, state).await } async fn internal_handle_sse_message( request: http::Request<&str>, state: Arc<McpAppState>, ) -> TransportServerResult<http::Response<GenericBody>> { let session_id = query_param(&request, "sessionId").ok_or(TransportServerError::SessionIdMissing)?; // transmit to the readable stream, that transport is reading from let transmit = state.session_store.get(&session_id).await.ok_or( TransportServerError::SessionIdInvalid(session_id.to_string()), )?; let message = request.body(); transmit .consume_payload_string(message.as_ref()) .await .map_err(|err| { tracing::trace!("{}", err); TransportServerError::StreamIoError(err.to_string()) })?; http::Response::builder() .status(StatusCode::ACCEPTED) .body(GenericBody::empty()) .map_err(|err| TransportServerError::HttpError(err.to_string())) } async fn internal_handle_streamable_http( request: http::Request<&str>, state: Arc<McpAppState>, ) -> TransportServerResult<http::Response<GenericBody>> { let (request, auth_info) = request.take::<AuthInfo>(); let method = request.method(); let response = match method { &http::Method::GET => return Self::handle_http_get(request, state, auth_info).await, &http::Method::POST => return Self::handle_http_post(request, state, auth_info).await, &http::Method::DELETE => return Self::handle_http_delete(request, state).await, other => { let error = SdkError::bad_request().with_message(&format!( "'{other}' is not a valid HTTP method for StreamableHTTP transport." )); error_response(StatusCode::METHOD_NOT_ALLOWED, error) } }; response } /// Processes POST requests for the Streamable HTTP Protocol async fn handle_http_post( request: http::Request<&str>, state: Arc<McpAppState>, auth_info: Option<AuthInfo>, ) -> TransportServerResult<http::Response<GenericBody>> { let headers = request.headers(); if !valid_streaming_http_accept_header(headers) { let error = SdkError::bad_request() .with_message(r#"Client must accept both application/json and text/event-stream"#); return error_response(StatusCode::NOT_ACCEPTABLE, error); } if !acceptable_content_type(headers) { let error = SdkError::bad_request() .with_message(r#"Unsupported Media Type: Content-Type must be application/json"#); return error_response(StatusCode::UNSUPPORTED_MEDIA_TYPE, error); } if let Err(parse_error) = validate_mcp_protocol_version_header(headers) { let error = SdkError::bad_request() .with_message(format!(r#"Bad Request: {parse_error}"#).as_str()); return error_response(StatusCode::BAD_REQUEST, error); } let session_id: Option<SessionId> = headers .get(MCP_SESSION_ID_HEADER) .and_then(|value| value.to_str().ok()) .map(|s| s.to_string()); let payload = request.body(); let response = match session_id { // has session-id => write to the existing stream Some(id) => { if state.enable_json_response { process_incoming_message_return(id, state, payload, auth_info).await } else { process_incoming_message(id, state, payload, auth_info).await } } None => match valid_initialize_method(payload) { Ok(_) => { return start_new_session(state, payload, auth_info).await; } Err(McpSdkError::SdkError(error)) => error_response(StatusCode::BAD_REQUEST, error), Err(error) => { let error = SdkError::bad_request().with_message(&error.to_string()); error_response(StatusCode::BAD_REQUEST, error) } }, }; response } /// Processes GET requests for the Streamable HTTP Protocol async fn handle_http_get( request: http::Request<&str>, state: Arc<McpAppState>, auth_info: Option<AuthInfo>, ) -> TransportServerResult<http::Response<GenericBody>> { let headers = request.headers(); if !accepts_event_stream(headers) { let error = SdkError::bad_request().with_message(r#"Client must accept text/event-stream"#); return error_response(StatusCode::NOT_ACCEPTABLE, error); } if let Err(parse_error) = validate_mcp_protocol_version_header(headers) { let error = SdkError::bad_request() .with_message(format!(r#"Bad Request: {parse_error}"#).as_str()); return error_response(StatusCode::BAD_REQUEST, error); } let session_id: Option<SessionId> = headers .get(MCP_SESSION_ID_HEADER) .and_then(|value| value.to_str().ok()) .map(|s| s.to_string()); let last_event_id: Option<SessionId> = headers .get(MCP_LAST_EVENT_ID_HEADER) .and_then(|value| value.to_str().ok()) .map(|s| s.to_string()); let response = match session_id { Some(session_id) => { let res = create_standalone_stream(session_id, last_event_id, state, auth_info).await; res } None => { let error = SdkError::bad_request().with_message("Bad request: session not found"); error_response(StatusCode::BAD_REQUEST, error) } }; response } /// Processes DELETE requests for the Streamable HTTP Protocol async fn handle_http_delete( request: http::Request<&str>, state: Arc<McpAppState>, ) -> TransportServerResult<http::Response<GenericBody>> { let headers = request.headers(); if let Err(parse_error) = validate_mcp_protocol_version_header(headers) { let error = SdkError::bad_request() .with_message(format!(r#"Bad Request: {parse_error}"#).as_str()); return error_response(StatusCode::BAD_REQUEST, error); } let session_id: Option<SessionId> = headers .get(MCP_SESSION_ID_HEADER) .and_then(|value| value.to_str().ok()) .map(|s| s.to_string()); let response = match session_id { Some(id) => delete_session(id, state).await, None => { let error = SdkError::bad_request().with_message("Bad Request: Session not found"); error_response(StatusCode::BAD_REQUEST, error) } }; response } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/middleware.rs
crates/rust-mcp-sdk/src/mcp_http/middleware.rs
#[cfg(feature = "auth")] mod auth_middleware; mod cors_middleware; mod dns_rebind_protector; pub mod logging_middleware; use super::types::{GenericBody, RequestHandler}; use crate::mcp_http::{McpAppState, MiddlewareNext}; use crate::mcp_server::error::TransportServerResult; #[cfg(feature = "auth")] pub(crate) use auth_middleware::*; pub use cors_middleware::*; pub(crate) use dns_rebind_protector::*; use http::{Request, Response}; use std::sync::Arc; #[async_trait::async_trait] pub trait Middleware: Send + Sync + 'static { async fn handle<'req>( &self, req: Request<&'req str>, state: Arc<McpAppState>, next: MiddlewareNext<'req>, ) -> TransportServerResult<Response<GenericBody>>; } /// Build the final handler by folding the middlewares **in reverse**. /// Each middleware and handler is consumed exactly once. pub fn compose<'a, I>(middlewares: I, final_handler: RequestHandler) -> RequestHandler where I: IntoIterator<Item = &'a Arc<dyn Middleware>>, I::IntoIter: DoubleEndedIterator, { // Start with the final handler let mut handler = final_handler; // Fold middlewares in reverse order for mw in middlewares.into_iter().rev() { let mw = Arc::clone(mw); let next = handler; // Each loop iteration consumes `next` and returns a new boxed FnOnce handler = Box::new(move |req: Request<&str>, state: Arc<McpAppState>| { let mw = Arc::clone(&mw); Box::pin(async move { mw.handle(req, state, next).await }) }); } handler } #[cfg(test)] mod tests { use super::*; use crate::mcp_icon; use crate::schema::{Implementation, InitializeResult, ProtocolVersion, ServerCapabilities}; use crate::{ id_generator::{FastIdGenerator, UuidGenerator}, mcp_http::{ middleware::{cors_middleware::CorsMiddleware, logging_middleware::LoggingMiddleware}, types::GenericBodyExt, }, mcp_server::{error::TransportServerError, ServerHandler, ToMcpServerHandler}, session_store::InMemorySessionStore, }; use async_trait::async_trait; use http::{HeaderName, Request, Response, StatusCode}; use http_body_util::BodyExt; use std::{ sync::{Arc, Mutex}, time::Duration, }; struct TestHandler; impl ServerHandler for TestHandler {} fn app_state() -> Arc<McpAppState> { let handler = TestHandler {}; Arc::new(McpAppState { session_store: Arc::new(InMemorySessionStore::new()), id_generator: Arc::new(UuidGenerator {}), stream_id_gen: Arc::new(FastIdGenerator::new(Some("s_"))), server_details: Arc::new(InitializeResult { capabilities: ServerCapabilities { ..Default::default() }, instructions: None, meta: None, protocol_version: ProtocolVersion::V2025_06_18.to_string(), server_info: Implementation { name: "server".to_string(), title: None, version: "0.1.0".to_string(), description: Some("test Server, by Rust MCP SDK".to_string()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".to_string()), }, }), handler: handler.to_mcp_server_handler(), ping_interval: Duration::from_secs(15), transport_options: Arc::new(rust_mcp_transport::TransportOptions::default()), enable_json_response: false, event_store: None, task_store:None, client_task_store:None }) } /// Helper: Convert response to string async fn response_string(res: Response<GenericBody>) -> String { let (_parts, body) = res.into_parts(); let bytes = body.collect().await.unwrap().to_bytes(); String::from_utf8(bytes.to_vec()).unwrap() } /// Test Middleware – records everything, modifies req/res, supports early return #[derive(Clone)] struct TestMiddleware { id: usize, request_calls: Arc<Mutex<Vec<(usize, String, Vec<(String, String)>)>>>, response_calls: Arc<Mutex<Vec<(usize, u16, Vec<(String, String)>)>>>, add_req_header: Option<(String, String)>, add_res_header: Option<(String, String)>, // ---- early return (clone-able) ---- early_return_status: Option<StatusCode>, early_return_body: Option<String>, fail_request: bool, fail_response: bool, } impl TestMiddleware { fn new(id: usize) -> Self { Self { id, request_calls: Arc::new(Mutex::new(Vec::new())), response_calls: Arc::new(Mutex::new(Vec::new())), add_req_header: None, add_res_header: None, early_return_status: None, early_return_body: None, fail_request: false, fail_response: false, } } fn with_req_header(mut self, name: &str, value: &str) -> Self { self.add_req_header = Some((name.to_string(), value.to_string())); self } fn with_res_header(mut self, name: &str, value: &str) -> Self { self.add_res_header = Some((name.to_string(), value.to_string())); self } fn early_return_200(mut self) -> Self { self.early_return_status = Some(StatusCode::OK); self.early_return_body = Some(format!("early-{}", self.id)); self } #[allow(unused)] fn early_return(mut self, status: StatusCode, body: impl Into<String>) -> Self { self.early_return_status = Some(status); self.early_return_body = Some(body.into()); self } fn fail_request(mut self) -> Self { self.fail_request = true; self } fn fail_response(mut self) -> Self { self.fail_response = true; self } } #[async_trait] impl Middleware for TestMiddleware { async fn handle<'req>( &self, mut req: Request<&'req str>, state: Arc<McpAppState>, next: MiddlewareNext<'req>, ) -> TransportServerResult<Response<GenericBody>> { // ---- record request ------------------------------------------------- let headers = req .headers() .iter() .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string())) .collect(); self.request_calls .lock() .unwrap() .push((self.id, req.body().to_string(), headers)); if self.fail_request { return Err(TransportServerError::HttpError(format!( "middleware {} failed request", self.id ))); } // ---- add request header -------------------------------------------- if let Some((name, value)) = &self.add_req_header { req.headers_mut().insert( HeaderName::from_bytes(name.as_bytes()).unwrap(), value.parse().unwrap(), ); } // ---- early return --------------------------------------------------- if let (Some(status), Some(body)) = (&self.early_return_status, &self.early_return_body) { return Ok(Response::builder() .status(*status) .body(GenericBody::from_string(body.to_string())) .unwrap()); } // ---- call next ------------------------------------------------------ let mut res = next(req, state).await?; // ---- add response header -------------------------------------------- if let Some((name, value)) = &self.add_res_header { res.headers_mut().insert( HeaderName::from_bytes(name.as_bytes()).unwrap(), value.parse().unwrap(), ); } if self.fail_response { return Err(TransportServerError::HttpError(format!( "middleware {} failed response", self.id ))); } // ---- record response ------------------------------------------------ let headers = res .headers() .iter() .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string())) .collect(); self.response_calls .lock() .unwrap() .push((self.id, res.status().as_u16(), headers)); Ok(res) } } /// Final handler – returns a fixed response fn final_handler(body: &'static str, status: StatusCode) -> RequestHandler { Box::new(move |_req, _| { let resp = Response::builder() .status(status) .body(GenericBody::from_string(body.to_string())) .unwrap(); Box::pin(async move { Ok(resp) }) }) } // TESTS /// Middleware order (request → final → response) #[tokio::test] async fn test_middleware_order() { let mw1 = Arc::new(TestMiddleware::new(1)); let mw2 = Arc::new(TestMiddleware::new(2)); let mw3 = Arc::new(TestMiddleware::new(3)); let middlewares: Vec<Arc<dyn Middleware>> = vec![mw1.clone(), mw2.clone(), mw3.clone()]; let handler = final_handler("final", StatusCode::OK); let composed = compose(&middlewares, handler); let req = Request::builder().body("").unwrap(); let _ = composed(req, app_state()).await.unwrap(); // request order: 3 → 2 → 1 → final let rc3 = mw3.request_calls.lock().unwrap(); let rc2 = mw2.request_calls.lock().unwrap(); let rc1 = mw1.request_calls.lock().unwrap(); assert_eq!(rc3[0].0, 3); assert_eq!(rc2[0].0, 2); assert_eq!(rc1[0].0, 1); // response order: 1 → 2 → 3 let pc1 = mw1.response_calls.lock().unwrap(); let pc2 = mw2.response_calls.lock().unwrap(); let pc3 = mw3.response_calls.lock().unwrap(); assert_eq!(pc1[0].0, 1); assert_eq!(pc2[0].0, 2); assert_eq!(pc3[0].0, 3); } /// Request header added by earlier middleware is visible later #[tokio::test] async fn test_request_header_propagation() { let mw1 = Arc::new(TestMiddleware::new(1).with_req_header("x-mid", "1")); let mw2 = Arc::new(TestMiddleware::new(2)); let middlewares: Vec<Arc<dyn Middleware>> = vec![mw1.clone(), mw2.clone()]; let handler = final_handler("ok", StatusCode::OK); let composed = compose(&middlewares, handler); let req = Request::builder().body("").unwrap(); let _ = composed(req, app_state()).await.unwrap(); let rc = mw2.request_calls.lock().unwrap(); let hdr = rc[0].2.iter().find(|(k, _)| k == "x-mid").map(|(_, v)| v); assert_eq!(hdr, Some(&"1".to_string())); } /// Response header added by later middleware is visible earlier #[tokio::test] async fn test_response_header_propagation() { let mw1 = Arc::new(TestMiddleware::new(1)); let mw2 = Arc::new(TestMiddleware::new(2).with_res_header("x-mid", "1")); let middlewares: Vec<Arc<dyn Middleware>> = vec![mw1.clone(), mw2.clone()]; let handler = final_handler("ok", StatusCode::OK); let composed = compose(&middlewares, handler); let req = Request::builder().body("").unwrap(); let res = composed(req, app_state()).await.unwrap(); let pc1 = mw1.response_calls.lock().unwrap(); let hdr = pc1[0].2.iter().find(|(k, _)| k == "x-mid").map(|(_, v)| v); assert_eq!(hdr, Some(&"1".to_string())); assert_eq!(res.headers().get("x-mid").unwrap().to_str().unwrap(), "1"); } /// Early return stops the chain #[tokio::test] async fn test_early_return_stops_chain() { let mw1 = Arc::new(TestMiddleware::new(1).early_return_200()); let mw2 = Arc::new(TestMiddleware::new(2)); let mw3 = Arc::new(TestMiddleware::new(3)); let middlewares: Vec<Arc<dyn Middleware>> = vec![mw1.clone(), mw2.clone(), mw3.clone()]; let handler = final_handler("should-not-see", StatusCode::OK); let composed = compose(&middlewares, handler); let req = Request::builder().body("").unwrap(); let res = composed(req, app_state()).await.unwrap(); assert_eq!(response_string(res).await, "early-1"); assert!(mw2.request_calls.lock().unwrap().is_empty()); assert!(mw3.request_calls.lock().unwrap().is_empty()); } /// Request error stops response processing #[tokio::test] async fn test_request_error_stops_response_chain() { let mw1 = Arc::new(TestMiddleware::new(1).fail_request()); let mw2 = Arc::new(TestMiddleware::new(2)); let middlewares: Vec<Arc<dyn Middleware>> = vec![mw1.clone(), mw2.clone()]; let handler = final_handler("ok", StatusCode::OK); let composed = compose(&middlewares, handler); let req = Request::builder().body("").unwrap(); let result = composed(req, app_state()).await; assert!(result.is_err()); assert!(mw2.request_calls.lock().unwrap().is_empty()); assert!(mw2.response_calls.lock().unwrap().is_empty()); } ///Response error after next() #[tokio::test] async fn test_response_error_after_next() { let mw1 = Arc::new(TestMiddleware::new(1).fail_response()); let mw2 = Arc::new(TestMiddleware::new(2)); let middlewares: Vec<Arc<dyn Middleware>> = vec![mw1.clone(), mw2.clone()]; let handler = final_handler("ok", StatusCode::OK); let composed = compose(&middlewares, handler); let req = Request::builder().body("").unwrap(); let result = composed(req, app_state()).await; assert!(result.is_err()); assert!(!mw1.request_calls.lock().unwrap().is_empty()); // response_calls is empty because we error before recording assert!(mw1.response_calls.lock().unwrap().is_empty()); } /// No middleware → direct handler #[tokio::test] async fn test_no_middleware() { let middlewares: Vec<Arc<dyn Middleware>> = vec![]; let handler = final_handler("direct", StatusCode::IM_A_TEAPOT); let composed = compose(&middlewares, handler); let req = Request::builder().body("").unwrap(); let res = composed(req, app_state()).await.unwrap(); assert_eq!(res.status(), StatusCode::IM_A_TEAPOT); assert_eq!(response_string(res).await, "direct"); } /// Multiple headers accumulate correctly #[tokio::test] async fn test_multiple_headers_accumulate() { let mw1 = Arc::new( TestMiddleware::new(1) .with_req_header("x-a", "1") .with_res_header("x-b", "1"), ); let mw2 = Arc::new( TestMiddleware::new(2) .with_req_header("x-c", "2") .with_res_header("x-d", "2"), ); let mw3 = Arc::new(TestMiddleware::new(3)); let middlewares: Vec<Arc<dyn Middleware>> = vec![mw1.clone(), mw2.clone(), mw3.clone()]; let handler = final_handler("ok", StatusCode::OK); let composed = compose(&middlewares, handler); let req = Request::builder().body("").unwrap(); let res = composed(req, app_state()).await.unwrap(); let h = res.headers(); assert_eq!(h["x-b"], "1"); assert_eq!(h["x-d"], "2"); // Request headers are NOT in response assert!(!h.contains_key("x-a")); assert!(!h.contains_key("x-c")); // But they were added to the request let req_calls_mw3 = mw3.request_calls.lock().unwrap(); let req_headers = &req_calls_mw3[0].2; assert!(req_headers.iter().any(|(k, v)| k == "x-a" && v == "1")); assert!(req_headers.iter().any(|(k, v)| k == "x-c" && v == "2")); } /// Request body is passed unchanged #[tokio::test] async fn test_request_body_unchanged() { let mw1 = Arc::new(TestMiddleware::new(1)); let mw2 = Arc::new(TestMiddleware::new(2)); let middlewares: Vec<Arc<dyn Middleware>> = vec![mw1.clone(), mw2.clone()]; let handler: RequestHandler = Box::new(move |req, _| { let body = req.into_body().to_string(); Box::pin(async move { Ok(Response::builder() .body(GenericBody::from_string(format!("echo:{body}"))) .unwrap()) }) }); let composed = compose(&middlewares, handler); let req = Request::builder().body("secret-payload").unwrap(); let res = composed(req, app_state()).await.unwrap(); assert_eq!(response_string(res).await, "echo:secret-payload"); } // Integration: CORS + Logger (order matters) #[tokio::test] async fn test_cors_and_logger_integration() { let cors = Arc::new(CorsMiddleware::permissive()); let logger = Arc::new(LoggingMiddleware); // Order in the vector is the order they are *registered*. // compose folds in reverse, so logger runs *first* (request) and *last* (response). let middlewares: Vec<Arc<dyn Middleware>> = vec![cors.clone(), logger.clone()]; let handler = final_handler("ok", StatusCode::OK); let composed = compose(&middlewares, handler); let req = Request::builder() .method(http::Method::GET) .uri("/api") .header("Origin", "https://example.com") .body("") .unwrap(); let res = composed(req, app_state()).await.unwrap(); // CORS headers added by CorsMiddleware assert_eq!( res.headers()["access-control-allow-origin"], "https://example.com" ); assert_eq!(res.headers()["access-control-allow-credentials"], "true"); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/app_state.rs
crates/rust-mcp-sdk/src/mcp_http/app_state.rs
use crate::mcp_traits::McpServerHandler; use crate::session_store::SessionStore; use crate::task_store::{ClientTaskStore, ServerTaskStore}; use crate::{id_generator::FastIdGenerator, mcp_traits::IdGenerator, schema::InitializeResult}; use rust_mcp_transport::event_store::EventStore; use rust_mcp_transport::{SessionId, TransportOptions}; use std::{sync::Arc, time::Duration}; /// Application state struct for the Hyper ser /// /// Holds shared, thread-safe references to session storage, ID generator, /// server details, handler, ping interval, and transport options. #[derive(Clone)] pub struct McpAppState { pub session_store: Arc<dyn SessionStore>, pub id_generator: Arc<dyn IdGenerator<SessionId>>, pub stream_id_gen: Arc<FastIdGenerator>, pub server_details: Arc<InitializeResult>, pub handler: Arc<dyn McpServerHandler>, pub ping_interval: Duration, pub transport_options: Arc<TransportOptions>, pub enable_json_response: bool, /// Event store for resumability support /// If provided, resumability will be enabled, allowing clients to reconnect and resume messages pub event_store: Option<Arc<dyn EventStore>>, pub task_store: Option<Arc<ServerTaskStore>>, pub client_task_store: Option<Arc<ClientTaskStore>>, }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/types.rs
crates/rust-mcp-sdk/src/mcp_http/types.rs
use crate::{ mcp_http::McpAppState, mcp_server::error::{TransportServerError, TransportServerResult}, }; use bytes::Bytes; use futures::future::BoxFuture; use http::{ header::{ALLOW, CONTENT_TYPE}, HeaderMap, HeaderName, HeaderValue, Method, Request, Response, StatusCode, }; use http_body_util::{combinators::BoxBody, BodyExt, Full}; use serde_json::Value; use std::sync::Arc; pub type GenericBody = BoxBody<Bytes, TransportServerError>; pub trait GenericBodyExt { fn from_string(s: String) -> Self; fn from_value(value: &Value) -> Self; fn empty() -> Self; fn build_response( status_code: StatusCode, payload: String, headers: Option<HeaderMap>, ) -> http::Response<GenericBody>; fn into_response( self, status_code: StatusCode, headers: Option<HeaderMap>, ) -> http::Response<GenericBody>; fn into_json_response( self, status_code: StatusCode, headers: Option<HeaderMap>, ) -> http::Response<GenericBody>; fn create_404_response() -> http::Response<GenericBody>; fn create_405_response( method: &Method, allowed_methods: &[Method], ) -> http::Response<GenericBody>; } impl GenericBodyExt for GenericBody { fn from_string(s: String) -> Self { Full::new(Bytes::from(s)) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed() } fn from_value(value: &Value) -> Self { let bytes = match serde_json::to_vec(value) { Ok(vec) => Bytes::from(vec), Err(_) => Bytes::from_static(b"{\"error\":\"internal_error\"}"), }; Full::new(bytes) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed() } fn empty() -> Self { Full::new(Bytes::new()) .map_err(|err| TransportServerError::HttpError(err.to_string())) .boxed() } fn build_response( status_code: StatusCode, payload: String, headers: Option<HeaderMap>, ) -> http::Response<GenericBody> { let body = Self::from_string(payload); body.into_response(status_code, headers) } fn into_json_response( self, status_code: StatusCode, headers: Option<HeaderMap>, ) -> http::Response<GenericBody> { let mut headers = headers.unwrap_or_default(); headers.append(CONTENT_TYPE, HeaderValue::from_static("application/json")); self.into_response(status_code, Some(headers)) } fn into_response( self, status_code: StatusCode, headers: Option<HeaderMap>, ) -> http::Response<GenericBody> { let mut resp = http::Response::new(self); *resp.status_mut() = status_code; if let Some(mut headers) = headers { let mut current_name: Option<HeaderName> = None; for (name_opt, value) in headers.drain() { if let Some(name) = name_opt { current_name = Some(name); } let name = current_name.as_ref().unwrap(); resp.headers_mut().append(name.clone(), value); } } if !resp.headers().contains_key(CONTENT_TYPE) { resp.headers_mut() .append(CONTENT_TYPE, HeaderValue::from_static("text/plain")); } resp } fn create_404_response() -> http::Response<GenericBody> { Self::empty().into_response(StatusCode::NOT_FOUND, None) } fn create_405_response( method: &Method, allowed_methods: &[Method], ) -> http::Response<GenericBody> { let allow_header_value = HeaderValue::from_str( allowed_methods .iter() .map(|m| m.as_str()) .collect::<Vec<_>>() .join(", ") .as_str(), ) .unwrap_or(HeaderValue::from_static("unknown")); let mut response = Self::from_string(format!( "The method {method} is not allowed for this endpoint" )) .into_response(StatusCode::METHOD_NOT_ALLOWED, None); response.headers_mut().append(ALLOW, allow_header_value); response } } pub trait RequestExt { fn insert<T: Clone + Send + Sync + 'static>(&mut self, val: T); fn get<T: Send + Sync + 'static>(&self) -> Option<&T>; fn take<T: Send + Sync + 'static>(self) -> (Self, Option<T>) where Self: Sized; } impl RequestExt for http::Request<&str> { fn insert<T: Clone + Send + Sync + 'static>(&mut self, val: T) { self.extensions_mut().insert(val); } fn get<T: Send + Sync + 'static>(&self) -> Option<&T> { self.extensions().get::<T>() } fn take<T: Send + Sync + 'static>(mut self) -> (Self, Option<T>) { let exts = self.extensions_mut(); let val = exts.remove::<T>(); (self, val) } } pub type BoxFutureResponse<'req> = BoxFuture<'req, TransportServerResult<Response<GenericBody>>>; // pub type BoxFutureResponse<'req> = // Pin<Box<dyn Future<Output = TransportServerResult<Response<GenericBody>>> + Send + 'req>>; // Handler function type (can only be called once) pub type RequestHandlerFnOnce = dyn for<'req> FnOnce(Request<&'req str>, Arc<McpAppState>) -> BoxFutureResponse<'req> + Send; // RequestHandler cannot be Arc<...> anymore because FnOnce isn’t clonable pub type RequestHandler = Box<RequestHandlerFnOnce>; // Middleware "next" closure type - can only be called once pub type MiddlewareNext<'req> = Box<dyn FnOnce(Request<&'req str>, Arc<McpAppState>) -> BoxFutureResponse<'req> + Send>;
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/middleware/auth_middleware.rs
crates/rust-mcp-sdk/src/mcp_http/middleware/auth_middleware.rs
use crate::{ auth::{AuthInfo, AuthProvider, AuthenticationError}, mcp_http::{types::GenericBody, GenericBodyExt, McpAppState, Middleware, MiddlewareNext}, mcp_server::error::TransportServerResult, }; use async_trait::async_trait; use http::{ header::{AUTHORIZATION, WWW_AUTHENTICATE}, HeaderMap, HeaderValue, Request, Response, StatusCode, }; use std::{sync::Arc, time::SystemTime}; pub struct AuthMiddleware { auth_provider: Arc<dyn AuthProvider>, } impl AuthMiddleware { pub fn new(auth_provider: Arc<dyn AuthProvider>) -> Self { Self { auth_provider } } async fn validate( &self, headers: &HeaderMap<HeaderValue>, ) -> Result<AuthInfo, AuthenticationError> { let Some(auth_token) = headers .get(AUTHORIZATION) .map(|v| v.to_str().ok().unwrap_or_default()) else { return Err(AuthenticationError::InvalidToken { description: "Missing access token in Authorization header", }); }; let token = auth_token.trim(); let parts: Vec<&str> = token.splitn(2, ' ').collect(); if parts.len() != 2 || !parts[0].eq_ignore_ascii_case("bearer") { return Err(AuthenticationError::InvalidToken { description: "Invalid Authorization header format, expected 'Bearer TOKEN'", }); } let bearer_token = parts[1].trim(); let auth_info = self .auth_provider .verify_token(bearer_token.to_string()) .await?; match auth_info.expires_at { Some(expires_at) => { if SystemTime::now() >= expires_at { return Err(AuthenticationError::InvalidToken { description: "Token has expired", }); } } None => { return Err(AuthenticationError::InvalidToken { description: "Token has no expiration time", }) } } if let Some(required_scopes) = self.auth_provider.required_scopes() { if let Some(user_scopes) = auth_info.scopes.as_ref() { if !required_scopes .iter() .all(|scope| user_scopes.contains(scope)) { return Err(AuthenticationError::InsufficientScope); } } } Ok(auth_info) } fn create_www_auth_value(&self, error_code: &str, error: AuthenticationError) -> String { if let Some(resource_metadata) = self.auth_provider.protected_resource_metadata_url() { format!( r#"Bearer error="{error_code}", error_description="{error}", resource_metadata="{resource_metadata}""#, ) } else { format!(r#"Bearer error="{error_code}", error_description="{error}""#,) } } fn error_response(&self, error: AuthenticationError) -> Response<GenericBody> { let as_json = error.as_json_value(); let error_code = as_json .get("error") .unwrap_or_default() .as_str() .unwrap_or("unknown"); let (status_code, www_auth_value) = match error { AuthenticationError::InactiveToken | AuthenticationError::InvalidToken { description: _ } => ( StatusCode::UNAUTHORIZED, Some(self.create_www_auth_value(error_code, error)), ), AuthenticationError::InsufficientScope => ( StatusCode::FORBIDDEN, Some(self.create_www_auth_value(error_code, error)), ), AuthenticationError::TokenVerificationFailed { description: _, status_code, } => { if status_code.is_some_and(|s| s == StatusCode::FORBIDDEN) { ( StatusCode::FORBIDDEN, Some(self.create_www_auth_value(error_code, error)), ) } else { ( status_code .and_then(|v| StatusCode::from_u16(v).ok()) .unwrap_or(StatusCode::BAD_REQUEST), None, ) } } _ => (StatusCode::BAD_REQUEST, None), }; let mut response = GenericBody::from_value(&as_json).into_json_response(status_code, None); if let Some(www_auth_value) = www_auth_value { let Ok(www_auth_header_value) = HeaderValue::from_str(&www_auth_value) else { return GenericBody::from_string("Unsupported WWW_AUTHENTICATE value".to_string()) .into_response(StatusCode::INTERNAL_SERVER_ERROR, None); }; response .headers_mut() .append(WWW_AUTHENTICATE, www_auth_header_value); } response } } #[async_trait] impl Middleware for AuthMiddleware { async fn handle<'req>( &self, mut req: Request<&'req str>, state: Arc<McpAppState>, next: MiddlewareNext<'req>, ) -> TransportServerResult<Response<GenericBody>> { let auth_info = match self.validate(req.headers()).await { Ok(auth_info) => auth_info, Err(err) => { return Ok(self.error_response(err)); } }; req.extensions_mut().insert(auth_info); next(req, state).await } } #[cfg(test)] mod tests { use super::*; use crate::auth::AuthMetadataBuilder; use crate::mcp_icon; use crate::schema::{Implementation, InitializeResult, ProtocolVersion, ServerCapabilities}; use crate::{ auth::{OauthTokenVerifier, RemoteAuthProvider}, error::SdkResult, id_generator::{FastIdGenerator, UuidGenerator}, mcp_server::{ServerHandler, ToMcpServerHandler}, session_store::InMemorySessionStore, }; use crate::{mcp_http::GenericBodyExt, mcp_server::error::TransportServerError}; use bytes::Bytes; use http_body_util::combinators::BoxBody; use http_body_util::BodyExt; use std::time::Duration; pub struct TestTokenVerifier {} impl TestTokenVerifier { pub fn new() -> Self { Self {} } } pub(crate) async fn body_to_string( body: BoxBody<Bytes, TransportServerError>, ) -> Result<String, TransportServerError> { let bytes = body.collect().await?.to_bytes(); Ok(String::from_utf8_lossy(&bytes).into_owned()) } #[async_trait] impl OauthTokenVerifier for TestTokenVerifier { async fn verify_token( &self, access_token: String, ) -> Result<AuthInfo, AuthenticationError> { let info = match access_token.as_str() { "valid-token" => AuthInfo { token_unique_id: "valid-token".to_string(), client_id: Some("client-id".to_string()), user_id: None, scopes: Some(vec!["read".to_string(), "write".to_string()]), expires_at: Some(SystemTime::now() + Duration::from_secs(90)), audience: None, extra: None, }, "expired-token" => AuthInfo { token_unique_id: "expired-token".to_string(), client_id: Some("client-id".to_string()), user_id: None, scopes: Some(vec!["read".to_string(), "write".to_string()]), expires_at: Some(SystemTime::now() - Duration::from_secs(90)), // 90 seconds in the past audience: None, extra: None, }, "no-expiration-token" => AuthInfo { token_unique_id: "no-expiration-token".to_string(), client_id: Some("client-id".to_string()), scopes: Some(vec!["read".to_string(), "write".to_string()]), user_id: None, expires_at: None, audience: None, extra: None, }, "insufficient-scope" => AuthInfo { token_unique_id: "insufficient-scope".to_string(), client_id: Some("client-id".to_string()), scopes: Some(vec!["read".to_string()]), user_id: None, expires_at: Some(SystemTime::now() + Duration::from_secs(90)), audience: None, extra: None, }, _ => return Err(AuthenticationError::NotFound("Bad token".to_string())), }; Ok(info) } } pub fn create_oauth_provider() -> SdkResult<RemoteAuthProvider> { let auth_metadata = AuthMetadataBuilder::new("http://127.0.0.1:3000/mcp") .issuer("http://localhost:8090") .authorization_servers(vec!["http://localhost:8090"]) .scopes_supported(vec![ "mcp:tools".to_string(), "read".to_string(), "write".to_string(), ]) .introspection_endpoint("/introspect") .authorization_endpoint("/authorize") .token_endpoint("/token") .resource_name("MCP Demo Server".to_string()) .build() .unwrap(); let token_verifier = TestTokenVerifier::new(); Ok(RemoteAuthProvider::new( auth_metadata.0, auth_metadata.1, Box::new(token_verifier), Some(vec!["read".to_string(), "write".to_string()]), )) } struct TestHandler; impl ServerHandler for TestHandler {} fn app_state() -> Arc<McpAppState> { let handler = TestHandler {}; Arc::new(McpAppState { session_store: Arc::new(InMemorySessionStore::new()), id_generator: Arc::new(UuidGenerator {}), stream_id_gen: Arc::new(FastIdGenerator::new(Some("s_"))), server_details: Arc::new(InitializeResult { capabilities: ServerCapabilities { ..Default::default() }, instructions: None, meta: None, protocol_version: ProtocolVersion::V2025_06_18.to_string(), server_info: Implementation { name: "server".to_string(), title: None, version: "0.1.0".to_string(), description: Some("Auth Middleware Test Server, by Rust MCP SDK".to_string()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".to_string()), }, }), handler: handler.to_mcp_server_handler(), ping_interval: Duration::from_secs(15), transport_options: Arc::new(rust_mcp_transport::TransportOptions::default()), enable_json_response: false, event_store: None, task_store:None, client_task_store:None }) } #[tokio::test] //should call next when token is valid async fn test_call_next_when_token_is_valid() { let provider = create_oauth_provider().unwrap(); let middleware = AuthMiddleware::new(Arc::new(provider)); let req = Request::builder() .header(AUTHORIZATION, "Bearer valid-token") .body("") .unwrap(); let res = middleware .handle( req, app_state(), Box::new(move |_req, _state| { let resp = Response::builder() .status(StatusCode::OK) .body(GenericBody::from_string("reached".to_string())) .unwrap(); Box::pin(async { Ok(resp) }) }), ) .await .unwrap(); let (parts, body) = res.into_parts(); assert_eq!(body_to_string(body).await.unwrap(), "reached"); assert_eq!(parts.status, StatusCode::OK) } #[tokio::test] //should reject expired tokens async fn should_reject_expired_tokens() { let provider = create_oauth_provider().unwrap(); let middleware = AuthMiddleware::new(Arc::new(provider)); let req = Request::builder() .header(AUTHORIZATION, "Bearer expired-token") .body("") .unwrap(); let res = middleware .handle( req, app_state(), Box::new(move |_req, _state| { let resp = Response::builder() .status(StatusCode::OK) .body(GenericBody::from_string("reached".to_string())) .unwrap(); Box::pin(async { Ok(resp) }) }), ) .await .unwrap(); let (parts, body) = res.into_parts(); let body_string = body_to_string(body).await.unwrap(); assert!(body_string.contains("Token has expired")); assert!(body_string.contains("invalid_token")); assert_eq!(parts.status, StatusCode::UNAUTHORIZED); let header_value = parts .headers .get(WWW_AUTHENTICATE) .unwrap() .to_str() .unwrap(); assert!(header_value.contains(r#"Bearer error="invalid_token""#)) } //should reject tokens with no expiration time #[tokio::test] async fn should_reject_tokens_with_no_expiration_time() { let provider = create_oauth_provider().unwrap(); let middleware = AuthMiddleware::new(Arc::new(provider)); let req = Request::builder() .header(AUTHORIZATION, "Bearer no-expiration-token") .body("") .unwrap(); let res = middleware .handle( req, app_state(), Box::new(move |_req, _state| { let resp = Response::builder() .status(StatusCode::OK) .body(GenericBody::from_string("reached".to_string())) .unwrap(); Box::pin(async { Ok(resp) }) }), ) .await .unwrap(); let (parts, body) = res.into_parts(); assert_eq!(parts.status, StatusCode::UNAUTHORIZED); let body_string = body_to_string(body).await.unwrap(); assert!(body_string.contains("invalid_token")); assert!(body_string.contains("Token has no expiration time")); let header_value = parts .headers .get(WWW_AUTHENTICATE) .unwrap() .to_str() .unwrap(); assert!(header_value.contains(r#"Bearer error="invalid_token""#)) } // should require specific scopes when configured #[tokio::test] async fn should_require_specific_scopes_when_configured() { let provider = create_oauth_provider().unwrap(); let middleware = AuthMiddleware::new(Arc::new(provider)); let req = Request::builder() .header(AUTHORIZATION, "Bearer insufficient-scope") .body("") .unwrap(); let res = middleware .handle( req, app_state(), Box::new(move |_req, _state| { let resp = Response::builder() .status(StatusCode::OK) .body(GenericBody::from_string("reached".to_string())) .unwrap(); Box::pin(async { Ok(resp) }) }), ) .await .unwrap(); let (parts, body) = res.into_parts(); assert_eq!(parts.status, StatusCode::FORBIDDEN); let body_string = body_to_string(body).await.unwrap(); assert!(body_string.contains("insufficient_scope")); assert!(body_string.contains("Insufficient scope")); let header_value = parts .headers .get(WWW_AUTHENTICATE) .unwrap() .to_str() .unwrap(); assert!(header_value.contains(r#"Bearer error="insufficient_scope""#)) } // should return 401 when no Authorization header is present #[tokio::test] async fn should_return_401_when_no_authorization_header_is_present() { let provider = create_oauth_provider().unwrap(); let middleware = AuthMiddleware::new(Arc::new(provider)); let req = Request::builder().body("").unwrap(); let res = middleware .handle( req, app_state(), Box::new(move |_req, _state| { let resp = Response::builder() .status(StatusCode::OK) .body(GenericBody::from_string("reached".to_string())) .unwrap(); Box::pin(async { Ok(resp) }) }), ) .await .unwrap(); let (parts, body) = res.into_parts(); assert_eq!(parts.status, StatusCode::UNAUTHORIZED); let body_string = body_to_string(body).await.unwrap(); assert!(body_string.contains("invalid_token")); assert!(body_string.contains("Missing access token in Authorization header")); let header_value = parts .headers .get(WWW_AUTHENTICATE) .unwrap() .to_str() .unwrap(); assert!(header_value.contains(r#"Bearer error="invalid_token""#)) } //should return 401 when Authorization header format is invalid #[tokio::test] async fn should_return_401_when_authorization_header_format_is_invalid() { let provider = create_oauth_provider().unwrap(); let middleware = AuthMiddleware::new(Arc::new(provider)); let req = Request::builder() .header(AUTHORIZATION, "INVALID") .body("") .unwrap(); let res = middleware .handle( req, app_state(), Box::new(move |_req, _state| { let resp = Response::builder() .status(StatusCode::OK) .body(GenericBody::from_string("reached".to_string())) .unwrap(); Box::pin(async { Ok(resp) }) }), ) .await .unwrap(); let (parts, body) = res.into_parts(); assert_eq!(parts.status, StatusCode::UNAUTHORIZED); let body_string = body_to_string(body).await.unwrap(); assert!(body_string.contains("invalid_token")); assert!(body_string.contains("Bearer TOKEN")); let header_value = parts .headers .get(WWW_AUTHENTICATE) .unwrap() .to_str() .unwrap(); assert!(header_value.contains(r#"Bearer error="invalid_token""#)); assert!(header_value.contains( r#"resource_metadata="http://127.0.0.1/.well-known/oauth-protected-resource/mcp"# )); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/middleware/dns_rebind_protector.rs
crates/rust-mcp-sdk/src/mcp_http/middleware/dns_rebind_protector.rs
//! DNS Rebinding Protection Middleware //! //! This module provides a middleware that protects against DNS rebinding attacks //! by validating the `Host` and `Origin` headers against configurable allowlists. //! //! DNS rebinding is an attack where a malicious site tricks a client's DNS resolver //! into resolving a domain (e.g., `attacker.com`) to a private IP (like `127.0.0.1`), //! allowing it to bypass same-origin policy and access internal services. //! //! # Security Model //! //! - If `allowed_hosts` is `Some(vec![..])` and non-empty → `Host` header **must** match (case-insensitive) //! - If `allowed_origins` is `Some(vec![..])` and non-empty → `Origin` header **must** match (case-insensitive) //! - Missing or unparsable headers → treated as invalid → 403 Forbidden //! - If allowlist is `None` or empty → that check is skipped use crate::{ mcp_http::{error_response, types::GenericBody, McpAppState, Middleware, MiddlewareNext}, mcp_server::error::TransportServerResult, schema::schema_utils::SdkError, }; use async_trait::async_trait; use http::{ header::{HOST, ORIGIN}, Request, Response, StatusCode, }; use std::sync::Arc; /// DNS Rebinding Protection Middleware /// /// Validates `Host` and `Origin` headers against allowlists to prevent DNS rebinding attacks. /// Returns `403 Forbidden` with a descriptive error if validation fails. /// /// This middleware should be placed **early** in the chain (before routing) to ensure /// protection even for unmatched routes. /// /// # When to use /// - Public-facing APIs /// - Services accessible via custom domains /// - Any server that should **never** be accessible via `127.0.0.1`, `localhost`, or raw IPs /// /// # Security Considerations /// - Always pin exact hostnames (e.g., `app.example.com:8443`) /// - Avoid wildcards or overly broad patterns /// - For local development, include `localhost:PORT` explicitly /// - Never allow raw IP addresses in production allowlists pub(crate) struct DnsRebindProtector { /// List of allowed host header values for DNS rebinding protection. /// If not specified, host validation is disabled. pub allowed_hosts: Option<Vec<String>>, /// List of allowed origin header values for DNS rebinding protection. /// If not specified, origin validation is disabled. pub allowed_origins: Option<Vec<String>>, } #[async_trait] impl Middleware for DnsRebindProtector { /// Processes the incoming request and applies DNS rebinding protection. /// /// # Arguments /// /// * `req` - The incoming HTTP request with `&str` body (pre-read) /// * `state` - Shared application state /// * `next` - The next middleware/handler in the chain /// /// # Returns /// /// * `Ok(Response)` - If validation passes, forwards to next handler /// * `Err` via `error_response(403, ...)` - If Host/Origin validation fails async fn handle<'req>( &self, req: Request<&'req str>, state: Arc<McpAppState>, next: MiddlewareNext<'req>, ) -> TransportServerResult<Response<GenericBody>> { if let Err(error) = self.protect_dns_rebinding(req.headers()).await { return error_response(StatusCode::FORBIDDEN, error); } next(req, state).await } } impl DnsRebindProtector { pub fn new(allowed_hosts: Option<Vec<String>>, allowed_origins: Option<Vec<String>>) -> Self { Self { allowed_hosts, allowed_origins, } } // Protect against DNS rebinding attacks by validating Host and Origin headers. // If protection fails, respond with HTTP 403 Forbidden. async fn protect_dns_rebinding(&self, headers: &http::HeaderMap) -> Result<(), SdkError> { if let Some(allowed_hosts) = self.allowed_hosts.as_ref() { if !allowed_hosts.is_empty() { let Some(host) = headers.get(HOST).and_then(|h| h.to_str().ok()) else { return Err( SdkError::bad_request().with_message("Invalid Host header: [unknown] ") ); }; if !allowed_hosts .iter() .any(|allowed| allowed.eq_ignore_ascii_case(host)) { return Err(SdkError::bad_request() .with_message(format!("Invalid Host header: \"{host}\" ").as_str())); } } } if let Some(allowed_origins) = self.allowed_origins.as_ref() { if !allowed_origins.is_empty() { let Some(origin) = headers.get(ORIGIN).and_then(|h| h.to_str().ok()) else { return Err( SdkError::bad_request().with_message("Invalid Origin header: [unknown] ") ); }; if !allowed_origins .iter() .any(|allowed| allowed.eq_ignore_ascii_case(origin)) { return Err(SdkError::bad_request() .with_message(format!("Invalid Origin header: \"{origin}\" ").as_str())); } } } Ok(()) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/middleware/cors_middleware.rs
crates/rust-mcp-sdk/src/mcp_http/middleware/cors_middleware.rs
//! # CORS Middleware //! //! A configurable CORS middleware that follows the //! [WHATWG CORS specification](https://fetch.spec.whatwg.org/#http-cors-protocol). //! //! ## Features //! - Full preflight (`OPTIONS`) handling //! - Configurable origins: `*`, explicit list, or echo //! - Credential support (with correct `Access-Control-Allow-Origin` behavior) //! - Header/method validation //! - `Access-Control-Expose-Headers` support use crate::{ mcp_http::{types::GenericBody, GenericBodyExt, McpAppState, Middleware, MiddlewareNext}, mcp_server::error::TransportServerResult, }; use http::{ header::{ self, HeaderName, HeaderValue, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_MAX_AGE, ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, }, Method, Request, Response, StatusCode, }; use rust_mcp_transport::MCP_SESSION_ID_HEADER; use std::{collections::HashSet, sync::Arc}; /// Configuration for CORS behavior. /// /// See [MDN CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) for details. #[derive(Clone)] pub struct CorsConfig { /// Which origins are allowed to make requests. pub allow_origins: AllowOrigins, /// HTTP methods allowed in preflight and actual requests. pub allow_methods: Vec<Method>, /// Request headers allowed in preflight. pub allow_headers: Vec<HeaderName>, /// Whether to allow credentials (cookies, HTTP auth, etc). /// /// **Important**: When `true`, `allow_origins` cannot be `Any` - browsers reject `*`. pub allow_credentials: bool, /// How long (in seconds) the preflight response can be cached. pub max_age: Option<u32>, /// Headers that should be exposed to the client JavaScript. pub expose_headers: Vec<HeaderName>, } impl Default for CorsConfig { fn default() -> Self { Self { allow_origins: AllowOrigins::Any, allow_methods: vec![Method::GET, Method::POST, Method::OPTIONS], allow_headers: vec![ header::CONTENT_TYPE, header::AUTHORIZATION, HeaderName::from_static(MCP_SESSION_ID_HEADER), ], allow_credentials: false, max_age: Some(86_400), // 24 hours expose_headers: vec![], } } } /// Policy for allowed origins. #[derive(Clone, Debug)] pub enum AllowOrigins { /// Allow any origin (`*`). /// /// **Cannot** be used with `allow_credentials = true`. Any, /// Allow only specific origins. List(HashSet<String>), /// Echo the `Origin` header back (required when `allow_credentials = true`). Echo, } /// CORS middleware implementing the `Middleware` trait. /// /// Handles both **preflight** (`OPTIONS`) and **actual** requests, /// adding appropriate CORS headers and rejecting invalid origins/methods/headers. #[derive(Clone, Default)] pub struct CorsMiddleware { config: Arc<CorsConfig>, } impl CorsMiddleware { /// Create a new CORS middleware with custom config. pub fn new(config: CorsConfig) -> Self { Self { config: Arc::new(config), } } /// Create a permissive CORS config - useful for public APIs or local dev. /// /// Allows all common methods, credentials, and common headers. pub fn permissive() -> Self { Self::new(CorsConfig { allow_origins: AllowOrigins::Any, allow_methods: vec![ Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::PATCH, Method::OPTIONS, Method::HEAD, ], allow_headers: vec![ header::CONTENT_TYPE, header::AUTHORIZATION, header::ACCEPT, header::ORIGIN, ], allow_credentials: true, max_age: Some(86_400), expose_headers: vec![], }) } // Internal: resolve allowed origin header value fn resolve_allowed_origin(&self, origin: &str) -> Option<String> { match &self.config.allow_origins { AllowOrigins::Any => { // Only return "*" if credentials are not allowed if self.config.allow_credentials { // rule MDN , RFC 6454 // If Access-Control-Allow-Credentials: true is set, // then Access-Control-Allow-Origin CANNOT be *. // It MUST be the exact origin (e.g., https://example.com). Some(origin.to_string()) } else { Some("*".to_string()) } } AllowOrigins::List(allowed) => { if allowed.contains(origin) { Some(origin.to_string()) } else { None } } AllowOrigins::Echo => Some(origin.to_string()), } } // Build preflight response (204 No Content) fn preflight_response(&self, origin: &str) -> Response<GenericBody> { let allowed_origin = self.resolve_allowed_origin(origin); let mut resp = Response::builder() .status(StatusCode::NO_CONTENT) .body(GenericBody::empty()) .expect("preflight response is static"); let headers = resp.headers_mut(); if let Some(origin) = allowed_origin { headers.insert( ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_str(&origin).expect("origin is validated"), ); } if self.config.allow_credentials { headers.insert( ACCESS_CONTROL_ALLOW_CREDENTIALS, HeaderValue::from_static("true"), ); } if let Some(age) = self.config.max_age { headers.insert( ACCESS_CONTROL_MAX_AGE, HeaderValue::from_str(&age.to_string()).expect("u32 is valid"), ); } let methods = self .config .allow_methods .iter() .map(|m| m.as_str()) .collect::<Vec<_>>() .join(", "); headers.insert( ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_str(&methods).expect("methods are static"), ); let headers_list = self .config .allow_headers .iter() .map(|h| h.as_str()) .collect::<Vec<_>>() .join(", "); headers.insert( ACCESS_CONTROL_ALLOW_HEADERS, HeaderValue::from_str(&headers_list).expect("headers are static"), ); resp } // Add CORS headers to normal response fn add_cors_to_response( &self, mut resp: Response<GenericBody>, origin: &str, ) -> Response<GenericBody> { let allowed_origin = self.resolve_allowed_origin(origin); let headers = resp.headers_mut(); if let Some(origin) = allowed_origin { headers.insert( ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_str(&origin).expect("origin is validated"), ); } if self.config.allow_credentials { headers.insert( ACCESS_CONTROL_ALLOW_CREDENTIALS, HeaderValue::from_static("true"), ); } if !self.config.expose_headers.is_empty() { let expose = self .config .expose_headers .iter() .map(|h| h.as_str()) .collect::<Vec<_>>() .join(", "); headers.insert( ACCESS_CONTROL_EXPOSE_HEADERS, HeaderValue::from_str(&expose).expect("expose headers are static"), ); } resp } } // Middleware trait implementation #[async_trait::async_trait] impl Middleware for CorsMiddleware { /// Process a request, handling preflight or adding CORS headers. /// /// - For `OPTIONS` with `Access-Control-Request-Method`: performs preflight. /// - For other requests: passes to `next`, then adds CORS headers. async fn handle<'req>( &self, req: Request<&'req str>, state: Arc<McpAppState>, next: MiddlewareNext<'req>, ) -> TransportServerResult<Response<GenericBody>> { let origin = req .headers() .get(header::ORIGIN) .and_then(|v| v.to_str().ok()) .map(|s| s.to_string()); // Preflight: OPTIONS + Access-Control-Request-Method if *req.method() == Method::OPTIONS { let requested_method = req .headers() .get(ACCESS_CONTROL_REQUEST_METHOD) .and_then(|v| v.to_str().ok()) .and_then(|s| s.parse::<Method>().ok()); let requested_headers = req .headers() .get(ACCESS_CONTROL_REQUEST_HEADERS) .and_then(|v| v.to_str().ok()) .map(|s| { s.split(',') .map(|h| h.trim().to_ascii_lowercase()) .collect::<HashSet<_>>() }) .unwrap_or_default(); let origin = match origin { Some(o) => o, None => { // Some tools send preflight without Origin - allow if Any if matches!(self.config.allow_origins, AllowOrigins::Any) && !self.config.allow_credentials { return Ok(self.preflight_response("*")); } else { return Ok(GenericBody::build_response( StatusCode::BAD_REQUEST, "CORS origin missing in preflight".to_string(), None, )); } } }; // Validate origin if self.resolve_allowed_origin(&origin).is_none() { return Ok(GenericBody::build_response( StatusCode::FORBIDDEN, "CORS origin not allowed".to_string(), None, )); } // Validate method if let Some(m) = requested_method { if !self.config.allow_methods.contains(&m) { return Ok(GenericBody::build_response( StatusCode::METHOD_NOT_ALLOWED, "CORS method not allowed".to_string(), None, )); } } // Validate headers let allowed = self .config .allow_headers .iter() .map(|h| h.as_str().to_ascii_lowercase()) .collect::<HashSet<_>>(); if !requested_headers.is_subset(&allowed) { return Ok(GenericBody::build_response( StatusCode::BAD_REQUEST, "CORS header not allowed".to_string(), None, )); } // All good - return preflight return Ok(self.preflight_response(&origin)); } // Normal request: forward to next handler let mut resp = next(req, state).await?; if let Some(origin) = origin { if self.resolve_allowed_origin(&origin).is_some() { resp = self.add_cors_to_response(resp, &origin); } } Ok(resp) } } #[cfg(test)] mod tests { use super::*; use crate::{ id_generator::{FastIdGenerator, UuidGenerator}, mcp_http::{types::GenericBodyExt, MiddlewareNext}, mcp_icon, mcp_server::{ServerHandler, ToMcpServerHandler}, schema::{Implementation, InitializeResult, ProtocolVersion, ServerCapabilities}, session_store::InMemorySessionStore, }; use http::{header, Request, Response, StatusCode}; use std::time::Duration; type TestResult = Result<(), Box<dyn std::error::Error>>; struct TestHandler; impl ServerHandler for TestHandler {} fn app_state() -> Arc<McpAppState> { let handler = TestHandler {}; Arc::new(McpAppState { session_store: Arc::new(InMemorySessionStore::new()), id_generator: Arc::new(UuidGenerator {}), stream_id_gen: Arc::new(FastIdGenerator::new(Some("s_"))), server_details: Arc::new(InitializeResult { capabilities: ServerCapabilities { ..Default::default() }, instructions: None, meta: None, protocol_version: ProtocolVersion::V2025_06_18.to_string(), server_info: Implementation { name: "server".to_string(), title: None, version: "0.1.0".to_string(), description: Some("test server, by Rust MCP SDK".to_string()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".to_string()), }, }), handler: handler.to_mcp_server_handler(), ping_interval: Duration::from_secs(15), transport_options: Arc::new(rust_mcp_transport::TransportOptions::default()), enable_json_response: false, event_store: None, task_store:None, client_task_store:None }) } fn make_handler<'req>(status: StatusCode, body: &'static str) -> MiddlewareNext<'req> { Box::new(move |_, _| { let resp = Response::builder() .status(status) .body(GenericBody::from_string(body.to_string())) .unwrap(); Box::pin(async { Ok(resp) }) }) } #[tokio::test] async fn test_preflight_allowed() -> TestResult { let cors = CorsMiddleware::permissive(); let handler = make_handler(StatusCode::OK, "should not see"); let req = Request::builder() .method(Method::OPTIONS) .uri("/") .header(header::ORIGIN, "https://example.com") .header(ACCESS_CONTROL_REQUEST_METHOD, "POST") .header( ACCESS_CONTROL_REQUEST_HEADERS, "content-type, authorization", ) .body("")?; let resp = cors.handle(req, app_state(), handler).await?; assert_eq!(resp.status(), StatusCode::NO_CONTENT); assert_eq!( resp.headers()[ACCESS_CONTROL_ALLOW_ORIGIN], "https://example.com" ); assert_eq!( resp.headers()[ACCESS_CONTROL_ALLOW_METHODS], "GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD" ); Ok(()) } #[tokio::test] async fn test_preflight_disallowed_origin() -> TestResult { let mut allowed = HashSet::new(); allowed.insert("https://trusted.com".to_string()); let cors = CorsMiddleware::new(CorsConfig { allow_origins: AllowOrigins::List(allowed), allow_methods: vec![Method::GET], allow_headers: vec![], allow_credentials: false, max_age: None, expose_headers: vec![], }); let handler = make_handler(StatusCode::OK, "irrelevant"); let req = Request::builder() .method(Method::OPTIONS) .uri("/") .header(header::ORIGIN, "https://evil.com") .header(ACCESS_CONTROL_REQUEST_METHOD, "GET") .body("")?; let result: Response<GenericBody> = cors.handle(req, app_state(), handler).await.unwrap(); let (parts, _body) = result.into_parts(); assert_eq!(parts.status, 403); Ok(()) } #[tokio::test] async fn test_normal_request_with_origin() -> TestResult { let cors = CorsMiddleware::permissive(); let handler = make_handler(StatusCode::OK, "hello"); let req = Request::builder() .method(Method::GET) .uri("/") .header(header::ORIGIN, "https://client.com") .body("")?; let resp = cors.handle(req, app_state(), handler).await?; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers()[ACCESS_CONTROL_ALLOW_ORIGIN], "https://client.com" ); assert_eq!(resp.headers()[ACCESS_CONTROL_ALLOW_CREDENTIALS], "true"); Ok(()) } #[tokio::test] async fn test_wildcard_with_no_credentials() -> TestResult { let cors = CorsMiddleware::new(CorsConfig { allow_origins: AllowOrigins::Any, allow_methods: vec![Method::GET], allow_headers: vec![], allow_credentials: false, max_age: None, expose_headers: vec![], }); let handler = make_handler(StatusCode::OK, "ok"); let req = Request::builder() .method(Method::GET) .uri("/") .header(header::ORIGIN, "https://any.com") .body("")?; let resp = cors.handle(req, app_state(), handler).await?; assert_eq!(resp.headers()[ACCESS_CONTROL_ALLOW_ORIGIN], "*"); Ok(()) } #[tokio::test] async fn test_no_wildcard_with_credentials() -> TestResult { let cors = CorsMiddleware::new(CorsConfig { allow_origins: AllowOrigins::Any, allow_methods: vec![Method::GET], allow_headers: vec![], allow_credentials: true, // This should prevent "*" max_age: None, expose_headers: vec![], }); let handler = make_handler(StatusCode::OK, "ok"); let req = Request::builder() .method(Method::GET) .uri("/") .header(header::ORIGIN, "https://any.com") .body("")?; let resp = cors.handle(req, app_state(), handler).await?; // Should NOT have "*" even though config says Any let origin_header = resp .headers() .get(ACCESS_CONTROL_ALLOW_ORIGIN) .expect("CORS header missing"); assert_eq!(origin_header, "https://any.com"); // And credentials should be allowed assert_eq!( resp.headers() .get(ACCESS_CONTROL_ALLOW_CREDENTIALS) .unwrap(), "true" ); Ok(()) } #[tokio::test] async fn test_echo_origin_with_credentials() -> TestResult { let cors = CorsMiddleware::new(CorsConfig { allow_origins: AllowOrigins::Echo, allow_methods: vec![Method::GET], allow_headers: vec![], allow_credentials: true, max_age: None, expose_headers: vec![], }); let handler = make_handler(StatusCode::OK, "ok"); let req = Request::builder() .method(Method::GET) .uri("/") .header(header::ORIGIN, "https://dynamic.com") .body("")?; let resp = cors.handle(req, app_state(), handler).await?; assert_eq!( resp.headers()[ACCESS_CONTROL_ALLOW_ORIGIN], "https://dynamic.com" ); assert_eq!(resp.headers()[ACCESS_CONTROL_ALLOW_CREDENTIALS], "true"); Ok(()) } #[tokio::test] async fn test_expose_headers() -> TestResult { let cors = CorsMiddleware::new(CorsConfig { allow_origins: AllowOrigins::Any, allow_methods: vec![Method::GET], allow_headers: vec![], allow_credentials: false, max_age: None, expose_headers: vec![HeaderName::from_static("x-ratelimit-remaining")], }); let handler = make_handler(StatusCode::OK, "ok"); let req = Request::builder() .method(Method::GET) .uri("/") .header(header::ORIGIN, "https://client.com") .body("")?; let resp = cors.handle(req, app_state(), handler).await?; assert_eq!( resp.headers()[ACCESS_CONTROL_EXPOSE_HEADERS], "x-ratelimit-remaining" ); Ok(()) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/src/mcp_http/middleware/logging_middleware.rs
crates/rust-mcp-sdk/src/mcp_http/middleware/logging_middleware.rs
//! A very simple example middleware for inspiration. //! //! This demonstrates how to implement a basic logging middleware //! using the `Middleware` trait. It logs incoming requests and outgoing //! responses. In a real-world application, you might extend this to //! include structured logging, tracing, timing, or error reporting. use crate::{ mcp_http::{types::GenericBody, McpAppState, Middleware, MiddlewareNext}, mcp_server::error::TransportServerResult, }; use async_trait::async_trait; use http::{Request, Response}; use std::sync::Arc; /// A minimal middleware that logs request URIs and response statuses. /// /// This is just a *very, very* simple example meant for inspiration. /// It shows how to wrap a request/response cycle inside a middleware layer. pub struct LoggingMiddleware; #[async_trait] impl Middleware for LoggingMiddleware { async fn handle<'req>( &self, req: Request<&'req str>, state: Arc<McpAppState>, next: MiddlewareNext<'req>, ) -> TransportServerResult<Response<GenericBody>> { println!("➡️ Logging request: {}", req.uri()); let res = next(req, state).await?; println!("⬅️ Logging response: {}", res.status()); Ok(res) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_macros.rs
crates/rust-mcp-sdk/tests/test_macros.rs
#[test] #[cfg(feature = "2025_06_18")] fn test_mcp_tool() { use serde_json::{Map, Value}; #[rust_mcp_macros::mcp_tool( name = "example_tool", title = "Example Tool", description = "An example tool", idempotent_hint = true, destructive_hint = true, open_world_hint = true, read_only_hint = true, meta = r#"{ "string_meta" : "meta value", "numeric_meta" : 15 }"# )] #[derive(rust_mcp_macros::JsonSchema)] #[allow(unused)] struct ExampleTool { field1: String, field2: i32, } assert_eq!(ExampleTool::tool_name(), "example_tool"); let tool: rust_mcp_schema::Tool = ExampleTool::tool(); assert_eq!(tool.name, "example_tool"); assert_eq!(tool.description.unwrap(), "An example tool"); assert!(tool.annotations.as_ref().unwrap().idempotent_hint.unwrap(),); assert!(tool.annotations.as_ref().unwrap().destructive_hint.unwrap(),); assert!(tool.annotations.as_ref().unwrap().open_world_hint.unwrap(),); assert!(tool.annotations.as_ref().unwrap().read_only_hint.unwrap(),); assert_eq!(tool.title.as_ref().unwrap(), "Example Tool"); let meta: &Map<String, Value> = tool.meta.as_ref().unwrap(); // Assert that "string_meta" equals "meta value" assert_eq!( meta.get("string_meta").unwrap(), &Value::String("meta value".to_string()) ); // Assert that "numeric_meta" equals 15 assert_eq!(meta.get("numeric_meta").unwrap(), &Value::Number(15.into())); let schema_properties = tool.input_schema.properties.unwrap(); assert_eq!(schema_properties.len(), 2); assert!(schema_properties.contains_key("field1")); assert!(schema_properties.contains_key("field2")); } #[test] #[cfg(feature = "2025_03_26")] fn test_mcp_tool() { #[rust_mcp_macros::mcp_tool( name = "example_tool", description = "An example tool", idempotent_hint = true, destructive_hint = true, open_world_hint = true, read_only_hint = true )] #[derive(rust_mcp_macros::JsonSchema)] #[allow(unused)] struct ExampleTool { field1: String, field2: i32, } assert_eq!(ExampleTool::tool_name(), "example_tool"); let tool: rust_mcp_schema::Tool = ExampleTool::tool(); assert_eq!(tool.name, "example_tool"); assert_eq!(tool.description.unwrap(), "An example tool"); assert!(tool.annotations.as_ref().unwrap().idempotent_hint.unwrap(),); assert!(tool.annotations.as_ref().unwrap().destructive_hint.unwrap(),); assert!(tool.annotations.as_ref().unwrap().open_world_hint.unwrap(),); assert!(tool.annotations.as_ref().unwrap().read_only_hint.unwrap(),); let schema_properties = tool.input_schema.properties.unwrap(); assert_eq!(schema_properties.len(), 2); assert!(schema_properties.contains_key("field1")); assert!(schema_properties.contains_key("field2")); } #[test] #[cfg(feature = "2024_11_05")] fn test_mcp_tool() { #[rust_mcp_macros::mcp_tool(name = "example_tool", description = "An example tool")] #[derive(rust_mcp_macros::JsonSchema)] #[allow(unused)] struct ExampleTool { field1: String, field2: i32, } assert_eq!(ExampleTool::tool_name(), "example_tool"); let tool: rust_mcp_schema::Tool = ExampleTool::tool(); assert_eq!(tool.name, "example_tool"); assert_eq!(tool.description.unwrap(), "An example tool"); let schema_properties = tool.input_schema.properties.unwrap(); assert_eq!(schema_properties.len(), 2); assert!(schema_properties.contains_key("field1")); assert!(schema_properties.contains_key("field2")); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_server_task.rs
crates/rust-mcp-sdk/tests/test_server_task.rs
#[path = "common/common.rs"] pub mod common; mod test_streamable_http_server; use crate::common::{ init_tracing, read_sse_event, sample_tools::TaskAugmentedTool, send_post_request, task_runner::TaskJobInfo, ONE_MILLISECOND, }; use hyper::StatusCode; use rust_mcp_macros::{mcp_elicit, JsonSchema}; use rust_mcp_schema::{ schema_utils::{ClientJsonrpcRequest, RequestFromClient}, CallToolResult, CreateTaskResult, ElicitRequestParams, ElicitResult, ElicitResultAction, ElicitResultContent, ElicitResultContentPrimitive, GetTaskResult, RequestId, Task, TaskMetadata, TaskStatus, }; use rust_mcp_sdk::schema::{ ClientJsonrpcResponse, ResultFromServer, ServerJsonrpcNotification, ServerJsonrpcResponse, }; use serde_json::json; use std::{collections::HashMap, panic, sync::Arc, time::Duration}; use test_streamable_http_server::*; #[tokio::test] async fn test_server_task_normal() { init_tracing(); let (server, session_id) = initialize_server(None, None).await.unwrap(); let response = get_standalone_stream(&server.streamable_url, &session_id, None).await; assert_eq!(response.status(), StatusCode::OK); let expected_result: ResultFromServer = CallToolResult::text_content(vec!["task-completed".into()]).into(); let task_info = TaskJobInfo { finish_in_ms: 1200, status_interval_ms: 250, task_final_status: TaskStatus::Completed.to_string(), task_result: Some(serde_json::to_string(&expected_result).unwrap()), meta: Some( json!({"task_meta":"meta_value"}) .as_object() .cloned() .unwrap(), ), }; let v = serde_json::to_value(task_info) .unwrap() .as_object() .unwrap() .clone(); let arguments = TaskAugmentedTool::request_params() .with_arguments(v) .with_task(TaskMetadata { ttl: None }); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::CallToolRequest(arguments).into(), ); let resp = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); let messages = read_sse_event(resp, 1).await.unwrap(); let result_message: ServerJsonrpcResponse = serde_json::from_str(&messages[0].2).unwrap(); let ResultFromServer::CreateTaskResult(create_task_result) = result_message.result else { panic!("Expected a CreateTaskResult!"); }; tokio::time::sleep(Duration::from_secs(2)).await; let messages = read_sse_event(response, 1).await.unwrap(); let message: ServerJsonrpcNotification = serde_json::from_str(&messages[0].2).unwrap(); let ServerJsonrpcNotification::TaskStatusNotification(notification) = message else { panic!("Expected a TaskStatusNotification") }; assert_eq!(notification.params.status, TaskStatus::Completed); assert!(notification.params.status_message.is_none()); assert_eq!( notification.params.meta, Some( json!( {"task_meta": "meta_value"}) .as_object() .cloned() .unwrap() ) ); let store = server.hyper_runtime.task_store().unwrap().clone(); let task_result = store .get_task_result(&create_task_result.task.task_id, Some(session_id)) .await .unwrap(); let ResultFromServer::CallToolResult(task_result) = task_result else { panic!("expected a CallToolResult!"); }; assert_eq!(task_result.content.len(), 1); let text_content = task_result.content[0].as_text_content().unwrap(); assert_eq!(text_content.text, "task-completed"); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } #[tokio::test] async fn test_server_task_wait_for_result() { #[mcp_elicit(message = "Please enter your info", mode = form)] #[derive(JsonSchema)] pub struct UserEmail { #[json_schema(title = "Email", format = "email")] pub email: Option<String>, } init_tracing(); let (server, session_id) = initialize_server(None, None).await.unwrap(); let response = get_standalone_stream(&server.streamable_url, &session_id, None).await; assert_eq!(response.status(), StatusCode::OK); let elicit_params: ElicitRequestParams = UserEmail::elicit_request_params().with_task(TaskMetadata { ttl: Some(10000) }); let hyper_server = Arc::new(server.hyper_runtime); let hyper_server_clone = hyper_server.clone(); let session_id_clone = session_id.clone(); tokio::spawn(async move { let task_result = hyper_server_clone .request_elicitation_task(&session_id_clone, elicit_params) .await .unwrap(); let task_store = hyper_server_clone.client_task_store().unwrap(); let task_result = task_store .wait_for_task_result(&task_result.task.task_id, Some(session_id_clone)) .await .unwrap(); assert_eq!(task_result.0, TaskStatus::Completed); let elicit_result: ElicitResult = task_result.1.unwrap().try_into().unwrap(); assert_eq!(elicit_result.action, ElicitResultAction::Accept); let email_value = elicit_result .content .as_ref() .unwrap() .get("email") .unwrap(); let ElicitResultContent::Primitive(ElicitResultContentPrimitive::String(email)) = email_value else { panic!("invalid elicit result content type"); }; assert_eq!(email, "email@example.com"); }); let res = CreateTaskResult { meta: None, task: Task { created_at: "".to_string(), last_updated_at: "".to_string(), poll_interval: Some(500), status: TaskStatus::Working, status_message: None, task_id: "tskAAAAAAAAAAA".to_string(), ttl: Some(60_000), }, }; // send taskcreate result let json_rpc_message: ClientJsonrpcResponse = ClientJsonrpcResponse::new(RequestId::Integer(0), res.into()); send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); tokio::time::sleep(Duration::from_millis(2200)).await; let get_task_result = GetTaskResult { created_at: "".to_string(), last_updated_at: "".to_string(), meta: None, poll_interval: Some(250), status: TaskStatus::Completed, status_message: None, task_id: "tskAAAAAAAAAAA".to_string(), ttl: 60_000, extra: None, }; let json_rpc_message: ClientJsonrpcResponse = ClientJsonrpcResponse::new(RequestId::Integer(1), get_task_result.into()); send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); tokio::time::sleep(Duration::from_millis(100)).await; let mut data: HashMap<String, ElicitResultContent> = HashMap::new(); data.insert("email".into(), "email@example.com".into()); let elicit_result: ElicitResult = ElicitResult { action: rust_mcp_schema::ElicitResultAction::Accept, content: Some(data), meta: None, }; let json_rpc_message: ClientJsonrpcResponse = ClientJsonrpcResponse::new(RequestId::Integer(2), elicit_result.into()); send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); hyper_server.graceful_shutdown(ONE_MILLISECOND); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_client_task.rs
crates/rust-mcp-sdk/tests/test_client_task.rs
#[path = "common/common.rs"] pub mod common; mod test_streamable_http_client; use std::{collections::HashMap, time::Duration}; use http::Method; use rust_mcp_macros::{mcp_elicit, JsonSchema}; use rust_mcp_schema::{ ElicitRequest, ElicitRequestFormParams, ElicitRequestParams, RequestId, TaskMetadata, TaskStatus, }; use rust_mcp_sdk::{ schema::{ ClientJsonrpcNotification, ClientJsonrpcResponse, ClientMessage, MessageFromClient, MessageFromServer, NotificationFromClient, RequestFromClient, ResultFromClient, ResultFromServer, ServerJsonrpcRequest, }, McpClient, }; use crate::common::{ debug_wiremock, init_tracing, test_client_common::{create_client, initialize_client, InitializedClient, TEST_SESSION_ID}, test_server_common::INITIALIZE_RESPONSE, MockBuilder, SimpleMockServer, SseEvent, }; #[mcp_elicit(message = "Please enter your info", mode = form)] #[derive(JsonSchema)] pub struct UserEmail { #[json_schema(title = "Email", format = "email")] pub email: Option<String>, } // // Sends a request to the client asking the user to provide input // let result: ElicitResult = server.request_elicitation(UserInfo::elicit_request_params()).await?; #[tokio::test] async fn test_client_task_normal() { let elicit_params: ElicitRequestParams = UserEmail::elicit_request_params().with_task(TaskMetadata { ttl: Some(10000) }); let elicit_request = ElicitRequest::new(RequestId::Integer(1), elicit_params); let request: ServerJsonrpcRequest = elicit_request.into(); let elicit_message_str = serde_json::to_string(&request).unwrap(); let mocks = vec![ MockBuilder::new_sse(Method::POST, "/mcp".to_string(), INITIALIZE_RESPONSE).build(), MockBuilder::new_breakable_sse( Method::GET, "/mcp".to_string(), SseEvent { data: Some(elicit_message_str.into()), event: Some("message".to_string()), id: None, }, Duration::from_millis(800), 2, ) .expect(2) .build(), MockBuilder::new_sse( Method::POST, "/mcp".to_string(), r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, ) .build(), ]; let (url, handle) = SimpleMockServer::start_with_mocks(mocks).await; let mcp_url = format!("{url}/mcp"); let mut headers = HashMap::new(); headers.insert("X-Custom-Header".to_string(), "CustomValue".to_string()); let (client, client_message_history) = create_client(&mcp_url, Some(headers)).await; client.clone().start().await.unwrap(); assert!(client.is_initialized()); tokio::time::sleep(Duration::from_secs(2)).await; handle.print().await; let h = client_message_history.read().await; let first_message: MessageFromServer = h[0].clone(); let MessageFromServer::RequestFromServer( rust_mcp_sdk::schema::RequestFromServer::ElicitRequest(elicit_request), ) = first_message else { panic!("Expected a ElicitRequest"); }; assert_eq!(elicit_request.message(), "Please enter your info"); let message_history = handle.get_history().await; let message_count = message_history.len(); let entry = message_history[message_count - 2].clone(); let result: ClientJsonrpcResponse = serde_json::from_str(&entry.0.body).unwrap(); let ResultFromClient::CreateTaskResult(message) = result.result.clone() else { panic!("Expected a CreateTaskResult") }; assert_eq!(message.task.status, TaskStatus::Working); // last message let entry = message_history[message_count - 1].clone(); let notification: ClientJsonrpcNotification = serde_json::from_str(&entry.0.body).unwrap(); let ClientJsonrpcNotification::TaskStatusNotification(notification) = notification else { panic!("Expected a TaskStatusNotification") }; assert_eq!(notification.params.status, TaskStatus::Completed); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/check_imports.rs
crates/rust-mcp-sdk/tests/check_imports.rs
// #[cfg(test)] // mod tests { // use std::fs::File; // use std::io::{self, Read}; // use std::path::{Path, MAIN_SEPARATOR_STR}; // // List of files to exclude from the check // const EXCLUDED_FILES: &[&str] = &["src/schema.rs"]; // // Check all .rs files for incorrect `use rust_mcp_schema` imports // #[test] // fn check_no_rust_mcp_schema_imports() { // let mut errors = Vec::new(); // // Walk through the src directory // for entry in walk_src_dir("src").expect("Failed to read src directory") { // let entry = entry.unwrap(); // let path = entry.path(); // // only check files with .rs extension // if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("rs") { // let abs_path = path.to_string_lossy(); // let relative_path = path.strip_prefix("src").unwrap_or(&path); // let path_str = relative_path.to_string_lossy(); // // Skip excluded files // if EXCLUDED_FILES // .iter() // .any(|&excluded| abs_path.replace(MAIN_SEPARATOR_STR, "/") == excluded) // { // continue; // } // // Read the file content // match read_file(&path) { // Ok(content) => { // // Check for `use rust_mcp_schema` // if content.contains("use rust_mcp_schema") { // errors.push(format!( // "File {abs_path} contains `use rust_mcp_schema`. Use `use crate::schema` instead." // )); // } // } // Err(e) => { // errors.push(format!("Failed to read file `{path_str}`: {e}")); // } // } // } // } // // If there are any errors, fail the test with all error messages // if !errors.is_empty() { // panic!( // "Found {} incorrect imports:\n{}\n\n", // errors.len(), // errors.join("\n") // ); // } // } // // Helper function to walk the src directory // fn walk_src_dir<P: AsRef<Path>>( // path: P, // ) -> io::Result<impl Iterator<Item = io::Result<std::fs::DirEntry>>> { // Ok(std::fs::read_dir(path)?.flat_map(|entry| { // let entry = entry.unwrap(); // let path = entry.path(); // if path.is_dir() { // // Recursively walk subdirectories // walk_src_dir(&path) // .into_iter() // .flatten() // .collect::<Vec<_>>() // } else { // vec![Ok(entry)] // } // })) // } // // Helper function to read file content // fn read_file(path: &Path) -> io::Result<String> { // let mut file = File::open(path)?; // let mut content = String::new(); // file.read_to_string(&mut content)?; // Ok(content) // } // }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_client_runtime.rs
crates/rust-mcp-sdk/tests/test_client_runtime.rs
#[cfg(unix)] use common::UVX_SERVER_GIT; use common::{test_client_info, TestClientHandler, NPX_SERVER_EVERYTHING}; use rust_mcp_sdk::{ mcp_client::{client_runtime, McpClientOptions}, McpClient, StdioTransport, ToMcpClientHandler, TransportOptions, }; #[path = "common/common.rs"] pub mod common; #[tokio::test] async fn tets_client_launch_npx_server() { // NPM based MCP servers should launch successfully using `npx` let transport = StdioTransport::create_with_server_launch( "npx", vec!["-y".into(), NPX_SERVER_EVERYTHING.into()], None, TransportOptions::default(), ) .unwrap(); let client = client_runtime::create_client(McpClientOptions { client_details: test_client_info(), transport, handler: TestClientHandler {}.to_mcp_client_handler(), task_store: None, server_task_store: None, }); client.clone().start().await.unwrap(); let server_capabilities = client.server_capabilities().unwrap(); let server_info = client.server_info().unwrap(); assert!(!server_info.server_info.name.is_empty()); assert!(!server_info.server_info.version.is_empty()); assert!(server_capabilities.tools.is_some()); } #[cfg(unix)] #[tokio::test] async fn tets_client_launch_uvx_server() { // The Python-based MCP server should launch successfully // provided that `uvx` is installed and accessible in the system's PATH let transport = StdioTransport::create_with_server_launch( "uvx", vec![UVX_SERVER_GIT.into()], None, TransportOptions::default(), ) .unwrap(); let client = client_runtime::create_client(McpClientOptions { client_details: test_client_info(), transport, handler: TestClientHandler {}.to_mcp_client_handler(), task_store: None, server_task_store: None, }); client.clone().start().await.unwrap(); let server_capabilities = client.server_capabilities().unwrap(); let server_info = client.server_info().unwrap(); assert!(!server_info.server_info.name.is_empty()); assert!(!server_info.server_info.version.is_empty()); assert!(server_capabilities.tools.is_some()); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_protocol_compatibility.rs
crates/rust-mcp-sdk/tests/test_protocol_compatibility.rs
#[path = "common/common.rs"] pub mod common; mod protocol_compatibility_on_server { use rust_mcp_sdk::mcp_server::{McpServerOptions, ServerHandler, ToMcpServerHandler}; use rust_mcp_sdk::schema::{InitializeResult, RpcError, INTERNAL_ERROR}; use crate::common::task_runner::McpTaskRunner; use crate::common::{ test_client_info, test_server_common::{test_server_details, TestServerHandler}, }; async fn handle_initialize_request( client_protocol_version: &str, ) -> Result<InitializeResult, RpcError> { let handler = TestServerHandler { mcp_task_runner: McpTaskRunner::new(), }; let mut initialize_request = test_client_info(); initialize_request.protocol_version = client_protocol_version.to_string(); let transport = rust_mcp_sdk::StdioTransport::new(rust_mcp_sdk::TransportOptions::default()).unwrap(); // mock unused runtime let runtime = rust_mcp_sdk::mcp_server::server_runtime::create_server(McpServerOptions { server_details: test_server_details(), transport, handler: TestServerHandler { mcp_task_runner: McpTaskRunner::new(), } .to_mcp_server_handler(), task_store: None, client_task_store: None, }); handler .handle_initialize_request(initialize_request, runtime) .await } #[tokio::test] async fn tets_protocol_compatibility_equal() { let result = handle_initialize_request("2025-03-26").await; assert!(result.is_ok()); let protocol_version = result.unwrap().protocol_version; assert_eq!(protocol_version, "2025-03-26"); } #[tokio::test] async fn tets_protocol_compatibility_downgrade() { let result = handle_initialize_request("2024_11_05").await; assert!(result.is_ok()); let protocol_version = result.unwrap().protocol_version; assert_eq!(protocol_version, "2024_11_05"); } #[tokio::test] async fn tets_protocol_compatibility_unsupported() { let result = handle_initialize_request("2034_11_05").await; assert!(result.is_err()); assert!(matches!(result, Err(err) if err.code == INTERNAL_ERROR)); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_tool_box.rs
crates/rust-mcp-sdk/tests/test_tool_box.rs
#[path = "common/common.rs"] pub mod common; use common::sample_tools::{SayGoodbyeTool, SayHelloTool}; use rust_mcp_sdk::tool_box; // Define tool box without trailing comma tool_box!(FileSystemToolsNoComma, [SayHelloTool, SayGoodbyeTool]); // Define tool box with trailing comma // Related Issue: https://github.com/rust-mcp-stack/rust-mcp-sdk/issues/57 tool_box!(FileSystemTools, [SayHelloTool, SayGoodbyeTool,]); #[test] fn test_tools_with_trailing_comma() { let tools = FileSystemTools::tools(); assert_eq!(tools.len(), 2); assert_eq!(tools[0].name, "say_hello"); assert_eq!(tools[1].name, "say_goodbye"); } #[test] fn test_tools_without_trailing_comma() { let tools = FileSystemToolsNoComma::tools(); assert_eq!(tools.len(), 2); assert_eq!(tools[0].name, "say_hello"); assert_eq!(tools[1].name, "say_goodbye"); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_server_sse.rs
crates/rust-mcp-sdk/tests/test_server_sse.rs
#[path = "common/common.rs"] pub mod common; #[cfg(feature = "hyper-server")] mod tets_server_sse { use std::{sync::Arc, time::Duration}; use crate::common::{ sse_data, sse_event, test_server_common::{ collect_sse_lines, create_test_server, TestIdGenerator, INITIALIZE_REQUEST, }, }; use reqwest::Client; use rust_mcp_sdk::mcp_server::HyperServerOptions; use rust_mcp_sdk::schema::{ schema_utils::{ResultFromServer, ServerMessage}, ServerResult, }; use tokio::time::sleep; #[tokio::test] async fn tets_sse_endpoint_event_default() { let server_options = HyperServerOptions { port: 8081, session_id_generator: Some(Arc::new(TestIdGenerator::new(vec![ "AAA-BBB-CCC".to_string() ]))), ..Default::default() }; let base_url = format!("http://{}:{}", server_options.host, server_options.port); let server_endpoint = format!("{}{}", base_url, server_options.sse_endpoint()); let server = create_test_server(server_options); let handle = server.server_handle(); let server_task = tokio::spawn(async move { server.start().await.unwrap(); eprintln!("Server 1 is down"); }); sleep(Duration::from_millis(750)).await; let client = Client::new(); println!("connecting to : {server_endpoint}"); // Act: Connect to the SSE endpoint and read the event stream let response = client .get(server_endpoint) .header("Accept", "text/event-stream") .send() .await .expect("Failed to connect to SSE endpoint"); assert_eq!( response.headers().get("content-type").map(|v| v.as_bytes()), Some(b"text/event-stream" as &[u8]), "Response content-type should be text/event-stream" ); let lines = collect_sse_lines(response, 2, Duration::from_secs(5)) .await .unwrap(); assert_eq!(sse_event(&lines[0]), "endpoint"); assert_eq!(sse_data(&lines[1]), "/messages?sessionId=AAA-BBB-CCC"); let message_endpoint = format!("{}{}", base_url, sse_data(&lines[1])); let res = client .post(message_endpoint) .header("Content-Type", "application/json") .body(INITIALIZE_REQUEST.to_string()) .send() .await .unwrap(); assert!(res.status().is_success()); handle.graceful_shutdown(Some(Duration::from_millis(1))); server_task.await.unwrap(); } #[tokio::test] async fn tets_sse_message_endpoint_query_hash() { let server_options = HyperServerOptions { port: 8082, custom_messages_endpoint: Some( "/custom-msg-endpoint?something=true&otherthing=false#section-59".to_string(), ), session_id_generator: Some(Arc::new(TestIdGenerator::new(vec![ "AAA-BBB-CCC".to_string() ]))), ..Default::default() }; let base_url = format!("http://{}:{}", server_options.host, server_options.port); let server_endpoint = format!("{}{}", base_url, server_options.sse_endpoint()); let server = create_test_server(server_options); let handle = server.server_handle(); let server_task = tokio::spawn(async move { server.start().await.unwrap(); eprintln!("Server 2 is down"); }); sleep(Duration::from_millis(750)).await; let client = Client::new(); println!("connecting to : {server_endpoint}"); // Act: Connect to the SSE endpoint and read the event stream let response = client .get(server_endpoint) .header("Accept", "text/event-stream") .send() .await .expect("Failed to connect to SSE endpoint"); assert_eq!( response.headers().get("content-type").map(|v| v.as_bytes()), Some(b"text/event-stream" as &[u8]), "Response content-type should be text/event-stream" ); let lines = collect_sse_lines(response, 2, Duration::from_secs(5)) .await .unwrap(); assert_eq!(sse_event(&lines[0]), "endpoint"); assert_eq!( sse_data(&lines[1]), "/custom-msg-endpoint?something=true&otherthing=false&sessionId=AAA-BBB-CCC#section-59" ); let message_endpoint = format!("{}{}", base_url, sse_data(&lines[1])); let res = client .post(message_endpoint) .header("Content-Type", "application/json") .body(INITIALIZE_REQUEST.to_string()) .send() .await .unwrap(); assert!(res.status().is_success()); handle.graceful_shutdown(Some(Duration::from_millis(1))); server_task.await.unwrap(); } #[tokio::test] async fn tets_sse_custom_message_endpoint() { let server_options = HyperServerOptions { port: 8083, custom_messages_endpoint: Some( "/custom-msg-endpoint?something=true&otherthing=false#section-59".to_string(), ), session_id_generator: Some(Arc::new(TestIdGenerator::new(vec![ "AAA-BBB-CCC".to_string() ]))), ..Default::default() }; let base_url = format!("http://{}:{}", server_options.host, server_options.port); let server_endpoint = format!("{}{}", base_url, server_options.sse_endpoint()); let server = create_test_server(server_options); let handle = server.server_handle(); let server_task = tokio::spawn(async move { server.start().await.unwrap(); eprintln!("Server 3 is down"); }); sleep(Duration::from_millis(750)).await; let client = Client::new(); println!("connecting to : {server_endpoint}"); // Act: Connect to the SSE endpoint and read the event stream let response = client .get(server_endpoint) .header("Accept", "text/event-stream") .send() .await .expect("Failed to connect to SSE endpoint"); assert_eq!( response.headers().get("content-type").map(|v| v.as_bytes()), Some(b"text/event-stream" as &[u8]), "Response content-type should be text/event-stream" ); let message_endpoint = format!( "{}{}", base_url, "/custom-msg-endpoint?something=true&otherthing=false&sessionId=AAA-BBB-CCC#section-59" ); let res = client .post(message_endpoint) .header("Content-Type", "application/json") .body(INITIALIZE_REQUEST.to_string()) .send() .await .unwrap(); assert!(res.status().is_success()); let lines = collect_sse_lines(response, 5, Duration::from_secs(5)) .await .unwrap(); let init_response = sse_data(&lines[3]); let result = serde_json::from_str::<ServerMessage>(&init_response).unwrap(); assert!(matches!(result, ServerMessage::Response(response) if matches!(&response.result, ResultFromServer::InitializeResult(init_result) if init_result.server_info.name == "Test MCP Server"))); handle.graceful_shutdown(Some(Duration::from_millis(1))); server_task.await.unwrap(); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_streamable_http_client.rs
crates/rust-mcp-sdk/tests/test_streamable_http_client.rs
#[path = "common/common.rs"] pub mod common; use crate::common::{ create_sse_response, debug_wiremock, random_port, test_client_common::{ initialize_client, InitializedClient, INITIALIZE_REQUEST, TEST_SESSION_ID, }, test_server_common::{ create_start_server, LaunchedServer, TestIdGenerator, INITIALIZE_RESPONSE, }, wait_for_n_requests, wiremock_request, MockBuilder, SimpleMockServer, SseEvent, }; use common::test_client_common::create_client; use hyper::{Method, StatusCode}; use rust_mcp_schema::{ schema_utils::{ ClientJsonrpcRequest, ClientMessage, CustomRequest, MessageFromServer, RequestFromClient, RequestFromServer, ResultFromServer, RpcMessage, ServerMessage, }, RequestId, }; use rust_mcp_sdk::{ error::McpSdkError, mcp_server::HyperServerOptions, McpClient, TransportError, MCP_LAST_EVENT_ID_HEADER, }; use serde_json::{json, Map, Value}; use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration}; use wiremock::{ http::{HeaderName, HeaderValue}, matchers::{body_json_string, header, method, path}, Mock, MockServer, ResponseTemplate, }; // should send JSON-RPC messages via POST #[tokio::test] async fn should_send_json_rpc_messages_via_post() { // Start a mock server let mock_server = MockServer::start().await; // initialize response let response = create_sse_response(INITIALIZE_RESPONSE); // initialize request and response Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string(INITIALIZE_REQUEST)) .respond_with(response) .expect(1) .mount(&mock_server) .await; // receive initialized notification Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string( r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, )) .respond_with(ResponseTemplate::new(202)) .expect(1) .mount(&mock_server) .await; let mcp_url = format!("{}/mcp", mock_server.uri()); let (client, _) = create_client(&mcp_url, None).await; client.clone().start().await.unwrap(); let received_request = wiremock_request(&mock_server, 0).await; let header_values = received_request .headers .get(&HeaderName::from_str("accept").unwrap()) .unwrap(); assert!(header_values.contains(&HeaderValue::from_str("application/json").unwrap())); assert!(header_values.contains(&HeaderValue::from_str("text/event-stream").unwrap())); wait_for_n_requests(&mock_server, 2, None).await; } // should send batch messages #[tokio::test] async fn should_send_batch_messages() { let InitializedClient { client, mcp_url: _, mock_server, } = initialize_client(None, None).await; let response = create_sse_response( r#"[{"id":"id1","jsonrpc":"2.0", "result":{}},{"id":"id2","jsonrpc":"2.0", "result":{}}]"#, ); Mock::given(method("POST")) .and(path("/mcp")) .respond_with(response) // .expect(1) .mount(&mock_server) .await; let message_1: ClientMessage = ClientJsonrpcRequest::new( RequestId::String("id1".to_string()), RequestFromClient::CustomRequest(CustomRequest { method: "test1".to_string(), params: Some(Map::new()), }), ) .into(); let message_2: ClientMessage = ClientJsonrpcRequest::new( RequestId::String("id2".to_string()), RequestFromClient::CustomRequest(CustomRequest { method: "test2".to_string(), params: Some(Map::new()), }), ) .into(); let result = client .send_batch(vec![message_1, message_2], None) .await .unwrap() .unwrap(); // two results for two requests assert_eq!(result.len(), 2); assert!(result.iter().all(|r| { let id = r.request_id().unwrap(); id == RequestId::String("id1".to_string()) || id == RequestId::String("id2".to_string()) })); // not an Error assert!(result .iter() .all(|r| matches!(r, ServerMessage::Response(_)))); // debug_wiremock(&mock_server).await; } // should store session ID received during initialization #[tokio::test] async fn should_store_session_id_received_during_initialization() { // Start a mock server let mock_server = MockServer::start().await; // initialize response let response = create_sse_response(INITIALIZE_RESPONSE).append_header("mcp-session-id", "test-session-id"); // initialize request and response Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string(INITIALIZE_REQUEST)) .respond_with(response) .expect(1) .mount(&mock_server) .await; // receive initialized notification Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string( r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, )) .and(header("mcp-session-id", "test-session-id")) .respond_with(ResponseTemplate::new(202)) .expect(1) .mount(&mock_server) .await; let mcp_url = format!("{}/mcp", mock_server.uri()); let (client, _) = create_client(&mcp_url, None).await; client.clone().start().await.unwrap(); let received_request = wiremock_request(&mock_server, 0).await; let header_values = received_request .headers .get(&HeaderName::from_str("accept").unwrap()) .unwrap(); assert!(header_values.contains(&HeaderValue::from_str("application/json").unwrap())); assert!(header_values.contains(&HeaderValue::from_str("text/event-stream").unwrap())); wait_for_n_requests(&mock_server, 2, None).await; } // should terminate session with DELETE request #[tokio::test] async fn should_terminate_session_with_delete_request() { let InitializedClient { client, mcp_url: _, mock_server, } = initialize_client(Some(TEST_SESSION_ID.to_string()), None).await; Mock::given(method("DELETE")) .and(path("/mcp")) .and(header("mcp-session-id", "test-session-id")) .respond_with(ResponseTemplate::new(202)) .expect(1) .mount(&mock_server) .await; client.terminate_session().await; } // should handle 405 response when server doesn't support session termination #[tokio::test] async fn should_handle_405_unsupported_session_termination() { let InitializedClient { client, mcp_url: _, mock_server, } = initialize_client(Some(TEST_SESSION_ID.to_string()), None).await; Mock::given(method("DELETE")) .and(path("/mcp")) .and(header("mcp-session-id", "test-session-id")) .respond_with(ResponseTemplate::new(405)) .expect(1) .mount(&mock_server) .await; client.terminate_session().await; } // should handle 404 response when session expires #[tokio::test] async fn should_handle_404_response_when_session_expires() { let InitializedClient { client, mcp_url: _, mock_server, } = initialize_client(Some(TEST_SESSION_ID.to_string()), None).await; Mock::given(method("POST")) .and(path("/mcp")) .respond_with(ResponseTemplate::new(404)) .expect(1) .mount(&mock_server) .await; let result = client.ping(None, None).await; matches!( result, Err(McpSdkError::Transport(TransportError::SessionExpired)) ); } // should handle non-streaming JSON response #[tokio::test] async fn should_handle_non_streaming_json_response() { let InitializedClient { client, mcp_url: _, mock_server, } = initialize_client(Some(TEST_SESSION_ID.to_string()), None).await; let response = ResponseTemplate::new(200) .set_body_json(json!({ "id":1,"jsonrpc":"2.0", "result":{"something":"good"} })) .insert_header("Content-Type", "application/json"); Mock::given(method("POST")) .and(path("/mcp")) .respond_with(response) .expect(1) .mount(&mock_server) .await; let request = RequestFromClient::CustomRequest(CustomRequest { method: "test1".to_string(), params: Some(Map::new()), }); let result = client.request(request, None).await.unwrap(); let ResultFromServer::Result(result) = result else { panic!("Wrong result variant!") }; let extra = result.extra.unwrap(); assert_eq!(extra.get("something").unwrap(), "good"); } // should handle successful initial GET connection for SSE #[tokio::test] async fn should_handle_successful_initial_get_connection_for_sse() { // Start a mock server let mock_server = MockServer::start().await; // initialize response let response = create_sse_response(INITIALIZE_RESPONSE); // initialize request and response Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string(INITIALIZE_REQUEST)) .respond_with(response) .expect(1) .mount(&mock_server) .await; // receive initialized notification Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string( r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, )) .respond_with(ResponseTemplate::new(202)) .expect(1) .mount(&mock_server) .await; // let payload = r#"{"jsonrpc": "2.0", "method": "serverNotification", "params": {}}"#; // let mut body = String::new(); body.push_str("data: Connection established\n\n"); let response = ResponseTemplate::new(200) .set_body_raw(body.into_bytes(), "text/event-stream") .append_header("Connection", "keep-alive"); // Mount the mock for a GET request Mock::given(method("GET")) .and(path("/mcp")) .respond_with(response) .mount(&mock_server) .await; let mcp_url = format!("{}/mcp", mock_server.uri()); let (client, _) = create_client(&mcp_url, None).await; client.clone().start().await.unwrap(); let requests = mock_server.received_requests().await.unwrap(); let get_request = requests .iter() .find(|r| r.method == wiremock::http::Method::Get); assert!(get_request.is_some()) } #[tokio::test] async fn should_receive_server_initiated_messaged() { let server_options = HyperServerOptions { port: random_port(), session_id_generator: Some(Arc::new(TestIdGenerator::new(vec![ "AAA-BBB-CCC".to_string() ]))), enable_json_response: Some(false), ..Default::default() }; let LaunchedServer { hyper_runtime, streamable_url, sse_url, sse_message_url, event_store, } = create_start_server(server_options).await; let (client, message_history) = create_client(&streamable_url, None).await; client.clone().start().await.unwrap(); tokio::time::sleep(Duration::from_secs(1)).await; let result = hyper_runtime .ping(&"AAA-BBB-CCC".to_string(), None, None) .await .unwrap(); let lock = message_history.read().await; let ping_request = lock .iter() .find(|m| { matches!( m, MessageFromServer::RequestFromServer(RequestFromServer::PingRequest(_)) ) }) .unwrap(); let MessageFromServer::RequestFromServer(RequestFromServer::PingRequest(_)) = ping_request else { panic!("Request is not a match!") }; assert!(result.meta.is_some()); let v = result.meta.unwrap().get("meta_number").unwrap().clone(); assert!(matches!(v, Value::Number(value) if value.as_i64().unwrap()==1515)) //1515 is passed from TestClientHandler } // should attempt initial GET connection and handle 405 gracefully #[tokio::test] async fn should_attempt_initial_get_connection_and_handle_405_gracefully() { // Start a mock server let mock_server = MockServer::start().await; // initialize response let response = create_sse_response(INITIALIZE_RESPONSE); // initialize request and response Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string(INITIALIZE_REQUEST)) .respond_with(response) .expect(1) .mount(&mock_server) .await; // Mount the mock for a GET request Mock::given(method("GET")) .and(path("/mcp")) .respond_with(ResponseTemplate::new(405)) .mount(&mock_server) .await; // receive initialized notification Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string( r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, )) .respond_with(ResponseTemplate::new(202)) .expect(1) .mount(&mock_server) .await; // let payload = r#"{"jsonrpc": "2.0", "method": "serverNotification", "params": {}}"#; // let mut body = String::new(); body.push_str("data: Connection established\n\n"); let _response = ResponseTemplate::new(405) .set_body_raw(body.into_bytes(), "text/event-stream") .append_header("Connection", "keep-alive"); let mcp_url = format!("{}/mcp", mock_server.uri()); let (client, _) = create_client(&mcp_url, None).await; client.clone().start().await.unwrap(); let requests = mock_server.received_requests().await.unwrap(); let get_request = requests .iter() .find(|r| r.method == wiremock::http::Method::Get); assert!(get_request.is_some()); // send a batch message, runtime should work as expected with no issue let response = create_sse_response( r#"[{"id":"id1","jsonrpc":"2.0", "result":{}},{"id":"id2","jsonrpc":"2.0", "result":{}}]"#, ); Mock::given(method("POST")) .and(path("/mcp")) .respond_with(response) // .expect(1) .mount(&mock_server) .await; let message_1: ClientMessage = ClientJsonrpcRequest::new( RequestId::String("id1".to_string()), RequestFromClient::CustomRequest(CustomRequest { method: "test1".to_string(), params: Some(Map::new()), }), ) .into(); let message_2: ClientMessage = ClientJsonrpcRequest::new( RequestId::String("id2".to_string()), RequestFromClient::CustomRequest(CustomRequest { method: "test2".to_string(), params: Some(Map::new()), }), ) .into(); let result = client .send_batch(vec![message_1, message_2], None) .await .unwrap() .unwrap(); // two results for two requests assert_eq!(result.len(), 2); assert!(result.iter().all(|r| { let id = r.request_id().unwrap(); id == RequestId::String("id1".to_string()) || id == RequestId::String("id2".to_string()) })); } // should handle multiple concurrent SSE streams #[tokio::test] async fn should_handle_multiple_concurrent_sse_streams() { let InitializedClient { client, mcp_url: _, mock_server, } = initialize_client(None, None).await; let message_1: ClientMessage = ClientJsonrpcRequest::new( RequestId::String("id1".to_string()), RequestFromClient::CustomRequest(CustomRequest { method: "test1".to_string(), params: Some(Map::new()), }), ) .into(); let message_2: ClientMessage = ClientJsonrpcRequest::new( RequestId::String("id2".to_string()), RequestFromClient::CustomRequest(CustomRequest { method: "test2".to_string(), params: Some(Map::new()), }), ) .into(); Mock::given(method("POST")) .and(path("/mcp")) .respond_with(|req: &wiremock::Request| { let body_string = String::from_utf8(req.body.clone()).unwrap(); if body_string.contains("test3") { create_sse_response(r#"{"id":1,"jsonrpc":"2.0", "result":{}}"#) } else { create_sse_response( r#"[{"id":"id1","jsonrpc":"2.0", "result":{}},{"id":"id2","jsonrpc":"2.0", "result":{}}]"#, ) } }) .expect(2) .mount(&mock_server) .await; let message_3 = RequestFromClient::CustomRequest(CustomRequest { method: "test3".to_string(), params: Some(Map::new()), }); let request1 = client.send_batch(vec![message_1, message_2], None); let request2 = client.send(message_3.into(), None, None); // Run them concurrently and wait for both let (res_batch, res_single) = tokio::join!(request1, request2); let res_batch = res_batch.unwrap().unwrap(); // two results for two requests in the batch assert_eq!(res_batch.len(), 2); assert!(res_batch.iter().all(|r| { let id = r.request_id().unwrap(); id == RequestId::String("id1".to_string()) || id == RequestId::String("id2".to_string()) })); // not an Error assert!(res_batch .iter() .all(|r| matches!(r, ServerMessage::Response(_)))); let res_single = res_single.unwrap().unwrap(); let ServerMessage::Response(res_single) = res_single else { panic!("invalid respinse type, expected Result!") }; assert!(matches!(res_single.id, RequestId::Integer(id) if id==1)); } // should throw error when invalid content-type is received #[tokio::test] async fn should_throw_error_when_invalid_content_type_is_received() { let InitializedClient { client, mcp_url: _, mock_server, } = initialize_client(None, None).await; Mock::given(method("POST")) .and(path("/mcp")) .respond_with(ResponseTemplate::new(200).set_body_raw( r#"{"id":0,"jsonrpc":"2.0", "result":{}}"#.to_string().into_bytes(), "text/plain", )) .expect(1) .mount(&mock_server) .await; let result = client.ping(None, None).await; let Err(McpSdkError::Transport(TransportError::UnexpectedContentType(content_type))) = result else { panic!("Expected a TransportError::UnexpectedContentType error!"); }; assert_eq!(content_type, "text/plain"); } // should always send specified custom headers #[tokio::test] async fn should_always_send_specified_custom_headers() { let mut headers = HashMap::new(); headers.insert("X-Custom-Header".to_string(), "CustomValue".to_string()); let InitializedClient { client, mcp_url: _, mock_server, } = initialize_client(None, Some(headers)).await; Mock::given(method("POST")) .and(path("/mcp")) .respond_with(ResponseTemplate::new(200).set_body_raw( r#"{"id":1,"jsonrpc":"2.0", "result":{}}"#.to_string().into_bytes(), "application/json", )) .expect(1) .mount(&mock_server) .await; let _result = client.ping(None, None).await; let requests = mock_server.received_requests().await.unwrap(); assert_eq!(requests.len(), 4); assert!(requests .iter() .all(|r| r.headers.get(&"X-Custom-Header".into()).unwrap().as_str() == "CustomValue")); debug_wiremock(&mock_server).await } // should reconnect a GET-initiated notification stream that fails #[tokio::test] async fn should_reconnect_a_get_initiated_notification_stream_that_fails() { // Start a mock server let mock_server = MockServer::start().await; // initialize response let response = create_sse_response(INITIALIZE_RESPONSE); // initialize request and response Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string(INITIALIZE_REQUEST)) .respond_with(response) .expect(1) .mount(&mock_server) .await; // two GET Mock, each expects one call , first time it fails, second retry it succeeds let response = ResponseTemplate::new(502) .set_body_raw("".to_string().into_bytes(), "text/event-stream") .append_header("Connection", "keep-alive"); // Mount the mock for a GET request Mock::given(method("GET")) .and(path("/mcp")) .respond_with(response) .expect(1) .up_to_n_times(1) .mount(&mock_server) .await; let response = ResponseTemplate::new(200) .set_body_raw( "data: Connection established\n\n".to_string().into_bytes(), "text/event-stream", ) .append_header("Connection", "keep-alive"); Mock::given(method("GET")) .and(path("/mcp")) .respond_with(response) .expect(1) .mount(&mock_server) .await; // receive initialized notification Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string( r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, )) .respond_with(ResponseTemplate::new(202)) .expect(1) .mount(&mock_server) .await; let mcp_url = format!("{}/mcp", mock_server.uri()); let (client, _) = create_client(&mcp_url, None).await; client.clone().start().await.unwrap(); } //****************** Resumability ****************** // should pass lastEventId when reconnecting #[tokio::test] async fn should_pass_last_event_id_when_reconnecting() { let msg = r#"{"jsonrpc":"2.0","method":"notifications/message","params":{"data":{},"level":"debug"}}"#; let mocks = vec![ MockBuilder::new_sse(Method::POST, "/mcp".to_string(), INITIALIZE_RESPONSE).build(), MockBuilder::new_breakable_sse( Method::GET, "/mcp".to_string(), SseEvent { data: Some(msg.into()), event: Some("message".to_string()), id: None, }, Duration::from_millis(100), 5, ) .expect(2) .build(), MockBuilder::new_sse( Method::POST, "/mcp".to_string(), r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, ) .build(), ]; let (url, handle) = SimpleMockServer::start_with_mocks(mocks).await; let mcp_url = format!("{url}/mcp"); let mut headers = HashMap::new(); headers.insert("X-Custom-Header".to_string(), "CustomValue".to_string()); let (client, _) = create_client(&mcp_url, Some(headers)).await; client.clone().start().await.unwrap(); assert!(client.is_initialized()); // give it time for re-connection tokio::time::sleep(Duration::from_secs(2)).await; let request_history = handle.get_history().await; let get_requests: Vec<_> = request_history .iter() .filter(|r| r.0.method == Method::GET) .collect(); // there should be more than one GET reueat, indicating reconnection assert!(get_requests.len() > 1); let Some(last_get_request) = get_requests.last() else { panic!("Unable to find last GET request!"); }; let last_event_id = last_get_request .0 .headers .get(axum::http::HeaderName::from_static( MCP_LAST_EVENT_ID_HEADER, )); // last-event-id should be sent assert!( matches!(last_event_id, Some(last_event_id) if last_event_id.to_str().unwrap().starts_with("msg-id")) ); // custom headers should be passed for all GET requests assert!(get_requests.iter().all(|r| r .0 .headers .get(axum::http::HeaderName::from_str("X-Custom-Header").unwrap()) .unwrap() .to_str() .unwrap() == "CustomValue")); println!("last_event_id {:?} ", last_event_id.unwrap()); } // should NOT reconnect a POST-initiated stream that fails #[tokio::test] async fn should_not_reconnect_a_post_initiated_stream_that_fails() { let mocks = vec![ MockBuilder::new_sse(Method::POST, "/mcp".to_string(), INITIALIZE_RESPONSE) .expect(1) .build(), MockBuilder::new_sse(Method::GET, "/mcp".to_string(), "".to_string()) .with_status(StatusCode::METHOD_NOT_ALLOWED) .build(), MockBuilder::new_sse( Method::POST, "/mcp".to_string(), r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, ) .expect(1) .build(), MockBuilder::new_breakable_sse( Method::POST, "/mcp".to_string(), SseEvent { data: Some("msg".to_string()), event: None, id: None, }, Duration::ZERO, 0, ) .build(), ]; let (url, handle) = SimpleMockServer::start_with_mocks(mocks).await; let mcp_url = format!("{url}/mcp"); let mut headers = HashMap::new(); headers.insert("X-Custom-Header".to_string(), "CustomValue".to_string()); let (client, _) = create_client(&mcp_url, Some(headers)).await; client.clone().start().await.unwrap(); assert!(client.is_initialized()); let result = client.send_roots_list_changed(None).await; assert!(result.is_err()); tokio::time::sleep(Duration::from_secs(2)).await; let request_history = handle.get_history().await; let post_requests: Vec<_> = request_history .iter() .filter(|r| r.0.method == Method::POST) .collect(); assert_eq!(post_requests.len(), 3); // initialize, initialized, root_list_changed } //****************** Auth ****************** // attempts auth flow on 401 during POST request // invalidates all credentials on InvalidClientError during auth // invalidates all credentials on UnauthorizedClientError during auth //invalidates tokens on InvalidGrantError during auth //****************** Others ****************** // custom fetch in auth code paths // should support custom reconnection options // uses custom fetch implementation if provided // should have exponential backoff with configurable maxRetries
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/test_streamable_http_server.rs
crates/rust-mcp-sdk/tests/test_streamable_http_server.rs
use crate::common::{ random_port, read_sse_event, read_sse_event_from_stream, send_delete_request, send_get_request, send_option_request, send_post_request, test_server_common::{ create_start_server, initialize_request, LaunchedServer, TestIdGenerator, }, TestTokenVerifier, ONE_MILLISECOND, }; use http::header::{ACCEPT, ACCESS_CONTROL_ALLOW_ORIGIN, AUTHORIZATION, CONTENT_TYPE}; use hyper::StatusCode; use rust_mcp_macros::{mcp_elicit, JsonSchema}; use rust_mcp_schema::{ schema_utils::{ ClientJsonrpcRequest, ClientJsonrpcResponse, ClientMessage, ClientMessages, FromMessage, MessageFromClient, NotificationFromClient, RequestFromClient, ResultFromServer, RpcMessage, SdkError, SdkErrorCodes, ServerJsonrpcNotification, ServerJsonrpcRequest, ServerJsonrpcResponse, ServerMessages, }, CallToolRequestParams, ElicitResult, ElicitResultContent, ListRootsResult, LoggingLevel, LoggingMessageNotificationParams, RequestId, ServerRequest, }; use rust_mcp_sdk::{ auth::{AuthInfo, AuthMetadataBuilder, AuthProvider, RemoteAuthProvider}, event_store::InMemoryEventStore, mcp_server::HyperServerOptions, schema::ResultFromClient, task_store::InMemoryTaskStore, }; use serde_json::{json, Map, Value}; use std::{ collections::HashMap, error::Error, sync::Arc, time::{Duration, SystemTime}, vec, }; use url::Url; #[path = "common/common.rs"] pub mod common; pub const VALID_ACCESS_TOKEN: &str = "valid-access-token"; pub async fn initialize_server( enable_json_response: Option<bool>, auth_token_map: Option<HashMap<&str, AuthInfo>>, ) -> Result<(LaunchedServer, String), Box<dyn Error>> { let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new(RequestId::Integer(0), initialize_request()); let port = random_port(); let auth = auth_token_map.and_then(|token_map| { let mut token_map: HashMap<String, AuthInfo> = token_map .into_iter() .map(|(k, v)| (k.to_string(), v)) .collect(); token_map.insert( VALID_ACCESS_TOKEN.to_string(), AuthInfo { token_unique_id: VALID_ACCESS_TOKEN.to_string(), client_id: Some("valid-client-id".to_string()), scopes: Some(vec!["mcp".to_string(), "mcp:tools".to_string()]), expires_at: Some(SystemTime::now() + Duration::from_secs(90)), audience: None, extra: None, user_id: None, }, ); let (auth_server_meta, protected_resource_met) = AuthMetadataBuilder::new("http://127.0.0.1:3000/mcp") .issuer("http://localhost:3030") .authorization_servers(vec!["http://localhost:3030"]) .authorization_endpoint("/authorize") .token_endpoint("/token") .scopes_supported(vec!["mcp:tools".to_string()]) .introspection_endpoint("/introspect") .resource_name("MCP Test Server".to_string()) .build() .unwrap(); let token_verifier = TestTokenVerifier::new(token_map); Some(RemoteAuthProvider::new( auth_server_meta, protected_resource_met, Box::new(token_verifier), None, )) }); let oauth_metadata_provider = auth.map(|v| -> Arc<dyn AuthProvider> { Arc::new(v) }); let server_options = HyperServerOptions { port, session_id_generator: Some(Arc::new(TestIdGenerator::new(vec![ "AAA-BBB-CCC".to_string() ]))), enable_json_response, ping_interval: Duration::from_secs(1), event_store: Some(Arc::new(InMemoryEventStore::default())), auth: oauth_metadata_provider, task_store: Some(Arc::new(InMemoryTaskStore::new(None))), client_task_store: Some(Arc::new(InMemoryTaskStore::new(None))), ..Default::default() }; let server = create_start_server(server_options).await; tokio::time::sleep(Duration::from_millis(250)).await; let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), None, Some(HashMap::from([ ( AUTHORIZATION.as_str(), format!("Bearer {VALID_ACCESS_TOKEN}").as_str(), ), (CONTENT_TYPE.as_str(), "application/json"), (ACCEPT.as_str(), "application/json, text/event-stream"), ])), ) .await .expect("Request failed"); let session_id = response .headers() .get("mcp-session-id") .unwrap() .to_str() .unwrap() .to_owned(); Ok((server, session_id)) } // should initialize server and generate session ID #[tokio::test] async fn should_initialize_server_and_generate_session_id() { let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new(RequestId::Integer(0), initialize_request().into()); let server_options = HyperServerOptions { port: random_port(), session_id_generator: Some(Arc::new(TestIdGenerator::new(vec![ "AAA-BBB-CCC".to_string() ]))), ..Default::default() }; let server = create_start_server(server_options).await; tokio::time::sleep(Duration::from_millis(250)).await; let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), None, None, ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::OK); assert_eq!( response.headers().get("content-type").unwrap(), "text/event-stream" ); assert!(response.headers().get("mcp-session-id").is_some()); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should reject batch initialize request #[tokio::test] async fn should_reject_batch_initialize_request() { let server_options = HyperServerOptions { port: random_port(), session_id_generator: Some(Arc::new(TestIdGenerator::new(vec![ "AAA-BBB-CCC".to_string() ]))), enable_json_response: None, ..Default::default() }; let server = create_start_server(server_options).await; tokio::time::sleep(Duration::from_millis(250)).await; let first_init_message = ClientJsonrpcRequest::new( RequestId::String("first-init".to_string()), initialize_request().into(), ); let second_init_message = ClientJsonrpcRequest::new( RequestId::String("second-init".to_string()), initialize_request().into(), ); let messages = vec![ ClientMessage::Request(first_init_message), ClientMessage::Request(second_init_message), ]; let batch_message = ClientMessages::Batch(messages); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&batch_message).unwrap(), None, None, ) .await .expect("Request failed"); let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::INVALID_REQUEST as i64); assert!(error_data .message .contains("Only one initialization request is allowed")); } // should handle post requests via sse response correctly #[tokio::test] async fn should_handle_post_requests_via_sse_response_correctly() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::ListToolsRequest(None), ); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::OK); let events = read_sse_event(response, 1).await.unwrap(); let message: ServerJsonrpcResponse = serde_json::from_str(&events[0].2).unwrap(); assert!(matches!(message.id, RequestId::Integer(1))); let ResultFromServer::ListToolsResult(result) = message.result else { panic!("invalid ListToolsResult") }; assert_eq!(result.tools.len(), 2); let tool = &result.tools[0]; assert_eq!(tool.name, "say_hello"); assert_eq!( tool.description.as_ref().unwrap(), r#"Accepts a person's name and says a personalized "Hello" to that person"# ); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should call a tool and return the result #[tokio::test] async fn should_call_a_tool_and_return_the_result() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let mut map = Map::new(); map.insert("name".to_string(), Value::String("Ali".to_string())); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::CallToolRequest(CallToolRequestParams { arguments: Some(map), name: "say_hello".to_string(), meta: None, task: None, }) .into(), ); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::OK); let events = read_sse_event(response, 1).await.unwrap(); let message: ServerJsonrpcResponse = serde_json::from_str(&events[0].2).unwrap(); assert!(matches!(message.id, RequestId::Integer(1))); let ResultFromServer::CallToolResult(result) = message.result else { panic!("invalid CallToolResult") }; assert_eq!(result.content.len(), 1); assert_eq!( result.content[0].as_text_content().unwrap().text, "Hello, Ali!" ); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should reject requests without a valid session ID #[tokio::test] async fn should_reject_requests_without_a_valid_session_id() { let (server, _session_id) = initialize_server(None, None).await.unwrap(); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::ListToolsRequest(None), ); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), None, // pass no session id None, ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::BAD_REQUEST); let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::BAD_REQUEST as i64); // Typescript sdk uses -32000 code server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should reject invalid session ID #[tokio::test] async fn should_reject_invalid_session_id() { let (server, _session_id) = initialize_server(None, None).await.unwrap(); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::ListToolsRequest(None), ); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some("invalid-session-id"), None, ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::NOT_FOUND); let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::SESSION_NOT_FOUND as i64); // Typescript sdk uses -32001 code server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } pub async fn get_standalone_stream( streamable_url: &str, session_id: &str, last_event_id: Option<&str>, ) -> reqwest::Response { let mut headers = HashMap::new(); headers.insert("Accept", "text/event-stream , application/json"); headers.insert("mcp-session-id", session_id); headers.insert("mcp-protocol-version", "2025-03-26"); if let Some(last_event_id) = last_event_id { headers.insert("last-event-id", last_event_id); } let response = send_get_request(streamable_url, Some(headers)) .await .unwrap(); response } // should establish standalone SSE stream and receive server-initiated messages #[tokio::test] async fn should_establish_standalone_stream_and_receive_server_messages() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let response = get_standalone_stream(&server.streamable_url, &session_id, None).await; assert_eq!(response.status(), StatusCode::OK); assert_eq!( response .headers() .get("mcp-session-id") .unwrap() .to_str() .unwrap(), session_id ); assert_eq!( response .headers() .get("content-type") .unwrap() .to_str() .unwrap(), "text/event-stream" ); // Send a notification (server-initiated message) that should appear on SSE stream server .hyper_runtime .notify_log_message( &session_id, LoggingMessageNotificationParams { data: json!("Test notification"), level: rust_mcp_schema::LoggingLevel::Info, logger: None, meta: None, }, ) .await .unwrap(); let events = read_sse_event(response, 1).await.unwrap(); let message: ServerJsonrpcNotification = serde_json::from_str(&events[0].2).unwrap(); let ServerJsonrpcNotification::LoggingMessageNotification(notification) = message else { panic!("invalid message received!"); }; assert_eq!(notification.params.level, LoggingLevel::Info); assert_eq!( notification.params.data.as_str().unwrap(), "Test notification" ); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should establish standalone SSE stream and receive server-initiated requests #[tokio::test] async fn should_establish_standalone_stream_and_receive_server_requests() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let response = get_standalone_stream(&server.streamable_url, &session_id, None).await; assert_eq!(response.status(), StatusCode::OK); assert_eq!( response .headers() .get("mcp-session-id") .unwrap() .to_str() .unwrap(), session_id ); assert_eq!( response .headers() .get("content-type") .unwrap() .to_str() .unwrap(), "text/event-stream" ); let hyper_server = Arc::new(server.hyper_runtime); // Send two server-initiated request that should appear on SSE stream with a valid request_id for _ in 0..2 { let hyper_server_clone = hyper_server.clone(); let session_id_clone = session_id.to_string(); tokio::spawn(async move { hyper_server_clone .list_roots(&session_id_clone, None) .await .unwrap(); }); } for i in 0..2 { // send responses back to the server for two server initiated requests let json_rpc_message: ClientJsonrpcResponse = ClientJsonrpcResponse::new( RequestId::Integer(i), ListRootsResult { meta: None, roots: vec![], } .into(), ); send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); } // read two events from the sse stream let events = read_sse_event(response, 2).await.unwrap(); let message1: ServerJsonrpcRequest = serde_json::from_str(&events[0].2).unwrap(); let ServerJsonrpcRequest::ListRootsRequest(_) = message1 else { panic!("invalid message received!"); }; let message2: ServerJsonrpcRequest = serde_json::from_str(&events[1].2).unwrap(); let ServerJsonrpcRequest::ListRootsRequest(_) = message1 else { panic!("invalid message received!"); }; // ensure request_ids are unique assert!(message2.request_id() != message1.request_id()); hyper_server.graceful_shutdown(ONE_MILLISECOND); } // should not close GET SSE stream after sending multiple server notifications #[tokio::test] async fn should_not_close_get_sse_stream() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let response = get_standalone_stream(&server.streamable_url, &session_id, None).await; assert_eq!(response.status(), StatusCode::OK); server .hyper_runtime .notify_log_message( &session_id, LoggingMessageNotificationParams { data: json!("First notification"), level: rust_mcp_schema::LoggingLevel::Info, logger: None, meta: None, }, ) .await .unwrap(); let mut stream = response.bytes_stream(); let event = read_sse_event_from_stream(&mut stream, 1).await.unwrap()[0].clone(); let message: ServerJsonrpcNotification = serde_json::from_str(&event.2).unwrap(); let ServerJsonrpcNotification::LoggingMessageNotification(notification) = message else { panic!("invalid message received!"); }; assert_eq!(notification.params.level, LoggingLevel::Info); assert_eq!( notification.params.data.as_str().unwrap(), "First notification" ); server .hyper_runtime .notify_log_message( &session_id, LoggingMessageNotificationParams { data: json!("Second notification"), level: rust_mcp_schema::LoggingLevel::Info, logger: None, meta: None, }, ) .await .unwrap(); let event = read_sse_event_from_stream(&mut stream, 1).await.unwrap()[0].clone(); let message: ServerJsonrpcNotification = serde_json::from_str(&event.2).unwrap(); let ServerJsonrpcNotification::LoggingMessageNotification(notification_2) = message else { panic!("invalid message received!"); }; assert_eq!(notification_2.params.level, LoggingLevel::Info); assert_eq!( notification_2.params.data.as_str().unwrap(), "Second notification" ); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } //should reject second SSE stream for the same session #[tokio::test] async fn should_reject_second_sse_stream_for_the_same_session() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let response = get_standalone_stream(&server.streamable_url, &session_id, None).await; assert_eq!(response.status(), StatusCode::OK); let second_response = get_standalone_stream(&server.streamable_url, &session_id, None).await; assert_eq!(second_response.status(), StatusCode::CONFLICT); let error_data: SdkError = second_response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::BAD_REQUEST as i64); // Typescript sdk uses -32000 code server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should reject GET requests without Accept: text/event-stream header #[tokio::test] async fn should_reject_get_requests() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let mut headers = HashMap::new(); headers.insert("Accept", "application/json"); headers.insert("mcp-session-id", &session_id); headers.insert("mcp-protocol-version", "2025-03-26"); let response = send_get_request(&server.streamable_url, Some(headers)) .await .unwrap(); assert_eq!(response.status(), StatusCode::NOT_ACCEPTABLE); //406 let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::BAD_REQUEST as i64); // Typescript sdk uses -32000 code assert!(error_data.message.contains("must accept text/event-stream")); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should reject POST requests without proper Accept header #[tokio::test] async fn reject_post_requests_without_accept_header() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::ListToolsRequest(None).into(), ); let mut headers = HashMap::new(); headers.insert("Accept", "application/json"); headers.insert("mcp-session-id", &session_id); headers.insert("mcp-protocol-version", "2025-03-26"); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), Some(headers), ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::NOT_ACCEPTABLE); //406 let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::BAD_REQUEST as i64); // Typescript sdk uses -32000 code assert!(error_data .message .contains("must accept both application/json and text/event-stream")); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } //should reject unsupported Content-Type #[tokio::test] async fn should_reject_unsupported_content_type() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::ListToolsRequest(None), ); let mut headers = HashMap::new(); headers.insert("Content-Type", "text/plain"); headers.insert("Accept", "application/json, text/event-stream"); headers.insert("mcp-session-id", &session_id); headers.insert("mcp-protocol-version", "2025-03-26"); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), Some(headers), ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); //415 let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::BAD_REQUEST as i64); // Typescript sdk uses -32000 code assert!(error_data .message .contains("Content-Type must be application/json")); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should handle JSON-RPC batch notification messages with 202 response #[tokio::test] async fn should_handle_batch_notification_messages_with_202_response() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let batch_notification = ClientMessages::Batch(vec![ ClientMessage::from_message( MessageFromClient::NotificationFromClient( NotificationFromClient::RootsListChangedNotification(None), ), None, ) .unwrap(), ClientMessage::from_message( MessageFromClient::NotificationFromClient( NotificationFromClient::RootsListChangedNotification(None), ), None, ) .unwrap(), ]); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&batch_notification).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::ACCEPTED); } // should properly handle invalid JSON data #[tokio::test] async fn should_properly_handle_invalid_json_data() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let response = send_post_request( &server.streamable_url, "This is not a valid JSON", Some(&session_id), None, ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::BAD_REQUEST); let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::PARSE_ERROR as i64); assert!(error_data.message.contains("Parse Error")); } // should send response messages to the connection that sent the request #[tokio::test] async fn should_send_response_messages_to_the_connection_that_sent_the_request() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let json_rpc_message_1: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::ListToolsRequest(None).into(), ); let mut map = Map::new(); map.insert("name".to_string(), Value::String("Ali".to_string())); let json_rpc_message_2: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::CallToolRequest(CallToolRequestParams { arguments: Some(map), name: "say_hello".to_string(), meta: None, task: None, }) .into(), ); let response_1 = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message_1).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); let response_2 = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message_2).unwrap(), Some(&session_id), None, ) .await .expect("Request failed"); assert_eq!(response_1.status(), StatusCode::OK); assert_eq!(response_2.status(), StatusCode::OK); let events = read_sse_event(response_2, 1).await.unwrap(); let message: ServerJsonrpcResponse = serde_json::from_str(&events[0].2).unwrap(); assert!(matches!(message.id, RequestId::Integer(1))); let ResultFromServer::CallToolResult(result) = message.result else { panic!("invalid CallToolResult") }; assert_eq!(result.content.len(), 1); assert_eq!( result.content[0].as_text_content().unwrap().text, "Hello, Ali!" ); let events = read_sse_event(response_1, 1).await.unwrap(); let message: ServerJsonrpcResponse = serde_json::from_str(&events[0].2).unwrap(); assert!(matches!(message.id, RequestId::Integer(1))); let ResultFromServer::ListToolsResult(result) = message.result else { panic!("invalid ListToolsResult") }; assert_eq!(result.tools.len(), 2); let tool = &result.tools[0]; assert_eq!(tool.name, "say_hello"); assert_eq!( tool.description.as_ref().unwrap(), r#"Accepts a person's name and says a personalized "Hello" to that person"# ); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should properly handle DELETE requests and close session #[tokio::test] async fn should_properly_handle_delete_requests_and_close_session() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let mut headers = HashMap::new(); headers.insert("Content-Type", "text/plain"); headers.insert("Accept", "application/json, text/event-stream"); headers.insert("mcp-session-id", &session_id); headers.insert("mcp-protocol-version", "2025-03-26"); let response = send_delete_request(&server.streamable_url, Some(&session_id), Some(headers)) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::OK); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should reject DELETE requests with invalid session ID #[tokio::test] async fn should_reject_delete_requests_with_invalid_session_id() { let (server, _session_id) = initialize_server(None, None).await.unwrap(); let mut headers = HashMap::new(); headers.insert("Content-Type", "text/plain"); headers.insert("Accept", "application/json, text/event-stream"); headers.insert("mcp-session-id", "invalid-session-id"); headers.insert("mcp-protocol-version", "2025-03-26"); let response = send_delete_request( &server.streamable_url, Some("invalid-session-id"), Some(headers), ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::NOT_FOUND); let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::SESSION_NOT_FOUND as i64); // Typescript sdk uses -32001 code assert!(error_data.message.contains("Session not found")); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } /** * protocol version header validation */ // should accept requests without protocol version header #[tokio::test] async fn should_accept_requests_without_protocol_version_header() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let mut headers = HashMap::new(); headers.insert("Content-Type", "application/json"); headers.insert("Accept", "application/json, text/event-stream"); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::ListToolsRequest(None).into(), ); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), Some(headers), ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::OK); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should reject requests with unsupported protocol version #[tokio::test] async fn should_reject_requests_with_unsupported_protocol_version() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let mut headers = HashMap::new(); headers.insert("Content-Type", "application/json"); headers.insert("Accept", "application/json, text/event-stream"); headers.insert("mcp-protocol-version", "1999-15-21"); let json_rpc_message: ClientJsonrpcRequest = ClientJsonrpcRequest::new( RequestId::Integer(1), RequestFromClient::ListToolsRequest(None).into(), ); let response = send_post_request( &server.streamable_url, &serde_json::to_string(&json_rpc_message).unwrap(), Some(&session_id), Some(headers), ) .await .expect("Request failed"); assert_eq!(response.status(), StatusCode::BAD_REQUEST); let error_data: SdkError = response.json().await.unwrap(); assert_eq!(error_data.code, SdkErrorCodes::BAD_REQUEST as i64); // Typescript sdk uses -32000 code assert!(error_data.message.contains("Unsupported protocol version")); server.hyper_runtime.graceful_shutdown(ONE_MILLISECOND); server.hyper_runtime.await_server().await.unwrap() } // should handle protocol version validation for get requests #[tokio::test] async fn should_handle_protocol_version_validation_for_get_requests() { let (server, session_id) = initialize_server(None, None).await.unwrap(); let mut headers = HashMap::new(); headers.insert("Content-Type", "application/json"); headers.insert("Accept", "application/json, text/event-stream"); headers.insert("mcp-protocol-version", "1999-15-21"); headers.insert("mcp-session-id", &session_id); let response = send_get_request(&server.streamable_url, Some(headers)) .await .unwrap();
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
true
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/common/test_server.rs
crates/rust-mcp-sdk/tests/common/test_server.rs
#[cfg(feature = "hyper-server")] pub mod test_server_common { use crate::common::sample_tools::{DisplayAuthInfo, SayHelloTool, TaskAugmentedTool}; use crate::common::task_runner::{McpTaskRunner, TaskJobInfo}; use async_trait::async_trait; use rust_mcp_schema::schema_utils::{CallToolError, RequestFromClient}; use rust_mcp_schema::{ CallToolRequestParams, CallToolResult, CreateTaskResult, ListToolsResult, PaginatedRequestParams, ProtocolVersion, RpcError, ServerTaskRequest, ServerTaskTools, ServerTasks, }; use rust_mcp_sdk::event_store::EventStore; use rust_mcp_sdk::id_generator::IdGenerator; use rust_mcp_sdk::mcp_icon; use rust_mcp_sdk::mcp_server::hyper_runtime::HyperRuntime; use rust_mcp_sdk::schema::{ ClientCapabilities, Implementation, InitializeRequest, InitializeRequestParams, InitializeResult, ServerCapabilities, ServerCapabilitiesTools, }; use rust_mcp_sdk::task_store::{CreateTaskOptions, ServerTaskCreator}; use rust_mcp_sdk::{ mcp_server::{ hyper_server, HyperServer, HyperServerOptions, ServerHandler, ToMcpServerHandler, }, McpServer, SessionId, }; use serde_json::{Map, Value}; use std::sync::{Arc, RwLock}; use std::time::Duration; use tokio::time::timeout; use tokio_stream::StreamExt; pub const INITIALIZE_REQUEST: &str = r#"{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"sampling":{},"roots":{"listChanged":true}},"clientInfo":{"name":"reqwest-test","version":"0.1.0"}}}"#; pub const PING_REQUEST: &str = r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#; pub const INITIALIZE_RESPONSE: &str = r#"{"result":{"protocolVersion":"2025-11-25","capabilities":{"prompts":{},"resources":{"subscribe":true},"tools":{},"logging":{}},"serverInfo":{"name":"example-servers/everything","version":"1.0.0"}},"jsonrpc":"2.0","id":0}"#; pub struct LaunchedServer { pub hyper_runtime: HyperRuntime, pub streamable_url: String, pub sse_url: String, pub sse_message_url: String, pub event_store: Option<Arc<dyn EventStore>>, } pub fn initialize_request() -> RequestFromClient { RequestFromClient::InitializeRequest(InitializeRequestParams { capabilities: ClientCapabilities { ..Default::default() }, client_info: Implementation { name: "test-server".to_string(), title: None, version: "0.1.0".to_string(), description: None, icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: None, }, protocol_version: ProtocolVersion::V2025_11_25.to_string(), meta: None, }) } pub fn test_server_details() -> InitializeResult { InitializeResult { // server name and version server_info: Implementation { name: "Test MCP Server".to_string(), version: "0.1.0".to_string(), title: None, description: None, icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: None, }, capabilities: ServerCapabilities { // indicates that server support mcp tools tools: Some(ServerCapabilitiesTools { list_changed: None }), tasks: Some(ServerTasks{ cancel: Some(Map::new()), list: Some(Map::new()), requests: Some(ServerTaskRequest{ tools: Some(ServerTaskTools{ call: Some(Map::new()) })} )}), ..Default::default() // Using default values for other fields }, meta: None, instructions: Some("server instructions...".to_string()), protocol_version: ProtocolVersion::V2025_11_25.to_string(), } } pub struct TestServerHandler { pub mcp_task_runner: McpTaskRunner, } #[async_trait] impl ServerHandler for TestServerHandler { async fn handle_list_tools_request( &self, _params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListToolsResult, RpcError> { Ok(ListToolsResult { meta: None, next_cursor: None, tools: vec![SayHelloTool::tool(), TaskAugmentedTool::tool()], }) } async fn handle_call_tool_request( &self, params: CallToolRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CallToolResult, CallToolError> { match params.name.as_str() { "say_hello" => { let tool = SayHelloTool { name: params.arguments.unwrap()["name"] .as_str() .unwrap() .to_string(), }; Ok(tool.call_tool().unwrap()) } "display_auth_info" => { let tool = DisplayAuthInfo {}; Ok(tool.call_tool(runtime.auth_info_cloned().await).unwrap()) } _ => Ok( CallToolError::unknown_tool(format!("Unknown tool: {}", params.name)).into(), ), _ => Ok( CallToolError::unknown_tool(format!("Unknown tool: {}", params.name)).into(), ), } } async fn handle_task_augmented_tool_call( &self, params: CallToolRequestParams, task_creator: ServerTaskCreator, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CreateTaskResult, CallToolError> { let task_meta = params.task.unwrap(); let task_store = runtime.task_store().unwrap(); let job_info: TaskJobInfo = serde_json::from_value(Value::Object(params.arguments.unwrap())).unwrap(); let task = task_creator .create_task(CreateTaskOptions { ttl: task_meta.ttl, poll_interval: None, meta: job_info.meta.clone(), }) .await; let task = self .mcp_task_runner .run_server_task(task, task_store, job_info, runtime.session_id()) .await; Ok(CreateTaskResult { meta: None, task }) } } pub fn create_test_server(options: HyperServerOptions) -> HyperServer { hyper_server::create_server( test_server_details(), TestServerHandler { mcp_task_runner: McpTaskRunner::new(), } .to_mcp_server_handler(), options, ) } pub async fn create_start_server(options: HyperServerOptions) -> LaunchedServer { let streamable_url = options.streamable_http_url(); let sse_url = options.sse_url(); let sse_message_url = options.sse_message_url(); let event_store_clone = options.event_store.clone(); let server = hyper_server::create_server( test_server_details(), TestServerHandler { mcp_task_runner: McpTaskRunner::new(), } .to_mcp_server_handler(), options, ); let hyper_runtime = HyperRuntime::create(server).await.unwrap(); tokio::time::sleep(Duration::from_millis(75)).await; LaunchedServer { hyper_runtime, streamable_url, sse_url, sse_message_url, event_store: event_store_clone, } } // Tests the session ID generator, ensuring it returns a sequence of predefined session IDs. pub struct TestIdGenerator { constant_ids: Vec<SessionId>, generated: RwLock<usize>, } impl TestIdGenerator { pub fn new(constant_ids: Vec<SessionId>) -> Self { TestIdGenerator { constant_ids, generated: RwLock::new(0), } } } impl<T> IdGenerator<T> for TestIdGenerator where T: From<String>, { fn generate(&self) -> T { let mut lock = self.generated.write().unwrap(); *lock += 1; if *lock > self.constant_ids.len() { *lock = 1; } T::from(self.constant_ids[*lock - 1].to_owned()) } } pub async fn collect_sse_lines( response: reqwest::Response, line_count: usize, read_timeout: Duration, ) -> Result<Vec<String>, Box<dyn std::error::Error>> { let mut collected_lines = Vec::new(); let mut stream = response.bytes_stream(); let result = timeout(read_timeout, async { while let Some(chunk) = stream.next().await { let chunk = chunk.map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?; let chunk_str = String::from_utf8_lossy(&chunk); // Split the chunk into lines let lines: Vec<&str> = chunk_str.lines().collect(); // Add each line to the collected_lines vector for line in lines { collected_lines.push(line.to_string()); // Check if we have collected 5 lines if collected_lines.len() >= line_count { return Ok(collected_lines.clone()); } } } // If the stream ends before collecting 5 lines, return what we have Ok(collected_lines.clone()) }) .await; // Handle timeout or stream result match result { Ok(Ok(lines)) => Ok(lines), Ok(Err(e)) => Err(e), Err(_) => Err(Box::new(std::io::Error::new( std::io::ErrorKind::TimedOut, format!( "Timed out waiting for 5 lines, received({}): {}", collected_lines.len(), collected_lines.join(" \n ") ), ))), } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/common/test_client.rs
crates/rust-mcp-sdk/tests/common/test_client.rs
use async_trait::async_trait; use rust_mcp_schema::{ schema_utils::{MessageFromServer, RequestFromServer}, CreateTaskResult, ElicitRequestParams, ElicitResult, ElicitResultAction, ElicitResultContent, ElicitResultContentPrimitive, LoggingMessageNotificationParams, PingRequest, RequestParams, RpcError, TaskStatus, TaskStatusNotificationParams, }; use rust_mcp_sdk::{ mcp_client::ClientHandler, schema::{NotificationFromServer, ResultFromClient}, task_store::{ClientTaskCreator, CreateTaskOptions}, McpClient, }; use serde_json::json; use std::{collections::HashMap, sync::Arc}; use tokio::sync::RwLock; use crate::common::task_runner::{McpTaskRunner, TaskJobInfo}; #[cfg(feature = "hyper-server")] pub mod test_client_common { use rust_mcp_schema::{ schema_utils::MessageFromServer, ClientCapabilities, ClientElicitation, ClientRoots, ClientSampling, ClientTaskElicitation, ClientTaskRequest, ClientTaskSampling, ClientTasks, Implementation, InitializeRequestParams, LATEST_PROTOCOL_VERSION, }; use rust_mcp_sdk::{ mcp_client::{client_runtime, ClientRuntime}, mcp_icon, task_store::InMemoryTaskStore, McpClient, RequestOptions, SessionId, StreamableTransportOptions, }; use serde_json::Map; use std::{collections::HashMap, sync::Arc, time::Duration}; use tokio::sync::RwLock; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use wiremock::{ matchers::{body_json_string, method, path}, Mock, MockServer, ResponseTemplate, }; use crate::common::{ create_sse_response, task_runner::McpTaskRunner, test_server_common::INITIALIZE_RESPONSE, wait_for_n_requests, }; pub struct InitializedClient { pub client: Arc<ClientRuntime>, pub mcp_url: String, pub mock_server: MockServer, } pub const TEST_SESSION_ID: &str = "test-session-id"; pub const INITIALIZE_REQUEST: &str = r#"{"id":0,"jsonrpc":"2.0","method":"initialize","params":{"capabilities":{"elicitation":{"form":{},"url":{}},"roots":{"listChanged":true},"sampling":{"context":{},"tools":{}},"tasks":{"cancel":{},"list":{},"requests":{"elicitation":{"create":{}},"sampling":{"createMessage":{}}}}},"clientInfo":{"icons":[{"mimeType":"image/png","sizes":["128x128"],"src":"https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png","theme":"dark"}],"name":"simple-rust-mcp-client-sse","title":"Simple Rust MCP Client (SSE)","version":"0.1.0"},"protocolVersion":"2025-11-25"}}"#; pub fn test_client_details() -> InitializeRequestParams { InitializeRequestParams { // capabilities: ClientCapabilities::default(), capabilities: { ClientCapabilities{ elicitation: Some(ClientElicitation{ form: Some(Map::new()), url: Some(Map::new()) }), experimental: None, roots: Some(ClientRoots{ list_changed: Some(true) }), sampling: Some(ClientSampling{ context: Some(Map::new()), tools: Some(Map::new()) }), tasks: Some(ClientTasks{ cancel: Some(Map::new()), list: Some(Map::new()), requests: Some(ClientTaskRequest{ elicitation: Some(ClientTaskElicitation{ create:Some( Map::new() )}), sampling: Some(ClientTaskSampling{ create_message: Some( Map::new() ) }) }) }), }}, client_info: Implementation { name: "simple-rust-mcp-client-sse".to_string(), version: "0.1.0".to_string(), title: Some("Simple Rust MCP Client (SSE)".to_string()), description: None, icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: None, }, protocol_version: LATEST_PROTOCOL_VERSION.into(), meta: None, } } pub async fn create_client( mcp_url: &str, custom_headers: Option<HashMap<String, String>>, ) -> (Arc<ClientRuntime>, Arc<RwLock<Vec<MessageFromServer>>>) { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| "info".into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let client_details: InitializeRequestParams = test_client_details(); let transport_options = StreamableTransportOptions { mcp_url: mcp_url.to_string(), request_options: RequestOptions { request_timeout: Duration::from_secs(2), custom_headers, ..RequestOptions::default() }, }; let message_history = Arc::new(RwLock::new(vec![])); let handler = super::TestClientHandler { message_history: message_history.clone(), mcp_task_runner: McpTaskRunner::new(), }; let client = client_runtime::with_transport_options( client_details, transport_options, handler, Some(Arc::new(InMemoryTaskStore::new(None))), Some(Arc::new(InMemoryTaskStore::new(None))), ); // client.clone().start().await.unwrap(); (client, message_history) } pub async fn initialize_client( session_id: Option<SessionId>, custom_headers: Option<HashMap<String, String>>, ) -> InitializedClient { let mock_server = MockServer::start().await; // initialize response let mut response = create_sse_response(INITIALIZE_RESPONSE); if let Some(session_id) = session_id { response = response.append_header("mcp-session-id", session_id.as_str()); } // initialize request and response Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string(INITIALIZE_REQUEST)) .respond_with(response) .expect(1) .mount(&mock_server) .await; // receive initialized notification Mock::given(method("POST")) .and(path("/mcp")) .and(body_json_string( r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, )) .respond_with(ResponseTemplate::new(202)) .expect(1) .mount(&mock_server) .await; let mcp_url = format!("{}/mcp", mock_server.uri()); let (client, _) = create_client(&mcp_url, custom_headers).await; client.clone().start().await.unwrap(); wait_for_n_requests(&mock_server, 2, None).await; InitializedClient { client, mcp_url, mock_server, } } } // Test handler pub struct TestClientHandler { message_history: Arc<RwLock<Vec<MessageFromServer>>>, mcp_task_runner: McpTaskRunner, } impl TestClientHandler { async fn register_message(&self, message: &MessageFromServer) { let mut lock = self.message_history.write().await; lock.push(message.clone()); } } #[async_trait] impl ClientHandler for TestClientHandler { async fn handle_ping_request( &self, params: Option<RequestParams>, _runtime: &dyn McpClient, ) -> std::result::Result<rust_mcp_schema::Result, RpcError> { self.register_message(&MessageFromServer::RequestFromServer( RequestFromServer::PingRequest(params), )) .await; Ok(rust_mcp_schema::Result { meta: Some(json!({"meta_number":1515}).as_object().unwrap().to_owned()), extra: None, }) } async fn handle_logging_message_notification( &self, params: LoggingMessageNotificationParams, _runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { self.register_message(&MessageFromServer::NotificationFromServer( NotificationFromServer::LoggingMessageNotification(params.clone()), )) .await; Ok(()) } async fn handle_task_status_notification( &self, params: TaskStatusNotificationParams, _runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { self.register_message(&MessageFromServer::NotificationFromServer( NotificationFromServer::TaskStatusNotification(params.clone()), )) .await; Ok(()) } async fn handle_task_augmented_elicit_request( &self, task_creator: ClientTaskCreator, params: ElicitRequestParams, runtime: &dyn McpClient, ) -> std::result::Result<CreateTaskResult, RpcError> { self.register_message(&MessageFromServer::RequestFromServer( RequestFromServer::ElicitRequest(params.clone()), )) .await; let ElicitRequestParams::FormParams(form_params) = params else { panic!("Expected a form elicitation!") }; let task_store = runtime.task_store().unwrap(); let task = task_creator .create_task(CreateTaskOptions { ttl: form_params.task.unwrap().ttl, poll_interval: None, meta: None, }) .await; let mut content: HashMap<String, ElicitResultContent> = HashMap::new(); content.insert( "content".to_string(), ElicitResultContentPrimitive::String("hello".to_string()).into(), ); let result = ResultFromClient::ElicitResult(ElicitResult { action: ElicitResultAction::Accept, content: Some(content), meta: None, }); let job_info: TaskJobInfo = TaskJobInfo { finish_in_ms: 300, status_interval_ms: 100, task_final_status: TaskStatus::Completed.to_string(), task_result: Some(serde_json::to_string(&result).unwrap()), meta: None, }; let task = self .mcp_task_runner .run_client_task(task, task_store, job_info, runtime.session_id().await) .await; Ok(CreateTaskResult { meta: None, task }) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/common/mock_server.rs
crates/rust-mcp-sdk/tests/common/mock_server.rs
use axum::{ body::Body, extract::Request, http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}, response::{ sse::{Event, KeepAlive}, IntoResponse, Response, Sse, }, routing::any, Router, }; use core::fmt; use futures::stream; use std::collections::VecDeque; use std::{future::Future, net::SocketAddr, pin::Pin}; use std::{ sync::{Arc, Mutex}, time::Duration, }; use tokio::net::TcpListener; pub struct SseEvent { /// The optional event type (e.g., "message"). pub event: Option<String>, /// The optional data payload of the event, stored as bytes. pub data: Option<String>, /// The optional event ID for reconnection or tracking purposes. pub id: Option<String>, } impl ToString for SseEvent { fn to_string(&self) -> String { let mut s = String::new(); if let Some(id) = &self.id { s.push_str("id: "); s.push_str(id); s.push('\n'); } if let Some(event) = &self.event { s.push_str("event: "); s.push_str(event); s.push('\n'); } if let Some(data) = &self.data { // Convert bytes to string safely, fallback if invalid UTF-8 for line in data.lines() { s.push_str("data: "); s.push_str(line); s.push('\n'); } } s.push('\n'); // End of event s } } impl fmt::Debug for SseEvent { /// Formats the `SseEvent` for debugging, converting the `data` field to a UTF-8 string /// (with lossy conversion if invalid UTF-8 is encountered). fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data_str = self.data.as_ref(); f.debug_struct("SseEvent") .field("event", &self.event) .field("data", &data_str) .field("id", &self.id) .finish() } } // RequestRecord stores the history of incoming requests #[derive(Clone, Debug)] pub struct RequestRecord { pub method: Method, pub path: String, pub headers: HeaderMap, pub body: String, } #[derive(Clone, Debug)] pub struct ResponseRecord { pub status: StatusCode, pub headers: HeaderMap, pub body: String, } // pub type BoxedStream = // Pin<Box<dyn futures::Stream<Item = Result<Event, std::convert::Infallible>> + Send>>; // pub type BoxedSseResponse = Sse<BoxedStream>; // pub type AsyncResponseFn = // Box<dyn Fn() -> Pin<Box<dyn Future<Output = BoxedSseResponse> + Send>> + Send + Sync>; type AsyncResponseFn = Box<dyn Fn() -> Pin<Box<dyn Future<Output = Response> + Send>> + Send + Sync>; // Mock defines a single mock response configuration // #[derive(Clone)] pub struct Mock { method: Method, path: String, response: String, response_func: Option<AsyncResponseFn>, header_map: HeaderMap, matcher: Option<Arc<dyn Fn(&str, &HeaderMap) -> bool + Send + Sync>>, remaining_calls: Option<Arc<Mutex<usize>>>, status: StatusCode, } // MockBuilder is a factory for creating Mock instances pub struct MockBuilder { method: Method, path: String, response: String, header_map: HeaderMap, response_func: Option<AsyncResponseFn>, matcher: Option<Arc<dyn Fn(&str, &HeaderMap) -> bool + Send + Sync>>, remaining_calls: Option<Arc<Mutex<usize>>>, status: StatusCode, } impl MockBuilder { fn new(method: Method, path: String, response: String, header_map: HeaderMap) -> Self { Self { method, path, response, response_func: None, header_map, matcher: None, status: StatusCode::OK, remaining_calls: None, // Default to unlimited calls } } fn new_with_func( method: Method, path: String, response_func: AsyncResponseFn, header_map: HeaderMap, ) -> Self { Self { method, path, response: String::new(), response_func: Some(response_func), header_map, matcher: None, status: StatusCode::OK, remaining_calls: None, // Default to unlimited calls } } pub fn new_breakable_sse( method: Method, path: String, repeating_message: SseEvent, interval: Duration, repeat: usize, ) -> Self { let message = Arc::new(repeating_message); let interval = interval; let max_repeats = repeat; let response_fn: AsyncResponseFn = Box::new({ let message = Arc::clone(&message); move || { let message = Arc::clone(&message); Box::pin(async move { // Construct SSE stream with count static messages using unfold let message_stream = stream::unfold(0, move |count| { let message = Arc::clone(&message); async move { if count >= max_repeats { return Some(( Err(std::io::Error::other("Message limit reached")), count, )); } tokio::time::sleep(interval).await; Some(( Ok(Event::default() .data(message.data.clone().unwrap_or("".into())) .id(message.id.clone().unwrap_or(format!("msg-id_{count}"))) .event(message.event.clone().unwrap_or("message".into()))), count + 1, )) } }); let sse_stream = Sse::new(message_stream) .keep_alive(KeepAlive::new().interval(Duration::from_secs(10))); sse_stream.into_response() }) } }); let mut header_map = HeaderMap::new(); header_map.insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream")); Self::new_with_func(method, path, response_fn, header_map) } pub fn with_matcher<F>(mut self, matcher: F) -> Self where F: Fn(&str, &HeaderMap) -> bool + Send + Sync + 'static, { self.matcher = Some(Arc::new(matcher)); self } pub fn add_header(mut self, key: HeaderName, val: HeaderValue) -> Self { self.header_map.insert(key, val); self } pub fn without_matcher(mut self) -> Self { self.matcher = None; self } pub fn expect(mut self, num_calls: usize) -> Self { self.remaining_calls = Some(Arc::new(Mutex::new(num_calls))); self } pub fn unlimited_calls(mut self) -> Self { self.remaining_calls = None; self } pub fn with_status(mut self, status: StatusCode) -> Self { self.status = status; self } pub fn build(self) -> Mock { Mock { method: self.method, path: self.path, response: self.response, header_map: self.header_map, matcher: self.matcher, remaining_calls: self.remaining_calls, status: self.status, response_func: self.response_func, } } // add_string with text/plain pub fn new_text(method: Method, path: String, response: impl Into<String>) -> Self { let mut header_map = HeaderMap::new(); header_map.insert(CONTENT_TYPE, HeaderValue::from_static("text/plain")); Self::new(method, path, response.into(), header_map) } /** MockBuilder::new_response( Method::GET, "/mcp".to_string(), Box::new(|| { // tokio::time::sleep(Duration::from_secs(1)).await; let json_response = Json(json!({ "status": "ok", "data": [1, 2, 3] })) .into_response(); Box::pin(async move { json_response }) }), ) .build(), */ pub fn new_response(method: Method, path: String, response_func: AsyncResponseFn) -> Self { Self::new_with_func(method, path, response_func, HeaderMap::new()) } // new_json with application/json pub fn new_json(method: Method, path: String, response: impl Into<String>) -> Self { let mut header_map = HeaderMap::new(); header_map.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); Self::new(method, path, response.into(), header_map) } // new_sse with text/event-stream pub fn new_sse(method: Method, path: String, response: impl Into<String>) -> Self { let response = format!(r#"data: {}{}"#, response.into(), '\n'); let mut header_map = HeaderMap::new(); header_map.insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream")); // ensure message ends with a \n\n , if needed let cr = if response.ends_with("\n\n") { "" } else { "\n\n" }; Self::new(method, path, format!("{response}{cr}"), header_map) } // new_raw with application/octet-stream pub fn new_raw(method: Method, path: String, response: impl Into<String>) -> Self { let mut header_map = HeaderMap::new(); header_map.insert( CONTENT_TYPE, HeaderValue::from_static("application/octet-stream"), ); Self::new(method, path, response.into(), header_map) } } // MockServerHandle provides access to the request history after the server starts pub struct MockServerHandle { history: Arc<Mutex<VecDeque<(RequestRecord, ResponseRecord)>>>, } impl MockServerHandle { pub async fn get_history(&self) -> Vec<(RequestRecord, ResponseRecord)> { let history = self.history.lock().unwrap(); history.iter().cloned().collect() } pub async fn print(&self) { let requests = self.get_history().await; let len = requests.len(); for (index, (request, response)) in requests.iter().enumerate() { println!( "\n--- Request {} of {len} ------------------------------------", index + 1 ); println!("Method: {}", request.method); println!("Path: {}", request.path); // println!("Headers: {:#?}", request.headers); println!("> headers "); for (key, values) in &request.headers { println!("{key}: {values:?}"); } println!("\n> Body"); println!("{}\n", &request.body); println!(">>>>> Response <<<<<"); println!("> status: {}", response.status); println!("> headers"); for (key, values) in &response.headers { println!("{key}: {values:?}"); } println!("> Body"); println!("{}", &response.body); } } } // MockServer is the main struct for configuring and starting the mock server pub struct SimpleMockServer { mocks: Vec<Mock>, history: Arc<Mutex<VecDeque<(RequestRecord, ResponseRecord)>>>, } impl Default for SimpleMockServer { fn default() -> Self { Self::new() } } impl SimpleMockServer { pub fn new() -> Self { Self { mocks: Vec::new(), history: Arc::new(Mutex::new(VecDeque::new())), } } pub async fn start_with_mocks(mocks: Vec<Mock>) -> (String, MockServerHandle) { let mut server = SimpleMockServer::new(); server.add_mocks(mocks); server.start().await } // Generic add function pub fn add_mock_builder(&mut self, builder: MockBuilder) -> &mut Self { self.mocks.push(builder.build()); self } pub fn add_mock(&mut self, mock: Mock) -> &mut Self { self.mocks.push(mock); self } pub fn add_mocks(&mut self, mock: Vec<Mock>) -> &mut Self { mock.into_iter().for_each(|m| self.mocks.push(m)); self } pub async fn start(self) -> (String, MockServerHandle) { let mocks = Arc::new(self.mocks); let history = Arc::clone(&self.history); async fn handler( mocks: Arc<Vec<Mock>>, history: Arc<Mutex<VecDeque<(RequestRecord, ResponseRecord)>>>, mut req: Request, ) -> impl IntoResponse { // Take ownership of the body using std::mem::take let body = std::mem::take(req.body_mut()); let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap(); let body_str = String::from_utf8_lossy(&body_bytes).to_string(); let request_record = RequestRecord { method: req.method().clone(), path: req.uri().path().to_string(), headers: req.headers().clone(), body: body_str.clone(), }; for m in mocks.iter() { if m.method != *req.method() || m.path != req.uri().path() { continue; } if let Some(matcher) = &m.matcher { if !(matcher)(&body_str, req.headers()) { continue; } } if let Some(remaining) = &m.remaining_calls { let mut rem = remaining.lock().unwrap(); if *rem == 0 { continue; } *rem -= 1; } let mut resp = match m.response_func.as_ref() { Some(get_response) => get_response().await.into_response(), None => Response::new(Body::from(m.response.clone())), }; // if let Some(resp_box) = &mut m.response_func.take() { // let response = resp_box.into_response(); // // *response.status_mut() = m.status; // // m.response_func = Some(Box::new(response)); // } // let mut resp = m.response_func.as_ref().unwrap().clone().to_owned(); // let resp = *resp; // *resp.into_response().status_mut() = m.status; // let mut response = m.response_func.as_ref().unwrap().clone(); // let mut response = m.response_func.as_ref().unwrap().clone().to_owned(); // let mut m = *response; // *response.status_mut() = m.status; // let resp = &*m.response_func.as_ref().unwrap().to_owned().clone().deref(); // let response = boxed_response.into_response(); // let mut resp = Response::new(Body::from(m.response.clone())); *resp.status_mut() = m.status; m.header_map.iter().for_each(|(k, v)| { resp.headers_mut().insert(k, v.clone()); }); let response_record = ResponseRecord { status: resp.status(), headers: resp.headers().clone(), body: m.response.clone(), }; { let mut hist = history.lock().unwrap(); hist.push_back((request_record, response_record)); } return resp; } let resp = Response::builder() .status(StatusCode::NOT_FOUND) .body(Body::empty()) .unwrap(); let response_record = ResponseRecord { status: resp.status(), headers: resp.headers().clone(), body: "".into(), }; { let mut hist = history.lock().unwrap(); hist.push_back((request_record, response_record)); } resp } let app = Router::new().route( "/{*path}", any(move |req: Request| handler(Arc::clone(&mocks), Arc::clone(&history), req)), ); let addr = SocketAddr::from(([127, 0, 0, 1], 0)); let listener = TcpListener::bind(addr).await.unwrap(); let local_addr = listener.local_addr().unwrap(); let url = format!("http://{local_addr}"); tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }); ( url, MockServerHandle { history: self.history, }, ) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/common/common.rs
crates/rust-mcp-sdk/tests/common/common.rs
mod mock_server; pub mod task_runner; mod test_client; mod test_server; use async_trait::async_trait; pub use mock_server::*; use reqwest::{Client, Response, Url}; use rust_mcp_macros::{mcp_tool, JsonSchema}; use rust_mcp_schema::ProtocolVersion; use rust_mcp_sdk::auth::{AuthInfo, AuthenticationError, OauthTokenVerifier}; use rust_mcp_sdk::mcp_client::ClientHandler; use rust_mcp_sdk::mcp_icon; use rust_mcp_sdk::schema::{ClientCapabilities, Implementation, InitializeRequestParams}; use std::collections::HashMap; use std::process; use std::sync::Once; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::time::timeout; use tokio_stream::StreamExt; use tracing_subscriber::EnvFilter; use wiremock::{MockServer, Request, ResponseTemplate}; pub use test_client::*; pub use test_server::*; pub const NPX_SERVER_EVERYTHING: &str = "@modelcontextprotocol/server-everything"; pub const ONE_MILLISECOND: Option<Duration> = Some(Duration::from_millis(1)); #[cfg(unix)] pub const UVX_SERVER_GIT: &str = "mcp-server-git"; static INIT: Once = Once::new(); pub fn init_tracing() { INIT.call_once(|| { let filter = EnvFilter::try_from_default_env() .or_else(|_| EnvFilter::try_new("tracing")) .unwrap(); tracing_subscriber::fmt().with_env_filter(filter).init(); }); } #[mcp_tool( name = "say_hello", description = "Accepts a person's name and says a personalized \"Hello\" to that person", title = "A tool that says hello!", idempotent_hint = false, destructive_hint = false, open_world_hint = false, read_only_hint = false, meta = r#"{"version": "1.0"}"# )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema)] pub struct SayHelloTool { /// The name of the person to greet with a "Hello". name: String, } pub async fn send_post_request( base_url: &str, message: &str, session_id: Option<&str>, post_headers: Option<HashMap<&str, &str>>, ) -> Result<Response, reqwest::Error> { let client = Client::new(); let url = Url::parse(base_url).expect("Invalid URL"); let mut headers = reqwest::header::HeaderMap::new(); let protocol_version = ProtocolVersion::V2025_06_18.to_string(); let post_headers = post_headers.unwrap_or({ let mut map: HashMap<&str, &str> = HashMap::new(); map.insert("Content-Type", "application/json"); map.insert("Accept", "application/json, text/event-stream"); map.insert("mcp-protocol-version", protocol_version.as_str()); map }); if let Some(sid) = session_id { headers.insert("mcp-session-id", sid.parse().unwrap()); } for (key, value) in post_headers { headers.insert( reqwest::header::HeaderName::from_bytes(key.as_bytes()).unwrap(), value.parse().unwrap(), ); } let body = message.to_string(); client.post(url).headers(headers).body(body).send().await } pub async fn send_delete_request( base_url: &str, session_id: Option<&str>, post_headers: Option<HashMap<&str, &str>>, ) -> Result<Response, reqwest::Error> { let client = Client::new(); let url = Url::parse(base_url).expect("Invalid URL"); let mut headers = reqwest::header::HeaderMap::new(); let protocol_version = ProtocolVersion::V2025_06_18.to_string(); let post_headers = post_headers.unwrap_or({ let mut map: HashMap<&str, &str> = HashMap::new(); map.insert("Content-Type", "application/json"); map.insert("Accept", "application/json, text/event-stream"); map.insert("mcp-protocol-version", protocol_version.as_str()); map }); if let Some(sid) = session_id { headers.insert("mcp-session-id", sid.parse().unwrap()); } for (key, value) in post_headers { headers.insert( reqwest::header::HeaderName::from_bytes(key.as_bytes()).unwrap(), value.parse().unwrap(), ); } client.delete(url).headers(headers).send().await } pub async fn send_get_request( base_url: &str, extra_headers: Option<HashMap<&str, &str>>, ) -> Result<Response, reqwest::Error> { let client = Client::new(); let url = Url::parse(base_url).expect("Invalid URL"); let mut headers = reqwest::header::HeaderMap::new(); if let Some(extra) = extra_headers { for (key, value) in extra { headers.insert( reqwest::header::HeaderName::from_bytes(key.as_bytes()).unwrap(), value.parse().unwrap(), ); } } client.get(url).headers(headers).send().await } pub async fn send_option_request( base_url: &str, extra_headers: Option<HashMap<&str, &str>>, ) -> Result<Response, reqwest::Error> { let client = Client::new(); let url = Url::parse(base_url).expect("Invalid URL"); let mut headers = reqwest::header::HeaderMap::new(); if let Some(extra) = extra_headers { for (key, value) in extra { headers.insert( reqwest::header::HeaderName::from_bytes(key.as_bytes()).unwrap(), value.parse().unwrap(), ); } } client .request(reqwest::Method::OPTIONS, url) .headers(headers) .send() .await } use futures::stream::Stream; // stream: &mut impl Stream<Item = Result<hyper::body::Bytes, hyper::Error>>, /// reads sse events and return them as (id, event, data) tuple pub async fn read_sse_event_from_stream( stream: &mut (impl Stream<Item = Result<hyper::body::Bytes, reqwest::Error>> + Unpin), event_count: usize, ) -> Option<Vec<(Option<String>, Option<String>, String)>> { let mut buffer = String::new(); let mut events = vec![]; while let Some(item) = stream.next().await { match item { Ok(chunk) => { let chunk_str = std::str::from_utf8(&chunk).unwrap(); buffer.push_str(chunk_str); while let Some(pos) = buffer.find("\n\n") { let (event_str, rest) = buffer.split_at(pos); let mut id = None; let mut event = None; let mut data = None; // Process the event string for line in event_str.lines() { if line.starts_with("id:") { id = Some(line.trim_start_matches("id:").trim().to_string()); } else if line.starts_with("event:") { event = Some(line.trim_start_matches("event:").trim().to_string()); } else if line.starts_with("data:") { data = Some(line.trim_start_matches("data:").trim().to_string()); } } // Update buffer after processing buffer = rest[2..].to_string(); // Skip "\n\n" // Only include events with data if let Some(data) = data { events.push((id, event, data)); if events.len().eq(&event_count) { return Some(events); } } } } Err(_e) => { return None; } } } if !events.is_empty() { Some(events) } else { None } } /// return sse event as (id, event, data) tuple pub async fn read_sse_event( response: Response, event_count: usize, ) -> Option<Vec<(Option<String>, Option<String>, String)>> { let mut stream = response.bytes_stream(); let events = read_sse_event_from_stream(&mut stream, event_count).await; events } pub fn test_client_info() -> InitializeRequestParams { InitializeRequestParams { capabilities: ClientCapabilities::default(), client_info: Implementation { name: "test-rust-mcp-client".into(), version: "0.1.0".into(), description: None, icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], title: None, website_url: None, }, protocol_version: ProtocolVersion::V2025_03_26.to_string(), meta: None, } } pub struct TestClientHandler; #[async_trait] impl ClientHandler for TestClientHandler {} pub fn sse_event(sse_raw: &str) -> String { sse_raw.replace("event: ", "") } pub fn sse_data(sse_raw: &str) -> String { sse_raw.replace("data: ", "") } // Simple Xorshift PRNG struct struct Xorshift { state: u64, } impl Xorshift { // Initialize with a seed based on system time and process ID fn new() -> Self { // Get nanoseconds since UNIX epoch let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("System time error") .as_nanos() as u64; // Get process ID for additional entropy let pid = process::id() as u64; // Combine nanos and pid with a simple mix let seed = nanos ^ (pid << 32) ^ (nanos.rotate_left(17)); Xorshift { state: seed | 1 } // Ensure non-zero seed } // Generate the next random u64 using Xorshift fn next_u64(&mut self) -> u64 { let mut x = self.state; self.state = x.wrapping_add(0x9E3779B97F4A7C15); x = (x ^ (x >> 30)).wrapping_mul(0xBF58476D1CE4E5B9); x = (x ^ (x >> 27)).wrapping_mul(0x94D049BB133111EB); x ^ (x >> 31) } // Generate a random u16 within a range [min, max] fn next_u16_range(&mut self, min: u16, max: u16) -> u16 { assert!(max >= min, "max must be greater than or equal to min"); let range = (max - min + 1) as u64; min + (self.next_u64() % range) as u16 } } // Generate a random port number in the range [8081, 15000] pub fn random_port() -> u16 { const MIN_PORT: u16 = 8081; const MAX_PORT: u16 = 15000; let mut rng = Xorshift::new(); rng.next_u16_range(MIN_PORT, MAX_PORT) } pub fn random_port_old() -> u16 { let min: u16 = 8081; let max: u16 = 15000; let range = max - min + 1; let now = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("systime error!"); // Combine seconds and nanoseconds for better entropy let nanos = now.subsec_nanos() as u64; let secs = now.as_secs(); // Simple hash-like mix let mixed = (nanos ^ (secs << 16)) ^ (nanos.rotate_left(13)); min + ((mixed as u16) % range) } pub mod sample_tools { use std::{sync::Arc, time::Duration}; use rust_mcp_macros::{mcp_tool, JsonSchema}; use rust_mcp_schema::{LoggingMessageNotificationParams, TextContent}; use rust_mcp_sdk::{ schema::{schema_utils::CallToolError, CallToolResult}, McpServer, }; use serde_json::json; //****************// // TaskAugmentedTool // //****************// #[mcp_tool( name = "task_augmented_tool", description = "invokes a long running mcp task, the result will be available after task is finished", idempotent_hint = false, destructive_hint = false, open_world_hint = false, read_only_hint = false )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, rust_mcp_macros::JsonSchema)] pub struct TaskAugmentedTool { /// TaskJobInfo indicating final status of the task and task duratins. pub job_info: TaskJobInfo, } //****************// // SayHelloTool // //****************// #[mcp_tool( name = "say_hello", description = "Accepts a person's name and says a personalized \"Hello\" to that person", idempotent_hint = false, destructive_hint = false, open_world_hint = false, read_only_hint = false )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, rust_mcp_macros::JsonSchema)] pub struct SayHelloTool { /// The name of the person to greet with a "Hello". pub name: String, } impl SayHelloTool { pub fn call_tool(&self) -> Result<CallToolResult, CallToolError> { let hello_message = format!("Hello, {}!", self.name); return Ok(CallToolResult::text_content(vec![hello_message.into()])); } } //******************// // AuthInfo Tool // //******************// #[mcp_tool( name = "display_auth_info", description = "Displays auth_info if user is authenticated", idempotent_hint = false, destructive_hint = false, open_world_hint = false, read_only_hint = false )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema)] pub struct DisplayAuthInfo {} use rust_mcp_sdk::auth::AuthInfo; use crate::common::task_runner::TaskJobInfo; impl DisplayAuthInfo { pub fn call_tool( &self, auth_info: Option<AuthInfo>, ) -> Result<CallToolResult, CallToolError> { let message = format!("{}", serde_json::to_string(&auth_info).unwrap()); return Ok(CallToolResult::text_content(vec![message.into()])); } } //******************// // SayGoodbyeTool // //******************// #[mcp_tool( name = "say_goodbye", description = "Accepts a person's name and says a personalized \"Goodbye\" to that person.", idempotent_hint = false, destructive_hint = false, open_world_hint = false, read_only_hint = false )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema)] pub struct SayGoodbyeTool { /// The name of the person to say goodbye to. name: String, } impl SayGoodbyeTool { pub fn call_tool(&self) -> Result<CallToolResult, CallToolError> { let goodbye_message = format!("Goodbye, {}!", self.name); return Ok(CallToolResult::text_content(vec![goodbye_message.into()])); } } //****************************// // StartNotificationStream // //****************************// #[mcp_tool( name = "start-notification-stream", description = "Accepts a person's name and says a personalized \"Goodbye\" to that person." )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema)] pub struct StartNotificationStream { /// Interval in milliseconds between notifications interval: u64, /// Number of notifications to send (0 for 100) count: u32, } impl StartNotificationStream { pub async fn call_tool( &self, runtime: Arc<dyn McpServer>, ) -> Result<CallToolResult, CallToolError> { for i in 0..self.count { let _ = runtime .send_logging_message(LoggingMessageNotificationParams { data: json!({"id":format!("message {} of {}",i,self.count)}), level: rust_mcp_sdk::schema::LoggingLevel::Emergency, logger: None, meta: None, }) .await; tokio::time::sleep(Duration::from_millis(self.interval)).await; } let message = "so many messages sent".to_string(); Ok(CallToolResult::text_content(vec![TextContent::from( message, )])) } } } pub async fn wiremock_request(mock_server: &MockServer, index: usize) -> Request { let requests = mock_server.received_requests().await.unwrap(); requests[index].clone() } pub async fn debug_wiremock(mock_server: &MockServer) { let requests = mock_server.received_requests().await.unwrap(); let len = requests.len(); for (index, request) in requests.iter().enumerate() { println!("\n--- #{index} of {len} ---"); println!("Method: {}", request.method); println!("Path: {}", request.url.path()); // println!("Headers: {:#?}", request.headers); println!("---- headers ----"); for (key, values) in &request.headers { println!("{key}: {values:?}"); } let body_str = String::from_utf8_lossy(&request.body); println!("Body: {body_str}\n"); } } pub fn create_sse_response(payload: &str) -> ResponseTemplate { let sse_body = format!(r#"data: {}{}"#, payload, "\n\n"); ResponseTemplate::new(200).set_body_raw(sse_body.into_bytes(), "text/event-stream") } pub async fn wait_for_n_requests( mock_server: &MockServer, num_requests: usize, duration: Option<Duration>, ) { let duration = duration.unwrap_or(Duration::from_secs(1)); timeout(duration, async { loop { let requests = mock_server.received_requests().await.unwrap(); if requests.len() >= num_requests { break; } tokio::time::sleep(Duration::from_millis(100)).await; } }) .await .unwrap(); } pub struct TestTokenVerifier { token_map: HashMap<String, AuthInfo>, } impl TestTokenVerifier { pub fn new(token_map: HashMap<String, AuthInfo>) -> Self { Self { token_map } } } #[async_trait] impl OauthTokenVerifier for TestTokenVerifier { async fn verify_token(&self, access_token: String) -> Result<AuthInfo, AuthenticationError> { let info = self.token_map.get(&access_token); let Some(info) = info else { return Err(AuthenticationError::InactiveToken); }; if info.expires_at.unwrap() < SystemTime::now() { return Err(AuthenticationError::InvalidOrExpiredToken( "expired".to_string(), )); } Ok(info.clone()) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/tests/common/task_runner.rs
crates/rust-mcp-sdk/tests/common/task_runner.rs
use std::{ collections::HashMap, sync::Arc, time::{Duration, Instant}, }; use rust_mcp_macros::JsonSchema; use rust_mcp_schema::{Task, TaskStatus}; use rust_mcp_sdk::{ task_store::{ClientTaskStore, ServerTaskStore, TaskStore}, SessionId, }; use tokio::{sync::Mutex, task::JoinHandle, time::sleep}; const MIN_TIME: u64 = 15; #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema)] pub struct TaskJobInfo { pub finish_in_ms: u64, pub status_interval_ms: u64, pub task_final_status: String, pub task_result: Option<String>, pub meta: Option<serde_json::Map<String, serde_json::Value>>, } pub struct McpTaskRunner { tasks: Arc<Mutex<HashMap<String, JoinHandle<()>>>>, } impl McpTaskRunner { pub fn new() -> Self { Self { tasks: Arc::new(Mutex::new(HashMap::new())), } } pub async fn run_server_task( &self, task: Task, task_store: Arc<ServerTaskStore>, job_info: TaskJobInfo, session_id: Option<SessionId>, ) -> Task { let task_id = task.task_id.to_string(); let task_id_clone = task_id.clone(); let tasks = Arc::clone(&self.tasks); let handle = tokio::spawn(async move { let start = Instant::now(); let mut next_status = Duration::from_millis(job_info.status_interval_ms.max(MIN_TIME)); let total_duration = Duration::from_millis(job_info.finish_in_ms); let final_status = serde_json::from_str::<TaskStatus>(&format!("\"{}\"", job_info.task_final_status)) .unwrap(); loop { let elapsed = start.elapsed(); // final completion if elapsed >= total_duration { match job_info.task_result { Some(result) => { task_store .store_task_result( &task_id_clone, final_status, serde_json::from_str(&result).unwrap(), session_id.as_ref(), ) .await } None => { task_store .update_task_status( &task_id_clone, final_status, Some(format!( "task status updated to {}", job_info.task_final_status )), session_id.clone(), ) .await } }; break; } // periodic status update if elapsed >= next_status { task_store .update_task_status( &task_id_clone, TaskStatus::Working, Some(format!( "time elapsed {} , still working...", elapsed.as_millis() )), session_id.clone(), ) .await; next_status += Duration::from_millis(job_info.status_interval_ms); } // sleep a bit to avoid busy looping sleep(Duration::from_millis(MIN_TIME)).await; } let mut tasks = tasks.lock().await; tasks.remove(&task_id_clone); }); self.tasks.lock().await.insert(task_id, handle); task } pub async fn run_client_task( &self, task: Task, task_store: Arc<ClientTaskStore>, job_info: TaskJobInfo, session_id: Option<SessionId>, ) -> Task { let task_id = task.task_id.to_string(); let task_id_clone = task_id.clone(); let tasks = Arc::clone(&self.tasks); let handle = tokio::spawn(async move { let start = Instant::now(); let mut next_status = Duration::from_millis(job_info.status_interval_ms.max(MIN_TIME)); let total_duration = Duration::from_millis(job_info.finish_in_ms); let final_status = serde_json::from_str::<TaskStatus>(&format!("\"{}\"", job_info.task_final_status)) .unwrap(); loop { let elapsed = start.elapsed(); // final completion if elapsed >= total_duration { match job_info.task_result { Some(result) => { task_store .store_task_result( &task_id_clone, final_status, serde_json::from_str(&result).unwrap(), session_id.as_ref(), ) .await } None => { task_store .update_task_status( &task_id_clone, final_status, Some(format!( "task status updated to {}", job_info.task_final_status )), session_id.clone(), ) .await } }; break; } // periodic status update if elapsed >= next_status { task_store .update_task_status( &task_id_clone, TaskStatus::Working, Some(format!( "time elapsed {} , still working...", elapsed.as_millis() )), session_id.clone(), ) .await; next_status += Duration::from_millis(job_info.status_interval_ms); } // sleep a bit to avoid busy looping sleep(Duration::from_millis(MIN_TIME)).await; } let mut tasks = tasks.lock().await; tasks.remove(&task_id_clone); }); self.tasks.lock().await.insert(task_id, handle); task } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/quick-start-client-stdio.rs
crates/rust-mcp-sdk/examples/quick-start-client-stdio.rs
use std::sync::Arc; use async_trait::async_trait; use rust_mcp_sdk::{ error::SdkResult, mcp_client::{client_runtime, ClientHandler, McpClientOptions, ToMcpClientHandler}, schema::*, task_store::InMemoryTaskStore, *, }; // Custom Handler to handle incoming MCP Messages pub struct MyClientHandler; #[async_trait] impl ClientHandler for MyClientHandler { // To see all the trait methods you can override, // check out: // https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/main/crates/rust-mcp-sdk/src/mcp_handlers/mcp_client_handler.rs } #[tokio::main] async fn main() -> SdkResult<()> { // Client details and capabilities let client_details: InitializeRequestParams = InitializeRequestParams { capabilities: ClientCapabilities::default(), client_info: Implementation { name: "simple-rust-mcp-client".into(), version: "0.1.0".into(), description: None, icons: vec![], title: None, website_url: None, }, protocol_version: ProtocolVersion::V2025_11_25.into(), meta: None, }; // Create a transport, with options to launch @modelcontextprotocol/server-everything MCP Server let transport = StdioTransport::create_with_server_launch( "npx", vec![ "-y".to_string(), "@modelcontextprotocol/server-everything@latest".to_string(), ], None, TransportOptions::default(), )?; // instantiate our custom handler for handling MCP messages let handler = MyClientHandler {}; // Create and start the MCP client let client = client_runtime::create_client(McpClientOptions { client_details, transport, handler: handler.to_mcp_client_handler(), task_store: Some(Arc::new(InMemoryTaskStore::new(None))), // support mcp tasks: https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks server_task_store: Some(Arc::new(InMemoryTaskStore::new(None))), }); client.clone().start().await?; // use client methods to communicate with the MCP Server as you wish: let server_version = client.server_version().unwrap(); // Retrieve and display the list of tools available on the server let tools = client.request_tool_list(None).await?.tools; println!( "List of tools for {}@{}", server_version.name, server_version.version ); tools.iter().enumerate().for_each(|(tool_index, tool)| { println!( " {}. {} : {}", tool_index + 1, tool.name, tool.description.clone().unwrap_or_default() ); }); println!("Call \"add\" tool with 100 and 28 ..."); let params = serde_json::json!({"a": 100,"b": 28}) .as_object() .unwrap() .clone(); let request = CallToolRequestParams { name: "add".to_string(), arguments: Some(params), meta: None, task: None, }; // invoke the tool let result = client.request_tool_call(request).await?; println!( "{}", result.content.first().unwrap().as_text_content()?.text ); client.shut_down().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/hello-world-mcp-server-stdio-core.rs
crates/rust-mcp-sdk/examples/hello-world-mcp-server-stdio-core.rs
pub mod common; use crate::common::{initialize_tracing, ExampleServerHandlerCore}; use rust_mcp_sdk::schema::{ Implementation, InitializeResult, ProtocolVersion, ServerCapabilities, ServerCapabilitiesResources, ServerCapabilitiesTools, }; use rust_mcp_sdk::{ error::SdkResult, mcp_icon, mcp_server::{server_runtime, McpServerOptions, ServerRuntime}, McpServer, StdioTransport, ToMcpServerHandlerCore, TransportOptions, }; use std::sync::Arc; #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // STEP 1: Define server details and capabilities let server_details = InitializeResult { server_info: Implementation { name: "Hello World MCP Server".into(), version: "0.1.0".into(), title: Some("Hello World MCP Server (core)".into()), description: Some("Hello World MCP Server (core), by Rust MCP SDK".into()), icons: vec![ mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" ) ], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, capabilities: ServerCapabilities { // indicates that server support mcp tools tools: Some(ServerCapabilitiesTools { list_changed: None }), resources: Some(ServerCapabilitiesResources { list_changed: None, subscribe: None }), completions:Some(serde_json::Map::new()), tasks: None, ..Default::default() // Using default values for other fields }, meta: None, instructions: Some("server instructions...".into()), protocol_version: ProtocolVersion::V2025_11_25.into(), }; // STEP 2: create a std transport with default options let transport = StdioTransport::new(TransportOptions::default())?; // STEP 3: instantiate our custom handler for handling MCP messages let handler = ExampleServerHandlerCore {}; // STEP 4: create a MCP server let server: Arc<ServerRuntime> = server_runtime::create_server(McpServerOptions { server_details, transport, handler: handler.to_mcp_server_handler(), task_store: None, client_task_store: None, }); // STEP 5: Start the server if let Err(start_error) = server.start().await { eprintln!( "{}", start_error .rpc_error_message() .unwrap_or(&start_error.to_string()) ); }; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/hello-world-mcp-server-stdio.rs
crates/rust-mcp-sdk/examples/hello-world-mcp-server-stdio.rs
pub mod common; use crate::common::{initialize_tracing, ExampleServerHandler}; use rust_mcp_sdk::schema::{ Implementation, InitializeResult, ProtocolVersion, ServerCapabilities, ServerCapabilitiesResources, ServerCapabilitiesTools, }; use rust_mcp_sdk::{ error::SdkResult, mcp_icon, mcp_server::{server_runtime, McpServerOptions, ServerRuntime}, McpServer, StdioTransport, ToMcpServerHandler, TransportOptions, }; use std::sync::Arc; #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // STEP 1: Define server details and capabilities let server_details = InitializeResult { server_info: Implementation { name: "Hello World MCP Server".into(), version: "0.1.0".into(), title: Some("Hello World MCP Server".into()), description: Some("Hello World MCP Server, by Rust MCP SDK".into()), icons: vec![ mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" ) ], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, capabilities: ServerCapabilities { // indicates that server support mcp tools tools: Some(ServerCapabilitiesTools { list_changed: None }), resources: Some(ServerCapabilitiesResources { list_changed: None, subscribe: None }), completions:Some(serde_json::Map::new()), tasks: None, ..Default::default() // Using default values for other fields }, meta: None, instructions: Some("server instructions...".into()), protocol_version: ProtocolVersion::V2025_11_25.into(), }; // STEP 2: create a std transport with default options let transport = StdioTransport::new(TransportOptions::default())?; // STEP 3: instantiate our custom handler for handling MCP messages let handler = ExampleServerHandler {}; // STEP 4: create a MCP server let server: Arc<ServerRuntime> = server_runtime::create_server(McpServerOptions { server_details, transport, handler: handler.to_mcp_server_handler(), task_store: None, client_task_store: None, }); // STEP 5: Start the server if let Err(start_error) = server.start().await { eprintln!( "{}", start_error .rpc_error_message() .unwrap_or(&start_error.to_string()) ); }; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/mcp-server-oauth-remote.rs
crates/rust-mcp-sdk/examples/mcp-server-oauth-remote.rs
pub mod common; extern crate mcp_extra as rust_mcp_extra; // Prevent release-please from mistakenly treating this dev dependency as a cyclic dependency use crate::common::ServerHandlerAuth; use rust_mcp_extra::token_verifier::{ GenericOauthTokenVerifier, TokenVerifierOptions, VerificationStrategies, }; use rust_mcp_sdk::schema::{ Implementation, InitializeResult, ServerCapabilities, ServerCapabilitiesTools, LATEST_PROTOCOL_VERSION, }; use rust_mcp_sdk::{ auth::{AuthMetadataBuilder, RemoteAuthProvider}, error::SdkResult, event_store::InMemoryEventStore, mcp_icon, mcp_server::{hyper_server, HyperServerOptions}, ToMcpServerHandler, }; use std::env; use std::sync::Arc; use std::time::Duration; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; // this function creates and setup a RemoteAuthProvider , pointing to a local KeyCloak server // please refer to the keycloak-setup section of the following blog post for // detailed instructions on how to setup a KeyCloak server for this : // https://modelcontextprotocol.io/docs/tutorials/security/authorization#keycloak-setup pub async fn create_oauth_provider() -> SdkResult<RemoteAuthProvider> { // build metadata from a oauth discovery url : .well-known/openid-configuration let (auth_server_meta, protected_resource_meta) = AuthMetadataBuilder::from_discovery_url( "http://localhost:8080/realms/master/.well-known/openid-configuration", "http://localhost:3000", //mcp server url vec!["mcp:tools", "phone"], ) .await? .resource_name("MCP Server with Remote Oauth") .build()?; // Alternatively, build metadata manually: // let (auth_server_meta, protected_resource_meta) = // AuthMetadataBuilder::new("http://localhost:3000") // .issuer("http://localhost:8080/realms/master") // .authorization_endpoint("/protocol/openid-connect/auth") // .token_endpoint("/protocol/openid-connect/token") // .jwks_uri("/protocol/openid-connect/certs") // .introspection_endpoint("/protocol/openid-connect/token/introspect") // .authorization_servers(vec!["http://localhost:8080/realms/master"]) // .scopes_supported(vec!["mcp:tools", "phone"]) // .resource_name("MCP Server with Remote Oauth") // .build()?; // create a token verifier with Jwks and Introspection strategies // GenericOauthTokenVerifier is used from rust-mcp-extra crate // you can implement yours by implementing the OauthTokenVerifier trait let token_verifier = GenericOauthTokenVerifier::new(TokenVerifierOptions { validate_audience: None, validate_issuer: Some(auth_server_meta.issuer.to_string()), strategies: vec![ VerificationStrategies::JWKs { jwks_uri: auth_server_meta.jwks_uri.as_ref().unwrap().to_string(), }, VerificationStrategies::Introspection { introspection_uri: auth_server_meta .introspection_endpoint .as_ref() .unwrap() .to_string(), client_id: env::var("OAUTH_CLIENT_ID") .expect("Please set the 'OAUTH_CLIENT_ID' environment variable!"), client_secret: env::var("OAUTH_CLIENT_SECRET") .expect("Please set the 'OAUTH_CLIENT_SECRET' environment variable!"), use_basic_auth: true, extra_params: None, }, ], cache_capacity: Some(15), }) .unwrap(); Ok(RemoteAuthProvider::new( auth_server_meta, protected_resource_meta, Box::new(token_verifier), Some(vec!["mcp:tools".to_string()]), )) } #[tokio::main] async fn main() -> SdkResult<()> { // initialize tracing tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let server_details = InitializeResult { // server name and version server_info: Implementation { name: "Remote Oauth Test MCP Server".into(), version: "0.1.0".into(), title: Some("Remote Oauth Test MCP Server".into()), description: Some("Remote Oauth Test MCP Server, by Rust MCP SDK".into()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, capabilities: ServerCapabilities { // indicates that server support mcp tools tools: Some(ServerCapabilitiesTools { list_changed: None }), ..Default::default() // Using default values for other fields }, meta: None, instructions: Some("server instructions...".into()), protocol_version: LATEST_PROTOCOL_VERSION.into(), }; let handler = ServerHandlerAuth {}; let oauth_metadata_provider = create_oauth_provider().await?; let server = hyper_server::create_server( server_details, handler.to_mcp_server_handler(), HyperServerOptions { host: "localhost".into(), port: 3000, custom_streamable_http_endpoint: Some("/".into()), ping_interval: Duration::from_secs(5), event_store: Some(Arc::new(InMemoryEventStore::default())), // enable resumability auth: Some(Arc::new(oauth_metadata_provider)), // enable authentication ..Default::default() }, ); server.start().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/simple-mcp-client-sse-core.rs
crates/rust-mcp-sdk/examples/simple-mcp-client-sse-core.rs
pub mod common; use crate::common::{initialize_tracing, inquiry_utils, ExampleClientHandlerCore}; use inquiry_utils::InquiryUtils; use rust_mcp_sdk::error::SdkResult; use rust_mcp_sdk::mcp_client::{client_runtime, McpClientOptions}; use rust_mcp_sdk::schema::{ ClientCapabilities, Implementation, InitializeRequestParams, LoggingLevel, SetLevelRequestParams, LATEST_PROTOCOL_VERSION, }; use rust_mcp_sdk::{ mcp_icon, ClientSseTransport, ClientSseTransportOptions, McpClient, ToMcpClientHandlerCore, }; use std::sync::Arc; // Connect to a server started with the following command: // npx @modelcontextprotocol/server-everything sse const MCP_SERVER_URL: &str = "http://127.0.0.1:3001/sse"; #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // Step1 : Define client details and capabilities let client_details: InitializeRequestParams = InitializeRequestParams { capabilities: ClientCapabilities::default(), client_info: Implementation { name: "simple-rust-mcp-client-core-sse".into(), version: "0.1.0".into(), title: Some("Simple Rust MCP Client (Core,SSE)".into()), description: Some("Simple Rust MCP Client (Core,SSE) by Rust MCP SDK".into()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, protocol_version: LATEST_PROTOCOL_VERSION.into(), meta: None, }; // Step2 : Create a transport, with options to launch/connect to a MCP Server // Assuming @modelcontextprotocol/server-everything is launched with sse argument and listening on port 3001 let transport = ClientSseTransport::new(MCP_SERVER_URL, ClientSseTransportOptions::default())?; // STEP 3: instantiate our custom handler that is responsible for handling MCP messages let handler = ExampleClientHandlerCore {}; // STEP 4: create the client let client = client_runtime::create_client(McpClientOptions { client_details, transport, handler: handler.to_mcp_client_handler(), task_store: None, server_task_store: None, }); // STEP 5: start the MCP client client.clone().start().await?; // You can utilize the client and its methods to interact with the MCP Server. // The following demonstrates how to use client methods to retrieve server information, // and print them in the terminal, set the log level, invoke a tool, and more. // Create a struct with utility functions for demonstration purpose, to utilize different client methods and display the information. let utils = InquiryUtils { client: Arc::clone(&client), }; // Display server information (name and version) utils.print_server_info(); // Display server capabilities utils.print_server_capabilities(); // Display the list of tools available on the server utils.print_tool_list().await?; // Display the list of prompts available on the server utils.print_prompts_list().await?; // Display the list of resources available on the server utils.print_resource_list().await?; // Display the list of resource templates available on the server utils.print_resource_templates().await?; // Call add tool, and print the result utils.call_add_tool(100, 25).await?; // // Set the log level match utils .client .request_set_logging_level(SetLevelRequestParams { level: LoggingLevel::Debug, meta: None, }) .await { Ok(_) => println!("Log level is set to \"Debug\""), Err(err) => eprintln!("Error setting the Log level : {err}"), } // Send 3 pings to the server, with a 2-second interval between each ping. utils.ping_n_times(3).await; client.shut_down().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/hello-world-server-streamable-http.rs
crates/rust-mcp-sdk/examples/hello-world-server-streamable-http.rs
pub mod common; use crate::common::{initialize_tracing, ExampleServerHandler}; use rust_mcp_schema::ServerCapabilitiesResources; use rust_mcp_sdk::schema::{ Implementation, InitializeResult, ProtocolVersion, ServerCapabilities, ServerCapabilitiesTools, }; use rust_mcp_sdk::{ error::SdkResult, event_store::InMemoryEventStore, mcp_icon, mcp_server::{hyper_server, HyperServerOptions, ServerHandler, ToMcpServerHandler}, task_store::InMemoryTaskStore, }; use serde_json::Map; use std::sync::Arc; pub struct AppState<H: ServerHandler> { pub server_details: InitializeResult, pub handler: H, } #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // STEP 1: Define server details and capabilities let server_details = InitializeResult { // server name and version server_info: Implementation { name: "Hello World MCP Server Streamable Http/SSE".into(), version: "0.1.0".into(), title: Some("Hello World MCP Streamable Http/SSE".into()), description: Some("test server, by Rust MCP SDK".into()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, capabilities: ServerCapabilities { // indicates that server support mcp tools tools: Some(ServerCapabilitiesTools { list_changed: None }), resources: Some(ServerCapabilitiesResources{ list_changed: None, subscribe: None }), completions:Some(Map::new()), ..Default::default() // Using default values for other fields }, meta: None, instructions: Some("server instructions...".into()), protocol_version: ProtocolVersion::V2025_11_25.into(), }; // STEP 2: instantiate our custom handler for handling MCP messages let handler = ExampleServerHandler {}; // STEP 3: instantiate HyperServer, providing `server_details` , `handler` and HyperServerOptions let server = hyper_server::create_server( server_details, handler.to_mcp_server_handler(), HyperServerOptions { host: "127.0.0.1".into(), event_store: Some(Arc::new(InMemoryEventStore::default())), // enable resumability task_store: Some(Arc::new(InMemoryTaskStore::new(None))), client_task_store: Some(Arc::new(InMemoryTaskStore::new(None))), ..Default::default() }, ); // STEP 4: Start the server server.start().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/simple-mcp-client-stdio.rs
crates/rust-mcp-sdk/examples/simple-mcp-client-stdio.rs
pub mod common; use crate::common::{initialize_tracing, inquiry_utils::InquiryUtils, ExampleClientHandler}; use rust_mcp_sdk::schema::{ ClientCapabilities, Implementation, InitializeRequestParams, LoggingLevel, SetLevelRequestParams, LATEST_PROTOCOL_VERSION, }; use rust_mcp_sdk::{ error::SdkResult, mcp_client::{client_runtime, McpClientOptions}, mcp_icon, McpClient, StdioTransport, ToMcpClientHandler, TransportOptions, }; use std::sync::Arc; const MCP_SERVER_TO_LAUNCH: &str = "@modelcontextprotocol/server-everything"; #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // Step1 : Define client details and capabilities let client_details: InitializeRequestParams = InitializeRequestParams { capabilities: ClientCapabilities::default(), client_info: Implementation { name: "simple-rust-mcp-client-stdio".into(), version: "0.1.0".into(), title: Some("Simple Rust MCP Client (Stdio)".into()), description: Some("Simple Rust MCP Client, by Rust MCP SDK".into()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, protocol_version: LATEST_PROTOCOL_VERSION.into(), meta: None, }; // Step2 : Create a transport, with options to launch/connect to a MCP Server // In this example we launch @modelcontextprotocol/server-everything (needs node.js and npm to be installed) let transport = StdioTransport::create_with_server_launch( "npx", vec!["-y".into(), MCP_SERVER_TO_LAUNCH.into()], None, TransportOptions::default(), )?; // STEP 3: instantiate our custom handler that is responsible for handling MCP messages let handler = ExampleClientHandler {}; // STEP 4: create a MCP client let client = client_runtime::create_client(McpClientOptions { client_details, transport, handler: handler.to_mcp_client_handler(), task_store: None, server_task_store: None, }); // STEP 5: start the MCP client client.clone().start().await?; // You can utilize the client and its methods to interact with the MCP Server. // The following demonstrates how to use client methods to retrieve server information, // and print them in the terminal, set the log level, invoke a tool, and more. // Create a struct with utility functions for demonstration purpose, to utilize different client methods and display the information. let utils = InquiryUtils { client: Arc::clone(&client), }; // Display server information (name and version) utils.print_server_info(); // Display server capabilities utils.print_server_capabilities(); // Display the list of tools available on the server utils.print_tool_list().await?; // Display the list of prompts available on the server utils.print_prompts_list().await?; // Display the list of resources available on the server utils.print_resource_list().await?; // Display the list of resource templates available on the server utils.print_resource_templates().await?; // Call add tool, and print the result utils.call_add_tool(100, 25).await?; // Set the log level utils .client .request_set_logging_level(SetLevelRequestParams { level: LoggingLevel::Debug, meta: None, }) .await?; // Send 3 pings to the server, with a 2-second interval between each ping. utils.ping_n_times(3).await; client.shut_down().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/quick-start-streamable-http.rs
crates/rust-mcp-sdk/examples/quick-start-streamable-http.rs
pub mod common; use async_trait::async_trait; use rust_mcp_sdk::{ error::SdkResult, event_store::InMemoryEventStore, macros, mcp_server::{hyper_server, HyperServerOptions, ServerHandler}, schema::*, *, }; use crate::common::initialize_tracing; // Define a mcp tool #[macros::mcp_tool( name = "say_hello", description = "returns \"Hello from Rust MCP SDK!\" message " )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, macros::JsonSchema)] pub struct SayHelloTool {} // define a custom handler #[derive(Default)] struct HelloHandler {} // implement ServerHandler #[async_trait] impl ServerHandler for HelloHandler { // Handles requests to list available tools. async fn handle_list_tools_request( &self, _request: Option<PaginatedRequestParams>, _runtime: std::sync::Arc<dyn McpServer>, ) -> std::result::Result<ListToolsResult, RpcError> { Ok(ListToolsResult { tools: vec![SayHelloTool::tool()], meta: None, next_cursor: None, }) } // Handles requests to call a specific tool. async fn handle_call_tool_request( &self, params: CallToolRequestParams, _runtime: std::sync::Arc<dyn McpServer>, ) -> std::result::Result<CallToolResult, CallToolError> { if params.name == "say_hello" { Ok(CallToolResult::text_content(vec![ "Hello from Rust MCP SDK!".into(), ])) } else { Err(CallToolError::unknown_tool(params.name)) } } } #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // Define server details and capabilities let server_info = InitializeResult { server_info: Implementation { name: "hello-rust-mcp".into(), version: "0.1.0".into(), title: Some("Hello World MCP Server".into()), description: Some("A minimal Rust MCP server".into()), icons: vec![mcp_icon!(src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "light")], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, capabilities: ServerCapabilities { tools: Some(ServerCapabilitiesTools { list_changed: None }), ..Default::default() }, protocol_version: ProtocolVersion::V2025_11_25.into(), instructions: None, meta:None }; let handler = HelloHandler::default().to_mcp_server_handler(); let server = hyper_server::create_server( server_info, handler, HyperServerOptions { host: "127.0.0.1".to_string(), event_store: Some(std::sync::Arc::new(InMemoryEventStore::default())), // enable resumability ..Default::default() }, ); server.start().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/simple-mcp-client-stdio-core.rs
crates/rust-mcp-sdk/examples/simple-mcp-client-stdio-core.rs
pub mod common; use rust_mcp_sdk::schema::{ ClientCapabilities, Implementation, InitializeRequestParams, LoggingLevel, SetLevelRequestParams, LATEST_PROTOCOL_VERSION, }; use rust_mcp_sdk::{ error::SdkResult, mcp_client::client_runtime_core, mcp_client::McpClientOptions, mcp_icon, McpClient, StdioTransport, ToMcpClientHandlerCore, TransportOptions, }; use crate::common::inquiry_utils::InquiryUtils; use crate::common::{initialize_tracing, ExampleClientHandlerCore}; use std::sync::Arc; const MCP_SERVER_TO_LAUNCH: &str = "@modelcontextprotocol/server-everything"; #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // Step1 : Define client details and capabilities let client_details: InitializeRequestParams = InitializeRequestParams { capabilities: ClientCapabilities::default(), client_info: Implementation { name: "simple-rust-mcp-client-core".into(), version: "0.1.0".into(), title: Some("Simple Rust MCP Client Core".into()), description: Some("Hello World MCP Server, by Rust MCP SDK".into()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, protocol_version: LATEST_PROTOCOL_VERSION.into(), meta: None, }; // Step2 : Create a transport, with options to launch/connect to a MCP Server // In this example we launch @modelcontextprotocol/server-everything (needs node.js and npm to be installed) let transport = StdioTransport::create_with_server_launch( "npx", vec!["-y".into(), MCP_SERVER_TO_LAUNCH.into()], None, TransportOptions::default(), )?; // STEP 3: instantiate our custom handler for handling MCP messages let handler = ExampleClientHandlerCore {}; // STEP 4: create a MCP client let client = client_runtime_core::create_client(McpClientOptions { client_details, transport, handler: handler.to_mcp_client_handler(), task_store: None, server_task_store: None, }); // STEP 5: start the MCP client client.clone().start().await?; // You can utilize the client and its methods to interact with the MCP Server. // The following demonstrates how to use client methods to retrieve server information, // and print them in the terminal, set the log level, invoke a tool, and more. // Create a struct with utility functions for demonstration purpose, to utilize different client methods and display the information. let utils = InquiryUtils { client: Arc::clone(&client), }; // Display server information (name and version) utils.print_server_info(); // Display server capabilities utils.print_server_capabilities(); // Display the list of tools available on the server utils.print_tool_list().await?; // Display the list of prompts available on the server utils.print_prompts_list().await?; // Display the list of resources available on the server utils.print_resource_list().await?; // Display the list of resource templates available on the server utils.print_resource_templates().await?; // Call add tool, and print the result utils.call_add_tool(100, 25).await?; // Set the log level utils .client .request_set_logging_level(SetLevelRequestParams { level: LoggingLevel::Debug, meta: None, }) .await?; // Send 3 ping requests to the server, with a 2-second interval between each ping request. utils.ping_n_times(3).await; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/simple-mcp-client-streamable-http.rs
crates/rust-mcp-sdk/examples/simple-mcp-client-streamable-http.rs
pub mod common; use crate::common::inquiry_utils::InquiryUtils; use crate::common::{initialize_tracing, ExampleClientHandler}; use rust_mcp_sdk::schema::{ ClientCapabilities, Implementation, InitializeRequestParams, LoggingLevel, SetLevelRequestParams, LATEST_PROTOCOL_VERSION, }; use rust_mcp_sdk::{ error::SdkResult, mcp_client::client_runtime, mcp_icon, McpClient, RequestOptions, StreamableTransportOptions, }; use std::sync::Arc; const MCP_SERVER_URL: &str = "http://127.0.0.1:3001/mcp"; #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // Step1 : Define client details and capabilities let client_details: InitializeRequestParams = InitializeRequestParams { capabilities: ClientCapabilities::default(), client_info: Implementation { name: "simple-rust-mcp-client".into(), version: "0.1.0".into(), title: Some("Simple Rust MCP Client (Streamable Http/SSE)".into()), description: None, icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: None, }, protocol_version: LATEST_PROTOCOL_VERSION.into(), meta: None, }; // Step 2: Create transport options to connect to an MCP server via Streamable HTTP. let transport_options = StreamableTransportOptions { mcp_url: MCP_SERVER_URL.into(), request_options: RequestOptions { ..RequestOptions::default() }, }; // STEP 3: instantiate our custom handler that is responsible for handling MCP messages let handler = ExampleClientHandler {}; // STEP 4: create the client with transport options and the handler let client = client_runtime::with_transport_options( client_details, transport_options, handler, None, None, ); // STEP 5: start the MCP client client.clone().start().await?; // You can utilize the client and its methods to interact with the MCP Server. // The following demonstrates how to use client methods to retrieve server information, // and print them in the terminal, set the log level, invoke a tool, and more. // Create a struct with utility functions for demonstration purpose, to utilize different client methods and display the information. let utils = InquiryUtils { client: Arc::clone(&client), }; // Display server information (name and version) utils.print_server_info(); // Display server capabilities utils.print_server_capabilities(); // Display the list of tools available on the server utils.print_tool_list().await?; // Display the list of prompts available on the server utils.print_prompts_list().await?; // Display the list of resources available on the server utils.print_resource_list().await?; // Display the list of resource templates available on the server utils.print_resource_templates().await?; // Call add tool, and print the result utils.call_add_tool(100, 25).await?; // Set the log level match utils .client .request_set_logging_level(SetLevelRequestParams { level: LoggingLevel::Debug, meta: None, }) .await { Ok(_) => println!("Log level is set to \"Debug\""), Err(err) => eprintln!("Error setting the Log level : {err}"), } // Send 3 pings to the server, with a 2-second interval between each ping. utils.ping_n_times(3).await; client.shut_down().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/simple-mcp-client-sse.rs
crates/rust-mcp-sdk/examples/simple-mcp-client-sse.rs
pub mod common; use crate::common::{initialize_tracing, inquiry_utils, ExampleClientHandler}; use inquiry_utils::InquiryUtils; use rust_mcp_sdk::error::SdkResult; use rust_mcp_sdk::mcp_client::{client_runtime, McpClientOptions}; use rust_mcp_sdk::schema::{ ClientCapabilities, Implementation, InitializeRequestParams, LoggingLevel, SetLevelRequestParams, LATEST_PROTOCOL_VERSION, }; use rust_mcp_sdk::{ mcp_icon, ClientSseTransport, ClientSseTransportOptions, McpClient, ToMcpClientHandler, }; use std::sync::Arc; // Connect to a server started with the following command: // npx @modelcontextprotocol/server-everything sse const MCP_SERVER_URL: &str = "http://127.0.0.1:3001/sse"; #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // Step1 : Define client details and capabilities let client_details: InitializeRequestParams = InitializeRequestParams { capabilities: ClientCapabilities::default(), client_info: Implementation { name: "simple-rust-mcp-client-sse".into(), version: "0.1.0".into(), title: Some("Simple Rust MCP Client (SSE)".into()), description: Some("Simple Rust MCP Client (SSE) by Rust MCP SDK".into()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, protocol_version: LATEST_PROTOCOL_VERSION.into(), meta: None, }; // Step2 : Create a transport, with options to launch/connect to a MCP Server // Assuming @modelcontextprotocol/server-everything is launched with sse argument and listening on port 3001 let transport = ClientSseTransport::new(MCP_SERVER_URL, ClientSseTransportOptions::default())?; // STEP 3: instantiate our custom handler that is responsible for handling MCP messages let handler = ExampleClientHandler {}; // STEP 4: create the client let client = client_runtime::create_client(McpClientOptions { client_details, transport, handler: handler.to_mcp_client_handler(), task_store: None, server_task_store: None, }); // STEP 5: start the MCP client client.clone().start().await?; // You can utilize the client and its methods to interact with the MCP Server. // The following demonstrates how to use client methods to retrieve server information, // and print them in the terminal, set the log level, invoke a tool, and more. // Create a struct with utility functions for demonstration purpose, to utilize different client methods and display the information. let utils = InquiryUtils { client: Arc::clone(&client), }; // Display server information (name and version) utils.print_server_info(); // Display server capabilities utils.print_server_capabilities(); // Display the list of tools available on the server utils.print_tool_list().await?; // Display the list of prompts available on the server utils.print_prompts_list().await?; // Display the list of resources available on the server utils.print_resource_list().await?; // Display the list of resource templates available on the server utils.print_resource_templates().await?; // Call add tool, and print the result utils.call_add_tool(100, 25).await?; // // Set the log level match utils .client .request_set_logging_level(SetLevelRequestParams { level: LoggingLevel::Debug, meta: None, }) .await { Ok(_) => println!("Log level is set to \"Debug\""), Err(err) => eprintln!("Error setting the Log level : {err}"), } // Send 3 pings to the server, with a 2-second interval between each ping. utils.ping_n_times(3).await; client.shut_down().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/simple-mcp-client-streamable-http-core.rs
crates/rust-mcp-sdk/examples/simple-mcp-client-streamable-http-core.rs
pub mod common; use crate::common::inquiry_utils::InquiryUtils; use crate::common::{initialize_tracing, ExampleClientHandlerCore}; use rust_mcp_sdk::mcp_client::client_runtime_core; use rust_mcp_sdk::schema::{ ClientCapabilities, Implementation, InitializeRequestParams, LoggingLevel, SetLevelRequestParams, LATEST_PROTOCOL_VERSION, }; use rust_mcp_sdk::{ error::SdkResult, mcp_icon, McpClient, RequestOptions, StreamableTransportOptions, }; use std::sync::Arc; // Assuming @modelcontextprotocol/server-everything is launched with streamableHttp argument and listening on port 3001 const MCP_SERVER_URL: &str = "http://127.0.0.1:3001/mcp"; #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // Step1 : Define client details and capabilities let client_details: InitializeRequestParams = InitializeRequestParams { capabilities: ClientCapabilities::default(), client_info: Implementation { name: "simple-rust-mcp-client-core-sse".into(), version: "0.1.0".into(), title: Some("Simple Rust MCP Client (Core,SSE)".into()), description: Some("Simple Rust MCP Client (Core,SSE), by Rust MCP SDK".into()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, protocol_version: LATEST_PROTOCOL_VERSION.into(), meta: None, }; // Step 2: Create transport options to connect to an MCP server via Streamable HTTP. let transport_options = StreamableTransportOptions { mcp_url: MCP_SERVER_URL.into(), request_options: RequestOptions { ..RequestOptions::default() }, }; // STEP 3: instantiate our custom handler that is responsible for handling MCP messages let handler = ExampleClientHandlerCore {}; // STEP 4: create the client let client = client_runtime_core::with_transport_options( client_details, transport_options, handler, None, None, ); // STEP 5: start the MCP client client.clone().start().await?; // You can utilize the client and its methods to interact with the MCP Server. // The following demonstrates how to use client methods to retrieve server information, // and print them in the terminal, set the log level, invoke a tool, and more. // Create a struct with utility functions for demonstration purpose, to utilize different client methods and display the information. let utils = InquiryUtils { client: Arc::clone(&client), }; // Display server information (name and version) utils.print_server_info(); // Display server capabilities utils.print_server_capabilities(); // Display the list of tools available on the server utils.print_tool_list().await?; // Display the list of prompts available on the server utils.print_prompts_list().await?; // Display the list of resources available on the server utils.print_resource_list().await?; // Display the list of resource templates available on the server utils.print_resource_templates().await?; // Call add tool, and print the result utils.call_add_tool(100, 25).await?; // Set the log level utils .client .request_set_logging_level(SetLevelRequestParams { level: LoggingLevel::Debug, meta: None, }) .await?; // Send 3 pings to the server, with a 2-second interval between each ping. utils.ping_n_times(3).await; client.shut_down().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/hello-world-server-streamable-http-core.rs
crates/rust-mcp-sdk/examples/hello-world-server-streamable-http-core.rs
pub mod common; use crate::common::{initialize_tracing, ExampleServerHandlerCore}; use rust_mcp_schema::ServerCapabilitiesResources; use rust_mcp_sdk::schema::{ Implementation, InitializeResult, ProtocolVersion, ServerCapabilities, ServerCapabilitiesTools, }; use rust_mcp_sdk::{ error::SdkResult, event_store::InMemoryEventStore, mcp_icon, mcp_server::{hyper_server, HyperServerOptions, ServerHandler}, task_store::InMemoryTaskStore, ToMcpServerHandlerCore, }; use std::sync::Arc; pub struct AppState<H: ServerHandler> { pub server_details: InitializeResult, pub handler: H, } #[tokio::main] async fn main() -> SdkResult<()> { // Set up the tracing subscriber for logging initialize_tracing(); // STEP 1: Define server details and capabilities let server_details = InitializeResult { // server name and version server_info: Implementation { name: "Hello World MCP Server (core) Streamable Http/SSE".into(), version: "0.1.0".into(), title: Some("Hello World MCP Server (core) Streamable Http/SSE".into()), description: Some("test server, by Rust MCP SDK".into()), icons: vec![mcp_icon!( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "dark" )], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, capabilities: ServerCapabilities { // indicates that server support mcp tools tools: Some(ServerCapabilitiesTools { list_changed: None }), resources: Some(ServerCapabilitiesResources{ list_changed: None, subscribe: None }), completions:Some(serde_json::Map::new()), ..Default::default() // Using default values for other fields }, meta: None, instructions: Some("server instructions...".into()), protocol_version: ProtocolVersion::V2025_11_25.into(), }; // STEP 2: instantiate our custom handler for handling MCP messages let handler = ExampleServerHandlerCore {}; // STEP 3: instantiate HyperServer, providing `server_details` , `handler` and HyperServerOptions let server = hyper_server::create_server( server_details, handler.to_mcp_server_handler(), HyperServerOptions { host: "127.0.0.1".into(), event_store: Some(Arc::new(InMemoryEventStore::default())), // enable resumability task_store: Some(Arc::new(InMemoryTaskStore::new(None))), client_task_store: Some(Arc::new(InMemoryTaskStore::new(None))), ..Default::default() }, ); // STEP 4: Start the server server.start().await?; Ok(()) }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/quick-start-server-stdio.rs
crates/rust-mcp-sdk/examples/quick-start-server-stdio.rs
use async_trait::async_trait; use rust_mcp_sdk::{ error::SdkResult, macros, mcp_server::{server_runtime, McpServerOptions, ServerHandler}, schema::*, *, }; // Define a mcp tool #[macros::mcp_tool( name = "say_hello", description = "returns \"Hello from Rust MCP SDK!\" message " )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, macros::JsonSchema)] pub struct SayHelloTool {} // define a custom handler #[derive(Default)] struct HelloHandler {} // implement ServerHandler #[async_trait] impl ServerHandler for HelloHandler { // Handles requests to list available tools. async fn handle_list_tools_request( &self, _request: Option<PaginatedRequestParams>, _runtime: std::sync::Arc<dyn McpServer>, ) -> std::result::Result<ListToolsResult, RpcError> { Ok(ListToolsResult { tools: vec![SayHelloTool::tool()], meta: None, next_cursor: None, }) } // Handles requests to call a specific tool. async fn handle_call_tool_request( &self, params: CallToolRequestParams, _runtime: std::sync::Arc<dyn McpServer>, ) -> std::result::Result<CallToolResult, CallToolError> { if params.name == "say_hello" { Ok(CallToolResult::text_content(vec![ "Hello from Rust MCP SDK!".into(), ])) } else { Err(CallToolError::unknown_tool(params.name)) } } } #[tokio::main] async fn main() -> SdkResult<()> { let server_details = InitializeResult { server_info: Implementation { name: "hello-rust-mcp".into(), version: "0.1.0".into(), title: Some("Hello World MCP Server".into()), description: Some("A minimal Rust MCP server".into()), icons: vec![mcp_icon!(src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png", mime_type = "image/png", sizes = ["128x128"], theme = "light")], website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".into()), }, capabilities: ServerCapabilities { tools: Some(ServerCapabilitiesTools { list_changed: None }), ..Default::default() }, protocol_version: ProtocolVersion::V2025_11_25.into(), instructions: None, meta:None }; let transport = StdioTransport::new(TransportOptions::default())?; let handler = HelloHandler::default().to_mcp_server_handler(); let server = server_runtime::create_server(McpServerOptions { transport, handler, server_details, task_store: None, client_task_store: None, }); server.start().await }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/example_server_handler.rs
crates/rust-mcp-sdk/examples/common/example_server_handler.rs
use super::tools::GreetingTools; use crate::common::resources::{BlobTextResource, PlainTextResource, PokemonImageResource}; use async_trait::async_trait; use rust_mcp_schema::{ CompleteRequestParams, CompleteResult, ListResourceTemplatesResult, ListResourcesResult, ReadResourceRequestParams, ReadResourceResult, }; use rust_mcp_sdk::{ mcp_server::ServerHandler, schema::{ schema_utils::CallToolError, CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams, RpcError, }, McpServer, }; use std::sync::Arc; // Custom Handler to handle MCP Messages pub struct ExampleServerHandler; // To check out a list of all the methods in the trait that you can override, take a look at // https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/main/crates/rust-mcp-sdk/src/mcp_handlers/mcp_server_handler.rs #[async_trait] #[allow(unused)] impl ServerHandler for ExampleServerHandler { // Handle ListToolsRequest, return list of available tools as ListToolsResult async fn handle_list_tools_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListToolsResult, RpcError> { Ok(ListToolsResult { meta: None, next_cursor: None, tools: GreetingTools::tools(), }) } /// Handles incoming CallToolRequest and processes it using the appropriate tool. async fn handle_call_tool_request( &self, params: CallToolRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CallToolResult, CallToolError> { // Attempt to convert request parameters into GreetingTools enum let tool_params: GreetingTools = GreetingTools::try_from(params).map_err(CallToolError::new)?; // Match the tool variant and execute its corresponding logic match tool_params { GreetingTools::SayHelloTool(say_hello_tool) => say_hello_tool.call_tool(), GreetingTools::SayGoodbyeTool(say_goodbye_tool) => say_goodbye_tool.call_tool(), } } /// Handles requests to list available resources. /// /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_list_resources_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListResourcesResult, RpcError> { Ok(ListResourcesResult { meta: None, next_cursor: None, resources: vec![PlainTextResource::resource(), BlobTextResource::resource()], }) } /// Handles requests to list resource templates. /// /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_list_resource_templates_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListResourceTemplatesResult, RpcError> { Ok(ListResourceTemplatesResult { meta: None, next_cursor: None, resource_templates: vec![PokemonImageResource::resource_template()], }) } /// Handles requests to read a specific resource. /// /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements. async fn handle_read_resource_request( &self, params: ReadResourceRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ReadResourceResult, RpcError> { if PlainTextResource::resource_uri().starts_with(&params.uri) { return PlainTextResource::get_resource().await; } if BlobTextResource::resource_uri().starts_with(&params.uri) { return BlobTextResource::get_resource().await; } if PokemonImageResource::matches_url(&params.uri) { return PokemonImageResource::get_resource(&params.uri).await; } Err(RpcError::invalid_request() .with_message(format!("No resource was found for '{}'.", params.uri))) } async fn handle_complete_request( &self, params: CompleteRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CompleteResult, RpcError> { if params.argument.name.eq("pokemon-id") { Ok(CompleteResult { completion: PokemonImageResource::completion(&params.argument.value), meta: None, }) } else { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", params.argument.name, ))) } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/example_client_handler_core.rs
crates/rust-mcp-sdk/examples/common/example_client_handler_core.rs
use async_trait::async_trait; use rust_mcp_sdk::schema::{ self, schema_utils::{NotificationFromServer, ResultFromClient}, RpcError, ServerJsonrpcRequest, }; use rust_mcp_sdk::{mcp_client::ClientHandlerCore, McpClient}; pub struct ExampleClientHandlerCore; // To check out a list of all the methods in the trait that you can override, take a look at // https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/main/crates/rust-mcp-sdk/src/mcp_handlers/mcp_client_handler_core.rs #[async_trait] impl ClientHandlerCore for ExampleClientHandlerCore { async fn handle_request( &self, request: ServerJsonrpcRequest, _runtime: &dyn McpClient, ) -> std::result::Result<ResultFromClient, RpcError> { match request { ServerJsonrpcRequest::PingRequest(_) => { return Ok(schema::Result::default().into()); } ServerJsonrpcRequest::CreateMessageRequest(_) => Err(RpcError::internal_error() .with_message("CreateMessageRequest handler is not implemented".to_string())), ServerJsonrpcRequest::ListRootsRequest(_) => Err(RpcError::internal_error() .with_message("ListRootsRequest handler is not implemented".to_string())), ServerJsonrpcRequest::ElicitRequest(_) => Err(RpcError::internal_error() .with_message("ElicitRequest handler is not implemented".to_string())), ServerJsonrpcRequest::GetTaskRequest(_) => Err(RpcError::internal_error() .with_message("GetTaskRequest handler is not implemented".to_string())), ServerJsonrpcRequest::GetTaskPayloadRequest(_) => Err(RpcError::internal_error() .with_message("GetTaskPayloadRequest handler is not implemented".to_string())), ServerJsonrpcRequest::CancelTaskRequest(_) => Err(RpcError::internal_error() .with_message("CancelTaskRequest handler is not implemented".to_string())), ServerJsonrpcRequest::ListTasksRequest(_) => Err(RpcError::internal_error() .with_message("ListTasksRequest handler is not implemented".to_string())), ServerJsonrpcRequest::CustomRequest(_) => Err(RpcError::internal_error() .with_message("CustomRequest handler is not implemented".to_string())), } } async fn handle_notification( &self, notification: NotificationFromServer, _runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { println!("Notification from server: \"{}\"", notification.method()); Ok(()) } async fn handle_error( &self, _error: &RpcError, _runtime: &dyn McpClient, ) -> std::result::Result<(), RpcError> { Err(RpcError::internal_error().with_message("handle_error() Not implemented".to_string())) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/inquiry_utils.rs
crates/rust-mcp-sdk/examples/common/inquiry_utils.rs
//! This module contains utility functions for querying and displaying server capabilities. use colored::Colorize; use rust_mcp_sdk::schema::CallToolRequestParams; use rust_mcp_sdk::McpClient; use rust_mcp_sdk::{error::SdkResult, mcp_client::ClientRuntime}; use serde_json::json; use std::io::Write; use std::sync::Arc; use std::time::Duration; use tokio::time::sleep; const GREY_COLOR: (u8, u8, u8) = (90, 90, 90); const HEADER_SIZE: usize = 31; pub struct InquiryUtils { pub client: Arc<ClientRuntime>, } impl InquiryUtils { fn print_header(&self, title: &str) { let pad = ((HEADER_SIZE as f32 / 2.0) + (title.len() as f32 / 2.0)).floor() as usize; println!("\n{}", "=".repeat(HEADER_SIZE).custom_color(GREY_COLOR)); println!("{:>pad$}", title.custom_color(GREY_COLOR)); println!("{}", "=".repeat(HEADER_SIZE).custom_color(GREY_COLOR)); } fn print_list(&self, list_items: Vec<(String, String)>) { list_items.iter().enumerate().for_each(|(index, item)| { println!("{}. {}: {}", index + 1, item.0.yellow(), item.1.cyan(),); }); } pub fn print_server_info(&self) { self.print_header("Server info"); let server_version = self.client.server_version().unwrap(); println!("{} {}", "Server name:".bold(), server_version.name.cyan()); println!( "{} {}", "Server version:".bold(), server_version.version.cyan() ); } pub fn print_server_capabilities(&self) { self.print_header("Capabilities"); let capability_vec = [ ("tools", self.client.server_has_tools()), ("prompts", self.client.server_has_prompts()), ("resources", self.client.server_has_resources()), ("logging", self.client.server_supports_logging()), ("experimental", self.client.server_has_experimental()), ]; capability_vec.iter().for_each(|(tool_name, opt)| { println!( "{}: {}", tool_name.bold(), opt.map(|b| if b { "Yes" } else { "No" }) .unwrap_or("Unknown") .cyan() ); }); } pub async fn print_tool_list(&self) -> SdkResult<()> { // Return if the MCP server does not support tools if !self.client.server_has_tools().unwrap_or(false) { return Ok(()); } let tools = self.client.request_tool_list(None).await?; self.print_header("Tools"); self.print_list( tools .tools .iter() .map(|item| { ( item.name.clone(), item.description.clone().unwrap_or_default(), ) }) .collect(), ); Ok(()) } pub async fn print_prompts_list(&self) -> SdkResult<()> { // Return if the MCP server does not support prompts if !self.client.server_has_prompts().unwrap_or(false) { return Ok(()); } let prompts = self.client.request_prompt_list(None).await?; self.print_header("Prompts"); self.print_list( prompts .prompts .iter() .map(|item| { ( item.name.clone(), item.description.clone().unwrap_or_default(), ) }) .collect(), ); Ok(()) } pub async fn print_resource_list(&self) -> SdkResult<()> { // Return if the MCP server does not support resources if !self.client.server_has_resources().unwrap_or(false) { return Ok(()); } let resources = self.client.request_resource_list(None).await?; self.print_header("Resources"); self.print_list( resources .resources .iter() .map(|item| { ( item.name.clone(), format!( "( uri: {} , mime: {}", item.uri, item.mime_type.as_ref().unwrap_or(&"?".to_string()), ), ) }) .collect(), ); Ok(()) } pub async fn print_resource_templates(&self) -> SdkResult<()> { // Return if the MCP server does not support resources if !self.client.server_has_resources().unwrap_or(false) { return Ok(()); } let templates = self.client.request_resource_template_list(None).await?; self.print_header("Resource Templates"); self.print_list( templates .resource_templates .iter() .map(|item| { ( item.name.clone(), item.description.clone().unwrap_or_default(), ) }) .collect(), ); Ok(()) } pub async fn call_add_tool(&self, a: i64, b: i64) -> SdkResult<()> { // Invoke the "add" tool with 100 and 25 as arguments, and display the result println!( "{}", format!("\nCalling the \"add\" tool with {a} and {b} ...").magenta() ); // Create a `Map<String, Value>` to represent the tool parameters let params = json!({ "a": a, "b": b }) .as_object() .unwrap() .clone(); // invoke the tool let result = self .client .request_tool_call(CallToolRequestParams { name: "add".to_string(), arguments: Some(params), meta: None, task: None, }) .await?; // Retrieve the result content and print it to the stdout let result_content = result.content.first().unwrap().as_text_content()?; println!("{}", result_content.text.green()); Ok(()) } pub async fn ping_n_times(&self, n: i32) { let max_pings = n; println!(); for ping_index in 1..=max_pings { print!("Ping the server ({ping_index} out of {max_pings})..."); std::io::stdout().flush().unwrap(); let ping_result = self.client.ping(None, None).await; print!( "\rPing the server ({} out of {}) : {}", ping_index, max_pings, if ping_result.is_ok() { "success".bright_green() } else { "failed".bright_red() } ); println!(); sleep(Duration::from_secs(2)).await; } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/server_handler_with_oauth.rs
crates/rust-mcp-sdk/examples/common/server_handler_with_oauth.rs
use async_trait::async_trait; use rust_mcp_sdk::auth::AuthInfo; use rust_mcp_sdk::schema::{ schema_utils::CallToolError, CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams, RpcError, TextContent, }; use rust_mcp_sdk::{ macros::{mcp_tool, JsonSchema}, mcp_server::ServerHandler, McpServer, }; use std::sync::Arc; use std::vec; //*******************************// // Show Authentication Info // //*******************************// #[mcp_tool( name = "show_auth_info", description = "Shows current user authentication info in json format" )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema, Default)] pub struct ShowAuthInfo {} impl ShowAuthInfo { pub fn call_tool(&self, auth_info: Option<AuthInfo>) -> Result<CallToolResult, CallToolError> { let auth_info_json = serde_json::to_string_pretty(&auth_info).map_err(|err| { CallToolError::from_message(format!("Undable to display auth info as string :{err}")) })?; Ok(CallToolResult::text_content(vec![TextContent::from( auth_info_json, )])) } } // Custom Handler to handle MCP Messages pub struct ServerHandlerAuth; // To check out a list of all the methods in the trait that you can override, take a look at // https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/main/crates/rust-mcp-sdk/src/mcp_handlers/mcp_server_handler.rs #[async_trait] #[allow(unused)] impl ServerHandler for ServerHandlerAuth { // Handle ListToolsRequest, return list of available tools as ListToolsResult async fn handle_list_tools_request( &self, params: Option<PaginatedRequestParams>, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ListToolsResult, RpcError> { Ok(ListToolsResult { meta: None, next_cursor: None, tools: vec![ShowAuthInfo::tool()], }) } /// Handles incoming CallToolRequest and processes it using the appropriate tool. async fn handle_call_tool_request( &self, params: CallToolRequestParams, runtime: Arc<dyn McpServer>, ) -> std::result::Result<CallToolResult, CallToolError> { if params.name.eq(&ShowAuthInfo::tool_name()) { let tool = ShowAuthInfo::default(); tool.call_tool(runtime.auth_info_cloned().await) } else { Err(CallToolError::from_message(format!( "Tool \"{}\" does not exists or inactive!", params.name, ))) } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/resources.rs
crates/rust-mcp-sdk/examples/common/resources.rs
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; use rust_mcp_macros::{mcp_resource, mcp_resource_template}; use rust_mcp_schema::{CompleteResultCompletion, TextResourceContents}; use rust_mcp_sdk::schema::{BlobResourceContents, McpMetaEx, ReadResourceResult, RpcError}; use serde_json::Map; /// A static resource provider for a simple plain-text example. /// /// This resource demonstrates how to expose readable text content via the MCP readresource request. /// It serves a famous movie quote as a self-contained, static text resource. #[mcp_resource( name = "Resource 1", description = "A plain text resource", title = "A plain text resource", mime_type = "text/plain", uri="test://static/resource/1", icons = [ ( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/text-resource.png", sizes = ["128x128"], mime_type = "image/png" ) ] )] pub struct PlainTextResource {} impl PlainTextResource { pub async fn get_resource() -> std::result::Result<ReadResourceResult, RpcError> { Ok(ReadResourceResult { contents: vec![TextResourceContents::new( "Resource 1: I'm gonna need a bigger boat", Self::resource_uri(), ) .with_mime_type("text/plain") .into()], meta: None, }) } } /// A static resource provider for a binary/blob example demonstrating base64-encoded content. /// /// This resource serves as a simple, self-contained example of how to expose arbitrary binary data /// (or base64-encoded text) via the MCP ReadResource request. /// /// The embedded payload is the base64 encoding of the string: /// `"Resource 2: I'm gonna need a bigger boat"` #[mcp_resource( name = "Resource 2", description = "A blob resource", title = "A blob resource", mime_type = "application/octet-stream", uri="test://static/resource/2", icons = [ ( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/blob-resource.png", sizes = ["128x128"], mime_type = "image/png" ) ] )] pub struct BlobTextResource {} impl BlobTextResource { pub async fn get_resource() -> std::result::Result<ReadResourceResult, RpcError> { Ok(ReadResourceResult { contents: vec![BlobResourceContents::new( "UmVzb3VyY2UgMjogSSdtIGdvbm5hIG5lZWQgYSBiaWdnZXIgYm9hdA==", Self::resource_uri(), ) .with_mime_type("application/octet-stream") .into()], meta: None, }) } } /// This struct enables MCP servers to expose official Pokémon sprites as resources /// /// ### URI Scheme /// - Custom protocol: `pokemon://<id>` /// - Example: `pokemon://25` → Pikachu sprite /// - The `<id>` is the Pokémon's National Pokédex number (1–1010+). /// /// The sprite is fetched from the public [PokeAPI sprites repository](https://github.com/PokeAPI/sprites). #[mcp_resource_template( name = "pokemon", description = "Official front-facing sprite of a Pokémon from the PokéAPI sprites", title = "Pokémon Sprite", mime_type = "image/png", uri_template = "pokemon://{pokemon-id}", audience = ["user", "assistant"], meta = r#"{ "source": "PokeAPI", "repository": "https://github.com/PokeAPI/sprites", "license": "CC-BY-4.0", "attribution": "Data from PokeAPI - https://pokeapi.co/" }"#, icons = [ ( src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/pokemon-icon.png", sizes = ["96x96"], mime_type = "image/png" ) ] )] pub struct PokemonImageResource {} impl PokemonImageResource { pub fn matches_url(uri: &str) -> bool { uri.starts_with("pokemon://") } // // Demonstration-only completion logic; not performance optimized. // pub fn completion(pokemon_id: &str) -> CompleteResultCompletion { let max_result = 100; // All Pokémon IDs as `String`s ranging from `"1"` to `"1050"`, let pokemon_ids: Vec<String> = (1..=1050).map(|i| i.to_string()).collect(); let matched_ids = pokemon_ids .iter() .filter(|id| id.starts_with(pokemon_id)) .cloned() .collect::<Vec<_>>(); let has_more = matched_ids.len() > max_result; CompleteResultCompletion { has_more: has_more.then_some(true), total: (!matched_ids.is_empty()).then_some(matched_ids.len() as i64), values: matched_ids.into_iter().take(max_result).collect::<Vec<_>>(), } } pub async fn get_resource(uri: &str) -> std::result::Result<ReadResourceResult, RpcError> { let id = uri.replace("pokemon://", ""); let pokemon_uri = format!( "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/{}.png", id.trim() ); let client = reqwest::Client::builder() .user_agent("rust-mcp-sdk") .build() .map_err(|e| { RpcError::internal_error().with_message(format!("Failed to build HTTP client: {e}")) })?; let response = client.get(&pokemon_uri).send().await.map_err(|e| { RpcError::invalid_request().with_message(format!("Failed to fetch image: {e}")) })?; if !response.status().is_success() { return Err(RpcError::invalid_params().with_message(format!( "Image not found (HTTP {}): {pokemon_uri}", response.status() ))); } let content_type = response .headers() .get(reqwest::header::CONTENT_TYPE) .and_then(|v| v.to_str().ok()) .unwrap_or("application/octet-stream") .to_string(); // Extract MIME type let mime_type = content_type .split(';') .next() .unwrap_or("application/octet-stream") .trim() .to_string(); let bytes = response.bytes().await.map_err(|e| { RpcError::internal_error().with_message(format!("Failed to read image bytes: {e}")) })?; let base64_content = BASE64.encode(&bytes); let meta = Map::new() .add("source", "PokeAPI") .add("repository", "https://github.com/PokeAPI/sprites") .add("attribution", "Data from PokeAPI - https://pokeapi.co/"); Ok(ReadResourceResult { contents: vec![BlobResourceContents::new(base64_content, pokemon_uri) .with_mime_type(mime_type) .with_meta(meta.clone()) .into()], meta: Some(meta.clone()), }) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/example_client_handler.rs
crates/rust-mcp-sdk/examples/common/example_client_handler.rs
use async_trait::async_trait; use rust_mcp_sdk::mcp_client::ClientHandler; pub struct ExampleClientHandler; #[async_trait] impl ClientHandler for ExampleClientHandler { // To check out a list of all the methods in the trait that you can override, take a look at // https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/main/crates/rust-mcp-sdk/src/mcp_handlers/mcp_client_handler.rs // }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/utils.rs
crates/rust-mcp-sdk/examples/common/utils.rs
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; /// Set up the tracing subscriber for logging pub fn initialize_tracing() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), ) .with(tracing_subscriber::fmt::layer()) .init(); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/example_server_handler_core.rs
crates/rust-mcp-sdk/examples/common/example_server_handler_core.rs
use crate::common::resources::{BlobTextResource, PlainTextResource, PokemonImageResource}; use super::tools::GreetingTools; use async_trait::async_trait; use rust_mcp_schema::{CompleteResult, ListResourceTemplatesResult, ListResourcesResult}; use rust_mcp_sdk::{ mcp_server::{enforce_compatible_protocol_version, ServerHandlerCore}, schema::{ schema_utils::CallToolError, ListToolsResult, NotificationFromClient, RequestFromClient, ResultFromServer, RpcError, }, McpServer, }; use std::sync::Arc; // Custom Handler to handle MCP Messages pub struct ExampleServerHandlerCore; // To check out a list of all the methods in the trait that you can override, take a look at // https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/main/crates/rust-mcp-sdk/src/mcp_handlers/mcp_server_handler.rs #[async_trait] #[allow(unused)] impl ServerHandlerCore for ExampleServerHandlerCore { // Process incoming requests from the client async fn handle_request( &self, request: RequestFromClient, runtime: Arc<dyn McpServer>, ) -> std::result::Result<ResultFromServer, RpcError> { let method_name = &request.method().to_owned(); match request { // Handle the initialization request RequestFromClient::InitializeRequest(params) => { let mut server_info = runtime.server_info().to_owned(); if let Some(updated_protocol_version) = enforce_compatible_protocol_version( &params.protocol_version, &server_info.protocol_version, ) .map_err(|err| RpcError::internal_error().with_message(err.to_string()))? { server_info.protocol_version = params.protocol_version; } return Ok(server_info.into()); } // Handle ListToolsRequest, return list of available tools RequestFromClient::ListToolsRequest(_params) => Ok(ListToolsResult { meta: None, next_cursor: None, tools: GreetingTools::tools(), } .into()), // Handles incoming CallToolRequest and processes it using the appropriate tool. RequestFromClient::CallToolRequest(params) => { let tool_name = params.name.to_string(); // Attempt to convert request parameters into GreetingTools enum let tool_params = GreetingTools::try_from(params) .map_err(|_| CallToolError::unknown_tool(tool_name.clone()))?; // Match the tool variant and execute its corresponding logic let result = match tool_params { GreetingTools::SayHelloTool(say_hello_tool) => say_hello_tool .call_tool() .map_err(|err| RpcError::internal_error().with_message(err.to_string()))?, GreetingTools::SayGoodbyeTool(say_goodbye_tool) => say_goodbye_tool .call_tool() .map_err(|err| RpcError::internal_error().with_message(err.to_string()))?, }; Ok(result.into()) } // return list of available resources RequestFromClient::ListResourcesRequest(params) => Ok(ListResourcesResult { meta: None, next_cursor: None, resources: vec![PlainTextResource::resource(), BlobTextResource::resource()], } .into()), // return list of available resource templates RequestFromClient::ListResourceTemplatesRequest(params) => { Ok(ListResourceTemplatesResult { meta: None, next_cursor: None, resource_templates: vec![PokemonImageResource::resource_template()], } .into()) } RequestFromClient::ReadResourceRequest(params) => { if PlainTextResource::resource_uri().starts_with(&params.uri) { return PlainTextResource::get_resource().await.map(|r| r.into()); } if BlobTextResource::resource_uri().starts_with(&params.uri) { return BlobTextResource::get_resource().await.map(|r| r.into()); } if PokemonImageResource::matches_url(&params.uri) { return PokemonImageResource::get_resource(&params.uri) .await .map(|r| r.into()); } Err(RpcError::invalid_request() .with_message(format!("No resource was found for '{}'.", params.uri))) } RequestFromClient::CompleteRequest(params) => { if params.argument.name.eq("pokemon-id") { Ok(CompleteResult { completion: PokemonImageResource::completion(&params.argument.value), meta: None, } .into()) } else { Err(RpcError::method_not_found().with_message(format!( "No handler is implemented for '{}'.", params.argument.name, ))) } } // Return Method not found for any other requests _ => Err(RpcError::method_not_found() .with_message(format!("No handler is implemented for '{method_name}'.",))), // Handle custom requests RequestFromClient::CustomRequest(_) => Err(RpcError::method_not_found() .with_message("No handler is implemented for custom requests.".to_string())), } } // Process incoming client notifications async fn handle_notification( &self, notification: NotificationFromClient, _: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError> { Ok(()) } // Process incoming client errors async fn handle_error( &self, error: &RpcError, _: Arc<dyn McpServer>, ) -> std::result::Result<(), RpcError> { Ok(()) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/mod.rs
crates/rust-mcp-sdk/examples/common/mod.rs
mod example_client_handler; mod example_client_handler_core; mod example_server_handler; mod example_server_handler_core; pub mod inquiry_utils; pub mod resources; mod server_handler_with_oauth; pub mod tools; mod utils; pub use example_client_handler::*; pub use example_client_handler_core::*; pub use example_server_handler::*; pub use example_server_handler_core::*; pub use server_handler_with_oauth::*; pub use utils::*;
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-sdk/examples/common/tools.rs
crates/rust-mcp-sdk/examples/common/tools.rs
use rust_mcp_sdk::auth::AuthInfo; use rust_mcp_sdk::macros::JsonSchema; use rust_mcp_sdk::schema::{schema_utils::CallToolError, CallToolResult, TextContent}; use rust_mcp_sdk::{macros::mcp_tool, tool_box}; //****************// // SayHelloTool // //****************// #[mcp_tool( name = "say_hello", description = "Accepts a person's name and says a personalized \"Hello\" to that person", title = "A tool that says hello!", idempotent_hint = false, destructive_hint = false, open_world_hint = false, read_only_hint = false, icons = [ (src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/hello_icon.png", mime_type = "image/png", sizes = ["128x128"]), ], )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema)] pub struct SayHelloTool { /// The name of the person to greet with a "Hello". name: String, } impl SayHelloTool { pub fn call_tool(&self) -> Result<CallToolResult, CallToolError> { let hello_message = format!("Hello, {}!", self.name); Ok(CallToolResult::text_content(vec![TextContent::from( hello_message, )])) } } //******************// // SayGoodbyeTool // //******************// #[mcp_tool( name = "say_goodbye", description = "Accepts a person's name and says a personalized \"Goodbye\" to that person.", idempotent_hint = false, destructive_hint = false, open_world_hint = false, read_only_hint = false, icons = [ (src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/goodbye_icon.png", mime_type = "image/png", sizes = ["128x128"]), ], )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema)] pub struct SayGoodbyeTool { /// The name of the person to say goodbye to. name: String, } impl SayGoodbyeTool { pub fn call_tool(&self) -> Result<CallToolResult, CallToolError> { let goodbye_message = format!("Goodbye, {}!", self.name); Ok(CallToolResult::text_content(vec![TextContent::from( goodbye_message, )])) } } //******************// // GreetingTools // //******************// // Generates an enum names GreetingTools, with SayHelloTool and SayGoodbyeTool variants tool_box!(GreetingTools, [SayHelloTool, SayGoodbyeTool]); //*******************************// // Show Authentication Info // //*******************************// #[mcp_tool( name = "show_auth_info", description = "Shows current user authentication info in json format" )] #[derive(Debug, ::serde::Deserialize, ::serde::Serialize, JsonSchema, Default)] pub struct ShowAuthInfo {} impl ShowAuthInfo { pub fn call_tool(&self, auth_info: Option<AuthInfo>) -> Result<CallToolResult, CallToolError> { let auth_info_json = serde_json::to_string_pretty(&auth_info).map_err(|err| { CallToolError::from_message(format!("Undable to display auth info as string :{err}")) })?; Ok(CallToolResult::text_content(vec![TextContent::from( auth_info_json, )])) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/resource.rs
crates/rust-mcp-macros/src/resource.rs
pub(crate) mod generator; pub(crate) mod parser;
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/lib.rs
crates/rust-mcp-macros/src/lib.rs
extern crate proc_macro; mod common; mod elicit; mod resource; mod tool; mod utils; use crate::elicit::generator::{generate_form_schema, generate_from_impl}; use crate::elicit::parser::{ElicitArgs, ElicitMode}; use crate::resource::generator::{ generate_resource_template_tokens, generate_resource_tokens, ResourceTemplateTokens, ResourceTokens, }; use crate::resource::parser::{McpResourceMacroAttributes, McpResourceTemplateMacroAttributes}; use crate::tool::generator::{generate_tool_tokens, ToolTokens}; use crate::tool::parser::McpToolMacroAttributes; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, Data, DeriveInput, Fields}; use utils::{base_crate, is_option, is_vec_string, renamed_field, type_to_json_schema}; /// A procedural macro attribute to generate rust_mcp_schema::Tool related utility methods for a struct. /// /// The `mcp_tool` macro generates an implementation for the annotated struct that includes: /// - A `tool_name()` method returning the tool's name as a string. /// - A `tool()` method returning a `rust_mcp_schema::Tool` instance with the tool's name, /// description, input schema, meta, and title derived from the struct's fields and attributes. /// /// # Attributes /// * `name` - The name of the tool (required, non-empty string). /// * `description` - A description of the tool (required, non-empty string). /// * `meta` - Optional JSON object as a string literal for metadata. /// * `title` - Optional string for the tool's title. /// /// # Panics /// Panics if the macro is applied to anything other than a struct. /// /// # Example /// ```rust,ignore /// # #[cfg(not(feature = "sdk"))] /// # { /// #[rust_mcp_macros::mcp_tool( /// name = "example_tool", /// description = "An example tool", /// meta = "{\"version\": \"1.0\"}", /// title = "Example Tool" /// )] /// #[derive(rust_mcp_macros::JsonSchema)] /// struct ExampleTool { /// field1: String, /// field2: i32, /// } /// /// assert_eq!(ExampleTool::tool_name(), "example_tool"); /// let tool: rust_mcp_schema::Tool = ExampleTool::tool(); /// assert_eq!(tool.name, "example_tool"); /// assert_eq!(tool.description.unwrap(), "An example tool"); /// assert_eq!(tool.meta.as_ref().unwrap().get("version").unwrap(), "1.0"); /// assert_eq!(tool.title.unwrap(), "Example Tool"); /// /// let schema_properties = tool.input_schema.properties.unwrap(); /// assert_eq!(schema_properties.len(), 2); /// assert!(schema_properties.contains_key("field1")); /// assert!(schema_properties.contains_key("field2")); /// } /// ``` #[proc_macro_attribute] pub fn mcp_tool(attributes: TokenStream, input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let input_ident = &input.ident; let macro_attributes = parse_macro_input!(attributes as McpToolMacroAttributes); let ToolTokens { base_crate, tool_name, tool_description, meta, title, output_schema, annotations, execution, icons, } = generate_tool_tokens(macro_attributes); // TODO: add support for schema version to ToolInputSchema : // it defaults to JSON Schema 2020-12 when no explicit $schema is provided. let tool_token = quote! { #base_crate::Tool { name: #tool_name.to_string(), description: Some(#tool_description.to_string()), #output_schema #title #meta #annotations #execution #icons input_schema: #base_crate::ToolInputSchema::new(required, properties, None) } }; let output = quote! { impl #input_ident { /// Returns the name of the tool as a String. pub fn tool_name() -> String { #tool_name.to_string() } /// Returns a `CallToolRequestParams` initialized with the current tool's name. /// /// You can further customize the request by adding arguments or other attributes /// using the builder pattern. For example: /// /// ```ignore /// # use my_crate::{MyTool}; /// let args = serde_json::Map::new(); /// let task_meta = TaskMetadata{ttl: Some(200)} /// /// let params: CallToolRequestParams = MyTool::request_params() /// .with_arguments(args) /// .with_task(task_meta); /// ``` /// /// # Returns /// A `CallToolRequestParams` with the tool name set. pub fn request_params() -> #base_crate::CallToolRequestParams { #base_crate::CallToolRequestParams::new(#tool_name.to_string()) } /// Constructs and returns a `rust_mcp_schema::Tool` instance. /// /// The tool includes the name, description, input schema, meta, and title derived from /// the struct's attributes. pub fn tool() -> #base_crate::Tool { let json_schema = &#input_ident::json_schema(); let required: Vec<_> = match json_schema.get("required").and_then(|r| r.as_array()) { Some(arr) => arr .iter() .filter_map(|item| item.as_str().map(String::from)) .collect(), None => Vec::new(), }; let properties: Option< std::collections::HashMap<String, serde_json::Map<String, serde_json::Value>>, > = json_schema .get("properties") .and_then(|v| v.as_object()) // Safely extract "properties" as an object. .map(|properties| { properties .iter() .filter_map(|(key, value)| { serde_json::to_value(value) .ok() // If serialization fails, return None. .and_then(|v| { if let serde_json::Value::Object(obj) = v { Some(obj) } else { None } }) .map(|obj| (key.to_string(), obj)) // Return the (key, value) tuple }) .collect() }); #tool_token } } // Retain the original item (struct definition) #input }; TokenStream::from(output) } #[proc_macro_attribute] pub fn mcp_elicit(args: TokenStream, input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let fields = match &input.data { Data::Struct(s) => match &s.fields { Fields::Named(n) => &n.named, _ => panic!("mcp_elicit only supports structs with named fields"), }, _ => panic!("mcp_elicit only supports structs"), }; let struct_name = &input.ident; let elicit_args = parse_macro_input!(args as ElicitArgs); let base_crate = base_crate(); let message = &elicit_args.message; let impl_block = match elicit_args.mode { ElicitMode::Form => { let (from_content, init) = generate_from_impl(fields, &base_crate); let schema = generate_form_schema(struct_name, &base_crate); quote! { impl #struct_name { pub fn message() -> &'static str{ #message } pub fn requested_schema() -> #base_crate::ElicitFormSchema { #schema } pub fn elicit_mode()->&'static str{ "form" } pub fn elicit_form_params() -> #base_crate::ElicitRequestFormParams { #base_crate::ElicitRequestFormParams::new( Self::message().to_string(), Self::requested_schema(), None, None, ) } pub fn elicit_request_params() -> #base_crate::ElicitRequestParams { Self::elicit_form_params().into() } pub fn from_elicit_result_content( mut content: Option<std::collections::HashMap<String, #base_crate::ElicitResultContent>>, ) -> Result<Self, #base_crate::RpcError> { use #base_crate::{ElicitResultContent as V, RpcError}; let mut map = content.take().unwrap_or_default(); #from_content Ok(#init) } } } } ElicitMode::Url { url } => { let (from_content, init) = generate_from_impl(fields, &base_crate); quote! { impl #struct_name { pub fn message() -> &'static str { #message } pub fn url() -> &'static str { #url } pub fn elicit_mode()->&'static str { "url" } pub fn elicit_url_params(elicitation_id:String) -> #base_crate::ElicitRequestUrlParams { #base_crate::ElicitRequestUrlParams::new( elicitation_id, Self::message().to_string(), Self::url().to_string(), None, None, ) } pub fn elicit_request_params(elicitation_id:String) -> #base_crate::ElicitRequestParams { Self::elicit_url_params(elicitation_id).into() } pub fn from_elicit_result_content( mut content: Option<std::collections::HashMap<String, #base_crate::ElicitResultContent>>, ) -> Result<Self, RpcError> { use #base_crate::{ElicitResultContent as V, RpcError}; let mut map = content.take().unwrap_or_default(); #from_content Ok(#init) } } } } }; let expanded = quote! { #input #impl_block }; TokenStream::from(expanded) } /// Derives a JSON Schema representation for a struct. /// /// This procedural macro generates a `json_schema()` method for the annotated struct, returning a /// `serde_json::Map<String, serde_json::Value>` that represents the struct as a JSON Schema object. /// The schema includes the struct's fields as properties, with support for basic types, `Option<T>`, /// `Vec<T>`, and nested structs that also derive `JsonSchema`. /// /// # Features /// - **Basic Types:** Maps `String` to `"string"`, `i32` to `"integer"`, `bool` to `"boolean"`, etc. /// - **`Option<T>`:** Adds `"nullable": true` to the schema of the inner type, indicating the field is optional. /// - **`Vec<T>`:** Generates an `"array"` schema with an `"items"` field describing the inner type. /// - **Nested Structs:** Recursively includes the schema of nested structs (assumed to derive `JsonSchema`), /// embedding their `"properties"` and `"required"` fields. /// - **Required Fields:** Adds a top-level `"required"` array listing field names not wrapped in `Option`. /// /// # Notes /// It’s designed as a straightforward solution to meet the basic needs of this package, supporting /// common types and simple nested structures. For more advanced features or robust JSON Schema generation, /// consider exploring established crates like /// [`schemars`](https://crates.io/crates/schemars) on crates.io /// /// # Limitations /// - Supports only structs with named fields (e.g., `struct S { field: Type }`). /// - Nested structs must also derive `JsonSchema`, or compilation will fail. /// - Unknown types are mapped to `{"type": "unknown"}`. /// - Type paths must be in scope (e.g., fully qualified paths like `my_mod::InnerStruct` work if imported). /// /// # Panics /// - If the input is not a struct with named fields (e.g., tuple structs or enums). /// /// # Dependencies /// Relies on `serde_json` for `Map` and `Value` types. /// #[proc_macro_derive(JsonSchema, attributes(json_schema))] pub fn derive_json_schema(input: TokenStream) -> TokenStream { let input = syn::parse_macro_input!(input as DeriveInput); let name = &input.ident; let schema_body = match &input.data { Data::Struct(data) => match &data.fields { Fields::Named(fields) => { let field_entries = fields.named.iter().map(|field| { let field_attrs = &field.attrs; let renamed_field = renamed_field(field_attrs); let field_name = renamed_field.unwrap_or(field.ident.as_ref().unwrap().to_string()); let field_type = &field.ty; let schema = type_to_json_schema(field_type, field_attrs); quote! { properties.insert( #field_name.to_string(), serde_json::Value::Object(#schema) ); } }); let required_fields = fields.named.iter().filter_map(|field| { let renamed_field = renamed_field(&field.attrs); let field_name = renamed_field.unwrap_or(field.ident.as_ref().unwrap().to_string()); let field_type = &field.ty; if !is_option(field_type) { Some(quote! { required.push(#field_name.to_string()); }) } else { None } }); quote! { let mut schema = serde_json::Map::new(); let mut properties = serde_json::Map::new(); let mut required = Vec::new(); #(#field_entries)* #(#required_fields)* schema.insert("type".to_string(), serde_json::Value::String("object".to_string())); schema.insert("properties".to_string(), serde_json::Value::Object(properties)); if !required.is_empty() { schema.insert("required".to_string(), serde_json::Value::Array( required.into_iter().map(serde_json::Value::String).collect() )); } schema } } _ => panic!("JsonSchema derive macro only supports named fields for structs"), }, Data::Enum(data) => { let variant_schemas = data.variants.iter().map(|variant| { let variant_attrs = &variant.attrs; let variant_name = variant.ident.to_string(); let renamed_variant = renamed_field(variant_attrs).unwrap_or(variant_name.clone()); // Parse variant-level json_schema attributes let mut title: Option<String> = None; let mut description: Option<String> = None; for attr in variant_attrs { if attr.path().is_ident("json_schema") { let _ = attr.parse_nested_meta(|meta| { if meta.path.is_ident("title") { title = Some(meta.value()?.parse::<syn::LitStr>()?.value()); } else if meta.path.is_ident("description") { description = Some(meta.value()?.parse::<syn::LitStr>()?.value()); } Ok(()) }); } } let title_quote = title.as_ref().map(|t| { quote! { map.insert("title".to_string(), serde_json::Value::String(#t.to_string())); } }); let description_quote = description.as_ref().map(|desc| { quote! { map.insert("description".to_string(), serde_json::Value::String(#desc.to_string())); } }); match &variant.fields { Fields::Unit => { // Unit variant: use "enum" with the variant name quote! { { let mut map = serde_json::Map::new(); map.insert("enum".to_string(), serde_json::Value::Array(vec![ serde_json::Value::String(#renamed_variant.to_string()) ])); #title_quote #description_quote serde_json::Value::Object(map) } } } Fields::Unnamed(fields) => { // Newtype or tuple variant if fields.unnamed.len() == 1 { // Newtype variant: use the inner type's schema let field = &fields.unnamed[0]; let field_type = &field.ty; let field_attrs = &field.attrs; let schema = type_to_json_schema(field_type, field_attrs); quote! { { let mut map = #schema; #title_quote #description_quote serde_json::Value::Object(map) } } } else { // Tuple variant: array with items let field_schemas = fields.unnamed.iter().map(|field| { let field_type = &field.ty; let field_attrs = &field.attrs; let schema = type_to_json_schema(field_type, field_attrs); quote! { serde_json::Value::Object(#schema) } }); quote! { { let mut map = serde_json::Map::new(); map.insert("type".to_string(), serde_json::Value::String("array".to_string())); map.insert("items".to_string(), serde_json::Value::Array(vec![#(#field_schemas),*])); map.insert("additionalItems".to_string(), serde_json::Value::Bool(false)); #title_quote #description_quote serde_json::Value::Object(map) } } } } Fields::Named(fields) => { // Struct variant: object with properties and required fields let field_entries = fields.named.iter().map(|field| { let field_attrs = &field.attrs; let renamed_field = renamed_field(field_attrs); let field_name = renamed_field.unwrap_or(field.ident.as_ref().unwrap().to_string()); let field_type = &field.ty; let schema = type_to_json_schema(field_type, field_attrs); quote! { properties.insert( #field_name.to_string(), serde_json::Value::Object(#schema) ); } }); let required_fields = fields.named.iter().filter_map(|field| { let renamed_field = renamed_field(&field.attrs); let field_name = renamed_field.unwrap_or(field.ident.as_ref().unwrap().to_string()); let field_type = &field.ty; if !is_option(field_type) { Some(quote! { required.push(#field_name.to_string()); }) } else { None } }); quote! { { let mut map = serde_json::Map::new(); let mut properties = serde_json::Map::new(); let mut required = Vec::new(); #(#field_entries)* #(#required_fields)* map.insert("type".to_string(), serde_json::Value::String("object".to_string())); map.insert("properties".to_string(), serde_json::Value::Object(properties)); if !required.is_empty() { map.insert("required".to_string(), serde_json::Value::Array( required.into_iter().map(serde_json::Value::String).collect() )); } #title_quote #description_quote serde_json::Value::Object(map) } } } } }); quote! { let mut schema = serde_json::Map::new(); schema.insert("oneOf".to_string(), serde_json::Value::Array(vec![ #(#variant_schemas),* ])); schema } } _ => panic!("JsonSchema derive macro only supports structs and enums"), }; let expanded = quote! { impl #name { pub fn json_schema() -> serde_json::Map<String, serde_json::Value> { #schema_body } } }; TokenStream::from(expanded) } #[proc_macro_attribute] /// A procedural macro attribute to generate `rust_mcp_schema::Resource` related utility methods for a struct. /// /// The `mcp_resource` macro adds static methods to the annotated struct that provide access to /// resource metadata and construct a fully populated `rust_mcp_schema::Resource` instance. /// /// Generated methods: /// - `resource_name()` → returns the resource name as `&'static str` /// - `resource_uri()` → returns the resource URI as `&'static str` /// - `resource()` → constructs and returns a complete `rust_mcp_schema::Resource` value /// /// # Attributes /// /// All attributes are optional except `name` and `uri`, which are **required** and must be non-empty. /// /// | Attribute | Type | Required | Description | /// |---------------|--------------------------------------|----------|-------------| /// | `name` | string literal or `concat!(...)` | Yes | Unique name of the resource. | /// | `description` | string literal or `concat!(...)` | Yes | Human-readable description of the resource. | /// | `title` | string literal or `concat!(...)` | No | Display title for the resource. | /// | `meta` | JSON object as string literal | No | Arbitrary metadata as a valid JSON object. Must parse as a JSON object (not array, null, etc.). | /// | `mime_type` | string literal | No | MIME type of the resource (e.g., `"image/png"`, `"application/pdf"`). | /// | `size` | integer literal (`i64`) | No | Size of the resource in bytes. | /// | `uri` | string literal | No | URI where the resource can be accessed. | /// | `audience` | array of string literals | No | List of intended audiences (e.g., `["user", "system"]`). | /// | `icons` | array of icon objects | No | List of icons in the same format as web app manifests (supports `src`, `sizes`, `type`). | /// /// String fields (`name`, `description`, `title`) support `concat!(...)` with string literals. /// /// # Panics /// /// The macro will cause a compile-time error (not a runtime panic) if: /// - Applied to anything other than a struct. /// - Required attributes (`name` or `uri`) are missing or empty. /// - `meta` is provided but is not a valid JSON object. /// - Invalid types are used for any attribute (e.g., non-integer for `size`). /// /// # Example /// /// ```rust /// use rust_mcp_macros::mcp_resource; /// #[mcp_resource( /// name = "company-logo", /// description = "The official company logo in high resolution", /// title = "Company Logo", /// mime_type = "image/png", /// size = 102400, /// uri = "https://example.com/assets/logo.png", /// audience = ["user", "assistant"], /// meta = "{\"license\": \"proprietary\", \"author\": \"Ali Hashemi\"}", /// icons = [ /// ( src = "logo-192.png", sizes = ["192x192"], mime_type = "image/png" ), /// ( src = "logo-512.png", sizes = ["512x512"], mime_type = "image/png" ) /// ] /// )] /// struct CompanyLogo{}; /// /// // Usage /// assert_eq!(CompanyLogo::resource_name(), "company-logo"); /// assert_eq!(CompanyLogo::resource_uri(), "https://example.com/assets/logo.png"); /// /// let resource = CompanyLogo::resource(); /// assert_eq!(resource.name, "company-logo"); /// assert_eq!(resource.mime_type.unwrap(), "image/png"); /// assert_eq!(resource.size.unwrap(), 102400); /// assert!(resource.icons.len() == 2); /// ``` pub fn mcp_resource(attributes: TokenStream, input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let input_ident = &input.ident; let macro_attributes = parse_macro_input!(attributes as McpResourceMacroAttributes); let ResourceTokens { base_crate, name, description, meta, title, icons, annotations, mime_type, size, uri, } = generate_resource_tokens(macro_attributes); quote! { impl #input_ident { /// returns the Resource uri pub fn resource_uri()->&'static str{ #uri } /// returns the Resource name pub fn resource_name()->&'static str{ #name } /// Constructs and returns a `rust_mcp_schema::Resource` instance. pub fn resource()->#base_crate::Resource{ #base_crate::Resource{ annotations: #annotations, description: #description, icons: #icons, meta: #meta, mime_type: #mime_type, name: #name, size: #size, title: #title, uri: #uri } } } #input } .into() } #[proc_macro_attribute] /// A procedural macro attribute to generate `rust_mcp_schema::Resource` related utility methods for a struct. /// /// The `mcp_resource` macro adds static methods to the annotated struct that provide access to /// resource metadata and construct a fully populated `rust_mcp_schema::Resource` instance. /// /// Generated methods: /// - `resource_name()` → returns the resource name as `&'static str` /// - `resource_uri_template()` → returns the resource template URI as `&'static str` /// - `resource()` → constructs and returns a complete `rust_mcp_schema::Resource` value /// /// # Attributes /// /// All attributes are optional except `name` and `uri`, which are **required** and must be non-empty. /// /// | Attribute | Type | Required | Description | /// |---------------|--------------------------------------|----------|-------------| /// | `name` | string literal or `concat!(...)` | Yes | Unique name of the resource. | /// | `description` | string literal or `concat!(...)` | Yes | Human-readable description of the resource. | /// | `title` | string literal or `concat!(...)` | No | Display title for the resource. | /// | `meta` | JSON object as string literal | No | Arbitrary metadata as a valid JSON object. Must parse as a JSON object (not array, null, etc.). | /// | `mime_type` | string literal | No | MIME type of the resource (e.g., `"image/png"`, `"application/pdf"`). | /// | `uri_template` | string literal | No | URI template where the resource can be accessed. | /// | `audience` | array of string literals | No | List of intended audiences (e.g., `["user", "system"]`). | /// | `icons` | array of icon objects | No | List of icons in the same format as web app manifests (supports `src`, `sizes`, `type`). | /// /// String fields (`name`, `description`, `title`) support `concat!(...)` with string literals. /// /// # Panics /// /// The macro will cause a compile-time error (not a runtime panic) if: /// - Applied to anything other than a struct. /// - Required attributes (`name` or `uri_template`) are missing or empty. /// - `meta` is provided but is not a valid JSON object. /// - Invalid types are used for any attribute (e.g., non-integer for `size`). /// /// # Example /// /// ```rust /// use rust_mcp_macros::mcp_resource_template; /// #[mcp_resource_template( /// name = "company-logos", /// description = "The official company logos in different resolutions", /// title = "Company Logos", /// mime_type = "image/png", /// uri_template = "https://example.com/assets/{file_path}", /// audience = ["user", "assistant"], /// meta = "{\"license\": \"proprietary\", \"author\": \"Ali Hashemi\"}", /// icons = [ /// ( src = "logo-192.png", sizes = ["192x192"], mime_type = "image/png" ), /// ( src = "logo-512.png", sizes = ["512x512"], mime_type = "image/png" ) /// ] /// )] /// struct CompanyLogo {}; /// /// // Usage /// assert_eq!(CompanyLogo::resource_template_name(), "company-logos"); /// assert_eq!( /// CompanyLogo::resource_template_uri(), /// "https://example.com/assets/{file_path}" /// ); /// /// let resource_template = CompanyLogo::resource_template(); /// assert_eq!(resource_template.name, "company-logos"); /// assert_eq!(resource_template.mime_type.unwrap(), "image/png"); /// assert!(resource_template.icons.len() == 2); /// ``` pub fn mcp_resource_template(attributes: TokenStream, input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let input_ident = &input.ident; let macro_attributes = parse_macro_input!(attributes as McpResourceTemplateMacroAttributes); let ResourceTemplateTokens { base_crate, name, description, meta, title, icons, annotations, mime_type, uri_template, } = generate_resource_template_tokens(macro_attributes); quote! { impl #input_ident { /// returns the Resource Template uri pub fn resource_template_uri()->&'static str{ #uri_template } /// returns the Resource Template name pub fn resource_template_name()->&'static str{ #name }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
true
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/utils.rs
crates/rust-mcp-macros/src/utils.rs
use proc_macro2::TokenStream; use quote::quote; use syn::{ punctuated::Punctuated, token, Attribute, DeriveInput, GenericArgument, Lit, LitInt, LitStr, Path, PathArguments, Type, TypePath, }; pub fn base_crate() -> TokenStream { // Conditionally select the path for Tool if cfg!(feature = "sdk") { quote! { rust_mcp_sdk::schema } } else { quote! { rust_mcp_schema } } } // Check if a type is an Option<T> pub fn is_option(ty: &Type) -> bool { if let Type::Path(type_path) = ty { if type_path.path.segments.len() == 1 { let segment = &type_path.path.segments[0]; return segment.ident == "Option" && matches!(segment.arguments, PathArguments::AngleBracketed(_)); } } false } #[allow(unused)] // Check if a type is a Vec<T> pub fn is_vec(ty: &Type) -> bool { if let Type::Path(type_path) = ty { if type_path.path.segments.len() == 1 { let segment = &type_path.path.segments[0]; return segment.ident == "Vec" && matches!(segment.arguments, PathArguments::AngleBracketed(_)); } } false } #[allow(unused)] // Extract the inner type from Vec<T> or Option<T> pub fn inner_type(ty: &Type) -> Option<&Type> { if let Type::Path(type_path) = ty { if type_path.path.segments.len() == 1 { let segment = &type_path.path.segments[0]; if matches!(segment.arguments, PathArguments::AngleBracketed(_)) { if let PathArguments::AngleBracketed(args) = &segment.arguments { if args.args.len() == 1 { if let syn::GenericArgument::Type(inner_ty) = &args.args[0] { return Some(inner_ty); } } } } } } None } pub fn doc_comment(attrs: &[Attribute]) -> Option<String> { let mut docs = Vec::new(); for attr in attrs { if attr.path().is_ident("doc") { if let syn::Meta::NameValue(meta) = &attr.meta { if let syn::Expr::Lit(expr_lit) = &meta.value { if let syn::Lit::Str(lit_str) = &expr_lit.lit { docs.push(lit_str.value().trim().to_string()); } } } } } if docs.is_empty() { None } else { Some(docs.join("\n")) } } pub fn might_be_struct(ty: &Type) -> bool { if let Type::Path(type_path) = ty { if type_path.path.segments.len() == 1 { let ident = type_path.path.segments[0].ident.to_string(); let common_types = vec![ "i8", "i16", "i32", "i64", "i128", "u8", "u16", "u32", "u64", "u128", "f32", "f64", "bool", "char", "str", "String", "Vec", "Option", ]; return !common_types.contains(&ident.as_str()) && type_path.path.segments[0].arguments.is_empty(); } } false } #[allow(unused)] // Helper to check if a type is an enum pub fn is_enum(ty: &Type, _input: &DeriveInput) -> bool { if let Type::Path(type_path) = ty { // Check for #[mcp_elicit(enum)] attribute on the type // Since we can't access the enum's definition directly, we rely on the attribute // This assumes the enum is marked with #[mcp_elicit(enum)] in its definition // Alternatively, we could pass a list of known enums, but attribute-based is simpler type_path .path .segments .last() .map(|s| { // For now, we'll assume any type could be an enum if it has the attribute // In a real-world scenario, we'd need to resolve the type's definition // For simplicity, we check if the type name is plausible (not String, bool, i32, i64) let ident = s.ident.to_string(); !["String", "bool", "i32", "i64"].contains(&ident.as_str()) }) .unwrap_or(false) } else { false } } #[allow(unused)] // Helper to generate enum parsing code pub fn generate_enum_parse( field_type: &Type, field_name: &str, base_crate: &proc_macro2::TokenStream, ) -> proc_macro2::TokenStream { let type_ident = match field_type { Type::Path(type_path) => type_path.path.segments.last().unwrap().ident.clone(), _ => panic!("Expected path type for enum"), }; // Since we can't access the enum's variants directly in this context, // we'll assume the enum has unit variants and expect strings matching their names // In a real-world scenario, you'd parse the enum's Data::Enum to get variant names // For now, we'll generate a generic parse assuming variant names are provided as strings quote! { { // Attempt to parse the string using a match // Since we don't have the variants, we rely on the enum implementing FromStr match s.as_str() { // We can't dynamically list variants, so we use FromStr // If FromStr is not implemented, this will fail at compile time s => s.parse().map_err(|_| #base_crate::RpcError::parse_error().with_message(format!( "Invalid enum value for field '{}': cannot parse '{}' into {}", #field_name, s, stringify!(#type_ident) )))? } } } } pub fn type_to_json_schema(ty: &Type, attrs: &[Attribute]) -> proc_macro2::TokenStream { let integer_types = [ "i8", "i16", "i32", "i64", "i128", "u8", "u16", "u32", "u64", "u128", ]; let float_types = ["f32", "f64"]; // Parse custom json_schema attributes let mut title: Option<String> = None; let mut format: Option<String> = None; let mut min_length: Option<u64> = None; let mut max_length: Option<u64> = None; let mut minimum: Option<i64> = None; let mut maximum: Option<i64> = None; let mut default: Option<proc_macro2::TokenStream> = None; let mut attr_description: Option<String> = None; for attr in attrs { if attr.path().is_ident("json_schema") { let _ = attr.parse_nested_meta(|meta| { if meta.path.is_ident("title") { title = Some(meta.value()?.parse::<LitStr>()?.value()); } else if meta.path.is_ident("description") { attr_description = Some(meta.value()?.parse::<LitStr>()?.value()); } else if meta.path.is_ident("format") { format = Some(meta.value()?.parse::<LitStr>()?.value()); } else if meta.path.is_ident("min_length") { min_length = Some(meta.value()?.parse::<LitInt>()?.base10_parse::<u64>()?); } else if meta.path.is_ident("max_length") { max_length = Some(meta.value()?.parse::<LitInt>()?.base10_parse::<u64>()?); } else if meta.path.is_ident("minimum") { minimum = Some(meta.value()?.parse::<LitInt>()?.base10_parse::<i64>()?); } else if meta.path.is_ident("maximum") { maximum = Some(meta.value()?.parse::<LitInt>()?.base10_parse::<i64>()?); } else if meta.path.is_ident("default") { let lit = meta.value()?.parse::<Lit>()?; default = Some(match lit { Lit::Str(lit_str) => { let value = lit_str.value(); quote! { serde_json::Value::String(#value.to_string()) } } Lit::Int(lit_int) => { let value = lit_int.base10_parse::<i64>()?; assert!( (i64::MIN..=i64::MAX).contains(&value), "Default value {value} out of range for i64" ); quote! { serde_json::Value::Number(serde_json::Number::from(#value)) } } Lit::Float(lit_float) => { let value = lit_float.base10_parse::<f64>()?; quote! { serde_json::Value::Number(serde_json::Number::from_f64(#value).expect("Invalid float")) } } Lit::Bool(lit_bool) => { let value = lit_bool.value(); quote! { serde_json::Value::Bool(#value) } } _ => return Err(meta.error("Unsupported default value type")), }); } Ok(()) }); } } let description = attr_description.or(doc_comment(attrs)); let description_quote = description.as_ref().map(|desc| { quote! { map.insert("description".to_string(), serde_json::Value::String(#desc.to_string())); } }); let title_quote = title.as_ref().map(|t| { quote! { map.insert("title".to_string(), serde_json::Value::String(#t.to_string())); } }); let default_quote = default.as_ref().map(|d| { quote! { map.insert("default".to_string(), #d); } }); match ty { Type::Path(type_path) => { if type_path.path.segments.len() == 1 { let segment = &type_path.path.segments[0]; let ident = &segment.ident; // Handle Option<T> if ident == "Option" { if let PathArguments::AngleBracketed(args) = &segment.arguments { if args.args.len() == 1 { if let syn::GenericArgument::Type(inner_ty) = &args.args[0] { let inner_schema = type_to_json_schema(inner_ty, attrs); let format_quote = format.as_ref().map(|f| { quote! { map.insert("format".to_string(), serde_json::Value::String(#f.to_string())); } }); let min_quote = min_length.as_ref().map(|min| { quote! { map.insert("minLength".to_string(), serde_json::Value::Number(serde_json::Number::from(#min))); } }); let max_quote = max_length.as_ref().map(|max| { quote! { map.insert("maxLength".to_string(), serde_json::Value::Number(serde_json::Number::from(#max))); } }); let min_num_quote = minimum.as_ref().map(|min| { quote! { map.insert("minimum".to_string(), serde_json::Value::Number(serde_json::Number::from(#min))); } }); let max_num_quote = maximum.as_ref().map(|max| { quote! { map.insert("maximum".to_string(), serde_json::Value::Number(serde_json::Number::from(#max))); } }); return quote! { { let mut map = #inner_schema; map.insert("nullable".to_string(), serde_json::Value::Bool(true)); #description_quote #title_quote #format_quote #min_quote #max_quote #min_num_quote #max_num_quote #default_quote map } }; } } } } // Handle Vec<T> else if ident == "Vec" { if let PathArguments::AngleBracketed(args) = &segment.arguments { if args.args.len() == 1 { if let syn::GenericArgument::Type(inner_ty) = &args.args[0] { let inner_schema = type_to_json_schema(inner_ty, &[]); let min_quote = min_length.as_ref().map(|min| { quote! { map.insert("minItems".to_string(), serde_json::Value::Number(serde_json::Number::from(#min))); } }); let max_quote = max_length.as_ref().map(|max| { quote! { map.insert("maxItems".to_string(), serde_json::Value::Number(serde_json::Number::from(#max))); } }); return quote! { { let mut map = serde_json::Map::new(); map.insert("type".to_string(), serde_json::Value::String("array".to_string())); map.insert("items".to_string(), serde_json::Value::Object(#inner_schema)); #description_quote #title_quote #min_quote #max_quote #default_quote map } }; } } } } // Handle nested structs else if might_be_struct(ty) { let path = &type_path.path; return quote! { { let mut map = #path::json_schema(); #description_quote #title_quote #default_quote map } }; } // Handle String else if ident == "String" { let format_quote = format.as_ref().map(|f| { quote! { map.insert("format".to_string(), serde_json::Value::String(#f.to_string())); } }); let min_quote = min_length.as_ref().map(|min| { quote! { map.insert("minLength".to_string(), serde_json::Value::Number(serde_json::Number::from(#min))); } }); let max_quote = max_length.as_ref().map(|max| { quote! { map.insert("maxLength".to_string(), serde_json::Value::Number(serde_json::Number::from(#max))); } }); return quote! { { let mut map = serde_json::Map::new(); map.insert("type".to_string(), serde_json::Value::String("string".to_string())); #description_quote #title_quote #format_quote #min_quote #max_quote #default_quote map } }; } // Handle integer types else if integer_types.iter().any(|t| ident == t) { let min_quote = minimum.as_ref().map(|min| { quote! { map.insert("minimum".to_string(), serde_json::Value::Number(serde_json::Number::from(#min))); } }); let max_quote = maximum.as_ref().map(|max| { quote! { map.insert("maximum".to_string(), serde_json::Value::Number(serde_json::Number::from(#max))); } }); return quote! { { let mut map = serde_json::Map::new(); map.insert("type".to_string(), serde_json::Value::String("integer".to_string())); #description_quote #title_quote #min_quote #max_quote #default_quote map } }; } // Handle float types else if float_types.iter().any(|t| ident == t) { let min_quote = minimum.as_ref().map(|min| { quote! { map.insert("minimum".to_string(), serde_json::Value::Number(serde_json::Number::from(#min))); } }); let max_quote = maximum.as_ref().map(|max| { quote! { map.insert("maximum".to_string(), serde_json::Value::Number(serde_json::Number::from(#max))); } }); return quote! { { let mut map = serde_json::Map::new(); map.insert("type".to_string(), serde_json::Value::String("number".to_string())); #description_quote #title_quote #min_quote #max_quote #default_quote map } }; } // Handle bool else if ident == "bool" { return quote! { { let mut map = serde_json::Map::new(); map.insert("type".to_string(), serde_json::Value::String("boolean".to_string())); #description_quote #title_quote #default_quote map } }; } } // Fallback for unknown types quote! { { let mut map = serde_json::Map::new(); map.insert("type".to_string(), serde_json::Value::String("unknown".to_string())); #description_quote #title_quote #default_quote map } } } _ => quote! { { let mut map = serde_json::Map::new(); map.insert("type".to_string(), serde_json::Value::String("unknown".to_string())); #description_quote #title_quote #default_quote map } }, } } #[allow(unused)] pub fn has_derive(attrs: &[Attribute], trait_name: &str) -> bool { attrs.iter().any(|attr| { if attr.path().is_ident("derive") { let parsed = attr.parse_args_with(Punctuated::<Path, token::Comma>::parse_terminated); if let Ok(derive_paths) = parsed { let derived = derive_paths.iter().any(|path| path.is_ident(trait_name)); return derived; } } false }) } pub fn is_vec_string(ty: &Type) -> bool { let Type::Path(TypePath { path, .. }) = ty else { return false; }; // Get last segment: e.g., `Vec` let Some(seg) = path.segments.last() else { return false; }; // Must be `Vec` if seg.ident != "Vec" { return false; } // Must have angle-bracketed args: <String> let PathArguments::AngleBracketed(args) = &seg.arguments else { return false; }; // Must contain exactly one type param if args.args.len() != 1 { return false; } // Check that the argument is `String` match args.args.first().unwrap() { GenericArgument::Type(Type::Path(tp)) => tp.path.is_ident("String"), _ => false, } } pub fn renamed_field(attrs: &[Attribute]) -> Option<String> { let mut renamed = None; for attr in attrs { if attr.path().is_ident("serde") { let _ = attr.parse_nested_meta(|meta| { if meta.path.is_ident("rename") { if let Ok(lit) = meta.value() { if let Ok(syn::Lit::Str(lit_str)) = lit.parse() { renamed = Some(lit_str.value()); } } } Ok(()) }); } } renamed } #[cfg(test)] mod tests { use super::*; use quote::quote; use syn::parse_quote; fn render(ts: proc_macro2::TokenStream) -> String { ts.to_string().replace(char::is_whitespace, "") } #[test] fn test_is_option() { let ty: Type = parse_quote!(Option<String>); assert!(is_option(&ty)); let ty: Type = parse_quote!(Vec<String>); assert!(!is_option(&ty)); } #[test] fn test_is_vec() { let ty: Type = parse_quote!(Vec<i32>); assert!(is_vec(&ty)); let ty: Type = parse_quote!(Option<i32>); assert!(!is_vec(&ty)); } #[test] fn test_inner_type() { let ty: Type = parse_quote!(Option<String>); let inner = inner_type(&ty); assert!(inner.is_some()); let inner = inner.unwrap(); assert_eq!(quote!(#inner).to_string(), quote!(String).to_string()); let ty: Type = parse_quote!(Vec<i32>); let inner = inner_type(&ty); assert!(inner.is_some()); let inner = inner.unwrap(); assert_eq!(quote!(#inner).to_string(), quote!(i32).to_string()); let ty: Type = parse_quote!(i32); assert!(inner_type(&ty).is_none()); } #[test] fn test_might_be_struct() { let ty: Type = parse_quote!(MyStruct); assert!(might_be_struct(&ty)); let ty: Type = parse_quote!(String); assert!(!might_be_struct(&ty)); } #[test] fn test_type_to_json_schema_string() { let ty: Type = parse_quote!(String); let attrs: Vec<Attribute> = vec![]; let tokens = type_to_json_schema(&ty, &attrs); let output = tokens.to_string(); assert!(output.contains("\"string\"")); } #[test] fn test_type_to_json_schema_option() { let ty: Type = parse_quote!(Option<i32>); let attrs: Vec<Attribute> = vec![]; let tokens = type_to_json_schema(&ty, &attrs); let output = tokens.to_string(); assert!(output.contains("\"nullable\"")); } #[test] fn test_type_to_json_schema_vec() { let ty: Type = parse_quote!(Vec<String>); let attrs: Vec<Attribute> = vec![]; let tokens = type_to_json_schema(&ty, &attrs); let output = tokens.to_string(); assert!(output.contains("\"array\"")); } #[test] fn test_has_derive() { let attr: Attribute = parse_quote!(#[derive(Clone, Debug)]); assert!(has_derive(&[attr.clone()], "Debug")); assert!(!has_derive(&[attr], "Serialize")); } #[test] fn test_renamed_field() { let attr: Attribute = parse_quote!(#[serde(rename = "renamed")]); assert_eq!(renamed_field(&[attr]), Some("renamed".to_string())); let attr: Attribute = parse_quote!(#[serde(skip_serializing_if = "Option::is_none")]); assert_eq!(renamed_field(&[attr]), None); } #[test] fn test_get_doc_comment_single_line() { let attrs: Vec<Attribute> = vec![parse_quote!(#[doc = "This is a test comment."])]; let result = super::doc_comment(&attrs); assert_eq!(result, Some("This is a test comment.".to_string())); } #[test] fn test_get_doc_comment_multi_line() { let attrs: Vec<Attribute> = vec![ parse_quote!(#[doc = "Line one."]), parse_quote!(#[doc = "Line two."]), parse_quote!(#[doc = "Line three."]), ]; let result = super::doc_comment(&attrs); assert_eq!( result, Some("Line one.\nLine two.\nLine three.".to_string()) ); } #[test] fn test_get_doc_comment_no_doc() { let attrs: Vec<Attribute> = vec![parse_quote!(#[allow(dead_code)])]; let result = super::doc_comment(&attrs); assert_eq!(result, None); } #[test] fn test_get_doc_comment_trim_whitespace() { let attrs: Vec<Attribute> = vec![parse_quote!(#[doc = " Trimmed line. "])]; let result = super::doc_comment(&attrs); assert_eq!(result, Some("Trimmed line.".to_string())); } #[test] fn test_renamed_field_basic() { let attrs = vec![parse_quote!(#[serde(rename = "new_name")])]; let result = renamed_field(&attrs); assert_eq!(result, Some("new_name".to_string())); } #[test] fn test_renamed_field_without_rename() { let attrs = vec![parse_quote!(#[serde(default)])]; let result = renamed_field(&attrs); assert_eq!(result, None); } #[test] fn test_renamed_field_with_multiple_attrs() { let attrs = vec![ parse_quote!(#[serde(default)]), parse_quote!(#[serde(rename = "actual_name")]), ]; let result = renamed_field(&attrs); assert_eq!(result, Some("actual_name".to_string())); } #[test] fn test_renamed_field_irrelevant_attribute() { let attrs = vec![parse_quote!(#[some_other_attr(value = "irrelevant")])]; let result = renamed_field(&attrs); assert_eq!(result, None); } #[test] fn test_renamed_field_ignores_other_serde_keys() { let attrs = vec![parse_quote!(#[serde(skip_serializing_if = "Option::is_none")])]; let result = renamed_field(&attrs); assert_eq!(result, None); } #[test] fn test_has_derive_positive() { let attrs: Vec<Attribute> = vec![parse_quote!(#[derive(Debug, Clone)])]; assert!(has_derive(&attrs, "Debug")); assert!(has_derive(&attrs, "Clone")); } #[test] fn test_has_derive_negative() { let attrs: Vec<Attribute> = vec![parse_quote!(#[derive(Serialize, Deserialize)])]; assert!(!has_derive(&attrs, "Debug")); } #[test] fn test_has_derive_no_derive_attr() { let attrs: Vec<Attribute> = vec![parse_quote!(#[allow(dead_code)])]; assert!(!has_derive(&attrs, "Debug")); } #[test] fn test_has_derive_multiple_attrs() { let attrs: Vec<Attribute> = vec![ parse_quote!(#[allow(unused)]), parse_quote!(#[derive(PartialEq)]), parse_quote!(#[derive(Eq)]), ]; assert!(has_derive(&attrs, "PartialEq")); assert!(has_derive(&attrs, "Eq")); assert!(!has_derive(&attrs, "Clone")); } #[test] fn test_has_derive_empty_attrs() { let attrs: Vec<Attribute> = vec![]; assert!(!has_derive(&attrs, "Debug")); } #[test] fn test_might_be_struct_with_custom_type() { let ty: syn::Type = parse_quote!(MyStruct); assert!(might_be_struct(&ty)); } #[test] fn test_might_be_struct_with_primitive_type() { let primitives = [ "i32", "u64", "bool", "f32", "String", "Option", "Vec", "char", "str", ]; for ty_str in &primitives { let ty: syn::Type = syn::parse_str(ty_str).unwrap(); assert!( !might_be_struct(&ty), "Expected '{ty_str}' to be not a struct" ); } } #[test] fn test_might_be_struct_with_namespaced_type() { let ty: syn::Type = parse_quote!(std::collections::HashMap<String, i32>); assert!(!might_be_struct(&ty)); // segments.len() > 1 } #[test] fn test_might_be_struct_with_generic_arguments() { let ty: syn::Type = parse_quote!(MyStruct<T>); assert!(!might_be_struct(&ty)); // has type arguments } #[test] fn test_might_be_struct_with_empty_type_path() { let ty: syn::Type = parse_quote!(()); assert!(!might_be_struct(&ty)); } #[test] fn test_json_schema_string() { let ty: syn::Type = parse_quote!(String); let tokens = type_to_json_schema(&ty, &[]); let output = render(tokens); assert!(output .contains("\"type\".to_string(),serde_json::Value::String(\"string\".to_string())")); } #[test] fn test_json_schema_integer() { let ty: syn::Type = parse_quote!(i32); let tokens = type_to_json_schema(&ty, &[]); let output = render(tokens); assert!(output .contains("\"type\".to_string(),serde_json::Value::String(\"integer\".to_string())")); } #[test] fn test_json_schema_boolean() { let ty: syn::Type = parse_quote!(bool); let tokens = type_to_json_schema(&ty, &[]); let output = render(tokens); assert!(output .contains("\"type\".to_string(),serde_json::Value::String(\"boolean\".to_string())")); } #[test] fn test_json_schema_vec_of_string() { let ty: syn::Type = parse_quote!(Vec<String>); let tokens = type_to_json_schema(&ty, &[]); let output = render(tokens); assert!(output .contains("\"type\".to_string(),serde_json::Value::String(\"array\".to_string())")); assert!(output.contains("\"items\".to_string(),serde_json::Value::Object")); } #[test] fn test_json_schema_option_of_number() { let ty: syn::Type = parse_quote!(Option<u64>); let tokens = type_to_json_schema(&ty, &[]); let output = render(tokens); assert!(output.contains("\"nullable\".to_string(),serde_json::Value::Bool(true)")); assert!(output .contains("\"type\".to_string(),serde_json::Value::String(\"integer\".to_string())")); } #[test] fn test_json_schema_custom_struct() { let ty: syn::Type = parse_quote!(MyStruct); let tokens = type_to_json_schema(&ty, &[]); let output = render(tokens); assert!(output.contains("MyStruct::json_schema()")); } #[test] fn test_json_schema_with_doc_comment() { let ty: syn::Type = parse_quote!(String); let attrs: Vec<Attribute> = vec![parse_quote!(#[doc = "A user name."])]; let tokens = type_to_json_schema(&ty, &attrs); let output = render(tokens); assert!(output.contains( "\"description\".to_string(),serde_json::Value::String(\"Ausername.\".to_string())" )); } #[test] fn test_json_schema_fallback_unknown() { let ty: syn::Type = parse_quote!((i32, i32)); let tokens = type_to_json_schema(&ty, &[]); let output = render(tokens); assert!(output .contains("\"type\".to_string(),serde_json::Value::String(\"unknown\".to_string())")); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/tool.rs
crates/rust-mcp-macros/src/tool.rs
pub(crate) mod generator; pub(crate) mod parser;
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/elicit.rs
crates/rust-mcp-macros/src/elicit.rs
pub(crate) mod generator; pub(crate) mod parser;
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/resource/parser.rs
crates/rust-mcp-macros/src/resource/parser.rs
use crate::common::{GenericMcpMacroAttributes, IconDsl}; use syn::{parse::Parse, Error}; pub(crate) const VALID_ROLES: [&str; 2] = ["assistant", "user"]; #[derive(Debug)] pub(crate) struct McpResourceMacroAttributes { pub name: Option<String>, pub description: Option<String>, pub meta: Option<String>, pub title: Option<String>, pub icons: Option<Vec<IconDsl>>, pub mime_type: Option<String>, pub size: Option<i64>, pub uri: Option<String>, pub audience: Option<Vec<String>>, } impl Parse for McpResourceMacroAttributes { fn parse(attributes: syn::parse::ParseStream) -> syn::Result<Self> { let GenericMcpMacroAttributes { name, description, meta, title, icons, mime_type, size, uri, audience, uri_template: _, destructive_hint: _, idempotent_hint: _, open_world_hint: _, read_only_hint: _, execution: _, } = GenericMcpMacroAttributes::parse(attributes)?; let instance = Self { name, description, meta, title, icons, mime_type, size, uri, audience, }; // Validate presence and non-emptiness if instance .name .as_ref() .map(|s| s.trim().is_empty()) .unwrap_or(true) { return Err(Error::new( attributes.span(), "The 'name' attribute is required and must not be empty.", )); } if instance .uri .as_ref() .map(|s| s.trim().is_empty()) .unwrap_or(true) { return Err(Error::new( attributes.span(), "The 'uri' attribute is required and must not be empty.", )); } if instance .audience .as_ref() .map(|s| s.len()) .unwrap_or_default() > VALID_ROLES.len() { return Err(Error::new( attributes.span(), format!("valid audience values are : {}. Is there any duplication in the audience values?", VALID_ROLES.join(" , ")), )); } Ok(instance) } } #[derive(Debug)] pub(crate) struct McpResourceTemplateMacroAttributes { pub name: Option<String>, pub description: Option<String>, pub meta: Option<String>, pub title: Option<String>, pub icons: Option<Vec<IconDsl>>, pub mime_type: Option<String>, pub uri_template: Option<String>, pub audience: Option<Vec<String>>, } impl Parse for McpResourceTemplateMacroAttributes { fn parse(attributes: syn::parse::ParseStream) -> syn::Result<Self> { let GenericMcpMacroAttributes { name, description, meta, title, icons, mime_type, audience, uri_template, uri: _, size: _, destructive_hint: _, idempotent_hint: _, open_world_hint: _, read_only_hint: _, execution: _, } = GenericMcpMacroAttributes::parse(attributes)?; let instance = Self { name, description, meta, title, icons, mime_type, uri_template, audience, }; // Validate presence and non-emptiness if instance .name .as_ref() .map(|s| s.trim().is_empty()) .unwrap_or(true) { return Err(Error::new( attributes.span(), "The 'name' attribute is required and must not be empty.", )); } if instance .uri_template .as_ref() .map(|s| s.trim().is_empty()) .unwrap_or(true) { return Err(Error::new( attributes.span(), "The 'uri_template' attribute is required and must not be empty.", )); } if instance .audience .as_ref() .map(|s| s.len()) .unwrap_or_default() > VALID_ROLES.len() { return Err(Error::new( attributes.span(), format!("valid audience values are : {}. Is there any duplication in the audience values?", VALID_ROLES.join(" , ")), )); } Ok(instance) } } #[cfg(test)] mod tests { use super::*; use syn::parse_str; fn parse_attributes(input: &str) -> syn::Result<McpResourceMacroAttributes> { parse_str(input) } #[test] fn test_minimal_required_attributes() { let attrs = parse_attributes( r#" name = "test-resource", description = "A test resource", uri="ks://crmofaroundc" "#, ) .unwrap(); assert_eq!(attrs.name, Some("test-resource".to_string())); assert_eq!(attrs.description, Some("A test resource".to_string())); assert_eq!(attrs.title, None); assert_eq!(attrs.meta, None); assert!(attrs.icons.is_none()); assert_eq!(attrs.mime_type, None); assert_eq!(attrs.size, None); assert_eq!(attrs.uri.clone(), Some("ks://crmofaroundc".into())); assert_eq!(attrs.audience, None); } #[test] fn test_all_attributes_with_simple_values() { let attrs = parse_attributes( r#" name = "my-file", description = "Important document", title = "My Document", meta = "{\"key\": \"value\", \"num\": 42}", mime_type = "application/pdf", size = 1024, uri = "https://example.com/file.pdf", audience = ["user", "assistant"], icons = [(src = "icon.png", mime_type = "image/png", sizes = ["48x48"])] "#, ) .unwrap(); assert_eq!(attrs.name.as_deref(), Some("my-file")); assert_eq!(attrs.description.as_deref(), Some("Important document")); assert_eq!(attrs.title.as_deref(), Some("My Document")); assert_eq!( attrs.meta.as_deref(), Some("{\"key\": \"value\", \"num\": 42}") ); assert_eq!(attrs.mime_type.as_deref(), Some("application/pdf")); assert_eq!(attrs.size, Some(1024)); assert_eq!(attrs.uri.as_deref(), Some("https://example.com/file.pdf")); assert_eq!( attrs.audience, Some(vec!["user".to_string(), "assistant".to_string()]) ); let icons = attrs.icons.unwrap(); assert_eq!(icons.len(), 1); assert_eq!(icons[0].src.value(), "icon.png"); assert_eq!(icons[0].sizes.as_ref().unwrap(), &vec!["48x48".to_string()]); assert_eq!(icons[0].mime_type, Some("image/png".to_string())); } #[test] fn test_concat_in_string_fields() { let attrs = parse_attributes( r#" name = concat!("prefix-", "resource"), description = concat!("This is ", "a multi-part ", "description"), title = concat!("Title: ", "Document"), uri="ks://crmofaroundc" "#, ) .unwrap(); assert_eq!(attrs.name, Some("prefix-resource".to_string())); assert_eq!( attrs.description, Some("This is a multi-part description".to_string()) ); assert_eq!(attrs.title, Some("Title: Document".to_string())); } #[test] fn test_multiple_icons() { let attrs = parse_attributes( r#" name = "app", uri="ks://crmofaroundc", description = "App with icons", icons = [(src = "icon-192.png", sizes = ["192x192"]), (src = "icon-512.png", mime_type = "image/png", sizes = ["512x512"]), ] "#, ) .unwrap(); let icons = attrs.icons.unwrap(); assert_eq!(icons.len(), 2); assert_eq!(icons[0].src.value(), "icon-192.png"); assert_eq!(icons[1].src.value(), "icon-512.png"); assert_eq!(icons[1].mime_type, Some("image/png".to_string())); } #[test] fn test_missing_name() { let err = parse_attributes( r#" description = "Has description but no name" "#, ) .unwrap_err(); assert_eq!( err.to_string(), "The 'name' attribute is required and must not be empty." ); } #[test] fn test_missing_uri() { let err = parse_attributes( r#" name = "has-name", "#, ) .unwrap_err(); assert_eq!( err.to_string(), "The 'uri' attribute is required and must not be empty." ); } #[test] fn test_invalid_audience() { let err = parse_attributes( r#" name = "has-name", uri="something", audience = ["user", "secretary"], "#, ) .unwrap_err(); assert_eq!( err.to_string(), "valid audience values are : assistant , user" ); } #[test] fn test_duplicated_audience() { let err = parse_attributes( r#" name = "has-name", uri="something", audience = ["user", "assistant", "user"], "#, ) .unwrap_err(); assert!(err .to_string() .contains("Is there any duplication in the audience values?"),); } #[test] fn test_empty_name() { let err = parse_attributes( r#" name = "", description = "valid" "#, ) .unwrap_err(); assert_eq!( err.to_string(), "The 'name' attribute is required and must not be empty." ); } #[test] fn test_invalid_meta_not_json_object() { let err = parse_attributes( r#" name = "test", description = "test", meta = "[1, 2, 3]" "#, ) .unwrap_err(); assert!(err.to_string().contains("Expected a JSON object")); } #[test] fn test_invalid_meta_not_string() { let err = parse_attributes( r#" name = "test", description = "test", meta = { invalid } "#, ) .unwrap_err(); assert!(err .to_string() .contains("Expected a JSON object as a string literal")); } #[test] fn test_invalid_audience_not_array() { let err = parse_attributes( r#" name = "test", description = "test", audience = "not-an-array" "#, ) .unwrap_err(); assert!(err .to_string() .contains("Expected an array of string literals")); } #[test] fn test_audience_with_non_string() { let err = parse_attributes( r#" name = "test", description = "test", audience = ["user", 123] "#, ) .unwrap_err(); assert!(err .to_string() .contains("Expected a string literal in array")); } #[test] fn test_icons_not_array() { let err = parse_attributes( r#" name = "test", description = "test", icons = (src = "icon.png") "#, ) .unwrap_err(); assert!(err .to_string() .contains("Expected an array for the 'icons' attribute")); } #[test] fn test_size_not_integer() { let err = parse_attributes( r#" name = "test", description = "test", size = "not-a-number" "#, ) .unwrap_err(); assert!(err.to_string().contains("Expected a integer literal")); } #[test] fn test_unknown_attribute_is_ignored() { // The parser currently ignores unknown name-value pairs silently let attrs = parse_attributes( r#" name = "test", description = "test", unknown = "should be ignored", uri="ks://crmofaroundc" "#, ) .unwrap(); assert_eq!(attrs.name.as_deref(), Some("test")); // No panic or error on unknown field } #[test] fn test_invalid_concat_usage() { let err = parse_attributes( r#" name = concat!(123), description = "valid" "#, ) .unwrap_err(); assert!(err .to_string() .contains("Only string literals are allowed inside concat!()")); } #[test] fn test_unsupported_expr_in_string_field() { let err = parse_attributes( r#" name = env!("CARGO_PKG_NAME"), description = "valid" "#, ) .unwrap_err(); assert!(err .to_string() .contains("Expected a string literal or concat!(...)")); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/resource/generator.rs
crates/rust-mcp-macros/src/resource/generator.rs
use crate::common::generate_icons; use crate::resource::parser::{McpResourceMacroAttributes, McpResourceTemplateMacroAttributes}; use crate::utils::base_crate; use proc_macro2::TokenStream; use quote::quote; pub struct ResourceTokens { pub base_crate: TokenStream, pub name: TokenStream, pub description: TokenStream, pub meta: TokenStream, pub title: TokenStream, pub icons: TokenStream, pub annotations: TokenStream, pub mime_type: TokenStream, pub size: TokenStream, pub uri: TokenStream, } pub struct ResourceTemplateTokens { pub base_crate: TokenStream, pub name: TokenStream, pub description: TokenStream, pub meta: TokenStream, pub title: TokenStream, pub icons: TokenStream, pub annotations: TokenStream, pub mime_type: TokenStream, pub uri_template: TokenStream, } pub fn generate_resource_tokens(macro_attributes: McpResourceMacroAttributes) -> ResourceTokens { let base_crate = base_crate(); let name = macro_attributes .name .as_ref() .map(|v| quote! {#v.into() }) .expect("'name' is a required attribute!"); let uri = macro_attributes .uri .as_ref() .map(|v| quote! {#v.into() }) .expect("'uri' is a required attribute!"); let size = macro_attributes .size .as_ref() .map_or(quote! { None }, |t| quote! { Some(#t.into()) }); let mime_type = macro_attributes .mime_type .as_ref() .map_or(quote! { None }, |t| quote! { Some(#t.into()) }); let description = macro_attributes .description .as_ref() .map_or(quote! { None }, |t| quote! { Some(#t.into()) }); let title = macro_attributes .title .as_ref() .map_or(quote! { None }, |t| quote! { Some(#t.into()) }); let meta = macro_attributes.meta.as_ref().map_or(quote! { None }, |m| { quote! { Some(serde_json::from_str(#m).expect("Failed to parse meta JSON")) } }); let annotations = generate_resource_annotations(&base_crate, macro_attributes.audience); let icons = generate_icons(&base_crate, &macro_attributes.icons); ResourceTokens { base_crate, meta, title, annotations, icons, name, description, mime_type, size, uri, } } pub fn generate_resource_template_tokens( macro_attributes: McpResourceTemplateMacroAttributes, ) -> ResourceTemplateTokens { let base_crate = base_crate(); let name = macro_attributes .name .as_ref() .map(|v| quote! {#v.into() }) .expect("'name' is a required attribute!"); let uri_template = macro_attributes .uri_template .as_ref() .map(|v| quote! {#v.into() }) .expect("'uri_template' is a required attribute!"); let mime_type = macro_attributes .mime_type .as_ref() .map_or(quote! { None }, |t| quote! { Some(#t.into()) }); let description = macro_attributes .description .as_ref() .map_or(quote! { None }, |t| quote! { Some(#t.into()) }); let title = macro_attributes .title .as_ref() .map_or(quote! { None }, |t| quote! { Some(#t.into()) }); let meta = macro_attributes.meta.as_ref().map_or(quote! { None }, |m| { quote! { Some(serde_json::from_str(#m).expect("Failed to parse meta JSON")) } }); let annotations = generate_resource_annotations(&base_crate, macro_attributes.audience); let icons = generate_icons(&base_crate, &macro_attributes.icons); ResourceTemplateTokens { base_crate, meta, title, annotations, icons, name, description, mime_type, uri_template, } } pub fn generate_resource_annotations( base_crate: &TokenStream, audience: Option<Vec<String>>, ) -> TokenStream { let Some(roles) = audience else { return quote! {None}; }; if roles.is_empty() { return quote! {None}; } let mcp_roles = roles .iter() .map(|r| match r.as_str() { "assistant" => quote! {#base_crate::Role::Assistant}, "user" => quote! {#base_crate::Role::User}, other => panic!("invalid audience role : {other}"), }) .collect::<Vec<_>>(); quote! { Some(#base_crate::Annotations{ audience: vec![#(#mcp_roles),*], last_modified: None, priority: None, }) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/common/icon_dsl.rs
crates/rust-mcp-macros/src/common/icon_dsl.rs
use syn::parenthesized; use syn::parse::ParseStream; use syn::spanned::Spanned; use syn::{parse::Parse, punctuated::Punctuated, Ident, LitStr, Token}; #[derive(Debug)] pub(crate) struct IconDsl { pub(crate) src: LitStr, pub(crate) mime_type: Option<String>, pub(crate) sizes: Option<Vec<String>>, pub(crate) theme: Option<IconThemeDsl>, } #[derive(Debug)] pub(crate) enum IconThemeDsl { Light, Dark, } pub(crate) struct IconField { pub(crate) key: Ident, pub(crate) _eq_token: Token![=], pub(crate) value: syn::Expr, } impl Parse for IconField { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(IconField { key: input.parse()?, _eq_token: input.parse()?, value: input.parse()?, }) } } impl Parse for IconDsl { fn parse(input: ParseStream) -> syn::Result<Self> { let content; parenthesized!(content in input); // parse ( ... ) let fields: Punctuated<IconField, Token![,]> = content.parse_terminated(IconField::parse, Token![,])?; let mut src = None; let mut mime_type = None; let mut sizes = None; let mut theme = None; for field in fields { let key_str = field.key.to_string(); match key_str.as_str() { "src" => { if let syn::Expr::Lit(expr_lit) = field.value { if let syn::Lit::Str(lit) = expr_lit.lit { src = Some(lit); } else { return Err(syn::Error::new( expr_lit.span(), "expected string literal for src", )); } } } "mime_type" => { if let syn::Expr::Lit(expr_lit) = field.value { if let syn::Lit::Str(lit) = expr_lit.lit { mime_type = Some(lit.value()); } else { return Err(syn::Error::new( expr_lit.span(), "expected string literal for mime_type", )); } } } "sizes" => { if let syn::Expr::Array(arr) = field.value { let mut stizes_vec = vec![]; // Validate that every element is a string literal. for elem in &arr.elems { match elem { syn::Expr::Lit(expr_lit) => { if let syn::Lit::Str(lit_str) = &expr_lit.lit { stizes_vec.push(lit_str.value()); } else { return Err(syn::Error::new( expr_lit.span(), "sizes array must contain string literals", )); } } _ => { return Err(syn::Error::new( elem.span(), "sizes array must contain only string literals", )); } } } sizes = Some(stizes_vec); } else { return Err(syn::Error::new( field.value.span(), "expected array expression for sizes", )); } } "theme" => { if let syn::Expr::Lit(expr_lit) = field.value { if let syn::Lit::Str(lit) = expr_lit.lit { theme = Some(match lit.value().as_str() { "light" => IconThemeDsl::Light, "dark" => IconThemeDsl::Dark, _ => { return Err(syn::Error::new( lit.span(), "theme must be \"light\" or \"dark\"", )); } }); } } } _ => { return Err(syn::Error::new( field.key.span(), "unexpected field in icon", )) } } } Ok(IconDsl { src: src.ok_or_else(|| syn::Error::new(input.span(), "icon must have `src`"))?, mime_type, sizes, theme, }) } } impl Parse for IconThemeDsl { fn parse(_input: ParseStream) -> syn::Result<Self> { panic!("IconThemeDsl should be parsed inside IconDsl") } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/common/mod.rs
crates/rust-mcp-macros/src/common/mod.rs
mod generators; mod global_parser; mod icon_dsl; pub(crate) use generators::*; pub(crate) use global_parser::*; pub(crate) use icon_dsl::*; use syn::parse::ParseStream; use syn::Expr; use syn::{parse::Parse, punctuated::Punctuated, Token}; pub struct ExprList { pub exprs: Punctuated<Expr, Token![,]>, } impl Parse for ExprList { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(ExprList { exprs: Punctuated::parse_terminated(input)?, }) } } #[derive(Debug)] pub(crate) enum ExecutionSupportDsl { Forbidden, Optional, Required, }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/common/generators.rs
crates/rust-mcp-macros/src/common/generators.rs
use crate::common::{IconDsl, IconThemeDsl}; use proc_macro2::TokenStream; use quote::quote; pub fn generate_icons(base_crate: &TokenStream, icons: &Option<Vec<IconDsl>>) -> TokenStream { let mut icon_exprs = Vec::new(); if let Some(icons) = &icons { for icon in icons { let src = &icon.src; let mime_type = icon .mime_type .as_ref() .map(|s| quote! { Some(#s.to_string()) }) .unwrap_or(quote! { None }); let theme = icon .theme .as_ref() .map(|t| match t { IconThemeDsl::Light => quote! { Some(#base_crate::IconTheme::Light) }, IconThemeDsl::Dark => quote! { Some(#base_crate::IconTheme::Dark) }, }) .unwrap_or(quote! { None }); let sizes: Vec<_> = icon .sizes .as_ref() .map(|arr| { arr.iter() .map(|elem| { quote! { #elem.to_string() } }) .collect::<Vec<_>>() }) .unwrap_or_default(); let icon_expr = quote! { #base_crate::Icon { src: #src.to_string(), mime_type: #mime_type, sizes: vec![ #(#sizes),* ], theme: #theme, } }; icon_exprs.push(icon_expr); } } if icon_exprs.is_empty() { quote! { ::std::vec::Vec::new() } } else { quote! { vec![ #(#icon_exprs),* ] } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/common/global_parser.rs
crates/rust-mcp-macros/src/common/global_parser.rs
use crate::common::{ExecutionSupportDsl, ExprList, IconDsl}; use quote::ToTokens; use syn::{parse::Parse, punctuated::Punctuated, Error, Expr, ExprLit, Lit, Meta, Token}; const VALID_ROLES: [&str; 2] = ["assistant", "user"]; #[derive(Debug)] pub(crate) struct GenericMcpMacroAttributes { pub name: Option<String>, pub description: Option<String>, pub meta: Option<String>, // Store raw JSON string instead of parsed Map pub title: Option<String>, pub icons: Option<Vec<IconDsl>>, pub mime_type: Option<String>, pub size: Option<i64>, pub uri: Option<String>, pub uri_template: Option<String>, pub audience: Option<Vec<String>>, // tool specific pub destructive_hint: Option<bool>, pub idempotent_hint: Option<bool>, pub open_world_hint: Option<bool>, pub read_only_hint: Option<bool>, pub execution: Option<ExecutionSupportDsl>, } impl Parse for GenericMcpMacroAttributes { fn parse(attributes: syn::parse::ParseStream) -> syn::Result<Self> { let mut instance = Self { name: None, description: None, meta: None, title: None, icons: None, mime_type: None, size: None, uri: None, uri_template: None, audience: None, destructive_hint: None, idempotent_hint: None, open_world_hint: None, read_only_hint: None, execution: None, }; let meta_list: Punctuated<Meta, Token![,]> = Punctuated::parse_terminated(attributes)?; for meta in meta_list { match meta { Meta::NameValue(meta_name_value) => { let ident = meta_name_value.path.get_ident().unwrap(); let ident_str = ident.to_string(); match ident_str.as_str() { // string literal or concat!() "name" | "description" | "title" => { let value = match &meta_name_value.value { Expr::Lit(ExprLit { lit: Lit::Str(lit_str), .. }) => lit_str.value(), Expr::Macro(expr_macro) => { let mac = &expr_macro.mac; if mac.path.is_ident("concat") { let args: ExprList = syn::parse2(mac.tokens.clone())?; let mut result = String::new(); for expr in args.exprs { if let Expr::Lit(ExprLit { lit: Lit::Str(lit_str), .. }) = expr { result.push_str(&lit_str.value()); } else { return Err(Error::new_spanned( expr, "Only string literals are allowed inside concat!()", )); } } result } else { return Err(Error::new_spanned( expr_macro, "Expected a string literal or concat!(...)", )); } } _ => { return Err(Error::new_spanned( &meta_name_value.value, "Expected a string literal or concat!(...)", )); } }; match ident_str.as_str() { "name" => instance.name = Some(value), "description" => instance.description = Some(value), "title" => instance.title = Some(value), _ => {} } } // string literals "mime_type" | "uri" | "uri_template" => { let value = match &meta_name_value.value { Expr::Lit(ExprLit { lit: Lit::Str(lit_str), .. }) => lit_str.value(), _ => { return Err(Error::new_spanned( &meta_name_value.value, "Expected a string literal", )); } }; match ident_str.as_str() { "mime_type" => instance.mime_type = Some(value), "uri" => instance.uri = Some(value), "uri_template" => instance.uri_template = Some(value), _ => {} } } // i64 "size" => { let value = match &meta_name_value.value { Expr::Lit(ExprLit { lit: Lit::Int(lit_int), .. }) => lit_int.base10_parse::<i64>()?, _ => { return Err(Error::new_spanned( &meta_name_value.value, "Expected a integer literal", )); } }; instance.size = Some(value); } "meta" => { let value = match &meta_name_value.value { Expr::Lit(ExprLit { lit: Lit::Str(lit_str), .. }) => lit_str.value(), _ => { return Err(Error::new_spanned( &meta_name_value.value, "Expected a JSON object as a string literal", )); } }; // Validate that the string is a valid JSON object let parsed: serde_json::Value = serde_json::from_str(&value).map_err(|e| { Error::new_spanned( &meta_name_value.value, format!("Expected a valid JSON object: {e}"), ) })?; if !parsed.is_object() { return Err(Error::new_spanned( &meta_name_value.value, "Expected a JSON object", )); } instance.meta = Some(value); } "audience" => { let values = match &meta_name_value.value { Expr::Array(expr_array) => { let mut result = Vec::new(); for elem in &expr_array.elems { match elem { Expr::Lit(ExprLit { lit: Lit::Str(lit_str), .. }) => { if !VALID_ROLES.contains(&lit_str.value().as_str()) { return Err(Error::new_spanned( elem, format!( "valid audience values are : {}", VALID_ROLES.join(" , ") ), )); } result.push(lit_str.value()); } _ => { return Err(Error::new_spanned( elem, "Expected a string literal in array", )); } } } result } _ => { return Err(Error::new_spanned( &meta_name_value.value, "Expected an array of string literals, e.g. [\"system\", \"user\"]", )); } }; instance.audience = Some(values); } "icons" => { // Check if the value is an array (Expr::Array) if let Expr::Array(array_expr) = &meta_name_value.value { let icon_list: Punctuated<IconDsl, Token![,]> = array_expr .elems .iter() .map(|elem| syn::parse2::<IconDsl>(elem.to_token_stream())) .collect::<Result<_, _>>()?; instance.icons = Some(icon_list.into_iter().collect()); } else { return Err(Error::new_spanned( &meta_name_value.value, "Expected an array for the 'icons' attribute", )); } } // for tools annotations "destructive_hint" | "idempotent_hint" | "open_world_hint" | "read_only_hint" => { let value = match &meta_name_value.value { Expr::Lit(ExprLit { lit: Lit::Bool(lit_bool), .. }) => lit_bool.value, _ => { return Err(Error::new_spanned( &meta_name_value.value, "Expected a boolean literal", )); } }; match ident_str.as_str() { "destructive_hint" => instance.destructive_hint = Some(value), "idempotent_hint" => instance.idempotent_hint = Some(value), "open_world_hint" => instance.open_world_hint = Some(value), "read_only_hint" => instance.read_only_hint = Some(value), _ => {} } } other => { eprintln!("other: {:?}", other) } } } Meta::List(meta_list) => { let ident = meta_list.path.get_ident().unwrap(); let ident_str = ident.to_string(); if ident_str == "execution" { let nested = meta_list .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?; let mut task_support = None; for meta in nested { if let Meta::NameValue(nv) = meta { if nv.path.is_ident("task_support") { if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = &nv.value { let value = s.value(); task_support = Some(match value.as_str() { "forbidden" => ExecutionSupportDsl::Forbidden, "optional" => ExecutionSupportDsl::Optional, "required" => ExecutionSupportDsl::Required, _ => return Err(Error::new_spanned(&nv.value, "task_support must be one of: forbidden, optional, required")), }); } } } } instance.execution = task_support; } } _ => {} } } Ok(instance) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/elicit/parser.rs
crates/rust-mcp-macros/src/elicit/parser.rs
use syn::{punctuated::Punctuated, Expr, ExprLit, Lit, LitStr, Meta, Token}; pub struct ElicitArgs { pub message: LitStr, pub mode: ElicitMode, } pub enum ElicitMode { Form, Url { url: LitStr }, } impl syn::parse::Parse for ElicitArgs { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { let mut message = None; let mut mode = ElicitMode::Form; // default let mut url_lit: Option<LitStr> = None; let metas = Punctuated::<Meta, Token![,]>::parse_terminated(input)?; // First pass for meta in &metas { if let Meta::NameValue(nv) = meta { if let Some(ident) = nv.path.get_ident() { if ident == "message" { if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = &nv.value { message = Some(s.clone()); } } else if ident == "url" { if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = &nv.value { url_lit = Some(s.clone()); } } } } } // Second pass: handle `mode = url` or `mode = form` for meta in &metas { if let Meta::NameValue(nv) = meta { if let Some(ident) = nv.path.get_ident() { if ident == "mode" { if let Expr::Path(path) = &nv.value { if let Some(k) = path.path.get_ident() { match k.to_string().as_str() { "url" => { let the_url = url_lit.clone().ok_or_else(|| { syn::Error::new_spanned(nv, "when `mode = url`, you must also provide `url = \"https://...\"`") })?; mode = ElicitMode::Url { url: the_url }; } "form" => { mode = ElicitMode::Form; } _ => { return Err(syn::Error::new_spanned( k, "mode must be `form` or `url`", )) } } } } else { return Err(syn::Error::new_spanned( &nv.value, "mode must be `form` or `url`", )); } } } } } let message = message.unwrap_or_else(|| LitStr::new("", proc_macro2::Span::call_site())); Ok(Self { message, mode }) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/elicit/generator.rs
crates/rust-mcp-macros/src/elicit/generator.rs
use crate::is_option; use crate::is_vec_string; use quote::quote; use quote::ToTokens; use syn::{ punctuated::Punctuated, token::Comma, Expr, ExprLit, Ident, Lit, Meta, PathArguments, Token, Type, }; fn json_field_name(field: &syn::Field) -> String { field .attrs .iter() .filter(|a| a.path().is_ident("serde")) .find_map(|attr| { // Parse everything inside #[serde(...)] let items = attr .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated) .ok()?; for item in items { match item { // Case 1: #[serde(rename = "field_name")] Meta::NameValue(nv) if nv.path.is_ident("rename") => { if let Expr::Lit(ExprLit { lit: Lit::Str(lit_str), .. }) = nv.value { return Some(lit_str.value()); } } // Case 2: #[serde(rename(serialize = "a", deserialize = "b"))] Meta::List(list) if list.path.is_ident("rename") => { let inner_items = list .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated) .ok()?; for inner in inner_items { if let Meta::NameValue(nv) = inner { if nv.path.is_ident("serialize") || nv.path.is_ident("deserialize") { if let Expr::Lit(ExprLit { lit: Lit::Str(lit_str), .. }) = nv.value { return Some(lit_str.value()); } } } } } _ => {} } } None }) .unwrap_or_else(|| field.ident.as_ref().unwrap().to_string()) } // Form implementation generation pub fn generate_from_impl( fields: &Punctuated<syn::Field, Comma>, base: &proc_macro2::TokenStream, ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) { let mut assigns = Vec::new(); let mut idents = Vec::new(); for field in fields { let ident = field.ident.as_ref().unwrap(); let key = json_field_name(field); let ty = &field.ty; idents.push(ident); let block = if is_option(ty) { let inner = get_option_inner(ty); let (expected, pat, conv) = match_type(inner, &key, base); quote! { let #ident = match map.remove(#key) { Some(#pat) => Some(#conv), Some(other) => return Err(RpcError::parse_error().with_message(format!( "Type mismatch for optional field '{}': expected {}, got {:?}", #key, #expected, other ))), None => None, }; } } else { let (expected, pat, conv) = match_type(ty, &key, base); quote! { let #ident = match map.remove(#key) { Some(#pat) => #conv, Some(other) => return Err(RpcError::parse_error().with_message(format!( "Type mismatch for required field '{}': expected {}, got {:?}", #key, #expected, other ))), None => return Err(RpcError::parse_error().with_message(format!("Missing required field '{}'", #key))), }; } }; assigns.push(block); } (quote! { #(#assigns)* }, quote! { Self { #(#idents),* } }) } pub fn get_option_inner(ty: &Type) -> &Type { if let Type::Path(p) = ty { if let Some(seg) = p.path.segments.last() { if seg.ident == "Option" { if let PathArguments::AngleBracketed(ref args) = seg.arguments { if let Some(syn::GenericArgument::Type(inner)) = args.args.first() { return inner; } } } } } panic!("Not Option<T>") } pub fn match_type( ty: &Type, key: &str, base: &proc_macro2::TokenStream, ) -> (String, proc_macro2::TokenStream, proc_macro2::TokenStream) { if is_vec_string(ty) { return ( "string array".into(), // expected quote! { V::StringArray(v) }, quote! { v }, ); }; match ty { Type::Path(p) if p.path.is_ident("String") => ( "string".into(), quote! { V::Primitive(#base::ElicitResultContentPrimitive::String(v)) }, quote! { v.clone() }, ), Type::Path(p) if p.path.is_ident("bool") => ( "bool".into(), quote! { V::Primitive(#base::ElicitResultContentPrimitive::Boolean(v)) }, quote! { v }, ), Type::Path(p) if p.path.is_ident("i32") => ( "i32".into(), quote! { V::Primitive(#base::ElicitResultContentPrimitive::Integer(v)) }, quote! { (v).try_into().map_err(|_| RpcError::parse_error().with_message(format!("i32 overflow in field '{}'", #key)))? }, ), Type::Path(p) if p.path.is_ident("i64") => ( "i64".into(), quote! { V::Primitive(#base::ElicitResultContentPrimitive::Integer(v)) }, quote! { v }, ), _ => panic!("Unsupported type in mcp_elicit: {}", ty.to_token_stream()), } } pub fn generate_form_schema( struct_name: &Ident, base: &proc_macro2::TokenStream, ) -> proc_macro2::TokenStream { quote! { { let json = #struct_name::json_schema(); let properties = json.get("properties") .and_then(|v| v.as_object()) .into_iter() .flatten() .filter_map(|(k, v)| #base::PrimitiveSchemaDefinition::try_from(v.as_object()?).ok().map(|def| (k.clone(), def))) .collect(); let required = json.get("required") .and_then(|v| v.as_array()) .into_iter() .flatten() .filter_map(|v| v.as_str().map(String::from)) .collect(); #base::ElicitFormSchema::new(properties, required, None) } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/tool/parser.rs
crates/rust-mcp-macros/src/tool/parser.rs
use syn::{parse::Parse, Error}; use crate::common::{ExecutionSupportDsl, GenericMcpMacroAttributes, IconDsl}; /// Represents the attributes for the `mcp_tool` procedural macro. /// /// This struct parses and validates the attributes provided to the `mcp_tool` macro. /// The `name` and `description` attributes are required and must not be empty strings. /// /// # Fields /// * `name` - A string representing the tool's name (required). /// * `description` - A string describing the tool (required). /// * `meta` - An optional JSON string for metadata. /// * `title` - An optional string for the tool's title. /// * The following fields are available only with the `2025_03_26` feature and later: /// * `destructive_hint` - Optional boolean for `ToolAnnotations::destructive_hint`. /// * `idempotent_hint` - Optional boolean for `ToolAnnotations::idempotent_hint`. /// * `open_world_hint` - Optional boolean for `ToolAnnotations::open_world_hint`. /// * `read_only_hint` - Optional boolean for `ToolAnnotations::read_only_hint`. /// pub(crate) struct McpToolMacroAttributes { pub name: Option<String>, pub description: Option<String>, pub meta: Option<String>, // Store raw JSON string instead of parsed Map pub title: Option<String>, pub destructive_hint: Option<bool>, pub idempotent_hint: Option<bool>, pub open_world_hint: Option<bool>, pub read_only_hint: Option<bool>, pub execution: Option<ExecutionSupportDsl>, pub icons: Option<Vec<IconDsl>>, } impl Parse for McpToolMacroAttributes { /// Parses the macro attributes from a `ParseStream`. /// /// This implementation extracts `name`, `description`, `meta`, and `title` from the attribute input. /// The `name` and `description` must be provided as string literals and be non-empty. /// The `meta` attribute must be a valid JSON object provided as a string literal, and `title` must be a string literal. /// /// # Errors /// Returns a `syn::Error` if: /// - The `name` attribute is missing or empty. /// - The `description` attribute is missing or empty. /// - The `meta` attribute is provided but is not a valid JSON object. /// - The `title` attribute is provided but is not a string literal. fn parse(attributes: syn::parse::ParseStream) -> syn::Result<Self> { let GenericMcpMacroAttributes { name, description, meta, title, icons, mime_type: _, audience: _, uri_template: _, uri: _, size: _, destructive_hint, idempotent_hint, open_world_hint, read_only_hint, execution, } = GenericMcpMacroAttributes::parse(attributes)?; let instance = Self { name, description, meta, title, destructive_hint, idempotent_hint, open_world_hint, read_only_hint, execution, icons, }; // Validate presence and non-emptiness if instance .name .as_ref() .map(|s| s.trim().is_empty()) .unwrap_or(true) { return Err(Error::new( attributes.span(), "The 'name' attribute is required and must not be empty.", )); } if instance .description .as_ref() .map(|s| s.trim().is_empty()) .unwrap_or(true) { return Err(Error::new( attributes.span(), "The 'description' attribute is required and must not be empty.", )); } Ok(instance) } } #[cfg(test)] mod tests { use super::*; use syn::parse_str; #[test] fn test_valid_macro_attributes() { let input = r#"name = "test_tool", description = "A test tool.", meta = "{\"version\": \"1.0\"}", title = "Test Tool""#; let parsed: McpToolMacroAttributes = parse_str(input).unwrap(); assert_eq!(parsed.name.unwrap(), "test_tool"); assert_eq!(parsed.description.unwrap(), "A test tool."); assert_eq!(parsed.meta.unwrap(), "{\"version\": \"1.0\"}"); assert_eq!(parsed.title.unwrap(), "Test Tool"); } #[test] fn test_missing_name() { let input = r#"description = "Only description""#; let result: Result<McpToolMacroAttributes, Error> = parse_str(input); assert!(result.is_err()); assert_eq!( result.err().unwrap().to_string(), "The 'name' attribute is required and must not be empty." ); } #[test] fn test_missing_description() { let input = r#"name = "OnlyName""#; let result: Result<McpToolMacroAttributes, Error> = parse_str(input); assert!(result.is_err()); assert_eq!( result.err().unwrap().to_string(), "The 'description' attribute is required and must not be empty." ); } #[test] fn test_empty_name_field() { let input = r#"name = "", description = "something""#; let result: Result<McpToolMacroAttributes, Error> = parse_str(input); assert!(result.is_err()); assert_eq!( result.err().unwrap().to_string(), "The 'name' attribute is required and must not be empty." ); } #[test] fn test_empty_description_field() { let input = r#"name = "my-tool", description = """#; let result: Result<McpToolMacroAttributes, Error> = parse_str(input); assert!(result.is_err()); assert_eq!( result.err().unwrap().to_string(), "The 'description' attribute is required and must not be empty." ); } #[test] fn test_invalid_meta() { let input = r#"name = "test_tool", description = "A test tool.", meta = "not_a_json_object""#; let result: Result<McpToolMacroAttributes, Error> = parse_str(input); assert!(result.is_err()); assert!(result .err() .unwrap() .to_string() .contains("Expected a valid JSON object")); } #[test] fn test_non_object_meta() { let input = r#"name = "test_tool", description = "A test tool.", meta = "[1, 2, 3]""#; let result: Result<McpToolMacroAttributes, Error> = parse_str(input); assert!(result.is_err()); assert_eq!(result.err().unwrap().to_string(), "Expected a JSON object"); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/src/tool/generator.rs
crates/rust-mcp-macros/src/tool/generator.rs
use crate::common::{ExecutionSupportDsl, IconThemeDsl}; use crate::utils::base_crate; use crate::McpToolMacroAttributes; use proc_macro2::TokenStream; use quote::quote; pub struct ToolTokens { pub base_crate: TokenStream, pub tool_name: String, pub tool_description: String, pub meta: TokenStream, pub title: TokenStream, pub output_schema: TokenStream, pub annotations: TokenStream, pub execution: TokenStream, pub icons: TokenStream, } pub fn generate_tool_tokens(macro_attributes: McpToolMacroAttributes) -> ToolTokens { // Conditionally select the path for Tool let base_crate = base_crate(); let tool_name = macro_attributes.name.clone().unwrap_or_default(); let tool_description = macro_attributes.description.clone().unwrap_or_default(); let title = macro_attributes.title.as_ref().map_or( quote! { title: None, }, |t| quote! { title: Some(#t.to_string()), }, ); let meta = macro_attributes .meta .as_ref() .map_or(quote! { meta: None, }, |m| { quote! { meta: Some(serde_json::from_str(#m).expect("Failed to parse meta JSON")), } }); //TODO: add support for output_schema let output_schema = quote! { output_schema: None,}; let annotations = generate_annotations(&base_crate, &macro_attributes); let execution = generate_executions(&base_crate, &macro_attributes); let icons = generate_icons(&base_crate, &macro_attributes); ToolTokens { base_crate, tool_name, tool_description, meta, title, output_schema, annotations, execution, icons, } } fn generate_icons( base_crate: &TokenStream, macro_attributes: &McpToolMacroAttributes, ) -> TokenStream { let mut icon_exprs = Vec::new(); if let Some(icons) = &macro_attributes.icons { for icon in icons { let src = &icon.src; let mime_type = icon .mime_type .as_ref() .map(|s| quote! { Some(#s.to_string()) }) .unwrap_or(quote! { None }); let theme = icon .theme .as_ref() .map(|t| match t { IconThemeDsl::Light => quote! { Some(#base_crate::IconTheme::Light) }, IconThemeDsl::Dark => quote! { Some(#base_crate::IconTheme::Dark) }, }) .unwrap_or(quote! { None }); let sizes: Vec<_> = icon .sizes .as_ref() .map(|arr| { arr.iter() .map(|elem| { quote! { #elem.to_string() } }) .collect::<Vec<_>>() }) .unwrap_or_default(); let icon_expr = quote! { #base_crate::Icon { src: #src.to_string(), mime_type: #mime_type, sizes: vec![ #(#sizes),* ], theme: #theme, } }; icon_exprs.push(icon_expr); } } if icon_exprs.is_empty() { quote! { icons: ::std::vec::Vec::new(), } } else { quote! { icons: vec![ #(#icon_exprs),* ], } } } fn generate_executions( base_crate: &TokenStream, macro_attributes: &McpToolMacroAttributes, ) -> TokenStream { if let Some(exec) = macro_attributes.execution.as_ref() { let task_support = match exec { ExecutionSupportDsl::Forbidden => { quote! { Some(#base_crate::ToolExecutionTaskSupport::Forbidden) } } ExecutionSupportDsl::Optional => { quote! { Some(#base_crate::ToolExecutionTaskSupport::Optional) } } ExecutionSupportDsl::Required => { quote! { Some(#base_crate::ToolExecutionTaskSupport::Required) } } }; quote! { execution: Some(#base_crate::ToolExecution { task_support: #task_support, }), } } else { quote! { execution: None, } } } fn generate_annotations( base_crate: &TokenStream, macro_attributes: &McpToolMacroAttributes, ) -> TokenStream { let some_annotations = macro_attributes.destructive_hint.is_some() || macro_attributes.idempotent_hint.is_some() || macro_attributes.open_world_hint.is_some() || macro_attributes.read_only_hint.is_some(); let annotations = if some_annotations { let destructive_hint = macro_attributes .destructive_hint .map_or(quote! {None}, |v| quote! {Some(#v)}); let idempotent_hint = macro_attributes .idempotent_hint .map_or(quote! {None}, |v| quote! {Some(#v)}); let open_world_hint = macro_attributes .open_world_hint .map_or(quote! {None}, |v| quote! {Some(#v)}); let read_only_hint = macro_attributes .read_only_hint .map_or(quote! {None}, |v| quote! {Some(#v)}); quote! { Some(#base_crate::ToolAnnotations { destructive_hint: #destructive_hint, idempotent_hint: #idempotent_hint, open_world_hint: #open_world_hint, read_only_hint: #read_only_hint, title: None, }) } } else { quote! { None } }; quote! { annotations: #annotations, } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/tests/test_mcp_tool.rs
crates/rust-mcp-macros/tests/test_mcp_tool.rs
#[macro_use] extern crate rust_mcp_macros; use common::EditOperation; use rust_mcp_macros::{mcp_elicit, JsonSchema}; use rust_mcp_schema::{ CallToolRequestParams, ElicitRequestFormParams, ElicitRequestParams, ElicitResultContent, ElicitResultContentPrimitive, RpcError, }; use rust_mcp_schema::{IconTheme, Tool, ToolExecutionTaskSupport}; use serde_json::json; #[path = "common/common.rs"] pub mod common; #[test] fn test_rename() { let schema = EditOperation::json_schema(); assert_eq!(schema.len(), 3); assert!(schema.contains_key("properties")); assert!(schema.contains_key("required")); assert!(schema.contains_key("type")); assert_eq!(schema.get("type").unwrap(), "object"); let required: Vec<_> = schema .get("required") .unwrap() .as_array() .unwrap() .iter() .filter_map(|v| v.as_str()) .collect(); assert_eq!(required.len(), 2); assert!(required.contains(&"oldText")); assert!(required.contains(&"newText")); let properties = schema.get("properties").unwrap().as_object().unwrap(); assert_eq!(properties.len(), 2); } #[test] fn test_attributes() { #[derive(JsonSchema)] struct User { /// This is a fallback description from doc comment. pub id: i32, #[json_schema( title = "User Name", description = "The user's full name (overrides doc)", min_length = 1, max_length = 100 )] pub name: String, #[json_schema( title = "User Email", format = "email", min_length = 5, max_length = 255 )] pub email: Option<String>, #[json_schema( title = "Tags", description = "List of tags", min_length = 0, max_length = 10 )] pub tags: Vec<String>, } let schema = User::json_schema(); let expected = json!({ "type": "object", "properties": { "id": { "type": "integer", "description": "This is a fallback description from doc comment." }, "name": { "type": "string", "title": "User Name", "description": "The user's full name (overrides doc)", "minLength": 1, "maxLength": 100 }, "email": { "type": "string", "title": "User Email", "format": "email", "minLength": 5, "maxLength": 255, "nullable": true }, "tags": { "type": "array", "items": { "type": "string", }, "title": "Tags", "description": "List of tags", "minItems": 0, "maxItems": 10 } }, "required": ["id", "name", "tags"] }); // Convert expected_value from serde_json::Value to serde_json::Map<String, serde_json::Value> let expected: serde_json::Map<String, serde_json::Value> = expected.as_object().expect("Expected JSON object").clone(); assert_eq!(schema, expected); } #[test] fn basic_tool_name_and_description() { #[derive(JsonSchema)] #[mcp_tool(name = "echo", description = "Repeats input")] struct Echo { message: String, } let tool = Echo::tool(); assert_eq!(tool.name, "echo"); assert_eq!(tool.description.unwrap(), "Repeats input"); } #[test] fn meta_json_is_parsed_correctly() { #[derive(JsonSchema)] #[mcp_tool( name = "weather", description = "Get weather", meta = r#"{"category": "utility", "version": "1.0"}"# )] struct Weather { location: String, } let tool = Weather::tool(); let meta = tool.meta.as_ref().unwrap(); assert_eq!(meta["category"], "utility"); assert_eq!(meta["version"], "1.0"); } #[test] fn title_is_set() { #[derive(JsonSchema)] #[mcp_tool( name = "calculator", description = "Math tool", title = "Scientific Calculator" )] struct Calc { expression: String, } let tool = Calc::tool(); assert_eq!(tool.title.unwrap(), "Scientific Calculator"); } #[test] fn all_annotations_are_set() { #[derive(JsonSchema)] #[mcp_tool( name = "delete_file", description = "Deletes a file", destructive_hint = true, idempotent_hint = false, open_world_hint = true, read_only_hint = false )] struct DeleteFile { path: String, } let tool = DeleteFile::tool(); let ann = tool.annotations.as_ref().unwrap(); assert!(ann.destructive_hint.unwrap()); assert!(!ann.idempotent_hint.unwrap()); assert!(ann.open_world_hint.unwrap()); assert!(!ann.read_only_hint.unwrap()); } #[test] fn partial_annotations_some_set_some_not() { #[derive(JsonSchema)] #[mcp_tool( name = "get_user", description = "Fetch user", read_only_hint = true, idempotent_hint = true )] struct GetUser { id: String, } let tool = GetUser::tool(); let ann = tool.annotations.as_ref().unwrap(); assert!(ann.read_only_hint.unwrap()); assert!(ann.idempotent_hint.unwrap()); assert!(ann.destructive_hint.is_none()); assert!(ann.open_world_hint.is_none()); } #[test] fn execution_task_support_required() { #[derive(JsonSchema)] #[mcp_tool( name = "long_task", description = "desc", execution(task_support = "required") )] struct LongTask { data: String, } let tool = LongTask::tool(); let exec = tool.execution.as_ref().unwrap(); assert_eq!(exec.task_support, Some(ToolExecutionTaskSupport::Required)); } #[test] fn execution_task_support_optional_and_forbidden() { #[derive(JsonSchema)] #[mcp_tool( name = "quick_op", description = "description", execution(task_support = "optional") )] struct QuickOp { value: i32, } #[derive(JsonSchema)] #[mcp_tool( name = "no_task", description = "description", execution(task_support = "forbidden") )] struct NoTask { flag: bool, } assert_eq!( QuickOp::tool().execution.unwrap().task_support, Some(ToolExecutionTaskSupport::Optional) ); assert_eq!( NoTask::tool().execution.unwrap().task_support, Some(ToolExecutionTaskSupport::Forbidden) ); } // #[derive(JsonSchema)] // #[mcp_tool( // name = "icon_tool", // icons = [ // { src = "/icons/light.png", mime_type = "image/png", sizes = ["48x48", "96x96"], theme = "light" }, // { src = "/icons/dark.svg", mime_type = "image/svg+xml", sizes = ["any"], theme = "dark" }, // { src = "/icons/default.ico", sizes = ["32x32"] } // no mime/theme // ] // )] // struct IconTool { // input: String, // } #[test] fn icons_full_support() { #[derive(JsonSchema)] #[mcp_tool( name = "icon_tool", description="desc", icons = [ (src = "/icons/light.png", mime_type = "image/png", sizes = ["48x48", "96x96"], theme = "light" ), ( src = "/icons/dark.svg", mime_type = "image/svg+xml", sizes = ["any"], theme = "dark" ), ( src = "/icons/default.ico", sizes = ["32x32"] ) ] )] struct IconTool { input: String, } let tool = IconTool::tool(); let icons = &tool.icons; assert_eq!(icons.len(), 3); assert_eq!(icons[0].src, "/icons/light.png"); assert_eq!(icons[0].mime_type.as_deref(), Some("image/png")); assert_eq!(icons[0].sizes, vec!["48x48", "96x96"]); assert_eq!(icons[0].theme, Some(IconTheme::Light)); assert_eq!(icons[1].src, "/icons/dark.svg"); assert_eq!(icons[1].mime_type.as_deref(), Some("image/svg+xml")); assert_eq!(icons[1].sizes, vec!["any"]); assert_eq!(icons[1].theme, Some(IconTheme::Dark)); assert_eq!(icons[2].src, "/icons/default.ico"); assert_eq!(icons[2].mime_type, None); assert_eq!(icons[2].sizes, vec!["32x32"]); assert_eq!(icons[2].theme, None); } #[test] fn icons_empty_when_not_provided() { #[derive(JsonSchema)] #[mcp_tool(name = "no_icons", description = "no_icons")] struct NoIcons { _x: i32, } assert!(NoIcons::tool().icons.is_empty()); } #[test] fn input_schema_has_correct_required_fields() { #[derive(JsonSchema)] #[mcp_tool(name = "user_create", description = "user_create")] struct UserCreate { username: String, email: String, age: Option<i32>, tags: Vec<String>, } let tool: Tool = UserCreate::tool(); let required = tool.input_schema.required; assert!(required.contains(&"username".to_string())); assert!(required.contains(&"email".to_string())); assert!(required.contains(&"tags".to_string())); assert!(!required.contains(&"age".to_string())); } #[test] fn properties_are_correctly_mapped() { #[allow(unused)] #[derive(JsonSchema)] #[mcp_tool(name = "test_props", description = "test_props")] struct TestProps { name: String, count: i32, active: bool, score: Option<f64>, } let tool: Tool = TestProps::tool(); let schema = tool.input_schema; let props = schema.properties.unwrap(); assert!(props.contains_key("name")); assert!(props.contains_key("count")); assert!(props.contains_key("active")); assert!(props.contains_key("score")); let name_prop = props.get("name").unwrap(); assert_eq!(name_prop.get("type").unwrap().as_str().unwrap(), "string"); let active_prop = props.get("active").unwrap(); assert_eq!( active_prop.get("type").unwrap().as_str().unwrap(), "boolean" ); } #[test] fn tool_name_fallback_when_not_provided() { #[derive(JsonSchema)] #[mcp_tool(name = "fallback-name-tool", description = "No name, uses struct name")] struct FallbackNameTool { input: String, } let tool: Tool = FallbackNameTool::tool(); assert_eq!(tool.name, "fallback-name-tool"); // Uses struct name } #[test] fn meta_is_ignored_when_feature_off() { // Should compile even if meta is provided #[derive(JsonSchema)] #[mcp_tool( name = "old_schema", description = "old_schema", meta = r#"{"ignored": true}"# )] struct OldTool { x: i32, } let tool: Tool = OldTool::tool(); assert_eq!(tool.name, "old_schema"); let meta = tool.meta.unwrap(); assert_eq!(meta, json!({"ignored": true}).as_object().unwrap().clone()); } #[test] fn readme_example_tool() { #[mcp_tool( name = "write_file", title = "Write File Tool", description = "Create or overwrite a file with content.", destructive_hint = false, idempotent_hint = false, open_world_hint = false, read_only_hint = false, execution(task_support = "optional"), icons = [ (src = "https:/mywebsite.com/write.png", mime_type = "image/png", sizes = ["128x128"], theme = "light"), (src = "https:/mywebsite.com/write_dark.svg", mime_type = "image/svg+xml", sizes = ["64x64","128x128"], theme = "dark") ], meta = r#"{"key": "value"}"# )] #[derive(JsonSchema)] pub struct WriteFileTool { /// The target file's path. pub path: String, /// The string content to be written to the file pub content: String, } assert_eq!(WriteFileTool::tool_name(), "write_file"); let tool: rust_mcp_schema::Tool = WriteFileTool::tool(); assert_eq!(tool.name, "write_file"); assert_eq!(tool.title.as_ref().unwrap(), "Write File Tool"); assert_eq!( tool.description.unwrap(), "Create or overwrite a file with content." ); let icons = tool.icons; assert_eq!(icons.len(), 2); assert_eq!(icons[0].src, "https:/mywebsite.com/write.png"); assert_eq!(icons[0].mime_type, Some("image/png".into())); assert_eq!(icons[0].theme, Some("light".into())); assert_eq!(icons[0].sizes, vec!["128x128"]); assert_eq!(icons[1].mime_type, Some("image/svg+xml".into())); let meta: &serde_json::Map<String, serde_json::Value> = tool.meta.as_ref().unwrap(); assert_eq!( meta.get("key").unwrap(), &serde_json::Value::String("value".to_string()) ); let schema_properties = tool.input_schema.properties.unwrap(); assert_eq!(schema_properties.len(), 2); assert!(schema_properties.contains_key("path")); assert!(schema_properties.contains_key("content")); // get the `content` prop from schema let content_prop = schema_properties.get("content").unwrap(); // assert the type assert_eq!(content_prop.get("type").unwrap(), "string"); // assert the description assert_eq!( content_prop.get("description").unwrap(), "The string content to be written to the file" ); let request_params = WriteFileTool::request_params().with_arguments( json!({"path":"./test.txt","content":"hello tool"}) .as_object() .unwrap() .clone(), ); assert_eq!(request_params.name, "write_file"); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/tests/test_mcp_resource.rs
crates/rust-mcp-macros/tests/test_mcp_resource.rs
use rust_mcp_macros::{mcp_elicit, mcp_resource, mcp_resource_template, JsonSchema}; use rust_mcp_schema::{Resource, ResourceTemplate, Role}; #[test] fn full_annotated_resource() { #[ mcp_resource( name = "my-resource", uri = "https://example.com/file.pdf", description = "Important document", title = "My Document", meta = "{\"key\": \"value\", \"num\": 42}", mime_type = "application/pdf", size = 1024, audience = ["user", "assistant"], icons = [(src = "icon.png", mime_type = "image/png", sizes = ["48x48"])], ) ] struct MyResource { pub api_key: String, } let resource: Resource = MyResource::resource(); assert_eq!(resource.name, "my-resource"); assert_eq!(resource.uri, "https://example.com/file.pdf"); assert_eq!(resource.description.unwrap(), "Important document"); assert_eq!(resource.title.unwrap(), "My Document"); assert_eq!(resource.mime_type.unwrap(), "application/pdf"); assert_eq!(resource.size.unwrap(), 1024); assert_eq!( resource.annotations.unwrap().audience, vec![Role::User, Role::Assistant] ); assert_eq!(resource.icons.len(), 1); let icon = &resource.icons[0]; assert_eq!(icon.mime_type.as_ref().unwrap(), "image/png"); assert_eq!(icon.src, "icon.png"); assert_eq!(icon.theme, None); assert_eq!(icon.sizes, vec!["48x48"]); } #[test] fn full_annotated_resource_template() { #[ mcp_resource_template( name = "my-resource-template", uri_template = "https://example.com/{path}", description = "Important document", title = "My Document", meta = "{\"key\": \"value\", \"num\": 42}", mime_type = "application/pdf", audience = ["user", "assistant"], icons = [(src = "icon.png", mime_type = "image/png", sizes = ["48x48"])], ) ] struct MyResource { pub api_key: String, } let resource: ResourceTemplate = MyResource::resource_template(); assert_eq!(resource.name, "my-resource-template"); assert_eq!(resource.uri_template, "https://example.com/{path}"); assert_eq!(resource.description.unwrap(), "Important document"); assert_eq!(resource.title.unwrap(), "My Document"); assert_eq!(resource.mime_type.unwrap(), "application/pdf"); assert_eq!( resource.annotations.unwrap().audience, vec![Role::User, Role::Assistant] ); assert_eq!(resource.icons.len(), 1); let icon = &resource.icons[0]; assert_eq!(icon.mime_type.as_ref().unwrap(), "image/png"); assert_eq!(icon.src, "icon.png"); assert_eq!(icon.theme, None); assert_eq!(icon.sizes, vec!["48x48"]); } #[test] fn adhoc() { use rust_mcp_macros::mcp_resource; #[mcp_resource_template( name = "company-logos", description = "The official company logos in different resolutions", title = "Company Logos", mime_type = "image/png", uri_template = "https://example.com/assets/{file_path}", audience = ["user", "assistant"], meta = "{\"license\": \"proprietary\", \"author\": \"Ali Hashemi\"}", icons = [ ( src = "logo-192.png", sizes = ["192x192"], mime_type = "image/png" ), ( src = "logo-512.png", sizes = ["512x512"], mime_type = "image/png" ) ] )] struct CompanyLogo {}; // Usage assert_eq!(CompanyLogo::resource_template_name(), "company-logos"); assert_eq!( CompanyLogo::resource_template_uri(), "https://example.com/assets/{file_path}" ); let resource_template = CompanyLogo::resource_template(); assert_eq!(resource_template.name, "company-logos"); assert_eq!(resource_template.mime_type.unwrap(), "image/png"); assert!(resource_template.icons.len() == 2); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/tests/test_mcp_elicit.rs
crates/rust-mcp-macros/tests/test_mcp_elicit.rs
use rust_mcp_macros::{mcp_elicit, JsonSchema}; use rust_mcp_schema::{ ElicitRequestFormParams, ElicitRequestParams, ElicitRequestUrlParams, ElicitResultContent, RpcError, }; use std::collections::HashMap; #[test] fn test_form_basic_conversion() { // Form elicit basic #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Please enter your name and age", mode=form)] pub struct BasicUser { pub name: String, pub age: Option<i32>, pub expertise: Vec<String>, } assert_eq!(BasicUser::message(), "Please enter your name and age"); let mut content: std::collections::HashMap<String, ElicitResultContent> = HashMap::new(); content.insert( "name".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::String( "Ali".to_string(), )), ); content.insert( "age".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::Integer(21)), ); content.insert( "expertise".to_string(), ElicitResultContent::StringArray(vec!["Rust".to_string(), "C++".to_string()]), ); let user: BasicUser = BasicUser::from_elicit_result_content(Some(content)).unwrap(); assert_eq!(user.name, "Ali"); assert_eq!(user.age, Some(21)); assert_eq!(user.expertise, vec!["Rust".to_string(), "C++".to_string()]); let req = BasicUser::elicit_request_params(); match req { ElicitRequestParams::FormParams(form) => { assert_eq!(form.message, "Please enter your name and age"); assert!(form.requested_schema.properties.contains_key("name")); assert!(form.requested_schema.properties.contains_key("age")); assert_eq!(form.requested_schema.required, vec!["name", "expertise"]); // age is optional assert!(form.meta.is_none()); assert_eq!(form.mode().as_ref().unwrap(), "form"); } _ => panic!("Expected FormParams"), } } #[test] fn test_url_basic_conversion() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Please enter your name and age", mode=url, url="https://github.com/rust-mcp-stack/rust-mcp-sdk")] pub struct InfoFromUrl { pub name: String, pub age: Option<i32>, pub expertise: Vec<String>, } assert_eq!(InfoFromUrl::message(), "Please enter your name and age"); assert_eq!( InfoFromUrl::url(), "https://github.com/rust-mcp-stack/rust-mcp-sdk" ); let mut content: std::collections::HashMap<String, ElicitResultContent> = HashMap::new(); content.insert( "name".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::String( "Ali".to_string(), )), ); content.insert( "age".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::Integer(21)), ); content.insert( "expertise".to_string(), ElicitResultContent::StringArray(vec!["Rust".to_string(), "C++".to_string()]), ); let user: InfoFromUrl = InfoFromUrl::from_elicit_result_content(Some(content)).unwrap(); assert_eq!(user.name, "Ali"); assert_eq!(user.age, Some(21)); assert_eq!(user.expertise, vec!["Rust".to_string(), "C++".to_string()]); let req = InfoFromUrl::elicit_request_params("elicit_id".to_string()); match req { ElicitRequestParams::UrlParams(params) => { assert_eq!(params.message, "Please enter your name and age"); assert!(params.meta.is_none()); assert!(params.task.is_none()); assert_eq!(params.mode(), "url"); } _ => panic!("Expected UrlParams"), } } #[test] fn test_missing_required_field_returns_error() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Enter user info", mode = form)] pub struct RequiredFields { pub name: String, pub email: String, pub tags: Vec<String>, } let mut content = HashMap::new(); content.insert( "name".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::String( "Alice".to_string(), )), ); // Missing 'email' and 'tags' - both required let result = RequiredFields::from_elicit_result_content(Some(content)); assert!(result.is_err()); } #[test] fn test_extra_unknown_field_is_ignored() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Test", mode = form)] pub struct StrictStruct { pub name: String, } let mut content = HashMap::new(); content.insert( "name".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::String( "Bob".to_string(), )), ); content.insert( "unknown_field".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::String( "ignored".to_string(), )), ); let user = StrictStruct::from_elicit_result_content(Some(content)).unwrap(); assert_eq!(user.name, "Bob"); // unknown_field is silently ignored - correct behavior } #[test] fn test_type_mismatch_returns_error() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Bad type", mode = form)] pub struct TypeSensitive { pub age: i32, pub active: bool, } let mut content = HashMap::new(); content.insert( "age".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::String( "not_a_number".to_string(), )), ); content.insert( "active".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::Integer(1)), ); let result = TypeSensitive::from_elicit_result_content(Some(content)); assert!(result.is_err()); } #[test] fn test_empty_string_array_when_missing_optional_vec() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Optional vec", mode = form)] pub struct OptionalVec { pub name: String, pub hobbies: Option<Vec<String>>, } let mut content = HashMap::new(); content.insert( "name".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::String( "Charlie".to_string(), )), ); // hobbies omitted entirely let user = OptionalVec::from_elicit_result_content(Some(content)).unwrap(); assert_eq!(user.name, "Charlie"); assert_eq!(user.hobbies, None); } #[test] fn test_empty_content_map_becomes_default_values() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Defaults", mode = form)] pub struct WithOptionals { pub name: String, pub age: i64, pub is_admin: bool, } let result = WithOptionals::from_elicit_result_content(None); assert!(result.is_err()); let result_empty = WithOptionals::from_elicit_result_content(Some(HashMap::new())); assert!(result_empty.is_err()); } #[test] fn test_boolean_handling() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Bool test", mode = form)] pub struct BoolStruct { pub is_active: bool, pub has_permission: Option<bool>, } let mut content = HashMap::new(); content.insert( "is_active".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::Boolean( true, )), ); content.insert( "has_permission".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::Boolean( false, )), ); let s = BoolStruct::from_elicit_result_content(Some(content)).unwrap(); assert!(s.is_active); assert_eq!(s.has_permission, Some(false)); } #[test] fn test_numeric_types_variations() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Numbers", mode = form)] pub struct Numbers { pub count: i32, pub ratio: Option<i32>, } let mut content = HashMap::new(); content.insert( "count".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::Integer(42)), ); let n = Numbers::from_elicit_result_content(Some(content)).unwrap(); assert_eq!(n.count, 42); assert_eq!(n.ratio, None); } #[test] fn test_url_mode_with_elicitation_id() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Go to this link", mode = url, url = "https://example.com/form/123")] pub struct ExternalForm { pub token: String, } let params = ExternalForm::elicit_url_params("elicit-999".to_string()); assert_eq!(params.elicitation_id, "elicit-999"); assert_eq!(params.message, "Go to this link"); assert_eq!(params.url, "https://example.com/form/123"); let req_params = ExternalForm::elicit_request_params("elicit-999".to_string()); match req_params { ElicitRequestParams::UrlParams(p) => { assert_eq!(p.elicitation_id, "elicit-999"); } _ => panic!("Wrong variant"), } } #[test] fn test_form_and_url_share_same_from_elicit_result_content_logic() { // This ensures both modes reuse the same parsing logic (good!) #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Same parsing", mode = form)] pub struct FormSame { pub x: String, } #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Same parsing", mode = url, url = "http://localhost")] pub struct UrlSame { pub x: String, } let mut content = HashMap::new(); content.insert( "x".to_string(), ElicitResultContent::Primitive(rust_mcp_schema::ElicitResultContentPrimitive::String( "shared".to_string(), )), ); let f = FormSame::from_elicit_result_content(Some(content.clone())).unwrap(); let u = UrlSame::from_elicit_result_content(Some(content)).unwrap(); assert_eq!(f.x, "shared"); assert_eq!(u.x, "shared"); } #[test] fn test_string_array_empty_input_becomes_empty_vec() { #[derive(Debug, Clone, JsonSchema)] #[mcp_elicit(message = "Empty array", mode = form)] pub struct EmptyArray { pub items: Vec<String>, } let mut content = HashMap::new(); content.insert( "items".to_string(), ElicitResultContent::StringArray(vec![]), ); let s = EmptyArray::from_elicit_result_content(Some(content)).unwrap(); assert!(s.items.is_empty()); } #[test] fn readme_example_elicitation() { use rust_mcp_macros::{mcp_elicit, JsonSchema}; use rust_mcp_schema::{ElicitRequestParams, ElicitResultContent}; use std::collections::HashMap; #[mcp_elicit(message = "Please enter your info", mode = form)] #[derive(JsonSchema)] pub struct UserInfo { #[json_schema(title = "Name", min_length = 5, max_length = 100)] pub name: String, #[json_schema(title = "Email", format = "email")] pub email: Option<String>, #[json_schema(title = "Age", minimum = 15, maximum = 125)] pub age: i32, #[json_schema(title = "Tags")] pub tags: Vec<String>, } let params = UserInfo::elicit_request_params(); if let ElicitRequestParams::FormParams(form) = params { assert_eq!(form.message, "Please enter your info"); } // Simulate user input let mut content: HashMap<String, ElicitResultContent> = HashMap::new(); content.insert("name".to_string(), "Alice".into()); content.insert("email".to_string(), "alice@Borderland.com".into()); content.insert("age".to_string(), 25.into()); content.insert("tags".to_string(), vec!["rust", "c++"].into()); let user = UserInfo::from_elicit_result_content(Some(content)).unwrap(); assert_eq!(user.name, "Alice"); assert_eq!(user.age, 25); assert_eq!(user.tags, vec!["rust", "c++"]); assert_eq!(user.email.unwrap(), "alice@Borderland.com"); } #[test] fn readme_example_elicitation_url() { #[mcp_elicit(message = "Complete the form", mode = url, url = "https://example.com/form")] #[derive(JsonSchema)] pub struct UserInfo { #[json_schema(title = "Name", min_length = 5, max_length = 100)] pub name: String, #[json_schema(title = "Email", format = "email")] pub email: Option<String>, #[json_schema(title = "Age", minimum = 15, maximum = 125)] pub age: i32, #[json_schema(title = "Tags")] pub tags: Vec<String>, } let elicit_url = UserInfo::elicit_url_params("elicit_10".into()); assert_eq!(elicit_url.message, "Complete the form"); // Simulate user input let mut content: HashMap<String, ElicitResultContent> = HashMap::new(); content.insert("name".to_string(), "Alice".into()); content.insert("email".to_string(), "alice@Borderland.com".into()); content.insert("age".to_string(), 25.into()); content.insert("tags".to_string(), vec!["rust", "c++"].into()); let user = UserInfo::from_elicit_result_content(Some(content)).unwrap(); assert_eq!(user.name, "Alice"); assert_eq!(user.age, 25); assert_eq!(user.tags, vec!["rust", "c++"]); assert_eq!(user.email.unwrap(), "alice@Borderland.com"); }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-macros/tests/common/common.rs
crates/rust-mcp-macros/tests/common/common.rs
use rust_mcp_macros::JsonSchema; use rust_mcp_schema::RpcError; use std::str::FromStr; #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, JsonSchema)] /// Represents a text replacement operation. pub struct EditOperation { /// Text to search for - must match exactly. #[serde(rename = "oldText")] pub old_text: String, #[serde(rename = "newText")] /// Text to replace the matched text with. pub new_text: String, } #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, JsonSchema)] pub struct EditFileTool { /// The path of the file to edit. pub path: String, /// The list of edit operations to apply. pub edits: Vec<EditOperation>, /// Preview changes using git-style diff format without applying them. #[serde( rename = "dryRun", default, skip_serializing_if = "std::option::Option::is_none" )] pub dry_run: Option<bool>, } #[derive(JsonSchema, Debug)] pub enum Colors { #[json_schema(title = "Green Color")] Green, #[json_schema(title = "Red Color")] Red, } impl FromStr for Colors { type Err = RpcError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().as_str() { "green" => Ok(Colors::Green), "red" => Ok(Colors::Red), _ => Err(RpcError::parse_error().with_message("Invalid color".to_string())), } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/event_store.rs
crates/rust-mcp-transport/src/event_store.rs
mod in_memory_event_store; use crate::{EventId, SessionId, StreamId}; use async_trait::async_trait; pub use in_memory_event_store::*; use thiserror::Error; #[derive(Debug, Clone)] pub struct EventStoreEntry { pub session_id: SessionId, pub stream_id: StreamId, pub messages: Vec<String>, } #[derive(Debug, Error)] #[error("{message}")] pub struct EventStoreError { pub message: String, } impl From<&str> for EventStoreError { fn from(s: &str) -> Self { EventStoreError { message: s.to_string(), } } } impl From<String> for EventStoreError { fn from(s: String) -> Self { EventStoreError { message: s } } } type EventStoreResult<T> = Result<T, EventStoreError>; /// Trait defining the interface for event storage and retrieval, used by the MCP server /// to store and replay events for state reconstruction after client reconnection #[async_trait] pub trait EventStore: Send + Sync { /// Stores a new event in the store and returns the generated event ID. /// For MCP, this stores protocol messages, timestamp is the number of microseconds since UNIX_EPOCH. /// The timestamp helps determine the order in which messages arrived. /// /// # Parameters /// - `session_id`: The session identifier for the event. /// - `stream_id`: The stream identifier within the session. /// - `timestamp`: The u128 timestamp of the event. /// - `message`: The event payload as json string. /// /// # Returns /// - `Ok(EventId)`: The generated ID (format: session_id:stream_id:timestamp) on success. /// - `Err(Self::Error)`: If input is invalid or storage fails. async fn store_event( &self, session_id: SessionId, stream_id: StreamId, timestamp: u128, message: String, ) -> EventStoreResult<EventId>; /// Removes all events associated with a given session ID. /// Used to clean up all events for a session when it is no longer needed (e.g., session ended). /// /// # Parameters /// - `session_id`: The session ID whose events should be removed. /// async fn remove_by_session_id(&self, session_id: SessionId) -> EventStoreResult<()>; /// Removes all events for a specific stream within a session. /// Useful for cleaning up a specific stream without affecting others. /// /// # Parameters /// - `session_id`: The session ID containing the stream. /// - `stream_id`: The stream ID whose events should be removed. /// /// # Returns /// - `Ok(())`: On successful deletion. /// - `Err(Self::Error)`: If deletion fails. async fn remove_stream_in_session( &self, session_id: SessionId, stream_id: StreamId, ) -> EventStoreResult<()>; /// Clears all events from the store. /// Used for resetting the store. /// async fn clear(&self) -> EventStoreResult<()>; /// Retrieves events after a given event ID for a session and stream. /// Critical for MCP server to replay events after a client reconnects, starting from the last known event. /// Events are returned in chronological order (ascending timestamp) to reconstruct state. /// /// # Parameters /// - `last_event_id`: The event ID to fetch events after. /// /// # Returns /// - `Some(Some(EventStoreEntry))`: Events after the specified ID, if any. /// - `None`: If no events exist after it OR the event ID is invalid. async fn events_after( &self, last_event_id: EventId, ) -> EventStoreResult<Option<EventStoreEntry>>; /// Prunes excess events to control storage usage. /// Implementations may apply custom logic, such as limiting /// the number of events per session or removing events older than a certain timestamp. /// Default implementation logs a warning if not overridden by the store. /// /// # Parameters /// - `session_id`: Optional session ID to prune a specific session; if None, prunes all sessions. async fn prune_excess_events(&self, _session_id: Option<SessionId>) -> EventStoreResult<()> { tracing::warn!("prune_excess_events() is not implemented for the event store."); Ok(()) } /// Counts the total number of events in the store. /// /// # Returns /// - The number of events across all sessions and streams. async fn count(&self) -> EventStoreResult<usize>; }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/lib.rs
crates/rust-mcp-transport/src/lib.rs
// Copyright (c) 2025 mcp-rust-stack // Licensed under the MIT License. See LICENSE file for details. // Modifications to this file must be documented with a description of the changes made. #[cfg(feature = "sse")] mod client_sse; #[cfg(feature = "streamable-http")] mod client_streamable_http; mod constants; pub mod error; pub mod event_store; mod mcp_stream; mod message_dispatcher; mod schema; #[cfg(any(feature = "sse", feature = "streamable-http"))] mod sse; #[cfg(feature = "stdio")] mod stdio; mod transport; mod utils; #[cfg(feature = "sse")] pub use client_sse::*; #[cfg(feature = "streamable-http")] pub use client_streamable_http::*; pub use constants::*; pub use message_dispatcher::*; #[cfg(any(feature = "sse", feature = "streamable-http"))] pub use sse::*; #[cfg(feature = "stdio")] pub use stdio::*; pub use transport::*; #[cfg(any(feature = "sse", feature = "streamable-http"))] pub use utils::SseEvent; // Type alias for session identifier, represented as a String pub type SessionId = String; // Type alias for stream identifier (that will be used at the transport scope), represented as a String pub type StreamId = String; // Type alias for mcp task identifier, represented as a String pub type TaskId = String; // Type alias for event (MCP message) identifier, represented as a String pub type EventId = String;
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/stdio.rs
crates/rust-mcp-transport/src/stdio.rs
use crate::schema::schema_utils::{ ClientMessage, ClientMessages, MessageFromClient, MessageFromServer, SdkError, ServerMessage, ServerMessages, }; use crate::schema::RequestId; use async_trait::async_trait; use serde::de::DeserializeOwned; use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; use tokio::process::Command; use tokio::sync::oneshot::Sender; use tokio::sync::{oneshot, Mutex}; use tokio::task::JoinHandle; use crate::error::{TransportError, TransportResult}; use crate::mcp_stream::MCPStream; use crate::message_dispatcher::MessageDispatcher; use crate::transport::Transport; use crate::utils::CancellationTokenSource; use crate::{IoStream, McpDispatch, TransportDispatcher, TransportOptions}; /// Implements a standard I/O transport for MCP communication. /// /// This module provides the `StdioTransport` struct, which serves as a transport layer for the /// Model Context Protocol (MCP) using standard input/output (stdio). It supports both client-side /// and server-side communication by optionally launching a subprocess or using the current /// process's stdio streams. The transport handles message streaming, dispatching, and shutdown /// operations, integrating with the MCP runtime ecosystem. pub struct StdioTransport<R> where R: Clone + Send + Sync + DeserializeOwned + 'static, { command: Option<String>, args: Option<Vec<String>>, env: Option<HashMap<String, String>>, options: TransportOptions, shutdown_source: tokio::sync::RwLock<Option<CancellationTokenSource>>, is_shut_down: Mutex<bool>, message_sender: Arc<tokio::sync::RwLock<Option<MessageDispatcher<R>>>>, error_stream: tokio::sync::RwLock<Option<IoStream>>, pending_requests: Arc<Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<R>>>>, } impl<R> StdioTransport<R> where R: Clone + Send + Sync + DeserializeOwned + 'static, { /// Creates a new `StdioTransport` instance for MCP Server. /// /// This constructor configures the transport to use the current process's stdio streams, /// /// # Arguments /// * `options` - Configuration options for the transport, including timeout settings. /// /// # Returns /// A `TransportResult` containing the initialized `StdioTransport` instance. /// /// # Errors /// Currently, this method does not fail, but it returns a `TransportResult` for API consistency. pub fn new(options: TransportOptions) -> TransportResult<Self> { Ok(Self { // when transport is used for MCP Server, we do not need a command args: None, command: None, env: None, options, shutdown_source: tokio::sync::RwLock::new(None), is_shut_down: Mutex::new(false), message_sender: Arc::new(tokio::sync::RwLock::new(None)), error_stream: tokio::sync::RwLock::new(None), pending_requests: Arc::new(Mutex::new(HashMap::new())), }) } /// Creates a new `StdioTransport` instance with a subprocess for MCP Client use. /// /// This constructor configures the transport to launch a MCP Server with a specified command /// arguments and optional environment variables /// /// # Arguments /// * `command` - The command to execute (e.g., "rust-mcp-filesystem"). /// * `args` - Arguments to pass to the command. (e.g., "~/Documents"). /// * `env` - Optional environment variables for the subprocess. /// * `options` - Configuration options for the transport, including timeout settings. /// /// # Returns /// A `TransportResult` containing the initialized `StdioTransport` instance, ready to launch /// the MCP server on `start`. pub fn create_with_server_launch<C: Into<String>>( command: C, args: Vec<String>, env: Option<HashMap<String, String>>, options: TransportOptions, ) -> TransportResult<Self> { Ok(Self { // when transport is used for MCP Server, we do not need a command args: Some(args), command: Some(command.into()), env, options, shutdown_source: tokio::sync::RwLock::new(None), is_shut_down: Mutex::new(false), message_sender: Arc::new(tokio::sync::RwLock::new(None)), error_stream: tokio::sync::RwLock::new(None), pending_requests: Arc::new(Mutex::new(HashMap::new())), }) } /// Retrieves the command and arguments for launching the subprocess. /// /// Adjusts the command based on the platform: on Windows, wraps it with `cmd.exe /c`. /// /// # Returns /// A tuple of the command string and its arguments. fn launch_commands(&self) -> (String, Vec<std::string::String>) { #[cfg(windows)] { let command = "cmd.exe".to_string(); let mut command_args = vec!["/c".to_string(), self.command.clone().unwrap_or_default()]; command_args.extend(self.args.clone().unwrap_or_default()); (command, command_args) } #[cfg(unix)] { let command = self.command.clone().unwrap_or_default(); let command_args = self.args.clone().unwrap_or_default(); (command, command_args) } } pub(crate) async fn set_message_sender(&self, sender: MessageDispatcher<R>) { let mut lock = self.message_sender.write().await; *lock = Some(sender); } pub(crate) async fn set_error_stream(&self, error_stream: IoStream) { let mut lock = self.error_stream.write().await; *lock = Some(error_stream); } } #[async_trait] impl<R, S, M, OR, OM> Transport<R, S, M, OR, OM> for StdioTransport<M> where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, S: Clone + Send + Sync + serde::Serialize + 'static, M: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, OR: Clone + Send + Sync + serde::Serialize + 'static, OM: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { /// Starts the transport, initializing streams and the message dispatcher. /// /// If configured with a command (MCP Client), launches the MCP server and connects its stdio streams. /// Otherwise, uses the current process's stdio for server-side communication. /// /// # Returns /// A `TransportResult` containing: /// - A pinned stream of incoming messages. /// - A `MessageDispatcher<R>` for sending messages. /// - An `IoStream` for stderr (readable) or stdout (writable) depending on the mode. /// /// # Errors /// Returns a `TransportError` if the subprocess fails to spawn or stdio streams cannot be accessed. async fn start(&self) -> TransportResult<tokio_stream::wrappers::ReceiverStream<R>> where MessageDispatcher<M>: McpDispatch<R, OR, M, OM>, { // Create CancellationTokenSource and token let (cancellation_source, cancellation_token) = CancellationTokenSource::new(); let mut lock = self.shutdown_source.write().await; *lock = Some(cancellation_source); if self.command.is_some() { let (command_name, command_args) = self.launch_commands(); let mut command = Command::new(command_name); command .envs(self.env.as_ref().unwrap_or(&HashMap::new())) .args(&command_args) .stdout(std::process::Stdio::piped()) .stdin(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .kill_on_drop(true); #[cfg(windows)] command.creation_flags(0x08000000); // https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags #[cfg(unix)] command.process_group(0); let mut process = command.spawn().map_err(TransportError::Io)?; let stdin = process .stdin .take() .ok_or_else(|| TransportError::Internal("Unable to retrieve stdin.".into()))?; let stdout = process .stdout .take() .ok_or_else(|| TransportError::Internal("Unable to retrieve stdout.".into()))?; let stderr = process .stderr .take() .ok_or_else(|| TransportError::Internal("Unable to retrieve stderr.".into()))?; let pending_requests_clone = self.pending_requests.clone(); tokio::spawn(async move { let _ = process.wait().await; // clean up pending requests to cancel waiting tasks let mut pending_requests = pending_requests_clone.lock().await; pending_requests.clear(); }); let (stream, sender, error_stream) = MCPStream::create( Box::pin(stdout), Mutex::new(Box::pin(stdin)), IoStream::Readable(Box::pin(stderr)), self.pending_requests.clone(), self.options.timeout, cancellation_token, ); self.set_message_sender(sender).await; self.set_error_stream(error_stream).await; Ok(stream) } else { let (stream, sender, error_stream) = MCPStream::create( Box::pin(tokio::io::stdin()), Mutex::new(Box::pin(tokio::io::stdout())), IoStream::Writable(Box::pin(tokio::io::stderr())), self.pending_requests.clone(), self.options.timeout, cancellation_token, ); self.set_message_sender(sender).await; self.set_error_stream(error_stream).await; Ok(stream) } } async fn pending_request_tx(&self, request_id: &RequestId) -> Option<Sender<M>> { let mut pending_requests = self.pending_requests.lock().await; pending_requests.remove(request_id) } /// Checks if the transport has been shut down. async fn is_shut_down(&self) -> bool { let result = self.is_shut_down.lock().await; *result } fn message_sender(&self) -> Arc<tokio::sync::RwLock<Option<MessageDispatcher<M>>>> { self.message_sender.clone() as _ } fn error_stream(&self) -> &tokio::sync::RwLock<Option<IoStream>> { &self.error_stream as _ } async fn consume_string_payload(&self, _payload: &str) -> TransportResult<()> { Err(TransportError::Internal( "Invalid invocation of consume_string_payload() function in StdioTransport".to_string(), )) } async fn keep_alive( &self, _interval: Duration, _disconnect_tx: oneshot::Sender<()>, ) -> TransportResult<JoinHandle<()>> { Err(TransportError::Internal( "Invalid invocation of keep_alive() function for StdioTransport".to_string(), )) } // Shuts down the transport, terminating any subprocess and signaling closure. /// /// Sends a shutdown signal via the watch channel and kills the subprocess if present. /// /// # Returns /// A `TransportResult` indicating success or failure. /// /// # Errors /// Returns a `TransportError` if the shutdown signal fails or the process cannot be killed. async fn shut_down(&self) -> TransportResult<()> { // Trigger cancellation let mut cancellation_lock = self.shutdown_source.write().await; if let Some(source) = cancellation_lock.as_ref() { source.cancel()?; } *cancellation_lock = None; // Clear cancellation_source // Mark as shut down let mut is_shut_down_lock = self.is_shut_down.lock().await; *is_shut_down_lock = true; Ok(()) } } #[async_trait] impl McpDispatch<ClientMessages, ServerMessages, ClientMessage, ServerMessage> for StdioTransport<ClientMessage> { async fn send_message( &self, message: ServerMessages, request_timeout: Option<Duration>, ) -> TransportResult<Option<ClientMessages>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_message(message, request_timeout).await } async fn send( &self, message: ServerMessage, request_timeout: Option<Duration>, ) -> TransportResult<Option<ClientMessage>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send(message, request_timeout).await } async fn send_batch( &self, message: Vec<ServerMessage>, request_timeout: Option<Duration>, ) -> TransportResult<Option<Vec<ClientMessage>>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_batch(message, request_timeout).await } async fn write_str(&self, payload: &str, skip_store: bool) -> TransportResult<()> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.write_str(payload, skip_store).await } } impl TransportDispatcher< ClientMessages, MessageFromServer, ClientMessage, ServerMessages, ServerMessage, > for StdioTransport<ClientMessage> { } #[async_trait] impl McpDispatch<ServerMessages, ClientMessages, ServerMessage, ClientMessage> for StdioTransport<ServerMessage> { async fn send_message( &self, message: ClientMessages, request_timeout: Option<Duration>, ) -> TransportResult<Option<ServerMessages>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_message(message, request_timeout).await } async fn send( &self, message: ClientMessage, request_timeout: Option<Duration>, ) -> TransportResult<Option<ServerMessage>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send(message, request_timeout).await } async fn send_batch( &self, message: Vec<ClientMessage>, request_timeout: Option<Duration>, ) -> TransportResult<Option<Vec<ServerMessage>>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_batch(message, request_timeout).await } async fn write_str(&self, payload: &str, skip_store: bool) -> TransportResult<()> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.write_str(payload, skip_store).await } } impl TransportDispatcher< ServerMessages, MessageFromClient, ServerMessage, ClientMessages, ClientMessage, > for StdioTransport<ServerMessage> { }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/client_sse.rs
crates/rust-mcp-transport/src/client_sse.rs
use crate::error::{TransportError, TransportResult}; use crate::mcp_stream::MCPStream; use crate::message_dispatcher::MessageDispatcher; use crate::transport::Transport; use crate::utils::{ extract_origin, http_post, CancellationTokenSource, ReadableChannel, SseStream, WritableChannel, }; use crate::{IoStream, McpDispatch, TransportDispatcher, TransportOptions}; use async_trait::async_trait; use bytes::Bytes; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use reqwest::Client; use tokio::sync::oneshot::Sender; use tokio::task::JoinHandle; use crate::schema::{ schema_utils::{ ClientMessage, ClientMessages, McpMessage, MessageFromClient, SdkError, ServerMessage, ServerMessages, }, RequestId, }; use std::cmp::Ordering; use std::collections::HashMap; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; use tokio::io::{BufReader, BufWriter}; use tokio::sync::{mpsc, oneshot, Mutex}; const DEFAULT_CHANNEL_CAPACITY: usize = 64; const DEFAULT_MAX_RETRY: usize = 5; const DEFAULT_RETRY_TIME_SECONDS: u64 = 1; const SHUTDOWN_TIMEOUT_SECONDS: u64 = 5; /// Configuration options for the Client SSE Transport /// /// Defines settings for request timeouts, retry behavior, and custom HTTP headers. pub struct ClientSseTransportOptions { pub request_timeout: Duration, pub retry_delay: Option<Duration>, pub max_retries: Option<usize>, pub custom_headers: Option<HashMap<String, String>>, } /// Provides default values for ClientSseTransportOptions impl Default for ClientSseTransportOptions { fn default() -> Self { Self { request_timeout: TransportOptions::default().timeout, retry_delay: None, max_retries: None, custom_headers: None, } } } /// Client-side Server-Sent Events (SSE) transport implementation /// /// Manages SSE connections, HTTP POST requests, and message streaming for client-server communication. pub struct ClientSseTransport<R> where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { /// Optional cancellation token source for shutting down the transport shutdown_source: tokio::sync::RwLock<Option<CancellationTokenSource>>, /// Flag indicating if the transport is shut down is_shut_down: Mutex<bool>, /// Timeout duration for MCP messages request_timeout: Duration, /// HTTP client for making requests client: Client, /// URL for the SSE endpoint sse_url: String, /// Base URL extracted from the server URL base_url: String, /// Delay between retry attempts retry_delay: Duration, /// Maximum number of retry attempts max_retries: usize, /// Optional custom HTTP headers custom_headers: Option<HeaderMap>, sse_task: tokio::sync::RwLock<Option<tokio::task::JoinHandle<()>>>, post_task: tokio::sync::RwLock<Option<tokio::task::JoinHandle<()>>>, message_sender: Arc<tokio::sync::RwLock<Option<MessageDispatcher<R>>>>, error_stream: tokio::sync::RwLock<Option<IoStream>>, pending_requests: Arc<Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<R>>>>, } impl<R> ClientSseTransport<R> where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { /// Creates a new ClientSseTransport instance /// /// Initializes the transport with the provided server URL and options. /// /// # Arguments /// * `server_url` - The URL of the SSE server /// * `options` - Configuration options for the transport /// /// # Returns /// * `TransportResult<Self>` - The initialized transport or an error pub fn new(server_url: &str, options: ClientSseTransportOptions) -> TransportResult<Self> { let client = Client::new(); let base_url = match extract_origin(server_url) { Some(url) => url, None => { let message = format!("Failed to extract origin from server URL: {server_url}"); tracing::error!(message); return Err(TransportError::Configuration { message }); } }; let headers = match &options.custom_headers { Some(h) => Some(Self::validate_headers(h)?), None => None, }; Ok(Self { client, base_url, sse_url: server_url.to_string(), max_retries: options.max_retries.unwrap_or(DEFAULT_MAX_RETRY), retry_delay: options .retry_delay .unwrap_or(Duration::from_secs(DEFAULT_RETRY_TIME_SECONDS)), shutdown_source: tokio::sync::RwLock::new(None), is_shut_down: Mutex::new(false), request_timeout: options.request_timeout, custom_headers: headers, sse_task: tokio::sync::RwLock::new(None), post_task: tokio::sync::RwLock::new(None), message_sender: Arc::new(tokio::sync::RwLock::new(None)), error_stream: tokio::sync::RwLock::new(None), pending_requests: Arc::new(Mutex::new(HashMap::new())), }) } /// Validates and converts a HashMap of headers into a HeaderMap /// /// # Arguments /// * `headers` - The HashMap of header names and values /// /// # Returns /// * `TransportResult<HeaderMap>` - The validated HeaderMap or an error fn validate_headers(headers: &HashMap<String, String>) -> TransportResult<HeaderMap> { let mut header_map = HeaderMap::new(); for (key, value) in headers { let header_name = key.parse::<HeaderName>() .map_err(|e| TransportError::Configuration { message: format!("Invalid header name: {e}"), })?; let header_value = HeaderValue::from_str(value).map_err(|e| TransportError::Configuration { message: format!("Invalid header value: {e}"), })?; header_map.insert(header_name, header_value); } Ok(header_map) } /// Validates the message endpoint URL /// /// Ensures the endpoint is either relative to the base URL or matches the base URL's origin. /// /// # Arguments /// * `endpoint` - The endpoint URL to validate /// /// # Returns /// * `TransportResult<String>` - The validated endpoint URL or an error pub fn validate_message_endpoint(&self, endpoint: String) -> TransportResult<String> { if endpoint.starts_with("/") { return Ok(format!("{}{}", self.base_url, endpoint)); } if let Some(endpoint_origin) = extract_origin(&endpoint) { if endpoint_origin.cmp(&self.base_url) != Ordering::Equal { return Err(TransportError::Configuration { message: format!( "Endpoint origin does not match connection origin. expected: {} , received: {}", self.base_url, endpoint_origin ), }); } return Ok(endpoint); } Ok(endpoint) } pub(crate) async fn set_message_sender(&self, sender: MessageDispatcher<R>) { let mut lock = self.message_sender.write().await; *lock = Some(sender); } pub(crate) async fn set_error_stream( &self, error_stream: Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>>, ) { let mut lock = self.error_stream.write().await; *lock = Some(IoStream::Readable(error_stream)); } } #[async_trait] impl<R, S, M, OR, OM> Transport<R, S, M, OR, OM> for ClientSseTransport<M> where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, S: McpMessage + Clone + Send + Sync + serde::Serialize + 'static, M: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, OR: Clone + Send + Sync + serde::Serialize + 'static, OM: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { /// Starts the transport, initializing SSE and POST tasks /// /// Sets up the SSE stream, POST request handler, and message streams for communication. /// /// # Returns /// * `TransportResult<(Pin<Box<dyn Stream<Item = R> + Send>>, MessageDispatcher<R>, IoStream)>` /// - The message stream, dispatcher, and error stream async fn start(&self) -> TransportResult<tokio_stream::wrappers::ReceiverStream<R>> where MessageDispatcher<M>: McpDispatch<R, OR, M, OM>, { // Create CancellationTokenSource and token let (cancellation_source, cancellation_token) = CancellationTokenSource::new(); let mut lock = self.shutdown_source.write().await; *lock = Some(cancellation_source); let (write_tx, mut write_rx) = mpsc::channel::<Bytes>(DEFAULT_CHANNEL_CAPACITY); let (read_tx, read_rx) = mpsc::channel::<Bytes>(DEFAULT_CHANNEL_CAPACITY); // Create oneshot channel for signaling SSE endpoint event message let (endpoint_event_tx, endpoint_event_rx) = oneshot::channel::<Option<String>>(); let endpoint_event_tx = Some(endpoint_event_tx); let sse_client = self.client.clone(); let sse_url = self.sse_url.clone(); let max_retries = self.max_retries; let retry_delay = self.retry_delay; let custom_headers = self.custom_headers.clone(); let read_stream = SseStream { sse_client, sse_url, max_retries, retry_delay, read_tx, }; // Spawn task to handle SSE stream with reconnection let cancellation_token_sse = cancellation_token.clone(); let sse_task_handle = tokio::spawn(async move { read_stream .run(endpoint_event_tx, cancellation_token_sse, &custom_headers) .await; }); let mut sse_task_lock = self.sse_task.write().await; *sse_task_lock = Some(sse_task_handle); // Await the first SSE message, expected to receive messages endpoint from he server let err = || std::io::Error::other("Failed to receive 'messages' endpoint from the server."); let post_url = endpoint_event_rx .await .map_err(|_| err())? .ok_or_else(err)?; let post_url = self.validate_message_endpoint(post_url)?; let client_clone = self.client.clone(); let custom_headers = self.custom_headers.clone(); let cancellation_token_post = cancellation_token.clone(); // Spawn task to handle POST requests from writable stream let post_task_handle = tokio::spawn(async move { loop { tokio::select! { _ = cancellation_token_post.cancelled() => { break; }, data = write_rx.recv() => { match data{ Some(data) => { // trim the trailing \n before making a request let body = String::from_utf8_lossy(&data).trim().to_string(); if let Err(e) = http_post(&client_clone, &post_url, body,None, custom_headers.as_ref()).await { tracing::error!("Failed to POST message: {e}"); } }, None => break, // Exit if channel is closed } } } } }); let mut post_task_lock = self.post_task.write().await; *post_task_lock = Some(post_task_handle); // Create writable stream let writable: Mutex<Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>> = Mutex::new(Box::pin(BufWriter::new(WritableChannel { write_tx }))); // Create readable stream let readable: Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>> = Box::pin(BufReader::new(ReadableChannel { read_rx, buffer: Bytes::new(), })); let (stream, sender, error_stream) = MCPStream::create( readable, writable, IoStream::Writable(Box::pin(tokio::io::stderr())), self.pending_requests.clone(), self.request_timeout, cancellation_token, ); self.set_message_sender(sender).await; if let IoStream::Readable(error_stream) = error_stream { self.set_error_stream(error_stream).await; } Ok(stream) } fn message_sender(&self) -> Arc<tokio::sync::RwLock<Option<MessageDispatcher<M>>>> { self.message_sender.clone() as _ } fn error_stream(&self) -> &tokio::sync::RwLock<Option<IoStream>> { &self.error_stream as _ } async fn consume_string_payload(&self, _payload: &str) -> TransportResult<()> { Err(TransportError::Internal( "Invalid invocation of consume_string_payload() function for ClientSseTransport" .to_string(), )) } async fn keep_alive( &self, _: Duration, _: oneshot::Sender<()>, ) -> TransportResult<JoinHandle<()>> { Err(TransportError::Internal( "Invalid invocation of keep_alive() function for ClientSseTransport".to_string(), )) } /// Checks if the transport has been shut down /// /// # Returns /// * `bool` - True if the transport is shut down, false otherwise async fn is_shut_down(&self) -> bool { let result = self.is_shut_down.lock().await; *result } // Shuts down the transport, terminating any subprocess and signaling closure. /// /// Sends a shutdown signal via the watch channel and kills the subprocess if present. /// /// # Returns /// A `TransportResult` indicating success or failure. /// /// # Errors /// Returns a `TransportError` if the shutdown signal fails or the process cannot be killed. async fn shut_down(&self) -> TransportResult<()> { // Trigger cancellation let mut cancellation_lock = self.shutdown_source.write().await; if let Some(source) = cancellation_lock.as_ref() { source.cancel()?; } *cancellation_lock = None; // Clear cancellation_source // Mark as shut down let mut is_shut_down_lock = self.is_shut_down.lock().await; *is_shut_down_lock = true; // Get task handles let sse_task = self.sse_task.write().await.take(); let post_task = self.post_task.write().await.take(); // Wait for tasks to complete with a timeout let timeout = Duration::from_secs(SHUTDOWN_TIMEOUT_SECONDS); let shutdown_future = async { if let Some(post_handle) = post_task { let _ = post_handle.await; } if let Some(sse_handle) = sse_task { let _ = sse_handle.await; } Ok::<(), TransportError>(()) }; tokio::select! { result = shutdown_future => { result // result of task completion } _ = tokio::time::sleep(timeout) => { tracing::warn!("Shutdown timed out after {:?}", timeout); Err(TransportError::ShutdownTimeout) } } } async fn pending_request_tx(&self, request_id: &RequestId) -> Option<Sender<M>> { let mut pending_requests = self.pending_requests.lock().await; pending_requests.remove(request_id) } } #[async_trait] impl McpDispatch<ServerMessages, ClientMessages, ServerMessage, ClientMessage> for ClientSseTransport<ServerMessage> { async fn send_message( &self, message: ClientMessages, request_timeout: Option<Duration>, ) -> TransportResult<Option<ServerMessages>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_message(message, request_timeout).await } async fn send( &self, message: ClientMessage, request_timeout: Option<Duration>, ) -> TransportResult<Option<ServerMessage>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send(message, request_timeout).await } async fn send_batch( &self, message: Vec<ClientMessage>, request_timeout: Option<Duration>, ) -> TransportResult<Option<Vec<ServerMessage>>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_batch(message, request_timeout).await } async fn write_str(&self, payload: &str, skip_store: bool) -> TransportResult<()> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.write_str(payload, skip_store).await } } impl TransportDispatcher< ServerMessages, MessageFromClient, ServerMessage, ClientMessages, ClientMessage, > for ClientSseTransport<ServerMessage> { }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/error.rs
crates/rust-mcp-transport/src/error.rs
use crate::schema::{schema_utils::SdkError, RpcError}; use crate::utils::CancellationError; use core::fmt; #[cfg(any(feature = "sse", feature = "streamable-http"))] use reqwest::Error as ReqwestError; #[cfg(any(feature = "sse", feature = "streamable-http"))] use reqwest::StatusCode; use std::any::Any; use std::io::Error as IoError; use thiserror::Error; use tokio::sync::{broadcast, mpsc}; /// A wrapper around a broadcast send error. This structure allows for generic error handling /// by boxing the underlying error into a type-erased form. #[derive(Debug)] pub struct GenericSendError { inner: Box<dyn Any + Send>, } #[allow(unused)] impl GenericSendError { pub fn new<T: Send + 'static>(error: mpsc::error::SendError<T>) -> Self { Self { inner: Box::new(error), } } /// Attempts to downcast the wrapped error to a specific `broadcast::error::SendError` type. /// /// # Returns /// `Some(T)` if the error can be downcasted, `None` otherwise. fn downcast<T: Send + 'static>(self) -> Option<broadcast::error::SendError<T>> { self.inner .downcast::<broadcast::error::SendError<T>>() .ok() .map(|boxed| *boxed) } } impl fmt::Display for GenericSendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Broadcast SendError: Failed to send a message.") } } // Implementing `Error` trait impl std::error::Error for GenericSendError {} /// A wrapper around a broadcast send error. This structure allows for generic error handling /// by boxing the underlying error into a type-erased form. #[derive(Debug)] pub struct GenericWatchSendError { inner: Box<dyn Any + Send>, } #[allow(unused)] impl GenericWatchSendError { pub fn new<T: Send + 'static>(error: tokio::sync::watch::error::SendError<T>) -> Self { Self { inner: Box::new(error), } } /// Attempts to downcast the wrapped error to a specific `broadcast::error::SendError` type. /// /// # Returns /// `Some(T)` if the error can be downcasted, `None` otherwise. fn downcast<T: Send + 'static>(self) -> Option<tokio::sync::watch::error::SendError<T>> { self.inner .downcast::<tokio::sync::watch::error::SendError<T>>() .ok() .map(|boxed| *boxed) } } impl fmt::Display for GenericWatchSendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Watch SendError: Failed to send a message.") } } // Implementing `Error` trait impl std::error::Error for GenericWatchSendError {} pub type TransportResult<T> = core::result::Result<T, TransportError>; #[derive(Debug, Error)] pub enum TransportError { #[error("Session expired or not found")] SessionExpired, #[error("Failed to open SSE stream: {0}")] FailedToOpenSSEStream(String), #[error("Unexpected content type: '{0}'")] UnexpectedContentType(String), #[error("Failed to send message: {0}")] SendFailure(String), #[error("I/O error: {0}")] Io(#[from] IoError), #[cfg(any(feature = "sse", feature = "streamable-http"))] #[error("HTTP connection error: {0}")] HttpConnection(#[from] ReqwestError), #[cfg(any(feature = "sse", feature = "streamable-http"))] #[error("HTTP error: {0}")] Http(StatusCode), #[error("SDK error: {0}")] Sdk(#[from] SdkError), #[error("Operation cancelled: {0}")] Cancelled(#[from] CancellationError), #[error("Channel closed: {0}")] ChannelClosed(#[from] tokio::sync::oneshot::error::RecvError), #[error("Configuration error: {message}")] Configuration { message: String }, #[error("{0}")] SendError(#[from] GenericSendError), #[error("{0}")] JsonrpcError(#[from] RpcError), #[error("Process error: {0}")] ProcessError(String), #[error("Internal error: {0}")] Internal(String), #[error("Shutdown timed out")] ShutdownTimeout, }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/schema.rs
crates/rust-mcp-transport/src/schema.rs
pub use rust_mcp_schema::*;
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/mcp_stream.rs
crates/rust-mcp-transport/src/mcp_stream.rs
use crate::schema::RequestId; use crate::{ error::{GenericSendError, TransportError}, message_dispatcher::MessageDispatcher, utils::CancellationToken, IoStream, }; use std::{collections::HashMap, pin::Pin, sync::Arc, time::Duration}; use tokio::task::JoinHandle; use tokio::{ io::{AsyncBufReadExt, BufReader}, sync::Mutex, }; const CHANNEL_CAPACITY: usize = 36; pub struct MCPStream {} impl MCPStream { /// Creates a new asynchronous stream and associated components for handling I/O operations. /// This function takes in a readable stream, a writable stream wrapped in a `Mutex`, and an `IoStream` /// # Returns /// /// A tuple containing: /// - A `Pin<Box<dyn Stream<Item = R> + Send>>`: A stream that yields items of type `R`. /// - A `MessageDispatcher<R>`: A sender that can be used to send messages of type `R`. /// - An `IoStream`: An error handling stream for managing error I/O (stderr). pub fn create<X, R>( readable: Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>>, writable: Mutex<Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>>, error_io: IoStream, pending_requests: Arc<Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<R>>>>, request_timeout: Duration, cancellation_token: CancellationToken, ) -> ( tokio_stream::wrappers::ReceiverStream<X>, MessageDispatcher<R>, IoStream, ) where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, X: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { let (tx, rx) = tokio::sync::mpsc::channel::<X>(CHANNEL_CAPACITY); let stream = tokio_stream::wrappers::ReceiverStream::new(rx); // Clone cancellation_token for reader let reader_token = cancellation_token.clone(); #[allow(clippy::let_underscore_future)] let _ = Self::spawn_reader(readable, tx, reader_token); // rpc message stream that receives incoming messages let sender = MessageDispatcher::new(pending_requests, writable, request_timeout); (stream, sender, error_io) } pub fn create_with_ack<X, R>( readable: Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>>, writable: tokio::sync::mpsc::Sender<( String, tokio::sync::oneshot::Sender<crate::error::TransportResult<()>>, )>, error_io: IoStream, pending_requests: Arc<Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<R>>>>, request_timeout: Duration, cancellation_token: CancellationToken, ) -> ( tokio_stream::wrappers::ReceiverStream<X>, MessageDispatcher<R>, IoStream, ) where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, X: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { let (tx, rx) = tokio::sync::mpsc::channel::<X>(CHANNEL_CAPACITY); let stream = tokio_stream::wrappers::ReceiverStream::new(rx); // Clone cancellation_token for reader let reader_token = cancellation_token.clone(); #[allow(clippy::let_underscore_future)] let _ = Self::spawn_reader(readable, tx, reader_token); let sender = MessageDispatcher::new_with_acknowledgement( pending_requests, writable, request_timeout, ); (stream, sender, error_io) } /// Creates a new task that continuously reads from the readable stream. /// The received data is deserialized into a JsonrpcMessage. If the deserialization is successful, /// the object is transmitted. If the object is a response or error corresponding to a pending request, /// the associated pending request will ber removed from pending_requests. fn spawn_reader<X>( readable: Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>>, tx: tokio::sync::mpsc::Sender<X>, cancellation_token: CancellationToken, ) -> JoinHandle<Result<(), TransportError>> where X: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { tokio::spawn(async move { let mut lines_stream = BufReader::new(readable).lines(); loop { tokio::select! { _ = cancellation_token.cancelled() => { break; }, line = lines_stream.next_line() =>{ match line { Ok(Some(line)) => { tracing::debug!("raw payload: {}",line); // deserialize and send it to the stream let message: X = match serde_json::from_str(&line){ Ok(mcp_message) => mcp_message, Err(_) => { // continue if malformed message is received continue; }, }; tx.send(message).await.map_err(GenericSendError::new)?; } Ok(None) => { // EOF reached, exit loop break; } Err(e) => { // Handle error in reading from readable_std return Err(TransportError::ProcessError(format!( "Error reading from readable_std: {e}" ))); } } } } } Ok::<(), TransportError>(()) }) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils.rs
crates/rust-mcp-transport/src/utils.rs
mod cancellation_token; #[cfg(any(feature = "sse", feature = "streamable-http"))] mod http_utils; #[cfg(any(feature = "sse", feature = "streamable-http"))] mod readable_channel; #[cfg(any(feature = "sse", feature = "streamable-http"))] mod sse_event; #[cfg(any(feature = "sse", feature = "streamable-http"))] mod sse_parser; #[cfg(feature = "sse")] mod sse_stream; #[cfg(feature = "streamable-http")] mod streamable_http_stream; mod time_utils; #[cfg(any(feature = "sse", feature = "streamable-http"))] mod writable_channel; use crate::error::{TransportError, TransportResult}; use crate::schema::schema_utils::SdkError; pub(crate) use cancellation_token::*; #[cfg(any(feature = "sse", feature = "streamable-http"))] use crate::SessionId; #[cfg(any(feature = "sse", feature = "streamable-http"))] pub(crate) use http_utils::*; #[cfg(any(feature = "sse", feature = "streamable-http"))] pub(crate) use readable_channel::*; #[cfg(any(feature = "sse", feature = "streamable-http"))] pub use sse_event::*; #[cfg(any(feature = "sse", feature = "streamable-http"))] pub(crate) use sse_parser::*; #[cfg(feature = "sse")] pub(crate) use sse_stream::*; #[cfg(feature = "streamable-http")] pub(crate) use streamable_http_stream::*; pub use time_utils::*; use tokio::time::{timeout, Duration}; #[cfg(any(feature = "sse", feature = "streamable-http"))] pub(crate) use writable_channel::*; pub async fn await_timeout<F, T, E>(operation: F, timeout_duration: Duration) -> TransportResult<T> where F: std::future::Future<Output = Result<T, E>>, // The operation returns a Result E: Into<TransportError>, { match timeout(timeout_duration, operation).await { Ok(result) => result.map_err(|err| err.into()), Err(_) => Err(SdkError::request_timeout(timeout_duration.as_millis()).into()), // Timeout error } } /// Adds a session ID as a query parameter to a given endpoint URL. /// /// # Arguments /// * `endpoint` - The base URL or endpoint (e.g., "/messages") /// * `session_id` - The session ID to append as a query parameter /// /// # Returns /// A String containing the endpoint with the session ID added as a query parameter /// #[cfg(any(feature = "sse", feature = "streamable-http"))] pub(crate) fn endpoint_with_session_id(endpoint: &str, session_id: &SessionId) -> String { // Handle empty endpoint let base = if endpoint.is_empty() { "/" } else { endpoint }; // Split fragment if it exists let (path_and_query, fragment) = if let Some((p, f)) = base.split_once('#') { (p, Some(f)) } else { (base, None) }; // Split path and query let (path, query) = if let Some((p, q)) = path_and_query.split_once('?') { (p, Some(q)) } else { (path_and_query, None) }; // Build the query string let new_query = match query { Some(q) if !q.is_empty() => format!("{q}&sessionId={session_id}"), _ => format!("sessionId={session_id}"), }; // Construct final URL match fragment { Some(f) => format!("{path}?{new_query}#{f}"), None => format!("{path}?{new_query}"), } } #[cfg(feature = "sse")] #[cfg(test)] mod tests { use super::*; #[test] fn test_endpoint_with_session_id() { let session_id: SessionId = "AAA".to_string(); assert_eq!( endpoint_with_session_id("/messages", &session_id), "/messages?sessionId=AAA" ); assert_eq!( endpoint_with_session_id("/messages?foo=bar&baz=qux", &session_id), "/messages?foo=bar&baz=qux&sessionId=AAA" ); assert_eq!( endpoint_with_session_id("/messages#section1", &session_id), "/messages?sessionId=AAA#section1" ); assert_eq!( endpoint_with_session_id("/messages?key=value#section2", &session_id), "/messages?key=value&sessionId=AAA#section2" ); assert_eq!( endpoint_with_session_id("/", &session_id), "/?sessionId=AAA" ); assert_eq!(endpoint_with_session_id("", &session_id), "/?sessionId=AAA"); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/transport.rs
crates/rust-mcp-transport/src/transport.rs
use crate::{error::TransportResult, message_dispatcher::MessageDispatcher}; use crate::{schema::RequestId, SessionId}; use async_trait::async_trait; use std::{pin::Pin, sync::Arc, time::Duration}; use tokio::{ sync::oneshot::{self, Sender}, task::JoinHandle, }; /// Default Timeout in milliseconds const DEFAULT_TIMEOUT_MSEC: u64 = 60_000; /// Enum representing a stream that can either be readable or writable. /// This allows the reuse of the same traits for both MCP Server and MCP Client, /// where the data direction is reversed. /// /// It encapsulates two types of I/O streams: /// - `Readable`: A stream that implements the `AsyncRead` trait for reading data asynchronously. /// - `Writable`: A stream that implements the `AsyncWrite` trait for writing data asynchronously. /// pub enum IoStream { Readable(Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>>), Writable(Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>), } /// Configuration for the transport layer #[derive(Debug, Clone)] pub struct TransportOptions { /// The timeout in milliseconds for requests. /// /// This value defines the maximum amount of time to wait for a response before /// considering the request as timed out. pub timeout: Duration, } impl Default for TransportOptions { fn default() -> Self { Self { timeout: Duration::from_millis(DEFAULT_TIMEOUT_MSEC), } } } /// A trait for dispatching MCP (Message Communication Protocol) messages. /// /// This trait is designed to be implemented by components such as clients, servers, or transports /// that send and receive messages in the MCP protocol. It defines the interface for transmitting messages, /// optionally awaiting responses, writing raw payloads, and handling batch communication. /// /// # Associated Types /// /// - `R`: The response type expected from a message. This must implement deserialization and be safe /// for concurrent use in async contexts. /// - `S`: The type of the outgoing message sent directly to the wire. Must be serializable. /// - `M`: The internal message type used for responses received from a remote peer. /// - `OM`: The outgoing message type submitted to the dispatcher. This is the higher-level form of `S` /// used by clients or services submitting requests. /// #[async_trait] pub trait McpDispatch<R, S, M, OM>: Send + Sync + 'static where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, S: Clone + Send + Sync + serde::Serialize + 'static, M: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, OM: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { /// Sends a raw message represented by type `S` and optionally includes a `request_id`. /// The `request_id` is used when sending a message in response to an MCP request. /// It should match the `request_id` of the original request. async fn send_message( &self, message: S, request_timeout: Option<Duration>, ) -> TransportResult<Option<R>>; async fn send(&self, message: OM, timeout: Option<Duration>) -> TransportResult<Option<M>>; async fn send_batch( &self, message: Vec<OM>, timeout: Option<Duration>, ) -> TransportResult<Option<Vec<M>>>; /// Writes a string payload to the underlying asynchronous writable stream, /// appending a newline character and flushing the stream afterward. /// async fn write_str(&self, payload: &str, skip_store: bool) -> TransportResult<()>; } /// A trait representing the transport layer for the MCP (Message Communication Protocol). /// /// This trait abstracts the transport layer functionality required to send and receive messages /// within an MCP-based system. It provides methods to initialize the transport, send and receive /// messages, handle errors, manage pending requests, and implement keep-alive functionality. /// /// # Associated Types /// /// - `R`: The type of message expected to be received from the transport layer. Must be deserializable. /// - `S`: The type of message to be sent over the transport layer. Must be serializable. /// - `M`: The internal message type used by the dispatcher. Typically this wraps or transforms `R`. /// - `OR`: The outbound response type expected to be produced by the dispatcher when handling incoming messages. /// - `OM`: The outbound message type that the dispatcher expects to send as a reply to received messages. /// #[async_trait] pub trait Transport<R, S, M, OR, OM>: Send + Sync + 'static where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, S: Clone + Send + Sync + serde::Serialize + 'static, M: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, OR: Clone + Send + Sync + serde::Serialize + 'static, OM: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { async fn start(&self) -> TransportResult<tokio_stream::wrappers::ReceiverStream<R>> where MessageDispatcher<M>: McpDispatch<R, OR, M, OM>; fn message_sender(&self) -> Arc<tokio::sync::RwLock<Option<MessageDispatcher<M>>>>; fn error_stream(&self) -> &tokio::sync::RwLock<Option<IoStream>>; async fn shut_down(&self) -> TransportResult<()>; async fn is_shut_down(&self) -> bool; async fn consume_string_payload(&self, payload: &str) -> TransportResult<()>; async fn pending_request_tx(&self, request_id: &RequestId) -> Option<Sender<M>>; async fn keep_alive( &self, interval: Duration, disconnect_tx: oneshot::Sender<()>, ) -> TransportResult<JoinHandle<()>>; async fn session_id(&self) -> Option<SessionId> { None } } /// A composite trait that combines both transport and dispatch capabilities for the MCP protocol. /// /// `TransportDispatcher` unifies the functionality of [`Transport`] and [`McpDispatch`], allowing implementors /// to both manage the transport layer and handle message dispatch logic in a single abstraction. /// /// This trait applies to components responsible for the following operations: /// - Handle low-level I/O (stream management, payload parsing, lifecycle control) /// - Dispatch and route messages, potentially awaiting or sending responses /// /// # Supertraits /// /// - [`Transport<R, S, M, OR, OM>`]: Provides the transport-level operations (starting, shutting down, /// receiving messages, etc.). /// - [`McpDispatch<R, OR, M, OM>`]: Provides message-sending and dispatching capabilities. /// /// # Associated Types /// /// - `R`: The raw message type expected to be received. Must be deserializable. /// - `S`: The message type sent over the transport (often serialized directly to wire). /// - `M`: The internal message type used within the dispatcher. /// - `OR`: The outbound response type returned from processing a received message. /// - `OM`: The outbound message type submitted by clients or application code. /// pub trait TransportDispatcher<R, S, M, OR, OM>: Transport<R, S, M, OR, OM> + McpDispatch<R, OR, M, OM> where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, S: Clone + Send + Sync + serde::Serialize + 'static, M: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, OR: Clone + Send + Sync + serde::Serialize + 'static, OM: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { } // pub trait IntoClientTransport { // type TransportType: Transport< // ServerMessages, // MessageFromClient, // ServerMessage, // ClientMessages, // ClientMessage, // >; // fn into_transport(self, session_id: Option<SessionId>) -> TransportResult<Self::TransportType>; // } // impl<T> IntoClientTransport for T // where // T: Transport<ServerMessages, MessageFromClient, ServerMessage, ClientMessages, ClientMessage>, // { // type TransportType = T; // fn into_transport(self, _: Option<SessionId>) -> TransportResult<Self::TransportType> { // Ok(self) // } // }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/constants.rs
crates/rust-mcp-transport/src/constants.rs
pub const MCP_SESSION_ID_HEADER: &str = "mcp-session-id"; pub const MCP_PROTOCOL_VERSION_HEADER: &str = "mcp-protocol-version"; pub const MCP_LAST_EVENT_ID_HEADER: &str = "last-event-id";
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/message_dispatcher.rs
crates/rust-mcp-transport/src/message_dispatcher.rs
use crate::error::{TransportError, TransportResult}; use crate::schema::{RequestId, RpcError}; use crate::utils::{await_timeout, current_timestamp}; use crate::McpDispatch; use crate::{ event_store::EventStore, schema::{ schema_utils::{ self, ClientMessage, ClientMessages, McpMessage, RpcMessage, ServerMessage, ServerMessages, }, JsonrpcErrorResponse, }, SessionId, StreamId, }; use async_trait::async_trait; use futures::future::join_all; use std::collections::HashMap; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; use tokio::io::AsyncWriteExt; use tokio::sync::oneshot::{self}; use tokio::sync::Mutex; pub const ID_SEPARATOR: u8 = b'|'; /// Provides a dispatcher for sending MCP messages and handling responses. /// /// `MessageDispatcher` facilitates MCP communication by managing message sending, request tracking, /// and response handling. It supports both client-to-server and server-to-client message flows through /// implementations of the `McpDispatch` trait. The dispatcher uses a transport mechanism /// (e.g., stdin/stdout) to serialize and send messages, and it tracks pending requests with /// a configurable timeout mechanism for asynchronous responses. pub struct MessageDispatcher<R> { pending_requests: Arc<Mutex<HashMap<RequestId, oneshot::Sender<R>>>>, writable_std: Option<Mutex<Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>>>, writable_tx: Option< tokio::sync::mpsc::Sender<( String, tokio::sync::oneshot::Sender<crate::error::TransportResult<()>>, )>, >, request_timeout: Duration, // resumability support session_id: Option<SessionId>, stream_id: Option<StreamId>, event_store: Option<Arc<dyn EventStore>>, } impl<R> MessageDispatcher<R> { /// Creates a new `MessageDispatcher` instance with the given configuration. /// /// # Arguments /// * `pending_requests` - A thread-safe map for storing pending request IDs and their response channels. /// * `writable_std` - A mutex-protected, pinned writer (e.g., stdout) for sending serialized messages. /// * `message_id_counter` - An atomic counter for generating unique request IDs. /// * `request_timeout` - The timeout duration in milliseconds for awaiting responses. /// /// # Returns /// A new `MessageDispatcher` instance configured for MCP message handling. pub fn new( pending_requests: Arc<Mutex<HashMap<RequestId, oneshot::Sender<R>>>>, writable_std: Mutex<Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>>, request_timeout: Duration, ) -> Self { Self { pending_requests, writable_std: Some(writable_std), writable_tx: None, request_timeout, session_id: None, stream_id: None, event_store: None, } } pub fn new_with_acknowledgement( pending_requests: Arc<Mutex<HashMap<RequestId, oneshot::Sender<R>>>>, writable_tx: tokio::sync::mpsc::Sender<( String, tokio::sync::oneshot::Sender<crate::error::TransportResult<()>>, )>, request_timeout: Duration, ) -> Self { Self { pending_requests, writable_tx: Some(writable_tx), writable_std: None, request_timeout, session_id: None, stream_id: None, event_store: None, } } /// Supports resumability for streamable HTTP transports by setting the session ID, /// stream ID, and event store. pub fn make_resumable( &mut self, session_id: SessionId, stream_id: StreamId, event_store: Arc<dyn EventStore>, ) { self.session_id = Some(session_id); self.stream_id = Some(stream_id); self.event_store = Some(event_store); } async fn store_pending_request( &self, request_id: RequestId, ) -> tokio::sync::oneshot::Receiver<R> { let (tx_response, rx_response) = oneshot::channel::<R>(); let mut pending_requests = self.pending_requests.lock().await; // store request id in the hashmap while waiting for a matching response pending_requests.insert(request_id.clone(), tx_response); rx_response } async fn store_pending_request_for_message<M: McpMessage + RpcMessage>( &self, message: &M, ) -> Option<tokio::sync::oneshot::Receiver<R>> { if message.is_request() { if let Some(request_id) = message.request_id() { Some(self.store_pending_request(request_id.clone()).await) } else { None } } else { None } } } // Client side dispatcher #[async_trait] impl McpDispatch<ServerMessages, ClientMessages, ServerMessage, ClientMessage> for MessageDispatcher<ServerMessage> { /// Sends a message from the client to the server and awaits a response if applicable. /// /// Serializes the `ClientMessages` to JSON, writes it to the transport, and waits for a /// `ServerMessages` response if the message is a request. Notifications and responses return /// `Ok(None)`. /// /// # Arguments /// * `messages` - The client message to send, coulld be a single message or batch. /// /// # Returns /// A `TransportResult` containing `Some(ServerMessages)` for requests with a response, /// or `None` for notifications/responses, or an error if the operation fails. /// /// # Errors /// Returns a `TransportError` if serialization, writing, or timeout occurs. async fn send_message( &self, messages: ClientMessages, request_timeout: Option<Duration>, ) -> TransportResult<Option<ServerMessages>> { match messages { ClientMessages::Single(message) => { let rx_response: Option<tokio::sync::oneshot::Receiver<ServerMessage>> = self.store_pending_request_for_message(&message).await; //serialize the message and write it to the writable_std let message_payload = serde_json::to_string(&message).map_err(|_| { crate::error::TransportError::JsonrpcError(RpcError::parse_error()) })?; self.write_str(message_payload.as_str(), true).await?; if let Some(rx) = rx_response { // Wait for the response with timeout match await_timeout(rx, request_timeout.unwrap_or(self.request_timeout)).await { Ok(response) => Ok(Some(ServerMessages::Single(response))), Err(error) => match error { TransportError::ChannelClosed(_) => { Err(schema_utils::SdkError::connection_closed().into()) } _ => Err(error), }, } } else { Ok(None) } } ClientMessages::Batch(client_messages) => { let (request_ids, pending_tasks): (Vec<_>, Vec<_>) = client_messages .iter() .filter(|message| message.is_request()) .map(|message| { ( message.request_id(), self.store_pending_request_for_message(message), ) }) .unzip(); // Ensure all request IDs are stored before sending the request let tasks = join_all(pending_tasks).await; // send the batch messages to the server let message_payload = serde_json::to_string(&client_messages).map_err(|_| { crate::error::TransportError::JsonrpcError(RpcError::parse_error()) })?; self.write_str(message_payload.as_str(), true).await?; // no request in the batch, no need to wait for the result if request_ids.is_empty() { return Ok(None); } let timeout_wrapped_futures = tasks.into_iter().filter_map(|rx| { rx.map(|rx| await_timeout(rx, request_timeout.unwrap_or(self.request_timeout))) }); let results: Vec<_> = join_all(timeout_wrapped_futures) .await .into_iter() .zip(request_ids) .map(|(res, request_id)| match res { Ok(response) => response, Err(error) => ServerMessage::Error(JsonrpcErrorResponse::new( RpcError::internal_error().with_message(error.to_string()), request_id.cloned(), )), }) .collect(); Ok(Some(ServerMessages::Batch(results))) } } } async fn send( &self, message: ClientMessage, request_timeout: Option<Duration>, ) -> TransportResult<Option<ServerMessage>> { let response = self.send_message(message.into(), request_timeout).await?; match response { Some(r) => Ok(Some(r.as_single()?)), None => Ok(None), } } async fn send_batch( &self, message: Vec<ClientMessage>, request_timeout: Option<Duration>, ) -> TransportResult<Option<Vec<ServerMessage>>> { let response = self.send_message(message.into(), request_timeout).await?; match response { Some(r) => Ok(Some(r.as_batch()?)), None => Ok(None), } } /// Writes a string payload to the underlying asynchronous writable stream, /// appending a newline character and flushing the stream afterward. /// async fn write_str(&self, payload: &str, _skip_store: bool) -> TransportResult<()> { if let Some(writable_std) = self.writable_std.as_ref() { let mut writable_std = writable_std.lock().await; writable_std.write_all(payload.as_bytes()).await?; writable_std.write_all(b"\n").await?; // new line writable_std.flush().await?; return Ok(()); }; if let Some(writable_tx) = self.writable_tx.as_ref() { let (resp_tx, resp_rx) = oneshot::channel(); writable_tx .send((payload.to_string(), resp_tx)) .await .map_err(|err| TransportError::Internal(format!("{err}")))?; // Send fails if channel closed return resp_rx.await?; // Await the POST result; propagates the error if POST failed } Err(TransportError::Internal("Invalid dispatcher!".to_string())) } } // Server side dispatcher, Sends S and Returns R #[async_trait] impl McpDispatch<ClientMessages, ServerMessages, ClientMessage, ServerMessage> for MessageDispatcher<ClientMessage> { /// Sends a message from the server to the client and awaits a response if applicable. /// /// Serializes the `ServerMessages` to JSON, writes it to the transport, and waits for a /// `ClientMessages` response if the message is a request. Notifications and responses return /// `Ok(None)`. /// /// # Arguments /// * `messages` - The client message to send, coulld be a single message or batch. /// /// # Returns /// A `TransportResult` containing `Some(ClientMessages)` for requests with a response, /// or `None` for notifications/responses, or an error if the operation fails. /// /// # Errors /// Returns a `TransportError` if serialization, writing, or timeout occurs. async fn send_message( &self, messages: ServerMessages, request_timeout: Option<Duration>, ) -> TransportResult<Option<ClientMessages>> { match messages { ServerMessages::Single(message) => { let rx_response: Option<tokio::sync::oneshot::Receiver<ClientMessage>> = self.store_pending_request_for_message(&message).await; let message_payload = serde_json::to_string(&message).map_err(|_| { crate::error::TransportError::JsonrpcError(RpcError::parse_error()) })?; self.write_str(message_payload.as_str(), false).await?; if let Some(rx) = rx_response { match await_timeout(rx, request_timeout.unwrap_or(self.request_timeout)).await { Ok(response) => Ok(Some(ClientMessages::Single(response))), Err(error) => Err(error), } } else { Ok(None) } } ServerMessages::Batch(server_messages) => { let (request_ids, pending_tasks): (Vec<_>, Vec<_>) = server_messages .iter() .filter(|message| message.is_request()) .map(|message| { ( message.request_id(), self.store_pending_request_for_message(message), ) }) .unzip(); // send the batch messages to the client let message_payload = serde_json::to_string(&server_messages).map_err(|_| { crate::error::TransportError::JsonrpcError(RpcError::parse_error()) })?; self.write_str(message_payload.as_str(), false).await?; // no request in the batch, no need to wait for the result if pending_tasks.is_empty() { return Ok(None); } let tasks = join_all(pending_tasks).await; let timeout_wrapped_futures = tasks.into_iter().filter_map(|rx| { rx.map(|rx| await_timeout(rx, request_timeout.unwrap_or(self.request_timeout))) }); let results: Vec<_> = join_all(timeout_wrapped_futures) .await .into_iter() .zip(request_ids) .map(|(res, request_id)| match res { Ok(response) => response, Err(error) => ClientMessage::Error(JsonrpcErrorResponse::new( RpcError::internal_error().with_message(error.to_string()), request_id.cloned(), )), }) .collect(); Ok(Some(ClientMessages::Batch(results))) } } } async fn send( &self, message: ServerMessage, request_timeout: Option<Duration>, ) -> TransportResult<Option<ClientMessage>> { let response = self.send_message(message.into(), request_timeout).await?; match response { Some(r) => Ok(Some(r.as_single()?)), None => Ok(None), } } async fn send_batch( &self, message: Vec<ServerMessage>, request_timeout: Option<Duration>, ) -> TransportResult<Option<Vec<ClientMessage>>> { let response = self.send_message(message.into(), request_timeout).await?; match response { Some(r) => Ok(Some(r.as_batch()?)), None => Ok(None), } } /// Writes a string payload to the underlying asynchronous writable stream, /// appending a newline character and flushing the stream afterward. /// async fn write_str(&self, payload: &str, skip_store: bool) -> TransportResult<()> { let mut event_id = None; if !skip_store && !payload.trim().is_empty() { if let (Some(session_id), Some(stream_id), Some(event_store)) = ( self.session_id.as_ref(), self.stream_id.as_ref(), self.event_store.as_ref(), ) { event_id = event_store .store_event( session_id.clone(), stream_id.clone(), current_timestamp(), payload.to_owned(), ) .await .map(Some) .unwrap_or_else(|err| { tracing::error!("{err}"); None }); }; } if let Some(writable_std) = self.writable_std.as_ref() { let mut writable_std = writable_std.lock().await; if let Some(id) = event_id { writable_std.write_all(id.as_bytes()).await?; writable_std.write_all(&[ID_SEPARATOR]).await?; // separate id from message } writable_std.write_all(payload.as_bytes()).await?; writable_std.write_all(b"\n").await?; // new line writable_std.flush().await?; return Ok(()); }; if let Some(writable_tx) = self.writable_tx.as_ref() { let (resp_tx, resp_rx) = oneshot::channel(); writable_tx .send((payload.to_string(), resp_tx)) .await .map_err(|err| TransportError::Internal(err.to_string()))?; // Send fails if channel closed return resp_rx.await?; // Await the POST result; propagates the error if POST failed } Err(TransportError::Internal("Invalid dispatcher!".to_string())) } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/client_streamable_http.rs
crates/rust-mcp-transport/src/client_streamable_http.rs
use crate::error::TransportError; use crate::mcp_stream::MCPStream; use crate::schema::{ schema_utils::{ ClientMessage, ClientMessages, McpMessage, MessageFromClient, SdkError, ServerMessage, ServerMessages, }, RequestId, }; use crate::utils::{ http_delete, http_post, CancellationTokenSource, ReadableChannel, StreamableHttpStream, WritableChannel, }; use crate::{error::TransportResult, IoStream, McpDispatch, MessageDispatcher, Transport}; use crate::{SessionId, TransportDispatcher, TransportOptions}; use async_trait::async_trait; use bytes::Bytes; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use reqwest::Client; use std::collections::HashMap; use std::pin::Pin; use std::{sync::Arc, time::Duration}; use tokio::io::{BufReader, BufWriter}; use tokio::sync::oneshot::Sender; use tokio::sync::{mpsc, oneshot, Mutex}; use tokio::task::JoinHandle; const DEFAULT_CHANNEL_CAPACITY: usize = 64; const DEFAULT_MAX_RETRY: usize = 5; const DEFAULT_RETRY_TIME_SECONDS: u64 = 1; const SHUTDOWN_TIMEOUT_SECONDS: u64 = 5; pub struct StreamableTransportOptions { pub mcp_url: String, pub request_options: RequestOptions, } impl StreamableTransportOptions { pub async fn terminate_session(&self, session_id: Option<&SessionId>) { let client = Client::new(); match http_delete(&client, &self.mcp_url, session_id, None).await { Ok(_) => {} Err(TransportError::Http(status_code)) => { tracing::info!("Session termination failed with status code {status_code}",); } Err(error) => { tracing::info!("Session termination failed with error :{error}"); } }; } } pub struct RequestOptions { pub request_timeout: Duration, pub retry_delay: Option<Duration>, pub max_retries: Option<usize>, pub custom_headers: Option<HashMap<String, String>>, } impl Default for RequestOptions { fn default() -> Self { Self { request_timeout: TransportOptions::default().timeout, retry_delay: None, max_retries: None, custom_headers: None, } } } pub struct ClientStreamableTransport<R> where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { /// Optional cancellation token source for shutting down the transport shutdown_source: tokio::sync::RwLock<Option<CancellationTokenSource>>, /// Flag indicating if the transport is shut down is_shut_down: Mutex<bool>, /// Timeout duration for MCP messages request_timeout: Duration, /// HTTP client for making requests client: Client, /// URL for the SSE endpoint mcp_server_url: String, /// Delay between retry attempts retry_delay: Duration, /// Maximum number of retry attempts max_retries: usize, /// Optional custom HTTP headers custom_headers: Option<HeaderMap>, sse_task: tokio::sync::RwLock<Option<tokio::task::JoinHandle<()>>>, post_task: tokio::sync::RwLock<Option<tokio::task::JoinHandle<()>>>, message_sender: Arc<tokio::sync::RwLock<Option<MessageDispatcher<R>>>>, error_stream: tokio::sync::RwLock<Option<IoStream>>, pending_requests: Arc<Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<R>>>>, session_id: Arc<tokio::sync::RwLock<Option<SessionId>>>, standalone: bool, } impl<R> ClientStreamableTransport<R> where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { pub fn new( options: &StreamableTransportOptions, session_id: Option<SessionId>, standalone: bool, ) -> TransportResult<Self> { let client = Client::new(); let headers = match &options.request_options.custom_headers { Some(h) => Some(Self::validate_headers(h)?), None => None, }; let mcp_server_url = options.mcp_url.to_owned(); Ok(Self { shutdown_source: tokio::sync::RwLock::new(None), is_shut_down: Mutex::new(false), request_timeout: options.request_options.request_timeout, client, mcp_server_url, retry_delay: options .request_options .retry_delay .unwrap_or(Duration::from_secs(DEFAULT_RETRY_TIME_SECONDS)), max_retries: options .request_options .max_retries .unwrap_or(DEFAULT_MAX_RETRY), sse_task: tokio::sync::RwLock::new(None), post_task: tokio::sync::RwLock::new(None), custom_headers: headers, message_sender: Arc::new(tokio::sync::RwLock::new(None)), error_stream: tokio::sync::RwLock::new(None), pending_requests: Arc::new(Mutex::new(HashMap::new())), session_id: Arc::new(tokio::sync::RwLock::new(session_id)), standalone, }) } fn validate_headers(headers: &HashMap<String, String>) -> TransportResult<HeaderMap> { let mut header_map = HeaderMap::new(); for (key, value) in headers { let header_name = key.parse::<HeaderName>() .map_err(|e| TransportError::Configuration { message: format!("Invalid header name: {e}"), })?; let header_value = HeaderValue::from_str(value).map_err(|e| TransportError::Configuration { message: format!("Invalid header value: {e}"), })?; header_map.insert(header_name, header_value); } Ok(header_map) } pub(crate) async fn set_message_sender(&self, sender: MessageDispatcher<R>) { let mut lock = self.message_sender.write().await; *lock = Some(sender); } pub(crate) async fn set_error_stream( &self, error_stream: Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>>, ) { let mut lock = self.error_stream.write().await; *lock = Some(IoStream::Readable(error_stream)); } } #[async_trait] impl<R, S, M, OR, OM> Transport<R, S, M, OR, OM> for ClientStreamableTransport<M> where R: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, S: McpMessage + Clone + Send + Sync + serde::Serialize + 'static, M: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, OR: Clone + Send + Sync + serde::Serialize + 'static, OM: Clone + Send + Sync + serde::de::DeserializeOwned + 'static, { async fn start(&self) -> TransportResult<tokio_stream::wrappers::ReceiverStream<R>> where MessageDispatcher<M>: McpDispatch<R, OR, M, OM>, { if self.standalone { // Create CancellationTokenSource and token let (cancellation_source, cancellation_token) = CancellationTokenSource::new(); let mut lock = self.shutdown_source.write().await; *lock = Some(cancellation_source); let (write_tx, mut write_rx) = mpsc::channel::<Bytes>(DEFAULT_CHANNEL_CAPACITY); let (read_tx, read_rx) = mpsc::channel::<Bytes>(DEFAULT_CHANNEL_CAPACITY); let max_retries = self.max_retries; let retry_delay = self.retry_delay; let post_url = self.mcp_server_url.clone(); let custom_headers = self.custom_headers.clone(); let cancellation_token_post = cancellation_token.clone(); let cancellation_token_sse = cancellation_token.clone(); let session_id_clone = self.session_id.clone(); let mut streamable_http = StreamableHttpStream { client: self.client.clone(), mcp_url: post_url, max_retries, retry_delay, read_tx, session_id: session_id_clone, //Arc<RwLock<Option<String>>> }; let session_id = self.session_id.read().await.to_owned(); let sse_response = streamable_http .make_standalone_stream_connection(&cancellation_token_sse, &custom_headers, None) .await?; let sse_task_handle = tokio::spawn(async move { if let Err(error) = streamable_http .run_standalone(&cancellation_token_sse, &custom_headers, sse_response) .await { if !matches!(error, TransportError::Cancelled(_)) { tracing::warn!("{error}"); } } }); let mut sse_task_lock = self.sse_task.write().await; *sse_task_lock = Some(sse_task_handle); let post_url = self.mcp_server_url.clone(); let client = self.client.clone(); let custom_headers = self.custom_headers.clone(); // Initiate a task to process POST requests from messages received via the writable stream. let post_task_handle = tokio::spawn(async move { loop { tokio::select! { _ = cancellation_token_post.cancelled() => { break; }, data = write_rx.recv() => { match data{ Some(data) => { // trim the trailing \n before making a request let payload = String::from_utf8_lossy(&data).trim().to_string(); if let Err(e) = http_post( &client, &post_url, payload.to_string(), session_id.as_ref(), custom_headers.as_ref(), ) .await{ tracing::error!("Failed to POST message: {e}") } }, None => break, // Exit if channel is closed } } } } }); let mut post_task_lock = self.post_task.write().await; *post_task_lock = Some(post_task_handle); // Create writable stream let writable: Mutex<Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>> = Mutex::new(Box::pin(BufWriter::new(WritableChannel { write_tx }))); // Create readable stream let readable: Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>> = Box::pin(BufReader::new(ReadableChannel { read_rx, buffer: Bytes::new(), })); let (stream, sender, error_stream) = MCPStream::create( readable, writable, IoStream::Writable(Box::pin(tokio::io::stderr())), self.pending_requests.clone(), self.request_timeout, cancellation_token, ); self.set_message_sender(sender).await; if let IoStream::Readable(error_stream) = error_stream { self.set_error_stream(error_stream).await; } Ok(stream) } else { // Create CancellationTokenSource and token let (cancellation_source, cancellation_token) = CancellationTokenSource::new(); let mut lock = self.shutdown_source.write().await; *lock = Some(cancellation_source); // let (write_tx, mut write_rx) = mpsc::channel::<Bytes>(DEFAULT_CHANNEL_CAPACITY); let (write_tx, mut write_rx): ( tokio::sync::mpsc::Sender<( String, tokio::sync::oneshot::Sender<crate::error::TransportResult<()>>, )>, tokio::sync::mpsc::Receiver<( String, tokio::sync::oneshot::Sender<crate::error::TransportResult<()>>, )>, ) = tokio::sync::mpsc::channel(DEFAULT_CHANNEL_CAPACITY); // Buffer size as needed let (read_tx, read_rx) = mpsc::channel::<Bytes>(DEFAULT_CHANNEL_CAPACITY); let max_retries = self.max_retries; let retry_delay = self.retry_delay; let post_url = self.mcp_server_url.clone(); let custom_headers = self.custom_headers.clone(); let cancellation_token_post = cancellation_token.clone(); let cancellation_token_sse = cancellation_token.clone(); let session_id_clone = self.session_id.clone(); let mut streamable_http = StreamableHttpStream { client: self.client.clone(), mcp_url: post_url, max_retries, retry_delay, read_tx, session_id: session_id_clone, //Arc<RwLock<Option<String>>> }; // Initiate a task to process POST requests from messages received via the writable stream. let post_task_handle = tokio::spawn(async move { loop { tokio::select! { _ = cancellation_token_post.cancelled() => { break; }, data = write_rx.recv() => { match data{ Some((data, ack_tx)) => { // trim the trailing \n before making a request let payload = data.trim().to_string(); let result = streamable_http.run(payload, &cancellation_token_sse, &custom_headers).await; let _ = ack_tx.send(result);// Ignore error if receiver dropped }, None => break, // Exit if channel is closed } } } } }); let mut post_task_lock = self.post_task.write().await; *post_task_lock = Some(post_task_handle); // Create readable stream let readable: Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>> = Box::pin(BufReader::new(ReadableChannel { read_rx, buffer: Bytes::new(), })); let (stream, sender, error_stream) = MCPStream::create_with_ack( readable, write_tx, IoStream::Writable(Box::pin(tokio::io::stderr())), self.pending_requests.clone(), self.request_timeout, cancellation_token, ); self.set_message_sender(sender).await; if let IoStream::Readable(error_stream) = error_stream { self.set_error_stream(error_stream).await; } Ok(stream) } } fn message_sender(&self) -> Arc<tokio::sync::RwLock<Option<MessageDispatcher<M>>>> { self.message_sender.clone() as _ } fn error_stream(&self) -> &tokio::sync::RwLock<Option<IoStream>> { &self.error_stream as _ } async fn shut_down(&self) -> TransportResult<()> { // Trigger cancellation let mut cancellation_lock = self.shutdown_source.write().await; if let Some(source) = cancellation_lock.as_ref() { source.cancel()?; } *cancellation_lock = None; // Clear cancellation_source // Mark as shut down let mut is_shut_down_lock = self.is_shut_down.lock().await; *is_shut_down_lock = true; // Get task handle let post_task = self.post_task.write().await.take(); // // Wait for tasks to complete with a timeout let timeout = Duration::from_secs(SHUTDOWN_TIMEOUT_SECONDS); let shutdown_future = async { if let Some(post_handle) = post_task { let _ = post_handle.await; } Ok::<(), TransportError>(()) }; tokio::select! { result = shutdown_future => { result // result of task completion } _ = tokio::time::sleep(timeout) => { tracing::warn!("Shutdown timed out after {:?}", timeout); Err(TransportError::ShutdownTimeout) } } } async fn is_shut_down(&self) -> bool { let result = self.is_shut_down.lock().await; *result } async fn consume_string_payload(&self, _: &str) -> TransportResult<()> { Err(TransportError::Internal( "Invalid invocation of consume_string_payload() function for ClientStreamableTransport" .to_string(), )) } async fn pending_request_tx(&self, request_id: &RequestId) -> Option<Sender<M>> { let mut pending_requests = self.pending_requests.lock().await; pending_requests.remove(request_id) } async fn keep_alive( &self, _: Duration, _: oneshot::Sender<()>, ) -> TransportResult<JoinHandle<()>> { Err(TransportError::Internal( "Invalid invocation of keep_alive() function for ClientStreamableTransport".to_string(), )) } async fn session_id(&self) -> Option<SessionId> { let guard = self.session_id.read().await; guard.clone() } } #[async_trait] impl McpDispatch<ServerMessages, ClientMessages, ServerMessage, ClientMessage> for ClientStreamableTransport<ServerMessage> { async fn send_message( &self, message: ClientMessages, request_timeout: Option<Duration>, ) -> TransportResult<Option<ServerMessages>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_message(message, request_timeout).await } async fn send( &self, message: ClientMessage, request_timeout: Option<Duration>, ) -> TransportResult<Option<ServerMessage>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send(message, request_timeout).await } async fn send_batch( &self, message: Vec<ClientMessage>, request_timeout: Option<Duration>, ) -> TransportResult<Option<Vec<ServerMessage>>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_batch(message, request_timeout).await } async fn write_str(&self, payload: &str, skip_store: bool) -> TransportResult<()> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.write_str(payload, skip_store).await } } impl TransportDispatcher< ServerMessages, MessageFromClient, ServerMessage, ClientMessages, ClientMessage, > for ClientStreamableTransport<ServerMessage> { }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/sse.rs
crates/rust-mcp-transport/src/sse.rs
use crate::event_store::EventStore; use crate::schema::schema_utils::{ ClientMessage, ClientMessages, MessageFromServer, SdkError, ServerMessage, ServerMessages, }; use crate::schema::RequestId; use async_trait::async_trait; use serde::de::DeserializeOwned; use std::collections::HashMap; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; use tokio::io::{AsyncWriteExt, DuplexStream}; use tokio::sync::oneshot::Sender; use tokio::sync::{oneshot, Mutex}; use tokio::task::JoinHandle; use tokio::time::{self, Interval}; use crate::error::{TransportError, TransportResult}; use crate::mcp_stream::MCPStream; use crate::message_dispatcher::MessageDispatcher; use crate::transport::Transport; use crate::utils::{endpoint_with_session_id, CancellationTokenSource}; use crate::{IoStream, McpDispatch, SessionId, StreamId, TransportDispatcher, TransportOptions}; pub struct SseTransport<R> where R: Clone + Send + Sync + DeserializeOwned + 'static, { shutdown_source: tokio::sync::RwLock<Option<CancellationTokenSource>>, is_shut_down: Mutex<bool>, read_write_streams: Mutex<Option<(DuplexStream, DuplexStream)>>, receiver_tx: Mutex<DuplexStream>, // receiving string payload options: Arc<TransportOptions>, message_sender: Arc<tokio::sync::RwLock<Option<MessageDispatcher<R>>>>, error_stream: tokio::sync::RwLock<Option<IoStream>>, pending_requests: Arc<Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<R>>>>, // resumability support session_id: Option<SessionId>, stream_id: Option<StreamId>, event_store: Option<Arc<dyn EventStore>>, } /// Server-Sent Events (SSE) transport implementation impl<R> SseTransport<R> where R: Clone + Send + Sync + DeserializeOwned + 'static, { /// Creates a new SseTransport instance /// /// Initializes the transport with provided read and write duplex streams and options. /// /// # Arguments /// * `read_rx` - Duplex stream for receiving messages /// * `write_tx` - Duplex stream for sending messages /// * `receiver_tx` - Duplex stream for receiving string payload /// * `options` - Shared transport configuration options /// /// # Returns /// * `TransportResult<Self>` - The initialized transport or an error pub fn new( read_rx: DuplexStream, write_tx: DuplexStream, receiver_tx: DuplexStream, options: Arc<TransportOptions>, ) -> TransportResult<Self> { Ok(Self { read_write_streams: Mutex::new(Some((read_rx, write_tx))), options, shutdown_source: tokio::sync::RwLock::new(None), is_shut_down: Mutex::new(false), receiver_tx: Mutex::new(receiver_tx), message_sender: Arc::new(tokio::sync::RwLock::new(None)), error_stream: tokio::sync::RwLock::new(None), pending_requests: Arc::new(Mutex::new(HashMap::new())), session_id: None, stream_id: None, event_store: None, }) } pub fn message_endpoint(endpoint: &str, session_id: &SessionId) -> String { endpoint_with_session_id(endpoint, session_id) } pub(crate) async fn set_message_sender(&self, sender: MessageDispatcher<R>) { let mut lock = self.message_sender.write().await; *lock = Some(sender); } pub(crate) async fn set_error_stream( &self, error_stream: Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>, ) { let mut lock = self.error_stream.write().await; *lock = Some(IoStream::Writable(error_stream)); } /// Supports resumability for streamable HTTP transports by setting the session ID, /// stream ID, and event store. pub fn make_resumable( &mut self, session_id: SessionId, stream_id: StreamId, event_store: Arc<dyn EventStore>, ) { self.session_id = Some(session_id); self.stream_id = Some(stream_id); self.event_store = Some(event_store); } } #[async_trait] impl McpDispatch<ClientMessages, ServerMessages, ClientMessage, ServerMessage> for SseTransport<ClientMessage> { async fn send_message( &self, message: ServerMessages, request_timeout: Option<Duration>, ) -> TransportResult<Option<ClientMessages>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_message(message, request_timeout).await } async fn send( &self, message: ServerMessage, request_timeout: Option<Duration>, ) -> TransportResult<Option<ClientMessage>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send(message, request_timeout).await } async fn send_batch( &self, message: Vec<ServerMessage>, request_timeout: Option<Duration>, ) -> TransportResult<Option<Vec<ClientMessage>>> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.send_batch(message, request_timeout).await } async fn write_str(&self, payload: &str, skip_store: bool) -> TransportResult<()> { let sender = self.message_sender.read().await; let sender = sender.as_ref().ok_or(SdkError::connection_closed())?; sender.write_str(payload, skip_store).await } } #[async_trait] //RSMX impl Transport<ClientMessages, MessageFromServer, ClientMessage, ServerMessages, ServerMessage> for SseTransport<ClientMessage> { /// Starts the transport, initializing streams and message dispatcher /// /// Sets up the MCP stream and dispatcher using the provided duplex streams. /// /// # Returns /// * `TransportResult<(Pin<Box<dyn Stream<Item = R> + Send>>, MessageDispatcher<R>, IoStream)>` /// - The message stream, dispatcher, and error stream /// /// # Errors /// * Returns `TransportError` if streams are already taken or not initialized async fn start(&self) -> TransportResult<tokio_stream::wrappers::ReceiverStream<ClientMessages>> where MessageDispatcher<ClientMessage>: McpDispatch<ClientMessages, ServerMessages, ClientMessage, ServerMessage>, { // Create CancellationTokenSource and token let (cancellation_source, cancellation_token) = CancellationTokenSource::new(); let mut lock = self.shutdown_source.write().await; *lock = Some(cancellation_source); let mut lock = self.read_write_streams.lock().await; let (read_rx, write_tx) = lock.take().ok_or_else(|| { TransportError::Internal( "SSE streams already taken or transport not initialized".to_string(), ) })?; let (stream, mut sender, error_stream) = MCPStream::create::<ClientMessages, ClientMessage>( Box::pin(read_rx), Mutex::new(Box::pin(write_tx)), IoStream::Writable(Box::pin(tokio::io::stderr())), self.pending_requests.clone(), self.options.timeout, cancellation_token, ); if let (Some(session_id), Some(stream_id), Some(event_store)) = ( self.session_id.as_ref(), self.stream_id.as_ref(), self.event_store.as_ref(), ) { sender.make_resumable( session_id.to_owned(), stream_id.to_owned(), event_store.clone(), ); } self.set_message_sender(sender).await; if let IoStream::Writable(error_stream) = error_stream { self.set_error_stream(error_stream).await; } Ok(stream) } /// Checks if the transport has been shut down /// /// # Returns /// * `bool` - True if the transport is shut down, false otherwise async fn is_shut_down(&self) -> bool { let result = self.is_shut_down.lock().await; *result } fn message_sender(&self) -> Arc<tokio::sync::RwLock<Option<MessageDispatcher<ClientMessage>>>> { self.message_sender.clone() as _ } fn error_stream(&self) -> &tokio::sync::RwLock<Option<IoStream>> { &self.error_stream as _ } async fn consume_string_payload(&self, payload: &str) -> TransportResult<()> { let mut transmit = self.receiver_tx.lock().await; transmit .write_all(format!("{payload}\n").as_bytes()) .await?; transmit.flush().await?; Ok(()) } /// Shuts down the transport, terminating tasks and signaling closure /// /// Cancels any running tasks and clears the cancellation source. /// /// # Returns /// * `TransportResult<()>` - Ok if shutdown is successful, Err if cancellation fails async fn shut_down(&self) -> TransportResult<()> { // Trigger cancellation let mut cancellation_lock = self.shutdown_source.write().await; if let Some(source) = cancellation_lock.as_ref() { source.cancel()?; } *cancellation_lock = None; // Clear cancellation_source // Mark as shut down let mut is_shut_down_lock = self.is_shut_down.lock().await; *is_shut_down_lock = true; Ok(()) } async fn keep_alive( &self, interval: Duration, disconnect_tx: oneshot::Sender<()>, ) -> TransportResult<JoinHandle<()>> { let sender = self.message_sender(); let handle = tokio::spawn(async move { let mut interval: Interval = time::interval(interval); interval.tick().await; // Skip the first immediate tick loop { interval.tick().await; let sender = sender.read().await; if let Some(sender) = sender.as_ref() { match sender.write_str("\n", true).await { Ok(_) => {} Err(TransportError::Io(error)) => { if error.kind() == std::io::ErrorKind::BrokenPipe { let _ = disconnect_tx.send(()); break; } } _ => {} } } } }); Ok(handle) } async fn pending_request_tx(&self, request_id: &RequestId) -> Option<Sender<ClientMessage>> { let mut pending_requests = self.pending_requests.lock().await; pending_requests.remove(request_id) } } impl TransportDispatcher< ClientMessages, MessageFromServer, ClientMessage, ServerMessages, ServerMessage, > for SseTransport<ClientMessage> { }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/http_utils.rs
crates/rust-mcp-transport/src/utils/http_utils.rs
use crate::error::{TransportError, TransportResult}; use crate::{SessionId, MCP_SESSION_ID_HEADER}; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, ACCEPT, CONTENT_TYPE}; use reqwest::{Client, Response}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ResponseType { EventStream, Json, } /// Determines the response type based on the `Content-Type` header. pub async fn validate_response_type(response: &Response) -> TransportResult<ResponseType> { match response.headers().get(reqwest::header::CONTENT_TYPE) { Some(content_type) => { let content_type_str = content_type.to_str().map_err(|_| { TransportError::UnexpectedContentType("<invalid UTF-8>".to_string()) })?; // Normalize to lowercase for case-insensitive comparison let content_type_normalized = content_type_str.to_ascii_lowercase(); match content_type_normalized.as_str() { "text/event-stream" => Ok(ResponseType::EventStream), "application/json" => Ok(ResponseType::Json), other => Err(TransportError::UnexpectedContentType(other.to_string())), } } None => Err(TransportError::UnexpectedContentType("<empty>".to_string())), } } /// Sends an HTTP POST request with the given body and headers /// /// # Arguments /// * `client` - The HTTP client to use /// * `post_url` - The URL to send the POST request to /// * `body` - The JSON body as a string /// * `headers` - Optional custom headers /// /// # Returns /// * `TransportResult<()>` - Ok if the request is successful, Err otherwise pub async fn http_post( client: &Client, post_url: &str, body: String, session_id: Option<&SessionId>, headers: Option<&HeaderMap>, ) -> TransportResult<Response> { let mut request = client .post(post_url) .header(CONTENT_TYPE, "application/json") .header(ACCEPT, "application/json, text/event-stream") .body(body); if let Some(map) = headers { request = request.headers(map.clone()); } if let Some(session_id) = session_id { request = request.header( MCP_SESSION_ID_HEADER, HeaderValue::from_str(session_id).unwrap(), ); } let response = request.send().await?; if !response.status().is_success() { return Err(TransportError::Http(response.status())); } Ok(response) } pub async fn http_get( client: &Client, url: &str, session_id: Option<&SessionId>, headers: Option<&HeaderMap>, ) -> TransportResult<Response> { let mut request = client .get(url) .header(CONTENT_TYPE, "application/json") .header(ACCEPT, "application/json, text/event-stream"); if let Some(map) = headers { request = request.headers(map.clone()); } if let Some(session_id) = session_id { request = request.header( MCP_SESSION_ID_HEADER, HeaderValue::from_str(session_id).unwrap(), ); } let response = request.send().await?; if !response.status().is_success() { return Err(TransportError::Http(response.status())); } Ok(response) } pub async fn http_delete( client: &Client, post_url: &str, session_id: Option<&SessionId>, headers: Option<&HeaderMap>, ) -> TransportResult<Response> { let mut request = client .delete(post_url) .header(CONTENT_TYPE, "application/json") .header(ACCEPT, "application/json, text/event-stream"); if let Some(map) = headers { request = request.headers(map.clone()); } if let Some(session_id) = session_id { request = request.header( MCP_SESSION_ID_HEADER, HeaderValue::from_str(session_id).unwrap(), ); } let response = request.send().await?; if !response.status().is_success() { let status_code = response.status(); return Err(TransportError::Http(status_code)); } Ok(response) } #[allow(unused)] pub fn get_header_value(response: &Response, header_name: HeaderName) -> Option<String> { let content_type = response.headers().get(header_name)?.to_str().ok()?; Some(content_type.to_string()) } pub fn extract_origin(url: &str) -> Option<String> { // Remove the fragment first (everything after '#') let url = url.split('#').next()?; // Keep only part before `#` // Split scheme and the rest let (scheme, rest) = url.split_once("://")?; // Get host and optionally the port (before first '/') let end = rest.find('/').unwrap_or(rest.len()); let host_port = &rest[..end]; // Reconstruct origin Some(format!("{scheme}://{host_port}")) } #[cfg(test)] mod tests { use super::*; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use wiremock::{ matchers::{body_json_string, header, method, path}, Mock, MockServer, ResponseTemplate, }; /// Helper function to create custom headers for testing fn create_test_headers() -> HeaderMap { let mut headers = HeaderMap::new(); headers.insert( HeaderName::from_static("x-custom-header"), HeaderValue::from_static("test-value"), ); headers } #[tokio::test] async fn test_http_post_success() { // Start a mock server let mock_server = MockServer::start().await; // Mock a successful POST response Mock::given(method("POST")) .and(path("/test")) .and(header("Content-Type", "application/json")) .and(body_json_string(r#"{"key":"value"}"#)) .respond_with(ResponseTemplate::new(200)) .mount(&mock_server) .await; let client = Client::new(); let url = format!("{}/test", mock_server.uri()); let body = r#"{"key":"value"}"#.to_string(); let headers = None; // Perform the POST request let result = http_post(&client, &url, body, None, headers.as_ref()).await; // Assert the result is Ok assert!(result.is_ok()); } #[tokio::test] async fn test_http_post_non_success_status() { // Start a mock server let mock_server = MockServer::start().await; // Mock a 400 Bad Request response Mock::given(method("POST")) .and(path("/test")) .and(header("Content-Type", "application/json")) .respond_with(ResponseTemplate::new(400)) .mount(&mock_server) .await; let client = Client::new(); let url = format!("{}/test", mock_server.uri()); let body = r#"{"key":"value"}"#.to_string(); let headers = None; // Perform the POST request let result = http_post(&client, &url, body, None, headers.as_ref()).await; // Assert the result is an HttpError with status 400 match result { Err(TransportError::Http(status)) => assert_eq!(status, 400), _ => panic!("Expected HttpError with status 400"), } } #[tokio::test] async fn test_http_post_with_custom_headers() { // Start a mock server let mock_server = MockServer::start().await; // Mock a successful POST response with custom header Mock::given(method("POST")) .and(path("/test")) .and(header("Content-Type", "application/json")) .and(header("x-custom-header", "test-value")) .respond_with(ResponseTemplate::new(200)) .mount(&mock_server) .await; let client = Client::new(); let url = format!("{}/test", mock_server.uri()); let body = r#"{"key":"value"}"#.to_string(); let headers = Some(create_test_headers()); // Perform the POST request let result = http_post(&client, &url, body, None, headers.as_ref()).await; // Assert the result is Ok assert!(result.is_ok()); } #[tokio::test] async fn test_http_post_network_error() { // Use an invalid URL to simulate a network error let client = Client::new(); let url = "http://localhost:9999/test"; // Assuming no server is running on this port let body = r#"{"key":"value"}"#.to_string(); let headers = None; // Perform the POST request let result = http_post(&client, url, body, None, headers.as_ref()).await; // Assert the result is an error (likely a connection error) assert!(result.is_err()); } #[test] fn test_extract_origin_with_path() { let url = "https://example.com:8080/some/path"; assert_eq!( extract_origin(url), Some("https://example.com:8080".to_string()) ); } #[test] fn test_extract_origin_without_path() { let url = "https://example.com"; assert_eq!(extract_origin(url), Some("https://example.com".to_string())); } #[test] fn test_extract_origin_with_fragment() { let url = "https://example.com:8080/path#section"; assert_eq!( extract_origin(url), Some("https://example.com:8080".to_string()) ); } #[test] fn test_extract_origin_invalid_url() { let url = "example.com/path"; assert_eq!(extract_origin(url), None); } #[test] fn test_extract_origin_empty_string() { assert_eq!(extract_origin(""), None); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/time_utils.rs
crates/rust-mcp-transport/src/utils/time_utils.rs
use std::time::{SystemTime, UNIX_EPOCH}; pub fn current_timestamp() -> u128 { SystemTime::now() .duration_since(UNIX_EPOCH) .expect("Invalid time") .as_nanos() }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/sse_event.rs
crates/rust-mcp-transport/src/utils/sse_event.rs
use bytes::Bytes; use core::fmt; /// Represents a single Server-Sent Event (SSE) as defined in the SSE protocol. /// /// Contains the event type, data payload, and optional event ID. #[derive(Clone, Default)] pub struct SseEvent { /// The optional event type (e.g., "message"). pub event: Option<String>, /// The optional data payload of the event, stored as bytes. pub data: Option<Bytes>, /// The optional event ID for reconnection or tracking purposes. pub id: Option<String>, /// Optional reconnection retry interval (in milliseconds). pub retry: Option<u64>, } impl SseEvent { /// Creates a new `SseEvent` with the given string data. pub fn new<T: Into<String>>(data: T) -> Self { Self { event: None, data: Some(Bytes::from(data.into())), id: None, retry: None, } } /// Sets the event name (e.g., "message"). pub fn with_event<T: Into<String>>(mut self, event: T) -> Self { self.event = Some(event.into()); self } /// Sets the ID of the event. pub fn with_id<T: Into<String>>(mut self, id: T) -> Self { self.id = Some(id.into()); self } /// Sets the retry interval (in milliseconds). pub fn with_retry(mut self, retry: u64) -> Self { self.retry = Some(retry); self } /// Sets the data as bytes. pub fn with_data_bytes(mut self, data: Bytes) -> Self { self.data = Some(data); self } /// Sets the data. pub fn with_data(mut self, data: String) -> Self { self.data = Some(Bytes::from(data)); self } /// Converts the event into a string in SSE format (ready for HTTP body). pub fn to_sse_string(&self) -> String { self.to_string() } pub fn as_bytes(&self) -> Bytes { Bytes::from(self.to_string()) } } impl std::fmt::Display for SseEvent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Emit retry interval if let Some(retry) = self.retry { writeln!(f, "retry: {retry}")?; } // Emit ID if let Some(id) = &self.id { writeln!(f, "id: {id}")?; } // Emit event type if let Some(event) = &self.event { writeln!(f, "event: {event}")?; } // Emit data lines if let Some(data) = &self.data { match std::str::from_utf8(data) { Ok(text) => { for line in text.lines() { writeln!(f, "data: {line}")?; } } Err(_) => { writeln!(f, "data: [binary data]")?; } } } writeln!(f)?; // Trailing newline for SSE message end, separates events Ok(()) } } impl fmt::Debug for SseEvent { /// Formats the `SseEvent` for debugging, converting the `data` field to a UTF-8 string /// (with lossy conversion if invalid UTF-8 is encountered). fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data_str = self .data .as_ref() .map(|b| String::from_utf8_lossy(b).to_string()); f.debug_struct("SseEvent") .field("event", &self.event) .field("data", &data_str) .field("id", &self.id) .field("retry", &self.retry) .finish() } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/sse_stream.rs
crates/rust-mcp-transport/src/utils/sse_stream.rs
use bytes::{Bytes, BytesMut}; use reqwest::header::{HeaderMap, HeaderValue, ACCEPT}; use reqwest::Client; use std::time::Duration; use tokio::sync::{mpsc, oneshot}; use tokio::time; use tokio_stream::StreamExt; use super::CancellationToken; const BUFFER_CAPACITY: usize = 1024; const ENDPOINT_SSE_EVENT: &str = "endpoint"; /// Server-Sent Events (SSE) stream handler /// /// Manages an SSE connection, handling reconnection logic and streaming data to a channel. pub(crate) struct SseStream { /// HTTP client for making SSE requests pub sse_client: Client, /// URL of the SSE endpoint pub sse_url: String, /// Maximum number of retry attempts for failed connections pub max_retries: usize, /// Delay between retry attempts pub retry_delay: Duration, /// Sender for transmitting received data to the readable channel pub read_tx: mpsc::Sender<Bytes>, } impl SseStream { /// Runs the SSE stream, processing incoming events and handling reconnections /// /// Continuously attempts to connect to the SSE endpoint in case connection is lost, processes incoming data, /// and sends it to the read channel. Handles retries and cancellation. /// /// # Arguments /// * `endpoint_event_tx` - Optional one-shot sender for the messages endpoint /// * `cancellation_token` - Token for monitoring cancellation requests pub(crate) async fn run( &self, mut endpoint_event_tx: Option<oneshot::Sender<Option<String>>>, cancellation_token: CancellationToken, custom_headers: &Option<HeaderMap>, ) { let mut retry_count = 0; let mut buffer = BytesMut::with_capacity(BUFFER_CAPACITY); let mut endpoint_event_received = false; let mut request_headers: HeaderMap = custom_headers.to_owned().unwrap_or_default(); request_headers.insert(ACCEPT, HeaderValue::from_static("text/event-stream")); // Main loop for reconnection attempts loop { // Check for cancellation before attempting connection if cancellation_token.is_cancelled() { tracing::info!("SSE cancelled before connection attempt"); return; } // Send GET request to the SSE endpoint let response = match self .sse_client .get(&self.sse_url) .headers(request_headers.clone()) .send() .await { Ok(resp) => resp, Err(e) => { tracing::error!("Failed to connect to SSE: {e}"); if retry_count >= self.max_retries { tracing::error!("Max retries reached, giving up"); if let Some(tx) = endpoint_event_tx.take() { let _ = tx.send(None); } return; } retry_count += 1; time::sleep(self.retry_delay).await; continue; } }; // Create a stream from the response bytes let mut stream = response.bytes_stream(); // Inner loop for processing stream chunks loop { let next_chunk = tokio::select! { // Wait for the next stream chunk chunk = stream.next() => { match chunk { Some(chunk) => chunk, None => { if retry_count >= self.max_retries { tracing::error!("Max retries ({}) reached, giving up",self.max_retries); if let Some(tx) = endpoint_event_tx.take() { let _ = tx.send(None); } return; } retry_count += 1; time::sleep(self.retry_delay).await; break; // Stream ended, break from inner loop to reconnect } } } // Wait for cancellation _ = cancellation_token.cancelled() => { return; } }; match next_chunk { Ok(bytes) => { buffer.extend_from_slice(&bytes); let mut batch = Vec::new(); // collect complete lines for processing while let Some(pos) = buffer.iter().position(|&b| b == b'\n') { let line = buffer.split_to(pos + 1).freeze(); // Skip empty lines if line.len() > 1 { batch.push(line); } } let mut current_event: Option<String> = None; // Process complete lines for line in batch { // Parse line as UTF-8, keep the trailing newline let line_str = String::from_utf8_lossy(&line); if let Some(event_name) = line_str.strip_prefix("event: ") { current_event = Some(event_name.trim().to_string()); continue; } // Extract content after data: or : let content = if let Some(data) = line_str.strip_prefix("data: ") { let payload = data.trim_start(); if !endpoint_event_received { if let Some(ENDPOINT_SSE_EVENT) = current_event.as_deref() { if let Some(tx) = endpoint_event_tx.take() { endpoint_event_received = true; let _ = tx.send(Some(payload.trim().to_owned())); continue; } } } payload } else if let Some(comment) = line_str.strip_prefix(":") { comment.trim_start() } else { continue; }; if !content.is_empty() { let bytes = Bytes::copy_from_slice(content.as_bytes()); if self.read_tx.send(bytes).await.is_err() { tracing::error!( "Readable stream closed, shutting down SSE task" ); if !endpoint_event_received { if let Some(tx) = endpoint_event_tx.take() { let _ = tx.send(None); } } return; } } } retry_count = 0; // Reset retry count on successful chunk } Err(e) => { tracing::error!("SSE stream error: {}", e); if retry_count >= self.max_retries { tracing::error!("Max retries reached, giving up"); if !endpoint_event_received { if let Some(tx) = endpoint_event_tx.take() { let _ = tx.send(None); } } return; } retry_count += 1; time::sleep(self.retry_delay).await; break; // Break inner loop to reconnect } } } } } } #[cfg(test)] mod tests { use super::*; use crate::utils::CancellationTokenSource; use reqwest::header::{HeaderMap, HeaderValue}; use tokio::time::Duration; use wiremock::matchers::{header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; #[tokio::test] async fn test_sse_client_sends_custom_headers_on_connection() { // Start WireMock server let mock_server = MockServer::builder().start().await; // Create WireMock stub with connection close Mock::given(method("GET")) .and(path("/sse")) .and(header("Accept", "text/event-stream")) .and(header("X-Custom-Header", "CustomValue")) .respond_with( ResponseTemplate::new(200) .set_body_string("event: endpoint\ndata: mock-endpoint\n\n") .append_header("Content-Type", "text/event-stream") .append_header("Connection", "close"), // Ensure connection closes ) .expect(1) // Expect exactly one request .mount(&mock_server) .await; // Create custom headers let mut custom_headers = HeaderMap::new(); custom_headers.insert("X-Custom-Header", HeaderValue::from_static("CustomValue")); // Create channel and SseStream let (read_tx, _read_rx) = mpsc::channel::<Bytes>(64); let sse = SseStream { sse_client: reqwest::Client::new(), sse_url: format!("{}/sse", mock_server.uri()), max_retries: 0, // to receive one request only retry_delay: Duration::from_millis(100), read_tx, }; // Create cancellation token and endpoint channel let (cancellation_source, cancellation_token) = CancellationTokenSource::new(); let (endpoint_event_tx, endpoint_event_rx) = oneshot::channel::<Option<String>>(); // Spawn the run method let sse_task = tokio::spawn({ async move { sse.run( Some(endpoint_event_tx), cancellation_token, &Some(custom_headers), ) .await; } }); // Wait for the endpoint event or timeout let event_result = tokio::time::timeout(Duration::from_millis(500), endpoint_event_rx).await; // Cancel the task to ensure loop exits let _ = cancellation_source.cancel(); // Wait for the task to complete with a timeout match tokio::time::timeout(Duration::from_secs(1), sse_task).await { Ok(result) => result.unwrap(), Err(_) => panic!("Test timed out after 1 second"), } // Verify the endpoint event was received match event_result { Ok(Ok(Some(event))) => assert_eq!(event, "mock-endpoint", "Expected endpoint event"), _ => panic!("Did not receive expected endpoint event"), } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/cancellation_token.rs
crates/rust-mcp-transport/src/utils/cancellation_token.rs
use std::sync::Arc; use tokio::sync::watch; /// Error type for cancellation operations /// /// Defines possible errors that can occur during cancellation, such as a closed channel. #[derive(Debug, thiserror::Error)] pub enum CancellationError { #[error("Cancellation channel closed")] ChannelClosed, } /// Token used by tasks to check or await cancellation /// /// Holds a receiver for a watch channel to monitor cancellation status. /// The struct is cloneable to allow multiple tasks to share the same token. #[derive(Clone)] pub struct CancellationToken { receiver: watch::Receiver<bool>, } /// Source that controls cancellation /// /// Manages the sender side of a watch channel to signal cancellation to associated tokens. pub struct CancellationTokenSource { sender: Arc<watch::Sender<bool>>, } impl CancellationTokenSource { /// Creates a new CancellationTokenSource and its associated CancellationToken /// /// Initializes a watch channel with an initial value of `false` (not cancelled). /// /// # Returns /// * `(Self, CancellationToken)` - A tuple containing the source and its token pub fn new() -> (Self, CancellationToken) { let (sender, receiver) = watch::channel(false); ( CancellationTokenSource { sender: Arc::new(sender), }, CancellationToken { receiver }, ) } /// Triggers cancellation /// /// Sends a `true` value through the watch channel to signal cancellation to all tokens. /// /// # Returns /// * `Result<(), CancellationError>` - Ok if cancellation is sent, Err if the channel is closed pub fn cancel(&self) -> Result<(), CancellationError> { self.sender .send(true) .map_err(|_| CancellationError::ChannelClosed) } /// Creates a new CancellationToken linked to this source /// /// Subscribes a new receiver to the watch channel for monitoring cancellation. /// /// # Returns /// * `CancellationToken` - A new token linked to this source #[allow(unused)] pub fn token(&self) -> CancellationToken { CancellationToken { receiver: self.sender.subscribe(), } } } impl CancellationToken { /// Checks if cancellation is requested (non-blocking) /// /// # Returns /// * `bool` - True if cancellation is requested, false otherwise #[allow(unused)] pub fn is_cancelled(&self) -> bool { *self.receiver.borrow() } /// Asynchronously waits for cancellation /// /// Polls the watch channel until cancellation is signaled or the channel is closed. /// /// # Returns /// * `Result<(), CancellationError>` - Ok if cancellation is received, Err if the channel is closed pub async fn cancelled(&self) -> Result<(), CancellationError> { // Clone receiver to avoid mutating the original let mut receiver = self.receiver.clone(); // Poll until the value is true or the channel is closed loop { if *receiver.borrow() { return Ok(()); } // Wait for any change receiver .changed() .await .map_err(|_| CancellationError::ChannelClosed)?; } } } #[cfg(test)] mod tests { use super::*; use tokio::time::{timeout, Duration}; /// Test creating a source and token, verifying initial state #[tokio::test] async fn test_create_and_initial_state() { let (_source, token) = CancellationTokenSource::new(); // Verify initial state is not cancelled assert!(!token.is_cancelled()); // Verify token can be awaited without immediate cancellation let wait_result = timeout(Duration::from_millis(100), token.cancelled()).await; assert!( wait_result.is_err(), "Expected timeout as cancellation not triggered" ); } /// Test triggering cancellation and checking status #[tokio::test] async fn test_trigger_cancellation() { let (source, token) = CancellationTokenSource::new(); // Trigger cancellation let cancel_result = source.cancel(); assert!(cancel_result.is_ok(), "Expected successful cancellation"); // Verify token reflects cancelled state assert!(token.is_cancelled()); // Verify cancelled() completes immediately let wait_result = timeout(Duration::from_millis(100), token.cancelled()).await; assert!(wait_result.is_ok(), "Expected cancellation to complete"); assert!( wait_result.unwrap().is_ok(), "Expected Ok result from cancelled()" ); } /// Test awaiting cancellation asynchronously #[tokio::test] async fn test_await_cancellation() { let (source, token) = CancellationTokenSource::new(); // Spawn a task to trigger cancellation after a delay let source_clone = source; tokio::spawn(async move { tokio::time::sleep(Duration::from_millis(50)).await; let _ = source_clone.cancel(); }); // Await cancellation let wait_result = timeout(Duration::from_millis(200), token.cancelled()).await; assert!(wait_result.is_ok(), "Expected cancellation within timeout"); assert!( wait_result.unwrap().is_ok(), "Expected Ok result from cancelled()" ); assert!(token.is_cancelled(), "Expected token to be cancelled"); } /// Test multiple tokens receiving cancellation #[tokio::test] async fn test_multiple_tokens() { let (source, token1) = CancellationTokenSource::new(); let token2 = source.token(); let token3 = source.token(); // Verify all tokens start non-cancelled assert!(!token1.is_cancelled()); assert!(!token2.is_cancelled()); assert!(!token3.is_cancelled()); // Trigger cancellation source.cancel().expect("Failed to cancel"); // Verify all tokens reflect cancelled state assert!(token1.is_cancelled()); assert!(token2.is_cancelled()); assert!(token3.is_cancelled()); // Verify all tokens can await cancellation let wait1 = timeout(Duration::from_millis(100), token1.cancelled()).await; let wait2 = timeout(Duration::from_millis(100), token2.cancelled()).await; let wait3 = timeout(Duration::from_millis(100), token3.cancelled()).await; assert!( wait1.is_ok() && wait1.unwrap().is_ok(), "Token1 should complete cancellation" ); assert!( wait2.is_ok() && wait2.unwrap().is_ok(), "Token2 should complete cancellation" ); assert!( wait3.is_ok() && wait3.unwrap().is_ok(), "Token3 should complete cancellation" ); } /// Test channel closure by dropping the source #[tokio::test] async fn test_channel_closed_error() { let (source, token) = CancellationTokenSource::new(); // Drop the source to close the channel drop(source); // Attempt to await cancellation let wait_result = token.cancelled().await; assert!( matches!(wait_result, Err(CancellationError::ChannelClosed)), "Expected ChannelClosed error" ); // Verify token still reports non-cancelled (no signal received) assert!(!token.is_cancelled()); } /// Test creating a new token with the token() method #[tokio::test] async fn test_new_token_creation() { let (source, token1) = CancellationTokenSource::new(); let token2 = source.token(); // Verify both tokens start non-cancelled assert!(!token1.is_cancelled()); assert!(!token2.is_cancelled()); // Trigger cancellation source.cancel().expect("Failed to cancel"); // Verify both tokens reflect cancelled state assert!(token1.is_cancelled()); assert!(token2.is_cancelled()); // Verify both tokens can await cancellation let wait1 = timeout(Duration::from_millis(100), token1.cancelled()).await; let wait2 = timeout(Duration::from_millis(100), token2.cancelled()).await; assert!( wait1.is_ok() && wait1.unwrap().is_ok(), "Token1 should complete cancellation" ); assert!( wait2.is_ok() && wait2.unwrap().is_ok(), "Token2 should complete cancellation" ); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/sse_parser.rs
crates/rust-mcp-transport/src/utils/sse_parser.rs
use bytes::{Bytes, BytesMut}; use std::collections::HashMap; use super::SseEvent; const BUFFER_CAPACITY: usize = 1024; /// A parser for Server-Sent Events (SSE) that processes incoming byte chunks into `SseEvent`s. /// This Parser is specifically designed for MCP messages and with no multi-line data support /// /// This struct maintains a buffer to accumulate incoming data and parses it into SSE events /// based on the SSE protocol. It handles fields like `event`, `data`, and `id` as defined /// in the SSE specification. #[derive(Debug)] pub struct SseParser { pub buffer: BytesMut, } impl SseParser { /// Creates a new `SseParser` with an empty buffer pre-allocated to a default capacity. /// /// The buffer is initialized with a capacity of `BUFFER_CAPACITY` to /// optimize for typical SSE message sizes. /// /// # Returns /// A new `SseParser` instance with an empty buffer. pub fn new() -> Self { Self { buffer: BytesMut::with_capacity(BUFFER_CAPACITY), } } /// Processes a new chunk of bytes and parses it into a vector of `SseEvent`s. /// /// This method appends the incoming `bytes` to the internal buffer, splits it into /// complete lines (delimited by `\n`), and parses each line according to the SSE /// protocol. It supports `event`, `id`, and `data` fields, as well as comments /// (lines starting with `:`). Empty lines are skipped, and incomplete lines remain /// in the buffer for future processing. /// /// # Parameters /// - `bytes`: The incoming chunk of bytes to parse. /// /// # Returns /// A vector of `SseEvent`s parsed from the complete lines in the buffer. If no /// complete events are found, an empty vector is returned. pub fn process_new_chunk(&mut self, bytes: Bytes) -> Vec<SseEvent> { self.buffer.extend_from_slice(&bytes); // Collect complete lines (ending in \n)-keep ALL lines, including empty ones for \n\n detection let mut lines = Vec::new(); while let Some(pos) = self.buffer.iter().position(|&b| b == b'\n') { let line = self.buffer.split_to(pos + 1).freeze(); lines.push(line); } let mut events = Vec::new(); let mut current_message_lines: Vec<Bytes> = Vec::new(); for line in lines { current_message_lines.push(line); // Check if we've hit a double newline (end of message) if current_message_lines.len() >= 2 && current_message_lines .last() .is_some_and(|b| b.as_ref() == b"\n") { // Process the complete message (exclude the last empty lines for parsing) let message_lines: Vec<_> = current_message_lines .drain(..current_message_lines.len() - 1) .filter(|l| l.as_ref() != b"\n") // Filter internal empties .collect(); if let Some(event) = self.parse_sse_message(&message_lines) { events.push(event); } } } // Put back any incomplete message if !current_message_lines.is_empty() { self.buffer.clear(); for line in current_message_lines { self.buffer.extend_from_slice(&line); } } events } fn parse_sse_message(&self, lines: &[Bytes]) -> Option<SseEvent> { let mut fields: HashMap<String, String> = HashMap::new(); let mut data_parts: Vec<String> = Vec::new(); for line_bytes in lines { let line_str = String::from_utf8_lossy(line_bytes); // Skip comments and empty lines if line_str.is_empty() || line_str.starts_with(':') { continue; } let (key, value) = if let Some(value) = line_str.strip_prefix("data: ") { ("data", value.trim_start().to_string()) } else if let Some(value) = line_str.strip_prefix("event: ") { ("event", value.trim().to_string()) } else if let Some(value) = line_str.strip_prefix("id: ") { ("id", value.trim().to_string()) } else if let Some(value) = line_str.strip_prefix("retry: ") { ("retry", value.trim().to_string()) } else { // Invalid line; skip continue; }; if key == "data" { if !value.is_empty() { data_parts.push(value); } } else { fields.insert(key.to_string(), value); } } // Build data (concat multi-line data with \n) , should not occur in MCP tho let data = if data_parts.is_empty() { None } else { let full_data = data_parts.join("\n"); Some(Bytes::copy_from_slice(full_data.as_bytes())) // Use copy_from_slice for efficiency }; // Skip invalid message with no data let data = data?; // Get event (default to None) let event = fields.get("event").cloned(); let id = fields.get("id").cloned(); let retry = fields .get("retry") .and_then(|r| r.trim().parse::<u64>().ok()); Some(SseEvent { event, data: Some(data), id, retry, }) } } #[cfg(test)] mod tests { use super::*; use bytes::Bytes; #[test] fn test_single_data_event() { let mut parser = SseParser::new(); let input = Bytes::from("data: hello\n\n"); let events = parser.process_new_chunk(input); assert_eq!(events.len(), 1); assert_eq!( events[0].data.as_deref(), Some(Bytes::from("hello\n").as_ref()) ); assert!(events[0].event.is_none()); assert!(events[0].id.is_none()); } #[test] fn test_event_with_id_and_data() { let mut parser = SseParser::new(); let input = Bytes::from("event: message\nid: 123\ndata: hello\n\n"); let events = parser.process_new_chunk(input); assert_eq!(events.len(), 1); assert_eq!(events[0].event.as_deref(), Some("message")); assert_eq!(events[0].id.as_deref(), Some("123")); assert_eq!( events[0].data.as_deref(), Some(Bytes::from("hello\n").as_ref()) ); } #[test] fn test_event_chunks_in_different_orders() { let mut parser = SseParser::new(); let input = Bytes::from("data: hello\nevent: message\nid: 123\n\n"); let events = parser.process_new_chunk(input); assert_eq!(events.len(), 1); assert_eq!(events[0].event.as_deref(), Some("message")); assert_eq!(events[0].id.as_deref(), Some("123")); assert_eq!( events[0].data.as_deref(), Some(Bytes::from("hello\n").as_ref()) ); } #[test] fn test_comment_line_ignored() { let mut parser = SseParser::new(); let input = Bytes::from(": this is a comment\n\n"); let events = parser.process_new_chunk(input); assert_eq!(events.len(), 0); } #[test] fn test_event_with_empty_data() { let mut parser = SseParser::new(); let input = Bytes::from("data:\n\n"); let events = parser.process_new_chunk(input); // Your parser skips data lines with empty content assert_eq!(events.len(), 0); } #[test] fn test_partial_chunks() { let mut parser = SseParser::new(); let part1 = Bytes::from("data: hello"); let part2 = Bytes::from(" world\n\n"); let events1 = parser.process_new_chunk(part1); assert_eq!(events1.len(), 0); // incomplete let events2 = parser.process_new_chunk(part2); assert_eq!(events2.len(), 1); assert_eq!( events2[0].data.as_deref(), Some(Bytes::from("hello world\n").as_ref()) ); } #[test] fn test_malformed_lines() { let mut parser = SseParser::new(); let input = Bytes::from("something invalid\ndata: ok\n\n"); let events = parser.process_new_chunk(input); assert_eq!(events.len(), 1); assert_eq!( events[0].data.as_deref(), Some(Bytes::from("ok\n").as_ref()) ); } #[test] fn test_multiple_events_in_one_chunk() { let mut parser = SseParser::new(); let input = Bytes::from("data: first\n\ndata: second\n\n"); let events = parser.process_new_chunk(input); assert_eq!(events.len(), 2); assert_eq!( events[0].data.as_deref(), Some(Bytes::from("first\n").as_ref()) ); assert_eq!( events[1].data.as_deref(), Some(Bytes::from("second\n").as_ref()) ); } #[test] fn test_basic_sse_event() { let mut parser = SseParser::new(); let input = Bytes::from("event: message\ndata: Hello\nid: 1\nretry: 5000\n\n"); let events = parser.process_new_chunk(input); assert_eq!(events.len(), 1); let event = &events[0]; assert_eq!(event.event.as_deref(), Some("message")); assert_eq!(event.data.as_deref(), Some(Bytes::from("Hello\n").as_ref())); assert_eq!(event.id.as_deref(), Some("1")); assert_eq!(event.retry, Some(5000)); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/writable_channel.rs
crates/rust-mcp-transport/src/utils/writable_channel.rs
use bytes::Bytes; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::io::{self, AsyncWrite, ErrorKind}; use tokio::sync::mpsc; /// A writable channel for asynchronous byte stream writing /// /// Wraps a Tokio mpsc sender to provide an AsyncWrite implementation, /// enabling asynchronous writing of byte data to a channel. pub(crate) struct WritableChannel { pub write_tx: mpsc::Sender<Bytes>, } impl AsyncWrite for WritableChannel { /// Polls the channel to write data /// /// Attempts to send the provided buffer through the mpsc channel. /// If the channel is full, spawns a task to send the data asynchronously /// and notifies the waker upon completion. /// /// # Arguments /// * `self` - Pinned mutable reference to the WritableChannel /// * `cx` - Task context for polling /// * `buf` - Data buffer to write /// /// # Returns /// * `Poll<io::Result<usize>>` - Ready with the number of bytes written if successful, /// Ready with an error if the channel is closed, or Pending if the channel is full fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { let write_tx = self.write_tx.clone(); let bytes = Bytes::copy_from_slice(buf); match write_tx.try_send(bytes.clone()) { Ok(()) => Poll::Ready(Ok(buf.len())), Err(mpsc::error::TrySendError::Full(_)) => { let waker = cx.waker().clone(); tokio::spawn(async move { if write_tx.send(bytes).await.is_ok() { waker.wake(); } }); Poll::Pending } Err(mpsc::error::TrySendError::Closed(_)) => Poll::Ready(Err(std::io::Error::new( ErrorKind::BrokenPipe, "Channel closed", ))), } } /// Polls to flush the channel /// /// Since the channel does not buffer data internally, this is a no-op. /// /// # Arguments /// * `self` - Pinned mutable reference to the WritableChannel /// * `_cx` - Task context for polling (unused) /// /// # Returns /// * `Poll<io::Result<()>>` - Always Ready with Ok fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(Ok(())) } /// Polls to shut down the channel /// /// Since the channel does not require explicit shutdown, this is a no-op. /// /// # Arguments /// * `self` - Pinned mutable reference to the WritableChannel /// * `_cx` - Task context for polling (unused) /// /// # Returns /// * `Poll<io::Result<()>>` - Always Ready with Ok fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(Ok(())) } } #[cfg(test)] mod tests { use super::WritableChannel; use bytes::Bytes; use tokio::io::{AsyncWriteExt, ErrorKind}; use tokio::sync::mpsc; #[tokio::test] async fn test_write_successful() { let (tx, mut rx) = mpsc::channel(1); let mut writer = WritableChannel { write_tx: tx }; let data = b"hello world"; let n = writer.write(data).await.unwrap(); assert_eq!(n, data.len()); let received = rx.recv().await.unwrap(); assert_eq!(received, Bytes::from_static(data)); } #[tokio::test] async fn test_write_when_channel_full() { let (tx, mut rx) = mpsc::channel(1); // Pre-fill the channel to make it full tx.send(Bytes::from_static(b"pre-filled")).await.unwrap(); let mut writer = WritableChannel { write_tx: tx }; let data = b"deferred"; // Start the write, which will hit "Full" and spawn a task let write_future = writer.write(data); // Drain the channel to make space let _ = rx.recv().await; // Await the write now that there's space let n = write_future.await.unwrap(); assert_eq!(n, data.len()); let received = rx.recv().await.unwrap(); assert_eq!(received, Bytes::from_static(data)); } #[tokio::test] async fn test_write_after_channel_closed() { let (tx, rx) = mpsc::channel(1); drop(rx); // simulate the receiver being dropped (channel is closed) let mut writer = WritableChannel { write_tx: tx }; let result = writer.write(b"data").await; assert!(result.is_err()); let err = result.unwrap_err(); assert_eq!(err.kind(), ErrorKind::BrokenPipe); } #[tokio::test] async fn test_poll_flush_and_shutdown() { let (tx, _rx) = mpsc::channel(1); let mut writer = WritableChannel { write_tx: tx }; // These are no-ops, just ensure they return Ok writer.flush().await.unwrap(); writer.shutdown().await.unwrap(); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/streamable_http_stream.rs
crates/rust-mcp-transport/src/utils/streamable_http_stream.rs
use super::CancellationToken; use crate::error::{TransportError, TransportResult}; use crate::utils::SseParser; use crate::utils::{http_get, validate_response_type, ResponseType}; use crate::{utils::http_post, MCP_SESSION_ID_HEADER}; use crate::{EventId, MCP_LAST_EVENT_ID_HEADER}; use bytes::Bytes; use reqwest::header::{HeaderMap, HeaderValue}; use reqwest::{Client, Response, StatusCode}; use std::sync::Arc; use std::time::Duration; use tokio::sync::{mpsc, RwLock}; use tokio::time; use tokio_stream::StreamExt; //-----------------------------------------------------------------------------------// pub(crate) struct StreamableHttpStream { /// HTTP client for making SSE requests pub client: Client, /// URL of the SSE endpoint pub mcp_url: String, /// Maximum number of retry attempts for failed connections pub max_retries: usize, /// Delay between retry attempts pub retry_delay: Duration, /// Sender for transmitting received data to the readable channel pub read_tx: mpsc::Sender<Bytes>, /// Session id will be received from the server in the http pub session_id: Arc<RwLock<Option<String>>>, } impl StreamableHttpStream { pub(crate) async fn run( &mut self, payload: String, cancellation_token: &CancellationToken, custom_headers: &Option<HeaderMap>, ) -> TransportResult<()> { let mut stream_parser = SseParser::new(); let mut _last_event_id: Option<EventId> = None; let session_id = self.session_id.read().await.clone(); // Check for cancellation before attempting connection if cancellation_token.is_cancelled() { tracing::info!( "StreamableHttp cancelled before connection attempt {}", payload ); return Err(TransportError::Cancelled( crate::utils::CancellationError::ChannelClosed, )); } //TODO: simplify let response = match http_post( &self.client, &self.mcp_url, payload.to_string(), session_id.as_ref(), custom_headers.as_ref(), ) .await { Ok(response) => { // if session_id_clone.read().await.is_none() { let session_id = response .headers() .get(MCP_SESSION_ID_HEADER) .and_then(|value| value.to_str().ok()) .map(|s| s.to_string()); let mut guard = self.session_id.write().await; *guard = session_id; response } Err(error) => { tracing::error!("Failed to connect to MCP endpoint: {error}"); return Err(error); } }; // return if status code != 200 and no result is expected if response.status() != StatusCode::OK { return Ok(()); } let response_type = validate_response_type(&response).await?; // Handle non-streaming JSON response if response_type == ResponseType::Json { return match response.bytes().await { Ok(bytes) => { // Send the message self.read_tx.send(bytes).await.map_err(|_| { tracing::error!("Readable stream closed, shutting down MCP task"); TransportError::SendFailure( "Failed to send message: channel closed or full".to_string(), ) })?; // Send the newline self.read_tx .send(Bytes::from_static(b"\n")) .await .map_err(|_| { tracing::error!( "Failed to send newline, channel may be closed or full" ); TransportError::SendFailure( "Failed to send newline: channel closed or full".to_string(), ) })?; Ok(()) } Err(error) => Err(error.into()), }; } // Create a stream from the response bytes let mut stream = response.bytes_stream(); // Inner loop for processing stream chunks loop { let next_chunk = tokio::select! { // Wait for the next stream chunk chunk = stream.next() => { match chunk { Some(chunk) => chunk, None => { // stream ended, unlike SSE, so no retry attempt here needed to reconnect return Err(TransportError::Internal("Stream has ended.".to_string())); } } } // Wait for cancellation _ = cancellation_token.cancelled() => { return Err(TransportError::Cancelled( crate::utils::CancellationError::ChannelClosed, )); } }; match next_chunk { Ok(bytes) => { let events = stream_parser.process_new_chunk(bytes); if !events.is_empty() { for event in events { if let Some(bytes) = event.data { if event.id.is_some() { _last_event_id = event.id.clone(); } if self.read_tx.send(bytes).await.is_err() { tracing::error!( "Readable stream closed, shutting down MCP task" ); return Err(TransportError::SendFailure( "Failed to send message: stream closed".to_string(), )); } } } // break after receiving the message(s) return Ok(()); } } Err(error) => { tracing::error!("Error reading stream: {error}"); return Err(error.into()); } } } } pub(crate) async fn make_standalone_stream_connection( &self, cancellation_token: &CancellationToken, custom_headers: &Option<HeaderMap>, last_event_id: Option<EventId>, ) -> TransportResult<reqwest::Response> { let mut retry_count = 0; let session_id = self.session_id.read().await.clone(); let headers = if let Some(event_id) = last_event_id.as_ref() { let mut headers = HeaderMap::new(); if let Some(custom) = custom_headers { headers.extend(custom.iter().map(|(k, v)| (k.clone(), v.clone()))); } if let Ok(event_id_value) = HeaderValue::from_str(event_id) { headers.insert(MCP_LAST_EVENT_ID_HEADER, event_id_value); } &Some(headers) } else { custom_headers }; loop { // Check for cancellation before attempting connection if cancellation_token.is_cancelled() { tracing::info!("Standalone StreamableHttp cancelled."); return Err(TransportError::Cancelled( crate::utils::CancellationError::ChannelClosed, )); } match http_get( &self.client, &self.mcp_url, session_id.as_ref(), headers.as_ref(), ) .await { Ok(response) => { let is_event_stream = validate_response_type(&response) .await .is_ok_and(|response_type| response_type == ResponseType::EventStream); if !is_event_stream { let message = "SSE stream response returned an unexpected Content-Type.".to_string(); tracing::warn!("{message}"); return Err(TransportError::FailedToOpenSSEStream(message)); } return Ok(response); } Err(error) => { match error { crate::error::TransportError::HttpConnection(_) => { // A reqwest::Error happened, we do not return ans instead retry the operation } crate::error::TransportError::Http(status_code) => match status_code { StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED => { return Err(crate::error::TransportError::FailedToOpenSSEStream( format!("Not supported (code: {status_code})"), )); } other => { tracing::warn!( "Failed to open SSE stream: {error} (code: {other})" ); } }, error => { return Err(error); // return the error where the retry wont help } } if retry_count >= self.max_retries { tracing::warn!("Max retries ({}) reached, giving up", self.max_retries); return Err(error); } retry_count += 1; time::sleep(self.retry_delay).await; continue; } }; } } pub(crate) async fn run_standalone( &mut self, cancellation_token: &CancellationToken, custom_headers: &Option<HeaderMap>, response: Response, ) -> TransportResult<()> { let mut retry_count = 0; let mut stream_parser = SseParser::new(); let mut _last_event_id: Option<EventId> = None; let mut response = Some(response); // Main loop for reconnection attempts loop { // Check for cancellation before attempting connection if cancellation_token.is_cancelled() { tracing::debug!("Standalone StreamableHttp cancelled."); return Err(TransportError::Cancelled( crate::utils::CancellationError::ChannelClosed, )); } // use initially passed response, otherwise try to make a new sse connection let response = match response.take() { Some(response) => response, None => { tracing::debug!( "Reconnecting to SSE stream... (try {} of {})", retry_count, self.max_retries ); self.make_standalone_stream_connection( cancellation_token, custom_headers, _last_event_id.clone(), ) .await? } }; // Create a stream from the response bytes let mut stream = response.bytes_stream(); // Inner loop for processing stream chunks loop { let next_chunk = tokio::select! { // Wait for the next stream chunk chunk = stream.next() => { match chunk { Some(chunk) => chunk, None => { // stream ended, unlike SSE, so no retry attempt here needed to reconnect return Err(TransportError::Internal("Stream has ended.".to_string())); } } } // Wait for cancellation _ = cancellation_token.cancelled() => { return Err(TransportError::Cancelled( crate::utils::CancellationError::ChannelClosed, )); } }; match next_chunk { Ok(bytes) => { let events = stream_parser.process_new_chunk(bytes); if !events.is_empty() { for event in events { if let Some(bytes) = event.data { if event.id.is_some() { _last_event_id = event.id.clone(); } if self.read_tx.send(bytes).await.is_err() { tracing::error!( "Readable stream closed, shutting down MCP task" ); return Err(TransportError::SendFailure( "Failed to send message: stream closed".to_string(), )); } } } } retry_count = 0; // Reset retry count on successful chunk } Err(error) => { if retry_count >= self.max_retries { tracing::error!("Error reading stream: {error}"); tracing::warn!("Max retries ({}) reached, giving up", self.max_retries); return Err(error.into()); } tracing::debug!( "The standalone SSE stream encountered an error: '{}'", error ); retry_count += 1; time::sleep(self.retry_delay).await; break; // Break inner loop to reconnect } } } } } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false
rust-mcp-stack/rust-mcp-sdk
https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/utils/readable_channel.rs
crates/rust-mcp-transport/src/utils/readable_channel.rs
use bytes::Bytes; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::io::{AsyncRead, ErrorKind}; use tokio::sync::mpsc; /// A readable channel for asynchronous byte stream reading /// /// Wraps a Tokio mpsc receiver to provide an AsyncRead implementation, /// buffering incoming data as needed. pub struct ReadableChannel { pub read_rx: mpsc::Receiver<Bytes>, pub buffer: Bytes, } impl AsyncRead for ReadableChannel { /// Polls the channel for readable data /// /// Attempts to fill the provided buffer with data from the internal buffer /// or the mpsc receiver. Handles partial reads and channel closure. /// /// # Arguments /// * `self` - Pinned mutable reference to the ReadableChannel /// * `cx` - Task context for polling /// * `buf` - Read buffer to fill with data /// /// # Returns /// * `Poll<tokio::io::Result<()>>` - Ready with Ok if data is read, Ready with Err if the channel is closed, or Pending if no data is available fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> Poll<tokio::io::Result<()>> { // Check if there is data in the internal buffer if !self.buffer.is_empty() { let to_copy = std::cmp::min(self.buffer.len(), buf.remaining()); buf.put_slice(&self.buffer[..to_copy]); self.buffer = self.buffer.slice(to_copy..); return Poll::Ready(Ok(())); } // Poll the receiver for new data match Pin::new(&mut self.read_rx).poll_recv(cx) { Poll::Ready(Some(data)) => { let to_copy = std::cmp::min(data.len(), buf.remaining()); buf.put_slice(&data[..to_copy]); if to_copy < data.len() { self.buffer = data.slice(to_copy..); } Poll::Ready(Ok(())) } Poll::Ready(None) => Poll::Ready(Err(std::io::Error::new( ErrorKind::BrokenPipe, "Channel closed", ))), Poll::Pending => Poll::Pending, } } } #[cfg(test)] mod tests { use bytes::Bytes; use tokio::sync::mpsc; use super::ReadableChannel; use tokio::io::{AsyncReadExt, ErrorKind}; #[tokio::test] async fn test_read_single_message() { let (tx, rx) = tokio::sync::mpsc::channel(1); let data = bytes::Bytes::from("hello world"); tx.send(data.clone()).await.unwrap(); drop(tx); // close the channel let mut reader = super::ReadableChannel { read_rx: rx, buffer: bytes::Bytes::new(), }; let mut buf = vec![0; 11]; reader.read_exact(&mut buf).await.unwrap(); // no need to assign assert_eq!(buf, data); } #[tokio::test] async fn test_read_partial_then_continue() { let (tx, rx) = mpsc::channel(1); let data = Bytes::from("hello world"); tx.send(data.clone()).await.unwrap(); let mut reader = ReadableChannel { read_rx: rx, buffer: Bytes::new(), }; let mut buf1 = vec![0; 5]; reader.read_exact(&mut buf1).await.unwrap(); assert_eq!(&buf1, b"hello"); let mut buf2 = vec![0; 6]; reader.read_exact(&mut buf2).await.unwrap(); assert_eq!(&buf2, b" world"); drop(tx); } #[tokio::test] async fn test_read_larger_than_buffer() { let (tx, rx) = mpsc::channel(1); let data = Bytes::from("abcdefghij"); // 10 bytes tx.send(data).await.unwrap(); let mut reader = ReadableChannel { read_rx: rx, buffer: Bytes::new(), }; let mut buf = vec![0; 6]; reader.read_exact(&mut buf).await.unwrap(); assert_eq!(&buf, b"abcdef"); let mut buf2 = vec![0; 4]; reader.read_exact(&mut buf2).await.unwrap(); assert_eq!(&buf2, b"ghij"); } #[tokio::test] async fn test_read_after_channel_closed() { let (tx, rx) = mpsc::channel(1); drop(tx); // Close without sending let mut reader = ReadableChannel { read_rx: rx, buffer: Bytes::new(), }; let mut buf = vec![0; 5]; let result = reader.read_exact(&mut buf).await; assert!(result.is_err()); let err = result.unwrap_err(); assert_eq!(err.kind(), ErrorKind::BrokenPipe); } #[tokio::test] async fn test_pending_read() { use tokio::time::{timeout, Duration}; let (_tx, rx) = tokio::sync::mpsc::channel::<bytes::Bytes>(1); let mut reader = super::ReadableChannel { read_rx: rx, buffer: bytes::Bytes::new(), }; let mut buf = vec![0; 5]; let result = timeout(Duration::from_millis(100), reader.read_exact(&mut buf)).await; // If the channel has no data and is still open, read should timeout assert!(result.is_err()); } }
rust
MIT
c25994d3d800242c1413b7401432f2a5bef3c23f
2026-01-04T20:25:10.242745Z
false