surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
//! "Check this address" (#47): what a remote MCP server asks of a client
//! before it answers, found without credentials, following the MCP
//! authorization specification (revision 2026-07-28,
//! <https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization>):
//!
//! 1. One MCP request to the address: a `server/discover` POST (Streamable
//!    HTTP), falling back to a legacy `initialize` POST when the answer is
//!    a `400`, `404` or `405` without a modern JSON-RPC error (the
//!    transport's backward compatibility rules); a `GET` expecting the
//!    `endpoint` event for an address whose path ends in `/sse` (the
//!    deprecated HTTP+SSE transport).
//! 2. A `401` (or a `403` with a challenge): the protected resource
//!    metadata (RFC 9728) from the `resource_metadata` of
//!    `WWW-Authenticate`, else the well-known URIs (path insertion, then
//!    the root), on the same host only.
//! 3. The first authorization server it names: its metadata (RFC 8414,
//!    then OpenID Connect Discovery, in the order the specification
//!    gives), whose `issuer` must be that server. `registration_endpoint`
//!    means dynamic client registration (RFC 7591, deprecated by MCP
//!    2026-07-28), `client_id_metadata_document_supported` means Client ID
//!    Metadata Documents.
//!
//! Outcomes: `oauth` (protected resource metadata found), `token` (asks
//! for credentials without OAuth metadata), `open` (answered MCP without
//! credentials), `unreachable`, `unexpected`, and `host_waiting` when the
//! user has not allowed the host (nothing is sent).
//!
//! Rules: `https://` only (`http://` only for `localhost`, `127.0.0.1`,
//! `::1`), no user name or password in the address, no cookies, no
//! credentials of any kind, 5 seconds per request and 20 for the whole
//! check, redirects followed only within the same scheme, host and port,
//! bodies capped. Proxies come from the injected [`Env`] as for catalogs.
//! Logs name the host only.

use std::io::Read;
use std::path::Path;
use std::time::{Duration, Instant};

use serde_json::{Value, json};
use ureq::tls::{RootCerts, TlsConfig};

use crate::catalog::http::proxy;
use crate::diagnostics::log;
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::local_settings::{AddressCheckHosts, LocalSettings};
use crate::model::server::Transport;
use crate::secrets::classify::classify_import;
use crate::server_input::transport_from_url;

/// Longest wait for one request.
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
/// Longest wait for the whole check.
pub const CHECK_TIMEOUT: Duration = Duration::from_secs(20);
/// The protocol revision of the modern request.
pub const PROTOCOL_VERSION: &str = "2026-07-28";
/// The revision a legacy `initialize` asks for.
pub const LEGACY_PROTOCOL_VERSION: &str = "2025-11-25";
/// Largest body read from any answer.
const MAX_BODY: usize = 256 * 1024;
/// Same-origin redirects followed per request.
const MAX_REDIRECTS: usize = 3;

/// What the check found.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    /// The server signs in with OAuth (protected resource metadata).
    OAuth,
    /// The server asks for credentials, without OAuth metadata: a token in
    /// a header.
    Token,
    /// The server answered MCP without credentials.
    Open,
    /// No answer (host not found, connection refused, timeout, TLS).
    Unreachable,
    /// An answer that is none of the above.
    Unexpected,
    /// The user has not allowed this host; nothing was sent.
    HostWaiting,
}

impl Outcome {
    pub const fn as_str(self) -> &'static str {
        match self {
            Outcome::OAuth => "oauth",
            Outcome::Token => "token",
            Outcome::Open => "open",
            Outcome::Unreachable => "unreachable",
            Outcome::Unexpected => "unexpected",
            Outcome::HostWaiting => "host_waiting",
        }
    }
}

/// The OAuth details of an [`Outcome::OAuth`] server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthInfo {
    /// The authorization server's identifier (issuer URL).
    pub authorization_server: String,
    /// Its metadata has a `registration_endpoint` (RFC 7591).
    pub dynamic_registration: bool,
    /// Its metadata says `client_id_metadata_document_supported`.
    pub client_id_metadata_document: bool,
    /// The authorization server's metadata was read: the two flags above
    /// are known (otherwise both are `false` for "not known").
    pub registration_known: bool,
}

impl OAuthInfo {
    /// A client can register itself (either way), so signing in needs no
    /// client id from the user.
    pub fn registration_supported(&self) -> bool {
        self.dynamic_registration || self.client_id_metadata_document
    }
}

