Skip to main content

strands/mcp/
transport.rs

1//! [`McpTransport`], how an [`McpClient`](super::McpClient) reaches its server, and the stdio
2//! transport.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use std::path::PathBuf;
7use std::process::Stdio;
8use std::sync::{Arc, Mutex, PoisonError};
9
10use futures::FutureExt;
11use futures::future::BoxFuture;
12use rmcp::RoleClient;
13use rmcp::model::{ClientJsonRpcMessage, ClientRequest, GetExtensions, RequestMetaObject};
14use rmcp::service::{RxJsonRpcMessage, TxJsonRpcMessage};
15use rmcp::transport::{IntoTransport, TokioChildProcess, Transport};
16
17use super::error::McpError;
18use crate::error::BoxError;
19
20/// Marks a `tools/call` request that must go out without a progress token, because no progress
21/// callback or timeout needs one.
22#[derive(Debug, Clone, Copy)]
23pub(crate) struct WithoutProgressToken;
24
25trait ErasedTransport: Send {
26    fn send(&mut self, item: TxJsonRpcMessage<RoleClient>) -> BoxFuture<'static, Result<(), BoxError>>;
27    fn receive(&mut self) -> BoxFuture<'_, Option<RxJsonRpcMessage<RoleClient>>>;
28    fn close(&mut self) -> BoxFuture<'_, Result<(), BoxError>>;
29}
30
31impl<T: Transport<RoleClient> + 'static> ErasedTransport for T {
32    fn send(&mut self, item: TxJsonRpcMessage<RoleClient>) -> BoxFuture<'static, Result<(), BoxError>> {
33        Transport::send(self, item)
34            .map(|result| result.map_err(|error| Box::new(error) as BoxError))
35            .boxed()
36    }
37
38    fn receive(&mut self) -> BoxFuture<'_, Option<RxJsonRpcMessage<RoleClient>>> {
39        Transport::receive(self).boxed()
40    }
41
42    fn close(&mut self) -> BoxFuture<'_, Result<(), BoxError>> {
43        Transport::close(self)
44            .map(|result| result.map_err(|error| Box::new(error) as BoxError))
45            .boxed()
46    }
47}
48
49/// A transport error, carrying the underlying transport's error.
50#[derive(Debug, thiserror::Error)]
51#[error("{0}")]
52pub(crate) struct TransportError(BoxError);
53
54/// A started transport of any type.
55pub(crate) struct BoxedTransport(Box<dyn ErasedTransport>);
56
57impl BoxedTransport {
58    pub(crate) fn new<T, E, A>(transport: T) -> Self
59    where
60        T: IntoTransport<RoleClient, E, A>,
61        E: std::error::Error + Send + Sync + 'static,
62    {
63        Self(Box::new(transport.into_transport()))
64    }
65}
66
67fn strip_progress_token(item: &mut TxJsonRpcMessage<RoleClient>) {
68    let ClientJsonRpcMessage::Request(request) = item else {
69        return;
70    };
71    let ClientRequest::CallToolRequest(call) = &mut request.request else {
72        return;
73    };
74    if call.extensions().get::<WithoutProgressToken>().is_none() {
75        return;
76    }
77    if let Some(meta) = call.extensions_mut().get_mut::<RequestMetaObject>() {
78        meta.remove("progressToken");
79    }
80    if let Some(meta) = &mut call.params.meta {
81        meta.remove("progressToken");
82    }
83}
84
85impl Transport<RoleClient> for BoxedTransport {
86    type Error = TransportError;
87
88    fn send(
89        &mut self,
90        mut item: TxJsonRpcMessage<RoleClient>,
91    ) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
92        strip_progress_token(&mut item);
93        self.0.send(item).map(|result| result.map_err(TransportError))
94    }
95
96    fn receive(&mut self) -> impl Future<Output = Option<RxJsonRpcMessage<RoleClient>>> + Send {
97        self.0.receive()
98    }
99
100    fn close(&mut self) -> impl Future<Output = Result<(), Self::Error>> + Send {
101        self.0.close().map(|result| result.map_err(TransportError))
102    }
103}
104
105type Factory = Arc<dyn Fn() -> BoxFuture<'static, Result<BoxedTransport, McpError>> + Send + Sync>;
106
107#[derive(Clone)]
108enum Source {
109    Factory(Factory),
110    Once(Arc<Mutex<Option<BoxedTransport>>>),
111}
112
113/// How an [`McpClient`](super::McpClient) reaches its server (`McpTransport`).
114///
115/// Built-in transports ([`stdio`](Self::stdio), [`sse`](Self::sse)) start afresh on every connect,
116/// so a client can reconnect. A transport passed to [`new`](Self::new) starts once; use
117/// [`from_fn`](Self::from_fn) to build a fresh one on every connect. A streamable HTTP client is
118/// configured with [`McpClientConfig::url`](super::McpClientConfig::url) instead.
119#[derive(Clone)]
120pub struct McpTransport {
121    source: Source,
122    kind: &'static str,
123}
124
125impl McpTransport {
126    /// Wraps any `rmcp` client transport, such as one end of an in-memory duplex stream. It can
127    /// start only once; a reconnect fails.
128    pub fn new<T, E, A>(transport: T) -> Self
129    where
130        T: IntoTransport<RoleClient, E, A>,
131        E: std::error::Error + Send + Sync + 'static,
132    {
133        Self {
134            source: Source::Once(Arc::new(Mutex::new(Some(BoxedTransport::new(transport))))),
135            kind: "custom",
136        }
137    }
138
139    /// Builds a fresh `rmcp` client transport on every connect.
140    pub fn from_fn<F, Fut, T, E, A>(factory: F) -> Self
141    where
142        F: Fn() -> Fut + Send + Sync + 'static,
143        Fut: Future<Output = Result<T, BoxError>> + Send + 'static,
144        T: IntoTransport<RoleClient, E, A>,
145        E: std::error::Error + Send + Sync + 'static,
146    {
147        let factory: Factory = Arc::new(move || {
148            factory()
149                .map(|result| result.map(BoxedTransport::new).map_err(McpError::transport))
150                .boxed()
151        });
152        Self {
153            source: Source::Factory(factory),
154            kind: "custom",
155        }
156    }
157
158    /// Spawns the server as a child process and talks to it over stdin and stdout.
159    #[must_use]
160    pub fn stdio(params: StdioServerParameters) -> Self {
161        let params = Arc::new(params);
162        let factory: Factory = Arc::new(move || {
163            let params = params.clone();
164            async move { spawn_stdio(&params).map_err(McpError::transport) }.boxed()
165        });
166        Self {
167            source: Source::Factory(factory),
168            kind: "stdio",
169        }
170    }
171
172    pub(crate) fn from_factory(kind: &'static str, factory: Factory) -> Self {
173        Self {
174            source: Source::Factory(factory),
175            kind,
176        }
177    }
178
179    /// Starts the transport for one connect attempt.
180    pub(crate) async fn start(&self) -> Result<BoxedTransport, McpError> {
181        match &self.source {
182            Source::Factory(factory) => factory().await,
183            Source::Once(slot) => slot
184                .lock()
185                .unwrap_or_else(PoisonError::into_inner)
186                .take()
187                .ok_or_else(|| {
188                    McpError::sdk(
189                        super::McpSdkErrorCode::SendFailed,
190                        "MCP transport already started and cannot start again; construct a new McpClient or use McpTransport::from_fn",
191                    )
192                }),
193        }
194    }
195}
196
197impl fmt::Debug for McpTransport {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        f.debug_tuple("McpTransport").field(&self.kind).finish()
200    }
201}
202
203/// How to spawn a stdio MCP server (`StdioServerParameters`).
204#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
205#[builder(on(String, into))]
206pub struct StdioServerParameters {
207    /// The executable to run.
208    pub command: String,
209    /// Its arguments.
210    #[builder(default)]
211    pub args: Vec<String>,
212    /// Variables set over the [`default_environment`].
213    pub env: Option<BTreeMap<String, String>>,
214    /// The working directory; the current one when absent.
215    #[builder(into)]
216    pub cwd: Option<PathBuf>,
217}
218
219impl StdioServerParameters {
220    /// Parameters that run `command` with `args`.
221    pub fn new(command: impl Into<String>, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
222        Self {
223            command: command.into(),
224            args: args.into_iter().map(Into::into).collect(),
225            env: None,
226            cwd: None,
227        }
228    }
229}
230
231#[cfg(windows)]
232const DEFAULT_INHERITED_ENV_VARS: &[&str] = &[
233    "APPDATA",
234    "COMSPEC",
235    "HOMEDRIVE",
236    "HOMEPATH",
237    "LOCALAPPDATA",
238    "PATH",
239    "PATHEXT",
240    "PROCESSOR_ARCHITECTURE",
241    "PROGRAMDATA",
242    "PROGRAMFILES",
243    "PROGRAMFILES(X86)",
244    "PROGRAMW6432",
245    "SYSTEMDRIVE",
246    "SYSTEMROOT",
247    "TEMP",
248    "USERNAME",
249    "USERPROFILE",
250    "WINDIR",
251];
252
253#[cfg(not(windows))]
254const DEFAULT_INHERITED_ENV_VARS: &[&str] = &["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"];
255
256/// The variables a stdio server inherits: only those deemed safe, and
257/// none whose value starts with `()` (an exported shell function).
258#[must_use]
259pub fn default_environment() -> BTreeMap<String, String> {
260    DEFAULT_INHERITED_ENV_VARS
261        .iter()
262        .filter_map(|key| {
263            let value = std::env::var(key).ok()?;
264            (!value.starts_with("()")).then(|| ((*key).to_owned(), value))
265        })
266        .collect()
267}
268
269fn spawn_stdio(params: &StdioServerParameters) -> std::io::Result<BoxedTransport> {
270    let mut command = tokio::process::Command::new(&params.command);
271    command.args(&params.args).env_clear().envs(default_environment());
272    if let Some(env) = &params.env {
273        command.envs(env);
274    }
275    if let Some(cwd) = &params.cwd {
276        command.current_dir(cwd);
277    }
278    let (transport, _) = TokioChildProcess::builder(command).stderr(Stdio::inherit()).spawn()?;
279    Ok(BoxedTransport::new(transport))
280}