agent-plugins 0.1.1

Sans-IO implementation of the Agent Plugins specification (agent-plugins.org): load, validate, and prepare agent plugins from any IO
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
//! The `mcp.json` configuration (§7.2): a closed union of transports.
//!
//! The spec models each server entry as "exactly one of a closed set of
//! variants" — which is to say, a Rust enum. [`McpServer`] carries only the
//! fields its transport defines, so an entry mixing stdio and HTTP fields is
//! unrepresentable here and is rejected during parsing, exactly as §7.2.1
//! demands.
//!
//! Failure boundaries follow §7.2.2: a top-level problem disables MCP for the
//! plugin ([`McpDisabledReason`]); a per-entry problem skips that one server
//! ([`ServerInvalid`]) and the rest keep loading.

use std::fmt;
use std::net::IpAddr;

use serde_json::{Map, Value};

use crate::diag::{Diagnostic, Origin, Rule};
use crate::manifest::SpecVersion;
use crate::path::{lexically_contained, RelativePath};
use crate::template::{Placeholder, Segment, Template};

/// The canonical `$schema` identifier for Agent Plugins 1.0.0 MCP
/// configuration (§7.2.1).
pub const MCP_SCHEMA_1_0_0: &str = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json";

/// A validated `mcp.json`: the servers that survived per-entry validation,
/// in declaration order.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct McpConfig {
    /// Valid server entries, in `mcpServers` declaration order.
    pub servers: Vec<ServerEntry>,
}

impl McpConfig {
    /// Look up a surviving server by its `mcpServers` member name.
    pub fn server(&self, name: &str) -> Option<&McpServer> {
        self.servers.iter().find(|entry| entry.name == name).map(|entry| &entry.server)
    }
}

/// One named server from `mcpServers`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ServerEntry {
    /// The `mcpServers` member name identifying this server.
    pub name: String,
    /// Its validated configuration.
    pub server: McpServer,
}

/// The closed union of §7.2.1 server variants, discriminated by `type`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum McpServer {
    /// `"type": "stdio"` — a local subprocess speaking MCP over stdio.
    Stdio(StdioServer),
    /// `"type": "streamable-http"` — the current MCP Streamable HTTP transport.
    StreamableHttp(RemoteServer),
    /// `"type": "sse"` — the deprecated HTTP+SSE transport (MCP 2024-11-05).
    Sse(RemoteServer),
}

impl McpServer {
    /// The transport this entry declares — the one a client MUST use for its
    /// initial connection attempt (§7.2.1).
    pub fn transport(&self) -> Transport {
        match self {
            Self::Stdio(_) => Transport::Stdio,
            Self::StreamableHttp(_) => Transport::StreamableHttp,
            Self::Sse(_) => Transport::Sse,
        }
    }
}

/// The three declared transports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Transport {
    /// Local subprocess over stdio.
    Stdio,
    /// MCP Streamable HTTP.
    StreamableHttp,
    /// Deprecated HTTP+SSE (MCP 2024-11-05).
    Sse,
}

impl fmt::Display for Transport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Stdio => "stdio",
            Self::StreamableHttp => "streamable-http",
            Self::Sse => "sse",
        })
    }
}

/// A stdio server: how to launch the subprocess (§7.2.1).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct StdioServer {
    /// The single executable token to launch.
    pub command: Command,
    /// Arguments, each subject to placeholder expansion (§9.2).
    pub args: Vec<Template>,
    /// Environment overlay, values subject to placeholder expansion (§9.2).
    /// Names `PLUGIN_ROOT` and `PLUGIN_DATA` are reserved and already
    /// rejected at parse time.
    pub env: Vec<(String, Template)>,
    /// Working directory; defaults to the plugin root when omitted.
    pub cwd: Cwd,
}

/// The `command` field: one executable token, never a shell string, never
/// expanded (§7.2.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    /// A bare executable name, resolved by the platform's search rules.
    /// Contains no path separators — a bare name is a *name*.
    Bare(String),
    /// A plugin-relative path to an executable bundled in the package.
    Bundled(RelativePath),
}

impl Command {
    /// The token exactly as configured.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Bare(name) => name,
            Self::Bundled(path) => path.as_str(),
        }
    }
}

