adk-tool 3.0.0

Tool system for Rust Agent Development Kit (ADK-Rust) agents (FunctionTool, MCP, Google Search)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
// MCP HTTP Transport (Streamable HTTP)
//
// Provides HTTP-based transport for connecting to remote MCP servers.
// Uses the streamable HTTP transport from rmcp when the http-transport feature is enabled.

use super::auth::McpAuth;
#[cfg(feature = "http-transport")]
use super::auth::OAuth2Config;
use super::elicitation::ElicitationHandler;
use super::resource_notifications::ResourceNotificationHandler;
#[cfg(feature = "http-transport")]
use adk_core::Url;
use adk_core::{ActingContext, AdkError, CredentialBroker, Result};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

#[cfg(feature = "http-transport")]
use reqwest::header::{HeaderName, HeaderValue};
#[cfg(feature = "http-transport")]
use rmcp::{
    model::ClientJsonRpcMessage,
    transport::{
        common::client_side_sse::BoxedSseResponse,
        streamable_http_client::{
            StreamableHttpClient, StreamableHttpError, StreamableHttpPostResponse,
        },
    },
};

#[cfg(feature = "http-transport")]
type HttpResult<T> = std::result::Result<T, StreamableHttpError<reqwest::Error>>;

/// Brokered credentials for an MCP HTTP connection: the broker, the acting context
/// tokens are minted for, the requested scopes, and the endpoint as the resource.
// Without `http-transport` the builder only stores the configuration.
#[cfg_attr(not(feature = "http-transport"), allow(dead_code))]
#[derive(Clone)]
struct BrokeredAuth {
    broker: Arc<dyn CredentialBroker>,
    acting: ActingContext,
    scopes: Vec<String>,
}

#[cfg(feature = "http-transport")]
impl BrokeredAuth {
    /// Mints a token for `resource` and returns its secret for a request to `request`.
    ///
    /// The token's audience is checked against the request URL, so a token minted for
    /// one resource is never attached to a request for another.
    async fn bearer_for(&self, resource: &Url, request: &Url) -> Result<String> {
        let token = self.broker.token_for(&self.acting, resource, &self.scopes).await?;
        Ok(token.authorize_for(request)?.expose().to_string())
    }
}

/// The streamable HTTP client behind [`McpHttpClientBuilder`].
///
/// With OAuth2 it attaches the current access token to each request rather
/// than the token fetched at connect time, so a long-lived connection keeps
/// working after that first token expires.
#[cfg(feature = "http-transport")]
#[derive(Clone)]
struct McpHttpClient {
    inner: reqwest::Client,
    oauth: Option<Arc<OAuth2Config>>,
    brokered: Option<(Arc<BrokeredAuth>, Url)>,
}

#[cfg(feature = "http-transport")]
impl McpHttpClient {
    /// Sends one request with the current OAuth2 token and, when the server
    /// answers 401, once more with a newly fetched token. Without OAuth2 the
    /// transport's configured `Authorization` value is sent unchanged.
    async fn authorized<T, F, Fut>(
        &self,
        uri: Arc<str>,
        configured: Option<String>,
        send: F,
    ) -> HttpResult<T>
    where
        F: Fn(Option<String>) -> Fut,
        Fut: Future<Output = HttpResult<T>>,
    {
        if let Some((brokered, resource)) = &self.brokered {
            let request = Url::parse(&uri).map_err(|error| {
                StreamableHttpError::UnexpectedServerResponse(
                    format!("invalid MCP request URL '{uri}': {error}").into(),
                )
            })?;
            let token = brokered.bearer_for(resource, &request).await.map_err(|error| {
                StreamableHttpError::UnexpectedServerResponse(
                    format!("brokered credential is unavailable: {error}").into(),
                )
            })?;
            return send(Some(token)).await;
        }
        let Some(oauth) = &self.oauth else {
            return send(configured).await;
        };
        let token = oauth_token(oauth).await?;
        // A 401 is answered before the request runs, so resending it cannot
        // repeat an effect. rmcp reports one with a `WWW-Authenticate` challenge
        // as `AuthRequired`, one without it on a POST as an unexpected
        // response, and one without it on a GET or DELETE as a client error.
        match send(Some(token.clone())).await {
            Err(StreamableHttpError::AuthRequired(_)) => {}
            Err(StreamableHttpError::UnexpectedServerResponse(message))
                if message.starts_with("HTTP 401 ") => {}
            Err(StreamableHttpError::Client(error))
                if error.status() == Some(reqwest::StatusCode::UNAUTHORIZED) => {}
            result => return result,
        }
        tracing::debug!("MCP server rejected the OAuth2 access token; fetching a new one");
        oauth.discard_token(&token).await;
        send(Some(oauth_token(oauth).await?)).await
    }
}

