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    Workflow,
14    Policy,
15    /// An external MCP server Tuff wires into each harness's native MCP
16    /// config. Distinct from a `tool` with `implementation.mcp = true`,
17    /// whose server code Tuff ships itself.
18    #[serde(rename = "mcp-server")]
19    McpServer,
20}
21
22impl CapabilityType {
23    pub fn plural_dir(&self) -> &'static str {
24        match self {
25            Self::Skill => "skills",
26            Self::Tool => "tools",
27            Self::Hook => "hooks",
28            Self::Workflow => "workflows",
29            Self::Policy => "policies",
30            Self::McpServer => "mcp-servers",
31        }
32    }
33
34    pub fn as_str(&self) -> &'static str {
35        match self {
36            Self::Skill => "skill",
37            Self::Tool => "tool",
38            Self::Hook => "hook",
39            Self::Workflow => "workflow",
40            Self::Policy => "policy",
41            Self::McpServer => "mcp-server",
42        }
43    }
44
45    pub fn parse(s: &str) -> Option<Self> {
46        match s {
47            "skill" => Some(Self::Skill),
48            "tool" => Some(Self::Tool),
49            "hook" => Some(Self::Hook),
50            "workflow" => Some(Self::Workflow),
51            "policy" => Some(Self::Policy),
52            "mcp-server" | "mcp" => Some(Self::McpServer),
53            _ => None,
54        }
55    }
56}
57
58impl std::fmt::Display for CapabilityType {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.write_str(self.as_str())
61    }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct CapabilityManifest {
66    pub id: String,
67    pub version: String,
68    #[serde(rename = "type")]
69    pub capability_type: CapabilityType,
70    pub description: String,
71    #[serde(default)]
72    pub files: Vec<String>,
73    #[serde(default)]
74    pub parameters: Option<serde_json::Value>,
75    #[serde(default)]
76    pub implementation: Option<ImplementationConfig>,
77    #[serde(default)]
78    pub hook: Option<HookConfig>,
79    #[serde(default)]
80    pub workflow: Option<WorkflowConfig>,
81    #[serde(default)]
82    pub server: Option<McpServerConfig>,
83    #[serde(default)]
84    #[allow(dead_code)]
85    pub targets: Vec<String>,
86
87    #[serde(skip)]
88    pub root: PathBuf,
89}
90
91/// Declaration of an external MCP server (`type = "mcp-server"`).
92///
93/// Secrets never appear here: every `[server.env]` value must be an
94/// [`EnvRef`], and every `[server.headers]` value a [`HeaderRef`], naming
95/// the variable to read on the developer's machine, so a manifest can be
96/// committed and shared without leaking anything.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct McpServerConfig {
99    #[serde(default)]
100    pub transport: McpTransport,
101    #[serde(default)]
102    pub command: Option<String>,
103    #[serde(default)]
104    pub args: Vec<String>,
105    #[serde(default)]
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)]
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)]
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
198#[derive(Debug, Clone, Serialize, Deserialize)]
199pub struct WorkflowConfig {
200    pub requires: Vec<Requirement>,
201}
202
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct Requirement {
205    pub id: String,
206    #[serde(rename = "type")]
207    pub capability_type: CapabilityType,
208}
209
210fn default_cwd() -> String {
211    ".".to_string()
212}
213
214impl CapabilityManifest {
215    pub fn source_files(&self) -> Result<Vec<PathBuf>> {
216        let mut paths = Vec::new();
217
218        for f in &self.files {
219            let clean = f.trim_start_matches("./");
220            let path = self.root.join(clean);
221            if !path.exists() {
222                return Err(TuffError::not_found(format!(
223                    "capability source file not found: {}",
224                    path.display()
225                )));
226            }
227            paths.push(path);
228        }
229
230        if self.capability_type == CapabilityType::Tool
231            && let Some(ref imp) = self.implementation
232        {
233            let ep_path = self.root.join(&imp.entrypoint);
234            if !paths.contains(&ep_path) && ep_path.exists() {
235                paths.push(ep_path);
236            }
237        }
238
239        Ok(paths)
240    }
241
242    pub fn read_source_contents_with_names(&self) -> Result<Vec<(String, Vec<u8>)>> {
243        self.source_files()?
244            .iter()
245            .map(|p| {
246                let rel = p
247                    .strip_prefix(&self.root)
248                    .unwrap_or(p)
249                    .to_string_lossy()
250                    .replace('\\', "/");
251                let rel = rel.strip_prefix("src/").unwrap_or(&rel).to_string();
252                let content = std::fs::read(p)?;
253                Ok((rel, content))
254            })
255            .collect()
256    }
257}
258
259fn validate_non_empty(field: &str, value: &str) -> Result<()> {
260    if value.is_empty() {
261        return Err(TuffError::usage(format!(
262            "capability manifest field '{field}' must be a non-empty string"
263        )));
264    }
265    Ok(())
266}
267
268pub fn load_manifest(capability_dir: &Path) -> Result<CapabilityManifest> {
269    let manifest_path = capability_dir.join("tuff.toml");
270    if !manifest_path.exists() {
271        return Err(TuffError::not_found(format!(
272            "capability manifest not found: {}",
273            manifest_path.display()
274        )));
275    }
276
277    let raw = std::fs::read_to_string(&manifest_path)?;
278    let mut manifest = parse_manifest(&raw, &manifest_path)?;
279    manifest.root = capability_dir.to_path_buf();
280
281    validate_non_empty("id", &manifest.id)?;
282    validate_non_empty("version", &manifest.version)?;
283    validate_non_empty("type", &manifest.capability_type.to_string())?;
284    validate_non_empty("description", &manifest.description)?;
285
286    match manifest.capability_type {
287        CapabilityType::Skill => {
288            if manifest.files.is_empty() {
289                return Err(TuffError::usage(
290                    "skill capability 'files' must not be empty",
291                ));
292            }
293            manifest.source_files()?;
294        }
295        CapabilityType::Tool => {
296            if manifest.parameters.is_none() {
297                return Err(TuffError::usage(
298                    "tool capability requires a [parameters] section with JSON Schema",
299                ));
300            }
301            if manifest.implementation.is_none() {
302                return Err(TuffError::usage(
303                    "tool capability requires an [implementation] section",
304                ));
305            }
306
307            let params = manifest.parameters.as_ref().unwrap();
308            crate::tool::validate_json_schema(params)?;
309
310            let impl_cfg = manifest.implementation.as_ref().unwrap();
311            crate::tool::validate_entrypoint(&manifest.root, &impl_cfg.entrypoint)?;
312
313            if !impl_cfg.runtime_deps.is_empty() {
314                eprintln!(
315                    "note: this tool requires runtime dependencies: {}",
316                    impl_cfg.runtime_deps.join(", ")
317                );
318            }
319
320            if !manifest.files.is_empty() {
321                manifest.source_files()?;
322            }
323        }
324        CapabilityType::Hook => {
325            let hook_cfg = manifest
326                .hook
327                .as_ref()
328                .ok_or_else(|| TuffError::usage("hook capability requires a [hook] section"))?;
329
330            if hook_cfg.event.trim().is_empty() {
331                return Err(TuffError::usage("hook 'event' must be a non-empty string"));
332            }
333            if hook_cfg.command.trim().is_empty() {
334                return Err(TuffError::usage(
335                    "hook 'command' must be a non-empty string",
336                ));
337            }
338
339            crate::tool::check_path_traversal(&hook_cfg.working_directory)?;
340
341            eprintln!(
342                "note: this hook runs '{}' on event '{}' — it will not be executed during install",
343                hook_cfg.command, hook_cfg.event
344            );
345
346            if !manifest.files.is_empty() {
347                manifest.source_files()?;
348            }
349        }
350        CapabilityType::Workflow => {
351            let wf = manifest.workflow.as_ref().ok_or_else(|| {
352                TuffError::usage("workflow capability requires a [[workflow.requires]] section")
353            })?;
354
355            if wf.requires.is_empty() {
356                return Err(TuffError::usage(
357                    "workflow 'requires' must have at least one entry",
358                ));
359            }
360
361            let mut seen = std::collections::HashSet::new();
362            for req in &wf.requires {
363                if req.id.trim().is_empty() {
364                    return Err(TuffError::usage(
365                        "workflow requirement 'id' must not be empty",
366                    ));
367                }
368                if req.id == manifest.id {
369                    return Err(TuffError::usage("workflow cannot require itself"));
370                }
371                if !seen.insert(&req.id) {
372                    return Err(TuffError::usage(format!(
373                        "duplicate requirement '{}' in workflow",
374                        req.id
375                    )));
376                }
377            }
378
379            let names: Vec<_> = wf
380                .requires
381                .iter()
382                .map(|r| format!("{} ({})", r.id, r.capability_type))
383                .collect();
384            eprintln!(
385                "note: workflow '{}' requires {} capabilities: {}",
386                manifest.id,
387                names.len(),
388                names.join(", ")
389            );
390        }
391        CapabilityType::Policy => {
392            return Err(TuffError::unsupported(
393                "policy capabilities are not supported yet",
394            ));
395        }
396        CapabilityType::McpServer => {
397            let server = manifest.server.as_ref().ok_or_else(|| {
398                TuffError::usage("mcp-server capability requires a [server] section")
399            })?;
400            validate_mcp_server(server)?;
401
402            if !manifest.files.is_empty() {
403                manifest.source_files()?;
404            }
405        }
406    }
407
408    Ok(manifest)
409}
410
411pub fn validate_mcp_server(server: &McpServerConfig) -> Result<()> {
412    match server.transport {
413        McpTransport::Stdio => {
414            if server
415                .command
416                .as_deref()
417                .is_none_or(|c| c.trim().is_empty())
418            {
419                return Err(TuffError::usage(
420                    "mcp-server with transport = \"stdio\" requires a non-empty 'command'",
421                ));
422            }
423        }
424        McpTransport::Http => {
425            if server.url.as_deref().is_none_or(|u| u.trim().is_empty()) {
426                return Err(TuffError::usage(
427                    "mcp-server with transport = \"http\" requires a non-empty 'url'",
428                ));
429            }
430        }
431    }
432    for (name, reference) in &server.env {
433        if name.trim().is_empty() {
434            return Err(TuffError::usage("[server.env] keys must be non-empty"));
435        }
436        if reference.from_env.trim().is_empty() {
437            return Err(TuffError::usage(format!(
438                "[server.env] {name} must reference a variable: {name} = {{ from_env = \"VAR\" }}"
439            )));
440        }
441    }
442    validate_mcp_headers(server)?;
443    Ok(())
444}
445
446/// Headers belong to the request a harness makes, so they are meaningful
447/// only over HTTP; on a stdio server they would be silently dropped, which
448/// is exactly the quiet-success failure RFC-106 exists to remove.
449fn validate_mcp_headers(server: &McpServerConfig) -> Result<()> {
450    if !server.headers.is_empty() && server.transport != McpTransport::Http {
451        return Err(TuffError::usage(
452            "[server.headers] applies to transport = \"http\"; a stdio server passes \
453             secrets through [server.env]",
454        ));
455    }
456    for (name, reference) in &server.headers {
457        if name.trim().is_empty() {
458            return Err(TuffError::usage("[server.headers] keys must be non-empty"));
459        }
460        if reference.from_env.trim().is_empty() {
461            return Err(TuffError::usage(format!(
462                "[server.headers] {name} must reference a variable: \
463                 {name} = {{ from_env = \"VAR\" }}"
464            )));
465        }
466        if let Some(format) = &reference.format {
467            let placeholders = format.matches(FORMAT_PLACEHOLDER).count();
468            if placeholders != 1 {
469                let problem = if placeholders == 0 {
470                    "would discard the value"
471                } else {
472                    "would repeat the value"
473                };
474                return Err(TuffError::usage(format!(
475                    "[server.headers] {name}: format \"{format}\" {problem}"
476                ))
477                .with_hint("format must contain exactly one {} placeholder, as in \"Bearer {}\""));
478            }
479        }
480    }
481    Ok(())
482}
483
484/// Parse a manifest, turning serde's opaque "invalid type: string" failure
485/// for a literal `[server.env]` value into an error that says what to write
486/// instead.
487fn parse_manifest(raw: &str, manifest_path: &Path) -> Result<CapabilityManifest> {
488    toml::from_str(raw).map_err(|error: toml::de::Error| {
489        let message = error.to_string();
490        let looks_literal =
491            message.contains("invalid type: string") || message.contains("expected a table");
492        let literal_table = looks_literal
493            .then(|| {
494                ["[server.env]", "[server.headers]"]
495                    .into_iter()
496                    .find(|table| raw.contains(table))
497            })
498            .flatten();
499        if let Some(table) = literal_table {
500            let example = if table == "[server.headers]" {
501                "Authorization = { from_env = \"TOKEN\", format = \"Bearer {}\" }"
502            } else {
503                "NAME = { from_env = \"NAME\" }"
504            };
505            TuffError::usage(format!(
506                "invalid manifest at {}: {} values must be references, never \
507                 literals — write {} ({})",
508                manifest_path.display(),
509                table,
510                example,
511                message.trim()
512            ))
513        } else {
514            TuffError::from(error)
515        }
516    })
517}
518
519/// Writes a capability manifest as deterministic TOML.
520///
521/// # Errors
522///
523/// Returns an error when serialization or filesystem writing fails.
524pub fn write_manifest(path: &Path, manifest: &CapabilityManifest) -> Result<()> {
525    std::fs::write(path, toml::to_string_pretty(manifest)?)?;
526    Ok(())
527}
528
529pub fn synthetic_manifest(
530    skill_dir: &Path,
531    name: &str,
532    version: &str,
533) -> Result<CapabilityManifest> {
534    let skill_file = skill_dir.join("SKILL.md");
535    if !skill_file.exists() {
536        return Err(TuffError::not_found(format!(
537            "skill entrypoint not found: {}",
538            skill_file.display()
539        )));
540    }
541    let mut files = Vec::new();
542    walk_skill_dir(skill_dir, "", &mut files)?;
543    files.sort();
544
545    Ok(CapabilityManifest {
546        id: name.to_string(),
547        version: version.to_string(),
548        capability_type: CapabilityType::Skill,
549        description: "Installed from git source.".to_string(),
550        files,
551        parameters: None,
552        implementation: None,
553        hook: None,
554        workflow: None,
555        server: None,
556        targets: Vec::new(),
557        root: skill_dir.to_path_buf(),
558    })
559}
560
561fn walk_skill_dir(base: &Path, prefix: &str, files: &mut Vec<String>) -> Result<()> {
562    for entry in std::fs::read_dir(base)? {
563        let entry = entry?;
564        let path = entry.path();
565        let metadata = std::fs::symlink_metadata(&path)?;
566        if metadata.file_type().is_symlink() {
567            return Err(TuffError::refused(format!(
568                "symbolic links are not allowed in capability sources: {}",
569                path.display()
570            )));
571        }
572        let rel = if prefix.is_empty() {
573            entry.file_name().to_string_lossy().to_string()
574        } else {
575            format!("{}/{}", prefix, entry.file_name().to_string_lossy())
576        };
577        if metadata.is_dir() {
578            walk_skill_dir(&path, &rel, files)?;
579        } else if metadata.is_file() && rel != "tuff.toml" {
580            files.push(rel);
581        }
582    }
583    Ok(())
584}
585
586#[cfg(test)]
587mod tests {
588    use super::*;
589    use std::fs;
590    use tempfile::TempDir;
591
592    fn write_manifest(dir: &std::path::Path, content: &str) {
593        fs::write(dir.join("tuff.toml"), content).unwrap();
594    }
595
596    #[test]
597    fn load_skill_manifest_succeeds() {
598        let tmp = TempDir::new().unwrap();
599        fs::create_dir_all(tmp.path().join("src")).unwrap();
600        fs::write(tmp.path().join("src").join("SKILL.md"), "# Skill").unwrap();
601        write_manifest(
602            tmp.path(),
603            r#"id = "test"
604version = "1.0.0"
605type = "skill"
606description = "A test skill"
607files = ["src/SKILL.md"]
608"#,
609        );
610        let m = load_manifest(tmp.path()).unwrap();
611        assert_eq!(m.id, "test");
612        assert_eq!(m.capability_type, CapabilityType::Skill);
613    }
614
615    #[test]
616    fn load_tool_manifest_succeeds() {
617        let tmp = TempDir::new().unwrap();
618        fs::write(tmp.path().join("run.sh"), "echo ok").unwrap();
619        write_manifest(
620            tmp.path(),
621            r#"id = "tool1"
622version = "1.0.0"
623type = "tool"
624description = "A test tool"
625files = ["run.sh"]
626
627[parameters]
628type = "object"
629required = ["x"]
630[parameters.properties.x]
631type = "string"
632description = "x"
633
634[implementation]
635language = "bash"
636entrypoint = "run.sh"
637"#,
638        );
639        let m = load_manifest(tmp.path()).unwrap();
640        assert_eq!(m.capability_type, CapabilityType::Tool);
641        assert!(m.implementation.is_some());
642    }
643
644    #[test]
645    fn load_hook_manifest_succeeds() {
646        let tmp = TempDir::new().unwrap();
647        write_manifest(
648            tmp.path(),
649            r#"id = "hook1"
650version = "1.0.0"
651type = "hook"
652description = "A test hook"
653
654[hook]
655event = "before_finish"
656command = "cargo test"
657"#,
658        );
659        let m = load_manifest(tmp.path()).unwrap();
660        assert_eq!(m.capability_type, CapabilityType::Hook);
661        assert!(m.hook.is_some());
662    }
663
664    #[test]
665    fn load_rejects_unsupported_type() {
666        let tmp = TempDir::new().unwrap();
667        write_manifest(
668            tmp.path(),
669            r#"id = "bad"
670version = "1.0.0"
671type = "unknown"
672description = "Bad"
673files = ["SKILL.md"]
674"#,
675        );
676        assert!(load_manifest(tmp.path()).is_err());
677    }
678
679    #[test]
680    fn load_rejects_missing_manifest() {
681        let tmp = TempDir::new().unwrap();
682        assert!(load_manifest(tmp.path()).is_err());
683    }
684
685    #[test]
686    fn source_files_resolves_paths() {
687        let tmp = TempDir::new().unwrap();
688        fs::create_dir_all(tmp.path().join("src")).unwrap();
689        fs::write(tmp.path().join("src").join("SKILL.md"), "skill").unwrap();
690        let m = CapabilityManifest {
691            id: "t".into(),
692            version: "1.0".into(),
693            capability_type: CapabilityType::Skill,
694            description: "desc".into(),
695            files: vec!["src/SKILL.md".into()],
696            parameters: None,
697            implementation: None,
698            hook: None,
699            workflow: None,
700            server: None,
701            targets: vec![],
702            root: tmp.path().to_path_buf(),
703        };
704        let files = m.source_files().unwrap();
705        assert_eq!(files.len(), 1);
706        assert!(files[0].ends_with("SKILL.md"));
707    }
708
709    #[test]
710    fn source_files_rejects_missing_file() {
711        let tmp = TempDir::new().unwrap();
712        let m = CapabilityManifest {
713            id: "t".into(),
714            version: "1.0".into(),
715            capability_type: CapabilityType::Skill,
716            description: "desc".into(),
717            files: vec!["src/MISSING.md".into()],
718            parameters: None,
719            implementation: None,
720            hook: None,
721            workflow: None,
722            server: None,
723            targets: vec![],
724            root: tmp.path().to_path_buf(),
725        };
726        assert!(m.source_files().is_err());
727    }
728
729    #[test]
730    fn validate_non_empty_rejects_empty() {
731        assert!(validate_non_empty("id", "").is_err());
732        assert!(validate_non_empty("id", "ok").is_ok());
733    }
734
735    fn load_mcp(toml_body: &str) -> Result<CapabilityManifest> {
736        let tmp = TempDir::new().unwrap();
737        fs::write(tmp.path().join("tuff.toml"), toml_body).unwrap();
738        load_manifest(tmp.path())
739    }
740
741    const MCP_HEAD: &str =
742        "id = \"srv\"\nversion = \"1.0.0\"\ntype = \"mcp-server\"\ndescription = \"d\"\n";
743
744    #[test]
745    fn mcp_server_requires_server_section() {
746        let error = load_mcp(MCP_HEAD).unwrap_err().to_string();
747        assert!(error.contains("requires a [server] section"), "{error}");
748    }
749
750    #[test]
751    fn mcp_server_stdio_requires_command_and_http_requires_url() {
752        let error = load_mcp(&format!("{MCP_HEAD}[server]\ntransport = \"stdio\"\n"))
753            .unwrap_err()
754            .to_string();
755        assert!(error.contains("requires a non-empty 'command'"), "{error}");
756        let error = load_mcp(&format!("{MCP_HEAD}[server]\ntransport = \"http\"\n"))
757            .unwrap_err()
758            .to_string();
759        assert!(error.contains("requires a non-empty 'url'"), "{error}");
760        let ok = load_mcp(&format!(
761            "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n"
762        ))
763        .unwrap();
764        assert_eq!(ok.server.unwrap().transport, McpTransport::Http);
765    }
766
767    #[test]
768    fn mcp_server_env_must_be_a_reference_not_a_literal() {
769        let error = load_mcp(&format!(
770            "{MCP_HEAD}[server]\ncommand = \"npx\"\n[server.env]\nTOKEN = \"literal\"\n"
771        ))
772        .unwrap_err()
773        .to_string();
774        assert!(error.contains("from_env"), "{error}");
775
776        let ok = load_mcp(&format!(
777            "{MCP_HEAD}[server]\ncommand = \"npx\"\n[server.env]\nTOKEN = {{ from_env = \"MY_TOKEN\" }}\n"
778        ))
779        .unwrap();
780        assert_eq!(ok.server.unwrap().env["TOKEN"].from_env, "MY_TOKEN");
781    }
782
783    #[test]
784    fn mcp_server_headers_must_be_references_not_literals() {
785        let error = load_mcp(&format!(
786            "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
787             [server.headers]\nAuthorization = \"Bearer secret\"\n"
788        ))
789        .unwrap_err()
790        .to_string();
791        assert!(error.contains("[server.headers]"), "{error}");
792        assert!(error.contains("from_env"), "{error}");
793    }
794
795    #[test]
796    fn mcp_server_header_reference_carries_an_optional_format() {
797        let server = load_mcp(&format!(
798            "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
799             [server.headers]\n\
800             Authorization = {{ from_env = \"NOTION_TOKEN\", format = \"Bearer {{}}\" }}\n\
801             X-Api-Key = {{ from_env = \"API_KEY\" }}\n"
802        ))
803        .unwrap()
804        .server
805        .unwrap();
806        assert_eq!(server.headers["Authorization"].from_env, "NOTION_TOKEN");
807        assert_eq!(
808            server.headers["Authorization"].render("${NOTION_TOKEN}"),
809            "Bearer ${NOTION_TOKEN}"
810        );
811        assert_eq!(server.headers["X-Api-Key"].format, None);
812        assert_eq!(
813            server.headers["X-Api-Key"].render("${API_KEY}"),
814            "${API_KEY}"
815        );
816    }
817
818    #[test]
819    fn mcp_server_header_format_needs_exactly_one_placeholder() {
820        for format in ["Bearer", "Bearer {} {}"] {
821            let error = load_mcp(&format!(
822                "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
823                 [server.headers]\n\
824                 Authorization = {{ from_env = \"TOKEN\", format = \"{format}\" }}\n"
825            ))
826            .unwrap_err()
827            .to_string();
828            assert!(error.contains("Authorization"), "{format}: {error}");
829        }
830    }
831
832    #[test]
833    fn mcp_server_headers_are_refused_on_stdio() {
834        let error = load_mcp(&format!(
835            "{MCP_HEAD}[server]\ncommand = \"npx\"\n\
836             [server.headers]\nAuthorization = {{ from_env = \"TOKEN\" }}\n"
837        ))
838        .unwrap_err()
839        .to_string();
840        assert!(error.contains("http"), "{error}");
841    }
842
843    /// A server without headers has to serialize exactly as it did before
844    /// the field existed, or every installed record drifts on upgrade.
845    #[test]
846    fn a_server_without_headers_serializes_without_the_table() {
847        let server = load_mcp(&format!("{MCP_HEAD}[server]\ncommand = \"npx\"\n"))
848            .unwrap()
849            .server
850            .unwrap();
851        let wire = toml::to_string_pretty(&server).unwrap();
852        assert!(!wire.contains("headers"), "{wire}");
853    }
854
855    #[test]
856    fn capability_type_round_trips_the_hyphenated_name() {
857        assert_eq!(CapabilityType::McpServer.as_str(), "mcp-server");
858        assert_eq!(
859            CapabilityType::parse("mcp-server"),
860            Some(CapabilityType::McpServer)
861        );
862        assert_eq!(
863            CapabilityType::parse("mcp"),
864            Some(CapabilityType::McpServer)
865        );
866        let wire = toml::to_string(&Requirement {
867            id: "x".into(),
868            capability_type: CapabilityType::McpServer,
869        })
870        .unwrap();
871        assert!(wire.contains("type = \"mcp-server\""), "{wire}");
872    }
873}