/// The working directory of a stdio server, in the three permitted forms of
/// §7.2.1 — plus the default. Any other shape never becomes a `Cwd`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Cwd {
    /// `cwd` omitted, or exactly `${PLUGIN_ROOT}`: the plugin root.
    PluginRoot,
    /// A plugin-relative path beginning with `./`.
    Relative(RelativePath),
    /// `${PLUGIN_ROOT}/subpath`, the subpath lexically contained.
    RootAnchored(String),
    /// Exactly `${PLUGIN_DATA}`, or `${PLUGIN_DATA}/subpath` with the
    /// subpath lexically contained in the data directory.
    DataAnchored(String),
}

/// A remote server: Streamable HTTP or legacy SSE (§7.2.1).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RemoteServer {
    /// The validated MCP endpoint URL.
    pub url: McpUrl,
    /// Fixed literal headers, in declaration order. Never expanded, never a
    /// secret mechanism (§7.2.1).
    pub headers: Vec<(String, String)>,
}

/// An MCP endpoint URL that satisfied §7.2.1: absolute `http`/`https`, no
/// user information, no fragment, and `http` only toward loopback.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McpUrl {
    raw: String,
    https: bool,
    loopback: bool,
}

impl McpUrl {
    /// Validate an endpoint URL against §7.2.1.
    pub fn parse(raw: &str) -> Result<Self, UrlInvalid> {
        if raw.contains('#') {
            return Err(UrlInvalid::HasFragment);
        }
        let (https, after_scheme) = if let Some(rest) = strip_scheme(raw, "https://") {
            (true, rest)
        } else if let Some(rest) = strip_scheme(raw, "http://") {
            (false, rest)
        } else {
            return Err(UrlInvalid::NotHttp);
        };
        let authority_end = after_scheme.find(['/', '?']).unwrap_or(after_scheme.len());
        let authority = &after_scheme[..authority_end];
        if authority.contains('@') {
            return Err(UrlInvalid::HasUserInfo);
        }
        let host = host_of(authority).ok_or(UrlInvalid::NoHost)?;
        let loopback = is_loopback_host(&host);
        if !https && !loopback {
            return Err(UrlInvalid::PlainHttpBeyondLoopback);
        }
        Ok(Self { raw: raw.to_owned(), https, loopback })
    }

    /// The URL exactly as configured.
    pub fn as_str(&self) -> &str {
        &self.raw
    }

    /// Whether the scheme is `https`.
    pub fn is_https(&self) -> bool {
        self.https
    }

    /// Whether the host is `localhost` or a loopback IP literal.
    pub fn is_loopback(&self) -> bool {
        self.loopback
    }
}

impl fmt::Display for McpUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.raw)
    }
}

fn strip_scheme<'a>(raw: &'a str, scheme: &str) -> Option<&'a str> {
    (raw.len() >= scheme.len() && raw[..scheme.len()].eq_ignore_ascii_case(scheme))
        .then(|| &raw[scheme.len()..])
}

/// Extract the host from an authority, honoring IPv6 bracket syntax.
/// Returns `None` for an empty or malformed host.
fn host_of(authority: &str) -> Option<String> {
    if let Some(rest) = authority.strip_prefix('[') {
        let end = rest.find(']')?;
        let host = &rest[..end];
        let port = &rest[end + 1..];
        if !port.is_empty() && !port.strip_prefix(':')?.chars().all(|c| c.is_ascii_digit()) {
            return None;
        }
        return (!host.is_empty()).then(|| format!("[{host}]"));
    }
    let host = match authority.split_once(':') {
        Some((host, port)) => {
            if port.is_empty() || !port.chars().all(|c| c.is_ascii_digit()) {
                return None;
            }
            host
        }
        None => authority,
    };
    (!host.is_empty()).then(|| host.to_owned())
}

fn is_loopback_host(host: &str) -> bool {
    if host.eq_ignore_ascii_case("localhost") {
        return true;
    }
    let bare = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
    bare.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
}

/// Why a URL failed §7.2.1.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UrlInvalid {
    /// Not an absolute `http`/`https` URL.
    NotHttp,
    /// The URL carries user information.
    HasUserInfo,
    /// The URL carries a fragment.
    HasFragment,
    /// The URL has no usable host.
    NoHost,
    /// Plain `http` toward a non-loopback host.
    PlainHttpBeyondLoopback,
}

impl fmt::Display for UrlInvalid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NotHttp => "URL must be absolute http or https",
            Self::HasUserInfo => "URL must not contain user information",
            Self::HasFragment => "URL must not contain a fragment",
            Self::NoHost => "URL has no valid host",
            Self::PlainHttpBeyondLoopback => {
                "http is only permitted when the host is localhost or a loopback IP literal"
            }
        })
    }
}

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

