tower-mcp 0.16.1

Tower-native Model Context Protocol (MCP) implementation
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
//! OAuth 2.0 Client Credentials grant for machine-to-machine authentication.
//!
//! Provides [`OAuthClientCredentials`] for acquiring and caching access tokens
//! using the [client credentials grant](https://datatracker.ietf.org/doc/html/rfc6749#section-4.4).
//! Tokens are cached in memory and refreshed automatically before expiry.
//!
//! # Example
//!
//! ```rust,no_run
//! use tower_mcp::client::{HttpClientTransport, OAuthClientCredentials};
//!
//! # async fn example() -> Result<(), tower_mcp::BoxError> {
//! // Direct token endpoint
//! let provider = OAuthClientCredentials::builder()
//!     .client_id("my-client")
//!     .client_secret("my-secret")
//!     .token_endpoint("https://auth.example.com/token")
//!     .scopes(["mcp:tools", "mcp:resources"])
//!     .build()?;
//!
//! let transport = HttpClientTransport::new("http://localhost:3000")
//!     .with_token_provider(provider);
//! # Ok(())
//! # }
//! ```
//!
//! # Auth Server Discovery
//!
//! ```rust,no_run
//! use tower_mcp::client::OAuthClientCredentials;
//!
//! # async fn example() -> Result<(), tower_mcp::BoxError> {
//! let provider = OAuthClientCredentials::discover(
//!     "https://auth.example.com",
//!     "my-client",
//!     "my-secret",
//! ).await?;
//! # Ok(())
//! # }
//! ```

use std::fmt;
use std::sync::Arc;
use std::time::{Duration, Instant};

use async_trait::async_trait;
use tokio::sync::RwLock;

/// Trait for dynamic token providers.
///
/// Implement this to provide bearer tokens that are acquired and refreshed
/// at runtime (e.g., via OAuth 2.0 grants).
///
/// # Example
///
/// ```rust,no_run
/// use async_trait::async_trait;
/// use tower_mcp::client::{TokenProvider, OAuthClientError};
///
/// struct StaticTokenProvider(String);
///
/// #[async_trait]
/// impl TokenProvider for StaticTokenProvider {
///     async fn get_token(&self) -> Result<String, OAuthClientError> {
///         Ok(self.0.clone())
///     }
/// }
/// ```
#[async_trait]
pub trait TokenProvider: Send + Sync + 'static {
    /// Get a valid bearer token.
    ///
    /// Implementations should cache tokens and return cached values when
    /// still valid. This method may be called concurrently from multiple
    /// tasks.
    async fn get_token(&self) -> Result<String, OAuthClientError>;
}

/// An OAuth `insufficient_scope` Bearer challenge.
///
/// MCP authorization servers use this challenge on HTTP 403 responses to tell
/// clients which additional scopes are required for the attempted operation.
/// See [`OAuthScopeChallenge::from_www_authenticate`] for parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthScopeChallenge {
    /// Scopes requested by the authorization server.
    pub required_scopes: Vec<String>,
    /// Protected resource metadata URL supplied by the server.
    pub resource_metadata: Option<String>,
    /// Human-readable description supplied by the server.
    pub error_description: Option<String>,
}

