Skip to main content

McpClient

Struct McpClient 

Source
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

Source

pub fn new(config: McpClientConfig) -> McpClient

Create a new MCP client with the given configuration

Source

pub async fn initialize(&mut self) -> Result<(), Error>

Initialize connections to all configured servers

Source

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.

Source

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 Tool definition 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);
}
Source

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.

Source

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:

§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);
}
Source

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?;
}
Source

pub fn config(&self) -> &McpClientConfig

Get the client configuration.

Source

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?;
Source

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?;
Source

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?;
Source

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");
}
Source

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?;
Source

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?;
Source

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?;
Source

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);
}
Source

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");
}
Source

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);
Source

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());
Source

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());
Source

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);
}
Source

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),
    }
}
Source

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§

Source§

impl Drop for McpClient

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

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> AsAny for T
where T: Any,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Source§

fn type_name(&self) -> &'static str

Gets the type name of self
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> Downcast for T
where T: AsAny + ?Sized,

Source§

fn is<T>(&self) -> bool
where T: AsAny,

Returns true if the boxed type is the same as T. Read more
Source§

fn downcast_ref<T>(&self) -> Option<&T>
where T: AsAny,

Forward to the method defined on the type Any.
Source§

fn downcast_mut<T>(&mut self) -> Option<&mut T>
where T: AsAny,

Forward to the method defined on the type Any.
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
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
Source§

impl<T> ErasedDestructor for T
where T: 'static,