fastmcp-client 0.11.0

MCP client implementation for FastMCP
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
//! HTTPS-only bearer-credential binding for the modern HTTP client.
//!
//! HTTP-03 requires that a bearer credential is attached only when the
//! complete configured target is the same admitted HTTPS resource the
//! credential was bound to, and never to a cleartext `http:` endpoint —
//! including localhost and loopback literals. A local server behind a TLS
//! terminator is addressed by its public HTTPS URL from the client side.
//!
//! The rules are enforced structurally rather than at call sites:
//!
//! - A [`BoundBearerCredential`] can only be constructed against an `https`
//!   [`CanonicalHttpUrl`], so a cleartext binding never exists.
//! - [`BoundBearerCredential::authorization_for_target`] returns a header
//!   value only for a target canonically equal to the bound resource; every
//!   other target — different path, authority, scheme, or query — yields
//!   `None` rather than a downgraded or redirected credential.
//! - The token is redacted from `Debug` output so credentials cannot leak
//!   through diagnostics. Binding uses the same bounded `token68` grammar
//!   as HTTP credential admission, before retaining or emitting a token.
//! - Local revocation is shared by every clone. It stops subsequent header
//!   construction and wakes managed response readers without changing another
//!   independently bound credential.

use core::fmt;
use std::time::Instant;

use fastmcp_core::{AccessToken, McpRequestCancellation};

/// Protected-resource and issuer discovery for preregistered native clients.
pub mod discovery;
/// Shared OAuth renewal and authenticated modern HTTP dispatch.
pub mod managed;
/// Interactive native-public-client authorization with a caller-owned runtime.
pub mod oauth;
/// Typed core MCP calls over managed OAuth, with incremental notifications.
pub mod rpc;
/// Caller-owned model and tool execution for embedded sampling conversations.
pub mod sampling;
/// Descriptor-relative atomic storage for caller-protected credential blobs.
#[cfg(target_os = "linux")]
pub mod secure_file;
/// Schema-bound tool execution with pre-dispatch and pre-publication validation.
pub mod tool;

pub use fastmcp_core::CanonicalHttpUrl;

/// Typed refusals raised when constructing a credential binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BearerBindingError {
    /// The binding resource is not an `https` URL. Cleartext HTTP —
    /// including localhost and loopback — can never hold a bearer
    /// credential.
    CleartextResource,
    /// The token is empty.
    EmptyToken,
    /// The token exceeds the shared credential byte limit or does not use
    /// the `token68` grammar required by a Bearer authorization field.
    InvalidTokenBytes,
}

impl fmt::Display for BearerBindingError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CleartextResource => {
                formatter.write_str("bearer credentials bind only to https resources")
            }
            Self::EmptyToken => formatter.write_str("bearer token is empty"),
            Self::InvalidTokenBytes => formatter
                .write_str("bearer token exceeds the byte limit or violates token68 syntax"),
        }
    }
}

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

/// A bearer token bound to exactly one admitted HTTPS resource.
///
/// Clones share local revocation state. Dropping one clone does not revoke
/// the others; explicit [`Self::revoke`] is irreversible for this lineage.
/// Owner-bound clones additionally retain their owner's cancellation signal.
#[derive(Clone)]
pub struct BoundBearerCredential {
    resource: CanonicalHttpUrl,
    token: String,
    expires_at: Option<Instant>,
    revoked: McpRequestCancellation,
    owner_cancellation: Option<McpRequestCancellation>,
}

impl fmt::Debug for BoundBearerCredential {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("BoundBearerCredential")
            .field("resource", &self.resource.as_str())
            .field("token", &"<redacted>")
            .finish()
    }
}

