pub struct McpClient { /* private fields */ }Expand description
Main MCP client implementation
Implementations§
Source§impl McpClient
impl McpClient
Sourcepub fn builder() -> McpClientBuilder
pub fn builder() -> McpClientBuilder
Create a new client builder (primary constructor)
Sourcepub fn new(name: String, version: String) -> Self
pub fn new(name: String, version: String) -> Self
Create a new MCP client with name and version
Sourcepub fn with_client_info(info: ClientInfo) -> Self
pub fn with_client_info(info: ClientInfo) -> Self
Create a new MCP client with a specific ClientInfo
Sourcepub fn tools(&self) -> ToolsBuilder<'_>
pub fn tools(&self) -> ToolsBuilder<'_>
Access tools with fluent interface
Sourcepub fn resources(&self) -> ResourcesBuilder<'_>
pub fn resources(&self) -> ResourcesBuilder<'_>
Access resources with fluent interface
Sourcepub fn prompts(&self) -> PromptsBuilder<'_>
pub fn prompts(&self) -> PromptsBuilder<'_>
Access prompts with fluent interface
Sourcepub 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
pub async fn call_tool_simple( &self, name: &str, arguments: Value, ) -> McpResult<CallToolResult>
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
Sourcepub fn with_config(name: String, version: String, config: ClientConfig) -> Self
pub fn with_config(name: String, version: String, config: ClientConfig) -> Self
Create a new MCP client with custom configuration
Sourcepub fn set_capabilities(&mut self, capabilities: ClientCapabilities)
pub fn set_capabilities(&mut self, capabilities: ClientCapabilities)
Set client capabilities
Sourcepub fn enable_tasks_extension(&mut self)
pub fn enable_tasks_extension(&mut self)
Declare support for the official MCP Tasks extension.
Sourcepub fn set_request_handler<H>(&mut self, handler: H)where
H: ClientRequestHandler + 'static,
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);Sourcepub async fn handle_server_request(
&self,
request: JsonRpcRequest,
) -> McpResult<JsonRpcResponse>
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
Sourcepub fn info(&self) -> &ClientInfo
pub fn info(&self) -> &ClientInfo
Get client information
Sourcepub fn capabilities(&self) -> &ClientCapabilities
pub fn capabilities(&self) -> &ClientCapabilities
Get client capabilities
Sourcepub fn config(&self) -> &ClientConfig
pub fn config(&self) -> &ClientConfig
Get client configuration
Sourcepub fn set_protocol_mode(&mut self, mode: ProtocolMode)
pub fn set_protocol_mode(&mut self, mode: ProtocolMode)
Set the protocol selection policy before connecting.
Sourcepub async fn negotiated_protocol(&self) -> Option<NegotiatedProtocol>
pub async fn negotiated_protocol(&self) -> Option<NegotiatedProtocol>
Return the protocol selected for the active connection.
Sourcepub async fn server_capabilities(&self) -> Option<ServerCapabilities>
pub async fn server_capabilities(&self) -> Option<ServerCapabilities>
Get server capabilities (if connected)
Sourcepub async fn server_info(&self) -> Option<ServerInfo>
pub async fn server_info(&self) -> Option<ServerInfo>
Get server information (if connected)
Sourcepub async fn is_connected(&self) -> bool
pub async fn is_connected(&self) -> bool
Check if the client is connected
Sourcepub async fn connect<T>(&mut self, transport: T) -> McpResult<ConnectResult>where
T: Transport + 'static,
pub async fn connect<T>(&mut self, transport: T) -> McpResult<ConnectResult>where
T: Transport + 'static,
Connect to an MCP server using the provided transport
Sourcepub async fn disconnect(&self) -> McpResult<()>
pub async fn disconnect(&self) -> McpResult<()>
Disconnect from the server
Sourcepub async fn connect_with_stdio(
&mut self,
command: &str,
args: Vec<&str>,
) -> McpResult<ConnectResult>
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:
- Creates a STDIO transport
- Connects to the server
- 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(())
}Sourcepub async fn connect_with_http(
&mut self,
server_url: &str,
sse_url: Option<&str>,
) -> McpResult<ConnectResult>
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:
- Creates an HTTP transport to the specified URL
- Connects to the server
- 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(())
}Sourcepub async fn connect_with_stdio_simple(
&mut self,
command: &str,
) -> McpResult<ConnectResult>
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(())
}Sourcepub async fn connect_with_websocket(
&mut self,
server_url: &str,
) -> McpResult<ConnectResult>
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:
- Creates a WebSocket transport to the specified URL
- Connects to the server
- 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(())
}Sourcepub async fn run_with_stdio<F, Fut>(
&mut self,
command: &str,
args: Vec<&str>,
session_handler: F,
) -> McpResult<()>
pub async fn run_with_stdio<F, Fut>( &mut self, command: &str, args: Vec<&str>, session_handler: F, ) -> McpResult<()>
Connect to an MCP server and run interactive session over STDIO (convenience method)
This is a convenience method that:
- Creates a STDIO transport
- Connects to the server
- Runs an interactive session until Ctrl+C
- 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
}Sourcepub async fn connect_with_chunked_encoding(
&mut self,
server_url: &str,
config: StreamingConfig,
) -> McpResult<ConnectResult>
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:
- Creates a streaming HTTP transport with smart content analysis
- Connects to the server
- 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(())
}Sourcepub async fn connect_with_chunked_encoding_default(
&mut self,
server_url: &str,
) -> McpResult<ConnectResult>
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(())
}Sourcepub async fn connect_with_chunked_encoding_memory_improved(
&mut self,
server_url: &str,
) -> McpResult<ConnectResult>
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(())
}Sourcepub async fn connect_with_chunked_encoding_performance_improved(
&mut self,
server_url: &str,
) -> McpResult<ConnectResult>
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(())
}Sourcepub async fn connect_with_recommended_transport(
&mut self,
use_case: TransportUseCase,
server_url: &str,
) -> McpResult<ConnectResult>
pub async fn connect_with_recommended_transport( &mut self, use_case: TransportUseCase, server_url: &str, ) -> McpResult<ConnectResult>
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 caseserver_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(())
}Sourcepub fn get_transport_recommendation(
&self,
use_case: TransportUseCase,
) -> &'static str
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);Sourcepub fn get_transport_comparison(&self) -> Vec<TransportInfo>
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);
}Sourcepub async fn list_tools(
&self,
cursor: Option<String>,
) -> McpResult<ListToolsResult>
pub async fn list_tools( &self, cursor: Option<String>, ) -> McpResult<ListToolsResult>
List available tools from the server
Sourcepub async fn call_tool(
&self,
name: String,
arguments: Option<HashMap<String, Value>>,
) -> McpResult<CallToolResult>
pub async fn call_tool( &self, name: String, arguments: Option<HashMap<String, Value>>, ) -> McpResult<CallToolResult>
Call a tool on the server
Sourcepub async fn list_resources(
&self,
cursor: Option<String>,
) -> McpResult<ListResourcesResult>
pub async fn list_resources( &self, cursor: Option<String>, ) -> McpResult<ListResourcesResult>
List available resources from the server
Sourcepub async fn read_resource(&self, uri: String) -> McpResult<ReadResourceResult>
pub async fn read_resource(&self, uri: String) -> McpResult<ReadResourceResult>
Read a resource from the server
Sourcepub async fn subscribe_resource(
&self,
uri: String,
) -> McpResult<SubscribeResourceResult>
pub async fn subscribe_resource( &self, uri: String, ) -> McpResult<SubscribeResourceResult>
Subscribe to resource updates
Sourcepub async fn unsubscribe_resource(
&self,
uri: String,
) -> McpResult<UnsubscribeResourceResult>
pub async fn unsubscribe_resource( &self, uri: String, ) -> McpResult<UnsubscribeResourceResult>
Unsubscribe from resource updates
Sourcepub async fn list_resource_templates(
&self,
cursor: Option<String>,
) -> McpResult<ListResourceTemplatesResult>
pub async fn list_resource_templates( &self, cursor: Option<String>, ) -> McpResult<ListResourceTemplatesResult>
List resource templates from the server (New in 2025-11-25)
Sourcepub async fn complete_argument(
&self,
reference: CompletionReference,
argument: CompletionArgument,
) -> McpResult<CompleteResult>
pub async fn complete_argument( &self, reference: CompletionReference, argument: CompletionArgument, ) -> McpResult<CompleteResult>
Request completion suggestions for an argument
Sourcepub async fn complete_prompt_argument(
&self,
prompt_name: &str,
argument_name: &str,
current_value: &str,
) -> McpResult<Vec<String>>
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
Sourcepub async fn complete_resource_uri(
&self,
uri_template: &str,
argument_name: &str,
current_value: &str,
) -> McpResult<Vec<String>>
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
Sourcepub async fn complete_tool_argument(
&self,
tool_name: &str,
argument_name: &str,
current_value: &str,
) -> McpResult<Vec<String>>
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
Sourcepub async fn list_prompts(
&self,
cursor: Option<String>,
) -> McpResult<ListPromptsResult>
pub async fn list_prompts( &self, cursor: Option<String>, ) -> McpResult<ListPromptsResult>
List available prompts from the server
Sourcepub async fn get_prompt(
&self,
name: String,
arguments: Option<HashMap<String, String>>,
) -> McpResult<GetPromptResult>
pub async fn get_prompt( &self, name: String, arguments: Option<HashMap<String, String>>, ) -> McpResult<GetPromptResult>
Get a prompt from the server
Sourcepub async fn create_message(
&self,
params: CreateMessageParams,
) -> McpResult<CreateMessageResult>
pub async fn create_message( &self, params: CreateMessageParams, ) -> McpResult<CreateMessageResult>
Create a message using server-side sampling
Sourcepub async fn ping(&self) -> McpResult<PingResult>
pub async fn ping(&self) -> McpResult<PingResult>
Send a ping to the server
Sourcepub async fn set_logging_level(
&self,
level: LoggingLevel,
) -> McpResult<SetLoggingLevelResult>
pub async fn set_logging_level( &self, level: LoggingLevel, ) -> McpResult<SetLoggingLevelResult>
Set the logging level on the server
Sourcepub async fn get_task(&self, task_id: impl Into<String>) -> McpResult<Task>
pub async fn get_task(&self, task_id: impl Into<String>) -> McpResult<Task>
Retrieve the current state of a durable task.
Sourcepub async fn update_task(
&self,
task_id: impl Into<String>,
input_responses: HashMap<String, Value>,
) -> McpResult<()>
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.
Sourcepub async fn cancel_task(&self, task_id: impl Into<String>) -> McpResult<()>
pub async fn cancel_task(&self, task_id: impl Into<String>) -> McpResult<()>
Signal cooperative cancellation of a task.
Sourcepub async fn receive_notification(
&self,
) -> McpResult<Option<JsonRpcNotification>>
pub async fn receive_notification( &self, ) -> McpResult<Option<JsonRpcNotification>>
Receive notifications from the server
Sourcepub async fn listen(
&self,
notifications: SubscriptionFilter,
) -> McpResult<ClientSubscription>
pub async fn listen( &self, notifications: SubscriptionFilter, ) -> McpResult<ClientSubscription>
Open a standards-track MCP 2026 notification stream.
Sourcepub async fn cancel_subscription(
&self,
subscription: &ClientSubscription,
) -> McpResult<()>
pub async fn cancel_subscription( &self, subscription: &ClientSubscription, ) -> McpResult<()>
Close an open subscription using transport-appropriate semantics.
Auto Trait Implementations§
impl !RefUnwindSafe for McpClient
impl !UnwindSafe for McpClient
impl Freeze for McpClient
impl Send for McpClient
impl Sync for McpClient
impl Unpin for McpClient
impl UnsafeUnpin for McpClient
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self>
fn with_context(self, otel_cx: Context) -> WithContext<Self>
§fn with_current_context(self) -> WithContext<Self>
fn with_current_context(self) -> WithContext<Self>
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].