feat: add local feature for !Send tool handler support (#740)

* feat: add local feature for !Send tool handler support

* fix: gate streamable HTTP transport on not(local) feature
This commit is contained in:
Dale Seo 2026-03-11 17:22:56 -04:00 committed by GitHub
parent 8700e5c920
commit 1a4a52a173
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
41 changed files with 362 additions and 222 deletions

View file

@ -22,4 +22,6 @@ serde_json = "1.0"
darling = { version = "0.23" } darling = { version = "0.23" }
[features] [features]
local = []
[dev-dependencies] [dev-dependencies]

View file

@ -95,6 +95,9 @@ pub struct ToolAttribute {
pub icons: Option<Expr>, pub icons: Option<Expr>,
/// Optional metadata for the tool /// Optional metadata for the tool
pub meta: Option<Expr>, pub meta: Option<Expr>,
/// When true, the generated future will not require `Send`. Useful for `!Send` handlers
/// (e.g. single-threaded database connections). Also enabled globally by the `local` crate feature.
pub local: bool,
} }
#[derive(FromMeta, Debug, Default)] #[derive(FromMeta, Debug, Default)]
@ -333,7 +336,9 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
if fn_item.sig.asyncness.is_some() { if fn_item.sig.asyncness.is_some() {
// 1. remove asyncness from sig // 1. remove asyncness from sig
// 2. make return type: `std::pin::Pin<Box<dyn std::future::Future<Output = #ReturnType> + Send + '_>>` // 2. make return type: `std::pin::Pin<Box<dyn std::future::Future<Output = #ReturnType> + Send + '_>>`
// (omit `+ Send` when the `local` crate feature is active or `#[tool(local)]` is used)
// 3. make body: { Box::pin(async move { #body }) } // 3. make body: { Box::pin(async move { #body }) }
let omit_send = cfg!(feature = "local") || attribute.local;
let new_output = syn::parse2::<ReturnType>({ let new_output = syn::parse2::<ReturnType>({
let mut lt = quote! { 'static }; let mut lt = quote! { 'static };
if let Some(receiver) = fn_item.sig.receiver() { if let Some(receiver) = fn_item.sig.receiver() {
@ -347,10 +352,18 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
} }
match &fn_item.sig.output { match &fn_item.sig.output {
syn::ReturnType::Default => { syn::ReturnType::Default => {
quote! { -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = ()> + Send + #lt>> } if omit_send {
quote! { -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = ()> + #lt>> }
} else {
quote! { -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = ()> + Send + #lt>> }
}
} }
syn::ReturnType::Type(_, ty) => { syn::ReturnType::Type(_, ty) => {
quote! { -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = #ty> + Send + #lt>> } if omit_send {
quote! { -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = #ty> + #lt>> }
} else {
quote! { -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = #ty> + Send + #lt>> }
}
} }
} }
})?; })?;

View file

@ -77,6 +77,7 @@ chrono = { version = "0.4.38", default-features = false, features = [
[features] [features]
default = ["base64", "macros", "server"] default = ["base64", "macros", "server"]
local = ["rmcp-macros?/local"]
client = ["dep:tokio-stream"] client = ["dep:tokio-stream"]
server = ["transport-async-rw", "dep:schemars", "dep:pastey"] server = ["transport-async-rw", "dep:schemars", "dep:pastey"]
macros = ["dep:rmcp-macros", "dep:pastey"] macros = ["dep:rmcp-macros", "dep:pastey"]

View file

@ -52,7 +52,7 @@ The transport layer is pluggable. Two built-in pairs cover the most common cases
| | Client | Server | | | Client | Server |
|:-:|:-:|:-:| |:-:|:-:|:-:|
| **stdio** | [`TokioChildProcess`](crate::transport::TokioChildProcess) | [`stdio`](crate::transport::stdio) | | **stdio** | [`TokioChildProcess`](crate::transport::TokioChildProcess) | [`stdio`](crate::transport::stdio) |
| **Streamable HTTP** | [`StreamableHttpClientTransport`](crate::transport::StreamableHttpClientTransport) | [`StreamableHttpService`](crate::transport::StreamableHttpService) | | **Streamable HTTP** | [`StreamableHttpClientTransport`](crate::transport::StreamableHttpClientTransport) | `StreamableHttpService` |
Any type that implements the [`Transport`](crate::transport::Transport) trait can be used. The [`IntoTransport`](crate::transport::IntoTransport) helper trait provides automatic conversions from: Any type that implements the [`Transport`](crate::transport::Transport) trait can be used. The [`IntoTransport`](crate::transport::IntoTransport) helper trait provides automatic conversions from:

View file

@ -4,7 +4,9 @@ use std::sync::Arc;
use crate::{ use crate::{
error::ErrorData as McpError, error::ErrorData as McpError,
model::*, model::*,
service::{NotificationContext, RequestContext, RoleClient, Service, ServiceRole}, service::{
MaybeSendFuture, NotificationContext, RequestContext, RoleClient, Service, ServiceRole,
},
}; };
impl<H: ClientHandler> Service<RoleClient> for H { impl<H: ClientHandler> Service<RoleClient> for H {
@ -83,7 +85,7 @@ pub trait ClientHandler: Sized + Send + Sync + 'static {
fn ping( fn ping(
&self, &self,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
std::future::ready(Ok(())) std::future::ready(Ok(()))
} }
@ -91,7 +93,7 @@ pub trait ClientHandler: Sized + Send + Sync + 'static {
&self, &self,
params: CreateMessageRequestParams, params: CreateMessageRequestParams,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<CreateMessageResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CreateMessageResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err( std::future::ready(Err(
McpError::method_not_found::<CreateMessageRequestMethod>(), McpError::method_not_found::<CreateMessageRequestMethod>(),
)) ))
@ -100,7 +102,7 @@ pub trait ClientHandler: Sized + Send + Sync + 'static {
fn list_roots( fn list_roots(
&self, &self,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<ListRootsResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListRootsResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Ok(ListRootsResult::default())) std::future::ready(Ok(ListRootsResult::default()))
} }
@ -162,7 +164,8 @@ pub trait ClientHandler: Sized + Send + Sync + 'static {
&self, &self,
request: CreateElicitationRequestParams, request: CreateElicitationRequestParams,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<CreateElicitationResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CreateElicitationResult, McpError>> + MaybeSendFuture + '_
{
// Default implementation declines all requests - real clients should override this // Default implementation declines all requests - real clients should override this
let _ = (request, context); let _ = (request, context);
std::future::ready(Ok(CreateElicitationResult { std::future::ready(Ok(CreateElicitationResult {
@ -175,7 +178,7 @@ pub trait ClientHandler: Sized + Send + Sync + 'static {
&self, &self,
request: CustomRequest, request: CustomRequest,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<CustomResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CustomResult, McpError>> + MaybeSendFuture + '_ {
let CustomRequest { method, .. } = request; let CustomRequest { method, .. } = request;
let _ = context; let _ = context;
std::future::ready(Err(McpError::new( std::future::ready(Err(McpError::new(
@ -189,46 +192,46 @@ pub trait ClientHandler: Sized + Send + Sync + 'static {
&self, &self,
params: CancelledNotificationParam, params: CancelledNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_progress( fn on_progress(
&self, &self,
params: ProgressNotificationParam, params: ProgressNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_logging_message( fn on_logging_message(
&self, &self,
params: LoggingMessageNotificationParam, params: LoggingMessageNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_resource_updated( fn on_resource_updated(
&self, &self,
params: ResourceUpdatedNotificationParam, params: ResourceUpdatedNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_resource_list_changed( fn on_resource_list_changed(
&self, &self,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_tool_list_changed( fn on_tool_list_changed(
&self, &self,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_prompt_list_changed( fn on_prompt_list_changed(
&self, &self,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
@ -236,14 +239,14 @@ pub trait ClientHandler: Sized + Send + Sync + 'static {
&self, &self,
params: ElicitationResponseNotificationParam, params: ElicitationResponseNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_custom_notification( fn on_custom_notification(
&self, &self,
notification: CustomNotification, notification: CustomNotification,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
let _ = (notification, context); let _ = (notification, context);
std::future::ready(()) std::future::ready(())
} }
@ -269,7 +272,7 @@ macro_rules! impl_client_handler_for_wrapper {
fn ping( fn ping(
&self, &self,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
(**self).ping(context) (**self).ping(context)
} }
@ -277,14 +280,14 @@ macro_rules! impl_client_handler_for_wrapper {
&self, &self,
params: CreateMessageRequestParams, params: CreateMessageRequestParams,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<CreateMessageResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CreateMessageResult, McpError>> + MaybeSendFuture + '_ {
(**self).create_message(params, context) (**self).create_message(params, context)
} }
fn list_roots( fn list_roots(
&self, &self,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<ListRootsResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListRootsResult, McpError>> + MaybeSendFuture + '_ {
(**self).list_roots(context) (**self).list_roots(context)
} }
@ -292,7 +295,7 @@ macro_rules! impl_client_handler_for_wrapper {
&self, &self,
request: CreateElicitationRequestParams, request: CreateElicitationRequestParams,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<CreateElicitationResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CreateElicitationResult, McpError>> + MaybeSendFuture + '_ {
(**self).create_elicitation(request, context) (**self).create_elicitation(request, context)
} }
@ -300,7 +303,7 @@ macro_rules! impl_client_handler_for_wrapper {
&self, &self,
request: CustomRequest, request: CustomRequest,
context: RequestContext<RoleClient>, context: RequestContext<RoleClient>,
) -> impl Future<Output = Result<CustomResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CustomResult, McpError>> + MaybeSendFuture + '_ {
(**self).on_custom_request(request, context) (**self).on_custom_request(request, context)
} }
@ -308,7 +311,7 @@ macro_rules! impl_client_handler_for_wrapper {
&self, &self,
params: CancelledNotificationParam, params: CancelledNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_cancelled(params, context) (**self).on_cancelled(params, context)
} }
@ -316,7 +319,7 @@ macro_rules! impl_client_handler_for_wrapper {
&self, &self,
params: ProgressNotificationParam, params: ProgressNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_progress(params, context) (**self).on_progress(params, context)
} }
@ -324,7 +327,7 @@ macro_rules! impl_client_handler_for_wrapper {
&self, &self,
params: LoggingMessageNotificationParam, params: LoggingMessageNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_logging_message(params, context) (**self).on_logging_message(params, context)
} }
@ -332,28 +335,28 @@ macro_rules! impl_client_handler_for_wrapper {
&self, &self,
params: ResourceUpdatedNotificationParam, params: ResourceUpdatedNotificationParam,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_resource_updated(params, context) (**self).on_resource_updated(params, context)
} }
fn on_resource_list_changed( fn on_resource_list_changed(
&self, &self,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_resource_list_changed(context) (**self).on_resource_list_changed(context)
} }
fn on_tool_list_changed( fn on_tool_list_changed(
&self, &self,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_tool_list_changed(context) (**self).on_tool_list_changed(context)
} }
fn on_prompt_list_changed( fn on_prompt_list_changed(
&self, &self,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_prompt_list_changed(context) (**self).on_prompt_list_changed(context)
} }
@ -361,7 +364,7 @@ macro_rules! impl_client_handler_for_wrapper {
&self, &self,
notification: CustomNotification, notification: CustomNotification,
context: NotificationContext<RoleClient>, context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_custom_notification(notification, context) (**self).on_custom_notification(notification, context)
} }

View file

@ -3,7 +3,10 @@ use std::sync::Arc;
use crate::{ use crate::{
error::ErrorData as McpError, error::ErrorData as McpError,
model::{TaskSupport, *}, model::{TaskSupport, *},
service::{NotificationContext, RequestContext, RoleServer, Service, ServiceRole}, service::{
MaybeSend, MaybeSendFuture, NotificationContext, RequestContext, RoleServer, Service,
ServiceRole,
},
}; };
pub mod common; pub mod common;
@ -159,12 +162,16 @@ impl<H: ServerHandler> Service<RoleServer> for H {
} }
#[allow(unused_variables)] #[allow(unused_variables)]
pub trait ServerHandler: Sized + Send + Sync + 'static { #[allow(
private_bounds,
reason = "MaybeSend is a sealed conditional Send + Sync alias"
)]
pub trait ServerHandler: Sized + MaybeSend + 'static {
fn enqueue_task( fn enqueue_task(
&self, &self,
_request: CallToolRequestParams, _request: CallToolRequestParams,
_context: RequestContext<RoleServer>, _context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CreateTaskResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CreateTaskResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err(McpError::internal_error( std::future::ready(Err(McpError::internal_error(
"Task processing not implemented".to_string(), "Task processing not implemented".to_string(),
None, None,
@ -173,7 +180,7 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
fn ping( fn ping(
&self, &self,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
std::future::ready(Ok(())) std::future::ready(Ok(()))
} }
// handle requests // handle requests
@ -181,7 +188,7 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
request: InitializeRequestParams, request: InitializeRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<InitializeResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<InitializeResult, McpError>> + MaybeSendFuture + '_ {
if context.peer.peer_info().is_none() { if context.peer.peer_info().is_none() {
context.peer.set_peer_info(request); context.peer.set_peer_info(request);
} }
@ -191,49 +198,50 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
request: CompleteRequestParams, request: CompleteRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CompleteResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CompleteResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Ok(CompleteResult::default())) std::future::ready(Ok(CompleteResult::default()))
} }
fn set_level( fn set_level(
&self, &self,
request: SetLevelRequestParams, request: SetLevelRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err(McpError::method_not_found::<SetLevelRequestMethod>())) std::future::ready(Err(McpError::method_not_found::<SetLevelRequestMethod>()))
} }
fn get_prompt( fn get_prompt(
&self, &self,
request: GetPromptRequestParams, request: GetPromptRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<GetPromptResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<GetPromptResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err(McpError::method_not_found::<GetPromptRequestMethod>())) std::future::ready(Err(McpError::method_not_found::<GetPromptRequestMethod>()))
} }
fn list_prompts( fn list_prompts(
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListPromptsResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListPromptsResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Ok(ListPromptsResult::default())) std::future::ready(Ok(ListPromptsResult::default()))
} }
fn list_resources( fn list_resources(
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListResourcesResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Ok(ListResourcesResult::default())) std::future::ready(Ok(ListResourcesResult::default()))
} }
fn list_resource_templates( fn list_resource_templates(
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListResourceTemplatesResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListResourceTemplatesResult, McpError>> + MaybeSendFuture + '_
{
std::future::ready(Ok(ListResourceTemplatesResult::default())) std::future::ready(Ok(ListResourceTemplatesResult::default()))
} }
fn read_resource( fn read_resource(
&self, &self,
request: ReadResourceRequestParams, request: ReadResourceRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ReadResourceResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ReadResourceResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err( std::future::ready(Err(
McpError::method_not_found::<ReadResourceRequestMethod>(), McpError::method_not_found::<ReadResourceRequestMethod>(),
)) ))
@ -242,28 +250,28 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
request: SubscribeRequestParams, request: SubscribeRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err(McpError::method_not_found::<SubscribeRequestMethod>())) std::future::ready(Err(McpError::method_not_found::<SubscribeRequestMethod>()))
} }
fn unsubscribe( fn unsubscribe(
&self, &self,
request: UnsubscribeRequestParams, request: UnsubscribeRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err(McpError::method_not_found::<UnsubscribeRequestMethod>())) std::future::ready(Err(McpError::method_not_found::<UnsubscribeRequestMethod>()))
} }
fn call_tool( fn call_tool(
&self, &self,
request: CallToolRequestParams, request: CallToolRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CallToolResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CallToolResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err(McpError::method_not_found::<CallToolRequestMethod>())) std::future::ready(Err(McpError::method_not_found::<CallToolRequestMethod>()))
} }
fn list_tools( fn list_tools(
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListToolsResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListToolsResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Ok(ListToolsResult::default())) std::future::ready(Ok(ListToolsResult::default()))
} }
/// Get a tool definition by name. /// Get a tool definition by name.
@ -277,7 +285,7 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
request: CustomRequest, request: CustomRequest,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CustomResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CustomResult, McpError>> + MaybeSendFuture + '_ {
let CustomRequest { method, .. } = request; let CustomRequest { method, .. } = request;
let _ = context; let _ = context;
std::future::ready(Err(McpError::new( std::future::ready(Err(McpError::new(
@ -291,34 +299,34 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
notification: CancelledNotificationParam, notification: CancelledNotificationParam,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_progress( fn on_progress(
&self, &self,
notification: ProgressNotificationParam, notification: ProgressNotificationParam,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_initialized( fn on_initialized(
&self, &self,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
tracing::info!("client initialized"); tracing::info!("client initialized");
std::future::ready(()) std::future::ready(())
} }
fn on_roots_list_changed( fn on_roots_list_changed(
&self, &self,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
std::future::ready(()) std::future::ready(())
} }
fn on_custom_notification( fn on_custom_notification(
&self, &self,
notification: CustomNotification, notification: CustomNotification,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
let _ = (notification, context); let _ = (notification, context);
std::future::ready(()) std::future::ready(())
} }
@ -331,7 +339,7 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListTasksResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListTasksResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Err(McpError::method_not_found::<ListTasksMethod>())) std::future::ready(Err(McpError::method_not_found::<ListTasksMethod>()))
} }
@ -339,7 +347,7 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
request: GetTaskInfoParams, request: GetTaskInfoParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<GetTaskResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<GetTaskResult, McpError>> + MaybeSendFuture + '_ {
let _ = (request, context); let _ = (request, context);
std::future::ready(Err(McpError::method_not_found::<GetTaskInfoMethod>())) std::future::ready(Err(McpError::method_not_found::<GetTaskInfoMethod>()))
} }
@ -348,7 +356,7 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
request: GetTaskResultParams, request: GetTaskResultParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<GetTaskPayloadResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<GetTaskPayloadResult, McpError>> + MaybeSendFuture + '_ {
let _ = (request, context); let _ = (request, context);
std::future::ready(Err(McpError::method_not_found::<GetTaskResultMethod>())) std::future::ready(Err(McpError::method_not_found::<GetTaskResultMethod>()))
} }
@ -357,7 +365,7 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
&self, &self,
request: CancelTaskParams, request: CancelTaskParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CancelTaskResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CancelTaskResult, McpError>> + MaybeSendFuture + '_ {
let _ = (request, context); let _ = (request, context);
std::future::ready(Err(McpError::method_not_found::<CancelTaskMethod>())) std::future::ready(Err(McpError::method_not_found::<CancelTaskMethod>()))
} }
@ -370,14 +378,14 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: CallToolRequestParams, request: CallToolRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CreateTaskResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CreateTaskResult, McpError>> + MaybeSendFuture + '_ {
(**self).enqueue_task(request, context) (**self).enqueue_task(request, context)
} }
fn ping( fn ping(
&self, &self,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
(**self).ping(context) (**self).ping(context)
} }
@ -385,7 +393,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: InitializeRequestParams, request: InitializeRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<InitializeResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<InitializeResult, McpError>> + MaybeSendFuture + '_ {
(**self).initialize(request, context) (**self).initialize(request, context)
} }
@ -393,7 +401,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: CompleteRequestParams, request: CompleteRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CompleteResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CompleteResult, McpError>> + MaybeSendFuture + '_ {
(**self).complete(request, context) (**self).complete(request, context)
} }
@ -401,7 +409,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: SetLevelRequestParams, request: SetLevelRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
(**self).set_level(request, context) (**self).set_level(request, context)
} }
@ -409,7 +417,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: GetPromptRequestParams, request: GetPromptRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<GetPromptResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<GetPromptResult, McpError>> + MaybeSendFuture + '_ {
(**self).get_prompt(request, context) (**self).get_prompt(request, context)
} }
@ -417,7 +425,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListPromptsResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListPromptsResult, McpError>> + MaybeSendFuture + '_ {
(**self).list_prompts(request, context) (**self).list_prompts(request, context)
} }
@ -425,7 +433,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListResourcesResult, McpError>> + MaybeSendFuture + '_ {
(**self).list_resources(request, context) (**self).list_resources(request, context)
} }
@ -433,7 +441,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListResourceTemplatesResult, McpError>> + Send + '_ ) -> impl Future<Output = Result<ListResourceTemplatesResult, McpError>> + MaybeSendFuture + '_
{ {
(**self).list_resource_templates(request, context) (**self).list_resource_templates(request, context)
} }
@ -442,7 +450,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: ReadResourceRequestParams, request: ReadResourceRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ReadResourceResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ReadResourceResult, McpError>> + MaybeSendFuture + '_ {
(**self).read_resource(request, context) (**self).read_resource(request, context)
} }
@ -450,7 +458,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: SubscribeRequestParams, request: SubscribeRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
(**self).subscribe(request, context) (**self).subscribe(request, context)
} }
@ -458,7 +466,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: UnsubscribeRequestParams, request: UnsubscribeRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
(**self).unsubscribe(request, context) (**self).unsubscribe(request, context)
} }
@ -466,7 +474,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: CallToolRequestParams, request: CallToolRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CallToolResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CallToolResult, McpError>> + MaybeSendFuture + '_ {
(**self).call_tool(request, context) (**self).call_tool(request, context)
} }
@ -474,7 +482,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListToolsResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListToolsResult, McpError>> + MaybeSendFuture + '_ {
(**self).list_tools(request, context) (**self).list_tools(request, context)
} }
@ -486,7 +494,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: CustomRequest, request: CustomRequest,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CustomResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CustomResult, McpError>> + MaybeSendFuture + '_ {
(**self).on_custom_request(request, context) (**self).on_custom_request(request, context)
} }
@ -494,7 +502,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
notification: CancelledNotificationParam, notification: CancelledNotificationParam,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_cancelled(notification, context) (**self).on_cancelled(notification, context)
} }
@ -502,21 +510,21 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
notification: ProgressNotificationParam, notification: ProgressNotificationParam,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_progress(notification, context) (**self).on_progress(notification, context)
} }
fn on_initialized( fn on_initialized(
&self, &self,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_initialized(context) (**self).on_initialized(context)
} }
fn on_roots_list_changed( fn on_roots_list_changed(
&self, &self,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_roots_list_changed(context) (**self).on_roots_list_changed(context)
} }
@ -524,7 +532,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
notification: CustomNotification, notification: CustomNotification,
context: NotificationContext<RoleServer>, context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
(**self).on_custom_notification(notification, context) (**self).on_custom_notification(notification, context)
} }
@ -536,7 +544,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: Option<PaginatedRequestParams>, request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListTasksResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<ListTasksResult, McpError>> + MaybeSendFuture + '_ {
(**self).list_tasks(request, context) (**self).list_tasks(request, context)
} }
@ -544,7 +552,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: GetTaskInfoParams, request: GetTaskInfoParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<GetTaskResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<GetTaskResult, McpError>> + MaybeSendFuture + '_ {
(**self).get_task_info(request, context) (**self).get_task_info(request, context)
} }
@ -552,7 +560,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: GetTaskResultParams, request: GetTaskResultParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<GetTaskPayloadResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<GetTaskPayloadResult, McpError>> + MaybeSendFuture + '_ {
(**self).get_task_result(request, context) (**self).get_task_result(request, context)
} }
@ -560,7 +568,7 @@ macro_rules! impl_server_handler_for_wrapper {
&self, &self,
request: CancelTaskParams, request: CancelTaskParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<CancelTaskResult, McpError>> + Send + '_ { ) -> impl Future<Output = Result<CancelTaskResult, McpError>> + MaybeSendFuture + '_ {
(**self).cancel_task(request, context) (**self).cancel_task(request, context)
} }
} }

