Skip to main content

Peer

Struct Peer 

Source
pub struct Peer<R: ServiceRole> { /* private fields */ }
Available on crate features 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>

Source

pub async fn complete( &self, params: CompleteRequestParams, ) -> Result<CompleteResult, ServiceError>

Available on crate feature client only.
Source

pub async fn set_level( &self, params: SetLevelRequestParams, ) -> Result<(), ServiceError>

Available on crate feature client only.
Source

pub async fn get_prompt( &self, params: GetPromptRequestParams, ) -> Result<GetPromptResult, ServiceError>

Available on crate feature client only.
Source

pub async fn list_prompts( &self, params: Option<PaginatedRequestParams>, ) -> Result<ListPromptsResult, ServiceError>

Available on crate feature client only.
Source

pub async fn list_resources( &self, params: Option<PaginatedRequestParams>, ) -> Result<ListResourcesResult, ServiceError>

Available on crate feature client only.
Source

pub async fn list_resource_templates( &self, params: Option<PaginatedRequestParams>, ) -> Result<ListResourceTemplatesResult, ServiceError>

Available on crate feature client only.
Source

pub async fn read_resource( &self, params: ReadResourceRequestParams, ) -> Result<ReadResourceResult, ServiceError>

Available on crate feature client only.
Source

pub async fn subscribe( &self, params: SubscribeRequestParams, ) -> Result<(), ServiceError>

Available on crate feature client only.
Source

pub async fn unsubscribe( &self, params: UnsubscribeRequestParams, ) -> Result<(), ServiceError>

Available on crate feature client only.
Source

pub async fn call_tool( &self, params: CallToolRequestParams, ) -> Result<CallToolResult, ServiceError>

Available on crate feature client only.
Source

pub async fn list_tools( &self, params: Option<PaginatedRequestParams>, ) -> Result<ListToolsResult, ServiceError>

Available on crate feature client only.
Source

pub async fn notify_cancelled( &self, params: CancelledNotificationParam, ) -> Result<(), ServiceError>

Available on crate feature client only.
Source

pub async fn notify_progress( &self, params: ProgressNotificationParam, ) -> Result<(), ServiceError>

Available on crate feature client only.
Source

pub async fn notify_initialized(&self) -> Result<(), ServiceError>

Available on crate feature client only.
Source

pub async fn notify_roots_list_changed(&self) -> Result<(), ServiceError>

Available on crate feature client only.
Source§

impl Peer<RoleClient>

Source

pub async fn list_all_tools(&self) -> Result<Vec<Tool>, ServiceError>

Available on crate feature 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.

Source

pub async fn list_all_prompts(&self) -> Result<Vec<Prompt>, ServiceError>

Available on crate feature 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.

Source

pub async fn list_all_resources(&self) -> Result<Vec<Resource>, ServiceError>

Available on crate feature 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.

Source

pub async fn list_all_resource_templates( &self, ) -> Result<Vec<ResourceTemplate>, ServiceError>

Available on crate feature 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.

Source

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>

Available on crate feature client only.

Convenient method to get completion suggestions for a prompt argument

§Arguments
  • prompt_name - Name of the prompt being completed
  • argument_name - Name of the argument being completed
  • current_value - Current partial value of the argument
  • context - Optional context with previously resolved arguments
§Returns

CompletionInfo with suggestions for the specified prompt argument

Source

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>

Available on crate feature client only.

Convenient method to get completion suggestions for a resource URI argument

§Arguments
  • uri_template - URI template pattern being completed
  • argument_name - Name of the URI parameter being completed
  • current_value - Current partial value of the parameter
  • context - Optional context with previously resolved arguments
§Returns

CompletionInfo with suggestions for the specified resource URI argument

Source

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>

Available on crate feature 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.

Source

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>

Available on crate feature 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>

Source

pub fn supports_sampling_tools(&self) -> bool

Available on crate feature server only.

Check if the client supports sampling tools capability.

Source

pub async fn create_message( &self, params: CreateMessageRequestParams, ) -> Result<CreateMessageResult, ServiceError>

Available on crate feature server only.
Source

pub async fn list_roots(&self) -> Result<ListRootsResult, ServiceError>

Available on crate feature server only.
Source

