Skip to main content

strands/mcp/
client.rs

1//! [`McpClient`]: lazy connection with `continue_on_error`, tool listing with prefixes and filters,
2//! tool calls with progress, prompts and resources, and list-changed refreshes.
3
4use std::collections::{BTreeMap, HashMap};
5use std::fmt;
6use std::future::Future;
7use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
8use std::time::Duration;
9
10use futures::FutureExt;
11use futures::future::{BoxFuture, Shared};
12use rmcp::RoleClient;
13use rmcp::model::{
14    CallToolRequest, CallToolRequestParams, ClientRequest, GetPromptRequestParams, GetPromptResult, Implementation,
15    ListPromptsResult, ListResourceTemplatesResult, ListResourcesResult, ListToolsResult, PaginatedRequestParams,
16    ProgressToken, ReadResourceRequestParams, ReadResourceResult, RequestId, ServerCapabilities, ServerResult,
17};
18use rmcp::service::{
19    ClientLifecycleMode, Peer, PeerRequestOptions, RunningService, ServiceError, serve_client_with_lifecycle,
20};
21use serde::Serialize;
22
23use super::callbacks::{ElicitationCallback, McpLogHandler, McpProgressCallback, ToolsChangedCallback};
24use super::error::{McpError, McpSdkErrorCode};
25use super::filters::McpToolFilters;
26use super::handler::Handler;
27use super::http::{self, HttpAuth, McpAuthProvider, McpClientCredentials};
28use super::mcp_tool::{McpTool, McpToolConfig};
29use super::progress::{ProgressRoute, ProgressRouter, RoutedTransport};
30use super::trace::{TraceCarrierFn, current_trace_carrier, inject_trace_context};
31use super::transport::{McpTransport, WithoutProgressToken};
32use crate::cancel::CancelSignal;
33use crate::error::{Error, Result, ToolValidationError};
34use crate::types::{JsonObject, JsonValue};
35
36/// The client name sent in the MCP handshake unless `application_name` overrides it.
37pub const DEFAULT_CLIENT_NAME: &str = "strands-agents-rs-sdk";
38
39const NOT_CONNECTED: &str = "MCP server failed to connect. Call connect(true) to retry.";
40const MAX_TOOL_NAME_LENGTH: usize = 64;
41const DEFAULT_LIST_MAX_PAGES: u32 = 64;
42const LIST_CHANGED_DEBOUNCE: Duration = Duration::from_millis(300);
43const MAX_TIMER_DELAY_MS: u128 = 2_147_483_647;
44const INVALID_REQUEST: i32 = -32600;
45const INVALID_PARAMS: i32 = -32602;
46
47/// Connection state of an MCP client (`McpConnectionState`).
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum McpConnectionState {
51    /// Not connected yet, or disconnected.
52    Disconnected,
53    /// Connected.
54    Connected,
55    /// A connect attempt failed under `continue_on_error`; `connect(true)` retries.
56    Failed,
57}
58
59/// Behaviour shared by every MCP client configuration (`McpClientOptions`).
60#[derive(Clone, Default, bon::Builder)]
61#[builder(on(String, into))]
62pub struct McpClientOptions {
63    /// The client name sent in the MCP handshake; [`DEFAULT_CLIENT_NAME`] when absent.
64    pub application_name: Option<String>,
65    /// The client version sent in the MCP handshake; the crate version when absent.
66    pub application_version: Option<String>,
67    /// Sends no W3C trace context in tool call arguments.
68    #[builder(default)]
69    pub disable_mcp_instrumentation: bool,
70    /// Prefix for agent-facing tool names, applied as `<prefix>_<toolName>`.
71    pub prefix: Option<String>,
72    /// Filters controlling which tools this client exposes.
73    pub tool_filters: Option<McpToolFilters>,
74    /// Page cap for the list methods that aggregate every page; 0 disables it. Defaults to 64.
75    pub list_max_pages: Option<u32>,
76    /// Receives progress notifications during tool calls, including the agent's. A per-call
77    /// callback takes precedence.
78    pub progress_callback: Option<McpProgressCallback>,
79    /// Handles server elicitation requests. When set, the client advertises elicitation
80    /// support (form and URL modes).
81    pub elicitation_callback: Option<Arc<dyn ElicitationCallback>>,
82    /// Skips connection failures and overlong prefixed tool names with warnings.
83    #[builder(default)]
84    pub continue_on_error: bool,
85    /// Receives the server's log messages; they go to `tracing` when absent.
86    #[builder(into)]
87    pub log_handler: Option<McpLogHandler>,
88}
89
90impl fmt::Debug for McpClientOptions {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        f.debug_struct("McpClientOptions")
93            .field("application_name", &self.application_name)
94            .field("application_version", &self.application_version)
95            .field("disable_mcp_instrumentation", &self.disable_mcp_instrumentation)
96            .field("prefix", &self.prefix)
97            .field("tool_filters", &self.tool_filters)
98            .field("list_max_pages", &self.list_max_pages)
99            .field("progress_callback", &self.progress_callback.is_some())
100            .field("elicitation_callback", &self.elicitation_callback.is_some())
101            .field("continue_on_error", &self.continue_on_error)
102            .field("log_handler", &self.log_handler.is_some())
103            .finish()
104    }
105}
106
107/// How to reach the server, plus the client's behaviour (`McpClientConfig`).
108///
109/// Give either a [`transport`](Self::transport) or a [`url`](Self::url) for streamable HTTP.
110/// `auth`, `auth_provider` and `headers` require `url`.
111#[derive(Clone, Default, bon::Builder)]
112#[builder(on(String, into))]
113pub struct McpClientConfig {
114    /// A transport. Mutually exclusive with `url`.
115    pub transport: Option<McpTransport>,
116    /// The server URL; the client builds a streamable HTTP transport on every connect.
117    pub url: Option<String>,
118    /// OAuth client credentials for machine-to-machine auth. Requires `url`.
119    pub auth: Option<McpClientCredentials>,
120    /// Supplies bearer tokens. Requires `url`; mutually exclusive with `auth`.
121    pub auth_provider: Option<Arc<dyn McpAuthProvider>>,
122    /// Headers sent with every request. Requires `url`.
123    pub headers: Option<BTreeMap<String, String>>,
124    /// The client's behaviour.
125    #[builder(default)]
126    pub options: McpClientOptions,
127}
128
129impl fmt::Debug for McpClientConfig {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        f.debug_struct("McpClientConfig")
132            .field("transport", &self.transport)
133            .field("url", &self.url)
134            .field("auth", &self.auth)
135            .field("auth_provider", &self.auth_provider.is_some())
136            .field("headers", &self.headers.as_ref().map(BTreeMap::len))
137            .field("options", &self.options)
138            .finish()
139    }
140}
141
142/// Options for the paginated list methods (`McpListOptions`).
143#[derive(Debug, Clone, Default, bon::Builder)]
144#[builder(on(String, into))]
145pub struct McpListOptions {
146    /// Fetches a single page starting at this token. Without it every page is aggregated.
147    pub pagination_token: Option<String>,
148}
149
150/// Per-call overrides for [`McpClient::list_tools_with`] (`McpListToolsOptions`).
151#[derive(Debug, Clone, Default, bon::Builder)]
152#[builder(on(String, into))]
153pub struct McpListToolsOptions {
154    /// Prefix for agent-facing names. An empty string disables a prefix set on the client.
155    pub prefix: Option<String>,
156    /// Tool filters. Empty filters disable filters set on the client.
157    pub tool_filters: Option<McpToolFilters>,
158}
159
160/// Options for one tool call (`McpCallToolOptions`).
161#[derive(Debug, Clone, Default, bon::Builder)]
162pub struct McpCallToolOptions {
163    /// Cancels the request.
164    pub cancel_signal: Option<CancelSignal>,
165    /// Time limit for the call; progress notifications reset it.
166    pub timeout: Option<Duration>,
167    /// Receives progress for this call, in place of the client's callback.
168    pub progress_callback: Option<McpProgressCallback>,
169}
170
171struct Settings {
172    name: String,
173    version: String,
174    prefix: Option<String>,
175    tool_filters: Option<McpToolFilters>,
176    list_max_pages: u32,
177    progress_callback: Option<McpProgressCallback>,
178    elicitation_callback: Option<Arc<dyn ElicitationCallback>>,
179    continue_on_error: bool,
180    log_handler: Option<McpLogHandler>,
181    disable_mcp_instrumentation: bool,
182    trace_carrier: TraceCarrierFn,
183}
184
185type Attempt = Shared<BoxFuture<'static, std::result::Result<(), McpError>>>;
186
187struct Conn {
188    state: McpConnectionState,
189    generation: u64,
190    service: Option<RunningService<RoleClient, Handler>>,
191    peer: Option<Peer<RoleClient>>,
192    router: Option<Arc<ProgressRouter>>,
193    attempt: Option<(u64, Attempt)>,
194    attempts: u64,
195}
196
197#[derive(Default)]
198struct ToolsState {
199    registered_names: Vec<String>,
200    on_tools_changed: Option<ToolsChangedCallback>,
201    refreshing: bool,
202    pending_refresh: bool,
203    debounce: u64,
204}
205
206/// A listed tool's compiled `outputSchema`, or why it does not compile.
207enum OutputSchema {
208    Valid(jsonschema::Validator),
209    Invalid(String),
210}
211
212pub(crate) struct Inner {
213    settings: Settings,
214    transport: McpTransport,
215    conn: Mutex<Conn>,
216    tools: Mutex<ToolsState>,
217    output_schemas: Mutex<HashMap<String, Arc<OutputSchema>>>,
218}
219
220fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
221    mutex.lock().unwrap_or_else(PoisonError::into_inner)
222}
223
224impl Inner {
225    pub(crate) fn name(&self) -> &str {
226        &self.settings.name
227    }
228
229    pub(crate) fn version(&self) -> &str {
230        &self.settings.version
231    }
232
233    pub(crate) fn elicitation_callback(&self) -> Option<&Arc<dyn ElicitationCallback>> {
234        self.settings.elicitation_callback.as_ref()
235    }
236
237    pub(crate) fn log_handler(&self) -> Option<&McpLogHandler> {
238        self.settings.log_handler.as_ref()
239    }
240}
241
242/// A client for one MCP server (`McpClient`).
243///
244/// Cloning shares the connection. The client connects lazily on first use; pass it to an agent
245/// with `.tools([client])` and the agent lists its tools when it initializes. Dropping the last
246/// clone ends the transport; [`disconnect`](Self::disconnect) ends it and waits.
247///
248/// ```no_run
249/// use strands::mcp::{McpClient, McpTransport, StdioServerParameters};
250/// use strands::Agent;
251///
252/// # async fn run() -> strands::Result<()> {
253/// let client = McpClient::with_transport(McpTransport::stdio(StdioServerParameters::new(
254///     "uvx",
255///     ["mcp-server-fetch"],
256/// )));
257/// let mut agent = Agent::builder().tools([client.clone()]).build()?;
258/// agent.invoke("Fetch https://strandsagents.com").await?;
259/// client.disconnect().await?;
260/// # Ok(())
261/// # }
262/// ```
263#[derive(Clone)]
264pub struct McpClient {
265    inner: Arc<Inner>,
266}
267
268fn config_error(message: &str) -> Error {
269    McpError::other(message).into()
270}
271
272fn resolve_transport(config: &McpClientConfig) -> Result<McpTransport> {
273    if config.transport.is_some() && config.url.is_some() {
274        return Err(config_error(
275            "McpClientConfig: provide either \"transport\" or \"url\", not both",
276        ));
277    }
278    if let Some(transport) = &config.transport {
279        if config.auth.is_some() || config.auth_provider.is_some() || config.headers.is_some() {
280            return Err(config_error(
281                "McpClientConfig: \"auth\", \"authProvider\", and \"headers\" require \"url\" (not compatible with \"transport\")",
282            ));
283        }
284        return Ok(transport.clone());
285    }
286    let Some(url) = &config.url else {
287        return Err(config_error(
288            "McpClientConfig: either \"transport\" or \"url\" must be provided",
289        ));
290    };
291    let auth = match (&config.auth, &config.auth_provider) {
292        (Some(_), Some(_)) => {
293            return Err(config_error(
294                "McpClientConfig: provide either \"auth\" or \"authProvider\", not both",
295            ));
296        }
297        (Some(credentials), None) => HttpAuth::Credentials(credentials.clone()),
298        (None, Some(provider)) => HttpAuth::Provider(provider.clone()),
299        (None, None) => HttpAuth::None,
300    };
301    let headers = config.headers.clone().unwrap_or_default();
302    Ok(http::streamable_http(url, &headers, auth)?)
303}
304
305fn aborted(signal: &CancelSignal) -> McpError {
306    McpError::other(
307        signal
308            .reason()
309            .unwrap_or_else(|| "The operation was aborted".to_owned()),
310    )
311}
312
313async fn race<T>(
314    future: impl Future<Output = std::result::Result<T, McpError>>,
315    signal: Option<&CancelSignal>,
316) -> std::result::Result<T, McpError> {
317    let Some(signal) = signal else {
318        return future.await;
319    };
320    tokio::select! {
321        biased;
322        () = signal.cancelled() => Err(aborted(signal)),
323        result = future => result,
324    }
325}
326
327fn validate_timeout(timeout: Option<Duration>) -> std::result::Result<(), McpError> {
328    let Some(timeout) = timeout else {
329        return Ok(());
330    };
331    let millis = timeout.as_millis();
332    if millis == 0 || millis > MAX_TIMER_DELAY_MS || timeout.subsec_nanos() % 1_000_000 != 0 {
333        return Err(McpError::other(format!(
334            "MCP call timeout must be a positive safe integer no greater than {MAX_TIMER_DELAY_MS}"
335        )));
336    }
337    Ok(())
338}
339
340fn js_type_name(value: &JsonValue) -> &'static str {
341    match value {
342        JsonValue::Array(_) => "Array",
343        JsonValue::Bool(_) => "boolean",
344        JsonValue::Number(_) => "number",
345        JsonValue::String(_) => "string",
346        JsonValue::Null | JsonValue::Object(_) => "object",
347    }
348}
349
350trait Paged: Serialize {
351    type Item: Serialize;
352    fn items(&mut self) -> &mut Vec<Self::Item>;
353    fn cursor(&mut self) -> &mut Option<String>;
354}
355
356impl Paged for ListToolsResult {
357    type Item = rmcp::model::Tool;
358    fn items(&mut self) -> &mut Vec<Self::Item> {
359        &mut self.tools
360    }
361    fn cursor(&mut self) -> &mut Option<String> {
362        &mut self.next_cursor
363    }
364}
365
366impl Paged for ListPromptsResult {
367    type Item = rmcp::model::Prompt;
368    fn items(&mut self) -> &mut Vec<Self::Item> {
369        &mut self.prompts
370    }
371    fn cursor(&mut self) -> &mut Option<String> {
372        &mut self.next_cursor
373    }
374}
375
376impl Paged for ListResourcesResult {
377    type Item = rmcp::model::Resource;
378    fn items(&mut self) -> &mut Vec<Self::Item> {
379        &mut self.resources
380    }
381    fn cursor(&mut self) -> &mut Option<String> {
382        &mut self.next_cursor
383    }
384}
385
386impl Paged for ListResourceTemplatesResult {
387    type Item = rmcp::model::ResourceTemplate;
388    fn items(&mut self) -> &mut Vec<Self::Item> {
389        &mut self.resource_templates
390    }
391    fn cursor(&mut self) -> &mut Option<String> {
392        &mut self.next_cursor
393    }
394}
395
396fn page_params(cursor: Option<String>) -> Option<PaginatedRequestParams> {
397    cursor.map(|cursor| PaginatedRequestParams::default().with_cursor(Some(cursor)))
398}
399
400/// Fetches every page into the first one: a page repeating the previous items and cursor ends the
401/// walk, and passing `max_pages` fails.
402async fn list_all_pages<R, F, Fut>(method: &str, max_pages: u32, fetch: F) -> std::result::Result<R, McpError>
403where
404    R: Paged,
405    F: Fn(Option<String>) -> Fut,
406    Fut: Future<Output = std::result::Result<R, ServiceError>>,
407{
408    let mut accumulated = fetch(None).await?;
409    let mut cursor = accumulated.cursor().clone();
410    let mut previous_items = serde_json::to_value(accumulated.items()).unwrap_or_default();
411    let mut pages = 1;
412    while let Some(current) = cursor {
413        if max_pages != 0 && pages >= max_pages {
414            return Err(McpError::sdk(
415                McpSdkErrorCode::ListPaginationExceeded,
416                format!("{method}: exceeded listMaxPages ({max_pages}); server pagination did not terminate"),
417            ));
418        }
419        let mut page = fetch(Some(current.clone())).await?;
420        let items = serde_json::to_value(page.items()).unwrap_or_default();
421        let next = page.cursor().clone();
422        if next.as_deref() == Some(current.as_str()) && items == previous_items {
423            break;
424        }
425        accumulated.items().append(page.items());
426        previous_items = items;
427        cursor = next;
428        pages += 1;
429    }
430    *accumulated.cursor() = None;
431    Ok(accumulated)
432}
433
434struct ProgressRegistration {
435    router: Arc<ProgressRouter>,
436    token: ProgressToken,
437}
438
439impl Drop for ProgressRegistration {
440    fn drop(&mut self) {
441        self.router.remove(&self.token);
442    }
443}
444
445struct CancelOnDrop {
446    peer: Peer<RoleClient>,
447    id: Option<RequestId>,
448}
449
450impl Drop for CancelOnDrop {
451    fn drop(&mut self) {
452        let Some(id) = self.id.take() else {
453            return;
454        };
455        let peer = self.peer.clone();
456        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
457            return;
458        };
459        runtime.spawn(async move {
460            let params =
461                rmcp::model::CancelledNotificationParam::new(Some(id), Some("The operation was aborted".to_owned()));
462            let _ = peer.notify_cancelled(params).await;
463        });
464    }
465}
466
467impl McpClient {
468    /// Creates a client (`new McpClient(config)`); it connects on first use.
469    ///
470    /// # Errors
471    ///
472    /// Both or neither of `transport` and `url`; `auth`, `auth_provider` or `headers` without
473    /// `url`; both `auth` and `auth_provider`; an invalid URL or header.
474    pub fn new(config: McpClientConfig) -> Result<Self> {
475        Self::with_trace_carrier(config, current_trace_carrier)
476    }
477
478    /// Creates a client over `transport` with default options.
479    #[must_use]
480    pub fn with_transport(transport: McpTransport) -> Self {
481        Self::from_parts(transport, McpClientOptions::default(), current_trace_carrier)
482    }
483
484    pub(crate) fn with_trace_carrier(config: McpClientConfig, trace_carrier: TraceCarrierFn) -> Result<Self> {
485        let transport = resolve_transport(&config)?;
486        Ok(Self::from_parts(transport, config.options, trace_carrier))
487    }
488
489    fn from_parts(transport: McpTransport, options: McpClientOptions, trace_carrier: TraceCarrierFn) -> Self {
490        let settings = Settings {
491            name: options
492                .application_name
493                .filter(|name| !name.is_empty())
494                .unwrap_or_else(|| DEFAULT_CLIENT_NAME.to_owned()),
495            version: options
496                .application_version
497                .filter(|version| !version.is_empty())
498                .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_owned()),
499            prefix: options.prefix,
500            tool_filters: options.tool_filters,
501            list_max_pages: options.list_max_pages.unwrap_or(DEFAULT_LIST_MAX_PAGES),
502            progress_callback: options.progress_callback,
503            elicitation_callback: options.elicitation_callback,
504            continue_on_error: options.continue_on_error,
505            log_handler: options.log_handler,
506            disable_mcp_instrumentation: options.disable_mcp_instrumentation,
507            trace_carrier,
508        };
509        Self {
510            inner: Arc::new(Inner {
511                settings,
512                transport,
513                conn: Mutex::new(Conn {
514                    state: McpConnectionState::Disconnected,
515                    generation: 0,
516                    service: None,
517                    peer: None,
518                    router: None,
519                    attempt: None,
520                    attempts: 0,
521                }),
522                tools: Mutex::new(ToolsState::default()),
523                output_schemas: Mutex::new(HashMap::new()),
524            }),
525        }
526    }
527
528    pub(crate) fn from_inner(inner: Arc<Inner>) -> Self {
529        Self { inner }
530    }
531
532    /// A weak handle on the shared state, to observe when the last clone is gone.
533    #[cfg(test)]
534    pub(crate) fn downgrade(&self) -> Weak<Inner> {
535        Arc::downgrade(&self.inner)
536    }
537
538    /// The connection state.
539    #[must_use]
540    pub fn connection_state(&self) -> McpConnectionState {
541        lock(&self.inner.conn).state
542    }
543
544    /// The client name sent in the handshake.
545    #[must_use]
546    pub fn client_name(&self) -> &str {
547        &self.inner.settings.name
548    }
549
550    /// Whether connection failures are skipped with a warning (`continueOnError`).
551    #[must_use]
552    pub fn continue_on_error(&self) -> bool {
553        self.inner.settings.continue_on_error
554    }
555
556    /// The `rmcp` peer of the live connection (`client`).
557    #[must_use]
558    pub fn client(&self) -> Option<Peer<RoleClient>> {
559        lock(&self.inner.conn).peer.clone()
560    }
561
562    fn server_info(&self) -> Option<Arc<rmcp::model::ServerPeerInfo>> {
563        self.client()?.peer_info()
564    }
565
566    /// The capabilities the server announced, once connected.
567    #[must_use]
568    pub fn server_capabilities(&self) -> Option<ServerCapabilities> {
569        self.server_info().map(|info| info.capabilities.clone())
570    }
571
572    /// The server's name and version, once connected.
573    #[must_use]
574    pub fn server_version(&self) -> Option<Implementation> {
575        self.server_info().and_then(|info| info.server_info.clone())
576    }
577
578    /// The server's usage instructions, once connected.
579    #[must_use]
580    pub fn server_instructions(&self) -> Option<String> {
581        self.server_info().and_then(|info| info.instructions.clone())
582    }
583
584    /// Connects to the server (`connect`). Operations call it lazily.
585    ///
586    /// Concurrent callers share one attempt. Under `continue_on_error` a failure is logged, the
587    /// client enters [`McpConnectionState::Failed`], and later calls do nothing until
588    /// `connect(true)` retries. `reconnect` forces a new connection even when connected or
589    /// failed; built-in transports and [`McpTransport::from_fn`] start afresh.
590    ///
591    /// # Errors
592    ///
593    /// The connection failure (without `continue_on_error`), or `MCP client disconnected` when
594    /// [`disconnect`](Self::disconnect) ran meanwhile.
595    pub async fn connect(&self, reconnect: bool) -> Result<()> {
596        self.connect_with(reconnect, None).await
597    }
598
599    /// [`connect`](Self::connect) that stops waiting when `cancel_signal` fires. The attempt
600    /// itself continues for other callers.
601    ///
602    /// # Errors
603    ///
604    /// As [`connect`](Self::connect), or the cancellation.
605    pub async fn connect_with(&self, reconnect: bool, cancel_signal: Option<&CancelSignal>) -> Result<()> {
606        if let Some(signal) = cancel_signal
607            && signal.is_cancelled()
608        {
609            return Err(aborted(signal).into());
610        }
611        let (generation, existing) = {
612            let conn = lock(&self.inner.conn);
613            (
614                conn.generation,
615                conn.attempt.as_ref().map(|(_, attempt)| attempt.clone()),
616            )
617        };
618        if let Some(existing) = existing {
619            let outcome = race(existing, cancel_signal).await;
620            if let Err(error) = outcome
621                && (!reconnect || cancel_signal.is_some_and(CancelSignal::is_cancelled))
622            {
623                return Err(error.into());
624            }
625            self.assert_current(generation)?;
626            if !reconnect {
627                return Ok(());
628            }
629        }
630        let attempt = {
631            let mut conn = lock(&self.inner.conn);
632            if conn.state != McpConnectionState::Disconnected && !reconnect {
633                return Ok(());
634            }
635            self.start_attempt(&mut conn, reconnect)
636        };
637        race(attempt, cancel_signal).await?;
638        self.assert_current(generation)?;
639        Ok(())
640    }
641
642    fn start_attempt(&self, conn: &mut Conn, reconnect: bool) -> Attempt {
643        conn.attempts += 1;
644        let id = conn.attempts;
645        let inner = self.inner.clone();
646        let task = tokio::spawn(async move {
647            let result = run_connect(&inner, reconnect).await;
648            let mut conn = lock(&inner.conn);
649            if conn.attempt.as_ref().is_some_and(|(current, _)| *current == id) {
650                conn.attempt = None;
651            }
652            result
653        });
654        let attempt = async move {
655            task.await
656                .unwrap_or_else(|error| Err(McpError::other(format!("MCP connect task failed: {error}"))))
657        }
658        .boxed()
659        .shared();
660        conn.attempt = Some((id, attempt.clone()));
661        attempt
662    }
663
664    fn assert_current(&self, generation: u64) -> std::result::Result<(), McpError> {
665        if lock(&self.inner.conn).generation == generation {
666            Ok(())
667        } else {
668            Err(McpError::disconnected())
669        }
670    }
671
672    async fn connect_or_throw(&self, cancel_signal: Option<&CancelSignal>) -> Result<Peer<RoleClient>> {
673        Ok(self.live_connection(cancel_signal).await?.0)
674    }
675
676    async fn live_connection(
677        &self,
678        cancel_signal: Option<&CancelSignal>,
679    ) -> Result<(Peer<RoleClient>, Option<Arc<ProgressRouter>>)> {
680        self.connect_with(false, cancel_signal).await?;
681        let conn = lock(&self.inner.conn);
682        if conn.state == McpConnectionState::Failed {
683            return Err(McpError::other(NOT_CONNECTED).into());
684        }
685        let peer = conn
686            .peer
687            .clone()
688            .ok_or_else(|| McpError::sdk(McpSdkErrorCode::NotConnected, "Not connected"))?;
689        Ok((peer, conn.router.clone()))
690    }
691
692    /// Disconnects and ends the transport (`disconnect`). Pending operations fail with
693    /// `MCP client disconnected`; a later operation connects again.
694    ///
695    /// # Errors
696    ///
697    /// None today; the signature leaves room for transport close failures.
698    pub async fn disconnect(&self) -> Result<()> {
699        cancel_tools_changed(&self.inner);
700        let service = {
701            let mut conn = lock(&self.inner.conn);
702            conn.generation += 1;
703            conn.state = McpConnectionState::Disconnected;
704            conn.peer = None;
705            conn.router = None;
706            conn.attempt = None;
707            conn.service.take()
708        };
709        if let Some(service) = service {
710            let _ = service.cancel().await;
711        }
712        Ok(())
713    }
714
715    /// Lists the server's tools as [`McpTool`]s with the client's prefix and filters. A failed
716    /// connection under `continue_on_error` lists none.
717    ///
718    /// # Errors
719    ///
720    /// A connection or protocol failure, or [`ToolValidationError`] when a prefixed name exceeds
721    /// 64 characters without `continue_on_error`.
722    pub async fn list_tools(&self) -> Result<Vec<McpTool>> {
723        self.list_tools_with(McpListToolsOptions::default()).await
724    }
725
726    /// [`list_tools`](Self::list_tools) with per-call overrides. A prefix renames tools for the
727    /// agent only: they are invoked, and matched by name and regex filters, under their
728    /// server-side names.
729    ///
730    /// # Errors
731    ///
732    /// As [`list_tools`](Self::list_tools).
733    pub async fn list_tools_with(&self, options: McpListToolsOptions) -> Result<Vec<McpTool>> {
734        self.connect(false).await?;
735        let peer = {
736            let conn = lock(&self.inner.conn);
737            if conn.state == McpConnectionState::Failed {
738                return Ok(Vec::new());
739            }
740            conn.peer.clone()
741        };
742        let Some(peer) = peer else {
743            return Err(McpError::sdk(McpSdkErrorCode::NotConnected, "Not connected").into());
744        };
745        let settings = &self.inner.settings;
746        let prefix = options.prefix.as_ref().or(settings.prefix.as_ref());
747        let filters = options.tool_filters.as_ref().or(settings.tool_filters.as_ref());
748        let listed: ListToolsResult = list_all_pages("tools/list", settings.list_max_pages, |cursor| {
749            let peer = peer.clone();
750            async move { peer.list_tools(page_params(cursor)).await }
751        })
752        .await?;
753        self.cache_output_schemas(&listed.tools);
754
755        let mut tools = Vec::new();
756        for spec in &listed.tools {
757            if let Some(tool) = self.listed_tool(spec, prefix.map(String::as_str), filters)? {
758                tools.push(tool);
759            }
760        }
761        if options.prefix.is_none() && options.tool_filters.is_none() {
762            lock(&self.inner.tools).registered_names = tools
763                .iter()
764                .map(|tool| crate::tools::Tool::name(tool).to_owned())
765                .collect();
766        }
767        Ok(tools)
768    }
769
770    /// Compiles the listed tools' output schemas for [`call_tool`](Self::call_tool), from the last
771    /// aggregated `tools/list`.
772    fn cache_output_schemas(&self, tools: &[rmcp::model::Tool]) {
773        let schemas = tools
774            .iter()
775            .filter_map(|tool| {
776                let schema = JsonValue::Object(tool.output_schema.as_ref()?.as_ref().clone());
777                let compiled = match jsonschema::validator_for(&schema) {
778                    Ok(validator) => OutputSchema::Valid(validator),
779                    Err(error) => OutputSchema::Invalid(error.to_string().chars().take(200).collect()),
780                };
781                Some((tool.name.to_string(), Arc::new(compiled)))
782            })
783            .collect();
784        *lock(&self.inner.output_schemas) = schemas;
785    }
786
787    fn listed_tool(
788        &self,
789        spec: &rmcp::model::Tool,
790        prefix: Option<&str>,
791        filters: Option<&McpToolFilters>,
792    ) -> Result<Option<McpTool>> {
793        let server_name = spec.name.to_string();
794        let prefix = prefix.filter(|prefix| !prefix.is_empty());
795        let tool_name = match prefix {
796            Some(prefix) => {
797                let renamed = format!("{prefix}_{server_name}");
798                tracing::debug!("tool_rename=<{server_name}->{renamed}> | renamed tool");
799                renamed
800            }
801            None => server_name.clone(),
802        };
803        let description = spec
804            .description
805            .as_deref()
806            .filter(|description| !description.is_empty())
807            .map_or_else(|| format!("Tool which performs {server_name}"), ToOwned::to_owned);
808        let annotations = spec
809            .annotations
810            .as_ref()
811            .and_then(|annotations| serde_json::to_value(annotations).ok())
812            .and_then(|value| match value {
813                JsonValue::Object(map) if !map.is_empty() => Some(map),
814                _ => None,
815            });
816        let config = McpToolConfig {
817            name: tool_name.clone(),
818            description,
819            input_schema: JsonValue::Object(spec.input_schema.as_ref().clone()),
820            output_schema: spec
821                .output_schema
822                .as_ref()
823                .map(|schema| JsonValue::Object(schema.as_ref().clone())),
824            annotations,
825            client: self.clone(),
826        };
827        let tool = McpTool::listed(config, server_name.clone());
828        if filters.is_some_and(|filters| !filters.includes(&tool, &server_name)) {
829            return Ok(None);
830        }
831        if prefix.is_none() || tool_name.len() <= MAX_TOOL_NAME_LENGTH {
832            return Ok(Some(tool));
833        }
834        let server = self
835            .server_version()
836            .map_or_else(|| "unknown".to_owned(), |version| version.name);
837        let message = format!(
838            "server=<{server}>, tool=<{server_name}>, name=<{tool_name}>, length=<{}>, limit=<{MAX_TOOL_NAME_LENGTH}> | tool name exceeds registry limit | use a shorter prefix or tool name",
839            tool_name.len()
840        );
841        if !self.inner.settings.continue_on_error {
842            return Err(ToolValidationError::new(message).into());
843        }
844        tracing::warn!("{message} | skipping tool (continueOnError)");
845        Ok(None)
846    }
847
848    /// Sets the callback run when the server's tool list changes, or removes
849    /// it with `None`. It receives the previously registered names and the refreshed tools.
850    pub fn set_on_tools_changed(&self, callback: Option<ToolsChangedCallback>) {
851        lock(&self.inner.tools).on_tools_changed = callback;
852    }
853
854    /// Schedules a refresh after a `notifications/tools/list_changed`, debounced by 300 ms.
855    /// Disconnecting or reconnecting cancels a pending refresh.
856    pub(crate) fn notify_tools_changed(&self) {
857        let debounce = {
858            let mut tools = lock(&self.inner.tools);
859            tools.debounce += 1;
860            tools.debounce
861        };
862        let connection = lock(&self.inner.conn).generation;
863        let weak = Arc::downgrade(&self.inner);
864        tokio::spawn(async move {
865            tokio::time::sleep(LIST_CHANGED_DEBOUNCE).await;
866            let Some(inner) = Weak::upgrade(&weak) else {
867                return;
868            };
869            if lock(&inner.tools).debounce != debounce {
870                return;
871            }
872            {
873                let conn = lock(&inner.conn);
874                if conn.generation != connection || conn.state != McpConnectionState::Connected {
875                    return;
876                }
877            }
878            Self { inner }.handle_tools_changed().await;
879        });
880    }
881
882    pub(crate) async fn handle_tools_changed(&self) {
883        {
884            let mut tools = lock(&self.inner.tools);
885            if tools.refreshing {
886                tools.pending_refresh = true;
887                return;
888            }
889            tools.refreshing = true;
890        }
891        loop {
892            let old_names = {
893                let mut tools = lock(&self.inner.tools);
894                tools.pending_refresh = false;
895                tools.registered_names.clone()
896            };
897            match self.list_tools().await {
898                Ok(new_tools) => {
899                    let callback = lock(&self.inner.tools).on_tools_changed.clone();
900                    if let Some(callback) = callback {
901                        callback(old_names, new_tools);
902                    }
903                }
904                Err(error) => {
905                    tracing::warn!(
906                        "client=<{}>, error=<{error}> | failed to refresh tools after toolsChanged notification",
907                        self.inner.settings.name
908                    );
909                    break;
910                }
911            }
912            if !lock(&self.inner.tools).pending_refresh {
913                break;
914            }
915        }
916        lock(&self.inner.tools).refreshing = false;
917    }
918
919    fn capabilities_lack(&self, has: impl Fn(&ServerCapabilities) -> bool) -> bool {
920        self.server_capabilities()
921            .is_some_and(|capabilities| !has(&capabilities))
922    }
923
924    /// Lists the server's prompts. Without a pagination token every page is
925    /// aggregated (failing past `list_max_pages`); with one, a single page is fetched.
926    ///
927    /// # Errors
928    ///
929    /// `MCP server failed to connect. Call connect(true) to retry.` after a failed connection
930    /// under `continue_on_error`; a connection or protocol failure.
931    pub async fn list_prompts(&self, options: McpListOptions) -> Result<ListPromptsResult> {
932        let peer = self.connect_or_throw(None).await?;
933        if self.capabilities_lack(|capabilities| capabilities.prompts.is_some()) {
934            return Ok(empty_list(ListPromptsResult::with_all_items(Vec::new())));
935        }
936        self.paged("prompts/list", options, move |cursor| {
937            let peer = peer.clone();
938            async move { peer.list_prompts(page_params(cursor)).await }
939        })
940        .await
941    }
942
943    /// Gets a prompt by name, with arguments for its template.
944    ///
945    /// # Errors
946    ///
947    /// As [`list_prompts`](Self::list_prompts).
948    pub async fn get_prompt(&self, prompt_id: &str, args: Option<JsonObject>) -> Result<GetPromptResult> {
949        let peer = self.connect_or_throw(None).await?;
950        let mut params = GetPromptRequestParams::new(prompt_id);
951        params.arguments = args;
952        Ok(peer.get_prompt(params).await.map_err(McpError::from)?)
953    }
954
955    /// Lists the server's resources, paginated as
956    /// [`list_prompts`](Self::list_prompts).
957    ///
958    /// # Errors
959    ///
960    /// As [`list_prompts`](Self::list_prompts).
961    pub async fn list_resources(&self, options: McpListOptions) -> Result<ListResourcesResult> {
962        let peer = self.connect_or_throw(None).await?;
963        if self.capabilities_lack(|capabilities| capabilities.resources.is_some()) {
964            return Ok(empty_list(ListResourcesResult::with_all_items(Vec::new())));
965        }
966        self.paged("resources/list", options, move |cursor| {
967            let peer = peer.clone();
968            async move { peer.list_resources(page_params(cursor)).await }
969        })
970        .await
971    }
972
973    /// Reads a resource.
974    ///
975    /// # Errors
976    ///
977    /// As [`list_prompts`](Self::list_prompts).
978    pub async fn read_resource(&self, uri: impl AsRef<str>) -> Result<ReadResourceResult> {
979        let peer = self.connect_or_throw(None).await?;
980        let params = ReadResourceRequestParams::new(uri.as_ref());
981        Ok(peer.read_resource(params).await.map_err(McpError::from)?)
982    }
983
984    /// Lists the server's resource templates, paginated as
985    /// [`list_prompts`](Self::list_prompts).
986    ///
987    /// # Errors
988    ///
989    /// As [`list_prompts`](Self::list_prompts).
990    pub async fn list_resource_templates(&self, options: McpListOptions) -> Result<ListResourceTemplatesResult> {
991        let peer = self.connect_or_throw(None).await?;
992        if self.capabilities_lack(|capabilities| capabilities.resources.is_some()) {
993            return Ok(empty_list(ListResourceTemplatesResult::with_all_items(Vec::new())));
994        }
995        self.paged("resources/templates/list", options, move |cursor| {
996            let peer = peer.clone();
997            async move { peer.list_resource_templates(page_params(cursor)).await }
998        })
999        .await
1000    }
1001
1002    async fn paged<R, F, Fut>(&self, method: &str, options: McpListOptions, fetch: F) -> Result<R>
1003    where
1004        R: Paged,
1005        F: Fn(Option<String>) -> Fut,
1006        Fut: Future<Output = std::result::Result<R, ServiceError>>,
1007    {
1008        if let Some(token) = options.pagination_token {
1009            return Ok(fetch(Some(token)).await.map_err(McpError::from)?);
1010        }
1011        Ok(list_all_pages(method, self.inner.settings.list_max_pages, fetch).await?)
1012    }
1013
1014    /// Calls `tool` on the server with `args` and returns the raw `tools/call` result.
1015    ///
1016    /// # Errors
1017    ///
1018    /// Arguments that are not a JSON object, an invalid timeout, a failed connection, a
1019    /// protocol error from the server, a timeout or the cancellation.
1020    pub async fn call_tool(&self, tool: &McpTool, args: JsonValue, options: McpCallToolOptions) -> Result<JsonValue> {
1021        validate_timeout(options.timeout)?;
1022        let signal = options.cancel_signal.as_ref();
1023        let (peer, router) = self.live_connection(signal).await?;
1024        let params = self.prepare_tool_call(tool, args)?;
1025        let output_schema = self.output_schema(tool.server_tool_name())?;
1026        let callback = options
1027            .progress_callback
1028            .or_else(|| self.inner.settings.progress_callback.clone());
1029
1030        let mut request = CallToolRequest::new(params);
1031        match (&callback, &router) {
1032            (Some(callback), Some(_)) => {
1033                request.extensions.insert(ProgressRoute(callback.clone()));
1034            }
1035            _ if options.timeout.is_none() => {
1036                request.extensions.insert(WithoutProgressToken);
1037            }
1038            _ => {}
1039        }
1040        let mut request_options = PeerRequestOptions::no_options();
1041        request_options.timeout = options.timeout;
1042        request_options.reset_timeout_on_progress = options.timeout.is_some();
1043        request_options.max_total_timeout = options.timeout;
1044        let handle = peer
1045            .send_request_with_option(ClientRequest::CallToolRequest(request), request_options)
1046            .await
1047            .map_err(McpError::from)?;
1048        let registration = router
1049            .filter(|_| callback.is_some())
1050            .map(|router| ProgressRegistration {
1051                router,
1052                token: handle.progress_token.clone(),
1053            });
1054        let mut guard = CancelOnDrop {
1055            peer,
1056            id: Some(handle.id.clone()),
1057        };
1058        let response = race(async { handle.await_response().await.map_err(McpError::from) }, signal).await;
1059        if !(response.is_err() && signal.is_some_and(CancelSignal::is_cancelled)) {
1060            guard.id = None;
1061        }
1062        if let Some(registration) = &registration
1063            && response.is_ok()
1064        {
1065            registration.router.flush().await;
1066        }
1067        let raw = match response? {
1068            ServerResult::CallToolResult(result) => serde_json::to_value(result)?,
1069            ServerResult::CustomResult(custom) => custom.0,
1070            _ => return Err(McpError::sdk(McpSdkErrorCode::InvalidResult, "Unexpected response type").into()),
1071        };
1072        if let Some(schema) = output_schema {
1073            validate_output(tool.server_tool_name(), &schema, &raw)?;
1074        }
1075        Ok(raw)
1076    }
1077
1078    /// The compiled output schema of a listed tool; an invalid one fails the call before it is
1079    /// sent.
1080    fn output_schema(&self, server_tool_name: &str) -> std::result::Result<Option<Arc<OutputSchema>>, McpError> {
1081        let Some(schema) = lock(&self.inner.output_schemas).get(server_tool_name).cloned() else {
1082            return Ok(None);
1083        };
1084        if let OutputSchema::Invalid(message) = schema.as_ref() {
1085            return Err(McpError::protocol(
1086                INVALID_PARAMS,
1087                format!("Tool '{server_tool_name}' has an invalid outputSchema: {message}"),
1088                None,
1089            ));
1090        }
1091        Ok(Some(schema))
1092    }
1093
1094    fn prepare_tool_call(&self, tool: &McpTool, args: JsonValue) -> Result<CallToolRequestParams> {
1095        let args = match args {
1096            JsonValue::Null => JsonObject::new(),
1097            JsonValue::Object(map) => map,
1098            other => {
1099                return Err(McpError::other(format!(
1100                    "MCP Protocol Error: Tool arguments must be a JSON Object (named parameters). Received: {}",
1101                    js_type_name(&other)
1102                ))
1103                .into());
1104            }
1105        };
1106        let settings = &self.inner.settings;
1107        let args = if settings.disable_mcp_instrumentation {
1108            args
1109        } else {
1110            inject_trace_context(args, settings.trace_carrier)
1111        };
1112        let mut params = CallToolRequestParams::new(tool.server_tool_name().to_owned());
1113        params.arguments = Some(args);
1114        Ok(params)
1115    }
1116}
1117
1118/// Checks a `tools/call` result against the tool's output schema.
1119fn validate_output(
1120    server_tool_name: &str,
1121    schema: &OutputSchema,
1122    raw: &JsonValue,
1123) -> std::result::Result<(), McpError> {
1124    let OutputSchema::Valid(validator) = schema else {
1125        return Ok(());
1126    };
1127    if raw.get("isError").is_some_and(|value| value.as_bool() == Some(true)) {
1128        return Ok(());
1129    }
1130    let Some(structured) = raw.get("structuredContent") else {
1131        return Err(McpError::protocol(
1132            INVALID_REQUEST,
1133            format!("Tool {server_tool_name} has an output schema but did not return structured content"),
1134            None,
1135        ));
1136    };
1137    let issues: Vec<String> = validator
1138        .iter_errors(structured)
1139        .map(|error| {
1140            let path = error.instance_path().as_str();
1141            if path.is_empty() {
1142                error.to_string()
1143            } else {
1144                format!("{path}: {error}")
1145            }
1146        })
1147        .collect();
1148    if issues.is_empty() {
1149        return Ok(());
1150    }
1151    Err(McpError::protocol(
1152        INVALID_PARAMS,
1153        format!(
1154            "Structured content does not match the tool's output schema: {}",
1155            issues.join("; ")
1156        ),
1157        None,
1158    ))
1159}
1160
1161fn empty_list<R: Paged + EmptyResultType>(mut result: R) -> R {
1162    result.clear_result_type();
1163    result
1164}
1165
1166trait EmptyResultType {
1167    fn clear_result_type(&mut self);
1168}
1169
1170macro_rules! clear_result_type {
1171    ($($result:ty),*) => {
1172        $(impl EmptyResultType for $result {
1173            fn clear_result_type(&mut self) {
1174                self.result_type = None;
1175            }
1176        })*
1177    };
1178}
1179
1180clear_result_type!(ListPromptsResult, ListResourcesResult, ListResourceTemplatesResult);
1181
1182/// Cancels a pending list-changed refresh.
1183fn cancel_tools_changed(inner: &Inner) {
1184    lock(&inner.tools).debounce += 1;
1185}
1186
1187async fn close_previous(inner: &Inner, generation: u64) -> std::result::Result<(), McpError> {
1188    cancel_tools_changed(inner);
1189    let previous = {
1190        let mut conn = lock(&inner.conn);
1191        if conn.state == McpConnectionState::Connected {
1192            conn.peer = None;
1193            conn.router = None;
1194            conn.service.take()
1195        } else {
1196            None
1197        }
1198    };
1199    if let Some(service) = previous {
1200        let _ = service.cancel().await;
1201    }
1202    let mut conn = lock(&inner.conn);
1203    if conn.generation != generation {
1204        return Err(McpError::disconnected());
1205    }
1206    if conn.state == McpConnectionState::Connected {
1207        conn.state = McpConnectionState::Disconnected;
1208    }
1209    Ok(())
1210}
1211
1212/// Stores a new connection unless `disconnect` ran meanwhile; returns the stale one to close.
1213fn store_connection(
1214    inner: &Inner,
1215    generation: u64,
1216    established: std::result::Result<Established, McpError>,
1217) -> (
1218    std::result::Result<(), McpError>,
1219    Option<RunningService<RoleClient, Handler>>,
1220) {
1221    let mut conn = lock(&inner.conn);
1222    if conn.generation != generation {
1223        return (
1224            Err(McpError::disconnected()),
1225            established.ok().map(|(service, _)| service),
1226        );
1227    }
1228    match established {
1229        Ok((service, router)) => {
1230            conn.peer = Some(service.peer().clone());
1231            conn.router = Some(router);
1232            conn.service = Some(service);
1233            conn.state = McpConnectionState::Connected;
1234            (Ok(()), None)
1235        }
1236        Err(error) if inner.settings.continue_on_error => {
1237            conn.state = McpConnectionState::Failed;
1238            tracing::warn!(
1239                "client=<{}>, error=<{error}> | MCP server failed to connect, continuing (continueOnError)",
1240                inner.settings.name
1241            );
1242            (Ok(()), None)
1243        }
1244        Err(error) => (Err(error), None),
1245    }
1246}
1247
1248async fn run_connect(inner: &Arc<Inner>, reconnect: bool) -> std::result::Result<(), McpError> {
1249    let generation = lock(&inner.conn).generation;
1250    if reconnect {
1251        close_previous(inner, generation).await?;
1252    }
1253    let established = establish(inner).await;
1254    let (result, stale) = store_connection(inner, generation, established);
1255    if let Some(service) = stale {
1256        let _ = service.cancel().await;
1257    }
1258    result
1259}
1260
1261type Established = (RunningService<RoleClient, Handler>, Arc<ProgressRouter>);
1262
1263async fn establish(inner: &Arc<Inner>) -> std::result::Result<Established, McpError> {
1264    let transport = inner.transport.start().await?;
1265    let router = ProgressRouter::new(inner.settings.name.clone());
1266    let transport = RoutedTransport::new(transport, router.clone());
1267    let handler = Handler::new(Arc::downgrade(inner), inner);
1268    let service = serve_client_with_lifecycle(handler, transport, ClientLifecycleMode::Initialize)
1269        .await
1270        .map_err(McpError::transport)?;
1271    Ok((service, router))
1272}
1273
1274impl fmt::Debug for McpClient {
1275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1276        f.debug_struct("McpClient")
1277            .field("client_name", &self.inner.settings.name)
1278            .field("transport", &self.inner.transport)
1279            .field("connection_state", &self.connection_state())
1280            .finish_non_exhaustive()
1281    }
1282}