/// The result of a check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddressCheck {
    pub outcome: Outcome,
    /// The host (with a non-default port) the check contacts.
    pub host: String,
    /// The HTTP status of the MCP request's answer, when there was one.
    pub status: Option<u16>,
    pub oauth: Option<OAuthInfo>,
    /// What happened, in English (no secret: the check sends none).
    pub detail: String,
}

/// The user's answer for a host.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostConsent {
    Allowed,
    Denied,
    Unanswered,
}

/// `url` checked against the rules (see the module docs): `invalid_value`
/// when it breaks one.
pub fn checked_url(url: &str) -> Result<url::Url, CoreError> {
    let invalid = |why: &str| CoreError::new(ErrorCode::InvalidValue, why.to_owned());
    let parsed = url::Url::parse(url.trim())
        .map_err(|_| invalid("the address is not a URL; use https://host/path"))?;
    if !matches!(parsed.scheme(), "http" | "https") || parsed.host().is_none() {
        return Err(invalid("the address must start with https://"));
    }
    if !parsed.username().is_empty() || parsed.password().is_some() {
        return Err(invalid(
            "the address holds a user name or password; remove it (the check sends no credentials)",
        ));
    }
    if parsed.scheme() == "http" && !is_loopback(&parsed) {
        return Err(invalid(
            "the check uses https:// only (http:// only for localhost, 127.0.0.1 and ::1)",
        ));
    }
    let flagged = url.contains("${")
        || classify_import(None, url.trim()).is_some()
        || parsed
            .query_pairs()
            .any(|(key, value)| classify_import(Some(&key), &value).is_some());
    if flagged {
        return Err(invalid(
            "the address holds what looks like a credential or a reference (${...}); remove it \
             first: the check sends no credentials",
        ));
    }
    Ok(parsed)
}

fn is_loopback(url: &url::Url) -> bool {
    match url.host() {
        Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
        None => false,
    }
}

/// The host consent is asked for: the host in lower case, with its port
/// when it is not the scheme's default (`localhost:8080`, `[::1]:3000`).
pub fn host_key(url: &url::Url) -> String {
    let host = match url.host() {
        Some(url::Host::Ipv6(ip)) => format!("[{ip}]"),
        Some(host) => host.to_string().to_ascii_lowercase(),
        None => String::new(),
    };
    match url.port() {
        Some(port) => format!("{host}:{port}"),
        None => host,
    }
}

fn hosts_of(settings: &LocalSettings) -> AddressCheckHosts {
    settings.address_check_hosts.clone().unwrap_or_default()
}

/// The user's answer for `host` on this machine.
pub fn consent(fs: &dyn Fs, state_dir: &Path, host: &str) -> Result<HostConsent, CoreError> {
    let hosts = hosts_of(&LocalSettings::load(fs, state_dir)?);
    Ok(if hosts.allowed.iter().any(|h| h == host) {
        HostConsent::Allowed
    } else if hosts.denied.iter().any(|h| h == host) {
        HostConsent::Denied
    } else {
        HostConsent::Unanswered
    })
}

/// Records the answer for `host` (machine-local, never synced); a new
/// answer replaces the old one.
pub fn answer_host(
    fs: &dyn Fs,
    state_dir: &Path,
    host: &str,
    allow: bool,
) -> Result<(), CoreError> {
    let host = host.trim().to_ascii_lowercase();
    if host.is_empty() || host.contains(['/', ' ']) {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!("{host:?} is not a host name"),
        ));
    }
    edit_hosts(fs, state_dir, |hosts| {
        hosts.allowed.retain(|h| *h != host);
        hosts.denied.retain(|h| *h != host);
        if allow {
            hosts.allowed.push(host.clone());
        } else {
            hosts.denied.push(host.clone());
        }
    })
}

/// Forgets the answer for `host`: the next check asks again. Unknown
/// hosts are fine.
pub fn clear_host(fs: &dyn Fs, state_dir: &Path, host: &str) -> Result<(), CoreError> {
    let host = host.trim().to_ascii_lowercase();
    edit_hosts(fs, state_dir, |hosts| {
        hosts.allowed.retain(|h| *h != host);
        hosts.denied.retain(|h| *h != host);
    })
}