impl OAuthScopeChallenge {
    /// Parse an `insufficient_scope` Bearer challenge from a
    /// `WWW-Authenticate` header value.
    ///
    /// Returns `None` for other authentication schemes, other OAuth errors,
    /// or challenges that do not include at least one required scope.
    pub fn from_www_authenticate(header: &str) -> Option<Self> {
        let mut in_bearer_challenge = false;
        let mut found_bearer_challenge = false;
        let mut error = None;
        let mut scope = None;
        let mut resource_metadata = None;
        let mut error_description = None;

        for segment in split_quoted_commas(header) {
            let segment = segment.trim();
            let (parameter, starts_challenge) = if let Some((candidate_scheme, remainder)) =
                segment.split_once(char::is_whitespace)
            {
                if !candidate_scheme.contains('=') {
                    if found_bearer_challenge {
                        break;
                    }
                    in_bearer_challenge = candidate_scheme.eq_ignore_ascii_case("Bearer");
                    found_bearer_challenge = in_bearer_challenge;
                    (remainder.trim(), true)
                } else {
                    (segment, false)
                }
            } else {
                (segment, false)
            };

            if starts_challenge && !in_bearer_challenge {
                continue;
            }
            if !in_bearer_challenge {
                continue;
            }

            let Some((name, value)) = parameter.split_once('=') else {
                continue;
            };
            let value = unquote_auth_param(value.trim())?;
            match name.trim() {
                name if name.eq_ignore_ascii_case("error") => error = Some(value),
                name if name.eq_ignore_ascii_case("scope") => scope = Some(value),
                name if name.eq_ignore_ascii_case("resource_metadata") => {
                    resource_metadata = Some(value)
                }
                name if name.eq_ignore_ascii_case("error_description") => {
                    error_description = Some(value)
                }
                _ => {}
            }
        }

        if error.as_deref() != Some("insufficient_scope") {
            return None;
        }
        let required_scopes = unique_scopes(scope?.split_ascii_whitespace());
        if required_scopes.is_empty() {
            return None;
        }

        Some(Self {
            required_scopes,
            resource_metadata,
            error_description,
        })
    }
}

/// Context passed to an [`OAuthScopeEscalationHandler`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthScopeEscalationRequest {
    /// MCP protected-resource URL that rejected the request.
    pub resource: String,
    /// MCP operation that was rejected, such as `tools/call:search`.
    pub operation: String,
    /// Parsed authorization-server challenge.
    pub challenge: OAuthScopeChallenge,
    /// Scopes held before this escalation.
    pub previous_scopes: Vec<String>,
    /// Stable-order union of previous and newly required scopes.
    pub requested_scopes: Vec<String>,
    /// One-based retry attempt for this resource operation.
    pub attempt: usize,
}

/// Application hook for interactive or headless OAuth reauthorization.
///
/// Implementations should acquire a token for `request.requested_scopes` and
/// update the [`TokenProvider`] installed with
/// [`HttpClientTransport::with_scope_aware_token_provider`](crate::client::HttpClientTransport::with_scope_aware_token_provider).
/// After this method succeeds, the transport asks that provider for a fresh
/// token and retries the rejected MCP operation.
#[async_trait]
pub trait OAuthScopeEscalationHandler: Send + Sync + 'static {
    /// Reauthorize for the stable-order scope union in `request`.
    async fn reauthorize(
        &self,
        request: OAuthScopeEscalationRequest,
    ) -> Result<(), OAuthClientError>;
}

/// Runtime scope-escalation policy for `HttpClientTransport`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthScopeEscalationConfig {
    initial_scopes: Vec<String>,
    max_attempts: usize,
}

impl Default for OAuthScopeEscalationConfig {
    fn default() -> Self {
        Self {
            initial_scopes: Vec::new(),
            max_attempts: 2,
        }
    }
}

impl OAuthScopeEscalationConfig {
    /// Create a policy with the scopes requested for the initial token.
    ///
    /// Duplicate and blank scope values are removed while preserving order.
    /// By default, at most two challenged retries are permitted per MCP
    /// operation.
    pub fn new(scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            initial_scopes: unique_scopes(scopes.into_iter().map(Into::into).flat_map(
                |scope: String| {
                    scope
                        .split_ascii_whitespace()
                        .map(str::to_string)
                        .collect::<Vec<_>>()
                },
            )),
            ..Self::default()
        }
    }

    /// Set the maximum number of challenged retries for one MCP operation.
    ///
    /// Set this to zero to surface the first HTTP 403 without reauthorizing.
    pub fn max_attempts(mut self, max_attempts: usize) -> Self {
        self.max_attempts = max_attempts;
        self
    }

    /// Initial scopes tracked by the policy.
    pub fn initial_scopes(&self) -> &[String] {
        &self.initial_scopes
    }

    /// Maximum challenged retries for one MCP operation.
    pub fn maximum_attempts(&self) -> usize {
        self.max_attempts
    }
}

fn unique_scopes(scopes: impl IntoIterator<Item = impl AsRef<str>>) -> Vec<String> {
    let mut unique = Vec::new();
    for scope in scopes {
        let scope = scope.as_ref();
        if !scope.is_empty() && !unique.iter().any(|existing| existing == scope) {
            unique.push(scope.to_string());
        }
    }
    unique
}

