pub struct Peer<R: ServiceRole> { /* private fields */ }client or server only.Expand description
An interface to fetch the remote client or server
For general purpose, call Peer::send_request or Peer::send_notification to send message to remote peer.
To create a cancellable request, call Peer::send_request_with_option.
Implementations§
Source§impl Peer<RoleClient>
impl Peer<RoleClient>
pub async fn complete( &self, params: CompleteRequestParams, ) -> Result<CompleteResult, ServiceError>
client only.pub async fn set_level( &self, params: SetLevelRequestParams, ) -> Result<(), ServiceError>
client only.pub async fn get_prompt( &self, params: GetPromptRequestParams, ) -> Result<GetPromptResult, ServiceError>
client only.pub async fn list_prompts( &self, params: Option<PaginatedRequestParams>, ) -> Result<ListPromptsResult, ServiceError>
client only.pub async fn list_resources( &self, params: Option<PaginatedRequestParams>, ) -> Result<ListResourcesResult, ServiceError>
client only.pub async fn list_resource_templates( &self, params: Option<PaginatedRequestParams>, ) -> Result<ListResourceTemplatesResult, ServiceError>
client only.pub async fn read_resource( &self, params: ReadResourceRequestParams, ) -> Result<ReadResourceResult, ServiceError>
client only.pub async fn subscribe( &self, params: SubscribeRequestParams, ) -> Result<(), ServiceError>
client only.pub async fn unsubscribe( &self, params: UnsubscribeRequestParams, ) -> Result<(), ServiceError>
client only.pub async fn call_tool( &self, params: CallToolRequestParams, ) -> Result<CallToolResult, ServiceError>
client only.pub async fn list_tools( &self, params: Option<PaginatedRequestParams>, ) -> Result<ListToolsResult, ServiceError>
client only.pub async fn notify_cancelled( &self, params: CancelledNotificationParam, ) -> Result<(), ServiceError>
client only.pub async fn notify_progress( &self, params: ProgressNotificationParam, ) -> Result<(), ServiceError>
client only.pub async fn notify_initialized(&self) -> Result<(), ServiceError>
client only.pub async fn notify_roots_list_changed(&self) -> Result<(), ServiceError>
client only.Source§impl Peer<RoleClient>
impl Peer<RoleClient>
Sourcepub async fn list_all_tools(&self) -> Result<Vec<Tool>, ServiceError>
Available on crate feature client only.
pub async fn list_all_tools(&self) -> Result<Vec<Tool>, ServiceError>
client only.A wrapper method for Peer<RoleClient>::list_tools.
This function will call Peer<RoleClient>::list_tools multiple times until all tools are listed.
Sourcepub async fn list_all_prompts(&self) -> Result<Vec<Prompt>, ServiceError>
Available on crate feature client only.
pub async fn list_all_prompts(&self) -> Result<Vec<Prompt>, ServiceError>
client only.A wrapper method for Peer<RoleClient>::list_prompts.
This function will call Peer<RoleClient>::list_prompts multiple times until all prompts are listed.
Sourcepub async fn list_all_resources(&self) -> Result<Vec<Resource>, ServiceError>
Available on crate feature client only.
pub async fn list_all_resources(&self) -> Result<Vec<Resource>, ServiceError>
client only.A wrapper method for Peer<RoleClient>::list_resources.
This function will call Peer<RoleClient>::list_resources multiple times until all resources are listed.
Sourcepub async fn list_all_resource_templates(
&self,
) -> Result<Vec<ResourceTemplate>, ServiceError>
Available on crate feature client only.
pub async fn list_all_resource_templates( &self, ) -> Result<Vec<ResourceTemplate>, ServiceError>
client only.A wrapper method for Peer<RoleClient>::list_resource_templates.
This function will call Peer<RoleClient>::list_resource_templates multiple times until all resource templates are listed.
Sourcepub async fn complete_prompt_argument(
&self,
prompt_name: impl Into<String>,
argument_name: impl Into<String>,
current_value: impl Into<String>,
context: Option<CompletionContext>,
) -> Result<CompletionInfo, ServiceError>
Available on crate feature client only.
pub async fn complete_prompt_argument( &self, prompt_name: impl Into<String>, argument_name: impl Into<String>, current_value: impl Into<String>, context: Option<CompletionContext>, ) -> Result<CompletionInfo, ServiceError>
client only.Convenient method to get completion suggestions for a prompt argument
§Arguments
prompt_name- Name of the prompt being completedargument_name- Name of the argument being completedcurrent_value- Current partial value of the argumentcontext- Optional context with previously resolved arguments
§Returns
CompletionInfo with suggestions for the specified prompt argument
Sourcepub async fn complete_resource_argument(
&self,
uri_template: impl Into<String>,
argument_name: impl Into<String>,
current_value: impl Into<String>,
context: Option<CompletionContext>,
) -> Result<CompletionInfo, ServiceError>
Available on crate feature client only.
pub async fn complete_resource_argument( &self, uri_template: impl Into<String>, argument_name: impl Into<String>, current_value: impl Into<String>, context: Option<CompletionContext>, ) -> Result<CompletionInfo, ServiceError>
client only.Convenient method to get completion suggestions for a resource URI argument
§Arguments
uri_template- URI template pattern being completedargument_name- Name of the URI parameter being completedcurrent_value- Current partial value of the parametercontext- Optional context with previously resolved arguments
§Returns
CompletionInfo with suggestions for the specified resource URI argument
Sourcepub async fn complete_prompt_simple(
&self,
prompt_name: impl Into<String>,
argument_name: impl Into<String>,
current_value: impl Into<String>,
) -> Result<Vec<String>, ServiceError>
Available on crate feature client only.
pub async fn complete_prompt_simple( &self, prompt_name: impl Into<String>, argument_name: impl Into<String>, current_value: impl Into<String>, ) -> Result<Vec<String>, ServiceError>
client only.Simple completion for a prompt argument without context
This is a convenience wrapper around complete_prompt_argument for
simple completion scenarios that don’t require context awareness.
Sourcepub async fn complete_resource_simple(
&self,
uri_template: impl Into<String>,
argument_name: impl Into<String>,
current_value: impl Into<String>,
) -> Result<Vec<String>, ServiceError>
Available on crate feature client only.
pub async fn complete_resource_simple( &self, uri_template: impl Into<String>, argument_name: impl Into<String>, current_value: impl Into<String>, ) -> Result<Vec<String>, ServiceError>
client only.Simple completion for a resource URI argument without context
This is a convenience wrapper around complete_resource_argument for
simple completion scenarios that don’t require context awareness.
Source§impl Peer<RoleServer>
impl Peer<RoleServer>
Sourcepub fn supports_sampling_tools(&self) -> bool
Available on crate feature server only.
pub fn supports_sampling_tools(&self) -> bool
server only.Check if the client supports sampling tools capability.
pub async fn create_message( &self, params: CreateMessageRequestParams, ) -> Result<CreateMessageResult, ServiceError>
server only.pub async fn list_roots(&self) -> Result<ListRootsResult, ServiceError>
server only.pub async fn create_elicitation( &self, params: CreateElicitationRequestParams, ) -> Result<CreateElicitationResult, ServiceError>
server only.pub async fn create_elicitation_with_timeout( &self, params: CreateElicitationRequestParams, timeout: Option<Duration>, ) -> Result<CreateElicitationResult, ServiceError>
server only.pub async fn notify_url_elicitation_completed( &self, params: ElicitationResponseNotificationParam, ) -> Result<(), ServiceError>
server only.pub async fn notify_cancelled( &self, params: CancelledNotificationParam, ) -> Result<(), ServiceError>
server only.pub async fn notify_progress( &self, params: ProgressNotificationParam, ) -> Result<(), ServiceError>
server only.pub async fn notify_logging_message( &self, params: LoggingMessageNotificationParam, ) -> Result<(), ServiceError>
server only.pub async fn notify_resource_updated( &self, params: ResourceUpdatedNotificationParam, ) -> Result<(), ServiceError>
server only.pub async fn notify_resource_list_changed(&self) -> Result<(), ServiceError>
server only.pub async fn notify_tool_list_changed(&self) -> Result<(), ServiceError>
server only.pub async fn notify_prompt_list_changed(&self) -> Result<(), ServiceError>
server only.Source§impl Peer<RoleServer>
impl Peer<RoleServer>
Sourcepub fn supported_elicitation_modes(&self) -> HashSet<ElicitationMode>
Available on crate features server and elicitation only.
pub fn supported_elicitation_modes(&self) -> HashSet<ElicitationMode>
server and elicitation only.Check if the client supports elicitation capability
Returns true if the client declared elicitation capability during initialization, false otherwise. According to MCP 2025-06-18 specification, clients that support elicitation MUST declare the capability during initialization.
Sourcepub async fn elicit<T>(
&self,
message: impl Into<String>,
) -> Result<Option<T>, ElicitationError>where
T: ElicitationSafe + for<'de> Deserialize<'de>,
Available on crate features server and elicitation and schemars only.
pub async fn elicit<T>(
&self,
message: impl Into<String>,
) -> Result<Option<T>, ElicitationError>where
T: ElicitationSafe + for<'de> Deserialize<'de>,
server and elicitation and schemars only.Request typed data from the user with automatic schema generation.
This method automatically generates the JSON schema from the Rust type using schemars,
eliminating the need to manually create schemas. The response is automatically parsed
into the requested type.
Requires the elicitation feature to be enabled.
§Type Requirements
The type T must implement:
schemars::JsonSchema- for automatic schema generationserde::Deserialize- for parsing the response
§Arguments
message- The prompt message for the user
§Returns
Ok(Some(data))if user provided valid data that matches type TErr(ElicitationError::UserDeclined)if user explicitly declined the requestErr(ElicitationError::UserCancelled)if user cancelled/dismissed the requestErr(ElicitationError::ParseError { .. })if response data couldn’t be parsed into type TErr(ElicitationError::NoContent)if no response content was providedErr(ElicitationError::Service(_))if the underlying service call failed
§Example
Add to your Cargo.toml:
[dependencies]
rmcp = { version = "0.3", features = ["elicitation"] }
serde = { version = "1.0", features = ["derive"] }
schemars = "1.0"#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct UserProfile {
#[schemars(description = "Full name")]
name: String,
#[schemars(description = "Email address")]
email: String,
#[schemars(description = "Age")]
age: u8,
}
// Mark as safe for elicitation (generates object schema)
rmcp::elicit_safe!(UserProfile);
match peer.elicit::<UserProfile>("Please enter your profile information").await {
Ok(Some(profile)) => {
println!("Name: {}, Email: {}, Age: {}", profile.name, profile.email, profile.age);
}
Ok(None) => {
println!("User provided no content");
}
Err(ElicitationError::UserDeclined) => {
println!("User explicitly declined to provide information");
// Handle explicit decline - perhaps offer alternatives
}
Err(ElicitationError::UserCancelled) => {
println!("User cancelled the request");
// Handle cancellation - perhaps prompt again later
}
Err(ElicitationError::ParseError { error, data }) => {
println!("Failed to parse response: {}\nData: {}", error, data);
}
Err(e) => return Err(e.into()),
}Sourcepub async fn elicit_with_timeout<T>(
&self,
message: impl Into<String>,
timeout: Option<Duration>,
) -> Result<Option<T>, ElicitationError>where
T: ElicitationSafe + for<'de> Deserialize<'de>,
Available on crate features server and elicitation and schemars only.
pub async fn elicit_with_timeout<T>(
&self,
message: impl Into<String>,
timeout: Option<Duration>,
) -> Result<Option<T>, ElicitationError>where
T: ElicitationSafe + for<'de> Deserialize<'de>,
server and elicitation and schemars only.Request typed data from the user with custom timeout.
Same as elicit() but allows specifying a custom timeout for the request.
If the user doesn’t respond within the timeout, the request will be cancelled.
§Arguments
message- The prompt message for the usertimeout- Optional timeout duration. If None, uses default timeout behavior
§Returns
Same as elicit() but may also return ServiceError::Timeout if timeout expires
§Example
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct QuickResponse {
answer: String,
}
// Mark as safe for elicitation
rmcp::elicit_safe!(QuickResponse);
// Give user 30 seconds to respond
let timeout = Some(Duration::from_secs(30));
match peer.elicit_with_timeout::<QuickResponse>(
"Quick question - what's your answer?",
timeout
).await {
Ok(Some(response)) => println!("Got answer: {}", response.answer),
Ok(None) => println!("User provided no content"),
Err(ElicitationError::UserDeclined) => {
println!("User explicitly declined");
// Handle explicit decline
}
Err(ElicitationError::UserCancelled) => {
println!("User cancelled/dismissed");
// Handle cancellation
}
Err(ElicitationError::Service(ServiceError::Timeout { .. })) => {
println!("User didn't respond in time");
}
Err(e) => return Err(e.into()),
}Sourcepub async fn elicit_url(
&self,
message: impl Into<String>,
url: impl Into<Url>,
elicitation_id: impl Into<String>,
) -> Result<ElicitationAction, ElicitationError>
Available on crate features server and elicitation only.
pub async fn elicit_url( &self, message: impl Into<String>, url: impl Into<Url>, elicitation_id: impl Into<String>, ) -> Result<ElicitationAction, ElicitationError>
server and elicitation only.Request the user to visit a URL and confirm completion.
This method sends a URL elicitation request to the client, prompting the user
to visit the specified URL and confirm completion. It returns the user’s action
(accept/decline/cancel) without any additional data.
Requires the elicitation feature to be enabled.
§Arguments
message- The prompt message for the userurl- The URL the user is requested to visitelicitation_id- A unique identifier for this elicitation request
§Returns
Ok(action)indicating the user’s response actionErr(ElicitationError::CapabilityNotSupported)if client does not support elicitation via URLErr(ElicitationError::Service(_))if the underlying service call failed
§Example
async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
let elicit_result = peer.elicit_url("Please visit the following URL to complete the action",
Url::parse("https://example.com/complete_action")?, "elicit_123").await?;
match elicit_result {
ElicitationAction::Accept => {
println!("User accepted and confirmed completion");
}
ElicitationAction::Decline => {
println!("User declined the request");
}
ElicitationAction::Cancel => {
println!("User cancelled/dismissed the request");
}
_ => {}
}
Ok(())
}Sourcepub async fn elicit_url_with_timeout(
&self,
message: impl Into<String>,
url: impl Into<Url>,
elicitation_id: impl Into<String>,
timeout: Option<Duration>,
) -> Result<ElicitationAction, ElicitationError>
Available on crate features server and elicitation only.
pub async fn elicit_url_with_timeout( &self, message: impl Into<String>, url: impl Into<Url>, elicitation_id: impl Into<String>, timeout: Option<Duration>, ) -> Result<ElicitationAction, ElicitationError>
server and elicitation only.Request the user to visit a URL and confirm completion.
Same as elicit_url() but allows specifying a custom timeout for the request.
§Arguments
message- The prompt message for the userurl- The URL the user is requested to visitelicitation_id- A unique identifier for this elicitation requesttimeout- Optional timeout duration. If None, uses default timeout behavior
§Returns
Ok(action)indicating the user’s response actionErr(ElicitationError::CapabilityNotSupported)if client does not support elicitation via URLErr(ElicitationError::Service(_))if the underlying service call failed
§Example
use rmcp::*;
async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
let elicit_result = peer.elicit_url_with_timeout("Please visit the following URL to complete the action",
Url::parse("https://example.com/complete_action")?,
"elicit_123",
Some(Duration::from_secs(30))).await?;
match elicit_result {
ElicitationAction::Accept => {
println!("User accepted and confirmed completion");
}
ElicitationAction::Decline => {
println!("User declined the request");
}
ElicitationAction::Cancel => {
println!("User cancelled/dismissed the request");
}
_ => {}
}
Ok(())
}Source§impl<R: ServiceRole> Peer<R>
impl<R: ServiceRole> Peer<R>
pub async fn send_notification( &self, notification: R::Not, ) -> Result<(), ServiceError>
pub async fn send_request( &self, request: R::Req, ) -> Result<R::PeerResp, ServiceError>
pub async fn send_cancellable_request( &self, request: R::Req, options: PeerRequestOptions, ) -> Result<RequestHandle<R>, ServiceError>
pub async fn send_request_with_option( &self, request: R::Req, options: PeerRequestOptions, ) -> Result<RequestHandle<R>, ServiceError>
pub fn peer_info(&self) -> Option<&R::PeerInfo>
pub fn set_peer_info(&self, info: R::PeerInfo)
pub fn is_transport_closed(&self) -> bool
Trait Implementations§
Source§impl<R: ServiceRole> Debug for Peer<R>
impl<R: ServiceRole> Debug for Peer<R>
Source§impl<C> FromContextPart<C> for Peer<RoleServer>where
C: AsRequestContext,
Available on crate feature server only.
impl<C> FromContextPart<C> for Peer<RoleServer>where
C: AsRequestContext,
server only.