fn edit_hosts(
    fs: &dyn Fs,
    state_dir: &Path,
    edit: impl FnOnce(&mut AddressCheckHosts),
) -> Result<(), CoreError> {
    let mut settings = LocalSettings::load(fs, state_dir)?;
    let mut hosts = hosts_of(&settings);
    let before = hosts.clone();
    edit(&mut hosts);
    if hosts == before {
        return Ok(());
    }
    settings.address_check_hosts =
        (!hosts.allowed.is_empty() || !hosts.denied.is_empty()).then_some(hosts);
    settings.save(fs, state_dir)
}

/// Every answered host and whether it is allowed, sorted by host.
pub fn hosts(fs: &dyn Fs, state_dir: &Path) -> Result<Vec<(String, bool)>, CoreError> {
    let hosts = hosts_of(&LocalSettings::load(fs, state_dir)?);
    let mut out: Vec<(String, bool)> = hosts
        .allowed
        .into_iter()
        .map(|h| (h, true))
        .chain(hosts.denied.into_iter().map(|h| (h, false)))
        .collect();
    out.sort();
    out.dedup_by(|a, b| a.0 == b.0);
    Ok(out)
}

/// Checks `url` (see the module docs) when the user allowed its host on
/// this machine; otherwise [`Outcome::HostWaiting`] and nothing is sent.
pub fn check(
    env: &Env,
    fs: &dyn Fs,
    state_dir: &Path,
    url: &str,
) -> Result<AddressCheck, CoreError> {
    let parsed = checked_url(url)?;
    let host = host_key(&parsed);
    match consent(fs, state_dir, &host)? {
        HostConsent::Allowed => {
            let denied = hosts_of(&LocalSettings::load(fs, state_dir)?).denied;
            Ok(probe(env, &parsed, REQUEST_TIMEOUT, CHECK_TIMEOUT, denied))
        }
        answer => Ok(AddressCheck {
            outcome: Outcome::HostWaiting,
            detail: if answer == HostConsent::Denied {
                format!("You chose not to check addresses on {host}. Allow it to check this one.")
            } else {
                format!("Checking sends a request to {host}. Allow it first.")
            },
            host,
            status: None,
            oauth: None,
        }),
    }
}

/// The check itself, with no consent lookup (`check` asks first);
/// `denied`: hosts not to contact for authorization server metadata.
pub fn probe(
    env: &Env,
    url: &url::Url,
    per_request: Duration,
    total: Duration,
    denied: Vec<String>,
) -> AddressCheck {
    let client = Client::new(
        env,
        per_request,
        Instant::now() + total,
        is_loopback(url),
        denied,
    );
    client.run(url)
}

/// An IP address in a private, link-local, loopback or unspecified range
/// (an authorization server there is not contacted from a public check).
fn is_private_ip(url: &url::Url) -> bool {
    match url.host() {
        Some(url::Host::Ipv4(ip)) => {
            ip.is_private() || ip.is_link_local() || ip.is_loopback() || ip.is_unspecified()
        }
        Some(url::Host::Ipv6(ip)) => {
            ip.is_loopback()
                || ip.is_unspecified()
                || ip.is_unique_local()
                || ip.is_unicast_link_local()
                || ip
                    .to_ipv4_mapped()
                    .is_some_and(|v4| v4.is_private() || v4.is_loopback())
        }
        Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
        None => false,
    }
}

/// An answer, with what the check reads of it.
#[derive(Debug, Default)]
struct Answer {
    status: u16,
    challenges: Vec<String>,
    content_type: String,
    body: Vec<u8>,
}

/// Why a request got no usable answer.
#[derive(Debug)]
enum Failure {
    /// No answer at all.
    Unreachable(String),
    /// A redirect off the origin, or another answer the check does not
    /// follow.
    Refused(String),
}

struct Client {
    https: ureq::Agent,
    loopback: ureq::Agent,
    https_problem: Option<String>,
    per_request: Duration,
    deadline: Instant,
    /// The address is a loopback one: an authorization server may be a
    /// loopback `http://` one too.
    local: bool,
    /// Hosts the user denied: an authorization server there is not read.
    denied: Vec<String>,
}