#[cfg(feature = "http-transport")]
async fn oauth_token(oauth: &OAuth2Config) -> HttpResult<String> {
    oauth.get_or_refresh_token().await.map_err(|error| {
        StreamableHttpError::UnexpectedServerResponse(
            format!("OAuth2 access token is unavailable: {error}").into(),
        )
    })
}

#[cfg(feature = "http-transport")]
impl StreamableHttpClient for McpHttpClient {
    type Error = reqwest::Error;

    fn post_message(
        &self,
        uri: Arc<str>,
        message: ClientJsonRpcMessage,
        session_id: Option<Arc<str>>,
        auth_header: Option<String>,
        custom_headers: HashMap<HeaderName, HeaderValue>,
    ) -> impl Future<Output = HttpResult<StreamableHttpPostResponse>> + Send + '_ {
        self.authorized(uri.clone(), auth_header, move |token| {
            self.inner.post_message(
                uri.clone(),
                message.clone(),
                session_id.clone(),
                token,
                custom_headers.clone(),
            )
        })
    }

    fn post_message_with_max_sse_event_size(
        &self,
        uri: Arc<str>,
        message: ClientJsonRpcMessage,
        session_id: Option<Arc<str>>,
        auth_header: Option<String>,
        custom_headers: HashMap<HeaderName, HeaderValue>,
        max_sse_event_size: usize,
    ) -> impl Future<Output = HttpResult<StreamableHttpPostResponse>> + Send + '_ {
        self.authorized(uri.clone(), auth_header, move |token| {
            self.inner.post_message_with_max_sse_event_size(
                uri.clone(),
                message.clone(),
                session_id.clone(),
                token,
                custom_headers.clone(),
                max_sse_event_size,
            )
        })
    }

    fn delete_session(
        &self,
        uri: Arc<str>,
        session_id: Arc<str>,
        auth_header: Option<String>,
        custom_headers: HashMap<HeaderName, HeaderValue>,
    ) -> impl Future<Output = HttpResult<()>> + Send + '_ {
        self.authorized(uri.clone(), auth_header, move |token| {
            self.inner.delete_session(
                uri.clone(),
                session_id.clone(),
                token,
                custom_headers.clone(),
            )
        })
    }

    fn get_stream(
        &self,
        uri: Arc<str>,
        session_id: Option<Arc<str>>,
        last_event_id: Option<String>,
        auth_header: Option<String>,
        custom_headers: HashMap<HeaderName, HeaderValue>,
    ) -> impl Future<Output = HttpResult<BoxedSseResponse>> + Send + '_ {
        self.authorized(uri.clone(), auth_header, move |token| {
            self.inner.get_stream(
                uri.clone(),
                session_id.clone(),
                last_event_id.clone(),
                token,
                custom_headers.clone(),
            )
        })
    }

    fn get_stream_with_max_sse_event_size(
        &self,
        uri: Arc<str>,
        session_id: Option<Arc<str>>,
        last_event_id: Option<String>,
        auth_header: Option<String>,
        custom_headers: HashMap<HeaderName, HeaderValue>,
        max_sse_event_size: usize,
    ) -> impl Future<Output = HttpResult<BoxedSseResponse>> + Send + '_ {
        self.authorized(uri.clone(), auth_header, move |token| {
            self.inner.get_stream_with_max_sse_event_size(
                uri.clone(),
                session_id.clone(),
                last_event_id.clone(),
                token,
                custom_headers.clone(),
                max_sse_event_size,
            )
        })
    }
}

#[cfg(feature = "http-transport")]
#[derive(Clone)]
struct HttpConnectionFactory {
    builder: McpHttpClientBuilder,
}