/// Why MCP was disabled for the whole plugin (§7.2.2 rule 2, §6.2).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum McpDisabledReason {
    /// `mcp.json` exists but is not a regular file (§6.2).
    NotAFile,
    /// `mcp.json` resolves outside the plugin root (§4.1 rule 2).
    LocationEscapes,
    /// The IO source could not provide `mcp.json`.
    Unavailable {
        /// The source's explanation.
        detail: String,
    },
    /// `mcp.json` is not valid JSON.
    NotJson {
        /// The JSON parser's explanation.
        detail: String,
    },
    /// The document is valid JSON but not an object.
    NotAnObject,
    /// The required `$schema` field is missing or not a string.
    MissingSchema,
    /// `$schema` declares an unsupported version, or one that does not match
    /// the version declared by `plugin.json` (§10.1).
    SchemaMismatch {
        /// The `$schema` value `mcp.json` declared.
        declared: String,
    },
    /// A field other than `$schema` and `mcpServers` appears at the top level.
    UnexpectedField {
        /// The unexpected field.
        field: String,
    },
    /// The required `mcpServers` field is missing or not an object.
    MissingServers,
}

impl fmt::Display for McpDisabledReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAFile => f.write_str("mcp.json is not a regular file"),
            Self::LocationEscapes => f.write_str("mcp.json resolves outside the plugin root"),
            Self::Unavailable { detail } => write!(f, "mcp.json could not be read: {detail}"),
            Self::NotJson { detail } => write!(f, "mcp.json is not valid JSON: {detail}"),
            Self::NotAnObject => f.write_str("mcp.json must contain a top-level JSON object"),
            Self::MissingSchema => f.write_str("required field `$schema` is missing"),
            Self::SchemaMismatch { declared } => {
                write!(f, "`$schema` declares an unsupported or mismatched version: {declared}")
            }
            Self::UnexpectedField { field } => {
                write!(f, "unexpected top-level field `{field}` in a closed schema")
            }
            Self::MissingServers => {
                f.write_str("required field `mcpServers` is missing or not an object")
            }
        }
    }
}

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

/// Why one server entry was skipped (§7.2.2 rule 3).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ServerInvalid {
    /// The entry is not a JSON object.
    NotAnObject,
    /// The `type` field is missing or not a string.
    MissingType,
    /// The `type` value is not a variant this specification defines.
    UnknownType {
        /// The declared `type` value.
        declared: String,
    },
    /// A field outside the declared variant's closed set appears.
    ForeignField {
        /// The foreign field.
        field: String,
    },
    /// A field has the wrong JSON type.
    WrongType {
        /// The offending field.
        field: &'static str,
        /// What the specification requires there.
        expected: &'static str,
    },
    /// `command` is empty, or a bare name containing path separators.
    NotAToken {
        /// The configured command.
        command: String,
    },
    /// A plugin-relative `command` escapes the plugin root.
    CommandEscapes,
    /// `cwd` matches none of the three permitted forms, or escapes its anchor.
    BadCwd {
        /// The configured working directory.
        cwd: String,
    },
    /// `env` names a reserved variable (§9.2).
    ReservedEnv {
        /// The reserved name: `PLUGIN_ROOT` or `PLUGIN_DATA`.
        name: String,
    },
    /// A header name is not a valid HTTP field name.
    BadHeaderName {
        /// The offending header name.
        name: String,
    },
    /// A header value is not a valid HTTP field value.
    BadHeaderValue {
        /// The header whose value is invalid.
        name: String,
    },
    /// The same header name appears more than once under different casing.
    DuplicateHeader {
        /// The duplicated header name (first spelling seen).
        name: String,
    },
    /// The endpoint URL failed §7.2.1.
    BadUrl(UrlInvalid),
}

