pub struct McpClient { /* private fields */ }Expand description
MCP client that manages connections to multiple MCP servers
The main interface for interacting with Model Context Protocol servers. Handles connection lifecycle, tool discovery, and provides integration with tool calling systems.
§Features
- Multi-server Management: Connects to and manages multiple MCP servers simultaneously
- Automatic Tool Discovery: Discovers available tools from connected servers
- Tool Registration: Converts MCP tools to internal Tool format for seamless integration
- Connection Pooling: Maintains persistent connections for efficient tool execution
- Error Handling: Robust error handling with proper cleanup and reconnection logic
§Example
use mistralrs_mcp::{McpClient, McpClientConfig};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
// Initialize all configured server connections
client.initialize().await?;
// Get tool callbacks for model integration
let callbacks = client.get_tool_callbacks_with_tools();
Ok(())
}Implementations§
Source§impl McpClient
impl McpClient
Sourcepub fn new(config: McpClientConfig) -> McpClient
pub fn new(config: McpClientConfig) -> McpClient
Create a new MCP client with the given configuration
Sourcepub async fn initialize(&mut self) -> Result<(), Error>
pub async fn initialize(&mut self) -> Result<(), Error>
Initialize connections to all configured servers
Sourcepub fn get_tool_callbacks(
&self,
) -> &HashMap<String, Arc<dyn Fn(&CalledFunction) -> Result<String, Error> + Send + Sync>>
pub fn get_tool_callbacks( &self, ) -> &HashMap<String, Arc<dyn Fn(&CalledFunction) -> Result<String, Error> + Send + Sync>>
Get tool callbacks for use with legacy tool calling systems.
Returns a map of tool names to their callback functions. These callbacks handle argument parsing, concurrency control, and timeout enforcement automatically.
For new integrations, prefer Self::get_tool_callbacks_with_tools which
includes tool definitions alongside callbacks.
Sourcepub fn get_tool_callbacks_with_tools(
&self,
) -> &HashMap<String, ToolCallbackWithTool>
pub fn get_tool_callbacks_with_tools( &self, ) -> &HashMap<String, ToolCallbackWithTool>
Get tool callbacks paired with their tool definitions.
This is the primary method for integrating MCP tools with the model’s automatic tool calling system. Each entry contains:
- A callback function that executes the tool with timeout and concurrency controls
- A
Tooldefinition with name, description, and parameter schema
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
let tools = client.get_tool_callbacks_with_tools();
for (name, tool_with_callback) in tools {
println!("Tool: {} - {:?}", name, tool_with_callback.tool.function.description);
}Sourcepub fn get_tools(&self) -> &HashMap<String, McpToolInfo>
pub fn get_tools(&self) -> &HashMap<String, McpToolInfo>
Get information about all discovered tools.
Returns metadata about tools discovered from connected MCP servers, including their names, descriptions, input schemas, and which server they came from.
Sourcepub fn servers(&self) -> &HashMap<String, Arc<dyn McpServerConnection>>
pub fn servers(&self) -> &HashMap<String, Arc<dyn McpServerConnection>>
Get a reference to all connected MCP server connections.
This provides direct access to server connections, allowing you to:
- List available resources with
McpServerConnection::list_resources - Read resources with
McpServerConnection::read_resource - Check server health with
McpServerConnection::ping - Call tools directly with
McpServerConnection::call_tool
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
for (server_id, connection) in client.servers() {
println!("Server: {} ({})", connection.server_name(), server_id);
let resources = connection.list_resources().await?;
println!(" Resources: {:?}", resources);
}Sourcepub fn server(&self, id: &str) -> Option<&Arc<dyn McpServerConnection>>
pub fn server(&self, id: &str) -> Option<&Arc<dyn McpServerConnection>>
Get a specific server connection by its ID.
Returns None if no server with the given ID is connected.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
if let Some(server) = client.server("my_server_id") {
server.ping().await?;
let resources = server.list_resources().await?;
}Sourcepub fn config(&self) -> &McpClientConfig
pub fn config(&self) -> &McpClientConfig
Get the client configuration.
Sourcepub async fn shutdown(&mut self) -> Result<(), Error>
pub async fn shutdown(&mut self) -> Result<(), Error>
Gracefully shutdown all server connections.
Closes all active connections and clears the tools and callbacks. The client cannot be used after calling this method without re-initializing.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
// ... use the client ...
// Gracefully shutdown when done
client.shutdown().await?;Sourcepub async fn disconnect(&mut self, id: &str) -> Result<(), Error>
pub async fn disconnect(&mut self, id: &str) -> Result<(), Error>
Disconnect a specific server by its ID.
Removes the server from active connections and clears its associated tools. Returns an error if the server ID is not found.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
// Disconnect a specific server
client.disconnect("my_server_id").await?;Sourcepub async fn reconnect(&mut self, id: &str) -> Result<(), Error>
pub async fn reconnect(&mut self, id: &str) -> Result<(), Error>
Reconnect to a specific server by its ID.
Re-establishes the connection using the stored configuration. Returns an error if the server ID is not in the configuration.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
// Reconnect to a server after it was disconnected or lost connection
client.reconnect("my_server_id").await?;Sourcepub fn is_connected(&self, id: &str) -> bool
pub fn is_connected(&self, id: &str) -> bool
Check if a specific server is currently connected.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
if client.is_connected("my_server_id") {
println!("Server is connected");
}Sourcepub async fn add_server(&mut self, config: McpServerConfig) -> Result<(), Error>
pub async fn add_server(&mut self, config: McpServerConfig) -> Result<(), Error>
Dynamically add and connect a new server at runtime.
Adds the server configuration and establishes the connection. If auto_register_tools is enabled, discovers and registers the server’s tools.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
// Add a new server dynamically
let new_server = McpServerConfig {
id: "new_server".to_string(),
name: "New MCP Server".to_string(),
source: McpServerSource::Http {
url: "https://api.example.com/mcp".to_string(),
timeout_secs: Some(30),
headers: None,
},
..Default::default()
};
client.add_server(new_server).await?;Sourcepub async fn remove_server(&mut self, id: &str) -> Result<(), Error>
pub async fn remove_server(&mut self, id: &str) -> Result<(), Error>
Disconnect and remove a server from the client.
Closes the connection and removes the server from the configuration.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
// Remove a server completely
client.remove_server("my_server_id").await?;Sourcepub async fn refresh_tools(&mut self) -> Result<(), Error>
pub async fn refresh_tools(&mut self) -> Result<(), Error>
Re-discover tools from all connected servers.
Clears existing tool registrations and re-queries all servers. Useful for long-running clients when servers update their tools.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
// Refresh tools after servers have been updated
client.refresh_tools().await?;Sourcepub fn get_tool(&self, name: &str) -> Option<&McpToolInfo>
pub fn get_tool(&self, name: &str) -> Option<&McpToolInfo>
Get a specific tool by name.
Returns None if no tool with the given name is registered.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
if let Some(tool) = client.get_tool("web_search") {
println!("Found tool: {:?}", tool.description);
}Sourcepub fn has_tool(&self, name: &str) -> bool
pub fn has_tool(&self, name: &str) -> bool
Check if a tool with the given name exists.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
if client.has_tool("web_search") {
println!("Tool is available");
}Sourcepub async fn call_tool(
&self,
name: &str,
arguments: Value,
) -> Result<String, Error>
pub async fn call_tool( &self, name: &str, arguments: Value, ) -> Result<String, Error>
Directly call a tool by name with the given arguments.
This bypasses the callback system and calls the tool directly on the appropriate server with timeout and concurrency controls.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
let result = client.call_tool("web_search", json!({"query": "rust programming"})).await?;
println!("Result: {}", result);Sourcepub fn tool_count(&self) -> usize
pub fn tool_count(&self) -> usize
Get the total number of registered tools.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
println!("Total tools: {}", client.tool_count());Sourcepub fn server_count(&self) -> usize
pub fn server_count(&self) -> usize
Get the number of connected servers.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
println!("Connected servers: {}", client.server_count());Sourcepub fn server_ids(&self) -> Vec<&str>
pub fn server_ids(&self) -> Vec<&str>
Get a list of all connected server IDs.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
for id in client.server_ids() {
println!("Server: {}", id);
}Sourcepub async fn ping_all(&self) -> HashMap<String, Result<(), Error>>
pub async fn ping_all(&self) -> HashMap<String, Result<(), Error>>
Ping all connected servers and return results per server.
Returns a map of server ID to ping result. Useful for health monitoring.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
let results = client.ping_all().await;
for (server_id, result) in results {
match result {
Ok(()) => println!("{}: healthy", server_id),
Err(e) => println!("{}: unhealthy - {}", server_id, e),
}
}Sourcepub async fn list_all_resources(&self) -> Result<Vec<(String, Resource)>, Error>
pub async fn list_all_resources(&self) -> Result<Vec<(String, Resource)>, Error>
List resources from all connected servers.
Returns a vector of (server_id, resource) tuples.
§Example
let config = McpClientConfig::default();
let mut client = McpClient::new(config);
client.initialize().await?;
let resources = client.list_all_resources().await?;
for (server_id, resource) in resources {
println!("Server {}: {:?}", server_id, resource);
}Trait Implementations§
Auto Trait Implementations§
impl Freeze for McpClient
impl !RefUnwindSafe for McpClient
impl Send for McpClient
impl Sync for McpClient
impl Unpin for McpClient
impl !UnwindSafe 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
Source§impl<T> Downcast for T
impl<T> Downcast for T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self is actually part of its subset T (and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self to the equivalent element of its superset.