#[cfg(feature = "http-transport")]
#[derive(Clone)]
struct HttpElicitationConnectionFactory {
    builder: McpHttpClientBuilder,
    handler: Arc<dyn ElicitationHandler>,
    resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
}

#[cfg(feature = "http-transport")]
impl HttpElicitationConnectionFactory {
    /// Opens one connection. A transport error keeps its code, such as
    /// `mcp.oauth.token_fetch` when the OAuth token cannot be fetched.
    async fn connect_once(
        &self,
    ) -> Result<rmcp::service::RunningService<rmcp::RoleClient, super::elicitation::AdkClientHandler>>
    {
        use rmcp::ServiceExt;

        let transport = self.builder.build_transport().await?;
        let mut handler = super::elicitation::AdkClientHandler::new(self.handler.clone());
        if let Some(resource_handler) = &self.resource_notification_handler {
            handler = handler.with_resource_notification_handler(Arc::clone(resource_handler));
        }
        if self.builder.tasks.as_ref().is_some_and(|config| config.enable_tasks) {
            handler = handler.with_tasks();
        }
        handler
            .serve(transport)
            .await
            .map_err(|error| AdkError::tool(format!("failed to connect to MCP server: {error}")))
    }
}

#[cfg(feature = "http-transport")]
#[async_trait::async_trait]
impl super::ConnectionFactory<super::elicitation::AdkClientHandler>
    for HttpElicitationConnectionFactory
{
    async fn create_connection(
        &self,
    ) -> std::result::Result<
        rmcp::service::RunningService<rmcp::RoleClient, super::elicitation::AdkClientHandler>,
        String,
    > {
        self.connect_once().await.map_err(|error| error.to_string())
    }
}

#[cfg(feature = "http-transport")]
impl HttpConnectionFactory {
    /// Opens one connection. A transport error keeps its code, such as
    /// `mcp.oauth.token_fetch` when the OAuth token cannot be fetched.
    async fn connect_once(&self) -> Result<rmcp::service::RunningService<rmcp::RoleClient, ()>> {
        use rmcp::ServiceExt;

        let transport = self.builder.build_transport().await?;
        ().serve(transport)
            .await
            .map_err(|error| AdkError::tool(format!("failed to connect to MCP server: {error}")))
    }
}

#[cfg(feature = "http-transport")]
#[async_trait::async_trait]
impl super::ConnectionFactory<()> for HttpConnectionFactory {
    async fn create_connection(
        &self,
    ) -> std::result::Result<rmcp::service::RunningService<rmcp::RoleClient, ()>, String> {
        self.connect_once().await.map_err(|error| error.to_string())
    }
}

/// Builder for HTTP-based MCP connections.
///
/// This builder creates connections to remote MCP servers using the
/// current MCP Streamable HTTP transport.
///
/// # Example
///
/// ```rust,ignore
/// use adk_tool::mcp::{McpHttpClientBuilder, McpAuth, OAuth2Config};
///
/// // Simple connection
/// let toolset = McpHttpClientBuilder::new("https://mcp.example.com/v1")
///     .connect()
///     .await?;
///
/// // With OAuth2 authentication
/// let toolset = McpHttpClientBuilder::new("https://mcp.example.com/v1")
///     .with_auth(McpAuth::oauth2(
///         OAuth2Config::new("client-id", "https://auth.example.com/token")
///             .with_secret("client-secret")
///             .with_scopes(vec!["mcp:read".into()])
///     ))
///     .timeout(Duration::from_secs(60))
///     .connect()
///     .await?;
/// ```
#[derive(Clone)]
pub struct McpHttpClientBuilder {
    /// MCP server endpoint URL
    endpoint: String,
    /// Authentication configuration
    auth: McpAuth,
    /// Request timeout
    timeout: Duration,
    /// Custom headers
    headers: HashMap<String, String>,
    /// Optional elicitation handler
    elicitation_handler: Option<Arc<dyn ElicitationHandler>>,
    /// Optional resource notification handler.
    resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
    /// Recreate the MCP session once when a remote HTTP session expires.
    reinit_on_expired_session: bool,
    /// Brokered credentials; when set they replace `auth`.
    brokered: Option<Arc<BrokeredAuth>>,
    /// Task support declared and used by `connect_with_elicitation`.
    tasks: Option<super::McpTaskConfig>,
}

