Skip to main content

strands/mcp/
callbacks.rs

1//! The callbacks an [`McpClient`](super::McpClient) takes: progress, server logs, elicitation
2//! and tool-list changes.
3use std::fmt;
4use std::future::Future;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use futures::FutureExt;
9use futures::future::BoxFuture;
10use rmcp::model::{ElicitRequestParams, ElicitResult};
11use serde::{Deserialize, Serialize};
12
13use super::mcp_tool::McpTool;
14use crate::cancel::CancelSignal;
15use crate::error::BoxError;
16use crate::types::JsonValue;
17
18/// A progress update an MCP server reports during a tool call (`McpProgress`).
19#[derive(Debug, Clone, PartialEq, serde::Serialize)]
20#[non_exhaustive]
21pub struct McpProgress {
22    /// Work completed so far. Increases even when the total is unknown.
23    pub progress: f64,
24    /// Total work, when the server reports one.
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub total: Option<f64>,
27    /// A description of the current progress, when the server provides one.
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub message: Option<String>,
30}
31
32impl McpProgress {
33    /// A progress update.
34    #[must_use]
35    pub fn new(progress: f64, total: Option<f64>, message: Option<String>) -> Self {
36        Self {
37            progress,
38            total,
39            message,
40        }
41    }
42}
43
44type ProgressFn = dyn Fn(McpProgress) -> BoxFuture<'static, Result<(), BoxError>> + Send + Sync;
45
46/// Receives progress notifications during a tool call (`McpProgressCallback`). A failure is
47/// logged as a warning.
48///
49/// Build one from a plain closure with `.into()`, or from an async, fallible one with
50/// [`new`](Self::new).
51#[derive(Clone)]
52pub struct McpProgressCallback(Arc<ProgressFn>);
53
54impl McpProgressCallback {
55    /// A callback that awaits `callback` for each update.
56    pub fn new<F, Fut>(callback: F) -> Self
57    where
58        F: Fn(McpProgress) -> Fut + Send + Sync + 'static,
59        Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
60    {
61        Self(Arc::new(move |progress| callback(progress).boxed()))
62    }
63
64    pub(crate) async fn call(&self, progress: McpProgress) -> Result<(), BoxError> {
65        (self.0)(progress).await
66    }
67}
68
69impl<F: Fn(McpProgress) + Send + Sync + 'static> From<F> for McpProgressCallback {
70    fn from(callback: F) -> Self {
71        Self(Arc::new(move |progress| {
72            callback(progress);
73            futures::future::ready(Ok(())).boxed()
74        }))
75    }
76}
77
78impl fmt::Debug for McpProgressCallback {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.write_str("McpProgressCallback")
81    }
82}
83
84/// The severity of an MCP server log message (`LoggingLevel`).
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "lowercase")]
87#[non_exhaustive]
88pub enum McpLogLevel {
89    /// `debug`.
90    Debug,
91    /// `info`.
92    Info,
93    /// `notice`.
94    Notice,
95    /// `warning`.
96    Warning,
97    /// `error`.
98    Error,
99    /// `critical`.
100    Critical,
101    /// `alert`.
102    Alert,
103    /// `emergency`.
104    Emergency,
105}
106
107/// A log message an MCP server emits (`LoggingMessageNotificationParams`).
108#[derive(Debug, Clone, PartialEq, Serialize)]
109#[non_exhaustive]
110pub struct McpLogMessage {
111    /// The severity.
112    pub level: McpLogLevel,
113    /// The name of the logger that emitted the message, when the server gives one.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub logger: Option<String>,
116    /// The message: any JSON value.
117    pub data: JsonValue,
118}
119
120impl McpLogMessage {
121    /// A message at `level` without a logger name.
122    #[must_use]
123    pub fn new(level: McpLogLevel, data: JsonValue) -> Self {
124        Self {
125            level,
126            logger: None,
127            data,
128        }
129    }
130
131    /// Sets the logger name.
132    #[must_use]
133    pub fn with_logger(mut self, logger: impl Into<String>) -> Self {
134        self.logger = Some(logger.into());
135        self
136    }
137}
138
139crate::callback::callback! {
140    /// Receives the log messages an MCP server emits.
141    ///
142    /// ```
143    /// use strands::mcp::{McpClientOptions, McpLogHandler};
144    ///
145    /// let handler = McpLogHandler::new(|message| println!("{:?} {}", message.level, message.data));
146    /// let options = McpClientOptions::builder().log_handler(handler).build();
147    /// assert!(options.log_handler.is_some());
148    /// ```
149    pub struct McpLogHandler(Fn(&McpLogMessage));
150}
151
152crate::callback::callback! {
153    /// Called when the server's tool list changes, with the previously registered tool names and
154    /// the refreshed tools.
155    pub struct ToolsChangedCallback(Fn(Vec<String>, Vec<McpTool>));
156}
157
158/// What an [`ElicitationCallback`] receives besides the request (`ElicitationContext`).
159#[derive(Debug, Clone)]
160#[non_exhaustive]
161pub struct ElicitationContext {
162    request_id: JsonValue,
163    cancel_signal: CancelSignal,
164}
165
166impl ElicitationContext {
167    pub(crate) fn new(request_id: JsonValue, cancel_signal: CancelSignal) -> Self {
168        Self {
169            request_id,
170            cancel_signal,
171        }
172    }
173
174    /// The JSON-RPC id of the server's request (`mcpReq.id`).
175    #[must_use]
176    pub fn request_id(&self) -> &JsonValue {
177        &self.request_id
178    }
179
180    /// Fires when the server cancels the request (`mcpReq.signal`).
181    #[must_use]
182    pub fn cancel_signal(&self) -> &CancelSignal {
183        &self.cancel_signal
184    }
185}
186
187/// Handles a server's request for user input during a tool call (`ElicitationCallback`).
188///
189/// Any async closure taking the context and the request implements it. A failure is returned to
190/// the server as a JSON-RPC error.
191///
192/// ```
193/// use strands::mcp::rmcp::model::{ElicitResult, ElicitationAction};
194/// use strands::mcp::{ElicitationCallback, McpClientOptions};
195/// use std::sync::Arc;
196///
197/// let callback: Arc<dyn ElicitationCallback> = Arc::new(|_context, _params| async {
198///     Ok(ElicitResult::new(ElicitationAction::Decline))
199/// });
200/// let options = McpClientOptions::builder().elicitation_callback(callback).build();
201/// assert!(options.elicitation_callback.is_some());
202/// ```
203#[async_trait]
204pub trait ElicitationCallback: Send + Sync + 'static {
205    /// Returns the user's answer: accept (with content), decline or cancel.
206    async fn elicit(&self, context: ElicitationContext, params: ElicitRequestParams) -> Result<ElicitResult, BoxError>;
207}
208
209#[async_trait]
210impl<F, Fut> ElicitationCallback for F
211where
212    F: Fn(ElicitationContext, ElicitRequestParams) -> Fut + Send + Sync + 'static,
213    Fut: Future<Output = Result<ElicitResult, BoxError>> + Send + 'static,
214{
215    async fn elicit(&self, context: ElicitationContext, params: ElicitRequestParams) -> Result<ElicitResult, BoxError> {
216        self(context, params).await
217    }
218}