impl Client {
    fn new(
        env: &Env,
        per_request: Duration,
        deadline: Instant,
        local: bool,
        denied: Vec<String>,
    ) -> Self {
        let agent = |proxy: Option<ureq::Proxy>, https_only: bool| {
            ureq::Agent::config_builder()
                .http_status_as_error(false)
                .timeout_connect(Some(per_request))
                .timeout_global(Some(per_request))
                .https_only(https_only)
                .max_redirects(0)
                .user_agent(format!("Surjection/{}", env!("CARGO_PKG_VERSION")))
                .proxy(proxy)
                .tls_config(
                    TlsConfig::builder()
                        .root_certs(RootCerts::PlatformVerifier)
                        .build(),
                )
                .build()
                .new_agent()
        };
        let https = proxy(
            env,
            &["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"],
        );
        let (https_proxy, https_problem) = match https {
            Ok(proxy) => (proxy, None),
            Err(why) => (None, Some(why)),
        };
        Self {
            https: agent(https_proxy, true),
            // Loopback addresses never go through a proxy.
            loopback: agent(None, false),
            https_problem,
            per_request,
            deadline,
            local,
            denied,
        }
    }

    /// Whether `url` may be contacted at all: https, or loopback http.
    fn allowed(&self, url: &url::Url) -> bool {
        url.scheme() == "https" || (url.scheme() == "http" && is_loopback(url))
    }

    /// One request, following redirects within the origin. `body`: a POST
    /// of that JSON with `headers`; otherwise a GET.
    fn send(
        &self,
        url: &url::Url,
        body: Option<&Value>,
        headers: &[(&str, &str)],
    ) -> Result<Answer, Failure> {
        let mut current = url.clone();
        for _ in 0..=MAX_REDIRECTS {
            let (answer, location) = self.send_once(&current, body, headers)?;
            let redirect = matches!(answer.status, 301 | 302 | 303 | 307 | 308);
            let Some(location) = location.filter(|_| redirect) else {
                return Ok(answer);
            };
            let next = current
                .join(&location)
                .map_err(|_| Failure::Refused("it redirected to an invalid address".to_owned()))?;
            if next.origin() != current.origin() {
                return Err(Failure::Refused(format!(
                    "it redirected to another host ({}), which the check does not follow",
                    host_key(&next)
                )));
            }
            if body.is_some() && !matches!(answer.status, 307 | 308) {
                return Err(Failure::Refused(format!(
                    "it answered the request with a redirect ({})",
                    answer.status
                )));
            }
            current = next;
        }
        Err(Failure::Refused("too many redirects".to_owned()))
    }

