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
impl McpClient
Sourcepub fn new(config: McpClientConfig) -> Result<Self>
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.
Sourcepub fn with_transport(transport: McpTransport) -> Self
pub fn with_transport(transport: McpTransport) -> Self
Creates a client over transport with default options.
Sourcepub fn connection_state(&self) -> McpConnectionState
pub fn connection_state(&self) -> McpConnectionState
The connection state.
Sourcepub fn client_name(&self) -> &str
pub fn client_name(&self) -> &str
The client name sent in the handshake.
Sourcepub fn continue_on_error(&self) -> bool
pub fn continue_on_error(&self) -> bool
Whether connection failures are skipped with a warning (continueOnError).
Sourcepub fn client(&self) -> Option<Peer<RoleClient>>
pub fn client(&self) -> Option<Peer<RoleClient>>
The rmcp peer of the live connection (client).
Sourcepub fn server_capabilities(&self) -> Option<ServerCapabilities>
pub fn server_capabilities(&self) -> Option<ServerCapabilities>
The capabilities the server announced, once connected.
Sourcepub fn server_version(&self) -> Option<Implementation>
pub fn server_version(&self) -> Option<Implementation>
The server’s name and version, once connected.
Sourcepub fn server_instructions(&self) -> Option<String>
pub fn server_instructions(&self) -> Option<String>
The server’s usage instructions, once connected.
Sourcepub async fn connect(&self, reconnect: bool) -> Result<()>
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.
Sourcepub async fn connect_with(
&self,
reconnect: bool,
cancel_signal: Option<&CancelSignal>,
) -> Result<()>
pub async fn connect_with( &self, reconnect: bool, cancel_signal: Option<&CancelSignal>, ) -> Result<()>
Sourcepub async fn disconnect(&self) -> Result<()>
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.
Sourcepub async fn list_tools(&self) -> Result<Vec<McpTool>>
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.
Sourcepub async fn list_tools_with(
&self,
options: McpListToolsOptions,
) -> Result<Vec<McpTool>>
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.
Sourcepub fn set_on_tools_changed(&self, callback: Option<ToolsChangedCallback>)
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.
Sourcepub async fn list_prompts(
&self,
options: McpListOptions,
) -> Result<ListPromptsResult>
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.
Sourcepub async fn get_prompt(
&self,
prompt_id: &str,
args: Option<JsonObject>,
) -> Result<GetPromptResult>
pub async fn get_prompt( &self, prompt_id: &str, args: Option<JsonObject>, ) -> Result<GetPromptResult>
Sourcepub async fn list_resources(
&self,
options: McpListOptions,
) -> Result<ListResourcesResult>
pub async fn list_resources( &self, options: McpListOptions, ) -> Result<ListResourcesResult>
Sourcepub async fn read_resource(
&self,
uri: impl AsRef<str>,
) -> Result<ReadResourceResult>
pub async fn read_resource( &self, uri: impl AsRef<str>, ) -> Result<ReadResourceResult>
Sourcepub async fn list_resource_templates(
&self,
options: McpListOptions,
) -> Result<ListResourceTemplatesResult>
pub async fn list_resource_templates( &self, options: McpListOptions, ) -> Result<ListResourceTemplatesResult>
Sourcepub async fn call_tool(
&self,
tool: &McpTool,
args: JsonValue,
options: McpCallToolOptions,
) -> Result<JsonValue>
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
impl McpClient
Sourcepub async fn load_servers(
source: impl Into<McpServersSource>,
defaults: McpClientOptions,
options: McpLoadServersOptions,
) -> Result<Vec<Self>>
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§
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§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> ⓘ
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 more