mcp-forge 0.1.2

Generate Rust MCP servers from OpenAPI specs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
use crate::ir::ApiSpec;
use heck::{ToSnakeCase, ToUpperCamelCase};

/// Generate all scaffold/boilerplate files for the MCP server project.
///
/// Returns a list of `(relative_path, content)` pairs. The caller writes
/// each pair to `output_dir / relative_path`.
///
/// Generated files:
/// - `Cargo.toml` -- dependencies (rmcp, reqwest, schemars, clap, serde, tokio, etc.)
/// - `src/main.rs` -- dual-mode entry point (CLI + MCP server)
/// - `src/error.rs` -- thiserror enum
/// - `src/config.rs` -- shikumi-style config loading with `{APP}_CONFIG` env
/// - `src/auth.rs` -- API key resolution (flag > env > file)
/// - `src/api/mod.rs` -- module declaration
/// - `flake.nix` -- substrate pattern with `crateOverrides` for rmcp
/// - `module/default.nix` -- home-manager module with `mkMcpOptions`
/// - `.gitignore`
#[must_use]
pub fn generate_scaffold(spec: &ApiSpec) -> Vec<(String, String)> {
    let mut files = Vec::with_capacity(10);

    files.push(("Cargo.toml".into(), generate_cargo_toml(spec)));
    files.push(("src/main.rs".into(), generate_main_rs(spec)));
    files.push(("src/error.rs".into(), generate_error_rs(spec)));
    files.push(("src/config.rs".into(), generate_config_rs(spec)));
    files.push(("src/auth.rs".into(), generate_auth_rs(spec)));
    files.push(("src/api/mod.rs".into(), generate_api_mod_rs()));
    files.push(("flake.nix".into(), generate_flake_nix(spec)));
    files.push((
        "module/default.nix".into(),
        generate_module_nix(spec),
    ));
    files.push((".gitignore".into(), generate_gitignore()));

    files
}

fn generate_cargo_toml(spec: &ApiSpec) -> String {
    let name = spec.name.to_snake_case();
    let default_description = format!("Rust CLI + MCP server for {}", spec.name);
    let description = spec
        .description
        .as_deref()
        .unwrap_or(&default_description);
    let version = &spec.version;

    format!(
        r#"[package]
name = "{name}"
version = "{version}"
edition = "2024"
rust-version = "1.89.0"
description = "{description}"
license = "MIT"

[[bin]]
name = "{name}"
path = "src/main.rs"

[dependencies]
anyhow = "1"
clap = {{ version = "4", features = ["derive"] }}
heck = "0.5"
reqwest = {{ version = "0.12", features = ["json", "rustls-tls"], default-features = false }}
rmcp = {{ version = "0.15", features = ["server", "transport-io"] }}
schemars = "0.8"
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
serde_yaml_ng = "0.10"
thiserror = "2"
tokio = {{ version = "1", features = ["macros", "rt-multi-thread"] }}
tracing = "0.1"
tracing-subscriber = {{ version = "0.3", features = ["env-filter", "json"] }}
urlencoding = "2"

[profile.release]
codegen-units = 1
lto = true
opt-level = "z"
strip = true

[lints.clippy]
pedantic = "warn"
"#
    )
}

fn generate_main_rs(spec: &ApiSpec) -> String {
    let name = spec.name.to_snake_case();
    let config_type = format!("{}Config", spec.name.to_upper_camel_case());
    let default_description = format!("{name} CLI + MCP server");
    let description = spec
        .description
        .as_deref()
        .unwrap_or(&default_description);

    format!(
        r#"use clap::Parser;
use std::process::ExitCode;

mod api;
mod auth;
mod client;
mod config;
mod error;
mod format;
mod mcp;

use config::{config_type};

#[derive(Parser)]
#[command(name = "{name}", about = "{description}")]
struct Cli {{
    /// Run in MCP server mode (default when no subcommand given)
    #[command(subcommand)]
    command: Option<Command>,

    /// API key (overrides env and config file)
    #[arg(long)]
    api_key: Option<String>,

    /// API base URL (overrides config)
    #[arg(long)]
    api_url: Option<String>,
}}

#[derive(clap::Subcommand)]
enum Command {{
    /// Run the MCP server on stdio
    Serve,
}}

#[tokio::main]
async fn main() -> ExitCode {{
    let cli = Cli::parse();

    // No subcommand or explicit serve -> MCP server mode (stdio)
    match cli.command {{
        None | Some(Command::Serve) => {{
            init_tracing(true);
            if let Err(e) = mcp::run().await {{
                eprintln!("MCP server error: {{e}}");
                return ExitCode::FAILURE;
            }}
            ExitCode::SUCCESS
        }}
    }}
}}

fn init_tracing(json: bool) {{
    use tracing_subscriber::{{EnvFilter, fmt}};

    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn"));
    if json {{
        fmt().json().with_env_filter(filter).with_writer(std::io::stderr).init();
    }} else {{
        fmt().with_env_filter(filter).init();
    }}
}}
"#,
    )
}

