Skip to main content

McpClient

Struct McpClient 

Source
pub struct McpClient { /* private fields */ }
Expand description

Main MCP client implementation

Implementations§

Source§

impl McpClient

Source

pub fn builder() -> McpClientBuilder

Create a new client builder (primary constructor)

Source

pub fn new(name: String, version: String) -> Self

Create a new MCP client with name and version

Source

pub fn with_client_info(info: ClientInfo) -> Self

Create a new MCP client with a specific ClientInfo

Source

pub fn tools(&self) -> ToolsBuilder<'_>

Access tools with fluent interface

Source

pub fn resources(&self) -> ResourcesBuilder<'_>

Access resources with fluent interface

Source

pub fn prompts(&self) -> PromptsBuilder<'_>

Access prompts with fluent interface

Source

pub async fn call_tool_simple( &self, name: &str, arguments: Value, ) -> McpResult<CallToolResult>

👎Deprecated since 0.2.0:

Use fluent interface: client.tools().call(name).args(args).execute().await

Convenience method: call_tool with &str name and serde_json::Value arguments

§Deprecated

Use client.tools().call(name).args(arguments).execute().await instead

Source

pub fn with_config(name: String, version: String, config: ClientConfig) -> Self

Create a new MCP client with custom configuration

Source

pub fn set_capabilities(&mut self, capabilities: ClientCapabilities)

Set client capabilities

Source

pub fn enable_tasks_extension(&mut self)

Declare support for the official MCP Tasks extension.

Source

pub fn set_request_handler<H>(&mut self, handler: H)
where H: ClientRequestHandler + 'static,

Set custom request handler for server-initiated requests

This enables bidirectional MCP communication by allowing the server to initiate requests to the client for sampling, elicitation, etc.

§Arguments
  • handler - Custom implementation of ClientRequestHandler
§Example
use prism_mcp_rs::client::{McpClient, InteractiveClientRequestHandler};

let mut client = McpClient::new("my-app".to_string(), "1.0.0".to_string());
let handler = InteractiveClientRequestHandler::new("my-app")
.add_root("file:///home/user", Some("Home"))
.auto_accept_elicitation(true);
client.set_request_handler(handler);
Source

pub async fn handle_server_request( &self, request: JsonRpcRequest, ) -> McpResult<JsonRpcResponse>

Handle incoming server request

Method processes server-initiated requests and returns appropriate responses. It’s called automatically by the transport layer when the server sends a request to the client.

§Arguments
  • request - The JSON-RPC request from the server
§Returns

JSON-RPC response to send back to the server

Source

pub fn info(&self) -> &ClientInfo

Get client information

Source

pub fn capabilities(&self) -> &ClientCapabilities

Get client capabilities

Source

pub fn config(&self) -> &ClientConfig

Get client configuration

Source

pub fn set_protocol_mode(&mut self, mode: ProtocolMode)

Set the protocol selection policy before connecting.

Source

pub async fn negotiated_protocol(&self) -> Option<NegotiatedProtocol>

Return the protocol selected for the active connection.

Source

pub async fn server_capabilities(&self) -> Option<ServerCapabilities>

Get server capabilities (if connected)

Source

pub async fn server_info(&self) -> Option<ServerInfo>

Get server information (if connected)

Source

pub async fn is_connected(&self) -> bool

Check if the client is connected

Source

pub async fn connect<T>(&mut self, transport: T) -> McpResult<ConnectResult>
where T: Transport + 'static,

Connect to an MCP server using the provided transport

Source

pub async fn disconnect(&self) -> McpResult<()>

Disconnect from the server

Source

pub async fn connect_with_stdio( &mut self, command: &str, args: Vec<&str>, ) -> McpResult<ConnectResult>

Connect to an MCP server over STDIO (convenience method)

This is a convenience method that:

  1. Creates a STDIO transport
  2. Connects to the server
  3. Returns the initialization result
§Example
use prism_mcp_rs::prelude::*;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("my-client".to_string(), "1.0.0".to_string());
let init_result = client.connect_with_stdio("my-mcp-server", vec!["--verbose"]).await?;
println!("Protocol: {}", init_result.protocol.version);
Ok(())
}
Source

pub async fn connect_with_http( &mut self, server_url: &str, sse_url: Option<&str>, ) -> McpResult<ConnectResult>

Connect to an MCP server over HTTP (convenience method)

This is a convenience method that:

  1. Creates an HTTP transport to the specified URL
  2. Connects to the server
  3. Returns the initialization result
§Arguments
  • server_url - The HTTP URL of the MCP server (e.g., “http://localhost:3000”)
  • sse_url - Optional Server-Sent Events URL for notifications
§Example
use prism_mcp_rs::prelude::*;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("my-client".to_string(), "1.0.0".to_string());
let init_result = client.connect_with_http("http://localhost:3000", None).await?;
println!("Protocol: {}", init_result.protocol.version);
Ok(())
}
Source

pub async fn connect_with_stdio_simple( &mut self, command: &str, ) -> McpResult<ConnectResult>