impl McpHttpClientBuilder {
    /// Create a new HTTP client builder for the given endpoint.
    ///
    /// # Arguments
    ///
    /// * `endpoint` - The MCP server URL (e.g., `https://mcp.example.com/v1`)
    pub fn new(endpoint: impl Into<String>) -> Self {
        Self {
            endpoint: endpoint.into(),
            auth: McpAuth::None,
            timeout: Duration::from_secs(30),
            headers: HashMap::new(),
            elicitation_handler: None,
            resource_notification_handler: None,
            reinit_on_expired_session: true,
            brokered: None,
            tasks: None,
        }
    }

    /// Authenticates with tokens minted by `broker` for `acting`, with `scopes`.
    ///
    /// The endpoint is the resource (RFC 8707): every request asks the broker for a
    /// token for the endpoint and attaches it only after
    /// [`ScopedToken::authorize_for`](adk_core::ScopedToken::authorize_for) accepts the
    /// request URL, so a token minted for another resource is never sent. The
    /// connection outlives any one run, so tokens are minted for the acting context
    /// given here rather than for each calling run. Replaces [`with_auth`](Self::with_auth).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::{ActingContext, AgentId, AgentPrincipal};
    /// use adk_tool::mcp::McpHttpClientBuilder;
    ///
    /// let acting =
    ///     ActingContext::new(AgentPrincipal::new(AgentId::new("spiffe://example.org/agent/billing")?));
    /// let toolset = McpHttpClientBuilder::new("https://mcp.example.com/v1")
    ///     .with_credential_broker(broker, acting, vec!["tools.read".into()])
    ///     .connect()
    ///     .await?;
    /// ```
    pub fn with_credential_broker(
        mut self,
        broker: Arc<dyn CredentialBroker>,
        acting: ActingContext,
        scopes: Vec<String>,
    ) -> Self {
        self.brokered = Some(Arc::new(BrokeredAuth { broker, acting, scopes }));
        self
    }

    /// Mints a brokered token for the endpoint and checks it may be sent there, so a
    /// misconfigured broker fails the connection with its own error code.
    #[cfg(feature = "http-transport")]
    async fn check_brokered(&self) -> Result<Option<(Arc<BrokeredAuth>, Url)>> {
        let Some(brokered) = &self.brokered else {
            return Ok(None);
        };
        let resource = adk_core::resource_indicator(&self.endpoint)?;
        brokered.bearer_for(&resource, &resource).await?;
        Ok(Some((Arc::clone(brokered), resource)))
    }

    /// Set authentication for the connection.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let builder = McpHttpClientBuilder::new("https://mcp.example.com")
    ///     .with_auth(McpAuth::bearer("my-token"));
    /// ```
    pub fn with_auth(mut self, auth: McpAuth) -> Self {
        self.auth = auth;
        self
    }