fn generate_error_rs(spec: &ApiSpec) -> String {
    let error_name = format!("{}Error", spec.name.to_upper_camel_case());
    let env_var = format!(
        "{}_API_KEY",
        spec.name.to_snake_case().to_uppercase()
    );

    format!(
        r#"use std::path::PathBuf;

#[derive(Debug, thiserror::Error)]
pub enum {error_name} {{
    #[error("HTTP request failed: {{0}}")]
    Request(#[from] reqwest::Error),

    #[error("API returned {{status}}: {{body}}")]
    Api {{ status: u16, body: String }},

    #[error("JSON parse error: {{0}}")]
    Json(#[from] serde_json::Error),

    #[error("API key not found -- set --api-key, {env_var}, or create {{path}}")]
    NoApiKey {{ path: PathBuf }},
}}

pub type Result<T> = std::result::Result<T, {error_name}>;
"#
    )
}

fn generate_config_rs(spec: &ApiSpec) -> String {
    let config_type = format!("{}Config", spec.name.to_upper_camel_case());
    let app_name = spec.name.to_snake_case();
    let app_upper = app_name.to_uppercase();
    let base_url = spec
        .base_url
        .as_deref()
        .unwrap_or("https://api.example.com");

    format!(
        r#"use serde::Deserialize;
use std::path::PathBuf;

#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct {config_type} {{
    pub api_url: String,
    pub api_key_file: PathBuf,
}}

impl Default for {config_type} {{
    fn default() -> Self {{
        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
        Self {{
            api_url: "{base_url}".into(),
            api_key_file: PathBuf::from(&home).join(".config/{app_name}/api-key"),
        }}
    }}
}}

impl {config_type} {{
    pub fn load() -> Self {{
        // Priority:
        // 1. {app_upper}_CONFIG env (set by Nix HM module for MCP server context)
        // 2. XDG_CONFIG_HOME/{app_name}/{app_name}.yaml
        // 3. ~/.config/{app_name}/{app_name}.yaml
        // 4. Defaults

        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());

        let candidates: Vec<PathBuf> = [
            // Nix module sets this for MCP server processes that lack user env
            std::env::var("{app_upper}_CONFIG").map(PathBuf::from).ok(),
            std::env::var("XDG_CONFIG_HOME")
                .map(|x| PathBuf::from(x).join("{app_name}/{app_name}.yaml"))
                .ok(),
            Some(PathBuf::from(&home).join(".config/{app_name}/{app_name}.yaml")),
        ]
        .into_iter()
        .flatten()
        .collect();

        for candidate in &candidates {{
            if candidate.exists() {{
                if let Ok(content) = std::fs::read_to_string(candidate) {{
                    match serde_yaml_ng::from_str::<Self>(&content) {{
                        Ok(config) => return config,
                        Err(e) => {{
                            tracing::warn!("failed to parse {{}}: {{e}}", candidate.display());
                        }}
                    }}
                }}
            }}
        }}

        Self::default()
    }}
}}
"#
    )
}