fn split_quoted_commas(header: &str) -> Vec<&str> {
    let mut segments = Vec::new();
    let mut start = 0;
    let mut quoted = false;
    let mut escaped = false;
    for (index, character) in header.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        match character {
            '\\' if quoted => escaped = true,
            '"' => quoted = !quoted,
            ',' if !quoted => {
                segments.push(&header[start..index]);
                start = index + 1;
            }
            _ => {}
        }
    }
    segments.push(&header[start..]);
    segments
}

fn unquote_auth_param(value: &str) -> Option<String> {
    if !value.starts_with('"') {
        return Some(value.to_string());
    }
    if !value.ends_with('"') || value.len() < 2 {
        return None;
    }

    let mut unquoted = String::new();
    let mut escaped = false;
    for character in value[1..value.len() - 1].chars() {
        if escaped {
            unquoted.push(character);
            escaped = false;
        } else if character == '\\' {
            escaped = true;
        } else {
            unquoted.push(character);
        }
    }
    if escaped {
        return None;
    }
    Some(unquoted)
}

/// Error type for OAuth client operations.
#[derive(Debug)]
#[non_exhaustive]
pub enum OAuthClientError {
    /// Failed to discover the authorization server metadata.
    Discovery(String),
    /// Failed to request a token from the token endpoint.
    TokenRequest(String),
    /// Failed to register an OAuth client.
    Registration(String),
    /// Failed to load, save, or remove persisted OAuth client credentials.
    CredentialStore(String),
    /// Failed to reauthorize after an insufficient-scope challenge.
    ScopeEscalation(String),
    /// The token response was invalid or missing required fields.
    InvalidResponse(String),
    /// Builder validation failed (missing required fields).
    BuildError(String),
}

impl fmt::Display for OAuthClientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Discovery(msg) => write!(f, "OAuth discovery error: {}", msg),
            Self::TokenRequest(msg) => write!(f, "OAuth token request error: {}", msg),
            Self::Registration(msg) => write!(f, "OAuth client registration error: {}", msg),
            Self::CredentialStore(msg) => write!(f, "OAuth credential store error: {}", msg),
            Self::ScopeEscalation(msg) => write!(f, "OAuth scope escalation error: {}", msg),
            Self::InvalidResponse(msg) => write!(f, "OAuth invalid response: {}", msg),
            Self::BuildError(msg) => write!(f, "OAuth builder error: {}", msg),
        }
    }
}

impl std::error::Error for OAuthClientError {}

/// A cached access token with its expiration time.
#[derive(Debug, Clone)]
struct CachedToken {
    access_token: String,
    expires_at: Instant,
}

/// OAuth 2.0 token response (subset of RFC 6749 Section 5.1).
#[derive(Debug, serde::Deserialize)]
struct TokenResponse {
    access_token: String,
    #[allow(dead_code)]
    token_type: String,
    /// Token lifetime in seconds.
    expires_in: Option<u64>,
    #[allow(dead_code)]
    scope: Option<String>,
}

/// Authorization server metadata response (RFC 8414).
#[derive(Debug, serde::Deserialize)]
struct AuthServerMetadata {
    token_endpoint: String,
}

/// Shared state for [`OAuthClientCredentials`].
struct OAuthClientCredentialsInner {
    client_id: String,
    client_secret: String,
    token_endpoint: String,
    scopes: Option<String>,
    refresh_buffer: Duration,
    client: reqwest::Client,
    cache: RwLock<Option<CachedToken>>,
}

/// OAuth 2.0 Client Credentials token provider.
///
/// Acquires access tokens using the
/// [client credentials grant](https://datatracker.ietf.org/doc/html/rfc6749#section-4.4)
/// and caches them until expiry. Uses `client_secret_basic` authentication
/// (HTTP Basic with `client_id:client_secret`).
///
/// # Token Caching
///
/// Tokens are cached in an `RwLock` and refreshed when they expire
/// (minus a configurable buffer, default 30 seconds). Concurrent
/// callers share the read lock; only one caller performs the refresh
/// while others wait on the write lock, then re-verify (double-check
/// pattern to prevent thundering herd).
///
/// # Example
///
/// ```rust,no_run
/// use tower_mcp::client::OAuthClientCredentials;
/// use std::time::Duration;
///
/// # fn example() -> Result<(), tower_mcp::BoxError> {
/// let provider = OAuthClientCredentials::builder()
///     .client_id("my-service")
///     .client_secret("s3cret")
///     .token_endpoint("https://auth.example.com/oauth/token")
///     .scopes(["mcp:tools"])
///     .refresh_buffer(Duration::from_secs(60))
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct OAuthClientCredentials {
    inner: Arc<OAuthClientCredentialsInner>,
}