impl BoundBearerCredential {
    /// Binds a token to one admitted HTTPS resource.
    ///
    /// RFC 6750 Bearer credentials use the same alphabet and trailing padding
    /// as `token68`. The shared [`AccessToken::is_valid_token68`] validator
    /// also enforces [`fastmcp_core::MAX_ACCESS_TOKEN_BYTES`]. No trimming,
    /// escaping, padding repair, or other token normalization is performed.
    ///
    /// # Errors
    ///
    /// Returns a typed [`BearerBindingError`] when the resource is not
    /// `https` or the token is empty, oversized, or syntactically invalid.
    /// There is no cleartext escape hatch: an `http:` resource — remote,
    /// localhost, or loopback — can never hold a credential.
    pub fn bind(
        resource: CanonicalHttpUrl,
        token: impl Into<String>,
    ) -> Result<Self, BearerBindingError> {
        if !resource.as_str().starts_with("https://") {
            return Err(BearerBindingError::CleartextResource);
        }
        let token = token.into();
        if token.is_empty() {
            return Err(BearerBindingError::EmptyToken);
        }
        // A safe header string is not necessarily a valid Bearer credential.
        // Share the server's grammar and byte cap so direct binding cannot
        // emit a token rejected before the verifier is even called.
        if !AccessToken::is_valid_token68(&token) {
            return Err(BearerBindingError::InvalidTokenBytes);
        }
        Ok(Self {
            resource,
            token,
            expires_at: None,
            revoked: McpRequestCancellation::new(),
            owner_cancellation: None,
        })
    }

    /// Binds a token with a monotonic deadline. At and after this instant,
    /// header construction withholds the credential, even from its resource.
    /// Already-emitted headers cannot be recalled by this value.
    pub fn bind_with_expiry(
        resource: CanonicalHttpUrl,
        token: impl Into<String>,
        expires_at: Instant,
    ) -> Result<Self, BearerBindingError> {
        let mut credential = Self::bind(resource, token)?;
        credential.expires_at = Some(expires_at);
        Ok(credential)
    }

    /// Creates a credential clone additionally bound to an owner's lifetime.
    /// Cancelling `owner` stops subsequent header construction by that clone
    /// and its descendants, without cancelling the source unowned credential.
    /// Token-local revocation remains shared with the source.
    ///
    /// Returns `None` when this credential already has an owner. Reparenting
    /// would remove the first owner's future revocation, so it is never
    /// permitted, even when the replacement owner is currently active.
    /// Binding an already-cancelled owner produces a revoked clone, not a
    /// fresh credential. No network revocation request is performed.
    #[must_use]
    pub fn for_owner(&self, owner: &McpRequestCancellation) -> Option<Self> {
        if self.owner_cancellation.is_some() {
            return None;
        }
        let mut credential = self.clone();
        credential.owner_cancellation = Some(owner.clone());
        Some(credential)
    }

    /// Returns the bound HTTPS resource.
    #[must_use]
    pub fn resource(&self) -> &CanonicalHttpUrl {
        &self.resource
    }

    /// Returns the locally enforced expiry, when the credential has one.
    #[must_use]
    pub fn expires_at(&self) -> Option<Instant> {
        self.expires_at
    }

    /// Irreversibly withholds this credential from subsequent header
    /// construction through this value and all existing or future clones.
    /// Active managed response readers are woken to discard their owned read;
    /// unpolled responses release their socket on the next poll or drop.
    ///
    /// This is local capability revocation, not an OAuth revocation-endpoint
    /// request. Already-created header strings, requests that captured such
    /// strings, and bytes already sent cannot be recalled. A header operation
    /// concurrent with revocation may have completed its admission first.
    pub fn revoke(&self) {
        self.revoked.cancel();
    }

    /// Returns whether this credential lineage has been locally revoked or
    /// its owner has cancelled. Expiry remains a separate condition.
    #[must_use]
    pub fn is_revoked(&self) -> bool {
        self.revoked.is_cancel_requested()
            || self
                .owner_cancellation
                .as_ref()
                .is_some_and(McpRequestCancellation::is_cancel_requested)
    }