impl fmt::Display for ServerInvalid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAnObject => f.write_str("server entry must be a JSON object"),
            Self::MissingType => f.write_str("required field `type` is missing"),
            Self::UnknownType { declared } => write!(f, "unknown transport type {declared:?}"),
            Self::ForeignField { field } => {
                write!(f, "field `{field}` does not belong to this transport variant")
            }
            Self::WrongType { field, expected } => {
                write!(f, "field `{field}` must be {expected}")
            }
            Self::NotAToken { command } => write!(
                f,
                "`command` {command:?} must be a single bare executable name or a `./` path"
            ),
            Self::CommandEscapes => f.write_str("`command` resolves outside the plugin root"),
            Self::BadCwd { cwd } => write!(
                f,
                "`cwd` {cwd:?} must be `./…`, `${{PLUGIN_ROOT}}[/…]`, or `${{PLUGIN_DATA}}[/…]` \
                 and stay inside its anchor"
            ),
            Self::ReservedEnv { name } => {
                write!(f, "`env` must not set reserved variable `{name}` (§9.2)")
            }
            Self::BadHeaderName { name } => write!(f, "invalid HTTP header name {name:?}"),
            Self::BadHeaderValue { name } => write!(f, "invalid value for HTTP header {name:?}"),
            Self::DuplicateHeader { name } => {
                write!(f, "header {name:?} appears more than once (names are case-insensitive)")
            }
            Self::BadUrl(err) => write!(f, "invalid endpoint URL: {err}"),
        }
    }
}

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

impl McpConfig {
    /// Parse and validate an `mcp.json` document against the version declared
    /// by `plugin.json` (§7.2, §10.1).
    ///
    /// A top-level problem disables MCP entirely (`Err`); per-entry problems
    /// skip only that server and are returned as diagnostics alongside the
    /// surviving configuration.
    pub fn parse(
        bytes: &[u8],
        manifest_spec: SpecVersion,
    ) -> Result<(Self, Vec<Diagnostic>), McpDisabledReason> {
        let document: Value = serde_json::from_slice(bytes)
            .map_err(|e| McpDisabledReason::NotJson { detail: e.to_string() })?;
        let Value::Object(object) = document else {
            return Err(McpDisabledReason::NotAnObject);
        };

        match object.get("$schema") {
            Some(Value::String(id)) => {
                // §10.1: the MCP `$schema` must declare the same Agent
                // Plugins version as `plugin.json`. With one recognized
                // version, that means exactly this identifier.
                let matches = match manifest_spec {
                    SpecVersion::V1_0_0 => id == MCP_SCHEMA_1_0_0,
                };
                if !matches {
                    return Err(McpDisabledReason::SchemaMismatch { declared: id.clone() });
                }
            }
            _ => return Err(McpDisabledReason::MissingSchema),
        }

        if let Some(field) = object.keys().find(|k| *k != "$schema" && *k != "mcpServers") {
            return Err(McpDisabledReason::UnexpectedField { field: field.clone() });
        }

        let Some(Value::Object(members)) = object.get("mcpServers") else {
            return Err(McpDisabledReason::MissingServers);
        };

        let mut servers = Vec::new();
        let mut diagnostics = Vec::new();
        for (name, value) in members {
            match parse_server(value) {
                Ok(server) => servers.push(ServerEntry { name: name.clone(), server }),
                Err(why) => diagnostics.push(Diagnostic::new(
                    Rule::ServerSkipped,
                    Origin::Server(name.clone()),
                    why.to_string(),
                )),
            }
        }
        Ok((Self { servers }, diagnostics))
    }
}

fn parse_server(value: &Value) -> Result<McpServer, ServerInvalid> {
    let Value::Object(fields) = value else {
        return Err(ServerInvalid::NotAnObject);
    };
    let declared = match fields.get("type") {
        Some(Value::String(t)) => t.as_str(),
        Some(_) => return Err(ServerInvalid::WrongType { field: "type", expected: "a string" }),
        None => return Err(ServerInvalid::MissingType),
    };
    match declared {
        "stdio" => parse_stdio(fields).map(McpServer::Stdio),
        "streamable-http" => parse_remote(fields).map(McpServer::StreamableHttp),
        "sse" => parse_remote(fields).map(McpServer::Sse),
        other => Err(ServerInvalid::UnknownType { declared: other.to_owned() }),
    }
}