    fn send_once(
        &self,
        url: &url::Url,
        body: Option<&Value>,
        headers: &[(&str, &str)],
    ) -> Result<(Answer, Option<String>), Failure> {
        if !self.allowed(url) {
            return Err(Failure::Refused(
                "the address must use https:// (http:// only for localhost)".to_owned(),
            ));
        }
        let remaining = self.deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Err(Failure::Unreachable("the check ran out of time".to_owned()));
        }
        let timeout = remaining.min(self.per_request);
        let agent = if url.scheme() == "http" {
            &self.loopback
        } else {
            if let Some(why) = &self.https_problem {
                return Err(Failure::Unreachable(why.clone()));
            }
            &self.https
        };
        let started = Instant::now();
        let result = match body {
            Some(body) => {
                let mut request = agent
                    .post(url.as_str())
                    .config()
                    .timeout_global(Some(timeout))
                    .build()
                    .header("Content-Type", "application/json");
                for (name, value) in headers {
                    request = request.header(*name, *value);
                }
                request.send(body.to_string())
            }
            None => {
                let mut request = agent
                    .get(url.as_str())
                    .config()
                    .timeout_global(Some(timeout))
                    .build();
                for (name, value) in headers {
                    request = request.header(*name, *value);
                }
                request.call()
            }
        };
        let response = match result {
            Ok(response) => response,
            Err(err) => {
                let failure = transport_failure(err);
                log::http(
                    "address_check",
                    url.as_str(),
                    Err(&CoreError::new(ErrorCode::IoError, "no answer")),
                    started,
                );
                return Err(failure);
            }
        };
        let status = response.status().as_u16();
        log::http("address_check", url.as_str(), Ok(status), started);
        let header = |name: &str| {
            response
                .headers()
                .get_all(name)
                .iter()
                .filter_map(|value| value.to_str().ok().map(str::to_owned))
                .collect::<Vec<_>>()
        };
        let challenges = header("www-authenticate");
        let content_type = header("content-type")
            .into_iter()
            .next()
            .unwrap_or_default()
            .to_ascii_lowercase();
        let location = header("location").into_iter().next();
        let stream = content_type.starts_with("text/event-stream");
        let body = read_body(response.into_body().into_reader(), stream);
        Ok((
            Answer {
                status,
                challenges,
                content_type,
                body,
            },
            location,
        ))
    }

    fn run(&self, url: &url::Url) -> AddressCheck {
        let host = host_key(url);
        let result = |outcome, status, oauth, detail: String| AddressCheck {
            outcome,
            host: host.clone(),
            status,
            oauth,
            detail,
        };
        let sse = transport_from_url(url.as_str()) == Transport::Sse;
        let first = if sse {
            self.send(url, None, &[("Accept", "text/event-stream")])
        } else {
            self.send(url, Some(&discover_request()), &MODERN_HEADERS)
        };
        let answer = match first {
            Ok(answer) => answer,
            Err(Failure::Unreachable(why)) => {
                return result(
                    Outcome::Unreachable,
                    None,
                    None,
                    format!("{host} could not be reached: {why}."),
                );
            }
            Err(Failure::Refused(why)) => {
                return result(
                    Outcome::Unexpected,
                    None,
                    None,
                    format!("Not checked: {why}."),
                );
            }
        };
        if let Some(check) = self.classify(url, &answer, sse) {
            return check;
        }
        // The legacy fallback of Streamable HTTP: a 400, 404 or 405 that is
        // not a modern JSON-RPC error.
        if !sse && matches!(answer.status, 400 | 404 | 405) && !modern_error(&answer) {
            let legacy = self.send(url, Some(&initialize_request()), &LEGACY_HEADERS);
            match legacy {
                Ok(legacy) => {
                    if let Some(check) = self.classify(url, &legacy, false) {
                        return check;
                    }
                    return result(
                        Outcome::Unexpected,
                        Some(legacy.status),
                        None,
                        format!(
                            "{host} answered {} to an MCP request, without asking for credentials. \
                             Check the address (the path too).",
                            legacy.status
                        ),
                    );
                }
                Err(Failure::Unreachable(why)) => {
                    return result(
                        Outcome::Unreachable,
                        None,
                        None,
                        format!("{host} could not be reached: {why}."),
                    );
                }
                Err(Failure::Refused(why)) => {
                    return result(
                        Outcome::Unexpected,
                        Some(answer.status),
                        None,
                        format!("Not checked: {why}."),
                    );
                }
            }
        }
        result(
            Outcome::Unexpected,
            Some(answer.status),
            None,
            format!(
                "{host} answered {} to an MCP request, without asking for credentials. Check the \
                 address (the path too).",
                answer.status
            ),
        )
    }

    /// The outcome an answer gives: sign-in (`401`, or `403` with a
    /// challenge), or an MCP answer; `None` for anything else.
    fn classify(&self, url: &url::Url, answer: &Answer, sse: bool) -> Option<AddressCheck> {
        let host = host_key(url);
        if answer.status == 401 || (answer.status == 403 && !answer.challenges.is_empty()) {
            return Some(self.sign_in(url, answer));
        }
        let answered = if sse {
            (200..300).contains(&answer.status) && sse_endpoint(&answer.body)
        } else {
            ((200..300).contains(&answer.status) && json_rpc_answer(answer).is_some())
                || modern_error(answer)
        };
        answered.then(|| {
            let name = json_rpc_answer(answer)
                .as_ref()
                .and_then(server_name)
                .map(|name| format!(" ({name})"))
                .unwrap_or_default();
            AddressCheck {
                outcome: Outcome::Open,
                host: host.clone(),
                status: Some(answer.status),
                oauth: None,
                detail: format!("{host} answered as an MCP server{name} without credentials."),
            }
        })
    }

    /// A `401`/`403`: OAuth when protected resource metadata is found,
    /// else a token.
    fn sign_in(&self, url: &url::Url, answer: &Answer) -> AddressCheck {
        let host = host_key(url);
        let challenge = Challenge::parse(&answer.challenges);
        let mut notes: Vec<String> = Vec::new();
        let mut candidates: Vec<url::Url> = Vec::new();
        if let Some(pointer) = &challenge.resource_metadata {
            match url.join(pointer) {
                Ok(target) if target.origin() == url.origin() => candidates.push(target),
                Ok(target) => notes.push(format!(
                    "its resource_metadata points to another host ({}), which the check does not \
                     contact",
                    host_key(&target)
                )),
                Err(_) => notes.push("its resource_metadata is not a valid address".to_owned()),
            }
        }
        candidates.extend(well_known(url, "oauth-protected-resource"));
        let metadata = candidates.iter().find_map(|candidate| {
            let answer = self
                .send(candidate, None, &[("Accept", "application/json")])
                .ok()?;
            let doc = json_body(&answer)?;
            let valid = (200..300).contains(&answer.status) && resource_matches(&doc, url);
            valid.then_some(doc)
        });
        let authorization_server = metadata.as_ref().and_then(|doc| {
            doc.get("authorization_servers")?
                .as_array()?
                .iter()
                .filter_map(Value::as_str)
                .next()
                .map(str::to_owned)
        });
        let status = Some(answer.status);
        let Some(authorization_server) = authorization_server else {
            let schemes = if challenge.schemes.is_empty() {
                String::new()
            } else {
                format!(" ({})", challenge.schemes.join(", "))
            };
            let notes = if notes.is_empty() {
                String::new()
            } else {
                format!(" Note: {}.", notes.join("; "))
            };
            return AddressCheck {
                outcome: Outcome::Token,
                host: host.clone(),
                status,
                oauth: None,
                detail: format!(
                    "{host} asks for credentials{schemes} and publishes no OAuth metadata: it \
                     needs a token, usually in an Authorization header kept as a secret.{notes}"
                ),
            };
        };
        let (info, detail) = self.authorization_server(&authorization_server);
        AddressCheck {
            outcome: Outcome::OAuth,
            host,
            status,
            oauth: Some(info),
            detail,
        }
    }

    /// The authorization server's metadata, tried in the specification's
    /// order; the first document whose `issuer` is the server counts.
    fn authorization_server(&self, issuer: &str) -> (OAuthInfo, String) {
        let mut info = OAuthInfo {
            authorization_server: issuer.to_owned(),
            dynamic_registration: false,
            client_id_metadata_document: false,
            registration_known: false,
        };
        let parsed = url::Url::parse(issuer).ok().filter(|parsed| {
            parsed.scheme() == "https"
                || (self.local && parsed.scheme() == "http" && is_loopback(parsed))
        });
        let Some(parsed) = parsed else {
            return (
                info,
                format!(
                    "Signs in with OAuth. Its authorization server ({issuer}) is not an https:// \
                     address, so the check did not read its metadata."
                ),
            );
        };
        let as_host = host_key(&parsed);
        if self.denied.contains(&as_host) {
            return (
                info,
                format!(
                    "Signs in with OAuth through {as_host}. You chose not to contact that host, \
                     so whether clients can register themselves is not known."
                ),
            );
        }
        if is_private_ip(&parsed) && !self.local {
            return (
                info,
                format!(
                    "Signs in with OAuth through {as_host}, a private address the check does not \
                     contact, so whether clients can register themselves is not known."
                ),
            );
        }
        let found = authorization_server_urls(&parsed)
            .into_iter()
            .find_map(|candidate| {
                let answer = self
                    .send(&candidate, None, &[("Accept", "application/json")])
                    .ok()?;
                let doc = json_body(&answer)?;
                let issued = doc.get("issuer").and_then(Value::as_str)?;
                ((200..300).contains(&answer.status) && same_identifier(issued, issuer))
                    .then_some(doc)
            });
        let Some(doc) = found else {
            return (
                info,
                format!(
                    "Signs in with OAuth through {as_host}. Its authorization server metadata \
                     could not be read, so whether clients can register themselves is not known."
                ),
            );
        };
        info.registration_known = true;
        info.dynamic_registration = doc
            .get("registration_endpoint")
            .and_then(Value::as_str)
            .is_some_and(|endpoint| !endpoint.is_empty());
        info.client_id_metadata_document = doc
            .get("client_id_metadata_document_supported")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        let how = match (info.client_id_metadata_document, info.dynamic_registration) {
            (true, true) => {
                "Clients can register themselves (Client ID Metadata Documents and dynamic client \
                 registration)."
            }
            (true, false) => "Clients can register themselves (Client ID Metadata Documents).",
            (false, true) => "Clients can register themselves (dynamic client registration).",
            (false, false) => {
                "It offers no self-registration: a client may need a client id from the server's \
                 owner."
            }
        };
        (
            info,
            format!(
                "Signs in with OAuth through {as_host}. {how} Each client signs in on its own."
            ),
        )
    }
}