Connect to an MCP server over STDIO with simple command (convenience method)

This is a convenience method for the most common STDIO use case: connecting to a server with just a command and no arguments.

§Arguments
  • command - Command to execute for the MCP server
§Example
use prism_mcp_rs::prelude::*;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("my-client".to_string(), "1.0.0".to_string());
let init_result = client.connect_with_stdio_simple("my-mcp-server").await?;
println!("Protocol: {}", init_result.protocol.version);
Ok(())
}
Source

pub async fn connect_with_websocket( &mut self, server_url: &str, ) -> McpResult<ConnectResult>

Connect to an MCP server over WebSocket (convenience method)

This is a convenience method that:

  1. Creates a WebSocket transport to the specified URL
  2. Connects to the server
  3. Returns the initialization result
§Arguments
  • server_url - The WebSocket URL of the MCP server (e.g., “ws://localhost:8080”)
§Example
use prism_mcp_rs::prelude::*;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("my-client".to_string(), "1.0.0".to_string());
let init_result = client.connect_with_websocket("ws://localhost:8080").await?;
println!("Protocol: {}", init_result.protocol.version);
Ok(())
}
Source

pub async fn run_with_stdio<F, Fut>( &mut self, command: &str, args: Vec<&str>, session_handler: F, ) -> McpResult<()>
where F: FnOnce(&Self) -> Fut, Fut: Future<Output = McpResult<()>>,

Connect to an MCP server and run interactive session over STDIO (convenience method)

This is a convenience method that:

  1. Creates a STDIO transport
  2. Connects to the server
  3. Runs an interactive session until Ctrl+C
  4. smoothly disconnects
§Arguments
  • session_handler - A closure that receives the connected client for operations
§Example
use prism_mcp_rs::prelude::*;

#[tokio::main]
async fn main() -> McpResult<()> {
    let mut client = McpClient::new("my-client".to_string(), "1.0.0".to_string());

    client.run_with_stdio("my-mcp-server", vec!["--verbose"], |_client| async move {
        // Your client operations here
        // Note: client operations would typically use _client parameter
        println!("Client connected successfully");
        Ok(())
    }).await
}
Source

pub async fn connect_with_chunked_encoding( &mut self, server_url: &str, config: StreamingConfig, ) -> McpResult<ConnectResult>

Connect to an MCP server with streaming HTTP transport for optimal efficiency

This is a convenience method that:

  1. Creates a streaming HTTP transport with smart content analysis
  2. Connects to the server
  3. Returns the initialization result

Optimized for:

  • Large payload applications (>100KB)
  • Memory-constrained environments
  • High-performance requirements
  • Applications with mixed payload sizes

Features:

  • Chunked transfer encoding for large payloads
  • Multiple compression algorithms (Gzip, Brotli, Zstd)
  • HTTP/2 Server Push support
  • smart content analysis
  • Automatic fallback to traditional HTTP
§Arguments
  • server_url - The HTTP URL of the MCP server (e.g., “http://localhost:3000”)
  • config - Streaming configuration options
§Example
use prism_mcp_rs::prelude::*;
use prism_mcp_rs::transport::StreamingConfig;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("data-processor".to_string(), "1.0.0".to_string());
let config = StreamingConfig::performance_improved();
let init = client.connect_with_chunked_encoding("http://localhost:3000", config).await?;
println!("Connected with {}", init.protocol.version);
Ok(())
}
Source

pub async fn connect_with_chunked_encoding_default( &mut self, server_url: &str, ) -> McpResult<ConnectResult>

Connect with streaming HTTP using default configuration

This is a convenience method that uses default streaming HTTP configuration improved for general use cases.

§Arguments
  • server_url - The HTTP URL of the MCP server
§Example
use prism_mcp_rs::prelude::*;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("my-app".to_string(), "1.0.0".to_string());
let init = client.connect_with_chunked_encoding_default("http://localhost:3000").await?;
Ok(())
}
Source

pub async fn connect_with_chunked_encoding_memory_improved( &mut self, server_url: &str, ) -> McpResult<ConnectResult>

Connect with memory-improved streaming HTTP configuration

This configuration is improved for memory-constrained environments with smaller chunk sizes and conservative buffering.

§Arguments
  • server_url - The HTTP URL of the MCP server
§Example
use prism_mcp_rs::prelude::*;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("embedded-app".to_string(), "1.0.0".to_string());
let init = client.connect_with_chunked_encoding_memory_improved("http://localhost:3000").await?;
Ok(())
}
Source

pub async fn connect_with_chunked_encoding_performance_improved( &mut self, server_url: &str, ) -> McpResult<ConnectResult>

Connect with performance-improved streaming HTTP configuration

This configuration is improved for high-performance scenarios with larger chunk sizes, multi-algorithm compression, and HTTP/2 features.

§Arguments
  • server_url - The HTTP URL of the MCP server
§Example
use prism_mcp_rs::prelude::*;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("high-perf-app".to_string(), "1.0.0".to_string());
let init = client.connect_with_chunked_encoding_performance_improved("http://localhost:3000").await?;
Ok(())
}

