Struct McpClient

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

A client for interacting with an MCP server.

The McpClient provides a high-level interface for communicating with Model Context Protocol servers. It abstracts away the details of the transport layer and JSON-RPC protocol, offering a simple API for listing and calling tools, and accessing resources. All public methods are instrumented with tracing spans.

§Examples

Basic usage:

use mcp_runner::{McpClient, transport::StdioTransport, error::Result};
use serde_json::{json, Value};
use async_process::{ChildStdin, ChildStdout};



// Create a transport
let transport = StdioTransport::new("fetch-server".to_string(), stdin, stdout);

// Create a client
let client = McpClient::new("fetch-server".to_string(), transport);

// Initialize
client.initialize().await?;

// List tools
let tools = client.list_tools().await?;
for tool in tools {
    println!("Tool: {} - {}", tool.name, tool.description);
}

// Call the fetch tool
#[derive(serde::Serialize, Debug)]
struct FetchInput {
    url: String,
}

let input = FetchInput {
    url: "https://modelcontextprotocol.io".to_string(),
};

let output: Value = client.call_tool("fetch", &input).await?;
println!("Fetch result: {}", output);

Implementations§

Source§

impl McpClient

Source

pub fn new(name: String, transport: impl Transport + 'static) -> Self

Creates a new MCP client with the specified name and transport.

This method is instrumented with tracing.

§Arguments
  • name - A name for this client, typically the server name
  • transport - The transport implementation to use for communication
§Returns

A new McpClient instance

Source

pub fn name(&self) -> &str

Gets the name of the client (usually the same as the server name).

§Returns

A string slice containing the client name

Source

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

Initializes the connection to the MCP server.

This method should be called before any other methods to ensure the server is ready to accept requests. This method is instrumented with tracing.

§Returns

A Result<()> indicating success or failure

Source

pub async fn list_tools(&self) -> Result<Vec<Tool>>

Lists all available tools provided by the MCP server.

This method is instrumented with tracing.

§Returns

A Result<Vec<Tool>> containing descriptions of available tools if successful

Source

pub async fn call_tool<T, R>(&self, name: &str, args: &T) -> Result<R>
where T: Serialize + Debug, R: for<'de> Deserialize<'de>,

Calls a tool on the MCP server with the given arguments.

This method provides a strongly-typed interface for tool calls, where the input and output types are specified as generic parameters. This method is instrumented with tracing.

§Type Parameters
  • T - The input type, which must be serializable to JSON and implement Debug
  • R - The output type, which must be deserializable from JSON
§Arguments
  • name - The name of the tool to call
  • args - The arguments to pass to the tool
§Returns

A Result<R> containing the tool’s response if successful

§Errors

Returns an error if:

  • The tool call fails
  • The arguments cannot be serialized
  • The result cannot be deserialized to type R
Source

pub async fn list_resources(&self) -> Result<Vec<Resource>>

Lists all available resources provided by the MCP server.

This method is instrumented with tracing.

§Returns

A Result<Vec<Resource>> containing descriptions of available resources if successful

Source

pub async fn get_resource<R>(&self, uri: &str) -> Result<R>
where R: for<'de> Deserialize<'de>,

Gets a specific resource from the MCP server.

This method provides a strongly-typed interface for resource retrieval, where the expected resource type is specified as a generic parameter. This method is instrumented with tracing.

§Type Parameters
  • R - The resource type, which must be deserializable from JSON
§Arguments
  • uri - The URI of the resource to retrieve
§Returns

A Result<R> containing the resource data if successful

§Errors

Returns an error if:

  • The resource retrieval fails
  • The result cannot be deserialized to type R
Source

pub async fn close(&self) -> Result<()>

Closes the client connection.

This is a placeholder method since the transport is behind an Arc and can’t actually be closed by the client directly. Users should drop all references to the client to properly clean up resources. This method is instrumented with tracing.

§Returns

A Result<()> that is always Ok

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