Skip to main content

tuff_core/
manifest.rs

1use std::path::{Path, PathBuf};
2
3use serde::{Deserialize, Serialize};
4
5use crate::error::{Result, TuffError};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum CapabilityType {
10    Skill,
11    Tool,
12    Hook,
13    Policy,
14    /// An external MCP server Tuff wires into each harness's native MCP
15    /// config. Distinct from a `tool` with `implementation.mcp = true`,
16    /// whose server code Tuff ships itself.
17    #[serde(rename = "mcp-server")]
18    McpServer,
19}
20
21impl CapabilityType {
22    pub fn plural_dir(&self) -> &'static str {
23        match self {
24            Self::Skill => "skills",
25            Self::Tool => "tools",
26            Self::Hook => "hooks",
27            Self::Policy => "policies",
28            Self::McpServer => "mcp-servers",
29        }
30    }
31
32    pub fn as_str(&self) -> &'static str {
33        match self {
34            Self::Skill => "skill",
35            Self::Tool => "tool",
36            Self::Hook => "hook",
37            Self::Policy => "policy",
38            Self::McpServer => "mcp-server",
39        }
40    }
41
42    pub fn parse(s: &str) -> Option<Self> {
43        match s {
44            "skill" => Some(Self::Skill),
45            "tool" => Some(Self::Tool),
46            "hook" => Some(Self::Hook),
47            "policy" => Some(Self::Policy),
48            "mcp-server" | "mcp" => Some(Self::McpServer),
49            _ => None,
50        }
51    }
52}
53
54impl std::fmt::Display for CapabilityType {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.write_str(self.as_str())
57    }
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct CapabilityManifest {
62    pub id: String,
63    pub version: String,
64    #[serde(rename = "type")]
65    pub capability_type: CapabilityType,
66    pub description: String,
67    #[serde(default)]
68    pub files: Vec<String>,
69    #[serde(default)]
70    pub parameters: Option<serde_json::Value>,
71    #[serde(default)]
72    pub implementation: Option<ImplementationConfig>,
73    #[serde(default)]
74    pub hook: Option<HookConfig>,
75    #[serde(default)]
76    pub server: Option<McpServerConfig>,
77    /// The rules of a `type = "policy"` capability.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub policy: Option<crate::policy::PolicyConfig>,
80    #[serde(default)]
81    #[allow(dead_code)]
82    pub targets: Vec<String>,
83
84    #[serde(skip)]
85    pub root: PathBuf,
86}
87
88/// Declaration of an external MCP server (`type = "mcp-server"`).
89///
90/// Secrets never appear here: every `[server.env]` value must be an
91/// [`EnvRef`], and every `[server.headers]` value a [`HeaderRef`], naming
92/// the variable to read on the developer's machine, so a manifest can be
93/// committed and shared without leaking anything.
94#[derive(Debug, Clone, Serialize, Deserialize)]
95// The `Option` fields are skipped when absent. TOML has no null and its
96// serializer drops them anyway; JSON has one, and the lockfile is JSON, so
97// without the skip an absent `url` would be written as `"url": null`.
98pub struct McpServerConfig {
99    #[serde(default)]
100    pub transport: McpTransport,
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub command: Option<String>,
103    #[serde(default)]
104    pub args: Vec<String>,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub url: Option<String>,
107    #[serde(default)]
108    pub env: std::collections::BTreeMap<String, EnvRef>,
109    /// HTTP request headers, keyed by header name. Skipped when empty so a
110    /// server that declares none serializes byte-for-byte as it did before
111    /// headers existed, and no installed record drifts on upgrade.
112    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
113    pub headers: std::collections::BTreeMap<String, HeaderRef>,
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub metadata: Option<McpServerMetadata>,
116}
117
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "lowercase")]
120pub enum McpTransport {
121    #[default]
122    Stdio,
123    Http,
124}
125
126impl McpTransport {
127    pub fn as_str(&self) -> &'static str {
128        match self {
129            Self::Stdio => "stdio",
130            Self::Http => "http",
131        }
132    }
133}
134
135/// A reference to an environment variable on the machine running the
136/// harness. Deliberately the only shape an env value can take — a bare
137/// string literal is rejected at parse time.
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(deny_unknown_fields)]
140pub struct EnvRef {
141    pub from_env: String,
142}
143
144/// A reference to the environment variable holding one HTTP header's value.
145///
146/// Headers carry secrets at least as often as environment variables do, so
147/// they take the same reference-only shape: a literal string is rejected at
148/// parse time. `format` wraps the value, with `{}` standing for it, which
149/// is what `Authorization = "Bearer <token>"` needs; it defaults to the
150/// bare value.
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(deny_unknown_fields)]
153pub struct HeaderRef {
154    pub from_env: String,
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub format: Option<String>,
157}
158
159impl HeaderRef {
160    /// The header value to emit, given how this harness spells a reference
161    /// to the variable. The reference is substituted into `format`, so the
162    /// harness expands the variable and Tuff never sees the secret.
163    pub fn render(&self, value_reference: &str) -> String {
164        match &self.format {
165            Some(format) => format.replacen(FORMAT_PLACEHOLDER, value_reference, 1),
166            None => value_reference.to_string(),
167        }
168    }
169}
170
171/// The one substitution `format` understands.
172pub const FORMAT_PLACEHOLDER: &str = "{}";
173
174#[derive(Debug, Clone, Default, Serialize, Deserialize)]
175pub struct McpServerMetadata {
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub tools_summary: Option<String>,
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct ImplementationConfig {
182    pub language: String,
183    pub entrypoint: String,
184    #[serde(default)]
185    pub mcp: bool,
186    #[serde(default)]
187    pub runtime_deps: Vec<String>,
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
191pub struct HookConfig {
192    pub event: String,
193    pub command: String,
194    #[serde(default = "default_cwd")]
195    pub working_directory: String,
196}
197
198fn default_cwd() -> String {
199    ".".to_string()
200}
201
202impl CapabilityManifest {
203    /// The files this capability installs, each confirmed to be a regular
204    /// file inside the capability directory.
205    ///
206    /// Every entry in `files`, and a tool's entrypoint, is a path the
207    /// manifest's author chose, and a capability can come from anyone's
208    /// repository. Each is copied into the project under the harness
209    /// directory using the same relative path, so an entry that climbs out
210    /// with `..`, is absolute, or passes through a symbolic link would read
211    /// a file from outside the capability and write it outside the place
212    /// Tuff installs to. Those are refused, the same way pack members and
213    /// skill directories already refuse them.
214    pub fn source_files(&self) -> Result<Vec<PathBuf>> {
215        let mut paths = Vec::new();
216
217        for f in &self.files {
218            let path = contained_source_file(&self.root, f)?;
219            paths.push(path);
220        }
221
222        if self.capability_type == CapabilityType::Tool
223            && let Some(ref imp) = self.implementation
224        {
225            let ep_path = self.root.join(imp.entrypoint.trim_start_matches("./"));
226            if !paths.contains(&ep_path) && ep_path.exists() {
227                paths.push(contained_source_file(&self.root, &imp.entrypoint)?);
228            }
229        }
230
231        Ok(paths)
232    }
233
234    /// Each listed file with the path it installs under: its path in the
235    /// capability directory with one leading `src/` removed.
236    ///
237    /// The same file listed twice installs once. Two different files that
238    /// would install under the same path are refused: `check.sh` and
239    /// `src/check.sh` both install as `check.sh`, and writing both used to
240    /// keep whichever came last without saying so.
241    pub fn read_source_contents_with_names(&self) -> Result<Vec<(String, Vec<u8>)>> {
242        let mut installed: Vec<(String, PathBuf, Vec<u8>)> = Vec::new();
243        for p in self.source_files()? {
244            let rel = p
245                .strip_prefix(&self.root)
246                .unwrap_or(&p)
247                .to_string_lossy()
248                .replace('\\', "/");
249            let rel = rel.strip_prefix("src/").unwrap_or(&rel).to_string();
250            if let Some((_, first, _)) = installed.iter().find(|(name, _, _)| *name == rel) {
251                if *first == p {
252                    continue;
253                }
254                return Err(TuffError::refused(format!(
255                    "capability '{}' lists two files that would install as '{rel}': {} and {}",
256                    self.id,
257                    first.display(),
258                    p.display()
259                ))
260                .with_hint("rename one of them, or list only one"));
261            }
262            let content = std::fs::read(&p)?;
263            installed.push((rel, p, content));
264        }
265        Ok(installed
266            .into_iter()
267            .map(|(rel, _, content)| (rel, content))
268            .collect())
269    }
270}
271
272/// Resolve one manifest-listed path to a regular file inside `root`.
273///
274/// The entry must be relative, may start with `./`, and may not contain
275/// `..`, a root, or a platform prefix. No component along it may be a
276/// symbolic link, since a link is the other way to reach outside the
277/// directory while every component still looks plain.
278fn contained_source_file(root: &Path, entry: &str) -> Result<PathBuf> {
279    let trimmed = entry.trim_start_matches("./");
280    let relative = crate::pack::validate_relative_path(Path::new(trimmed)).map_err(|_| {
281        TuffError::refused(format!(
282            "capability source path must stay inside the capability directory: '{entry}'"
283        ))
284        .with_hint("list files by their path relative to tuff.toml, without '..' or a leading '/'")
285    })?;
286    let mut current = root.to_path_buf();
287    for component in relative.components() {
288        current.push(component);
289        match std::fs::symlink_metadata(&current) {
290            Ok(metadata) if metadata.file_type().is_symlink() => {
291                return Err(TuffError::refused(format!(
292                    "symbolic links are not allowed in capability sources: {}",
293                    current.display()
294                )));
295            }
296            Ok(_) => {}
297            Err(_) => {
298                return Err(TuffError::not_found(format!(
299                    "capability source file not found: {}",
300                    root.join(&relative).display()
301                )));
302            }
303        }
304    }
305    if !current.is_file() {
306        return Err(TuffError::usage(format!(
307            "capability source must be a file, not a directory: {}",
308            current.display()
309        )));
310    }
311    Ok(current)
312}
313
314/// Refuse a capability id that could name a directory outside where it
315/// belongs.
316///
317/// The id names the directory a capability is installed into and, when it
318/// is deleted, the directory Tuff removes: `<harness>/<kind>s/<id>`. Ids may
319/// be nested, `security/security-review` installs into a grouping directory
320/// and that is a supported layout, so the rule is not "no slashes". It is
321/// that every segment is a plain name: no `..` or `.`, no empty segment from
322/// a leading, trailing, or doubled `/`, no backslash, and no NUL. An id that
323/// breaks it would aim install and delete outside that directory, and a
324/// manifest from someone else's repository, or a lockfile committed to one,
325/// could then make `tuff delete` remove a directory outside the project.
326/// Every id Tuff accepts goes through here: manifest ids, name overrides,
327/// pack artifact members, and every name read back from a lockfile.
328pub fn validate_capability_id(id: &str) -> Result<()> {
329    let plain = !id.is_empty()
330        && id.trim() == id
331        && !id.contains(['\\', '\0'])
332        && id
333            .split('/')
334            .all(|segment| !segment.is_empty() && segment != "." && segment != "..");
335    if plain {
336        return Ok(());
337    }
338    Err(TuffError::refused(format!(
339        "capability id must be a relative path of plain names: '{}'",
340        id.escape_debug()
341    ))
342    .with_hint(
343        "use a name such as 'release-checklist' or 'security/review', without '..', '.', a leading '/', or '\\'",
344    ))
345}
346
347fn validate_non_empty(field: &str, value: &str) -> Result<()> {
348    if value.is_empty() {
349        return Err(TuffError::usage(format!(
350            "capability manifest field '{field}' must be a non-empty string"
351        )));
352    }
353    Ok(())
354}
355
356pub fn load_manifest(capability_dir: &Path) -> Result<CapabilityManifest> {
357    let manifest_path = capability_dir.join("tuff.toml");
358    if !manifest_path.exists() {
359        return Err(TuffError::not_found(format!(
360            "capability manifest not found: {}",
361            manifest_path.display()
362        )));
363    }
364
365    let raw = std::fs::read_to_string(&manifest_path)?;
366    let mut manifest = parse_manifest(&raw, &manifest_path)?;
367    manifest.root = capability_dir.to_path_buf();
368
369    validate_non_empty("id", &manifest.id)?;
370    validate_capability_id(&manifest.id)?;
371    validate_non_empty("version", &manifest.version)?;
372    validate_non_empty("type", &manifest.capability_type.to_string())?;
373    validate_non_empty("description", &manifest.description)?;
374
375    match manifest.capability_type {
376        CapabilityType::Skill => {
377            if manifest.files.is_empty() {
378                return Err(TuffError::usage(
379                    "skill capability 'files' must not be empty",
380                ));
381            }
382            manifest.source_files()?;
383        }
384        CapabilityType::Tool => {
385            if manifest.parameters.is_none() {
386                return Err(TuffError::usage(
387                    "tool capability requires a [parameters] section with JSON Schema",
388                ));
389            }
390            if manifest.implementation.is_none() {
391                return Err(TuffError::usage(
392                    "tool capability requires an [implementation] section",
393                ));
394            }
395
396            let params = manifest.parameters.as_ref().unwrap();
397            crate::tool::validate_json_schema(params)?;
398
399            let impl_cfg = manifest.implementation.as_ref().unwrap();
400            crate::tool::validate_entrypoint(&manifest.root, &impl_cfg.entrypoint)?;
401
402            if !impl_cfg.runtime_deps.is_empty() {
403                eprintln!(
404                    "note: this tool requires runtime dependencies: {}",
405                    impl_cfg.runtime_deps.join(", ")
406                );
407            }
408
409            if !manifest.files.is_empty() {
410                manifest.source_files()?;
411            }
412        }
413        CapabilityType::Hook => {
414            let hook_cfg = manifest
415                .hook
416                .as_ref()
417                .ok_or_else(|| TuffError::usage("hook capability requires a [hook] section"))?;
418
419            if hook_cfg.event.trim().is_empty() {
420                return Err(TuffError::usage("hook 'event' must be a non-empty string"));
421            }
422            if hook_cfg.command.trim().is_empty() {
423                return Err(TuffError::usage(
424                    "hook 'command' must be a non-empty string",
425                ));
426            }
427
428            crate::tool::check_path_traversal(&hook_cfg.working_directory)?;
429
430            eprintln!(
431                "note: this hook runs '{}' on event '{}' — it will not be executed during install",
432                hook_cfg.command, hook_cfg.event
433            );
434
435            if !manifest.files.is_empty() {
436                manifest.source_files()?;
437            }
438        }
439        CapabilityType::Policy => {
440            let policy = manifest.policy.as_ref().ok_or_else(|| {
441                TuffError::usage(
442                    "policy capability requires a [policy] section with at least one [[policy.rules]] entry",
443                )
444            })?;
445            crate::policy::validate_policy(policy)?;
446            if !manifest.files.is_empty() {
447                return Err(TuffError::usage(
448                    "a policy capability installs no files; remove `files` from its tuff.toml",
449                ));
450            }
451        }
452        CapabilityType::McpServer => {
453            let server = manifest.server.as_ref().ok_or_else(|| {
454                TuffError::usage("mcp-server capability requires a [server] section")
455            })?;
456            validate_mcp_server(server)?;
457
458            if !manifest.files.is_empty() {
459                manifest.source_files()?;
460            }
461        }
462    }
463
464    Ok(manifest)
465}
466
467pub fn validate_mcp_server(server: &McpServerConfig) -> Result<()> {
468    match server.transport {
469        McpTransport::Stdio => {
470            if server
471                .command
472                .as_deref()
473                .is_none_or(|c| c.trim().is_empty())
474            {
475                return Err(TuffError::usage(
476                    "mcp-server with transport = \"stdio\" requires a non-empty 'command'",
477                ));
478            }
479        }
480        McpTransport::Http => {
481            if server.url.as_deref().is_none_or(|u| u.trim().is_empty()) {
482                return Err(TuffError::usage(
483                    "mcp-server with transport = \"http\" requires a non-empty 'url'",
484                ));
485            }
486        }
487    }
488    for (name, reference) in &server.env {
489        if name.trim().is_empty() {
490            return Err(TuffError::usage("[server.env] keys must be non-empty"));
491        }
492        if reference.from_env.trim().is_empty() {
493            return Err(TuffError::usage(format!(
494                "[server.env] {name} must reference a variable: {name} = {{ from_env = \"VAR\" }}"
495            )));
496        }
497    }
498    validate_mcp_headers(server)?;
499    Ok(())
500}
501
502/// Headers belong to the request a harness makes, so they are meaningful
503/// only over HTTP; on a stdio server they would be silently dropped, which
504/// is exactly the quiet-success failure RFC-106 exists to remove.
505fn validate_mcp_headers(server: &McpServerConfig) -> Result<()> {
506    if !server.headers.is_empty() && server.transport != McpTransport::Http {
507        return Err(TuffError::usage(
508            "[server.headers] applies to transport = \"http\"; a stdio server passes \
509             secrets through [server.env]",
510        ));
511    }
512    for (name, reference) in &server.headers {
513        if name.trim().is_empty() {
514            return Err(TuffError::usage("[server.headers] keys must be non-empty"));
515        }
516        if reference.from_env.trim().is_empty() {
517            return Err(TuffError::usage(format!(
518                "[server.headers] {name} must reference a variable: \
519                 {name} = {{ from_env = \"VAR\" }}"
520            )));
521        }
522        if let Some(format) = &reference.format {
523            let placeholders = format.matches(FORMAT_PLACEHOLDER).count();
524            if placeholders != 1 {
525                let problem = if placeholders == 0 {
526                    "would discard the value"
527                } else {
528                    "would repeat the value"
529                };
530                return Err(TuffError::usage(format!(
531                    "[server.headers] {name}: format \"{format}\" {problem}"
532                ))
533                .with_hint("format must contain exactly one {} placeholder, as in \"Bearer {}\""));
534            }
535        }
536    }
537    Ok(())
538}
539
540/// Parse a manifest, turning serde's opaque "invalid type: string" failure
541/// for a literal `[server.env]` value into an error that says what to write
542/// instead.
543fn parse_manifest(raw: &str, manifest_path: &Path) -> Result<CapabilityManifest> {
544    toml::from_str(raw).map_err(|error: toml::de::Error| {
545        let message = error.to_string();
546        let looks_literal =
547            message.contains("invalid type: string") || message.contains("expected a table");
548        let literal_table = looks_literal
549            .then(|| {
550                ["[server.env]", "[server.headers]"]
551                    .into_iter()
552                    .find(|table| raw.contains(table))
553            })
554            .flatten();
555        if let Some(table) = literal_table {
556            let example = if table == "[server.headers]" {
557                "Authorization = { from_env = \"TOKEN\", format = \"Bearer {}\" }"
558            } else {
559                "NAME = { from_env = \"NAME\" }"
560            };
561            TuffError::usage(format!(
562                "invalid manifest at {}: {} values must be references, never \
563                 literals — write {} ({})",
564                manifest_path.display(),
565                table,
566                example,
567                message.trim()
568            ))
569        } else if message.contains("unknown variant `workflow`") {
570            TuffError::usage(format!(
571                "invalid manifest at {}: Tuff no longer has workflow capabilities",
572                manifest_path.display()
573            ))
574            .with_hint("install the skills, tools, and hooks the workflow listed on their own, or group them in a pack")
575        } else {
576            TuffError::from(error)
577        }
578    })
579}
580
581/// Writes a capability manifest as deterministic TOML.
582///
583/// # Errors
584///
585/// Returns an error when serialization or filesystem writing fails.
586pub fn write_manifest(path: &Path, manifest: &CapabilityManifest) -> Result<()> {
587    std::fs::write(path, toml::to_string_pretty(manifest)?)?;
588    Ok(())
589}
590
591/// The version a capability source declares for itself, if any: `version`
592/// in `tuff.toml`, else `version:` or `metadata.version:` in the `SKILL.md`
593/// frontmatter (RFC-101 tier 2). It is what the author wrote, not what was
594/// released: it may not change when the content does, which is why a
595/// release tag outranks it and the lockfile records which one it holds.
596pub fn declared_version(dir: &Path) -> Option<String> {
597    if dir.join("tuff.toml").is_file() {
598        return load_manifest(dir).ok().map(|manifest| manifest.version);
599    }
600    let skill = std::fs::read_to_string(dir.join("SKILL.md")).ok()?;
601    frontmatter_version(&skill)
602}
603
604/// Read a version out of `SKILL.md` frontmatter without a YAML parser: a
605/// top-level `version:` line, else `version:` indented under `metadata:`,
606/// which is where the Agent Skills specification puts it. Quotes are
607/// stripped; anything else is taken as written.
608pub fn frontmatter_version(skill: &str) -> Option<String> {
609    let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
610    if lines.next()?.trim() != "---" {
611        return None;
612    }
613    let mut in_metadata = false;
614    let mut nested = None;
615    for line in lines {
616        if line.trim() == "---" {
617            break;
618        }
619        let indented = line.starts_with([' ', '\t']);
620        if !indented {
621            in_metadata = line.trim_end() == "metadata:";
622            if let Some(value) = line.strip_prefix("version:") {
623                return frontmatter_scalar(value);
624            }
625            continue;
626        }
627        if in_metadata
628            && nested.is_none()
629            && let Some(value) = line.trim_start().strip_prefix("version:")
630        {
631            nested = frontmatter_scalar(value);
632        }
633    }
634    nested
635}
636
637/// The description a capability source declares for itself, if any:
638/// `description` in `tuff.toml`, else `description:` in the `SKILL.md`
639/// frontmatter, which is where the Agent Skills specification puts it.
640///
641/// Unlike a version, a description is prose that no command depends on, so
642/// an absent one is an empty line in a report rather than an error.
643pub fn declared_description(dir: &Path) -> Option<String> {
644    if dir.join("tuff.toml").is_file() {
645        return load_manifest(dir).ok().map(|manifest| manifest.description);
646    }
647    let skill = std::fs::read_to_string(dir.join("SKILL.md")).ok()?;
648    frontmatter_description(&skill)
649}
650
651/// Read a top-level `description:` out of `SKILL.md` frontmatter.
652///
653/// Only the top level, and only a single line: a folded or block scalar is
654/// left alone rather than half-read, because a description this misses is a
655/// blank cell, while one it mangles is a wrong cell.
656pub fn frontmatter_description(skill: &str) -> Option<String> {
657    let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
658    if lines.next()?.trim() != "---" {
659        return None;
660    }
661    for line in lines {
662        if line.trim() == "---" {
663            break;
664        }
665        if line.starts_with([' ', '\t']) {
666            continue;
667        }
668        if let Some(value) = line.strip_prefix("description:") {
669            return frontmatter_text(value);
670        }
671    }
672    None
673}
674
675/// Read a top-level `name:` out of `SKILL.md` frontmatter, the field the
676/// Agent Skills specification uses for a skill's identifier.
677pub fn frontmatter_name(skill: &str) -> Option<String> {
678    let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
679    if lines.next()?.trim() != "---" {
680        return None;
681    }
682    for line in lines {
683        if line.trim() == "---" {
684            break;
685        }
686        if line.starts_with([' ', '\t']) {
687            continue;
688        }
689        if let Some(value) = line.strip_prefix("name:") {
690            return frontmatter_scalar(value);
691        }
692    }
693    None
694}
695
696/// A frontmatter value that is allowed to contain spaces, unlike a version.
697fn frontmatter_text(value: &str) -> Option<String> {
698    let value = value.trim();
699    let value = value
700        .strip_prefix('"')
701        .and_then(|rest| rest.strip_suffix('"'))
702        .or_else(|| {
703            value
704                .strip_prefix('\'')
705                .and_then(|rest| rest.strip_suffix('\''))
706        })
707        .unwrap_or(value)
708        .trim();
709    // `>` and `|` open a multi-line scalar whose body is on the next lines.
710    if value.is_empty() || value.starts_with(['>', '|']) {
711        return None;
712    }
713    Some(value.to_string())
714}
715
716fn frontmatter_scalar(value: &str) -> Option<String> {
717    let value = value.trim();
718    let value = value
719        .strip_prefix('"')
720        .and_then(|rest| rest.strip_suffix('"'))
721        .or_else(|| {
722            value
723                .strip_prefix('\'')
724                .and_then(|rest| rest.strip_suffix('\''))
725        })
726        .unwrap_or(value)
727        .trim();
728    (!value.is_empty() && !value.contains(char::is_whitespace)).then(|| value.to_string())
729}
730
731pub fn synthetic_manifest(
732    skill_dir: &Path,
733    name: &str,
734    version: &str,
735) -> Result<CapabilityManifest> {
736    validate_capability_id(name)?;
737    let skill_file = skill_dir.join("SKILL.md");
738    if !skill_file.exists() {
739        return Err(TuffError::not_found(format!(
740            "skill entrypoint not found: {}",
741            skill_file.display()
742        )));
743    }
744    let mut files = Vec::new();
745    walk_skill_dir(skill_dir, "", &mut files)?;
746    files.sort();
747
748    Ok(CapabilityManifest {
749        id: name.to_string(),
750        version: version.to_string(),
751        capability_type: CapabilityType::Skill,
752        description: "Installed from git source.".to_string(),
753        files,
754        parameters: None,
755        implementation: None,
756        hook: None,
757        server: None,
758        policy: None,
759        targets: Vec::new(),
760        root: skill_dir.to_path_buf(),
761    })
762}
763
764fn walk_skill_dir(base: &Path, prefix: &str, files: &mut Vec<String>) -> Result<()> {
765    for entry in std::fs::read_dir(base)? {
766        let entry = entry?;
767        let path = entry.path();
768        let metadata = std::fs::symlink_metadata(&path)?;
769        if metadata.file_type().is_symlink() {
770            return Err(TuffError::refused(format!(
771                "symbolic links are not allowed in capability sources: {}",
772                path.display()
773            )));
774        }
775        let rel = if prefix.is_empty() {
776            entry.file_name().to_string_lossy().to_string()
777        } else {
778            format!("{}/{}", prefix, entry.file_name().to_string_lossy())
779        };
780        if metadata.is_dir() {
781            walk_skill_dir(&path, &rel, files)?;
782        } else if metadata.is_file() && rel != "tuff.toml" {
783            files.push(rel);
784        }
785    }
786    Ok(())
787}
788
789#[cfg(test)]
790mod tests {
791    use super::*;
792    use std::fs;
793    use tempfile::TempDir;
794
795    fn write_manifest(dir: &std::path::Path, content: &str) {
796        fs::write(dir.join("tuff.toml"), content).unwrap();
797    }
798
799    #[test]
800    fn frontmatter_name_reads_the_top_level_name_only() {
801        assert_eq!(
802            frontmatter_name("---\nname: pdf\ndescription: x\n---\n").as_deref(),
803            Some("pdf")
804        );
805        assert_eq!(
806            frontmatter_name("---\nname: \"quoted\"\n---\n").as_deref(),
807            Some("quoted")
808        );
809        assert_eq!(
810            frontmatter_name("---\nmetadata:\n  name: nested\n---\n"),
811            None
812        );
813        assert_eq!(frontmatter_name("# no frontmatter\nname: x\n"), None);
814    }
815
816    #[test]
817    fn frontmatter_version_reads_top_level_then_metadata() {
818        assert_eq!(
819            frontmatter_version("---\nname: x\nversion: 1.2.0\n---\n# X\n").as_deref(),
820            Some("1.2.0")
821        );
822        assert_eq!(
823            frontmatter_version("---\nname: x\nversion: \"1.2.0\"\n---\n").as_deref(),
824            Some("1.2.0")
825        );
826        // The Agent Skills specification nests it under `metadata`.
827        assert_eq!(
828            frontmatter_version(
829                "---\nname: x\nmetadata:\n  author: org\n  version: \"1.0\"\n---\n"
830            )
831            .as_deref(),
832            Some("1.0")
833        );
834        // Top level wins over nested when both are present.
835        assert_eq!(
836            frontmatter_version("---\nmetadata:\n  version: 0.9.0\nversion: 1.2.0\n---\n")
837                .as_deref(),
838            Some("1.2.0")
839        );
840        // A `version:` nested under some other key is not the skill's.
841        assert_eq!(
842            frontmatter_version("---\nname: x\nextra:\n  version: 3.0.0\n---\n"),
843            None
844        );
845        assert_eq!(
846            frontmatter_version("# no frontmatter\nversion: 1.0.0\n"),
847            None
848        );
849        assert_eq!(
850            frontmatter_version("---\nname: x\n---\nversion: 9.9.9\n"),
851            None
852        );
853        assert_eq!(frontmatter_version("---\nversion:\n---\n"), None);
854        assert_eq!(frontmatter_version("---\nversion: 1.2.0 beta\n---\n"), None);
855        assert_eq!(
856            frontmatter_version("---\r\nname: x\r\nversion: 2.0.0\r\n---\r\n").as_deref(),
857            Some("2.0.0")
858        );
859    }
860
861    #[test]
862    fn declared_description_reads_the_frontmatter_and_prefers_the_manifest() {
863        let tmp = TempDir::new().unwrap();
864        fs::write(
865            tmp.path().join("SKILL.md"),
866            "---\nname: x\ndescription: Reviews a diff for security problems.\n---\n# X\n",
867        )
868        .unwrap();
869        assert_eq!(
870            declared_description(tmp.path()).as_deref(),
871            Some("Reviews a diff for security problems.")
872        );
873
874        write_manifest(
875            tmp.path(),
876            r#"id = "x"
877version = "1.0.0"
878type = "skill"
879description = "From the manifest"
880files = ["SKILL.md"]
881"#,
882        );
883        assert_eq!(
884            declared_description(tmp.path()).as_deref(),
885            Some("From the manifest")
886        );
887    }
888
889    #[test]
890    fn a_multi_line_description_is_left_alone_rather_than_half_read() {
891        // A folded scalar's text is on the following lines, so reading the
892        // marker would record ">" as the description.
893        assert_eq!(
894            frontmatter_description("---\nname: x\ndescription: >\n  Long text here.\n---\n"),
895            None
896        );
897        // An indented `description:` belongs to some nested mapping, not to
898        // the skill.
899        assert_eq!(
900            frontmatter_description("---\nmetadata:\n  description: Nested.\n---\n"),
901            None
902        );
903        // No frontmatter at all is not an error.
904        assert_eq!(frontmatter_description("# Just a heading\n"), None);
905    }
906
907    #[test]
908    fn declared_version_prefers_the_manifest_over_the_frontmatter() {
909        let tmp = TempDir::new().unwrap();
910        fs::write(
911            tmp.path().join("SKILL.md"),
912            "---\nname: x\nversion: 2.0.0\n---\n# X\n",
913        )
914        .unwrap();
915        assert_eq!(declared_version(tmp.path()).as_deref(), Some("2.0.0"));
916        fs::write(
917            tmp.path().join("tuff.toml"),
918            "id = \"x\"\nversion = \"1.0.0\"\ntype = \"skill\"\ndescription = \"d\"\nfiles = [\"SKILL.md\"]\n",
919        )
920        .unwrap();
921        assert_eq!(declared_version(tmp.path()).as_deref(), Some("1.0.0"));
922
923        let bare = TempDir::new().unwrap();
924        fs::write(bare.path().join("SKILL.md"), "# no version\n").unwrap();
925        assert_eq!(declared_version(bare.path()), None);
926    }
927
928    #[test]
929    fn load_skill_manifest_succeeds() {
930        let tmp = TempDir::new().unwrap();
931        fs::create_dir_all(tmp.path().join("src")).unwrap();
932        fs::write(tmp.path().join("src").join("SKILL.md"), "# Skill").unwrap();
933        write_manifest(
934            tmp.path(),
935            r#"id = "test"
936version = "1.0.0"
937type = "skill"
938description = "A test skill"
939files = ["src/SKILL.md"]
940"#,
941        );
942        let m = load_manifest(tmp.path()).unwrap();
943        assert_eq!(m.id, "test");
944        assert_eq!(m.capability_type, CapabilityType::Skill);
945    }
946
947    #[test]
948    fn load_tool_manifest_succeeds() {
949        let tmp = TempDir::new().unwrap();
950        fs::write(tmp.path().join("run.sh"), "echo ok").unwrap();
951        write_manifest(
952            tmp.path(),
953            r#"id = "tool1"
954version = "1.0.0"
955type = "tool"
956description = "A test tool"
957files = ["run.sh"]
958
959[parameters]
960type = "object"
961required = ["x"]
962[parameters.properties.x]
963type = "string"
964description = "x"
965
966[implementation]
967language = "bash"
968entrypoint = "run.sh"
969"#,
970        );
971        let m = load_manifest(tmp.path()).unwrap();
972        assert_eq!(m.capability_type, CapabilityType::Tool);
973        assert!(m.implementation.is_some());
974    }
975
976    #[test]
977    fn load_hook_manifest_succeeds() {
978        let tmp = TempDir::new().unwrap();
979        write_manifest(
980            tmp.path(),
981            r#"id = "hook1"
982version = "1.0.0"
983type = "hook"
984description = "A test hook"
985
986[hook]
987event = "before_finish"
988command = "cargo test"
989"#,
990        );
991        let m = load_manifest(tmp.path()).unwrap();
992        assert_eq!(m.capability_type, CapabilityType::Hook);
993        assert!(m.hook.is_some());
994    }
995
996    #[test]
997    fn load_rejects_unsupported_type() {
998        let tmp = TempDir::new().unwrap();
999        write_manifest(
1000            tmp.path(),
1001            r#"id = "bad"
1002version = "1.0.0"
1003type = "unknown"
1004description = "Bad"
1005files = ["SKILL.md"]
1006"#,
1007        );
1008        assert!(load_manifest(tmp.path()).is_err());
1009    }
1010
1011    #[test]
1012    fn load_rejects_missing_manifest() {
1013        let tmp = TempDir::new().unwrap();
1014        assert!(load_manifest(tmp.path()).is_err());
1015    }
1016
1017    #[test]
1018    fn source_files_resolves_paths() {
1019        let tmp = TempDir::new().unwrap();
1020        fs::create_dir_all(tmp.path().join("src")).unwrap();
1021        fs::write(tmp.path().join("src").join("SKILL.md"), "skill").unwrap();
1022        let m = CapabilityManifest {
1023            id: "t".into(),
1024            version: "1.0".into(),
1025            capability_type: CapabilityType::Skill,
1026            description: "desc".into(),
1027            files: vec!["src/SKILL.md".into()],
1028            parameters: None,
1029            implementation: None,
1030            hook: None,
1031            server: None,
1032            policy: None,
1033            targets: vec![],
1034            root: tmp.path().to_path_buf(),
1035        };
1036        let files = m.source_files().unwrap();
1037        assert_eq!(files.len(), 1);
1038        assert!(files[0].ends_with("SKILL.md"));
1039    }
1040
1041    fn manifest_listing(root: &Path, files: &[&str]) -> CapabilityManifest {
1042        CapabilityManifest {
1043            id: "t".into(),
1044            version: "1.0".into(),
1045            capability_type: CapabilityType::Hook,
1046            description: "desc".into(),
1047            files: files.iter().map(|f| f.to_string()).collect(),
1048            parameters: None,
1049            implementation: None,
1050            hook: None,
1051            server: None,
1052            policy: None,
1053            targets: vec![],
1054            root: root.to_path_buf(),
1055        }
1056    }
1057
1058    #[test]
1059    fn source_files_refuse_a_path_that_climbs_out_of_the_capability() {
1060        // A capability from someone else's repository chooses these paths.
1061        // `../` would read a file beside the capability and, because the
1062        // relative path is reused for the destination, write it outside the
1063        // harness directory Tuff installs into.
1064        let tmp = TempDir::new().unwrap();
1065        let capability = tmp.path().join("capability");
1066        fs::create_dir_all(&capability).unwrap();
1067        fs::write(tmp.path().join("outside.txt"), "outside").unwrap();
1068        fs::write(capability.join("inside.txt"), "inside").unwrap();
1069
1070        for entry in [
1071            "../outside.txt",
1072            "sub/../../outside.txt",
1073            "./../outside.txt",
1074        ] {
1075            let error = manifest_listing(&capability, &["inside.txt", entry])
1076                .source_files()
1077                .unwrap_err();
1078            assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{entry}");
1079            assert!(
1080                error
1081                    .to_string()
1082                    .contains("must stay inside the capability directory"),
1083                "{entry}: {error}"
1084            );
1085        }
1086        let absolute = tmp.path().join("outside.txt");
1087        let error = manifest_listing(&capability, &[absolute.to_str().unwrap()])
1088            .source_files()
1089            .unwrap_err();
1090        assert_eq!(error.kind(), crate::error::ErrorKind::Refused);
1091    }
1092
1093    #[cfg(unix)]
1094    #[test]
1095    fn source_files_refuse_a_symbolic_link_anywhere_along_the_path() {
1096        let tmp = TempDir::new().unwrap();
1097        let capability = tmp.path().join("capability");
1098        let secrets = tmp.path().join("secrets");
1099        fs::create_dir_all(capability.join("docs")).unwrap();
1100        fs::create_dir_all(&secrets).unwrap();
1101        fs::write(secrets.join("key.txt"), "pretend secret").unwrap();
1102        std::os::unix::fs::symlink(secrets.join("key.txt"), capability.join("notes.md")).unwrap();
1103        std::os::unix::fs::symlink(&secrets, capability.join("docs").join("linked")).unwrap();
1104
1105        for entry in ["notes.md", "docs/linked/key.txt"] {
1106            let error = manifest_listing(&capability, &[entry])
1107                .source_files()
1108                .unwrap_err();
1109            assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{entry}");
1110            assert!(
1111                error.to_string().contains("symbolic links are not allowed"),
1112                "{entry}: {error}"
1113            );
1114        }
1115    }
1116
1117    #[test]
1118    fn source_files_accept_plain_nested_and_dot_slash_paths() {
1119        let tmp = TempDir::new().unwrap();
1120        fs::create_dir_all(tmp.path().join("src/lib")).unwrap();
1121        fs::write(tmp.path().join("src/lib/check.sh"), "x").unwrap();
1122        fs::write(tmp.path().join("run.sh"), "x").unwrap();
1123
1124        let files = manifest_listing(tmp.path(), &["./run.sh", "src/lib/check.sh"])
1125            .source_files()
1126            .unwrap();
1127        assert_eq!(
1128            files,
1129            vec![
1130                tmp.path().join("run.sh"),
1131                tmp.path().join("src/lib/check.sh")
1132            ]
1133        );
1134        let error = manifest_listing(tmp.path(), &["src"])
1135            .source_files()
1136            .unwrap_err();
1137        assert!(error.to_string().contains("must be a file"), "{error}");
1138    }
1139
1140    #[test]
1141    fn listed_files_that_install_to_the_same_path_are_refused_but_a_repeat_is_not() {
1142        let tmp = TempDir::new().unwrap();
1143        fs::create_dir_all(tmp.path().join("src")).unwrap();
1144        fs::write(tmp.path().join("check.sh"), "top").unwrap();
1145        fs::write(tmp.path().join("src/check.sh"), "src").unwrap();
1146
1147        let repeated = manifest_listing(tmp.path(), &["check.sh", "./check.sh", "check.sh"])
1148            .read_source_contents_with_names()
1149            .unwrap();
1150        assert_eq!(repeated, vec![("check.sh".to_string(), b"top".to_vec())]);
1151
1152        let error = manifest_listing(tmp.path(), &["check.sh", "src/check.sh"])
1153            .read_source_contents_with_names()
1154            .unwrap_err();
1155        assert_eq!(error.kind(), crate::error::ErrorKind::Refused);
1156        assert!(
1157            error.to_string().contains("would install as 'check.sh'"),
1158            "{error}"
1159        );
1160    }
1161
1162    #[test]
1163    fn source_files_rejects_missing_file() {
1164        let tmp = TempDir::new().unwrap();
1165        let m = CapabilityManifest {
1166            id: "t".into(),
1167            version: "1.0".into(),
1168            capability_type: CapabilityType::Skill,
1169            description: "desc".into(),
1170            files: vec!["src/MISSING.md".into()],
1171            parameters: None,
1172            implementation: None,
1173            hook: None,
1174            server: None,
1175            policy: None,
1176            targets: vec![],
1177            root: tmp.path().to_path_buf(),
1178        };
1179        assert!(m.source_files().is_err());
1180    }
1181
1182    #[test]
1183    fn a_capability_id_is_a_relative_path_of_plain_names() {
1184        // Nested ids are a supported layout (`tuff add skill <repo>
1185        // security/security-review`), so they must keep working.
1186        for id in [
1187            "release-checklist",
1188            "tuff-cli-guide",
1189            "a.b",
1190            "x_1",
1191            "...x",
1192            "security/security-review",
1193            "a/b/c",
1194        ] {
1195            assert!(validate_capability_id(id).is_ok(), "{id}");
1196        }
1197        for id in [
1198            "",
1199            ".",
1200            "..",
1201            "../victim",
1202            "../../victim",
1203            "a/../b",
1204            "a/..",
1205            "./a",
1206            "a/./b",
1207            "/abs",
1208            "a/",
1209            "a//b",
1210            "a\\b",
1211            "nul\0x",
1212            " padded",
1213            "padded ",
1214        ] {
1215            let error = validate_capability_id(id).unwrap_err();
1216            assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{id:?}");
1217        }
1218    }
1219
1220    #[test]
1221    fn a_manifest_with_an_escaping_id_is_refused_at_load() {
1222        let tmp = TempDir::new().unwrap();
1223        fs::write(
1224            tmp.path().join("tuff.toml"),
1225            "id = \"../../victim\"\ntype = \"hook\"\nversion = \"1.0.0\"\ndescription = \"d\"\n[hook]\nevent = \"stop\"\ncommand = \"true\"\n",
1226        )
1227        .unwrap();
1228        let error = load_manifest(tmp.path()).unwrap_err();
1229        assert!(
1230            error.to_string().contains("relative path of plain names"),
1231            "{error}"
1232        );
1233    }
1234
1235    #[test]
1236    fn a_policy_manifest_loads_and_refuses_files() {
1237        let tmp = TempDir::new().unwrap();
1238        let head = "id = \"guard\"\ntype = \"policy\"\nversion = \"1.0.0\"\ndescription = \"d\"\n";
1239        let rules =
1240            "[[policy.rules]]\neffect = \"deny\"\ncommand = [\"git\", \"push\", \"--force\"]\n";
1241        fs::write(tmp.path().join("tuff.toml"), format!("{head}{rules}")).unwrap();
1242        let manifest = load_manifest(tmp.path()).unwrap();
1243        assert_eq!(manifest.policy.unwrap().rules.len(), 1);
1244
1245        fs::write(tmp.path().join("tuff.toml"), head).unwrap();
1246        let error = load_manifest(tmp.path()).unwrap_err();
1247        assert!(
1248            error.to_string().contains("requires a [policy] section"),
1249            "{error}"
1250        );
1251
1252        fs::write(tmp.path().join("x.sh"), "x").unwrap();
1253        fs::write(
1254            tmp.path().join("tuff.toml"),
1255            format!("{head}files = [\"x.sh\"]\n{rules}"),
1256        )
1257        .unwrap();
1258        let error = load_manifest(tmp.path()).unwrap_err();
1259        assert!(error.to_string().contains("installs no files"), "{error}");
1260    }
1261
1262    #[test]
1263    fn validate_non_empty_rejects_empty() {
1264        assert!(validate_non_empty("id", "").is_err());
1265        assert!(validate_non_empty("id", "ok").is_ok());
1266    }
1267
1268    fn load_mcp(toml_body: &str) -> Result<CapabilityManifest> {
1269        let tmp = TempDir::new().unwrap();
1270        fs::write(tmp.path().join("tuff.toml"), toml_body).unwrap();
1271        load_manifest(tmp.path())
1272    }
1273
1274    const MCP_HEAD: &str =
1275        "id = \"srv\"\nversion = \"1.0.0\"\ntype = \"mcp-server\"\ndescription = \"d\"\n";
1276
1277    #[test]
1278    fn mcp_server_requires_server_section() {
1279        let error = load_mcp(MCP_HEAD).unwrap_err().to_string();
1280        assert!(error.contains("requires a [server] section"), "{error}");
1281    }
1282
1283    #[test]
1284    fn mcp_server_stdio_requires_command_and_http_requires_url() {
1285        let error = load_mcp(&format!("{MCP_HEAD}[server]\ntransport = \"stdio\"\n"))
1286            .unwrap_err()
1287            .to_string();
1288        assert!(error.contains("requires a non-empty 'command'"), "{error}");
1289        let error = load_mcp(&format!("{MCP_HEAD}[server]\ntransport = \"http\"\n"))
1290            .unwrap_err()
1291            .to_string();
1292        assert!(error.contains("requires a non-empty 'url'"), "{error}");
1293        let ok = load_mcp(&format!(
1294            "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n"
1295        ))
1296        .unwrap();
1297        assert_eq!(ok.server.unwrap().transport, McpTransport::Http);
1298    }
1299
1300    #[test]
1301    fn mcp_server_env_must_be_a_reference_not_a_literal() {
1302        let error = load_mcp(&format!(
1303            "{MCP_HEAD}[server]\ncommand = \"npx\"\n[server.env]\nTOKEN = \"literal\"\n"
1304        ))
1305        .unwrap_err()
1306        .to_string();
1307        assert!(error.contains("from_env"), "{error}");
1308
1309        let ok = load_mcp(&format!(
1310            "{MCP_HEAD}[server]\ncommand = \"npx\"\n[server.env]\nTOKEN = {{ from_env = \"MY_TOKEN\" }}\n"
1311        ))
1312        .unwrap();
1313        assert_eq!(ok.server.unwrap().env["TOKEN"].from_env, "MY_TOKEN");
1314    }
1315
1316    #[test]
1317    fn mcp_server_headers_must_be_references_not_literals() {
1318        let error = load_mcp(&format!(
1319            "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1320             [server.headers]\nAuthorization = \"Bearer secret\"\n"
1321        ))
1322        .unwrap_err()
1323        .to_string();
1324        assert!(error.contains("[server.headers]"), "{error}");
1325        assert!(error.contains("from_env"), "{error}");
1326    }
1327
1328    #[test]
1329    fn mcp_server_header_reference_carries_an_optional_format() {
1330        let server = load_mcp(&format!(
1331            "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1332             [server.headers]\n\
1333             Authorization = {{ from_env = \"NOTION_TOKEN\", format = \"Bearer {{}}\" }}\n\
1334             X-Api-Key = {{ from_env = \"API_KEY\" }}\n"
1335        ))
1336        .unwrap()
1337        .server
1338        .unwrap();
1339        assert_eq!(server.headers["Authorization"].from_env, "NOTION_TOKEN");
1340        assert_eq!(
1341            server.headers["Authorization"].render("${NOTION_TOKEN}"),
1342            "Bearer ${NOTION_TOKEN}"
1343        );
1344        assert_eq!(server.headers["X-Api-Key"].format, None);
1345        assert_eq!(
1346            server.headers["X-Api-Key"].render("${API_KEY}"),
1347            "${API_KEY}"
1348        );
1349    }
1350
1351    #[test]
1352    fn mcp_server_header_format_needs_exactly_one_placeholder() {
1353        for format in ["Bearer", "Bearer {} {}"] {
1354            let error = load_mcp(&format!(
1355                "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1356                 [server.headers]\n\
1357                 Authorization = {{ from_env = \"TOKEN\", format = \"{format}\" }}\n"
1358            ))
1359            .unwrap_err()
1360            .to_string();
1361            assert!(error.contains("Authorization"), "{format}: {error}");
1362        }
1363    }
1364
1365    #[test]
1366    fn mcp_server_headers_are_refused_on_stdio() {
1367        let error = load_mcp(&format!(
1368            "{MCP_HEAD}[server]\ncommand = \"npx\"\n\
1369             [server.headers]\nAuthorization = {{ from_env = \"TOKEN\" }}\n"
1370        ))
1371        .unwrap_err()
1372        .to_string();
1373        assert!(error.contains("http"), "{error}");
1374    }
1375
1376    /// A server without headers has to serialize exactly as it did before
1377    /// the field existed, or every installed record drifts on upgrade.
1378    #[test]
1379    fn a_server_without_headers_serializes_without_the_table() {
1380        let server = load_mcp(&format!("{MCP_HEAD}[server]\ncommand = \"npx\"\n"))
1381            .unwrap()
1382            .server
1383            .unwrap();
1384        let wire = toml::to_string_pretty(&server).unwrap();
1385        assert!(!wire.contains("headers"), "{wire}");
1386    }
1387
1388    #[test]
1389    fn capability_type_round_trips_the_hyphenated_name() {
1390        assert_eq!(CapabilityType::McpServer.as_str(), "mcp-server");
1391        assert_eq!(
1392            CapabilityType::parse("mcp-server"),
1393            Some(CapabilityType::McpServer)
1394        );
1395        assert_eq!(
1396            CapabilityType::parse("mcp"),
1397            Some(CapabilityType::McpServer)
1398        );
1399        #[derive(serde::Serialize)]
1400        struct Wire {
1401            #[serde(rename = "type")]
1402            capability_type: CapabilityType,
1403        }
1404        let wire = toml::to_string(&Wire {
1405            capability_type: CapabilityType::McpServer,
1406        })
1407        .unwrap();
1408        assert!(wire.contains("type = \"mcp-server\""), "{wire}");
1409        assert_eq!(CapabilityType::parse("workflow"), None);
1410    }
1411}