    /// Returns the `Authorization` header value for `target`, or `None`
    /// when the target is not canonically identical to the bound resource or
    /// the credential has expired or been revoked.
    ///
    /// A `None` is not an error: the request simply proceeds without a
    /// credential, so a mismatched, downgraded, or redirected target can
    /// never observe the token. Consumers requiring authenticated dispatch
    /// must reject a withheld credential rather than silently sending a
    /// request without authorization.
    #[must_use]
    pub fn authorization_for_target(&self, target: &CanonicalHttpUrl) -> Option<String> {
        self.authorization_at(target, Instant::now())
    }

    fn authorization_at(&self, target: &CanonicalHttpUrl, now: Instant) -> Option<String> {
        if target.as_str() == self.resource.as_str()
            && self.expires_at.is_none_or(|deadline| now < deadline)
            && !self.is_revoked()
        {
            let authorization = format!("Bearer {}", self.token);
            // Revocation during allocation must not be ignored. As with any
            // admission check, revocation after this load cannot recall the
            // header returned to its caller.
            (!self.is_revoked()).then_some(authorization)
        } else {
            None
        }
    }

    /// Detects a peer reflecting this credential into an error's diagnostics.
    /// Inspect decoded strings so JSON escaping cannot hide the token.
    pub(crate) fn is_reflected_by_error(&self, error: &fastmcp_protocol::JsonRpcError) -> bool {
        error.message.contains(&self.token)
            || error
                .data
                .as_ref()
                .is_some_and(|data| self.is_reflected_by_value(data))
    }