View file

@ -6,7 +6,8 @@
use std::{future::Future, marker::PhantomData}; use std::{future::Future, marker::PhantomData};
use futures::future::{BoxFuture, FutureExt}; #[cfg(not(feature = "local"))]
use futures::future::BoxFuture;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use super::common::{AsRequestContext, FromContextPart}; use super::common::{AsRequestContext, FromContextPart};
@ -15,7 +16,7 @@ use crate::{
RoleServer, RoleServer,
handler::server::wrapper::Parameters, handler::server::wrapper::Parameters,
model::{GetPromptResult, PromptMessage}, model::{GetPromptResult, PromptMessage},
service::RequestContext, service::{MaybeBoxFuture, MaybeSend, MaybeSendFuture, RequestContext},
}; };
/// Context for prompt retrieval operations /// Context for prompt retrieval operations
@ -57,14 +58,23 @@ pub trait GetPromptHandler<S, A> {
fn handle( fn handle(
self, self,
context: PromptContext<'_, S>, context: PromptContext<'_, S>,
) -> BoxFuture<'_, Result<GetPromptResult, crate::ErrorData>>; ) -> MaybeBoxFuture<'_, Result<GetPromptResult, crate::ErrorData>>;
} }
/// Type alias for dynamic prompt handlers /// Type alias for dynamic prompt handlers
#[cfg(not(feature = "local"))]
pub type DynGetPromptHandler<S> = dyn for<'a> Fn(PromptContext<'a, S>) -> BoxFuture<'a, Result<GetPromptResult, crate::ErrorData>> pub type DynGetPromptHandler<S> = dyn for<'a> Fn(PromptContext<'a, S>) -> BoxFuture<'a, Result<GetPromptResult, crate::ErrorData>>
+ Send + Send
+ Sync; + Sync;
#[cfg(feature = "local")]
pub type DynGetPromptHandler<S> = dyn for<'a> Fn(
PromptContext<'a, S>,
) -> futures::future::LocalBoxFuture<
'a,
Result<GetPromptResult, crate::ErrorData>,
>;
/// Adapter type for async methods that return `Vec<PromptMessage>` /// Adapter type for async methods that return `Vec<PromptMessage>`
pub struct AsyncMethodAdapter<T>(PhantomData<T>); pub struct AsyncMethodAdapter<T>(PhantomData<T>);
@ -191,31 +201,31 @@ macro_rules! impl_prompt_handler_for {
impl<$($Tn,)* S, F, R> GetPromptHandler<S, ($($Tn,)*)> for F impl<$($Tn,)* S, F, R> GetPromptHandler<S, ($($Tn,)*)> for F
where where
$( $(
$Tn: for<'a> FromContextPart<PromptContext<'a, S>> + Send, $Tn: for<'a> FromContextPart<PromptContext<'a, S>> + MaybeSendFuture,
)* )*
F: FnOnce(&S, $($Tn,)*) -> BoxFuture<'_, R> + Send, F: FnOnce(&S, $($Tn,)*) -> MaybeBoxFuture<'_, R> + MaybeSendFuture,
R: IntoGetPromptResult + Send + 'static, R: IntoGetPromptResult + MaybeSendFuture + 'static,
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
#[allow(unused_variables, non_snake_case, unused_mut)] #[allow(unused_variables, non_snake_case, unused_mut)]
fn handle( fn handle(
self, self,
mut context: PromptContext<'_, S>, mut context: PromptContext<'_, S>,
) -> BoxFuture<'_, Result<GetPromptResult, crate::ErrorData>> ) -> MaybeBoxFuture<'_, Result<GetPromptResult, crate::ErrorData>>
{ {
$( $(
let result = $Tn::from_context_part(&mut context); let result = $Tn::from_context_part(&mut context);
let $Tn = match result { let $Tn = match result {
Ok(value) => value, Ok(value) => value,
Err(e) => return std::future::ready(Err(e)).boxed(), Err(e) => return Box::pin(std::future::ready(Err(e))),
}; };
)* )*
let service = context.server; let service = context.server;
let fut = self(service, $($Tn,)*); let fut = self(service, $($Tn,)*);
async move { Box::pin(async move {
let result = fut.await; let result = fut.await;
result.into_get_prompt_result() result.into_get_prompt_result()
}.boxed() })
} }
} }
@ -224,28 +234,28 @@ macro_rules! impl_prompt_handler_for {
impl<$($Tn,)* S, F, R> GetPromptHandler<S, SyncPromptMethodAdapter<($($Tn,)*), R>> for F impl<$($Tn,)* S, F, R> GetPromptHandler<S, SyncPromptMethodAdapter<($($Tn,)*), R>> for F
where where
$( $(
$Tn: for<'a> FromContextPart<PromptContext<'a, S>> + Send, $Tn: for<'a> FromContextPart<PromptContext<'a, S>> + MaybeSendFuture,
)* )*
F: FnOnce(&S, $($Tn,)*) -> R + Send, F: FnOnce(&S, $($Tn,)*) -> R + MaybeSendFuture,
R: IntoGetPromptResult + Send, R: IntoGetPromptResult + MaybeSendFuture,
S: Send + Sync, S: MaybeSend,
{ {
#[allow(unused_variables, non_snake_case, unused_mut)] #[allow(unused_variables, non_snake_case, unused_mut)]
fn handle( fn handle(
self, self,
mut context: PromptContext<'_, S>, mut context: PromptContext<'_, S>,
) -> BoxFuture<'_, Result<GetPromptResult, crate::ErrorData>> ) -> MaybeBoxFuture<'_, Result<GetPromptResult, crate::ErrorData>>
{ {
$( $(
let result = $Tn::from_context_part(&mut context); let result = $Tn::from_context_part(&mut context);
let $Tn = match result { let $Tn = match result {
Ok(value) => value, Ok(value) => value,
Err(e) => return std::future::ready(Err(e)).boxed(), Err(e) => return Box::pin(std::future::ready(Err(e))),
}; };
)* )*
let service = context.server; let service = context.server;
let result = self(service, $($Tn,)*); let result = self(service, $($Tn,)*);
std::future::ready(result.into_get_prompt_result()).boxed() Box::pin(std::future::ready(result.into_get_prompt_result()))
} }
} }
@ -254,25 +264,25 @@ macro_rules! impl_prompt_handler_for {
impl<$($Tn,)* S, F, Fut, R> GetPromptHandler<S, AsyncPromptAdapter<($($Tn,)*), Fut, R>> for F impl<$($Tn,)* S, F, Fut, R> GetPromptHandler<S, AsyncPromptAdapter<($($Tn,)*), Fut, R>> for F
where where
$( $(
$Tn: for<'a> FromContextPart<PromptContext<'a, S>> + Send + 'static, $Tn: for<'a> FromContextPart<PromptContext<'a, S>> + MaybeSendFuture + 'static,
)* )*
F: FnOnce($($Tn,)*) -> Fut + Send + 'static, F: FnOnce($($Tn,)*) -> Fut + MaybeSendFuture + 'static,
Fut: Future<Output = Result<R, crate::ErrorData>> + Send + 'static, Fut: Future<Output = Result<R, crate::ErrorData>> + MaybeSendFuture + 'static,
R: IntoGetPromptResult + Send + 'static, R: IntoGetPromptResult + MaybeSendFuture + 'static,
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
#[allow(unused_variables, non_snake_case, unused_mut)] #[allow(unused_variables, non_snake_case, unused_mut)]
fn handle( fn handle(
self, self,
mut context: PromptContext<'_, S>, mut context: PromptContext<'_, S>,
) -> BoxFuture<'_, Result<GetPromptResult, crate::ErrorData>> ) -> MaybeBoxFuture<'_, Result<GetPromptResult, crate::ErrorData>>
{ {
// Extract all parameters before moving into the async block // Extract all parameters before moving into the async block
$( $(
let result = $Tn::from_context_part(&mut context); let result = $Tn::from_context_part(&mut context);
let $Tn = match result { let $Tn = match result {
Ok(value) => value, Ok(value) => value,
Err(e) => return std::future::ready(Err(e)).boxed(), Err(e) => return Box::pin(std::future::ready(Err(e))),
}; };
)* )*
@ -290,27 +300,27 @@ macro_rules! impl_prompt_handler_for {
impl<$($Tn,)* S, F, R> GetPromptHandler<S, SyncPromptAdapter<($($Tn,)*), R>> for F impl<$($Tn,)* S, F, R> GetPromptHandler<S, SyncPromptAdapter<($($Tn,)*), R>> for F
where where
$( $(
$Tn: for<'a> FromContextPart<PromptContext<'a, S>> + Send + 'static, $Tn: for<'a> FromContextPart<PromptContext<'a, S>> + MaybeSendFuture + 'static,
)* )*
F: FnOnce($($Tn,)*) -> Result<R, crate::ErrorData> + Send + 'static, F: FnOnce($($Tn,)*) -> Result<R, crate::ErrorData> + MaybeSendFuture + 'static,
R: IntoGetPromptResult + Send + 'static, R: IntoGetPromptResult + MaybeSendFuture + 'static,
S: Send + Sync, S: MaybeSend,
{ {
#[allow(unused_variables, non_snake_case, unused_mut)] #[allow(unused_variables, non_snake_case, unused_mut)]
fn handle( fn handle(
self, self,
mut context: PromptContext<'_, S>, mut context: PromptContext<'_, S>,
) -> BoxFuture<'_, Result<GetPromptResult, crate::ErrorData>> ) -> MaybeBoxFuture<'_, Result<GetPromptResult, crate::ErrorData>>
{ {
$( $(
let result = $Tn::from_context_part(&mut context); let result = $Tn::from_context_part(&mut context);
let $Tn = match result { let $Tn = match result {
Ok(value) => value, Ok(value) => value,
Err(e) => return std::future::ready(Err(e)).boxed(), Err(e) => return Box::pin(std::future::ready(Err(e))),
}; };
)* )*
let result = self($($Tn,)*); let result = self($($Tn,)*);
std::future::ready(result.and_then(|r| r.into_get_prompt_result())).boxed() Box::pin(std::future::ready(result.and_then(|r| r.into_get_prompt_result())))
} }
} }

View file

@ -1,10 +1,9 @@
use std::{borrow::Cow, sync::Arc}; use std::{borrow::Cow, sync::Arc};
use futures::future::BoxFuture;
use crate::{ use crate::{
handler::server::prompt::{DynGetPromptHandler, GetPromptHandler, PromptContext}, handler::server::prompt::{DynGetPromptHandler, GetPromptHandler, PromptContext},
model::{GetPromptResult, Prompt}, model::{GetPromptResult, Prompt},
service::{MaybeBoxFuture, MaybeSend},
}; };
pub struct PromptRoute<S> { pub struct PromptRoute<S> {
@ -32,10 +31,10 @@ impl<S> Clone for PromptRoute<S> {
} }
} }
impl<S: Send + Sync + 'static> PromptRoute<S> { impl<S: MaybeSend + 'static> PromptRoute<S> {
pub fn new<H, A: 'static>(attr: impl Into<Prompt>, handler: H) -> Self pub fn new<H, A: 'static>(attr: impl Into<Prompt>, handler: H) -> Self
where where
H: GetPromptHandler<S, A> + Send + Sync + Clone + 'static, H: GetPromptHandler<S, A> + MaybeSend + Clone + 'static,
{ {
Self { Self {
get: Arc::new(move |context: PromptContext<S>| { get: Arc::new(move |context: PromptContext<S>| {
@ -50,9 +49,8 @@ impl<S: Send + Sync + 'static> PromptRoute<S> {
where where
H: for<'a> Fn( H: for<'a> Fn(
PromptContext<'a, S>, PromptContext<'a, S>,
) -> BoxFuture<'a, Result<GetPromptResult, crate::ErrorData>> ) -> MaybeBoxFuture<'a, Result<GetPromptResult, crate::ErrorData>>
+ Send + MaybeSend
+ Sync
+ 'static, + 'static,
{ {
Self { Self {
@ -72,9 +70,9 @@ pub trait IntoPromptRoute<S, A> {
impl<S, H, A, P> IntoPromptRoute<S, A> for (P, H) impl<S, H, A, P> IntoPromptRoute<S, A> for (P, H)
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
A: 'static, A: 'static,
H: GetPromptHandler<S, A> + Send + Sync + Clone + 'static, H: GetPromptHandler<S, A> + MaybeSend + Clone + 'static,
P: Into<Prompt>, P: Into<Prompt>,
{ {
fn into_prompt_route(self) -> PromptRoute<S> { fn into_prompt_route(self) -> PromptRoute<S> {
@ -84,7 +82,7 @@ where
impl<S> IntoPromptRoute<S, ()> for PromptRoute<S> impl<S> IntoPromptRoute<S, ()> for PromptRoute<S>
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
fn into_prompt_route(self) -> PromptRoute<S> { fn into_prompt_route(self) -> PromptRoute<S> {
self self
@ -96,7 +94,7 @@ pub struct PromptAttrGenerateFunctionAdapter;
impl<S, F> IntoPromptRoute<S, PromptAttrGenerateFunctionAdapter> for F impl<S, F> IntoPromptRoute<S, PromptAttrGenerateFunctionAdapter> for F
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
F: Fn() -> PromptRoute<S>, F: Fn() -> PromptRoute<S>,
{ {
fn into_prompt_route(self) -> PromptRoute<S> { fn into_prompt_route(self) -> PromptRoute<S> {
@ -137,7 +135,7 @@ impl<S> IntoIterator for PromptRouter<S> {
impl<S> PromptRouter<S> impl<S> PromptRouter<S>
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
@ -195,7 +193,7 @@ where
impl<S> std::ops::Add<PromptRouter<S>> for PromptRouter<S> impl<S> std::ops::Add<PromptRouter<S>> for PromptRouter<S>
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
type Output = Self; type Output = Self;
@ -207,7 +205,7 @@ where
impl<S> std::ops::AddAssign<PromptRouter<S>> for PromptRouter<S> impl<S> std::ops::AddAssign<PromptRouter<S>> for PromptRouter<S>
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
fn add_assign(&mut self, other: PromptRouter<S>) { fn add_assign(&mut self, other: PromptRouter<S>) {
self.merge(other); self.merge(other);

View file

@ -124,7 +124,6 @@ mod tool_traits;
use std::{borrow::Cow, sync::Arc}; use std::{borrow::Cow, sync::Arc};
use futures::{FutureExt, future::BoxFuture};
use schemars::JsonSchema; use schemars::JsonSchema;
pub use tool_traits::{AsyncTool, SyncTool, ToolBase}; pub use tool_traits::{AsyncTool, SyncTool, ToolBase};
@ -134,6 +133,7 @@ use crate::{
tool_name_validation::validate_and_warn_tool_name, tool_name_validation::validate_and_warn_tool_name,
}, },
model::{CallToolResult, Tool, ToolAnnotations}, model::{CallToolResult, Tool, ToolAnnotations},
service::{MaybeBoxFuture, MaybeSend},
}; };
pub struct ToolRoute<S> { pub struct ToolRoute<S> {
@ -161,15 +161,15 @@ impl<S> Clone for ToolRoute<S> {
} }
} }
impl<S: Send + Sync + 'static> ToolRoute<S> { impl<S: MaybeSend + 'static> ToolRoute<S> {
pub fn new<C, A>(attr: impl Into<Tool>, call: C) -> Self pub fn new<C, A>(attr: impl Into<Tool>, call: C) -> Self
where where
C: CallToolHandler<S, A> + Send + Sync + Clone + 'static, C: CallToolHandler<S, A> + MaybeSend + Clone + 'static,
{ {
Self { Self {
call: Arc::new(move |context: ToolCallContext<S>| { call: Arc::new(move |context: ToolCallContext<S>| {
let call = call.clone(); let call = call.clone();
context.invoke(call).boxed() context.invoke(call)
}), }),
attr: attr.into(), attr: attr.into(),
} }
@ -178,9 +178,8 @@ impl<S: Send + Sync + 'static> ToolRoute<S> {
where where
C: for<'a> Fn( C: for<'a> Fn(
ToolCallContext<'a, S>, ToolCallContext<'a, S>,
) -> BoxFuture<'a, Result<CallToolResult, crate::ErrorData>> ) -> MaybeBoxFuture<'a, Result<CallToolResult, crate::ErrorData>>
+ Send + MaybeSend
+ Sync
+ 'static, + 'static,
{ {
Self { Self {
@ -199,8 +198,8 @@ pub trait IntoToolRoute<S, A> {
impl<S, C, A, T> IntoToolRoute<S, A> for (T, C) impl<S, C, A, T> IntoToolRoute<S, A> for (T, C)
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
C: CallToolHandler<S, A> + Send + Sync + Clone + 'static, C: CallToolHandler<S, A> + MaybeSend + Clone + 'static,
T: Into<Tool>, T: Into<Tool>,
{ {
fn into_tool_route(self) -> ToolRoute<S> { fn into_tool_route(self) -> ToolRoute<S> {
@ -210,7 +209,7 @@ where
impl<S> IntoToolRoute<S, ()> for ToolRoute<S> impl<S> IntoToolRoute<S, ()> for ToolRoute<S>
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
fn into_tool_route(self) -> ToolRoute<S> { fn into_tool_route(self) -> ToolRoute<S> {
self self
@ -220,7 +219,7 @@ where
pub struct ToolAttrGenerateFunctionAdapter; pub struct ToolAttrGenerateFunctionAdapter;
impl<S, F> IntoToolRoute<S, ToolAttrGenerateFunctionAdapter> for F impl<S, F> IntoToolRoute<S, ToolAttrGenerateFunctionAdapter> for F
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
F: Fn() -> ToolRoute<S>, F: Fn() -> ToolRoute<S>,
{ {
fn into_tool_route(self) -> ToolRoute<S> { fn into_tool_route(self) -> ToolRoute<S> {
@ -230,14 +229,14 @@ where
pub trait CallToolHandlerExt<S, A>: Sized pub trait CallToolHandlerExt<S, A>: Sized
where where
Self: CallToolHandler<S, A> + Send + Sync + Clone + 'static, Self: CallToolHandler<S, A> + MaybeSend + Clone + 'static,
{ {
fn name(self, name: impl Into<Cow<'static, str>>) -> WithToolAttr<Self, S, A>; fn name(self, name: impl Into<Cow<'static, str>>) -> WithToolAttr<Self, S, A>;
} }
impl<C, S, A> CallToolHandlerExt<S, A> for C impl<C, S, A> CallToolHandlerExt<S, A> for C
where where
C: CallToolHandler<S, A> + Send + Sync + Clone + 'static, C: CallToolHandler<S, A> + MaybeSend + Clone + 'static,
{ {
fn name(self, name: impl Into<Cow<'static, str>>) -> WithToolAttr<Self, S, A> { fn name(self, name: impl Into<Cow<'static, str>>) -> WithToolAttr<Self, S, A> {
WithToolAttr { WithToolAttr {
@ -254,7 +253,7 @@ where
pub struct WithToolAttr<C, S, A> pub struct WithToolAttr<C, S, A>
where where
C: CallToolHandler<S, A> + Send + Sync + Clone + 'static, C: CallToolHandler<S, A> + MaybeSend + Clone + 'static,
{ {
pub attr: crate::model::Tool, pub attr: crate::model::Tool,
pub call: C, pub call: C,
@ -263,8 +262,8 @@ where
impl<C, S, A> IntoToolRoute<S, A> for WithToolAttr<C, S, A> impl<C, S, A> IntoToolRoute<S, A> for WithToolAttr<C, S, A>
where where
C: CallToolHandler<S, A> + Send + Sync + Clone + 'static, C: CallToolHandler<S, A> + MaybeSend + Clone + 'static,
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
fn into_tool_route(self) -> ToolRoute<S> { fn into_tool_route(self) -> ToolRoute<S> {
ToolRoute::new(self.attr, self.call) ToolRoute::new(self.attr, self.call)
@ -273,7 +272,7 @@ where
impl<C, S, A> WithToolAttr<C, S, A> impl<C, S, A> WithToolAttr<C, S, A>
where where
C: CallToolHandler<S, A> + Send + Sync + Clone + 'static, C: CallToolHandler<S, A> + MaybeSend + Clone + 'static,
{ {
pub fn description(mut self, description: impl Into<Cow<'static, str>>) -> Self { pub fn description(mut self, description: impl Into<Cow<'static, str>>) -> Self {
self.attr.description = Some(description.into()); self.attr.description = Some(description.into());
@ -328,7 +327,7 @@ impl<S> IntoIterator for ToolRouter<S> {
impl<S> ToolRouter<S> impl<S> ToolRouter<S>
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
@ -428,7 +427,7 @@ where
impl<S> std::ops::Add<ToolRouter<S>> for ToolRouter<S> impl<S> std::ops::Add<ToolRouter<S>> for ToolRouter<S>
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
type Output = Self; type Output = Self;
@ -440,7 +439,7 @@ where
impl<S> std::ops::AddAssign<ToolRouter<S>> for ToolRouter<S> impl<S> std::ops::AddAssign<ToolRouter<S>> for ToolRouter<S>
where where
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
fn add_assign(&mut self, other: ToolRouter<S>) { fn add_assign(&mut self, other: ToolRouter<S>) {
self.merge(other); self.merge(other);

View file

@ -1,4 +1,4 @@
use std::{borrow::Cow, pin::Pin, sync::Arc}; use std::{borrow::Cow, future::Future, sync::Arc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -11,6 +11,7 @@ use crate::{
}, },
model::{Icon, JsonObject, Meta, ToolAnnotations, ToolExecution}, model::{Icon, JsonObject, Meta, ToolAnnotations, ToolExecution},
schemars::JsonSchema, schemars::JsonSchema,
service::{MaybeSend, MaybeSendFuture},
}; };
/// Base trait to define attributes of a tool. /// Base trait to define attributes of a tool.
@ -84,7 +85,8 @@ pub trait ToolBase {
/// ///
/// Consider using [`AsyncTool`] if your workflow involves asynchronous operations. /// Consider using [`AsyncTool`] if your workflow involves asynchronous operations.
/// Examples are shown in [the module-level documentation][crate::handler::server::router::tool]. /// Examples are shown in [the module-level documentation][crate::handler::server::router::tool].
pub trait SyncTool<S: Sync + Send + 'static>: ToolBase { #[allow(private_bounds)]
pub trait SyncTool<S: MaybeSend + 'static>: ToolBase {
fn invoke(service: &S, param: Self::Parameter) -> Result<Self::Output, Self::Error>; fn invoke(service: &S, param: Self::Parameter) -> Result<Self::Output, Self::Error>;
} }
@ -92,11 +94,12 @@ pub trait SyncTool<S: Sync + Send + 'static>: ToolBase {
/// ///
/// Consider using [`SyncTool`] if your workflow does not involve asynchronous operations. /// Consider using [`SyncTool`] if your workflow does not involve asynchronous operations.
/// Examples are shown in [the module-level documentation][crate::handler::server::router::tool]. /// Examples are shown in [the module-level documentation][crate::handler::server::router::tool].
pub trait AsyncTool<S: Sync + Send + 'static>: ToolBase { #[allow(private_bounds)]
pub trait AsyncTool<S: MaybeSend + 'static>: ToolBase {
fn invoke( fn invoke(
service: &S, service: &S,
param: Self::Parameter, param: Self::Parameter,
) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send; ) -> impl Future<Output = Result<Self::Output, Self::Error>> + MaybeSendFuture;
} }
pub(crate) fn tool_attribute<T: ToolBase>() -> crate::model::Tool { pub(crate) fn tool_attribute<T: ToolBase>() -> crate::model::Tool {
@ -113,14 +116,14 @@ pub(crate) fn tool_attribute<T: ToolBase>() -> crate::model::Tool {
} }
} }
pub(crate) fn sync_tool_wrapper<S: Sync + Send + 'static, T: SyncTool<S>>( pub(crate) fn sync_tool_wrapper<S: MaybeSend + 'static, T: SyncTool<S>>(
service: &S, service: &S,
Parameters(params): Parameters<T::Parameter>, Parameters(params): Parameters<T::Parameter>,
) -> Result<Json<T::Output>, ErrorData> { ) -> Result<Json<T::Output>, ErrorData> {
T::invoke(service, params).map(Json).map_err(Into::into) T::invoke(service, params).map(Json).map_err(Into::into)
} }
pub(crate) fn sync_tool_wrapper_with_empty_params<S: Sync + Send + 'static, T: SyncTool<S>>( pub(crate) fn sync_tool_wrapper_with_empty_params<S: MaybeSend + 'static, T: SyncTool<S>>(
service: &S, service: &S,
) -> Result<Json<T::Output>, ErrorData> { ) -> Result<Json<T::Output>, ErrorData> {
T::invoke(service, T::Parameter::default()) T::invoke(service, T::Parameter::default())
@ -128,11 +131,10 @@ pub(crate) fn sync_tool_wrapper_with_empty_params<S: Sync + Send + 'static, T: S
.map_err(Into::into) .map_err(Into::into)
} }
#[expect(clippy::type_complexity)] pub(crate) fn async_tool_wrapper<S: MaybeSend + 'static, T: AsyncTool<S>>(
pub(crate) fn async_tool_wrapper<S: Sync + Send + 'static, T: AsyncTool<S>>(
service: &S, service: &S,
Parameters(params): Parameters<T::Parameter>, Parameters(params): Parameters<T::Parameter>,
) -> Pin<Box<dyn Future<Output = Result<Json<T::Output>, ErrorData>> + Send + '_>> { ) -> crate::service::MaybeBoxFuture<'_, Result<Json<T::Output>, ErrorData>> {
Box::pin(async move { Box::pin(async move {
T::invoke(service, params) T::invoke(service, params)
.await .await
@ -141,10 +143,9 @@ pub(crate) fn async_tool_wrapper<S: Sync + Send + 'static, T: AsyncTool<S>>(
}) })
} }
#[expect(clippy::type_complexity)] pub(crate) fn async_tool_wrapper_with_empty_params<S: MaybeSend + 'static, T: AsyncTool<S>>(
pub(crate) fn async_tool_wrapper_with_empty_params<S: Sync + Send + 'static, T: AsyncTool<S>>(
service: &S, service: &S,
) -> Pin<Box<dyn Future<Output = Result<Json<T::Output>, ErrorData>> + Send + '_>> { ) -> crate::service::MaybeBoxFuture<'_, Result<Json<T::Output>, ErrorData>> {
Box::pin(async move { Box::pin(async move {
T::invoke(service, T::Parameter::default()) T::invoke(service, T::Parameter::default())
.await .await

View file

@ -4,7 +4,8 @@ use std::{
marker::PhantomData, marker::PhantomData,
}; };
use futures::future::{BoxFuture, FutureExt}; #[cfg(not(feature = "local"))]
use futures::future::BoxFuture;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use super::common::{AsRequestContext, FromContextPart}; use super::common::{AsRequestContext, FromContextPart};
@ -16,7 +17,7 @@ use crate::{
RoleServer, RoleServer,
handler::server::wrapper::Parameters, handler::server::wrapper::Parameters,
model::{CallToolRequestParams, CallToolResult, IntoContents, JsonObject}, model::{CallToolRequestParams, CallToolResult, IntoContents, JsonObject},
service::RequestContext, service::{MaybeBoxFuture, MaybeSend, MaybeSendFuture, RequestContext},
}; };
/// Deserialize a JSON object into a type /// Deserialize a JSON object into a type
@ -146,13 +147,21 @@ pub trait CallToolHandler<S, A> {
fn call( fn call(
self, self,
context: ToolCallContext<'_, S>, context: ToolCallContext<'_, S>,
) -> BoxFuture<'_, Result<CallToolResult, crate::ErrorData>>; ) -> MaybeBoxFuture<'_, Result<CallToolResult, crate::ErrorData>>;
} }
#[cfg(not(feature = "local"))]
pub type DynCallToolHandler<S> = dyn for<'s> Fn(ToolCallContext<'s, S>) -> BoxFuture<'s, Result<CallToolResult, crate::ErrorData>> pub type DynCallToolHandler<S> = dyn for<'s> Fn(ToolCallContext<'s, S>) -> BoxFuture<'s, Result<CallToolResult, crate::ErrorData>>
+ Send + Send
+ Sync; + Sync;
#[cfg(feature = "local")]
pub type DynCallToolHandler<S> =
dyn for<'s> Fn(
ToolCallContext<'s, S>,
)
-> futures::future::LocalBoxFuture<'s, Result<CallToolResult, crate::ErrorData>>;
// Tool-specific extractor for tool name // Tool-specific extractor for tool name
pub struct ToolName(pub Cow<'static, str>); pub struct ToolName(pub Cow<'static, str>);
@ -189,7 +198,7 @@ impl<S> FromContextPart<ToolCallContext<'_, S>> for JsonObject {
} }
impl<'s, S> ToolCallContext<'s, S> { impl<'s, S> ToolCallContext<'s, S> {
pub fn invoke<H, A>(self, h: H) -> BoxFuture<'s, Result<CallToolResult, crate::ErrorData>> pub fn invoke<H, A>(self, h: H) -> MaybeBoxFuture<'s, Result<CallToolResult, crate::ErrorData>>
where where
H: CallToolHandler<S, A>, H: CallToolHandler<S, A>,
{ {
@ -221,31 +230,31 @@ macro_rules! impl_for {
$( $(
$Tn: for<'a> FromContextPart<ToolCallContext<'a, S>> , $Tn: for<'a> FromContextPart<ToolCallContext<'a, S>> ,
)* )*
F: FnOnce(&S, $($Tn,)*) -> BoxFuture<'_, R>, F: FnOnce(&S, $($Tn,)*) -> MaybeBoxFuture<'_, R>,
// Need RTN support here(I guess), https://github.com/rust-lang/rust/pull/138424 // Need RTN support here(I guess), https://github.com/rust-lang/rust/pull/138424
// Fut: Future<Output = R> + Send + 'a, // Fut: Future<Output = R> + Send + 'a,
R: IntoCallToolResult + Send + 'static, R: IntoCallToolResult + MaybeSendFuture + 'static,
S: Send + Sync + 'static, S: MaybeSend + 'static,
{ {
#[allow(unused_variables, non_snake_case, unused_mut)] #[allow(unused_variables, non_snake_case, unused_mut)]
fn call( fn call(
self, self,
mut context: ToolCallContext<'_, S>, mut context: ToolCallContext<'_, S>,
) -> BoxFuture<'_, Result<CallToolResult, crate::ErrorData>>{ ) -> MaybeBoxFuture<'_, Result<CallToolResult, crate::ErrorData>>{
$( $(
let result = $Tn::from_context_part(&mut context); let result = $Tn::from_context_part(&mut context);
let $Tn = match result { let $Tn = match result {
Ok(value) => value, Ok(value) => value,
Err(e) => return std::future::ready(Err(e)).boxed(), Err(e) => return Box::pin(std::future::ready(Err(e))),
}; };
)* )*
let service = context.service; let service = context.service;
let fut = self(service, $($Tn,)*); let fut = self(service, $($Tn,)*);
async move { Box::pin(async move {
let result = fut.await; let result = fut.await;
result.into_call_tool_result() result.into_call_tool_result()
}.boxed() })
} }
} }
@ -254,28 +263,28 @@ macro_rules! impl_for {
$( $(
$Tn: for<'a> FromContextPart<ToolCallContext<'a, S>> , $Tn: for<'a> FromContextPart<ToolCallContext<'a, S>> ,
)* )*
F: FnOnce($($Tn,)*) -> Fut + Send + , F: FnOnce($($Tn,)*) -> Fut + MaybeSendFuture,
Fut: Future<Output = R> + Send + 'static, Fut: Future<Output = R> + MaybeSendFuture + 'static,
R: IntoCallToolResult + Send + 'static, R: IntoCallToolResult + MaybeSendFuture + 'static,
S: Send + Sync, S: MaybeSend,
{ {
#[allow(unused_variables, non_snake_case, unused_mut)] #[allow(unused_variables, non_snake_case, unused_mut)]
fn call( fn call(
self, self,
mut context: ToolCallContext<S>, mut context: ToolCallContext<S>,
) -> BoxFuture<'static, Result<CallToolResult, crate::ErrorData>>{ ) -> MaybeBoxFuture<'static, Result<CallToolResult, crate::ErrorData>>{
$( $(
let result = $Tn::from_context_part(&mut context); let result = $Tn::from_context_part(&mut context);
let $Tn = match result { let $Tn = match result {
Ok(value) => value, Ok(value) => value,
Err(e) => return std::future::ready(Err(e)).boxed(), Err(e) => return Box::pin(std::future::ready(Err(e))),
}; };
)* )*
let fut = self($($Tn,)*); let fut = self($($Tn,)*);
async move { Box::pin(async move {
let result = fut.await; let result = fut.await;
result.into_call_tool_result() result.into_call_tool_result()
}.boxed() })
} }
} }
@ -284,23 +293,23 @@ macro_rules! impl_for {
$( $(
$Tn: for<'a> FromContextPart<ToolCallContext<'a, S>> + , $Tn: for<'a> FromContextPart<ToolCallContext<'a, S>> + ,
)* )*
F: FnOnce(&S, $($Tn,)*) -> R + Send + , F: FnOnce(&S, $($Tn,)*) -> R + MaybeSendFuture,
R: IntoCallToolResult + Send + , R: IntoCallToolResult + MaybeSendFuture,
S: Send + Sync, S: MaybeSend,
{ {
#[allow(unused_variables, non_snake_case, unused_mut)] #[allow(unused_variables, non_snake_case, unused_mut)]
fn call( fn call(
self, self,
mut context: ToolCallContext<S>, mut context: ToolCallContext<S>,
) -> BoxFuture<'static, Result<CallToolResult, crate::ErrorData>> { ) -> MaybeBoxFuture<'static, Result<CallToolResult, crate::ErrorData>> {
$( $(
let result = $Tn::from_context_part(&mut context); let result = $Tn::from_context_part(&mut context);
let $Tn = match result { let $Tn = match result {
Ok(value) => value, Ok(value) => value,
Err(e) => return std::future::ready(Err(e)).boxed(), Err(e) => return Box::pin(std::future::ready(Err(e))),
}; };
)* )*
std::future::ready(self(context.service, $($Tn,)*).into_call_tool_result()).boxed() Box::pin(std::future::ready(self(context.service, $($Tn,)*).into_call_tool_result()))
} }
} }
@ -309,23 +318,23 @@ macro_rules! impl_for {
$( $(
$Tn: for<'a> FromContextPart<ToolCallContext<'a, S>> + , $Tn: for<'a> FromContextPart<ToolCallContext<'a, S>> + ,
)* )*
F: FnOnce($($Tn,)*) -> R + Send + , F: FnOnce($($Tn,)*) -> R + MaybeSendFuture,
R: IntoCallToolResult + Send + , R: IntoCallToolResult + MaybeSendFuture,
S: Send + Sync, S: MaybeSend,
{ {
#[allow(unused_variables, non_snake_case, unused_mut)] #[allow(unused_variables, non_snake_case, unused_mut)]
fn call( fn call(
self, self,
mut context: ToolCallContext<S>, mut context: ToolCallContext<S>,
) -> BoxFuture<'static, Result<CallToolResult, crate::ErrorData>> { ) -> MaybeBoxFuture<'static, Result<CallToolResult, crate::ErrorData>> {
$( $(
let result = $Tn::from_context_part(&mut context); let result = $Tn::from_context_part(&mut context);
let $Tn = match result { let $Tn = match result {
Ok(value) => value, Ok(value) => value,
Err(e) => return std::future::ready(Err(e)).boxed(), Err(e) => return Box::pin(std::future::ready(Err(e))),
}; };
)* )*
std::future::ready(self($($Tn,)*).into_call_tool_result()).boxed() Box::pin(std::future::ready(self($($Tn,)*).into_call_tool_result()))
} }
} }
}; };

View file

@ -1,6 +1,47 @@
use futures::{FutureExt, future::BoxFuture}; use futures::FutureExt;
#[cfg(not(feature = "local"))]
use futures::future::BoxFuture;
#[cfg(feature = "local")]
use futures::future::LocalBoxFuture;
use thiserror::Error; use thiserror::Error;
// ---------------------------------------------------------------------------
// Conditional Send helpers
//
// `MaybeSend` supertrait alias: `Send + Sync` without `local`, empty with `local`
// `MaybeSendFuture` future bound alias: `Send` without `local`, empty with `local`
// `MaybeBoxFuture` boxed future type: `BoxFuture` without `local`, `LocalBoxFuture` with `local`
// ---------------------------------------------------------------------------
#[cfg(not(feature = "local"))]
#[doc(hidden)]
pub trait MaybeSend: Send + Sync {}
#[cfg(not(feature = "local"))]
impl<T: Send + Sync> MaybeSend for T {}
#[cfg(feature = "local")]
#[doc(hidden)]
pub trait MaybeSend {}
#[cfg(feature = "local")]
impl<T> MaybeSend for T {}
#[cfg(not(feature = "local"))]
#[doc(hidden)]
pub trait MaybeSendFuture: Send {}
#[cfg(not(feature = "local"))]
impl<T: Send> MaybeSendFuture for T {}
#[cfg(feature = "local")]
#[doc(hidden)]
pub trait MaybeSendFuture {}
#[cfg(feature = "local")]
impl<T> MaybeSendFuture for T {}
#[cfg(not(feature = "local"))]
pub(crate) type MaybeBoxFuture<'a, T> = BoxFuture<'a, T>;
#[cfg(feature = "local")]
pub(crate) type MaybeBoxFuture<'a, T> = LocalBoxFuture<'a, T>;
#[cfg(feature = "server")] #[cfg(feature = "server")]
use crate::model::ServerJsonRpcMessage; use crate::model::ServerJsonRpcMessage;
use crate::{ use crate::{
@ -87,17 +128,21 @@ pub type RxJsonRpcMessage<R> = JsonRpcMessage<
<R as ServiceRole>::PeerNot, <R as ServiceRole>::PeerNot,
>; >;
pub trait Service<R: ServiceRole>: Send + Sync + 'static { #[allow(
private_bounds,
reason = "MaybeSend is a sealed conditional Send + Sync alias"
)]
pub trait Service<R: ServiceRole>: MaybeSend + 'static {
fn handle_request( fn handle_request(
&self, &self,
request: R::PeerReq, request: R::PeerReq,
context: RequestContext<R>, context: RequestContext<R>,
) -> impl Future<Output = Result<R::Resp, McpError>> + Send + '_; ) -> impl Future<Output = Result<R::Resp, McpError>> + MaybeSendFuture + '_;
fn handle_notification( fn handle_notification(
&self, &self,
notification: R::PeerNot, notification: R::PeerNot,
context: NotificationContext<R>, context: NotificationContext<R>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_; ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_;
fn get_info(&self) -> R::Info; fn get_info(&self) -> R::Info;
} }
@ -111,7 +156,7 @@ pub trait ServiceExt<R: ServiceRole>: Service<R> + Sized {
fn serve<T, E, A>( fn serve<T, E, A>(
self, self,
transport: T, transport: T,
) -> impl Future<Output = Result<RunningService<R, Self>, R::InitializeError>> + Send ) -> impl Future<Output = Result<RunningService<R, Self>, R::InitializeError>> + MaybeSendFuture
where where
T: IntoTransport<R, E, A>, T: IntoTransport<R, E, A>,
E: std::error::Error + Send + Sync + 'static, E: std::error::Error + Send + Sync + 'static,
@ -123,7 +168,7 @@ pub trait ServiceExt<R: ServiceRole>: Service<R> + Sized {
self, self,
transport: T, transport: T,
ct: CancellationToken, ct: CancellationToken,
) -> impl Future<Output = Result<RunningService<R, Self>, R::InitializeError>> + Send ) -> impl Future<Output = Result<RunningService<R, Self>, R::InitializeError>> + MaybeSendFuture
where where
T: IntoTransport<R, E, A>, T: IntoTransport<R, E, A>,
E: std::error::Error + Send + Sync + 'static, E: std::error::Error + Send + Sync + 'static,
@ -135,7 +180,7 @@ impl<R: ServiceRole> Service<R> for Box<dyn DynService<R>> {
&self, &self,
request: R::PeerReq, request: R::PeerReq,
context: RequestContext<R>, context: RequestContext<R>,
) -> impl Future<Output = Result<R::Resp, McpError>> + Send + '_ { ) -> impl Future<Output = Result<R::Resp, McpError>> + MaybeSendFuture + '_ {
DynService::handle_request(self.as_ref(), request, context) DynService::handle_request(self.as_ref(), request, context)
} }
@ -143,7 +188,7 @@ impl<R: ServiceRole> Service<R> for Box<dyn DynService<R>> {
&self, &self,
notification: R::PeerNot, notification: R::PeerNot,
context: NotificationContext<R>, context: NotificationContext<R>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
DynService::handle_notification(self.as_ref(), notification, context) DynService::handle_notification(self.as_ref(), notification, context)
} }
@ -152,17 +197,21 @@ impl<R: ServiceRole> Service<R> for Box<dyn DynService<R>> {
} }
} }
pub trait DynService<R: ServiceRole>: Send + Sync { #[allow(
private_bounds,
reason = "MaybeSend is a sealed conditional Send + Sync alias"
)]
pub trait DynService<R: ServiceRole>: MaybeSend {
fn handle_request( fn handle_request(
&self, &self,
request: R::PeerReq, request: R::PeerReq,
context: RequestContext<R>, context: RequestContext<R>,
) -> BoxFuture<'_, Result<R::Resp, McpError>>; ) -> MaybeBoxFuture<'_, Result<R::Resp, McpError>>;
fn handle_notification( fn handle_notification(
&self, &self,
notification: R::PeerNot, notification: R::PeerNot,
context: NotificationContext<R>, context: NotificationContext<R>,
) -> BoxFuture<'_, Result<(), McpError>>; ) -> MaybeBoxFuture<'_, Result<(), McpError>>;
fn get_info(&self) -> R::Info; fn get_info(&self) -> R::Info;
} }
@ -171,14 +220,14 @@ impl<R: ServiceRole, S: Service<R>> DynService<R> for S {
&self, &self,
request: R::PeerReq, request: R::PeerReq,
context: RequestContext<R>, context: RequestContext<R>,
) -> BoxFuture<'_, Result<R::Resp, McpError>> { ) -> MaybeBoxFuture<'_, Result<R::Resp, McpError>> {
Box::pin(self.handle_request(request, context)) Box::pin(self.handle_request(request, context))
} }
fn handle_notification( fn handle_notification(
&self, &self,
notification: R::PeerNot, notification: R::PeerNot,
context: NotificationContext<R>, context: NotificationContext<R>,
) -> BoxFuture<'_, Result<(), McpError>> { ) -> MaybeBoxFuture<'_, Result<(), McpError>> {
Box::pin(self.handle_notification(notification, context)) Box::pin(self.handle_notification(notification, context))
} }
fn get_info(&self) -> R::Info { fn get_info(&self) -> R::Info {
@ -639,6 +688,28 @@ where
serve_inner(service, transport.into_transport(), peer, peer_rx, ct) serve_inner(service, transport.into_transport(), peer, peer_rx, ct)
} }
/// Spawn a task that may hold `!Send` state when the `local` feature is active.
///
/// Without the `local` feature this is `tokio::spawn` (requires `Future: Send + 'static`).
/// With `local` it uses `tokio::task::spawn_local` (requires only `Future: 'static`).
#[cfg(not(feature = "local"))]
fn spawn_service_task<F>(future: F) -> tokio::task::JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
tokio::spawn(future)
}
#[cfg(feature = "local")]
fn spawn_service_task<F>(future: F) -> tokio::task::JoinHandle<F::Output>
where
F: Future + 'static,
F::Output: 'static,
{
tokio::task::spawn_local(future)
}
#[instrument(skip_all)] #[instrument(skip_all)]
fn serve_inner<R, S, T>( fn serve_inner<R, S, T>(
service: S, service: S,
@ -674,7 +745,7 @@ where
let serve_loop_ct = ct.child_token(); let serve_loop_ct = ct.child_token();
let peer_return: Peer<R> = peer.clone(); let peer_return: Peer<R> = peer.clone();
let current_span = tracing::Span::current(); let current_span = tracing::Span::current();
let handle = tokio::spawn(async move { let handle = spawn_service_task(async move {
let mut transport = transport.into_transport(); let mut transport = transport.into_transport();
let mut batch_messages = VecDeque::<RxJsonRpcMessage<R>>::new(); let mut batch_messages = VecDeque::<RxJsonRpcMessage<R>>::new();
let mut send_task_set = tokio::task::JoinSet::<SendTaskResult>::new(); let mut send_task_set = tokio::task::JoinSet::<SendTaskResult>::new();
@ -860,7 +931,7 @@ where
extensions, extensions,
}; };
let current_span = tracing::Span::current(); let current_span = tracing::Span::current();
tokio::spawn(async move { spawn_service_task(async move {
let result = service let result = service
.handle_request(request, context) .handle_request(request, context)
.await; .await;
@ -907,7 +978,7 @@ where
extensions, extensions,
}; };
let current_span = tracing::Span::current(); let current_span = tracing::Span::current();
tokio::spawn(async move { spawn_service_task(async move {
let result = service.handle_notification(notification, context).await; let result = service.handle_notification(notification, context).await;
if let Err(error) = result { if let Err(error) = result {
tracing::warn!(%error, "Error sending notification"); tracing::warn!(%error, "Error sending notification");

View file

@ -162,7 +162,8 @@ impl<S: Service<RoleClient>> ServiceExt<RoleClient> for S {
self, self,
transport: T, transport: T,
ct: CancellationToken, ct: CancellationToken,
) -> impl Future<Output = Result<RunningService<RoleClient, Self>, ClientInitializeError>> + Send ) -> impl Future<Output = Result<RunningService<RoleClient, Self>, ClientInitializeError>>
+ MaybeSendFuture
where where
T: IntoTransport<RoleClient, E, A>, T: IntoTransport<RoleClient, E, A>,
E: std::error::Error + Send + Sync + 'static, E: std::error::Error + Send + Sync + 'static,

View file

@ -95,7 +95,8 @@ impl<S: Service<RoleServer>> ServiceExt<RoleServer> for S {
self, self,
transport: T, transport: T,
ct: CancellationToken, ct: CancellationToken,
) -> impl Future<Output = Result<RunningService<RoleServer, Self>, ServerInitializeError>> + Send ) -> impl Future<Output = Result<RunningService<RoleServer, Self>, ServerInitializeError>>
+ MaybeSendFuture
where where
T: IntoTransport<RoleServer, E, A>, T: IntoTransport<RoleServer, E, A>,
E: std::error::Error + Send + Sync + 'static, E: std::error::Error + Send + Sync + 'static,

View file

@ -3,7 +3,7 @@ use std::{future::poll_fn, marker::PhantomData};
use tower_service::Service as TowerService; use tower_service::Service as TowerService;
use super::NotificationContext; use super::NotificationContext;
use crate::service::{RequestContext, Service, ServiceRole}; use crate::service::{MaybeSendFuture, RequestContext, Service, ServiceRole};
pub struct TowerHandler<S, R: ServiceRole> { pub struct TowerHandler<S, R: ServiceRole> {
pub service: S, pub service: S,
@ -44,7 +44,7 @@ where
&self, &self,
_notification: R::PeerNot, _notification: R::PeerNot,
_context: NotificationContext<R>, _context: NotificationContext<R>,
) -> impl Future<Output = Result<(), crate::ErrorData>> + Send + '_ { ) -> impl Future<Output = Result<(), crate::ErrorData>> + MaybeSendFuture + '_ {
std::future::ready(Ok(())) std::future::ready(Ok(()))
} }

View file

@ -7,7 +7,7 @@
//! | transport | client | server | //! | transport | client | server |
//! |:-: |:-: |:-: | //! |:-: |:-: |:-: |
//! | std IO | [`child_process::TokioChildProcess`] | [`io::stdio`] | //! | std IO | [`child_process::TokioChildProcess`] | [`io::stdio`] |
//! | streamable http | [`streamable_http_client::StreamableHttpClientTransport`] | [`streamable_http_server::StreamableHttpService`] | //! | streamable http | [`streamable_http_client::StreamableHttpClientTransport`] | `streamable_http_server::StreamableHttpService` |
//! //!
//## Helper Transport Types //## Helper Transport Types
//! Thers are several helper transport types that can help you to create transport quickly. //! Thers are several helper transport types that can help you to create transport quickly.
@ -107,7 +107,7 @@ pub use auth::{
// pub mod ws; // pub mod ws;
#[cfg(feature = "transport-streamable-http-server-session")] #[cfg(feature = "transport-streamable-http-server-session")]
pub mod streamable_http_server; pub mod streamable_http_server;
#[cfg(feature = "transport-streamable-http-server")] #[cfg(all(feature = "transport-streamable-http-server", not(feature = "local")))]
pub use streamable_http_server::tower::{StreamableHttpServerConfig, StreamableHttpService}; pub use streamable_http_server::tower::{StreamableHttpServerConfig, StreamableHttpService};
#[cfg(feature = "transport-streamable-http-client")] #[cfg(feature = "transport-streamable-http-client")]

View file

@ -1,6 +1,6 @@
pub mod session; pub mod session;
#[cfg(feature = "transport-streamable-http-server")] #[cfg(all(feature = "transport-streamable-http-server", not(feature = "local")))]
pub mod tower; pub mod tower;
pub use session::{SessionId, SessionManager}; pub use session::{SessionId, SessionManager};
#[cfg(feature = "transport-streamable-http-server")] #[cfg(all(feature = "transport-streamable-http-server", not(feature = "local")))]
pub use tower::{StreamableHttpServerConfig, StreamableHttpService}; pub use tower::{StreamableHttpServerConfig, StreamableHttpService};

View file

@ -33,7 +33,7 @@ pub mod never;
/// Controls how MCP sessions are created, validated, and closed. /// Controls how MCP sessions are created, validated, and closed.
/// ///
/// The [`StreamableHttpService`](super::StreamableHttpService) calls into this /// The `StreamableHttpService` calls into this
/// trait for every HTTP request that carries (or should carry) a session ID. /// trait for every HTTP request that carries (or should carry) a session ID.
/// ///
/// See the [module-level docs](self) for background on sessions. /// See the [module-level docs](self) for background on sessions.

View file

@ -204,7 +204,7 @@ impl<S, M> Clone for StreamableHttpService<S, M> {
impl<RequestBody, S, M> tower_service::Service<Request<RequestBody>> for StreamableHttpService<S, M> impl<RequestBody, S, M> tower_service::Service<Request<RequestBody>> for StreamableHttpService<S, M>
where where
RequestBody: Body + Send + 'static, RequestBody: Body + Send + 'static,
S: crate::Service<RoleServer>, S: crate::Service<RoleServer> + Send + 'static,
M: SessionManager, M: SessionManager,
RequestBody::Error: Display, RequestBody::Error: Display,
RequestBody::Data: Send + 'static, RequestBody::Data: Send + 'static,

View file

@ -7,7 +7,11 @@ use std::{
use rmcp::service::NotificationContext; use rmcp::service::NotificationContext;
#[cfg(feature = "client")] #[cfg(feature = "client")]
use rmcp::{ClientHandler, RoleClient}; use rmcp::{ClientHandler, RoleClient};
use rmcp::{ErrorData as McpError, RoleServer, ServerHandler, model::*, service::RequestContext}; use rmcp::{
ErrorData as McpError, RoleServer, ServerHandler,
model::*,
service::{MaybeSendFuture, RequestContext},
};
#[cfg(feature = "client")] #[cfg(feature = "client")]
use serde_json::json; use serde_json::json;
use tokio::sync::Notify; use tokio::sync::Notify;
@ -85,7 +89,7 @@ impl ClientHandler for TestClientHandler {
&self, &self,
params: LoggingMessageNotificationParam, params: LoggingMessageNotificationParam,
_context: NotificationContext<RoleClient>, _context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ { ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
let receive_signal = self.receive_signal.clone(); let receive_signal = self.receive_signal.clone();
let received_messages = self.received_messages.clone(); let received_messages = self.received_messages.clone();
@ -116,7 +120,7 @@ impl ServerHandler for TestServer {
&self, &self,
request: SetLevelRequestParams, request: SetLevelRequestParams,
context: RequestContext<RoleServer>, context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<(), McpError>> + Send + '_ { ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
let peer = context.peer; let peer = context.peer;
async move { async move {
let (data, logger) = match request.level { let (data, logger) = match request.level {

View file

@ -1,5 +1,5 @@
// cargo test --features "server client" --package rmcp test_client_initialization // cargo test --features "server client" --package rmcp test_client_initialization
#![cfg(feature = "client")] #![cfg(all(feature = "client", not(feature = "local")))]
mod common; mod common;

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
//cargo test --test test_close_connection --features "client server" //cargo test --test test_close_connection --features "client server"
mod common; mod common;

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use std::collections::HashMap; use std::collections::HashMap;
use http::{HeaderName, HeaderValue}; use http::{HeaderName, HeaderValue};

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use std::sync::Arc; use std::sync::Arc;
use rmcp::{ use rmcp::{

View file

@ -1,4 +1,5 @@
// cargo test --features "server client" --package rmcp test_logging // cargo test --features "server client" --package rmcp test_logging
#![cfg(not(feature = "local"))]
mod common; mod common;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};

View file

@ -1,4 +1,5 @@
//cargo test --test test_message_protocol --features "client server" //cargo test --test test_message_protocol --features "client server"
#![cfg(not(feature = "local"))]
mod common; mod common;
use common::handlers::{TestClientHandler, TestServer}; use common::handlers::{TestClientHandler, TestServer};

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use std::sync::Arc; use std::sync::Arc;
use rmcp::{ use rmcp::{

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use futures::StreamExt; use futures::StreamExt;
use rmcp::{ use rmcp::{
ClientHandler, Peer, RoleServer, ServerHandler, ServiceExt, ClientHandler, Peer, RoleServer, ServerHandler, ServiceExt,

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
//cargo test --test test_prompt_macros --features "client server" //cargo test --test test_prompt_macros --features "client server"
#![allow(dead_code)] #![allow(dead_code)]
use std::sync::Arc; use std::sync::Arc;

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use std::collections::HashMap; use std::collections::HashMap;
use futures::future::BoxFuture; use futures::future::BoxFuture;

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
mod common; mod common;
use anyhow::Result; use anyhow::Result;

View file

@ -1,5 +1,5 @@
// cargo test --features "client" --package rmcp -- server_init // cargo test --features "client" --package rmcp -- server_init
#![cfg(feature = "client")] #![cfg(all(feature = "client", not(feature = "local")))]
mod common; mod common;
use common::handlers::TestServer; use common::handlers::TestServer;

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
/// Tests for concurrent SSE stream handling (shadow channels) /// Tests for concurrent SSE stream handling (shadow channels)
/// ///
/// These tests verify that multiple GET SSE streams on the same session /// These tests verify that multiple GET SSE streams on the same session

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use rmcp::transport::streamable_http_server::{ use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager, StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
}; };

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use std::time::Duration; use std::time::Duration;
use rmcp::transport::streamable_http_server::{ use rmcp::transport::streamable_http_server::{

View file

@ -1,7 +1,8 @@
#![cfg(all( #![cfg(all(
feature = "transport-streamable-http-client", feature = "transport-streamable-http-client",
feature = "transport-streamable-http-client-reqwest", feature = "transport-streamable-http-client-reqwest",
feature = "transport-streamable-http-server" feature = "transport-streamable-http-server",
not(feature = "local")
))] ))]
use std::{collections::HashMap, sync::Arc}; use std::{collections::HashMap, sync::Arc};

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
//! Tests for task support validation in tool calls. //! Tests for task support validation in tool calls.
//! //!
//! Verifies that the server correctly validates `execution.taskSupport` settings //! Verifies that the server correctly validates `execution.taskSupport` settings

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
//! Test tool macros, including documentation for generated fns. //! Test tool macros, including documentation for generated fns.
//cargo test --test test_tool_macros --features "client server" //cargo test --test test_tool_macros --features "client server"

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use std::collections::HashMap; use std::collections::HashMap;
use futures::future::BoxFuture; use futures::future::BoxFuture;

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use rmcp::{ use rmcp::{
ServiceExt, ServiceExt,
service::QuitReason, service::QuitReason,

View file

@ -1,3 +1,4 @@
#![cfg(not(feature = "local"))]
use std::process::Stdio; use std::process::Stdio;
use rmcp::{ use rmcp::{