impl fmt::Debug for OAuthClientCredentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OAuthClientCredentials")
            .field("client_id", &self.inner.client_id)
            .field("token_endpoint", &self.inner.token_endpoint)
            .field("scopes", &self.inner.scopes)
            .field("refresh_buffer", &self.inner.refresh_buffer)
            .finish()
    }
}

impl OAuthClientCredentials {
    /// Create a builder for configuring the client credentials provider.
    pub fn builder() -> OAuthClientCredentialsBuilder {
        OAuthClientCredentialsBuilder::default()
    }

    /// Discover the token endpoint from the authorization server metadata
    /// and create a provider.
    ///
    /// Fetches `{issuer}/.well-known/oauth-authorization-server` to find
    /// the `token_endpoint`, then creates the provider with default settings.
    ///
    /// # Errors
    ///
    /// Returns [`OAuthClientError::Discovery`] if the metadata endpoint
    /// is unreachable or does not contain a `token_endpoint`.
    pub async fn discover(
        issuer: &str,
        client_id: impl Into<String>,
        client_secret: impl Into<String>,
    ) -> Result<Self, OAuthClientError> {
        let client = reqwest::Client::new();
        let url = format!(
            "{}/.well-known/oauth-authorization-server",
            issuer.trim_end_matches('/')
        );

        let metadata: AuthServerMetadata = client
            .get(&url)
            .send()
            .await
            .map_err(|e| OAuthClientError::Discovery(e.to_string()))?
            .json()
            .await
            .map_err(|e| OAuthClientError::Discovery(e.to_string()))?;

        Self::builder()
            .client_id(client_id)
            .client_secret(client_secret)
            .token_endpoint(metadata.token_endpoint)
            .build()
            .map_err(|e| OAuthClientError::Discovery(e.to_string()))
    }

    /// Check if the cached token is still valid (not expired minus buffer).
    fn is_token_valid(token: &CachedToken, buffer: Duration) -> bool {
        token
            .expires_at
            .checked_sub(buffer)
            .is_some_and(|effective| Instant::now() < effective)
    }

    /// Perform the token request to the authorization server.
    async fn fetch_token(&self) -> Result<CachedToken, OAuthClientError> {
        use base64::Engine;

        let credentials = base64::engine::general_purpose::STANDARD.encode(format!(
            "{}:{}",
            self.inner.client_id, self.inner.client_secret
        ));

        let mut body = "grant_type=client_credentials".to_string();
        if let Some(ref scopes) = self.inner.scopes {
            body.push_str("&scope=");
            body.push_str(scopes);
        }

        let response = self
            .inner
            .client
            .post(&self.inner.token_endpoint)
            .header("Authorization", format!("Basic {}", credentials))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .body(body)
            .send()
            .await
            .map_err(|e| OAuthClientError::TokenRequest(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(OAuthClientError::TokenRequest(format!(
                "HTTP {}: {}",
                status, body
            )));
        }

        let token_response: TokenResponse = response
            .json()
            .await
            .map_err(|e| OAuthClientError::InvalidResponse(e.to_string()))?;

        // Default to 1 hour if expires_in not provided
        let expires_in = Duration::from_secs(token_response.expires_in.unwrap_or(3600));
        let expires_at = Instant::now() + expires_in;

        Ok(CachedToken {
            access_token: token_response.access_token,
            expires_at,
        })
    }
}

#[async_trait]
impl TokenProvider for OAuthClientCredentials {
    async fn get_token(&self) -> Result<String, OAuthClientError> {
        // Fast path: read lock, return cached token if valid
        {
            let cache = self.inner.cache.read().await;
            if let Some(ref token) = *cache
                && Self::is_token_valid(token, self.inner.refresh_buffer)
            {
                return Ok(token.access_token.clone());
            }
        }

        // Slow path: write lock, double-check, then fetch
        let mut cache = self.inner.cache.write().await;

        // Another task may have refreshed while we waited for the lock
        if let Some(ref token) = *cache
            && Self::is_token_valid(token, self.inner.refresh_buffer)
        {
            return Ok(token.access_token.clone());
        }

        let token = self.fetch_token().await?;
        let access_token = token.access_token.clone();
        *cache = Some(token);

        Ok(access_token)
    }
}

/// Builder for [`OAuthClientCredentials`].
///
/// # Required Fields
///
/// - `client_id`
/// - `client_secret`
/// - `token_endpoint`
///
/// # Example
///
/// ```rust,no_run
/// use tower_mcp::client::OAuthClientCredentials;
///
/// # fn example() -> Result<(), tower_mcp::BoxError> {
/// let provider = OAuthClientCredentials::builder()
///     .client_id("my-service")
///     .client_secret("s3cret")
///     .token_endpoint("https://auth.example.com/token")
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Default)]
pub struct OAuthClientCredentialsBuilder {
    client_id: Option<String>,
    client_secret: Option<String>,
    token_endpoint: Option<String>,
    scopes: Option<String>,
    refresh_buffer: Option<Duration>,
    client: Option<reqwest::Client>,
}