    fn is_reflected_by_value(&self, value: &serde_json::Value) -> bool {
        match value {
            serde_json::Value::String(text) => text.contains(&self.token),
            serde_json::Value::Array(values) => {
                values.iter().any(|value| self.is_reflected_by_value(value))
            }
            serde_json::Value::Object(values) => values
                .iter()
                .any(|(key, value)| key.contains(&self.token) || self.is_reflected_by_value(value)),
            value => value.to_string().contains(&self.token),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{BearerBindingError, BoundBearerCredential, CanonicalHttpUrl};

    fn url(value: &str) -> CanonicalHttpUrl {
        CanonicalHttpUrl::parse(value).expect("test URL is canonical")
    }

    #[test]
    fn binds_only_to_https_resources() {
        assert!(BoundBearerCredential::bind(url("https://mcp.example/api"), "token-1").is_ok());

        for cleartext in [
            "http://mcp.example/api",
            "http://localhost:8080/api",
            "http://127.0.0.1:8080/api",
            "http://[::1]:8080/api",
        ] {
            assert_eq!(
                BoundBearerCredential::bind(url(cleartext), "token-1").err(),
                Some(BearerBindingError::CleartextResource),
                "cleartext resource {cleartext:?} must never hold a credential"
            );
        }
    }

    #[test]
    fn refuses_empty_and_header_hostile_tokens() {
        let resource = url("https://mcp.example/api");
        assert_eq!(
            BoundBearerCredential::bind(resource.clone(), "").err(),
            Some(BearerBindingError::EmptyToken)
        );
        assert_eq!(
            BoundBearerCredential::bind(resource.clone(), "to\r\nken").err(),
            Some(BearerBindingError::InvalidTokenBytes)
        );
        assert_eq!(
            BoundBearerCredential::bind(resource, "to ken").err(),
            Some(BearerBindingError::InvalidTokenBytes)
        );
    }

    #[test]
    fn attaches_only_to_the_exact_bound_resource() {
        let credential =
            BoundBearerCredential::bind(url("https://mcp.example/api"), "token-1").expect("binds");

        assert_eq!(
            credential.authorization_for_target(&url("https://mcp.example/api")),
            Some("Bearer token-1".to_owned())
        );

        // One changed dimension per case: path, authority, scheme-equivalent
        // http twin, and added query all withhold the credential.
        for target in [
            "https://mcp.example/other",
            "https://other.example/api",
            "http://mcp.example/api",
            "https://mcp.example/api?extra=1",
        ] {
            assert_eq!(
                credential.authorization_for_target(&url(target)),
                None,
                "target {target:?} must not observe the token"
            );
        }
    }

    #[test]
    fn debug_output_redacts_the_token() {
        let credential =
            BoundBearerCredential::bind(url("https://mcp.example/api"), "super-secret-token-value")
                .expect("binds");
        let debug = format!("{credential:?}");
        assert!(debug.contains("<redacted>"));
        assert!(
            !debug.contains("super-secret-token-value"),
            "the token must never appear in diagnostics: {debug}"
        );
    }

    #[test]
    fn expiring_credential_clones_withhold_headers_at_the_exact_deadline() {
        use std::time::{Duration, Instant};

        let resource = url("https://mcp.example/api");
        let deadline = Instant::now() + Duration::from_secs(60);
        let credential =
            BoundBearerCredential::bind_with_expiry(resource.clone(), "expiring-secret", deadline)
                .unwrap();
        for credential in [credential.clone(), credential] {
            assert_eq!(credential.expires_at(), Some(deadline));
            assert_eq!(
                credential.authorization_at(&resource, deadline - Duration::from_nanos(1)),
                Some("Bearer expiring-secret".to_owned()),
            );
            assert_eq!(credential.authorization_at(&resource, deadline), None);
            assert_eq!(
                credential.authorization_at(&resource, deadline + Duration::from_nanos(1)),
                None
            );
            assert_eq!(
                credential.authorization_at(
                    &url("https://other.example/api"),
                    deadline - Duration::from_secs(1)
                ),
                None
            );
        }
        let expired =
            BoundBearerCredential::bind_with_expiry(resource.clone(), "expired", Instant::now())
                .unwrap();
        assert_eq!(expired.authorization_for_target(&resource), None);
    }

    #[test]
    fn revocation_withholds_existing_and_future_clones_without_affecting_another_binding() {
        let resource = url("https://mcp.example/api");
        let credential = BoundBearerCredential::bind(resource.clone(), "shared-secret").unwrap();
        let clone = credential.clone();
        // Even identical token bytes do not create a process-global identity.
        let independent = BoundBearerCredential::bind(resource.clone(), "shared-secret").unwrap();
        for candidate in [&credential, &clone, &independent] {
            assert!(!candidate.is_revoked());
            assert_eq!(
                candidate.authorization_for_target(&resource),
                Some("Bearer shared-secret".to_owned())
            );
        }

        clone.revoke();
        clone.revoke();
        for candidate in [credential.clone(), clone.clone(), credential, clone] {
            assert!(candidate.is_revoked());
            assert_eq!(candidate.authorization_for_target(&resource), None);
            assert_eq!(candidate.resource(), &resource);
            assert_eq!(candidate.expires_at(), None);
            assert!(!format!("{candidate:?}").contains("shared-secret"));
        }
        assert!(!independent.is_revoked());
        assert_eq!(
            independent.authorization_for_target(&resource),
            Some("Bearer shared-secret".to_owned())
        );
    }

    #[test]
    fn revocation_does_not_depend_on_expiry_or_clone_drop() {
        use std::time::{Duration, Instant};

        let resource = url("https://mcp.example/api");
        let now = Instant::now();
        let deadline = now + Duration::from_secs(60);
        let credential =
            BoundBearerCredential::bind_with_expiry(resource.clone(), "secret", deadline).unwrap();
        drop(credential.clone());
        assert_eq!(
            credential.authorization_at(&resource, now),
            Some("Bearer secret".to_owned())
        );
        assert_eq!(credential.authorization_at(&resource, deadline), None);
        assert!(!credential.is_revoked(), "expiry is not local revocation");
        credential.revoke();
        assert_eq!(credential.authorization_at(&resource, now), None);
        assert_eq!(credential.expires_at(), Some(deadline));
    }

    #[test]
    fn revocation_is_visible_to_a_credential_moved_to_another_thread() {
        let resource = url("https://mcp.example/api");
        let credential = BoundBearerCredential::bind(resource.clone(), "secret").unwrap();
        let worker = credential.clone();
        let (revoked, observe) = std::sync::mpsc::channel();
        let thread = std::thread::spawn(move || {
            observe
                .recv_timeout(std::time::Duration::from_secs(5))
                .unwrap();
            assert!(worker.is_revoked());
            assert_eq!(worker.authorization_for_target(&resource), None);
        });
        credential.revoke();
        revoked.send(()).unwrap();
        thread.join().unwrap();
    }

    #[test]
    fn owner_cancellation_cannot_be_removed_by_cloning_or_reparenting() {
        use fastmcp_core::McpRequestCancellation;

        let resource = url("https://mcp.example/api");
        let source = BoundBearerCredential::bind(resource.clone(), "secret").unwrap();
        let owner = McpRequestCancellation::new();
        let other = McpRequestCancellation::new();
        let owned = source.for_owner(&owner).unwrap();
        let clone = owned.clone();
        assert!(owned.for_owner(&other).is_none());
        assert_eq!(
            owned.authorization_for_target(&resource),
            Some("Bearer secret".to_owned())
        );
        owner.cancel();
        for candidate in [&owned, &clone] {
            assert!(candidate.is_revoked());
            assert_eq!(candidate.authorization_for_target(&resource), None);
            assert!(candidate.for_owner(&other).is_none());
        }
        assert!(!source.is_revoked());
        assert_eq!(
            source.authorization_for_target(&resource),
            Some("Bearer secret".to_owned())
        );
        assert!(source.for_owner(&owner).unwrap().is_revoked());
    }

    #[test]
    fn token_revocation_survives_binding_to_a_new_owner() {
        use fastmcp_core::McpRequestCancellation;

        let resource = url("https://mcp.example/api");
        let source = BoundBearerCredential::bind(resource.clone(), "secret").unwrap();
        let owner = McpRequestCancellation::new();
        source.revoke();
        let owned = source.for_owner(&owner).unwrap();
        assert!(owned.is_revoked());
        assert_eq!(owned.authorization_for_target(&resource), None);
        assert!(!owner.is_cancel_requested());
    }

    #[test]
    fn bearer_alphabet_and_trailing_padding_round_trip_http_admission() {
        use std::time::{Duration, Instant};

        use fastmcp_core::AccessToken;

        let resource = url("https://mcp.example/api");
        let now = Instant::now();
        for token in ["A", "aZ09-._~+/", "abc=", "abc==", "a==="] {
            let candidates = [
                BoundBearerCredential::bind(resource.clone(), token).unwrap(),
                BoundBearerCredential::bind_with_expiry(
                    resource.clone(),
                    token,
                    now + Duration::from_secs(60),
                )
                .unwrap(),
            ];
            for credential in candidates {
                let header = credential.authorization_at(&resource, now).unwrap();
                assert_eq!(header, format!("Bearer {token}"));
                let parsed = AccessToken::parse(&header).unwrap();
                assert_eq!(parsed.scheme, "Bearer");
                assert_eq!(parsed.token, token);
            }
        }
    }

    #[test]
    fn both_bearer_constructors_refuse_invalid_grammar_without_repair() {
        use std::time::Instant;

        let resource = url("https://mcp.example/api");
        let deadline = Instant::now();
        // Delimiters and non-ASCII text can be ordinary header-value bytes,
        // but they are not Bearer token68 credentials. '=' is padding only.
        for token in [
            "secret:tail",
            "secret,tail",
            "secret;tail",
            "secret\"tail",
            "secret\\tail",
            "secret(tail)",
            "secret%20tail",
            "secret=tail",
            "=secret",
            "=",
            "secreté",
            "secret\u{a0}tail",
            " secret",
            "secret ",
            "secret\ttail",
            "secret\0tail",
        ] {
            for result in [
                BoundBearerCredential::bind(resource.clone(), token),
                BoundBearerCredential::bind_with_expiry(resource.clone(), token, deadline),
            ] {
                let error = result.expect_err("invalid credentials must fail during binding");
                assert_eq!(error, BearerBindingError::InvalidTokenBytes);
                assert!(!format!("{error:?} {error}").contains("secret"));
            }
        }
        assert_eq!(
            BoundBearerCredential::bind_with_expiry(resource, "", deadline).err(),
            Some(BearerBindingError::EmptyToken)
        );
    }

    #[test]
    fn bearer_byte_limit_includes_padding_in_both_constructors() {
        use std::time::{Duration, Instant};

        use fastmcp_core::{AccessToken, MAX_ACCESS_TOKEN_BYTES};

        let resource = url("https://mcp.example/api");
        let now = Instant::now();
        for padding in ["", "=="] {
            let exact = format!(
                "{}{padding}",
                "a".repeat(MAX_ACCESS_TOKEN_BYTES - padding.len())
            );
            let excessive = format!("a{exact}");
            assert_eq!(exact.len(), MAX_ACCESS_TOKEN_BYTES);
            assert_eq!(excessive.len(), MAX_ACCESS_TOKEN_BYTES + 1);
            for (token, accepted) in [(&exact, true), (&excessive, false)] {
                for result in [
                    BoundBearerCredential::bind(resource.clone(), token.as_str()),
                    BoundBearerCredential::bind_with_expiry(
                        resource.clone(),
                        token.as_str(),
                        now + Duration::from_secs(60),
                    ),
                ] {
                    if accepted {
                        let credential = result.unwrap();
                        let header = credential.authorization_at(&resource, now).unwrap();
                        assert_eq!(AccessToken::parse(&header).unwrap().token, *token);
                    } else {
                        assert_eq!(result.err(), Some(BearerBindingError::InvalidTokenBytes));
                    }
                }
            }
        }
    }

    #[test]
    fn native_request_headers_preserve_bound_tokens_and_resource_isolation() {
        use fastmcp_core::{AccessToken, MAX_ACCESS_TOKEN_BYTES};
        use fastmcp_protocol::FINAL_PROTOCOL_VERSION;

        use crate::http_executor::ModernHttpRequest;

        let resource = url("https://mcp.example/api");
        for token in [
            "aZ09-._~+/==".to_owned(),
            "a".repeat(MAX_ACCESS_TOKEN_BYTES),
        ] {
            let credential = BoundBearerCredential::bind(resource.clone(), token.clone()).unwrap();
            let make_request = |target| {
                ModernHttpRequest::new(
                    target,
                    b"{}".to_vec(),
                    FINAL_PROTOCOL_VERSION,
                    "tools/call",
                    None,
                )
                .unwrap()
                .with_authorization(&credential)
            };
            let request = make_request(resource.as_str());
            let mut headers = request
                .headers()
                .into_iter()
                .filter(|(name, _)| name.eq_ignore_ascii_case("authorization"));
            let (_, header) = headers
                .next()
                .expect("bound target receives its credential");
            assert!(headers.next().is_none());
            assert_eq!(AccessToken::parse(&header).unwrap().token, token);
            let other = make_request("https://mcp.example/other");
            assert!(
                other
                    .headers()
                    .iter()
                    .all(|(name, _)| !name.eq_ignore_ascii_case("authorization"))
            );
            credential.revoke();
            assert!(
                make_request(resource.as_str())
                    .headers()
                    .iter()
                    .all(|(name, _)| !name.eq_ignore_ascii_case("authorization"))
            );
        }
    }
}