Skip to main content

McpClient

Struct McpClient 

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

A client for one MCP server (McpClient).

Cloning shares the connection. The client connects lazily on first use; pass it to an agent with .tools([client]) and the agent lists its tools when it initializes. Dropping the last clone ends the transport; disconnect ends it and waits.

use strands::mcp::{McpClient, McpTransport, StdioServerParameters};
use strands::Agent;

let client = McpClient::with_transport(McpTransport::stdio(StdioServerParameters::new(
    "uvx",
    ["mcp-server-fetch"],
)));
let mut agent = Agent::builder().tools([client.clone()]).build()?;
agent.invoke("Fetch https://strandsagents.com").await?;
client.disconnect().await?;

Implementations§

Source§

impl McpClient

Source

pub fn new(config: McpClientConfig) -> Result<Self>

Creates a client (new McpClient(config)); it connects on first use.

§Errors

Both or neither of transport and url; auth, auth_provider or headers without url; both auth and auth_provider; an invalid URL or header.

Source

pub fn with_transport(transport: McpTransport) -> Self

Creates a client over transport with default options.

Source

pub fn connection_state(&self) -> McpConnectionState

The connection state.

Source

pub fn client_name(&self) -> &str

The client name sent in the handshake.

Source

pub fn continue_on_error(&self) -> bool

Whether connection failures are skipped with a warning (continueOnError).

Source

pub fn client(&self) -> Option<Peer<RoleClient>>

The rmcp peer of the live connection (client).

Source

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

The capabilities the server announced, once connected.

Source

pub fn server_version(&self) -> Option<Implementation>

The server’s name and version, once connected.

Source

pub fn server_instructions(&self) -> Option<String>

The server’s usage instructions, once connected.

Source

pub async fn connect(&self, reconnect: bool) -> Result<()>

Connects to the server (connect). Operations call it lazily.

Concurrent callers share one attempt. Under continue_on_error a failure is logged, the client enters McpConnectionState::Failed, and later calls do nothing until connect(true) retries. reconnect forces a new connection even when connected or failed; built-in transports and McpTransport::from_fn start afresh.

§Errors

The connection failure (without continue_on_error), or MCP client disconnected when disconnect ran meanwhile.

Source

pub async fn connect_with( &self, reconnect: bool, cancel_signal: Option<&CancelSignal>, ) -> Result<()>

connect that stops waiting when cancel_signal fires. The attempt itself continues for other callers.

§Errors

As connect, or the cancellation.

Source

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

Disconnects and ends the transport (disconnect). Pending operations fail with MCP client disconnected; a later operation connects again.

§Errors

None today; the signature leaves room for transport close failures.

Source

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

Lists the server’s tools as McpTools with the client’s prefix and filters. A failed connection under continue_on_error lists none.

§Errors

A connection or protocol failure, or ToolValidationError when a prefixed name exceeds 64 characters without continue_on_error.

Source

pub async fn list_tools_with( &self, options: McpListToolsOptions, ) -> Result<Vec<McpTool>>

list_tools with per-call overrides. A prefix renames tools for the agent only: they are invoked, and matched by name and regex filters, under their server-side names.

§Errors

As list_tools.

Source

pub fn set_on_tools_changed(&self, callback: Option<ToolsChangedCallback>)

Sets the callback run when the server’s tool list changes, or removes it with None. It receives the previously registered names and the refreshed tools.

Source

pub async fn list_prompts( &self, options: McpListOptions, ) -> Result<ListPromptsResult>

Lists the server’s prompts. Without a pagination token every page is aggregated (failing past list_max_pages); with one, a single page is fetched.

§Errors

MCP server failed to connect. Call connect(true) to retry. after a failed connection under continue_on_error; a connection or protocol failure.

Source

pub async fn get_prompt( &self, prompt_id: &str, args: Option<JsonObject>, ) -> Result<GetPromptResult>

Gets a prompt by name, with arguments for its template.

§Errors

As list_prompts.

Source

pub async fn list_resources( &self, options: McpListOptions, ) -> Result<ListResourcesResult>

Lists the server’s resources, paginated as list_prompts.

§Errors

As list_prompts.

Source

pub async fn read_resource( &self, uri: impl AsRef<str>, ) -> Result<ReadResourceResult>

Reads a resource.

§Errors

As list_prompts.

Source

pub async fn list_resource_templates( &self, options: McpListOptions, ) -> Result<ListResourceTemplatesResult>

Lists the server’s resource templates, paginated as list_prompts.

§Errors

As list_prompts.

Source

pub async fn call_tool( &self, tool: &McpTool, args: JsonValue, options: McpCallToolOptions, ) -> Result<JsonValue>

Calls tool on the server with args and returns the raw tools/call result.

§Errors

Arguments that are not a JSON object, an invalid timeout, a failed connection, a protocol error from the server, a timeout or the cancellation.

Source§

impl McpClient

Source

pub async fn load_servers( source: impl Into<McpServersSource>, defaults: McpClientOptions, options: McpLoadServersOptions, ) -> Result<Vec<Self>>

Creates one client per enabled server of an mcp.json-style config.

defaults apply to every client unless the entry overrides them; each client is named after its config key unless defaults names the application.

use strands::mcp::{McpClient, McpClientOptions, McpLoadServersOptions, McpServerConfig};

let clients = McpClient::load_servers(
    [("docs", McpServerConfig::builder().url("https://example.com/mcp").build())],
    McpClientOptions::default(),
    McpLoadServersOptions::default(),
)
.await?;
assert_eq!(clients[0].client_name(), "docs");
§Errors

An unreadable or malformed file, a non-object entry, or an entry that fails to resolve (missing fields, an unset variable, an invalid regex or URL) unless continue_on_error applies to it.

Trait Implementations§

Source§

impl Clone for McpClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for McpClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<McpClient> for ToolSource

Available on crate feature mcp only.
Source§

fn from(client: McpClient) -> Self

Converts to this type from the input type.

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

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.

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
§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
§

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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

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