const MODERN_HEADERS: [(&str, &str); 3] = [
    ("Accept", "application/json, text/event-stream"),
    ("MCP-Protocol-Version", PROTOCOL_VERSION),
    ("Mcp-Method", "server/discover"),
];

const LEGACY_HEADERS: [(&str, &str); 1] = [("Accept", "application/json, text/event-stream")];

fn client_info() -> Value {
    json!({"name": "Surjection", "version": env!("CARGO_PKG_VERSION")})
}

/// The modern request: `server/discover` with the per-request metadata.
fn discover_request() -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "server/discover",
        "params": {
            "_meta": {
                "io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
                "io.modelcontextprotocol/clientCapabilities": {},
                "io.modelcontextprotocol/clientInfo": client_info(),
            }
        }
    })
}

/// The legacy request: `initialize`.
fn initialize_request() -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": LEGACY_PROTOCOL_VERSION,
            "capabilities": {},
            "clientInfo": client_info(),
        }
    })
}

fn transport_failure(err: ureq::Error) -> Failure {
    let why = match err {
        ureq::Error::Timeout(_) => "it did not answer in time".to_owned(),
        ureq::Error::HostNotFound => "the host was not found".to_owned(),
        ureq::Error::ConnectionFailed => "the connection failed".to_owned(),
        ureq::Error::RequireHttpsOnly(_) => {
            return Failure::Refused("it needs an address without encryption".to_owned());
        }
        ureq::Error::Io(err) => format!("the connection failed ({})", err.kind()),
        other => format!("the secure connection failed or was cut ({other})"),
    };
    Failure::Unreachable(why)
}

