Skip to main content

adk_tool/mcp/
http.rs

1// MCP HTTP Transport (Streamable HTTP)
2//
3// Provides HTTP-based transport for connecting to remote MCP servers.
4// Uses the streamable HTTP transport from rmcp when the http-transport feature is enabled.
5
6use super::auth::McpAuth;
7#[cfg(feature = "http-transport")]
8use super::auth::OAuth2Config;
9use super::elicitation::ElicitationHandler;
10use super::resource_notifications::ResourceNotificationHandler;
11#[cfg(feature = "http-transport")]
12use adk_core::Url;
13use adk_core::{ActingContext, AdkError, CredentialBroker, Result};
14use std::collections::HashMap;
15use std::sync::Arc;
16use std::time::Duration;
17
18#[cfg(feature = "http-transport")]
19use reqwest::header::{HeaderName, HeaderValue};
20#[cfg(feature = "http-transport")]
21use rmcp::{
22    model::ClientJsonRpcMessage,
23    transport::{
24        common::client_side_sse::BoxedSseResponse,
25        streamable_http_client::{
26            StreamableHttpClient, StreamableHttpError, StreamableHttpPostResponse,
27        },
28    },
29};
30
31#[cfg(feature = "http-transport")]
32type HttpResult<T> = std::result::Result<T, StreamableHttpError<reqwest::Error>>;
33
34/// Brokered credentials for an MCP HTTP connection: the broker, the acting context
35/// tokens are minted for, the requested scopes, and the endpoint as the resource.
36// Without `http-transport` the builder only stores the configuration.
37#[cfg_attr(not(feature = "http-transport"), allow(dead_code))]
38#[derive(Clone)]
39struct BrokeredAuth {
40    broker: Arc<dyn CredentialBroker>,
41    acting: ActingContext,
42    scopes: Vec<String>,
43}
44
45#[cfg(feature = "http-transport")]
46impl BrokeredAuth {
47    /// Mints a token for `resource` and returns its secret for a request to `request`.
48    ///
49    /// The token's audience is checked against the request URL, so a token minted for
50    /// one resource is never attached to a request for another.
51    async fn bearer_for(&self, resource: &Url, request: &Url) -> Result<String> {
52        let token = self.broker.token_for(&self.acting, resource, &self.scopes).await?;
53        Ok(token.authorize_for(request)?.expose().to_string())
54    }
55}
56
57/// The streamable HTTP client behind [`McpHttpClientBuilder`].
58///
59/// With OAuth2 it attaches the current access token to each request rather
60/// than the token fetched at connect time, so a long-lived connection keeps
61/// working after that first token expires.
62#[cfg(feature = "http-transport")]
63#[derive(Clone)]
64struct McpHttpClient {
65    inner: reqwest::Client,
66    oauth: Option<Arc<OAuth2Config>>,
67    brokered: Option<(Arc<BrokeredAuth>, Url)>,
68}
69
70#[cfg(feature = "http-transport")]
71impl McpHttpClient {
72    /// Sends one request with the current OAuth2 token and, when the server
73    /// answers 401, once more with a newly fetched token. Without OAuth2 the
74    /// transport's configured `Authorization` value is sent unchanged.
75    async fn authorized<T, F, Fut>(
76        &self,
77        uri: Arc<str>,
78        configured: Option<String>,
79        send: F,
80    ) -> HttpResult<T>
81    where
82        F: Fn(Option<String>) -> Fut,
83        Fut: Future<Output = HttpResult<T>>,
84    {
85        if let Some((brokered, resource)) = &self.brokered {
86            let request = Url::parse(&uri).map_err(|error| {
87                StreamableHttpError::UnexpectedServerResponse(
88                    format!("invalid MCP request URL '{uri}': {error}").into(),
89                )
90            })?;
91            let token = brokered.bearer_for(resource, &request).await.map_err(|error| {
92                StreamableHttpError::UnexpectedServerResponse(
93                    format!("brokered credential is unavailable: {error}").into(),
94                )
95            })?;
96            return send(Some(token)).await;
97        }
98        let Some(oauth) = &self.oauth else {
99            return send(configured).await;
100        };
101        let token = oauth_token(oauth).await?;
102        // A 401 is answered before the request runs, so resending it cannot
103        // repeat an effect. rmcp reports one with a `WWW-Authenticate` challenge
104        // as `AuthRequired`, one without it on a POST as an unexpected
105        // response, and one without it on a GET or DELETE as a client error.
106        match send(Some(token.clone())).await {
107            Err(StreamableHttpError::AuthRequired(_)) => {}
108            Err(StreamableHttpError::UnexpectedServerResponse(message))
109                if message.starts_with("HTTP 401 ") => {}
110            Err(StreamableHttpError::Client(error))
111                if error.status() == Some(reqwest::StatusCode::UNAUTHORIZED) => {}
112            result => return result,
113        }
114        tracing::debug!("MCP server rejected the OAuth2 access token; fetching a new one");
115        oauth.discard_token(&token).await;
116        send(Some(oauth_token(oauth).await?)).await
117    }
118}
119
120#[cfg(feature = "http-transport")]
121async fn oauth_token(oauth: &OAuth2Config) -> HttpResult<String> {
122    oauth.get_or_refresh_token().await.map_err(|error| {
123        StreamableHttpError::UnexpectedServerResponse(
124            format!("OAuth2 access token is unavailable: {error}").into(),
125        )
126    })
127}
128
129#[cfg(feature = "http-transport")]
130impl StreamableHttpClient for McpHttpClient {
131    type Error = reqwest::Error;
132
133    fn post_message(
134        &self,
135        uri: Arc<str>,
136        message: ClientJsonRpcMessage,
137        session_id: Option<Arc<str>>,
138        auth_header: Option<String>,
139        custom_headers: HashMap<HeaderName, HeaderValue>,
140    ) -> impl Future<Output = HttpResult<StreamableHttpPostResponse>> + Send + '_ {
141        self.authorized(uri.clone(), auth_header, move |token| {
142            self.inner.post_message(
143                uri.clone(),
144                message.clone(),
145                session_id.clone(),
146                token,
147                custom_headers.clone(),
148            )
149        })
150    }
151
152    fn post_message_with_max_sse_event_size(
153        &self,
154        uri: Arc<str>,
155        message: ClientJsonRpcMessage,
156        session_id: Option<Arc<str>>,
157        auth_header: Option<String>,
158        custom_headers: HashMap<HeaderName, HeaderValue>,
159        max_sse_event_size: usize,
160    ) -> impl Future<Output = HttpResult<StreamableHttpPostResponse>> + Send + '_ {
161        self.authorized(uri.clone(), auth_header, move |token| {
162            self.inner.post_message_with_max_sse_event_size(
163                uri.clone(),
164                message.clone(),
165                session_id.clone(),
166                token,
167                custom_headers.clone(),
168                max_sse_event_size,
169            )
170        })
171    }
172
173    fn delete_session(
174        &self,
175        uri: Arc<str>,
176        session_id: Arc<str>,
177        auth_header: Option<String>,
178        custom_headers: HashMap<HeaderName, HeaderValue>,
179    ) -> impl Future<Output = HttpResult<()>> + Send + '_ {
180        self.authorized(uri.clone(), auth_header, move |token| {
181            self.inner.delete_session(
182                uri.clone(),
183                session_id.clone(),
184                token,
185                custom_headers.clone(),
186            )
187        })
188    }
189
190    fn get_stream(
191        &self,
192        uri: Arc<str>,
193        session_id: Option<Arc<str>>,
194        last_event_id: Option<String>,
195        auth_header: Option<String>,
196        custom_headers: HashMap<HeaderName, HeaderValue>,
197    ) -> impl Future<Output = HttpResult<BoxedSseResponse>> + Send + '_ {
198        self.authorized(uri.clone(), auth_header, move |token| {
199            self.inner.get_stream(
200                uri.clone(),
201                session_id.clone(),
202                last_event_id.clone(),
203                token,
204                custom_headers.clone(),
205            )
206        })
207    }
208
209    fn get_stream_with_max_sse_event_size(
210        &self,
211        uri: Arc<str>,
212        session_id: Option<Arc<str>>,
213        last_event_id: Option<String>,
214        auth_header: Option<String>,
215        custom_headers: HashMap<HeaderName, HeaderValue>,
216        max_sse_event_size: usize,
217    ) -> impl Future<Output = HttpResult<BoxedSseResponse>> + Send + '_ {
218        self.authorized(uri.clone(), auth_header, move |token| {
219            self.inner.get_stream_with_max_sse_event_size(
220                uri.clone(),
221                session_id.clone(),
222                last_event_id.clone(),
223                token,
224                custom_headers.clone(),
225                max_sse_event_size,
226            )
227        })
228    }
229}
230
231#[cfg(feature = "http-transport")]
232#[derive(Clone)]
233struct HttpConnectionFactory {
234    builder: McpHttpClientBuilder,
235}
236
237#[cfg(feature = "http-transport")]
238#[derive(Clone)]
239struct HttpElicitationConnectionFactory {
240    builder: McpHttpClientBuilder,
241    handler: Arc<dyn ElicitationHandler>,
242    resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
243}
244
245#[cfg(feature = "http-transport")]
246impl HttpElicitationConnectionFactory {
247    /// Opens one connection. A transport error keeps its code, such as
248    /// `mcp.oauth.token_fetch` when the OAuth token cannot be fetched.
249    async fn connect_once(
250        &self,
251    ) -> Result<rmcp::service::RunningService<rmcp::RoleClient, super::elicitation::AdkClientHandler>>
252    {
253        use rmcp::ServiceExt;
254
255        let transport = self.builder.build_transport().await?;
256        let mut handler = super::elicitation::AdkClientHandler::new(self.handler.clone());
257        if let Some(resource_handler) = &self.resource_notification_handler {
258            handler = handler.with_resource_notification_handler(Arc::clone(resource_handler));
259        }
260        if self.builder.tasks.as_ref().is_some_and(|config| config.enable_tasks) {
261            handler = handler.with_tasks();
262        }
263        handler
264            .serve(transport)
265            .await
266            .map_err(|error| AdkError::tool(format!("failed to connect to MCP server: {error}")))
267    }
268}
269
270#[cfg(feature = "http-transport")]
271#[async_trait::async_trait]
272impl super::ConnectionFactory<super::elicitation::AdkClientHandler>
273    for HttpElicitationConnectionFactory
274{
275    async fn create_connection(
276        &self,
277    ) -> std::result::Result<
278        rmcp::service::RunningService<rmcp::RoleClient, super::elicitation::AdkClientHandler>,
279        String,
280    > {
281        self.connect_once().await.map_err(|error| error.to_string())
282    }
283}
284
285#[cfg(feature = "http-transport")]
286impl HttpConnectionFactory {
287    /// Opens one connection. A transport error keeps its code, such as
288    /// `mcp.oauth.token_fetch` when the OAuth token cannot be fetched.
289    async fn connect_once(&self) -> Result<rmcp::service::RunningService<rmcp::RoleClient, ()>> {
290        use rmcp::ServiceExt;
291
292        let transport = self.builder.build_transport().await?;
293        ().serve(transport)
294            .await
295            .map_err(|error| AdkError::tool(format!("failed to connect to MCP server: {error}")))
296    }
297}
298
299#[cfg(feature = "http-transport")]
300#[async_trait::async_trait]
301impl super::ConnectionFactory<()> for HttpConnectionFactory {
302    async fn create_connection(
303        &self,
304    ) -> std::result::Result<rmcp::service::RunningService<rmcp::RoleClient, ()>, String> {
305        self.connect_once().await.map_err(|error| error.to_string())
306    }
307}
308
309/// Builder for HTTP-based MCP connections.
310///
311/// This builder creates connections to remote MCP servers using the
312/// current MCP Streamable HTTP transport.
313///
314/// # Example
315///
316/// ```rust,ignore
317/// use adk_tool::mcp::{McpHttpClientBuilder, McpAuth, OAuth2Config};
318///
319/// // Simple connection
320/// let toolset = McpHttpClientBuilder::new("https://mcp.example.com/v1")
321///     .connect()
322///     .await?;
323///
324/// // With OAuth2 authentication
325/// let toolset = McpHttpClientBuilder::new("https://mcp.example.com/v1")
326///     .with_auth(McpAuth::oauth2(
327///         OAuth2Config::new("client-id", "https://auth.example.com/token")
328///             .with_secret("client-secret")
329///             .with_scopes(vec!["mcp:read".into()])
330///     ))
331///     .timeout(Duration::from_secs(60))
332///     .connect()
333///     .await?;
334/// ```
335#[derive(Clone)]
336pub struct McpHttpClientBuilder {
337    /// MCP server endpoint URL
338    endpoint: String,
339    /// Authentication configuration
340    auth: McpAuth,
341    /// Request timeout
342    timeout: Duration,
343    /// Custom headers
344    headers: HashMap<String, String>,
345    /// Optional elicitation handler
346    elicitation_handler: Option<Arc<dyn ElicitationHandler>>,
347    /// Optional resource notification handler.
348    resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
349    /// Recreate the MCP session once when a remote HTTP session expires.
350    reinit_on_expired_session: bool,
351    /// Brokered credentials; when set they replace `auth`.
352    brokered: Option<Arc<BrokeredAuth>>,
353    /// Task support declared and used by `connect_with_elicitation`.
354    tasks: Option<super::McpTaskConfig>,
355}
356
357impl McpHttpClientBuilder {
358    /// Create a new HTTP client builder for the given endpoint.
359    ///
360    /// # Arguments
361    ///
362    /// * `endpoint` - The MCP server URL (e.g., `https://mcp.example.com/v1`)
363    pub fn new(endpoint: impl Into<String>) -> Self {
364        Self {
365            endpoint: endpoint.into(),
366            auth: McpAuth::None,
367            timeout: Duration::from_secs(30),
368            headers: HashMap::new(),
369            elicitation_handler: None,
370            resource_notification_handler: None,
371            reinit_on_expired_session: true,
372            brokered: None,
373            tasks: None,
374        }
375    }
376
377    /// Authenticates with tokens minted by `broker` for `acting`, with `scopes`.
378    ///
379    /// The endpoint is the resource (RFC 8707): every request asks the broker for a
380    /// token for the endpoint and attaches it only after
381    /// [`ScopedToken::authorize_for`](adk_core::ScopedToken::authorize_for) accepts the
382    /// request URL, so a token minted for another resource is never sent. The
383    /// connection outlives any one run, so tokens are minted for the acting context
384    /// given here rather than for each calling run. Replaces [`with_auth`](Self::with_auth).
385    ///
386    /// # Example
387    ///
388    /// ```rust,ignore
389    /// use adk_core::{ActingContext, AgentId, AgentPrincipal};
390    /// use adk_tool::mcp::McpHttpClientBuilder;
391    ///
392    /// let acting =
393    ///     ActingContext::new(AgentPrincipal::new(AgentId::new("spiffe://example.org/agent/billing")?));
394    /// let toolset = McpHttpClientBuilder::new("https://mcp.example.com/v1")
395    ///     .with_credential_broker(broker, acting, vec!["tools.read".into()])
396    ///     .connect()
397    ///     .await?;
398    /// ```
399    pub fn with_credential_broker(
400        mut self,
401        broker: Arc<dyn CredentialBroker>,
402        acting: ActingContext,
403        scopes: Vec<String>,
404    ) -> Self {
405        self.brokered = Some(Arc::new(BrokeredAuth { broker, acting, scopes }));
406        self
407    }
408
409    /// Mints a brokered token for the endpoint and checks it may be sent there, so a
410    /// misconfigured broker fails the connection with its own error code.
411    #[cfg(feature = "http-transport")]
412    async fn check_brokered(&self) -> Result<Option<(Arc<BrokeredAuth>, Url)>> {
413        let Some(brokered) = &self.brokered else {
414            return Ok(None);
415        };
416        let resource = adk_core::resource_indicator(&self.endpoint)?;
417        brokered.bearer_for(&resource, &resource).await?;
418        Ok(Some((Arc::clone(brokered), resource)))
419    }
420
421    /// Set authentication for the connection.
422    ///
423    /// # Example
424    ///
425    /// ```rust,ignore
426    /// let builder = McpHttpClientBuilder::new("https://mcp.example.com")
427    ///     .with_auth(McpAuth::bearer("my-token"));
428    /// ```
429    pub fn with_auth(mut self, auth: McpAuth) -> Self {
430        self.auth = auth;
431        self
432    }
433
434    /// Set the request timeout.
435    ///
436    /// Default is 30 seconds.
437    pub fn timeout(mut self, timeout: Duration) -> Self {
438        self.timeout = timeout;
439        self
440    }
441
442    /// Add a custom header to all requests.
443    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
444        self.headers.insert(key.into(), value.into());
445        self
446    }
447
448    /// Configure bounded automatic recovery when the server reports an expired session.
449    ///
450    /// Enabled by default. rmcp performs at most one re-initialization attempt.
451    pub fn reinit_on_expired_session(mut self, enabled: bool) -> Self {
452        self.reinit_on_expired_session = enabled;
453        self
454    }
455
456    #[cfg(feature = "http-transport")]
457    async fn build_transport(
458        &self,
459    ) -> Result<rmcp::transport::streamable_http_client::StreamableHttpClientTransport<McpHttpClient>>
460    {
461        use adk_core::{ErrorCategory, ErrorComponent};
462        use rmcp::transport::streamable_http_client::{
463            StreamableHttpClientTransport, StreamableHttpClientTransportConfig,
464        };
465
466        let mut custom_headers = HashMap::new();
467        for (name, value) in &self.headers {
468            let name = HeaderName::from_bytes(name.as_bytes()).map_err(|error| {
469                AdkError::tool(format!("invalid MCP HTTP header '{name}': {error}"))
470            })?;
471            let value = HeaderValue::from_str(value).map_err(|error| {
472                AdkError::tool(format!("invalid value for MCP HTTP header '{name}': {error}"))
473            })?;
474            custom_headers.insert(name, value);
475        }
476
477        let brokered = self.check_brokered().await?;
478        let mut oauth = None;
479        let token = match &self.auth {
480            _ if brokered.is_some() => None,
481            McpAuth::Bearer(token) => Some(token.clone()),
482            McpAuth::OAuth2(config) => {
483                // Fetched now so bad credentials fail the connection rather than
484                // its first request. McpHttpClient attaches it, and its successors.
485                config.get_or_refresh_token().await.map_err(|error| {
486                    AdkError::new(
487                        ErrorComponent::Tool,
488                        ErrorCategory::Unauthorized,
489                        "mcp.oauth.token_fetch",
490                        format!("OAuth2 client-credentials authentication failed: {error}"),
491                    )
492                })?;
493                oauth = Some(Arc::clone(config));
494                None
495            }
496            McpAuth::ApiKey { header, key } => {
497                let name = HeaderName::from_bytes(header.as_bytes()).map_err(|error| {
498                    AdkError::tool(format!("invalid MCP API-key header '{header}': {error}"))
499                })?;
500                let value = HeaderValue::from_str(key).map_err(|error| {
501                    AdkError::tool(format!("invalid MCP API-key value for '{header}': {error}"))
502                })?;
503                custom_headers.insert(name, value);
504                None
505            }
506            McpAuth::None => None,
507        };
508
509        let mut config = StreamableHttpClientTransportConfig::with_uri(self.endpoint.as_str())
510            .custom_headers(custom_headers)
511            .reinit_on_expired_session(self.reinit_on_expired_session);
512        if let Some(token) = token {
513            config = config.auth_header(token);
514        }
515
516        let inner = reqwest::Client::builder()
517            .timeout(self.timeout)
518            .build()
519            .map_err(|error| AdkError::tool(format!("failed to build MCP HTTP client: {error}")))?;
520        Ok(StreamableHttpClientTransport::with_client(
521            McpHttpClient { inner, oauth, brokered },
522            config,
523        ))
524    }
525
526    /// Configure an elicitation handler for the HTTP connection.
527    ///
528    /// When set, use [`connect_with_elicitation`](Self::connect_with_elicitation)
529    /// to create a toolset that advertises elicitation capabilities.
530    pub fn with_elicitation_handler(mut self, handler: Arc<dyn ElicitationHandler>) -> Self {
531        self.elicitation_handler = Some(handler);
532        self
533    }
534
535    /// Declares the tasks extension (SEP-2663) and follows the tasks the server answers calls
536    /// with under `config`.
537    ///
538    /// A task may ask for input, so this applies to
539    /// [`connect_with_elicitation`](Self::connect_with_elicitation), whose handler answers it;
540    /// [`connect`](Self::connect) refuses a builder with task support.
541    ///
542    /// # Example
543    ///
544    /// ```rust
545    /// use std::sync::Arc;
546    ///
547    /// use adk_tool::mcp::{AutoDeclineElicitationHandler, McpHttpClientBuilder, McpTaskConfig};
548    ///
549    /// let builder = McpHttpClientBuilder::new("https://agents.example.com/mcp")
550    ///     .with_elicitation_handler(Arc::new(AutoDeclineElicitationHandler))
551    ///     .with_task_support(McpTaskConfig::enabled());
552    /// # let _ = builder;
553    /// ```
554    pub fn with_task_support(mut self, config: super::McpTaskConfig) -> Self {
555        self.tasks = Some(config);
556        self
557    }
558
559    /// Configure a handler for resource and resource-list update notifications.
560    ///
561    /// Use this with [`connect_with_elicitation`](Self::connect_with_elicitation);
562    /// the handler is retained when an expired HTTP session is recreated.
563    pub fn with_resource_notification_handler(
564        mut self,
565        handler: Arc<dyn ResourceNotificationHandler>,
566    ) -> Self {
567        self.resource_notification_handler = Some(handler);
568        self
569    }
570
571    /// Get the endpoint URL.
572    pub fn endpoint(&self) -> &str {
573        &self.endpoint
574    }
575
576    /// Get the configured timeout.
577    pub fn get_timeout(&self) -> Duration {
578        self.timeout
579    }
580
581    /// Get the authentication configuration.
582    pub fn get_auth(&self) -> &McpAuth {
583        &self.auth
584    }
585
586    /// Connect to the MCP server and create a toolset.
587    ///
588    /// This method establishes a connection to the remote MCP server
589    /// using the streamable HTTP transport.
590    ///
591    /// # Errors
592    ///
593    /// Returns an error if:
594    /// - The `http-transport` feature is not enabled
595    /// - Connection to the server fails
596    /// - Authentication fails
597    #[cfg(feature = "http-transport")]
598    pub async fn connect(self) -> Result<super::McpToolset<()>> {
599        if self.tasks.is_some() {
600            return Err(AdkError::tool(
601                "a toolset with task support answers its tasks' input requests; set a handler \
602                 with `with_elicitation_handler` and connect with `connect_with_elicitation`",
603            ));
604        }
605        self.check_brokered().await?;
606        let factory = Arc::new(HttpConnectionFactory { builder: self.clone() });
607        let client = factory.connect_once().await?;
608
609        Ok(super::McpToolset::new(client).with_connection_factory(factory))
610    }
611
612    /// Connect to the MCP server (stub when http-transport feature is disabled).
613    #[cfg(not(feature = "http-transport"))]
614    pub async fn connect(self) -> Result<()> {
615        Err(AdkError::tool(
616            "HTTP transport requires the 'http-transport' feature. \
617             Add `adk-tool = { features = [\"http-transport\"] }` to your Cargo.toml",
618        ))
619    }
620
621    /// Connect with elicitation support.
622    ///
623    /// Requires [`with_elicitation_handler`](Self::with_elicitation_handler) to have been called.
624    /// Returns a `McpToolset<AdkClientHandler>` that advertises elicitation capabilities.
625    ///
626    /// # Errors
627    ///
628    /// Returns an error if no elicitation handler was configured or if the connection fails.
629    ///
630    /// # Example
631    ///
632    /// ```rust,ignore
633    /// use adk_tool::{McpHttpClientBuilder, AutoDeclineElicitationHandler};
634    /// use std::sync::Arc;
635    ///
636    /// let toolset = McpHttpClientBuilder::new("https://mcp.example.com/v1")
637    ///     .with_elicitation_handler(Arc::new(AutoDeclineElicitationHandler))
638    ///     .connect_with_elicitation()
639    ///     .await?;
640    /// ```
641    #[cfg(feature = "http-transport")]
642    pub async fn connect_with_elicitation(
643        self,
644    ) -> Result<super::McpToolset<super::elicitation::AdkClientHandler>> {
645        let handler = self.elicitation_handler.clone().ok_or_else(|| {
646            AdkError::tool(
647                "connect_with_elicitation requires with_elicitation_handler to be called first",
648            )
649        })?;
650
651        self.check_brokered().await?;
652        let resource_notification_handler = self.resource_notification_handler.clone();
653        let tasks = self.tasks.clone();
654        let factory = Arc::new(HttpElicitationConnectionFactory {
655            builder: self,
656            handler,
657            resource_notification_handler,
658        });
659        let client = factory.connect_once().await?;
660
661        let toolset = super::McpToolset::new(client).with_connection_factory(factory);
662        Ok(match tasks {
663            Some(config) => toolset.with_task_support(config),
664            None => toolset,
665        })
666    }
667
668    /// Connect with elicitation support (stub when http-transport feature is disabled).
669    #[cfg(not(feature = "http-transport"))]
670    pub async fn connect_with_elicitation(self) -> Result<()> {
671        Err(AdkError::tool(
672            "HTTP transport requires the 'http-transport' feature. \
673             Add `adk-tool = { features = [\"http-transport\"] }` to your Cargo.toml",
674        ))
675    }
676}
677
678impl std::fmt::Debug for McpHttpClientBuilder {
679    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
680        f.debug_struct("McpHttpClientBuilder")
681            .field("endpoint", &self.endpoint)
682            .field("auth", &self.auth)
683            .field("timeout", &self.timeout)
684            .field("credential_broker", &self.brokered.as_ref().map(|b| &b.broker))
685            .field("headers", &self.headers.keys().collect::<Vec<_>>())
686            .finish()
687    }
688}
689
690#[cfg(test)]
691mod tests {
692    use super::*;
693
694    #[test]
695    fn test_builder_new() {
696        let builder = McpHttpClientBuilder::new("https://mcp.example.com");
697        assert_eq!(builder.endpoint(), "https://mcp.example.com");
698        assert_eq!(builder.get_timeout(), Duration::from_secs(30));
699    }
700
701    #[test]
702    fn test_builder_with_auth() {
703        let builder = McpHttpClientBuilder::new("https://mcp.example.com")
704            .with_auth(McpAuth::bearer("test-token"));
705        assert!(builder.get_auth().is_configured());
706    }
707
708    #[test]
709    fn test_builder_timeout() {
710        let builder =
711            McpHttpClientBuilder::new("https://mcp.example.com").timeout(Duration::from_secs(60));
712        assert_eq!(builder.get_timeout(), Duration::from_secs(60));
713    }
714
715    #[test]
716    fn test_builder_headers() {
717        let builder =
718            McpHttpClientBuilder::new("https://mcp.example.com").header("X-Custom", "value");
719        assert!(builder.headers.contains_key("X-Custom"));
720    }
721}