impl OAuthClientCredentialsBuilder {
    /// Set the OAuth client ID.
    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }

    /// Set the OAuth client secret.
    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
        self.client_secret = Some(client_secret.into());
        self
    }

    /// Set the token endpoint URL.
    pub fn token_endpoint(mut self, url: impl Into<String>) -> Self {
        self.token_endpoint = Some(url.into());
        self
    }

    /// Set the requested scopes.
    ///
    /// Accepts an iterator of scope strings, which are joined with spaces
    /// per RFC 6749 Section 3.3.
    pub fn scopes(mut self, scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
        let scope_str: Vec<String> = scopes.into_iter().map(|s| s.into()).collect();
        if !scope_str.is_empty() {
            self.scopes = Some(scope_str.join(" "));
        }
        self
    }

    /// Set the refresh buffer duration.
    ///
    /// Tokens are refreshed this long before their actual expiry to avoid
    /// using a token that expires during a request. Default: 30 seconds.
    pub fn refresh_buffer(mut self, duration: Duration) -> Self {
        self.refresh_buffer = Some(duration);
        self
    }

    /// Set a custom `reqwest::Client` for token requests.
    ///
    /// Use this when you need custom TLS configuration or proxy settings.
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.client = Some(client);
        self
    }

    /// Build the [`OAuthClientCredentials`] provider.
    ///
    /// # Errors
    ///
    /// Returns [`OAuthClientError::BuildError`] if `client_id`, `client_secret`,
    /// or `token_endpoint` are not set.
    pub fn build(self) -> Result<OAuthClientCredentials, OAuthClientError> {
        let client_id = self
            .client_id
            .ok_or_else(|| OAuthClientError::BuildError("client_id is required".into()))?;
        let client_secret = self
            .client_secret
            .ok_or_else(|| OAuthClientError::BuildError("client_secret is required".into()))?;
        let token_endpoint = self
            .token_endpoint
            .ok_or_else(|| OAuthClientError::BuildError("token_endpoint is required".into()))?;

        let inner = OAuthClientCredentialsInner {
            client_id,
            client_secret,
            token_endpoint,
            scopes: self.scopes,
            refresh_buffer: self.refresh_buffer.unwrap_or(Duration::from_secs(30)),
            client: self.client.unwrap_or_default(),
            cache: RwLock::new(None),
        };

        Ok(OAuthClientCredentials {
            inner: Arc::new(inner),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn test_builder_missing_client_id() {
        let err = OAuthClientCredentials::builder()
            .client_secret("secret")
            .token_endpoint("https://auth.example.com/token")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("client_id"));
    }

    #[test]
    fn test_builder_missing_client_secret() {
        let err = OAuthClientCredentials::builder()
            .client_id("id")
            .token_endpoint("https://auth.example.com/token")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("client_secret"));
    }

    #[test]
    fn test_builder_missing_token_endpoint() {
        let err = OAuthClientCredentials::builder()
            .client_id("id")
            .client_secret("secret")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("token_endpoint"));
    }

    #[test]
    fn test_builder_success() {
        let provider = OAuthClientCredentials::builder()
            .client_id("my-client")
            .client_secret("my-secret")
            .token_endpoint("https://auth.example.com/token")
            .build()
            .unwrap();

        assert_eq!(provider.inner.client_id, "my-client");
        assert_eq!(
            provider.inner.token_endpoint,
            "https://auth.example.com/token"
        );
        assert!(provider.inner.scopes.is_none());
        assert_eq!(provider.inner.refresh_buffer, Duration::from_secs(30));
    }

    #[test]
    fn test_builder_with_scopes() {
        let provider = OAuthClientCredentials::builder()
            .client_id("id")
            .client_secret("secret")
            .token_endpoint("https://auth.example.com/token")
            .scopes(["mcp:tools", "mcp:resources"])
            .build()
            .unwrap();

        assert_eq!(
            provider.inner.scopes.as_deref(),
            Some("mcp:tools mcp:resources")
        );
    }

    #[test]
    fn test_builder_with_refresh_buffer() {
        let provider = OAuthClientCredentials::builder()
            .client_id("id")
            .client_secret("secret")
            .token_endpoint("https://auth.example.com/token")
            .refresh_buffer(Duration::from_secs(60))
            .build()
            .unwrap();

        assert_eq!(provider.inner.refresh_buffer, Duration::from_secs(60));
    }

    #[test]
    fn test_debug_impl() {
        let provider = OAuthClientCredentials::builder()
            .client_id("my-client")
            .client_secret("secret")
            .token_endpoint("https://auth.example.com/token")
            .build()
            .unwrap();

        let debug = format!("{:?}", provider);
        assert!(debug.contains("my-client"));
        assert!(debug.contains("auth.example.com"));
        // Secret should NOT appear in debug output
        assert!(!debug.contains("secret"));
    }

    #[test]
    fn test_token_validity() {
        let valid_token = CachedToken {
            access_token: "valid".into(),
            expires_at: Instant::now() + Duration::from_secs(300),
        };
        assert!(OAuthClientCredentials::is_token_valid(
            &valid_token,
            Duration::from_secs(30)
        ));

        let expiring_soon = CachedToken {
            access_token: "expiring".into(),
            expires_at: Instant::now() + Duration::from_secs(10),
        };
        // 30s buffer > 10s remaining = invalid
        assert!(!OAuthClientCredentials::is_token_valid(
            &expiring_soon,
            Duration::from_secs(30)
        ));

        let expired = CachedToken {
            access_token: "expired".into(),
            expires_at: Instant::now() - Duration::from_secs(10),
        };
        assert!(!OAuthClientCredentials::is_token_valid(
            &expired,
            Duration::from_secs(30)
        ));
    }

    #[test]
    fn test_error_display() {
        let err = OAuthClientError::Discovery("not found".into());
        assert_eq!(err.to_string(), "OAuth discovery error: not found");

        let err = OAuthClientError::TokenRequest("timeout".into());
        assert_eq!(err.to_string(), "OAuth token request error: timeout");

        let err = OAuthClientError::Registration("rejected".into());
        assert_eq!(err.to_string(), "OAuth client registration error: rejected");

        let err = OAuthClientError::CredentialStore("unavailable".into());
        assert_eq!(err.to_string(), "OAuth credential store error: unavailable");

        let err = OAuthClientError::ScopeEscalation("denied".into());
        assert_eq!(err.to_string(), "OAuth scope escalation error: denied");

        let err = OAuthClientError::InvalidResponse("bad json".into());
        assert_eq!(err.to_string(), "OAuth invalid response: bad json");

        let err = OAuthClientError::BuildError("missing field".into());
        assert_eq!(err.to_string(), "OAuth builder error: missing field");
    }

    #[test]
    fn parses_insufficient_scope_challenge() {
        let challenge = OAuthScopeChallenge::from_www_authenticate(
            r#"Bearer error="insufficient_scope", scope="files.read files.write files.read", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource", error_description="Need files, including \"shared\"""#,
        )
        .unwrap();

        assert_eq!(challenge.required_scopes, vec!["files.read", "files.write"]);
        assert_eq!(
            challenge.resource_metadata.as_deref(),
            Some("https://mcp.example.com/.well-known/oauth-protected-resource")
        );
        assert_eq!(
            challenge.error_description.as_deref(),
            Some(r#"Need files, including "shared""#)
        );
    }

    #[test]
    fn selects_bearer_from_multiple_authentication_challenges() {
        let challenge = OAuthScopeChallenge::from_www_authenticate(
            r#"Basic realm="legacy", Bearer realm="mcp", error="insufficient_scope", scope="tools.call""#,
        )
        .unwrap();

        assert_eq!(challenge.required_scopes, vec!["tools.call"]);
    }

    #[test]
    fn ignores_non_scope_authentication_challenges() {
        assert!(
            OAuthScopeChallenge::from_www_authenticate(
                r#"Bearer error="invalid_token", scope="tools.call""#
            )
            .is_none()
        );
        assert!(
            OAuthScopeChallenge::from_www_authenticate(
                r#"Bearer error="insufficient_scope", scope="""#
            )
            .is_none()
        );
        assert!(OAuthScopeChallenge::from_www_authenticate(r#"Basic realm="mcp""#).is_none());
    }

    #[test]
    fn scope_escalation_config_normalizes_scopes() {
        let config =
            OAuthScopeEscalationConfig::new(["openid profile", "profile", "", "tools.call"])
                .max_attempts(3);

        assert_eq!(
            config.initial_scopes(),
            &["openid", "profile", "tools.call"]
        );
        assert_eq!(config.maximum_attempts(), 3);
    }

    #[tokio::test]
    async fn test_caching_returns_same_token() {
        // Manually insert a cached token and verify get_token returns it
        let provider = OAuthClientCredentials::builder()
            .client_id("id")
            .client_secret("secret")
            .token_endpoint("https://auth.example.com/token")
            .build()
            .unwrap();

        // Seed the cache directly
        {
            let mut cache = provider.inner.cache.write().await;
            *cache = Some(CachedToken {
                access_token: "cached-token-123".into(),
                expires_at: Instant::now() + Duration::from_secs(300),
            });
        }

        let token = provider.get_token().await.unwrap();
        assert_eq!(token, "cached-token-123");

        // Second call should return the same cached token
        let token2 = provider.get_token().await.unwrap();
        assert_eq!(token2, "cached-token-123");
    }

    #[tokio::test]
    async fn test_expired_token_triggers_refresh_attempt() {
        let provider = OAuthClientCredentials::builder()
            .client_id("id")
            .client_secret("secret")
            .token_endpoint("http://127.0.0.1:1/nonexistent")
            .build()
            .unwrap();

        // Seed with an expired token
        {
            let mut cache = provider.inner.cache.write().await;
            *cache = Some(CachedToken {
                access_token: "expired-token".into(),
                expires_at: Instant::now() - Duration::from_secs(60),
            });
        }

        // get_token should try to refresh and fail (unreachable endpoint)
        let err = provider.get_token().await.unwrap_err();
        assert!(matches!(err, OAuthClientError::TokenRequest(_)));
    }

    #[tokio::test]
    async fn test_custom_token_provider() {
        let call_count = Arc::new(AtomicUsize::new(0));
        let count = call_count.clone();

        struct CountingProvider {
            count: Arc<AtomicUsize>,
        }

        #[async_trait]
        impl TokenProvider for CountingProvider {
            async fn get_token(&self) -> Result<String, OAuthClientError> {
                let n = self.count.fetch_add(1, Ordering::SeqCst);
                Ok(format!("token-{}", n))
            }
        }

        let provider = CountingProvider { count };

        assert_eq!(provider.get_token().await.unwrap(), "token-0");
        assert_eq!(provider.get_token().await.unwrap(), "token-1");
        assert_eq!(call_count.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn test_clone() {
        let provider = OAuthClientCredentials::builder()
            .client_id("id")
            .client_secret("secret")
            .token_endpoint("https://auth.example.com/token")
            .build()
            .unwrap();

        let cloned = provider.clone();
        // Both share the same inner state
        assert!(Arc::ptr_eq(&provider.inner, &cloned.inner));
    }
}