fn generate_auth_rs(spec: &ApiSpec) -> String {
    let config_type = format!("{}Config", spec.name.to_upper_camel_case());
    let error_name = format!("{}Error", spec.name.to_upper_camel_case());
    let env_var = format!(
        "{}_API_KEY",
        spec.name.to_snake_case().to_uppercase()
    );

    format!(
        r#"use crate::config::{config_type};
use crate::error::{{{error_name}, Result}};
use std::path::PathBuf;

/// Resolve the API key from (in priority order):
/// 1. Explicit CLI flag value
/// 2. {env_var} environment variable
/// 3. Contents of the configured api_key_file
pub fn resolve_api_key(explicit: Option<&str>, config: &{config_type}) -> Result<String> {{
    // 1. Explicit flag
    if let Some(key) = explicit {{
        return Ok(key.to_string());
    }}

    // 2. Environment variable
    if let Ok(key) = std::env::var("{env_var}") {{
        if !key.is_empty() {{
            return Ok(key);
        }}
    }}

    // 3. File
    let path = expand_tilde(&config.api_key_file);
    match std::fs::read_to_string(&path) {{
        Ok(content) => {{
            let key = content.trim().to_string();
            if key.is_empty() {{
                Err({error_name}::NoApiKey {{ path }})
            }} else {{
                Ok(key)
            }}
        }}
        Err(_) => Err({error_name}::NoApiKey {{ path }}),
    }}
}}

fn expand_tilde(path: &PathBuf) -> PathBuf {{
    let s = path.to_string_lossy();
    if let Some(rest) = s.strip_prefix("~/") {{
        if let Ok(home) = std::env::var("HOME") {{
            return PathBuf::from(home).join(rest);
        }}
    }}
    path.clone()
}}
"#
    )
}

fn generate_api_mod_rs() -> String {
    "pub mod types;\n".into()
}

fn generate_flake_nix(spec: &ApiSpec) -> String {
    let app_name = spec.name.to_snake_case();
    let default_description = format!("{app_name} -- Rust CLI + MCP server");
    let description = spec
        .description
        .as_deref()
        .unwrap_or(&default_description);

    format!(
        r#"{{
  description = "{app_name} -- {description}";

  nixConfig = {{
    allow-import-from-derivation = true;
  }};

  inputs = {{
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
    crate2nix.url = "github:nix-community/crate2nix";
    flake-utils.url = "github:numtide/flake-utils";
    substrate = {{
      url = "github:pleme-io/substrate";
      inputs.nixpkgs.follows = "nixpkgs";
    }};
    devenv = {{
      url = "github:cachix/devenv";
      inputs.nixpkgs.follows = "nixpkgs";
    }};
  }};

  outputs = {{
    self,
    nixpkgs,
    crate2nix,
    flake-utils,
    substrate,
    devenv,
  }}:
    (import "${{substrate}}/lib/rust-tool-release-flake.nix" {{
      inherit nixpkgs crate2nix flake-utils devenv;
    }}) {{
      toolName = "{app_name}";
      src = self;
      repo = "pleme-io/{app_name}";
      crateOverrides = {{
        rmcp = attrs: {{
          CARGO_CRATE_NAME = "rmcp";
        }};
      }};
    }}
    // {{
      homeManagerModules.default = import ./module {{
        hmHelpers = import "${{substrate}}/lib/hm-service-helpers.nix" {{ lib = nixpkgs.lib; }};
      }};
    }};
}}
"#
    )
}