Choose the right transport automatically based on your use case

This is a convenience method that selects the optimal transport based on your application characteristics. Use this if you want automatic selection.

§Arguments
  • use_case - Your primary use case
  • server_url - Server URL (protocol will be adjusted automatically)
§Example
use prism_mcp_rs::prelude::*;
use prism_mcp_rs::client::TransportUseCase;

#[tokio::main]
async fn main() -> McpResult<()> {
let mut client = McpClient::new("my-app".to_string(), "1.0.0".to_string());
let init = client.connect_with_recommended_transport(
TransportUseCase::LargeDataProcessing,
"http://localhost:3000"
).await?;
Ok(())
}
Source

pub fn get_transport_recommendation( &self, use_case: TransportUseCase, ) -> &'static str

Get transport recommendation for a use case (informational)

Returns a human-readable recommendation for the best transport to use for a given use case.

§Example
use prism_mcp_rs::client::{McpClient, TransportUseCase};

let client = McpClient::new("app".to_string(), "1.0.0".to_string());
let recommendation = client.get_transport_recommendation(TransportUseCase::RealTime);
println!("Recommendation: {}", recommendation);
Source

pub fn get_transport_comparison(&self) -> Vec<TransportInfo>

Get detailed transport comparison for decision making

Returns detailed information about all available transports to help with transport selection decisions.

§Example
use prism_mcp_rs::client::McpClient;

let client = McpClient::new("app".to_string(), "1.0.0".to_string());
let comparison = client.get_transport_comparison();
for transport in comparison {
println!("{}: {}", transport.name, transport.description);
}
Source

pub async fn list_tools( &self, cursor: Option<String>, ) -> McpResult<ListToolsResult>

List available tools from the server

Source

pub async fn call_tool( &self, name: String, arguments: Option<HashMap<String, Value>>, ) -> McpResult<CallToolResult>

Call a tool on the server

Source

pub async fn list_resources( &self, cursor: Option<String>, ) -> McpResult<ListResourcesResult>

List available resources from the server

Source

pub async fn read_resource(&self, uri: String) -> McpResult<ReadResourceResult>

Read a resource from the server

Source

pub async fn subscribe_resource( &self, uri: String, ) -> McpResult<SubscribeResourceResult>

Subscribe to resource updates

Source

pub async fn unsubscribe_resource( &self, uri: String, ) -> McpResult<UnsubscribeResourceResult>

Unsubscribe from resource updates

Source

pub async fn list_resource_templates( &self, cursor: Option<String>, ) -> McpResult<ListResourceTemplatesResult>

List resource templates from the server (New in 2025-11-25)

Source

pub async fn complete_argument( &self, reference: CompletionReference, argument: CompletionArgument, ) -> McpResult<CompleteResult>

Request completion suggestions for an argument

Source

pub async fn complete_prompt_argument( &self, prompt_name: &str, argument_name: &str, current_value: &str, ) -> McpResult<Vec<String>>

Convenience method for prompt argument completion

Source

pub async fn complete_resource_uri( &self, uri_template: &str, argument_name: &str, current_value: &str, ) -> McpResult<Vec<String>>

Convenience method for resource URI completion

Source

pub async fn complete_tool_argument( &self, tool_name: &str, argument_name: &str, current_value: &str, ) -> McpResult<Vec<String>>

Convenience method for tool argument completion

Source

pub async fn list_prompts( &self, cursor: Option<String>, ) -> McpResult<ListPromptsResult>

List available prompts from the server

Source

pub async fn get_prompt( &self, name: String, arguments: Option<HashMap<String, String>>, ) -> McpResult<GetPromptResult>

Get a prompt from the server

Source

pub async fn create_message( &self, params: CreateMessageParams, ) -> McpResult<CreateMessageResult>

Create a message using server-side sampling

Source

pub async fn ping(&self) -> McpResult<PingResult>

Send a ping to the server

Source

pub async fn set_logging_level( &self, level: LoggingLevel, ) -> McpResult<SetLoggingLevelResult>

Set the logging level on the server

Source

pub async fn get_task(&self, task_id: impl Into<String>) -> McpResult<Task>

Retrieve the current state of a durable task.

Source

pub async fn update_task( &self, task_id: impl Into<String>, input_responses: HashMap<String, Value>, ) -> McpResult<()>

Submit responses for currently outstanding task input requests.

Source

pub async fn cancel_task(&self, task_id: impl Into<String>) -> McpResult<()>

Signal cooperative cancellation of a task.

Source

pub async fn receive_notification( &self, ) -> McpResult<Option<JsonRpcNotification>>

Receive notifications from the server

Source

pub async fn listen( &self, notifications: SubscriptionFilter, ) -> McpResult<ClientSubscription>

Open a standards-track MCP 2026 notification stream.

Source

pub async fn cancel_subscription( &self, subscription: &ClientSubscription, ) -> McpResult<()>

Close an open subscription using transport-appropriate semantics.

Auto Trait Implementations§

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

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

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

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.

§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + 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
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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