/// The body, at most [`MAX_BODY`] bytes; for an event stream, only up to
/// the end of its first event (the stream may stay open).
fn read_body(mut reader: impl Read, stream: bool) -> Vec<u8> {
    let mut body = Vec::new();
    let mut buf = [0u8; 4096];
    while body.len() < MAX_BODY {
        match reader.read(&mut buf) {
            Ok(0) | Err(_) => break,
            Ok(n) => {
                body.extend_from_slice(&buf[..n.min(MAX_BODY - body.len())]);
                if stream && first_event(&body).is_some() {
                    break;
                }
            }
        }
    }
    body
}

/// The first complete event of an event stream that carries data: its
/// `event` name and its `data` lines joined. Events without data (the
/// "priming" event a server may send first: an `id` and an empty `data`)
/// are skipped.
fn first_event(body: &[u8]) -> Option<(String, String)> {
    let text = String::from_utf8_lossy(body).replace("\r\n", "\n");
    let mut event = String::new();
    let mut data: Vec<&str> = Vec::new();
    let mut lines = text.split('\n').peekable();
    while let Some(line) = lines.next() {
        if line.is_empty() {
            // Complete only when the blank line was read.
            if data.iter().any(|d| !d.is_empty()) {
                return Some((event, data.join("\n")));
            }
            event.clear();
            data.clear();
            continue;
        }
        lines.peek()?;
        if let Some(value) = line.strip_prefix("event:") {
            event = value.trim().to_owned();
        } else if let Some(value) = line.strip_prefix("data:") {
            data.push(value.strip_prefix(' ').unwrap_or(value));
        }
    }
    None
}

/// The JSON of an answer: the body, or the data of its first event.
fn json_body(answer: &Answer) -> Option<Value> {
    if answer.content_type.starts_with("text/event-stream") {
        let (_, data) = first_event(&answer.body)?;
        serde_json::from_str(&data).ok()
    } else {
        serde_json::from_slice(&answer.body).ok()
    }
}

/// A JSON-RPC 2.0 response (a result or an error) in the answer.
fn json_rpc_answer(answer: &Answer) -> Option<Value> {
    json_body(answer).filter(|doc| {
        doc.get("jsonrpc").and_then(Value::as_str) == Some("2.0")
            && (doc.get("result").is_some() || doc.get("error").is_some())
    })
}

/// A JSON-RPC error only a modern server sends: header mismatch,
/// missing capability, unsupported version, or method not found on a 404.
fn modern_error(answer: &Answer) -> bool {
    let code = json_rpc_answer(answer).and_then(|doc| doc.get("error")?.get("code")?.as_i64());
    match code {
        Some(-32022..=-32020) => true,
        Some(-32601) => answer.status == 404,
        _ => false,
    }
}

/// The server's name and version from a `server/discover` or
/// `initialize` result, shortened and printable.
fn server_name(doc: &Value) -> Option<String> {
    let result = doc.get("result")?;
    let info = result.get("serverInfo").or_else(|| {
        result
            .get("_meta")?
            .get("io.modelcontextprotocol/serverInfo")
    })?;
    let name = info.get("name")?.as_str()?;
    let version = info.get("version").and_then(Value::as_str);
    let text = match version {
        Some(version) => format!("{name} {version}"),
        None => name.to_owned(),
    };
    let clean: String = text.chars().filter(|c| !c.is_control()).take(80).collect();
    (!clean.trim().is_empty()).then_some(clean)
}