    /// Set the request timeout.
    ///
    /// Default is 30 seconds.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Add a custom header to all requests.
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(key.into(), value.into());
        self
    }

    /// Configure bounded automatic recovery when the server reports an expired session.
    ///
    /// Enabled by default. rmcp performs at most one re-initialization attempt.
    pub fn reinit_on_expired_session(mut self, enabled: bool) -> Self {
        self.reinit_on_expired_session = enabled;
        self
    }

    #[cfg(feature = "http-transport")]
    async fn build_transport(
        &self,
    ) -> Result<rmcp::transport::streamable_http_client::StreamableHttpClientTransport<McpHttpClient>>
    {
        use adk_core::{ErrorCategory, ErrorComponent};
        use rmcp::transport::streamable_http_client::{
            StreamableHttpClientTransport, StreamableHttpClientTransportConfig,
        };

        let mut custom_headers = HashMap::new();
        for (name, value) in &self.headers {
            let name = HeaderName::from_bytes(name.as_bytes()).map_err(|error| {
                AdkError::tool(format!("invalid MCP HTTP header '{name}': {error}"))
            })?;
            let value = HeaderValue::from_str(value).map_err(|error| {
                AdkError::tool(format!("invalid value for MCP HTTP header '{name}': {error}"))
            })?;
            custom_headers.insert(name, value);
        }

        let brokered = self.check_brokered().await?;
        let mut oauth = None;
        let token = match &self.auth {
            _ if brokered.is_some() => None,
            McpAuth::Bearer(token) => Some(token.clone()),
            McpAuth::OAuth2(config) => {
                // Fetched now so bad credentials fail the connection rather than
                // its first request. McpHttpClient attaches it, and its successors.
                config.get_or_refresh_token().await.map_err(|error| {
                    AdkError::new(
                        ErrorComponent::Tool,
                        ErrorCategory::Unauthorized,
                        "mcp.oauth.token_fetch",
                        format!("OAuth2 client-credentials authentication failed: {error}"),
                    )
                })?;
                oauth = Some(Arc::clone(config));
                None
            }
            McpAuth::ApiKey { header, key } => {
                let name = HeaderName::from_bytes(header.as_bytes()).map_err(|error| {
                    AdkError::tool(format!("invalid MCP API-key header '{header}': {error}"))
                })?;
                let value = HeaderValue::from_str(key).map_err(|error| {
                    AdkError::tool(format!("invalid MCP API-key value for '{header}': {error}"))
                })?;
                custom_headers.insert(name, value);
                None
            }
            McpAuth::None => None,
        };

        let mut config = StreamableHttpClientTransportConfig::with_uri(self.endpoint.as_str())
            .custom_headers(custom_headers)
            .reinit_on_expired_session(self.reinit_on_expired_session);
        if let Some(token) = token {
            config = config.auth_header(token);
        }

        let inner = reqwest::Client::builder()
            .timeout(self.timeout)
            .build()
            .map_err(|error| AdkError::tool(format!("failed to build MCP HTTP client: {error}")))?;
        Ok(StreamableHttpClientTransport::with_client(
            McpHttpClient { inner, oauth, brokered },
            config,
        ))
    }

    /// Configure an elicitation handler for the HTTP connection.
    ///
    /// When set, use [`connect_with_elicitation`](Self::connect_with_elicitation)
    /// to create a toolset that advertises elicitation capabilities.
    pub fn with_elicitation_handler(mut self, handler: Arc<dyn ElicitationHandler>) -> Self {
        self.elicitation_handler = Some(handler);
        self
    }

    /// Declares the tasks extension (SEP-2663) and follows the tasks the server answers calls
    /// with under `config`.
    ///
    /// A task may ask for input, so this applies to
    /// [`connect_with_elicitation`](Self::connect_with_elicitation), whose handler answers it;
    /// [`connect`](Self::connect) refuses a builder with task support.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use adk_tool::mcp::{AutoDeclineElicitationHandler, McpHttpClientBuilder, McpTaskConfig};
    ///
    /// let builder = McpHttpClientBuilder::new("https://agents.example.com/mcp")
    ///     .with_elicitation_handler(Arc::new(AutoDeclineElicitationHandler))
    ///     .with_task_support(McpTaskConfig::enabled());
    /// # let _ = builder;
    /// ```
    pub fn with_task_support(mut self, config: super::McpTaskConfig) -> Self {
        self.tasks = Some(config);
        self
    }

    /// Configure a handler for resource and resource-list update notifications.
    ///
    /// Use this with [`connect_with_elicitation`](Self::connect_with_elicitation);
    /// the handler is retained when an expired HTTP session is recreated.
    pub fn with_resource_notification_handler(
        mut self,
        handler: Arc<dyn ResourceNotificationHandler>,
    ) -> Self {
        self.resource_notification_handler = Some(handler);
        self
    }

    /// Get the endpoint URL.
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }

    /// Get the configured timeout.
    pub fn get_timeout(&self) -> Duration {
        self.timeout
    }

    /// Get the authentication configuration.
    pub fn get_auth(&self) -> &McpAuth {
        &self.auth
    }

    /// Connect to the MCP server and create a toolset.
    ///
    /// This method establishes a connection to the remote MCP server
    /// using the streamable HTTP transport.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The `http-transport` feature is not enabled
    /// - Connection to the server fails
    /// - Authentication fails
    #[cfg(feature = "http-transport")]
    pub async fn connect(self) -> Result<super::McpToolset<()>> {
        if self.tasks.is_some() {
            return Err(AdkError::tool(
                "a toolset with task support answers its tasks' input requests; set a handler \
                 with `with_elicitation_handler` and connect with `connect_with_elicitation`",
            ));
        }
        self.check_brokered().await?;
        let factory = Arc::new(HttpConnectionFactory { builder: self.clone() });
        let client = factory.connect_once().await?;

        Ok(super::McpToolset::new(client).with_connection_factory(factory))
    }

    /// Connect to the MCP server (stub when http-transport feature is disabled).
    #[cfg(not(feature = "http-transport"))]
    pub async fn connect(self) -> Result<()> {
        Err(AdkError::tool(
            "HTTP transport requires the 'http-transport' feature. \
             Add `adk-tool = { features = [\"http-transport\"] }` to your Cargo.toml",
        ))
    }

    /// Connect with elicitation support.
    ///
    /// Requires [`with_elicitation_handler`](Self::with_elicitation_handler) to have been called.
    /// Returns a `McpToolset<AdkClientHandler>` that advertises elicitation capabilities.
    ///
    /// # Errors
    ///
    /// Returns an error if no elicitation handler was configured or if the connection fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_tool::{McpHttpClientBuilder, AutoDeclineElicitationHandler};
    /// use std::sync::Arc;
    ///
    /// let toolset = McpHttpClientBuilder::new("https://mcp.example.com/v1")
    ///     .with_elicitation_handler(Arc::new(AutoDeclineElicitationHandler))
    ///     .connect_with_elicitation()
    ///     .await?;
    /// ```
    #[cfg(feature = "http-transport")]
    pub async fn connect_with_elicitation(
        self,
    ) -> Result<super::McpToolset<super::elicitation::AdkClientHandler>> {
        let handler = self.elicitation_handler.clone().ok_or_else(|| {
            AdkError::tool(
                "connect_with_elicitation requires with_elicitation_handler to be called first",
            )
        })?;

        self.check_brokered().await?;
        let resource_notification_handler = self.resource_notification_handler.clone();
        let tasks = self.tasks.clone();
        let factory = Arc::new(HttpElicitationConnectionFactory {
            builder: self,
            handler,
            resource_notification_handler,
        });
        let client = factory.connect_once().await?;

        let toolset = super::McpToolset::new(client).with_connection_factory(factory);
        Ok(match tasks {
            Some(config) => toolset.with_task_support(config),
            None => toolset,
        })
    }

    /// Connect with elicitation support (stub when http-transport feature is disabled).
    #[cfg(not(feature = "http-transport"))]
    pub async fn connect_with_elicitation(self) -> Result<()> {
        Err(AdkError::tool(
            "HTTP transport requires the 'http-transport' feature. \
             Add `adk-tool = { features = [\"http-transport\"] }` to your Cargo.toml",
        ))
    }
}