#[allow(clippy::too_many_lines)]
fn generate_module_nix(spec: &ApiSpec) -> String {
    let app_name = spec.name.to_snake_case();
    let app_upper = app_name.to_uppercase();
    let config_type_name = &spec.name;
    let base_url = spec
        .base_url
        .as_deref()
        .unwrap_or("https://api.example.com");

    format!(
        r#"# {config_type_name} home-manager module -- MCP server + CLI
#
# Namespace: services.{app_name}.*
#
# Provides:
#   - MCP server entry (consumed by claude/anvil for all AI agents)
#   - CLI binary in PATH
#   - Config file generation (~/.config/{app_name}/{app_name}.yaml)
#   - Env propagation: {app_upper}_CONFIG passed to MCP server process
#
# Usage:
#   services.{app_name}.package = inputs.{app_name}.packages.${{system}}.default;
#   services.{app_name}.enable = true;
#   services.{app_name}.mcp.enable = true;
{{ hmHelpers }}:
{{
  lib,
  config,
  pkgs,
  ...
}}:
with lib; let
  inherit (hmHelpers) mkMcpOptions mkMcpServerEntry;
  cfg = config.services.{app_name};
  mcpCfg = cfg.mcp;
  homeDir = config.home.homeDirectory;

  defaultApiKeyFile = "${{homeDir}}/.config/{app_name}/api-key";

  resolvedApiKeyFile =
    if cfg.settings.apiKeyFile != null
    then cfg.settings.apiKeyFile
    else defaultApiKeyFile;

  configFile = pkgs.writeText "{app_name}.yaml"
    (builtins.toJSON ({{
      api_url = cfg.settings.apiUrl;
      api_key_file = resolvedApiKeyFile;
    }}));

  mcpEnv = optionalAttrs cfg.settings.propagateApiKey {{
    {app_upper}_CONFIG = "${{configFile}}";
  }};
in {{
  options.services.{app_name} = {{
    enable = mkEnableOption "{app_name} -- CLI + MCP server";

    package = mkOption {{
      type = types.package;
      description = ''
        The {app_name} binary package. Must be set explicitly from your flake input:
          services.{app_name}.package = inputs.{app_name}.packages.''${{system}}.default;
      '';
    }};

    mcp = mkMcpOptions {{
      defaultPackage = pkgs.hello;
    }};

    settings = {{
      apiUrl = mkOption {{
        type = types.str;
        default = "{base_url}";
        description = "API base URL.";
      }};

      apiKeyFile = mkOption {{
        type = types.nullOr types.str;
        default = null;
        description = ''
          Path to file containing the API key.
          When null, defaults to ~/.config/{app_name}/api-key.
        '';
      }};

      propagateApiKey = mkOption {{
        type = types.bool;
        default = true;
        description = ''
          Pass config file path to the MCP server process via {app_upper}_CONFIG env.
          Ensures the MCP server can find the API key when launched by Claude
          Code or other MCP clients that don't inherit user environment.
        '';
      }};
    }};
  }};

  config = mkMerge [
    {{
      services.{app_name}.mcp.package = mkDefault cfg.package;
    }}

    (mkIf cfg.enable {{
      home.packages = [ cfg.package ];

      xdg.configFile."{app_name}/{app_name}.yaml".source = configFile;
    }})

    (mkIf mcpCfg.enable {{
      services.{app_name}.mcp.serverEntry = mkMcpServerEntry ({{
        command = "${{mcpCfg.package}}/bin/{app_name}";
      }} // optionalAttrs (mcpEnv != {{}}) {{
        env = mcpEnv;
      }});
    }})
  ];
}}
"#
    )
}