/// Whether an event stream begins with the HTTP+SSE `endpoint` event.
fn sse_endpoint(body: &[u8]) -> bool {
    first_event(body).is_some_and(|(event, _)| event == "endpoint")
}

/// The well-known metadata URIs for `url`: with the path inserted (when
/// it has one), then at the root.
fn well_known(url: &url::Url, suffix: &str) -> Vec<url::Url> {
    let path = url.path().trim_end_matches('/');
    let mut out = Vec::new();
    let mut base = url.clone();
    base.set_query(None);
    base.set_fragment(None);
    if !path.is_empty() {
        let mut inserted = base.clone();
        inserted.set_path(&format!("/.well-known/{suffix}{path}"));
        out.push(inserted);
    }
    let mut root = base;
    root.set_path(&format!("/.well-known/{suffix}"));
    out.push(root);
    out
}

/// The authorization server metadata URIs for issuer `issuer`, in the
/// order the MCP specification gives.
fn authorization_server_urls(issuer: &url::Url) -> Vec<url::Url> {
    let path = issuer.path().trim_end_matches('/');
    let mut base = issuer.clone();
    base.set_query(None);
    base.set_fragment(None);
    let at = |p: String| {
        let mut url = base.clone();
        url.set_path(&p);
        url
    };
    if path.is_empty() {
        vec![
            at("/.well-known/oauth-authorization-server".to_owned()),
            at("/.well-known/openid-configuration".to_owned()),
        ]
    } else {
        vec![
            at(format!("/.well-known/oauth-authorization-server{path}")),
            at(format!("/.well-known/openid-configuration{path}")),
            at(format!("{path}/.well-known/openid-configuration")),
        ]
    }
}

/// Whether protected resource metadata is for `url`: its `resource` is
/// the address, its origin, or a path prefix of it on the same origin
/// (RFC 9728 3.3, read leniently for the root well-known URI). A document
/// without `resource` is not used.
fn resource_matches(doc: &Value, url: &url::Url) -> bool {
    let Some(resource) = doc.get("resource").and_then(Value::as_str) else {
        return false;
    };
    let Ok(resource) = url::Url::parse(resource) else {
        return false;
    };
    if resource.origin() != url.origin() {
        return false;
    }
    let wanted = url.path().trim_end_matches('/');
    let given = resource.path().trim_end_matches('/');
    given.is_empty() || wanted == given || wanted.starts_with(&format!("{given}/"))
}

/// Issuer identifiers compared as the specification requires, a single
/// trailing `/` aside.
fn same_identifier(a: &str, b: &str) -> bool {
    a.trim_end_matches('/') == b.trim_end_matches('/')
}

/// What `WWW-Authenticate` says.
#[derive(Debug, Default, PartialEq, Eq)]
struct Challenge {
    /// Auth schemes, as given (`Bearer`, `Basic`).
    schemes: Vec<String>,
    resource_metadata: Option<String>,
}

impl Challenge {
    fn parse(headers: &[String]) -> Self {
        let mut challenge = Self::default();
        for header in headers {
            for piece in split_outside_quotes(header) {
                let piece = piece.trim();
                let (first, rest) = piece.split_once(' ').unwrap_or((piece, ""));
                let param = if first.contains('=') {
                    piece
                } else {
                    if !first.is_empty() && !challenge.schemes.iter().any(|s| s == first) {
                        challenge.schemes.push(first.to_owned());
                    }
                    rest.trim()
                };
                if let Some((name, value)) = param.split_once('=')
                    && name.trim().eq_ignore_ascii_case("resource_metadata")
                {
                    let value = value.trim().trim_matches('"').to_owned();
                    if !value.is_empty() && challenge.resource_metadata.is_none() {
                        challenge.resource_metadata = Some(value);
                    }
                }
            }
        }
        challenge
    }
}

/// `text` split at commas outside double quotes.
fn split_outside_quotes(text: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut start = 0;
    let mut quoted = false;
    let mut escaped = false;
    for (i, c) in text.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' if quoted => escaped = true,
            '"' => quoted = !quoted,
            ',' if !quoted => {
                out.push(&text[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    out.push(&text[start..]);
    out
}

#[cfg(test)]
mod tests;