pub async fn create_elicitation( &self, params: CreateElicitationRequestParams, ) -> Result<CreateElicitationResult, ServiceError>

Available on crate feature server only.
Source

pub async fn create_elicitation_with_timeout( &self, params: CreateElicitationRequestParams, timeout: Option<Duration>, ) -> Result<CreateElicitationResult, ServiceError>

Available on crate feature server only.
Source

pub async fn notify_url_elicitation_completed( &self, params: ElicitationResponseNotificationParam, ) -> Result<(), ServiceError>

Available on crate feature server only.
Source

pub async fn notify_cancelled( &self, params: CancelledNotificationParam, ) -> Result<(), ServiceError>

Available on crate feature server only.
Source

pub async fn notify_progress( &self, params: ProgressNotificationParam, ) -> Result<(), ServiceError>

Available on crate feature server only.
Source

pub async fn notify_logging_message( &self, params: LoggingMessageNotificationParam, ) -> Result<(), ServiceError>

Available on crate feature server only.
Source

pub async fn notify_resource_updated( &self, params: ResourceUpdatedNotificationParam, ) -> Result<(), ServiceError>

Available on crate feature server only.
Source

pub async fn notify_resource_list_changed(&self) -> Result<(), ServiceError>

Available on crate feature server only.
Source

pub async fn notify_tool_list_changed(&self) -> Result<(), ServiceError>

Available on crate feature server only.
Source

pub async fn notify_prompt_list_changed(&self) -> Result<(), ServiceError>

Available on crate feature server only.
Source§

impl Peer<RoleServer>

Source

pub fn supported_elicitation_modes(&self) -> HashSet<ElicitationMode>

Available on crate features 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.

Source

pub 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.

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 generation
  • serde::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 T
  • Err(ElicitationError::UserDeclined) if user explicitly declined the request
  • Err(ElicitationError::UserCancelled) if user cancelled/dismissed the request
  • Err(ElicitationError::ParseError { .. }) if response data couldn’t be parsed into type T
  • Err(ElicitationError::NoContent) if no response content was provided
  • Err(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()),
}
Source

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>,

Available on crate features 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 user
  • timeout - 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()),
}
Source

pub 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.

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 user
  • url - The URL the user is requested to visit
  • elicitation_id - A unique identifier for this elicitation request
§Returns
  • Ok(action) indicating the user’s response action
  • Err(ElicitationError::CapabilityNotSupported) if client does not support elicitation via URL
  • Err(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(())
}
Source

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>

Available on crate features 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 user
  • url - The URL the user is requested to visit
  • elicitation_id - A unique identifier for this elicitation request
  • timeout - Optional timeout duration. If None, uses default timeout behavior
§Returns
  • Ok(action) indicating the user’s response action
  • Err(ElicitationError::CapabilityNotSupported) if client does not support elicitation via URL
  • Err(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>

Source

pub async fn send_notification( &self, notification: R::Not, ) -> Result<(), ServiceError>

Source

pub async fn send_request( &self, request: R::Req, ) -> Result<R::PeerResp, ServiceError>

Source

pub async fn send_cancellable_request( &self, request: R::Req, options: PeerRequestOptions, ) -> Result<RequestHandle<R>, ServiceError>

Source

pub async fn send_request_with_option( &self, request: R::Req, options: PeerRequestOptions, ) -> Result<RequestHandle<R>, ServiceError>

Source

pub fn peer_info(&self) -> Option<&R::PeerInfo>

Source

pub fn set_peer_info(&self, info: R::PeerInfo)

Source

pub fn is_transport_closed(&self) -> bool

Trait Implementations§

Source§

impl<R: Clone + ServiceRole> Clone for Peer<R>
where R::PeerInfo: Clone,

Source§

fn clone(&self) -> Peer<R>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<R: ServiceRole> Debug for Peer<R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<C> FromContextPart<C> for Peer<RoleServer>

Available on crate feature server only.

Auto Trait Implementations§

§

impl<R> Freeze for Peer<R>

§

impl<R> !RefUnwindSafe for Peer<R>

§

impl<R> Send for Peer<R>

§

impl<R> Sync for Peer<R>

§

impl<R> Unpin for Peer<R>

§

impl<R> UnsafeUnpin for Peer<R>

§

impl<R> !UnwindSafe for Peer<R>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more