impl std::fmt::Debug for McpHttpClientBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpHttpClientBuilder")
            .field("endpoint", &self.endpoint)
            .field("auth", &self.auth)
            .field("timeout", &self.timeout)
            .field("credential_broker", &self.brokered.as_ref().map(|b| &b.broker))
            .field("headers", &self.headers.keys().collect::<Vec<_>>())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_new() {
        let builder = McpHttpClientBuilder::new("https://mcp.example.com");
        assert_eq!(builder.endpoint(), "https://mcp.example.com");
        assert_eq!(builder.get_timeout(), Duration::from_secs(30));
    }

    #[test]
    fn test_builder_with_auth() {
        let builder = McpHttpClientBuilder::new("https://mcp.example.com")
            .with_auth(McpAuth::bearer("test-token"));
        assert!(builder.get_auth().is_configured());
    }

    #[test]
    fn test_builder_timeout() {
        let builder =
            McpHttpClientBuilder::new("https://mcp.example.com").timeout(Duration::from_secs(60));
        assert_eq!(builder.get_timeout(), Duration::from_secs(60));
    }

    #[test]
    fn test_builder_headers() {
        let builder =
            McpHttpClientBuilder::new("https://mcp.example.com").header("X-Custom", "value");
        assert!(builder.headers.contains_key("X-Custom"));
    }
}