Skip to main content

strands/mcp/
http.rs

1//! The streamable HTTP transport a URL-configured client builds, with OAuth client credentials
2//! ([`McpClientCredentials`]) or a token provider ([`McpAuthProvider`]).
3
4use std::collections::{BTreeMap, HashMap};
5use std::fmt;
6use std::sync::Arc;
7
8use async_trait::async_trait;
9use futures::future::BoxFuture;
10use futures::stream::BoxStream;
11use reqwest::Url;
12use reqwest::header::{HeaderName, HeaderValue};
13use rmcp::model::ClientJsonRpcMessage;
14use rmcp::transport::StreamableHttpClientTransport;
15use rmcp::transport::auth::{AuthClient, AuthError, ClientCredentialsConfig, OAuthState};
16use rmcp::transport::streamable_http_client::{
17    StreamableHttpClient, StreamableHttpClientTransportConfig, StreamableHttpError, StreamableHttpPostResponse,
18};
19use serde::Deserialize;
20use sse_stream::{Error as SseError, Sse};
21
22use super::error::McpError;
23use super::transport::{BoxedTransport, McpTransport};
24use crate::error::BoxError;
25use crate::types::JsonValue;
26
27/// OAuth client credentials for machine-to-machine authentication (`McpClientCredentials`).
28///
29/// The client discovers the authorization server from the MCP server's protected resource
30/// metadata and exchanges the credentials for a token on every connect, and again whenever the
31/// server rejects the token or it expires.
32///
33/// Discovery refuses metadata that points at private addresses unless the server URL itself
34/// names one of the same class (such as `localhost`); set
35/// [`allow_private_addresses`](Self::allow_private_addresses) for an authorization server on a
36/// private network. Link-local and other reserved addresses are always refused.
37#[derive(Clone, Default, PartialEq, Eq, Deserialize, bon::Builder)]
38#[serde(rename_all = "camelCase")]
39#[builder(on(String, into))]
40pub struct McpClientCredentials {
41    /// The OAuth client id.
42    pub client_id: String,
43    /// The OAuth client secret.
44    pub client_secret: String,
45    /// The scopes to request.
46    #[serde(default)]
47    pub scopes: Option<Vec<String>>,
48    /// Lets discovered metadata name hosts that resolve to private addresses
49    /// (`allowPrivateAddresses`). Defaults to `false`.
50    #[serde(default)]
51    #[builder(default)]
52    pub allow_private_addresses: bool,
53}
54
55impl fmt::Debug for McpClientCredentials {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.debug_struct("McpClientCredentials")
58            .field("client_id", &self.client_id)
59            .field("client_secret", &"<redacted>")
60            .field("scopes", &self.scopes)
61            .field("allow_private_addresses", &self.allow_private_addresses)
62            .finish()
63    }
64}
65
66/// Supplies the bearer token for each request of a URL-configured client (`authProvider`).
67///
68/// ```
69/// use strands::mcp::McpAuthProvider;
70///
71/// struct StaticToken(String);
72///
73/// #[strands::async_trait]
74/// impl McpAuthProvider for StaticToken {
75///     async fn token(&self) -> Result<Option<String>, strands::BoxError> {
76///         Ok(Some(self.0.clone()))
77///     }
78/// }
79/// ```
80#[async_trait]
81pub trait McpAuthProvider: Send + Sync + 'static {
82    /// The token to send as `Authorization: Bearer <token>`, or `None` to send none.
83    async fn token(&self) -> Result<Option<String>, BoxError>;
84}
85
86#[derive(Clone)]
87pub(crate) enum HttpAuth {
88    None,
89    Credentials(McpClientCredentials),
90    Provider(Arc<dyn McpAuthProvider>),
91}
92
93#[derive(Clone)]
94struct ProviderClient {
95    inner: reqwest::Client,
96    provider: Arc<dyn McpAuthProvider>,
97}
98
99type HttpResult<T> = Result<T, StreamableHttpError<reqwest::Error>>;
100
101impl ProviderClient {
102    async fn bearer(&self) -> HttpResult<Option<String>> {
103        self.provider
104            .token()
105            .await
106            .map_err(|error| StreamableHttpError::Auth(AuthError::InternalError(error.to_string())))
107    }
108}
109
110impl StreamableHttpClient for ProviderClient {
111    type Error = reqwest::Error;
112
113    async fn post_message(
114        &self,
115        uri: Arc<str>,
116        message: ClientJsonRpcMessage,
117        session_id: Option<Arc<str>>,
118        _auth_header: Option<String>,
119        custom_headers: HashMap<HeaderName, HeaderValue>,
120    ) -> HttpResult<StreamableHttpPostResponse> {
121        let token = self.bearer().await?;
122        self.inner
123            .post_message(uri, message, session_id, token, custom_headers)
124            .await
125    }
126
127    async fn post_message_with_max_sse_event_size(
128        &self,
129        uri: Arc<str>,
130        message: ClientJsonRpcMessage,
131        session_id: Option<Arc<str>>,
132        _auth_header: Option<String>,
133        custom_headers: HashMap<HeaderName, HeaderValue>,
134        max_sse_event_size: usize,
135    ) -> HttpResult<StreamableHttpPostResponse> {
136        let token = self.bearer().await?;
137        self.inner
138            .post_message_with_max_sse_event_size(uri, message, session_id, token, custom_headers, max_sse_event_size)
139            .await
140    }
141
142    async fn delete_session(
143        &self,
144        uri: Arc<str>,
145        session_id: Arc<str>,
146        _auth_header: Option<String>,
147        custom_headers: HashMap<HeaderName, HeaderValue>,
148    ) -> HttpResult<()> {
149        let token = self.bearer().await?;
150        self.inner.delete_session(uri, session_id, token, custom_headers).await
151    }
152
153    async fn get_stream(
154        &self,
155        uri: Arc<str>,
156        session_id: Option<Arc<str>>,
157        last_event_id: Option<String>,
158        _auth_header: Option<String>,
159        custom_headers: HashMap<HeaderName, HeaderValue>,
160    ) -> HttpResult<BoxStream<'static, Result<Sse, SseError>>> {
161        let token = self.bearer().await?;
162        self.inner
163            .get_stream(uri, session_id, last_event_id, token, custom_headers)
164            .await
165    }
166
167    async fn get_stream_with_max_sse_event_size(
168        &self,
169        uri: Arc<str>,
170        session_id: Option<Arc<str>>,
171        last_event_id: Option<String>,
172        _auth_header: Option<String>,
173        custom_headers: HashMap<HeaderName, HeaderValue>,
174        max_sse_event_size: usize,
175    ) -> HttpResult<BoxStream<'static, Result<Sse, SseError>>> {
176        let token = self.bearer().await?;
177        self.inner
178            .get_stream_with_max_sse_event_size(
179                uri,
180                session_id,
181                last_event_id,
182                token,
183                custom_headers,
184                max_sse_event_size,
185            )
186            .await
187    }
188}
189
190/// A client-credentials session that runs the grant again, and retries once, when the server
191/// rejects the request for authorization: rmcp's `AuthClient` cannot refresh a client-credentials
192/// token, so an expired token would otherwise fail every later request.
193#[derive(Clone)]
194struct CredentialsClient {
195    auth: AuthClient<reqwest::Client>,
196    config: Arc<ClientCredentialsConfig>,
197}
198
199fn needs_grant<E: std::error::Error + Send + Sync + 'static>(error: &StreamableHttpError<E>) -> bool {
200    matches!(
201        error,
202        StreamableHttpError::AuthRequired(_) | StreamableHttpError::Auth(AuthError::AuthorizationRequired)
203    )
204}
205
206impl CredentialsClient {
207    async fn grant(&self) -> HttpResult<String> {
208        tracing::debug!("requesting a new mcp access token");
209        let token = self
210            .auth
211            .auth_manager
212            .lock()
213            .await
214            .exchange_client_credentials(&self.config)
215            .await?;
216        serde_json::to_value(&token)?
217            .get("access_token")
218            .and_then(JsonValue::as_str)
219            .map(str::to_owned)
220            .ok_or_else(|| AuthError::InternalError("token response without access_token".to_owned()).into())
221    }
222
223    async fn with_grant<T, F, Fut>(&self, call: F) -> HttpResult<T>
224    where
225        F: Fn(Option<String>) -> Fut,
226        Fut: Future<Output = HttpResult<T>>,
227    {
228        match call(None).await {
229            Err(error) if needs_grant(&error) => {
230                let token = self.grant().await?;
231                call(Some(token)).await
232            }
233            result => result,
234        }
235    }
236}
237
238impl StreamableHttpClient for CredentialsClient {
239    type Error = reqwest::Error;
240
241    async fn post_message(
242        &self,
243        uri: Arc<str>,
244        message: ClientJsonRpcMessage,
245        session_id: Option<Arc<str>>,
246        _auth_header: Option<String>,
247        custom_headers: HashMap<HeaderName, HeaderValue>,
248    ) -> HttpResult<StreamableHttpPostResponse> {
249        self.with_grant(|token| {
250            self.auth.post_message(
251                uri.clone(),
252                message.clone(),
253                session_id.clone(),
254                token,
255                custom_headers.clone(),
256            )
257        })
258        .await
259    }
260
261    async fn post_message_with_max_sse_event_size(
262        &self,
263        uri: Arc<str>,
264        message: ClientJsonRpcMessage,
265        session_id: Option<Arc<str>>,
266        _auth_header: Option<String>,
267        custom_headers: HashMap<HeaderName, HeaderValue>,
268        max_sse_event_size: usize,
269    ) -> HttpResult<StreamableHttpPostResponse> {
270        self.with_grant(|token| {
271            self.auth.post_message_with_max_sse_event_size(
272                uri.clone(),
273                message.clone(),
274                session_id.clone(),
275                token,
276                custom_headers.clone(),
277                max_sse_event_size,
278            )
279        })
280        .await
281    }
282
283    async fn delete_session(
284        &self,
285        uri: Arc<str>,
286        session_id: Arc<str>,
287        _auth_header: Option<String>,
288        custom_headers: HashMap<HeaderName, HeaderValue>,
289    ) -> HttpResult<()> {
290        self.with_grant(|token| {
291            self.auth
292                .delete_session(uri.clone(), session_id.clone(), token, custom_headers.clone())
293        })
294        .await
295    }
296
297    async fn get_stream(
298        &self,
299        uri: Arc<str>,
300        session_id: Option<Arc<str>>,
301        last_event_id: Option<String>,
302        _auth_header: Option<String>,
303        custom_headers: HashMap<HeaderName, HeaderValue>,
304    ) -> HttpResult<BoxStream<'static, Result<Sse, SseError>>> {
305        self.with_grant(|token| {
306            self.auth.get_stream(
307                uri.clone(),
308                session_id.clone(),
309                last_event_id.clone(),
310                token,
311                custom_headers.clone(),
312            )
313        })
314        .await
315    }
316
317    async fn get_stream_with_max_sse_event_size(
318        &self,
319        uri: Arc<str>,
320        session_id: Option<Arc<str>>,
321        last_event_id: Option<String>,
322        _auth_header: Option<String>,
323        custom_headers: HashMap<HeaderName, HeaderValue>,
324        max_sse_event_size: usize,
325    ) -> HttpResult<BoxStream<'static, Result<Sse, SseError>>> {
326        self.with_grant(|token| {
327            self.auth.get_stream_with_max_sse_event_size(
328                uri.clone(),
329                session_id.clone(),
330                last_event_id.clone(),
331                token,
332                custom_headers.clone(),
333                max_sse_event_size,
334            )
335        })
336        .await
337    }
338}
339
340fn auth_error(error: &AuthError) -> McpError {
341    McpError::transport(format!("MCP authorization failed: {error}"))
342}
343
344async fn credentials_client(url: &Url, credentials: &McpClientCredentials) -> Result<CredentialsClient, McpError> {
345    let manager = if credentials.allow_private_addresses {
346        tracing::debug!(
347            "client_id=<{}> | allowing private addresses in mcp authorization metadata",
348            credentials.client_id
349        );
350        rmcp::transport::AuthorizationManager::new_allowing_private_addresses(url.as_str()).await
351    } else {
352        rmcp::transport::AuthorizationManager::new(url.as_str()).await
353    }
354    .map_err(|error| auth_error(&error))?;
355    let mut state = OAuthState::Unauthorized(manager);
356    let config = ClientCredentialsConfig::ClientSecret {
357        client_id: credentials.client_id.clone(),
358        client_secret: credentials.client_secret.clone(),
359        scopes: credentials.scopes.clone().unwrap_or_default(),
360        resource: Some(url.to_string()),
361    };
362    state
363        .authenticate_client_credentials(config.clone())
364        .await
365        .map_err(|error| auth_error(&error))?;
366    let manager = state
367        .into_authorization_manager()
368        .ok_or_else(|| McpError::transport("MCP authorization failed: no authorized session"))?;
369    Ok(CredentialsClient {
370        auth: AuthClient::new(reqwest::Client::new(), manager),
371        config: Arc::new(config),
372    })
373}
374
375fn header_map(headers: &BTreeMap<String, String>) -> Result<HashMap<HeaderName, HeaderValue>, McpError> {
376    headers
377        .iter()
378        .map(|(name, value)| {
379            let header = HeaderName::from_bytes(name.as_bytes())
380                .map_err(|error| McpError::other(format!("Invalid header name \"{name}\": {error}")))?;
381            let value = HeaderValue::from_str(value)
382                .map_err(|error| McpError::other(format!("Invalid header value for \"{name}\": {error}")))?;
383            Ok((header, value))
384        })
385        .collect()
386}
387
388async fn start(
389    url: Url,
390    headers: HashMap<HeaderName, HeaderValue>,
391    auth: HttpAuth,
392) -> Result<BoxedTransport, McpError> {
393    let config = StreamableHttpClientTransportConfig::with_uri(url.as_str()).custom_headers(headers);
394    let transport = match auth {
395        HttpAuth::None => BoxedTransport::new(StreamableHttpClientTransport::with_client(
396            reqwest::Client::new(),
397            config,
398        )),
399        HttpAuth::Provider(provider) => BoxedTransport::new(StreamableHttpClientTransport::with_client(
400            ProviderClient {
401                inner: reqwest::Client::new(),
402                provider,
403            },
404            config,
405        )),
406        HttpAuth::Credentials(credentials) => {
407            let client = credentials_client(&url, &credentials).await?;
408            BoxedTransport::new(StreamableHttpClientTransport::with_client(client, config))
409        }
410    };
411    Ok(transport)
412}
413
414/// The streamable HTTP transport for `url`, built afresh on every connect.
415pub(crate) fn streamable_http(
416    url: &str,
417    headers: &BTreeMap<String, String>,
418    auth: HttpAuth,
419) -> Result<McpTransport, McpError> {
420    let url = Url::parse(url).map_err(|error| McpError::other(format!("Invalid URL \"{url}\": {error}")))?;
421    let headers = header_map(headers)?;
422    let factory = Arc::new(move || -> BoxFuture<'static, Result<BoxedTransport, McpError>> {
423        Box::pin(start(url.clone(), headers.clone(), auth.clone()))
424    });
425    Ok(McpTransport::from_factory("streamable-http", factory))
426}