fn parse_stdio(fields: &Map<String, Value>) -> Result<StdioServer, ServerInvalid> {
    for field in fields.keys() {
        if !matches!(field.as_str(), "type" | "command" | "args" | "env" | "cwd") {
            return Err(ServerInvalid::ForeignField { field: field.clone() });
        }
    }

    let command = match fields.get("command") {
        Some(Value::String(raw)) => parse_command(raw)?,
        Some(_) => return Err(ServerInvalid::WrongType { field: "command", expected: "a string" }),
        None => return Err(ServerInvalid::WrongType { field: "command", expected: "present" }),
    };

    let args = match fields.get("args") {
        None => Vec::new(),
        Some(Value::Array(items)) => items
            .iter()
            .map(|item| match item {
                Value::String(s) => Ok(Template::parse(s)),
                _ => {
                    Err(ServerInvalid::WrongType { field: "args", expected: "an array of strings" })
                }
            })
            .collect::<Result<_, _>>()?,
        Some(_) => {
            return Err(ServerInvalid::WrongType { field: "args", expected: "an array of strings" })
        }
    };

    let env = match fields.get("env") {
        None => Vec::new(),
        Some(Value::Object(entries)) => {
            let mut env = Vec::with_capacity(entries.len());
            for (name, value) in entries {
                if name == "PLUGIN_ROOT" || name == "PLUGIN_DATA" {
                    return Err(ServerInvalid::ReservedEnv { name: name.clone() });
                }
                let Value::String(raw) = value else {
                    return Err(ServerInvalid::WrongType {
                        field: "env",
                        expected: "an object of strings",
                    });
                };
                env.push((name.clone(), Template::parse(raw)));
            }
            env
        }
        Some(_) => {
            return Err(ServerInvalid::WrongType { field: "env", expected: "an object of strings" })
        }
    };

    let cwd = match fields.get("cwd") {
        None => Cwd::PluginRoot,
        Some(Value::String(raw)) => parse_cwd(raw)?,
        Some(_) => return Err(ServerInvalid::WrongType { field: "cwd", expected: "a string" }),
    };

    Ok(StdioServer { command, args, env, cwd })
}

/// §7.2.1: `command` is one executable token — a bare name (no separators)
/// or a plugin-relative `./` path. Never a shell string, never expanded.
fn parse_command(raw: &str) -> Result<Command, ServerInvalid> {
    if raw.starts_with("./") {
        return RelativePath::parse(raw)
            .map(Command::Bundled)
            .map_err(|_| ServerInvalid::CommandEscapes);
    }
    if raw.is_empty() || raw.contains('/') || raw.contains('\\') {
        return Err(ServerInvalid::NotAToken { command: raw.to_owned() });
    }
    Ok(Command::Bare(raw.to_owned()))
}

/// §7.2.1: `cwd` has exactly three permitted forms. A placeholder anywhere
/// but the very start is none of them.
fn parse_cwd(raw: &str) -> Result<Cwd, ServerInvalid> {
    let bad = || ServerInvalid::BadCwd { cwd: raw.to_owned() };
    let template = Template::parse(raw);
    match template.segments() {
        [Segment::Literal(_)] => RelativePath::parse(raw).map(Cwd::Relative).map_err(|_| bad()),
        [Segment::Anchor(Placeholder::PluginRoot)] => Ok(Cwd::PluginRoot),
        [Segment::Anchor(Placeholder::PluginData)] => Ok(Cwd::DataAnchored(String::new())),
        [Segment::Anchor(anchor), Segment::Literal(rest)] => {
            let subpath = rest.strip_prefix('/').ok_or_else(bad)?;
            if !lexically_contained(subpath) {
                return Err(bad());
            }
            Ok(match anchor {
                Placeholder::PluginRoot => Cwd::RootAnchored(subpath.to_owned()),
                Placeholder::PluginData => Cwd::DataAnchored(subpath.to_owned()),
            })
        }
        _ => Err(bad()),
    }
}

fn parse_remote(fields: &Map<String, Value>) -> Result<RemoteServer, ServerInvalid> {
    for field in fields.keys() {
        if !matches!(field.as_str(), "type" | "url" | "headers") {
            return Err(ServerInvalid::ForeignField { field: field.clone() });
        }
    }
    let url = match fields.get("url") {
        Some(Value::String(raw)) => McpUrl::parse(raw).map_err(ServerInvalid::BadUrl)?,
        Some(_) => return Err(ServerInvalid::WrongType { field: "url", expected: "a string" }),
        None => return Err(ServerInvalid::WrongType { field: "url", expected: "present" }),
    };
    let headers = match fields.get("headers") {
        None => Vec::new(),
        Some(Value::Object(entries)) => {
            let mut headers: Vec<(String, String)> = Vec::with_capacity(entries.len());
            for (name, value) in entries {
                if !is_valid_header_name(name) {
                    return Err(ServerInvalid::BadHeaderName { name: name.clone() });
                }
                let Value::String(v) = value else {
                    return Err(ServerInvalid::WrongType {
                        field: "headers",
                        expected: "an object of strings",
                    });
                };
                if !is_valid_header_value(v) {
                    return Err(ServerInvalid::BadHeaderValue { name: name.clone() });
                }
                if headers.iter().any(|(seen, _)| seen.eq_ignore_ascii_case(name)) {
                    return Err(ServerInvalid::DuplicateHeader { name: name.clone() });
                }
                headers.push((name.clone(), v.clone()));
            }
            headers
        }
        Some(_) => {
            return Err(ServerInvalid::WrongType {
                field: "headers",
                expected: "an object of strings",
            })
        }
    };
    Ok(RemoteServer { url, headers })
}