fn generate_gitignore() -> String {
    "/target\n/result\n".into()
}

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

    fn make_spec() -> ApiSpec {
        ApiSpec {
            name: "Pet Store".into(),
            description: Some("A sample pet store API.".into()),
            version: "2.0.0".into(),
            base_url: Some("https://api.petstore.example.com/v2".into()),
            auth: AuthMethod::Bearer,
            operations: vec![],
            types: vec![],
        }
    }

    #[test]
    fn scaffold_returns_expected_file_count() {
        let spec = make_spec();
        let files = generate_scaffold(&spec);
        assert_eq!(files.len(), 9);
    }

    #[test]
    fn scaffold_file_paths() {
        let spec = make_spec();
        let files = generate_scaffold(&spec);
        let paths: Vec<&str> = files.iter().map(|(p, _)| p.as_str()).collect();
        assert!(paths.contains(&"Cargo.toml"));
        assert!(paths.contains(&"src/main.rs"));
        assert!(paths.contains(&"src/error.rs"));
        assert!(paths.contains(&"src/config.rs"));
        assert!(paths.contains(&"src/auth.rs"));
        assert!(paths.contains(&"src/api/mod.rs"));
        assert!(paths.contains(&"flake.nix"));
        assert!(paths.contains(&"module/default.nix"));
        assert!(paths.contains(&".gitignore"));
    }

    // -- Cargo.toml --

    #[test]
    fn cargo_toml_name() {
        let spec = make_spec();
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("name = \"pet_store\""));
    }

    #[test]
    fn cargo_toml_version() {
        let spec = make_spec();
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("version = \"2.0.0\""));
    }

    #[test]
    fn cargo_toml_edition() {
        let spec = make_spec();
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("edition = \"2024\""));
        assert!(content.contains("rust-version = \"1.89.0\""));
    }

    #[test]
    fn cargo_toml_dependencies() {
        let spec = make_spec();
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("rmcp"));
        assert!(content.contains("reqwest"));
        assert!(content.contains("schemars"));
        assert!(content.contains("serde"));
        assert!(content.contains("serde_json"));
        assert!(content.contains("tokio"));
        assert!(content.contains("thiserror"));
        assert!(content.contains("clap"));
        assert!(content.contains("urlencoding"));
    }

    #[test]
    fn cargo_toml_release_profile() {
        let spec = make_spec();
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("[profile.release]"));
        assert!(content.contains("lto = true"));
    }

    #[test]
    fn cargo_toml_clippy_lints() {
        let spec = make_spec();
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("[lints.clippy]"));
        assert!(content.contains("pedantic = \"warn\""));
    }

    #[test]
    fn cargo_toml_description_from_spec() {
        let spec = make_spec();
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("A sample pet store API."));
    }

    #[test]
    fn cargo_toml_default_description() {
        let mut spec = make_spec();
        spec.description = None;
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("Rust CLI + MCP server for Pet Store"));
    }

    // -- main.rs --

    #[test]
    fn main_rs_has_cli_struct() {
        let spec = make_spec();
        let content = generate_main_rs(&spec);
        assert!(content.contains("#[derive(Parser)]"));
        assert!(content.contains("struct Cli {"));
        assert!(content.contains("#[command(subcommand)]"));
    }

    #[test]
    fn main_rs_has_serve_command() {
        let spec = make_spec();
        let content = generate_main_rs(&spec);
        assert!(content.contains("enum Command {"));
        assert!(content.contains("Serve,"));
    }

    #[test]
    fn main_rs_has_tokio_main() {
        let spec = make_spec();
        let content = generate_main_rs(&spec);
        assert!(content.contains("#[tokio::main]"));
    }

    #[test]
    fn main_rs_imports_config() {
        let spec = make_spec();
        let content = generate_main_rs(&spec);
        assert!(content.contains("use config::PetStoreConfig;"));
    }

    #[test]
    fn main_rs_has_tracing_init() {
        let spec = make_spec();
        let content = generate_main_rs(&spec);
        assert!(content.contains("fn init_tracing(json: bool)"));
    }

    // -- error.rs --

    #[test]
    fn error_rs_has_error_enum() {
        let spec = make_spec();
        let content = generate_error_rs(&spec);
        assert!(content.contains("pub enum PetStoreError {"));
        assert!(content.contains("Request("));
        assert!(content.contains("Api {"));
        assert!(content.contains("Json("));
        assert!(content.contains("NoApiKey {"));
    }

    #[test]
    fn error_rs_env_var_name() {
        let spec = make_spec();
        let content = generate_error_rs(&spec);
        assert!(content.contains("PET_STORE_API_KEY"));
    }

    #[test]
    fn error_rs_result_type_alias() {
        let spec = make_spec();
        let content = generate_error_rs(&spec);
        assert!(content.contains("pub type Result<T> = std::result::Result<T, PetStoreError>;"));
    }

    // -- config.rs --

    #[test]
    fn config_rs_struct() {
        let spec = make_spec();
        let content = generate_config_rs(&spec);
        assert!(content.contains("pub struct PetStoreConfig {"));
        assert!(content.contains("pub api_url: String,"));
        assert!(content.contains("pub api_key_file: PathBuf,"));
    }

    #[test]
    fn config_rs_default_base_url() {
        let spec = make_spec();
        let content = generate_config_rs(&spec);
        assert!(content.contains("https://api.petstore.example.com/v2"));
    }

    #[test]
    fn config_rs_default_base_url_fallback() {
        let mut spec = make_spec();
        spec.base_url = None;
        let content = generate_config_rs(&spec);
        assert!(content.contains("https://api.example.com"));
    }

    #[test]
    fn config_rs_load_method() {
        let spec = make_spec();
        let content = generate_config_rs(&spec);
        assert!(content.contains("pub fn load() -> Self"));
        assert!(content.contains("PET_STORE_CONFIG"));
    }

    #[test]
    fn config_rs_xdg_config() {
        let spec = make_spec();
        let content = generate_config_rs(&spec);
        assert!(content.contains("XDG_CONFIG_HOME"));
        assert!(content.contains("pet_store/pet_store.yaml"));
    }

    // -- auth.rs --

    #[test]
    fn auth_rs_resolve_function() {
        let spec = make_spec();
        let content = generate_auth_rs(&spec);
        assert!(content.contains("pub fn resolve_api_key("));
        assert!(content.contains("PetStoreConfig"));
        assert!(content.contains("PetStoreError"));
    }

    #[test]
    fn auth_rs_env_var() {
        let spec = make_spec();
        let content = generate_auth_rs(&spec);
        assert!(content.contains("PET_STORE_API_KEY"));
    }

    #[test]
    fn auth_rs_priority_order() {
        let spec = make_spec();
        let content = generate_auth_rs(&spec);
        // Check that explicit, env, and file are all present
        assert!(content.contains("Explicit flag"));
        assert!(content.contains("Environment variable"));
        assert!(content.contains("File"));
    }

    #[test]
    fn auth_rs_expand_tilde() {
        let spec = make_spec();
        let content = generate_auth_rs(&spec);
        assert!(content.contains("fn expand_tilde("));
        assert!(content.contains("strip_prefix(\"~/\")"));
    }

    // -- api/mod.rs --

    #[test]
    fn api_mod_rs_declares_types() {
        let content = generate_api_mod_rs();
        assert_eq!(content, "pub mod types;\n");
    }

    // -- flake.nix --

    #[test]
    fn flake_nix_app_name() {
        let spec = make_spec();
        let content = generate_flake_nix(&spec);
        assert!(content.contains("pet_store"));
        assert!(content.contains("toolName = \"pet_store\""));
    }

    #[test]
    fn flake_nix_inputs() {
        let spec = make_spec();
        let content = generate_flake_nix(&spec);
        assert!(content.contains("nixpkgs.url"));
        assert!(content.contains("crate2nix.url"));
        assert!(content.contains("substrate"));
        assert!(content.contains("devenv"));
    }

    #[test]
    fn flake_nix_rmcp_crate_override() {
        let spec = make_spec();
        let content = generate_flake_nix(&spec);
        assert!(content.contains("crateOverrides"));
        assert!(content.contains("CARGO_CRATE_NAME = \"rmcp\""));
    }

    // -- module/default.nix --

    #[test]
    fn module_nix_service_namespace() {
        let spec = make_spec();
        let content = generate_module_nix(&spec);
        assert!(content.contains("services.pet_store"));
    }

    #[test]
    fn module_nix_mcp_options() {
        let spec = make_spec();
        let content = generate_module_nix(&spec);
        assert!(content.contains("mkMcpOptions"));
        assert!(content.contains("mkMcpServerEntry"));
    }

    #[test]
    fn module_nix_settings() {
        let spec = make_spec();
        let content = generate_module_nix(&spec);
        assert!(content.contains("apiUrl"));
        assert!(content.contains("apiKeyFile"));
        assert!(content.contains("propagateApiKey"));
    }

    #[test]
    fn module_nix_env_propagation() {
        let spec = make_spec();
        let content = generate_module_nix(&spec);
        assert!(content.contains("PET_STORE_CONFIG"));
    }

    // -- .gitignore --

    #[test]
    fn gitignore_content() {
        let content = generate_gitignore();
        assert!(content.contains("/target"));
        assert!(content.contains("/result"));
    }

    // -- Scaffold with no base_url falls back to example.com --

    #[test]
    fn config_rs_no_base_url_uses_fallback() {
        let mut spec = make_spec();
        spec.base_url = None;
        let content = generate_config_rs(&spec);
        assert!(content.contains("https://api.example.com"));
    }

    // -- Module nix with no base_url --

    #[test]
    fn module_nix_no_base_url_uses_fallback() {
        let mut spec = make_spec();
        spec.base_url = None;
        let content = generate_module_nix(&spec);
        assert!(content.contains("https://api.example.com"));
    }

    // -- Flake description with no spec description --

    #[test]
    fn flake_nix_no_description_uses_fallback() {
        let mut spec = make_spec();
        spec.description = None;
        let content = generate_flake_nix(&spec);
        assert!(content.contains("pet_store -- Rust CLI + MCP server"));
    }

    // -- Main.rs with no description --

    #[test]
    fn main_rs_no_description_uses_fallback() {
        let mut spec = make_spec();
        spec.description = None;
        let content = generate_main_rs(&spec);
        assert!(content.contains("pet_store CLI + MCP server"));
    }

    // -- Error.rs env var name follows snake_case UPPER pattern --

    #[test]
    fn error_rs_env_var_for_custom_name() {
        let mut spec = make_spec();
        spec.name = "My Cool API".into();
        let content = generate_error_rs(&spec);
        assert!(content.contains("MY_COOL_API_API_KEY"));
    }

    // -- Config loads from XDG + HOME --

    #[test]
    fn config_rs_has_home_fallback() {
        let spec = make_spec();
        let content = generate_config_rs(&spec);
        assert!(content.contains(".config/pet_store/pet_store.yaml"));
    }

    // -- Auth.rs expand_tilde handles non-tilde paths --

    #[test]
    fn auth_rs_has_expand_tilde() {
        let spec = make_spec();
        let content = generate_auth_rs(&spec);
        assert!(content.contains("fn expand_tilde("));
    }

    // -- Scaffold files are all non-empty --

    #[test]
    fn scaffold_files_all_non_empty() {
        let spec = make_spec();
        let files = generate_scaffold(&spec);
        for (path, content) in &files {
            assert!(
                !content.is_empty(),
                "scaffold file should not be empty: {path}"
            );
        }
    }

    // -- Different spec name produces different naming --

    #[test]
    fn scaffold_uses_spec_name() {
        let mut spec = make_spec();
        spec.name = "Widget Factory".into();
        let files = generate_scaffold(&spec);
        let cargo = files.iter().find(|(p, _)| p == "Cargo.toml").unwrap();
        assert!(cargo.1.contains("widget_factory"));

        let main = files.iter().find(|(p, _)| p == "src/main.rs").unwrap();
        assert!(main.1.contains("WidgetFactoryConfig"));

        let error = files.iter().find(|(p, _)| p == "src/error.rs").unwrap();
        assert!(error.1.contains("WidgetFactoryError"));
    }

    // -- flake.nix has homeManagerModules --

    #[test]
    fn flake_nix_has_hm_modules() {
        let spec = make_spec();
        let content = generate_flake_nix(&spec);
        assert!(content.contains("homeManagerModules.default"));
    }

    // -- module/default.nix has mkIf --

    #[test]
    fn module_nix_has_mkif() {
        let spec = make_spec();
        let content = generate_module_nix(&spec);
        assert!(content.contains("mkIf cfg.enable"));
        assert!(content.contains("mkIf mcpCfg.enable"));
    }

    // -- config.rs serde(default) attribute --

    #[test]
    fn config_rs_has_serde_default() {
        let spec = make_spec();
        let content = generate_config_rs(&spec);
        assert!(content.contains("#[serde(default)]"));
    }

    // -- auth.rs returns error for empty key file --

    #[test]
    fn auth_rs_handles_empty_key() {
        let spec = make_spec();
        let content = generate_auth_rs(&spec);
        assert!(content.contains("key.is_empty()"));
    }

    // -- main.rs has MCP server mode --

    #[test]
    fn main_rs_has_mcp_server_mode() {
        let spec = make_spec();
        let content = generate_main_rs(&spec);
        assert!(content.contains("mcp::run().await"));
    }

    // -- Cargo.toml has bin section --

    #[test]
    fn cargo_toml_has_bin_section() {
        let spec = make_spec();
        let content = generate_cargo_toml(&spec);
        assert!(content.contains("[[bin]]"));
        assert!(content.contains("path = \"src/main.rs\""));
    }
}