/// RFC 9110 token characters, the legal alphabet of an HTTP field name.
fn is_valid_header_name(name: &str) -> bool {
    !name.is_empty()
        && name.bytes().all(|b| {
            b.is_ascii_alphanumeric()
                || matches!(
                    b,
                    b'!' | b'#'
                        | b'$'
                        | b'%'
                        | b'&'
                        | b'\''
                        | b'*'
                        | b'+'
                        | b'-'
                        | b'.'
                        | b'^'
                        | b'_'
                        | b'`'
                        | b'|'
                        | b'~'
                )
        })
}

/// An HTTP field value: no control characters other than horizontal tab.
fn is_valid_header_value(value: &str) -> bool {
    value.bytes().all(|b| b == b'\t' || (b != 0x7f && b >= 0x20))
}

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

    #[test]
    fn url_rules() {
        assert!(McpUrl::parse("https://deploy.example.com/mcp").is_ok());
        assert!(McpUrl::parse("http://localhost:8080/mcp").unwrap().is_loopback());
        assert!(McpUrl::parse("http://127.0.0.1/mcp").unwrap().is_loopback());
        assert!(McpUrl::parse("http://[::1]:9000/sse").unwrap().is_loopback());
        assert_eq!(
            McpUrl::parse("http://mcp.example.com/api"),
            Err(UrlInvalid::PlainHttpBeyondLoopback)
        );
        assert_eq!(McpUrl::parse("https://a:b@example.com/"), Err(UrlInvalid::HasUserInfo));
        assert_eq!(McpUrl::parse("https://example.com/api#frag"), Err(UrlInvalid::HasFragment));
        assert_eq!(McpUrl::parse("ftp://example.com/"), Err(UrlInvalid::NotHttp));
        assert_eq!(McpUrl::parse("https:///path"), Err(UrlInvalid::NoHost));
        // Loopback by IP range, not just 127.0.0.1 exactly.
        assert!(McpUrl::parse("http://127.8.9.1/x").unwrap().is_loopback());
    }

    #[test]
    fn command_rules() {
        assert_eq!(parse_command("npx"), Ok(Command::Bare("npx".into())));
        assert!(matches!(parse_command("./bin/server"), Ok(Command::Bundled(_))));
        assert!(matches!(parse_command("../bin/server"), Err(ServerInvalid::NotAToken { .. })));
        assert!(matches!(parse_command("bin/server"), Err(ServerInvalid::NotAToken { .. })));
        assert!(matches!(parse_command("./bin/../../server"), Err(ServerInvalid::CommandEscapes)));
        assert!(matches!(parse_command(""), Err(ServerInvalid::NotAToken { .. })));
    }

    #[test]
    fn cwd_forms() {
        assert!(matches!(parse_cwd("./data"), Ok(Cwd::Relative(_))));
        assert_eq!(parse_cwd("${PLUGIN_ROOT}"), Ok(Cwd::PluginRoot));
        assert_eq!(parse_cwd("${PLUGIN_ROOT}/x"), Ok(Cwd::RootAnchored("x".into())));
        assert_eq!(parse_cwd("${PLUGIN_DATA}"), Ok(Cwd::DataAnchored(String::new())));
        assert_eq!(parse_cwd("${PLUGIN_DATA}/x/y"), Ok(Cwd::DataAnchored("x/y".into())));
        assert!(parse_cwd("data").is_err());
        assert!(parse_cwd("${PLUGIN_ROOT}/../x").is_err());
        assert!(parse_cwd("./x/${PLUGIN_ROOT}").is_err());
        assert!(parse_cwd("${PLUGIN_ROOT}x").is_err());
    }
}