turbomcp-cli 3.1.3

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

use crate::cli::{NewArgs, ProjectTemplate};
use crate::error::{CliError, CliResult};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
const WORKER_VERSION: &str = "0.8";

/// Execute the new project command.
pub fn execute(args: &NewArgs) -> CliResult<()> {
    // Determine output directory
    let output_dir = args
        .output
        .clone()
        .unwrap_or_else(|| PathBuf::from(&args.name));

    // Check if directory already exists
    if output_dir.exists() {
        return Err(CliError::Other(format!(
            "Directory '{}' already exists",
            output_dir.display()
        )));
    }

    println!("Creating new MCP server project '{}'...", args.name);
    println!("  Template: {}", args.template);

    // Create project directory
    fs::create_dir_all(&output_dir)
        .map_err(|e| CliError::Other(format!("Failed to create directory: {}", e)))?;

    // Generate project files based on template
    match args.template {
        ProjectTemplate::Minimal => generate_minimal(args, &output_dir)?,
        ProjectTemplate::Full => generate_full(args, &output_dir)?,
        ProjectTemplate::CloudflareWorkers => generate_cloudflare_workers(args, &output_dir)?,
        ProjectTemplate::CloudflareWorkersOauth => {
            generate_cloudflare_workers_oauth(args, &output_dir)?
        }
        ProjectTemplate::CloudflareWorkersDurableObjects => {
            generate_cloudflare_workers_do(args, &output_dir)?
        }
    }

    // Initialize git repository if requested
    if args.git {
        init_git(&output_dir)?;
    }

    println!("\nProject created successfully!");
    println!("\nNext steps:");
    println!("  cd {}", output_dir.display());

    match args.template {
        ProjectTemplate::CloudflareWorkers
        | ProjectTemplate::CloudflareWorkersOauth
        | ProjectTemplate::CloudflareWorkersDurableObjects => {
            println!("  npx wrangler dev    # Start local development");
            println!("  npx wrangler deploy # Deploy to Cloudflare");
        }
        _ => {
            println!("  cargo build         # Build the server");
            println!("  cargo run           # Run the server");
        }
    }

    Ok(())
}

/// Generate a minimal MCP server project.
fn generate_minimal(args: &NewArgs, output_dir: &Path) -> CliResult<()> {
    let description = args
        .description
        .as_deref()
        .unwrap_or("A minimal MCP server");

    // Cargo.toml
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"
description = "{description}"
{author}

[dependencies]
turbomcp = "{sdk_version}"
tokio = {{ version = "1", features = ["full"] }}
serde = {{ version = "1", features = ["derive"] }}
schemars = "1.2"
"#,
        name = args.name,
        description = description,
        sdk_version = SDK_VERSION,
        author = args
            .author
            .as_ref()
            .map(|a| format!("authors = [\"{}\"]", a))
            .unwrap_or_default(),
    );

    // src/main.rs
    let main_rs = format!(
        r#"//! {description}

use turbomcp::prelude::*;
use serde::Deserialize;

#[derive(Clone)]
struct {struct_name};

#[derive(Deserialize, schemars::JsonSchema)]
struct HelloArgs {{
    /// Name to greet
    name: String,
}}

#[server(name = "{name}", version = "0.1.0")]
impl {struct_name} {{
    /// Say hello to someone
    #[tool("Say hello to someone")]
    async fn hello(&self, args: HelloArgs) -> String {{
        format!("Hello, {{}}!", args.name)
    }}
}}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {{
    let server = {struct_name};
    server.run_stdio().await?;
    Ok(())
}}
"#,
        description = description,
        struct_name = to_struct_name(&args.name),
        name = args.name,
    );

    // Write files
    write_file(output_dir, "Cargo.toml", &cargo_toml)?;
    fs::create_dir_all(output_dir.join("src"))?;
    write_file(&output_dir.join("src"), "main.rs", &main_rs)?;

    // .gitignore
    write_file(output_dir, ".gitignore", "/target\n")?;

    Ok(())
}

/// Generate a full-featured MCP server project.
fn generate_full(args: &NewArgs, output_dir: &Path) -> CliResult<()> {
    let description = args
        .description
        .as_deref()
        .unwrap_or("A full-featured MCP server");

    // Cargo.toml
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"
description = "{description}"
{author}

[dependencies]
turbomcp = {{ version = "{sdk_version}", features = ["http", "auth"] }}
tokio = {{ version = "1", features = ["full"] }}
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
schemars = "1.2"
tracing = "0.1"
tracing-subscriber = {{ version = "0.3", features = ["env-filter"] }}
"#,
        name = args.name,
        description = description,
        sdk_version = SDK_VERSION,
        author = args
            .author
            .as_ref()
            .map(|a| format!("authors = [\"{}\"]", a))
            .unwrap_or_default(),
    );

    // src/main.rs
    let main_rs = format!(
        r#"//! {description}

use turbomcp::prelude::*;
use serde::{{Deserialize, Serialize}};
use tracing_subscriber::{{layer::SubscriberExt, util::SubscriberInitExt}};

#[derive(Clone)]
struct {struct_name} {{
    config: ServerConfig,
}}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct ServerConfig {{
    name: String,
}}

// Tool argument types
#[derive(Deserialize, schemars::JsonSchema)]
struct HelloArgs {{
    /// Name to greet
    name: String,
}}

#[derive(Deserialize, schemars::JsonSchema)]
struct CalculateArgs {{
    /// First number
    a: f64,
    /// Second number
    b: f64,
    /// Operation to perform
    operation: String,
}}

// Prompt argument types
#[derive(Deserialize, schemars::JsonSchema)]
struct GreetingArgs {{
    /// User's name
    name: String,
    /// Tone of greeting
    tone: Option<String>,
}}

#[server(
    name = "{name}",
    version = "0.1.0",
    description = "{description}"
)]
impl {struct_name} {{
    /// Say hello to someone
    #[tool("Say hello to someone")]
    async fn hello(&self, args: HelloArgs) -> String {{
        format!("Hello, {{}}!", args.name)
    }}

    /// Perform a calculation
    #[tool("Perform basic arithmetic")]
    async fn calculate(&self, args: CalculateArgs) -> Result<String, ToolError> {{
        let result = match args.operation.as_str() {{
            "add" => args.a + args.b,
            "subtract" => args.a - args.b,
            "multiply" => args.a * args.b,
            "divide" => {{
                if args.b == 0.0 {{
                    return Err(ToolError::new("Cannot divide by zero"));
                }}
                args.a / args.b
            }}
            _ => return Err(ToolError::new(format!(
                "Unknown operation: {{}}. Use: add, subtract, multiply, divide",
                args.operation
            ))),
        }};
        Ok(format!("{{}} {{}} {{}} = {{}}", args.a, args.operation, args.b, result))
    }}

    /// Server configuration
    #[resource("config://server")]
    async fn config(&self, _uri: String) -> ResourceResult {{
        ResourceResult::json("config://server", &self.config)
            .unwrap_or_else(|e| ResourceResult::text("config://server", format!("Error: {{}}", e)))
    }}

    /// Greeting prompt
    #[prompt("Generate a greeting")]
    async fn greeting(&self, args: GreetingArgs) -> PromptResult {{
        let tone = args.tone.as_deref().unwrap_or("friendly");
        PromptResult::user(format!(
            "Generate a {{}} greeting for {{}}.",
            tone,
            args.name
        ))
    }}
}}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {{
    // Initialize tracing
    tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::new(
            std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into()),
        ))
        .with(tracing_subscriber::fmt::layer())
        .init();

    let server = {struct_name} {{
        config: ServerConfig {{
            name: "{name}".to_string(),
        }},
    }};

    // Choose transport based on environment
    if std::env::var("MCP_HTTP").is_ok() {{
        tracing::info!("Starting HTTP server on port 8080...");
        server.run_http("0.0.0.0:8080").await?;
    }} else {{
        tracing::info!("Starting STDIO server...");
        server.run_stdio().await?;
    }}

    Ok(())
}}
"#,
        description = description,
        struct_name = to_struct_name(&args.name),
        name = args.name,
    );

    // Write files
    write_file(output_dir, "Cargo.toml", &cargo_toml)?;
    fs::create_dir_all(output_dir.join("src"))?;
    write_file(&output_dir.join("src"), "main.rs", &main_rs)?;

    // .gitignore
    write_file(output_dir, ".gitignore", "/target\n")?;

    Ok(())
}

/// Generate a Cloudflare Workers MCP server project.
fn generate_cloudflare_workers(args: &NewArgs, output_dir: &Path) -> CliResult<()> {
    let description = args
        .description
        .as_deref()
        .unwrap_or("An MCP server for Cloudflare Workers");

    // Cargo.toml
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"
description = "{description}"
{author}

[lib]
crate-type = ["cdylib"]

[dependencies]
turbomcp-wasm = {{ version = "{sdk_version}", features = ["macros", "streamable"] }}
worker = "{worker_version}"
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
schemars = "1.2"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
console_error_panic_hook = "0.1"

[profile.release]
opt-level = "s"
lto = true
"#,
        name = args.name,
        description = description,
        sdk_version = SDK_VERSION,
        worker_version = WORKER_VERSION,
        author = args
            .author
            .as_ref()
            .map(|a| format!("authors = [\"{}\"]", a))
            .unwrap_or_default(),
    );

    // wrangler.toml
    let wrangler_toml = format!(
        r#"name = "{name}"
main = "build/worker/shim.mjs"
compatibility_date = "2024-01-01"

[build]
command = "cargo install -q worker-build && worker-build --release"

# Uncomment for KV storage
# [[kv_namespaces]]
# binding = "MY_KV"
# id = "your-kv-namespace-id"

# Uncomment for Durable Objects
# [[durable_objects.bindings]]
# name = "MCP_STATE"
# class_name = "McpState"
"#,
        name = args.name,
    );

    // src/lib.rs
    let lib_rs = format!(
        r#"//! {description}

use turbomcp_wasm::prelude::*;
use serde::Deserialize;
use worker::*;

#[derive(Clone)]
struct {struct_name};

#[derive(Deserialize, schemars::JsonSchema)]
struct HelloArgs {{
    /// Name to greet
    name: String,
}}

#[server(name = "{name}", version = "0.1.0")]
impl {struct_name} {{
    /// Say hello to someone
    #[tool("Say hello to someone")]
    async fn hello(&self, args: HelloArgs) -> String {{
        format!("Hello, {{}}!", args.name)
    }}

    /// Get server status
    #[tool("Check server health")]
    async fn status(&self) -> String {{
        "OK".to_string()
    }}
}}

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {{
    console_error_panic_hook::set_once();

    let server = {struct_name};
    let mcp = server.into_mcp_server();

    mcp.handle(req).await
}}
"#,
        description = description,
        struct_name = to_struct_name(&args.name),
        name = args.name,
    );

    // Write files
    write_file(output_dir, "Cargo.toml", &cargo_toml)?;
    write_file(output_dir, "wrangler.toml", &wrangler_toml)?;
    fs::create_dir_all(output_dir.join("src"))?;
    write_file(&output_dir.join("src"), "lib.rs", &lib_rs)?;

    // .gitignore
    write_file(output_dir, ".gitignore", "/target\n/build\n/node_modules\n")?;

    Ok(())
}

/// Generate a Cloudflare Workers MCP server with OAuth 2.1.
fn generate_cloudflare_workers_oauth(args: &NewArgs, output_dir: &Path) -> CliResult<()> {
    let description = args
        .description
        .as_deref()
        .unwrap_or("An MCP server for Cloudflare Workers with OAuth 2.1");

    // Cargo.toml
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"
description = "{description}"
{author}

[lib]
crate-type = ["cdylib"]

[dependencies]
turbomcp-wasm = {{ version = "{sdk_version}", features = ["macros", "streamable", "auth"] }}
worker = "{worker_version}"
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
schemars = "1.2"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
console_error_panic_hook = "0.1"

[profile.release]
opt-level = "s"
lto = true
"#,
        name = args.name,
        description = description,
        sdk_version = SDK_VERSION,
        worker_version = WORKER_VERSION,
        author = args
            .author
            .as_ref()
            .map(|a| format!("authors = [\"{}\"]", a))
            .unwrap_or_default(),
    );

    // wrangler.toml
    let wrangler_toml = format!(
        r#"name = "{name}"
main = "build/worker/shim.mjs"
compatibility_date = "2024-01-01"

[build]
command = "cargo install -q worker-build && worker-build --release"

# OAuth token storage
[[kv_namespaces]]
binding = "OAUTH_TOKENS"
id = "your-kv-namespace-id"

# Secrets (set via wrangler secret put)
# JWT_SECRET - Secret for signing JWT tokens
# OAUTH_CLIENT_SECRET - OAuth client secret
"#,
        name = args.name,
    );

    // src/lib.rs
    let lib_rs = format!(
        r#"//! {description}

use turbomcp_wasm::prelude::*;
use turbomcp_wasm::wasm_server::{{WithAuth, AuthExt}};
use serde::Deserialize;
use worker::*;
use std::sync::Arc;

#[derive(Clone)]
struct {struct_name};

#[derive(Deserialize, schemars::JsonSchema)]
struct HelloArgs {{
    /// Name to greet
    name: String,
}}

#[server(name = "{name}", version = "0.1.0")]
impl {struct_name} {{
    /// Say hello to someone (requires authentication)
    #[tool("Say hello to someone")]
    async fn hello(&self, ctx: Arc<RequestContext>, args: HelloArgs) -> Result<String, ToolError> {{
        // Check authentication
        if !ctx.is_authenticated() {{
            return Err(ToolError::new("Authentication required"));
        }}

        let user = ctx.user_id().unwrap_or("unknown");
        Ok(format!("Hello, {{}}! (authenticated as {{}})", args.name, user))
    }}

    /// Get server status (public)
    #[tool("Check server health")]
    async fn status(&self) -> String {{
        "OK".to_string()
    }}
}}

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {{
    console_error_panic_hook::set_once();

    let server = {struct_name};
    let mcp = server
        .into_mcp_server()
        .with_jwt_auth(env.secret("JWT_SECRET")?.to_string());

    mcp.handle(req).await
}}
"#,
        description = description,
        struct_name = to_struct_name(&args.name),
        name = args.name,
    );

    // Write files
    write_file(output_dir, "Cargo.toml", &cargo_toml)?;
    write_file(output_dir, "wrangler.toml", &wrangler_toml)?;
    fs::create_dir_all(output_dir.join("src"))?;
    write_file(&output_dir.join("src"), "lib.rs", &lib_rs)?;

    // .gitignore
    write_file(output_dir, ".gitignore", "/target\n/build\n/node_modules\n")?;

    Ok(())
}

/// Generate a Cloudflare Workers MCP server with Durable Objects.
fn generate_cloudflare_workers_do(args: &NewArgs, output_dir: &Path) -> CliResult<()> {
    let description = args
        .description
        .as_deref()
        .unwrap_or("An MCP server for Cloudflare Workers with Durable Objects");

    // Cargo.toml
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"
description = "{description}"
{author}

[lib]
crate-type = ["cdylib"]

[dependencies]
turbomcp-wasm = {{ version = "{sdk_version}", features = ["macros", "streamable"] }}
worker = "{worker_version}"
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
schemars = "1.2"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
console_error_panic_hook = "0.1"

[profile.release]
opt-level = "s"
lto = true
"#,
        name = args.name,
        description = description,
        sdk_version = SDK_VERSION,
        worker_version = WORKER_VERSION,
        author = args
            .author
            .as_ref()
            .map(|a| format!("authors = [\"{}\"]", a))
            .unwrap_or_default(),
    );

    // wrangler.toml
    let wrangler_toml = format!(
        r#"name = "{name}"
main = "build/worker/shim.mjs"
compatibility_date = "2024-01-01"

[build]
command = "cargo install -q worker-build && worker-build --release"

# Durable Objects for session and state management
[[durable_objects.bindings]]
name = "MCP_SESSIONS"
class_name = "McpSession"

[[durable_objects.bindings]]
name = "MCP_STATE"
class_name = "McpState"

[[durable_objects.bindings]]
name = "MCP_RATE_LIMIT"
class_name = "McpRateLimit"

[[migrations]]
tag = "v1"
new_classes = ["McpSession", "McpState", "McpRateLimit"]
"#,
        name = args.name,
    );

    // src/lib.rs
    let lib_rs = format!(
        r#"//! {description}

use turbomcp_wasm::prelude::*;
use turbomcp_wasm::wasm_server::{{
    DurableObjectSessionStore,
    DurableObjectStateStore,
    DurableObjectRateLimiter,
    RateLimitConfig,
    StreamableHandler,
}};
use serde::{{Deserialize, Serialize}};
use worker::*;
use std::sync::Arc;

#[derive(Clone)]
struct {struct_name} {{
    state_store: DurableObjectStateStore,
}}

#[derive(Deserialize, schemars::JsonSchema)]
struct HelloArgs {{
    /// Name to greet
    name: String,
}}

#[derive(Deserialize, schemars::JsonSchema)]
struct SaveArgs {{
    /// Key to save under
    key: String,
    /// Value to save
    value: String,
}}

#[derive(Deserialize, schemars::JsonSchema)]
struct LoadArgs {{
    /// Key to load
    key: String,
}}

#[server(name = "{name}", version = "0.1.0")]
impl {struct_name} {{
    /// Say hello to someone
    #[tool("Say hello to someone")]
    async fn hello(&self, args: HelloArgs) -> String {{
        format!("Hello, {{}}!", args.name)
    }}

    /// Save a value to persistent state
    #[tool("Save a value to persistent storage")]
    async fn save(&self, ctx: Arc<RequestContext>, args: SaveArgs) -> Result<String, ToolError> {{
        let session_id = ctx.session_id().unwrap_or("default");

        self.state_store
            .set(session_id, &args.key, &args.value)
            .await
            .map_err(|e| ToolError::new(format!("Failed to save: {{}}", e)))?;

        Ok(format!("Saved '{{}}' = '{{}}'", args.key, args.value))
    }}

    /// Load a value from persistent state
    #[tool("Load a value from persistent storage")]
    async fn load(&self, ctx: Arc<RequestContext>, args: LoadArgs) -> Result<String, ToolError> {{
        let session_id = ctx.session_id().unwrap_or("default");

        let value: Option<String> = self.state_store
            .get(session_id, &args.key)
            .await
            .map_err(|e| ToolError::new(format!("Failed to load: {{}}", e)))?;

        match value {{
            Some(v) => Ok(v),
            None => Ok(format!("Key '{{}}' not found", args.key)),
        }}
    }}
}}

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {{
    console_error_panic_hook::set_once();

    // Initialize Durable Object stores
    let session_store = DurableObjectSessionStore::from_env(&env, "MCP_SESSIONS")?;
    let state_store = DurableObjectStateStore::from_env(&env, "MCP_STATE")?;
    let rate_limiter = DurableObjectRateLimiter::from_env(&env, "MCP_RATE_LIMIT")?
        .with_config(RateLimitConfig::per_minute(100));

    let server = {struct_name} {{ state_store }};
    let mcp = server.into_mcp_server();

    // Use Streamable HTTP with session persistence
    let handler = StreamableHandler::new(mcp)
        .with_session_store(session_store);

    handler.handle(req).await
}}

// Durable Object implementations (minimal stubs - expand as needed)
// See turbomcp_wasm::wasm_server::durable_objects for protocol documentation

#[durable_object]
pub struct McpSession {{
    state: State,
    #[allow(dead_code)]
    env: Env,
}}

#[durable_object]
impl DurableObject for McpSession {{
    fn new(state: State, env: Env) -> Self {{
        Self {{ state, env }}
    }}

    async fn fetch(&mut self, req: Request) -> Result<Response> {{
        // Handle session storage requests
        // See DurableObjectSessionStore protocol documentation
        Response::ok("{{}}")
    }}
}}

#[durable_object]
pub struct McpState {{
    state: State,
    #[allow(dead_code)]
    env: Env,
}}

#[durable_object]
impl DurableObject for McpState {{
    fn new(state: State, env: Env) -> Self {{
        Self {{ state, env }}
    }}

    async fn fetch(&mut self, req: Request) -> Result<Response> {{
        // Handle state storage requests
        // See DurableObjectStateStore protocol documentation
        Response::ok("{{}}")
    }}
}}

#[durable_object]
pub struct McpRateLimit {{
    state: State,
    #[allow(dead_code)]
    env: Env,
}}

#[durable_object]
impl DurableObject for McpRateLimit {{
    fn new(state: State, env: Env) -> Self {{
        Self {{ state, env }}
    }}

    async fn fetch(&mut self, req: Request) -> Result<Response> {{
        // Handle rate limiting requests
        // See DurableObjectRateLimiter protocol documentation
        Response::ok("{{}}")
    }}
}}
"#,
        description = description,
        struct_name = to_struct_name(&args.name),
        name = args.name,
    );

    // Write files
    write_file(output_dir, "Cargo.toml", &cargo_toml)?;
    write_file(output_dir, "wrangler.toml", &wrangler_toml)?;
    fs::create_dir_all(output_dir.join("src"))?;
    write_file(&output_dir.join("src"), "lib.rs", &lib_rs)?;

    // .gitignore
    write_file(output_dir, ".gitignore", "/target\n/build\n/node_modules\n")?;

    Ok(())
}

/// Initialize a git repository in the project directory.
fn init_git(output_dir: &Path) -> CliResult<()> {
    let status = Command::new("git")
        .arg("init")
        .current_dir(output_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    match status {
        Ok(s) if s.success() => {
            println!("  Initialized git repository");
            Ok(())
        }
        _ => {
            println!("  Warning: Failed to initialize git repository");
            Ok(()) // Don't fail the whole operation
        }
    }
}

/// Write a file to the specified directory.
fn write_file(dir: &Path, name: &str, content: &str) -> CliResult<()> {
    let path = dir.join(name);
    fs::write(&path, content)
        .map_err(|e| CliError::Other(format!("Failed to write {}: {}", path.display(), e)))
}

/// Convert a project name to a valid Rust struct name.
fn to_struct_name(name: &str) -> String {
    let name = name
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '_' })
        .collect::<String>();

    // Convert to PascalCase
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in name.chars() {
        if c == '_' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }

    // Ensure it starts with a letter
    if result.chars().next().is_none_or(|c| c.is_ascii_digit()) {
        result = format!("Server{}", result);
    }

    result
}

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

    #[test]
    fn test_to_struct_name() {
        assert_eq!(to_struct_name("my-server"), "MyServer");
        assert_eq!(to_struct_name("hello_world"), "HelloWorld");
        assert_eq!(to_struct_name("123test"), "Server123test");
        assert_eq!(to_struct_name("simple"), "Simple");
    }

    #[test]
    fn test_template_display() {
        assert_eq!(ProjectTemplate::Minimal.to_string(), "minimal");
        assert_eq!(
            ProjectTemplate::CloudflareWorkers.to_string(),
            "cloudflare-workers"
        );
    }

    fn test_args(template: ProjectTemplate, output: &Path) -> NewArgs {
        NewArgs {
            name: "generated-server".to_string(),
            template,
            output: Some(output.to_path_buf()),
            git: false,
            description: None,
            author: None,
        }
    }

    #[test]
    fn generated_native_templates_use_current_sdk_version() {
        let dir = tempfile::tempdir().unwrap();
        let minimal = dir.path().join("minimal");
        fs::create_dir_all(&minimal).unwrap();
        generate_minimal(&test_args(ProjectTemplate::Minimal, &minimal), &minimal).unwrap();
        let cargo_toml = fs::read_to_string(minimal.join("Cargo.toml")).unwrap();
        assert!(cargo_toml.contains(&format!("turbomcp = \"{}\"", SDK_VERSION)));

        let full = dir.path().join("full");
        fs::create_dir_all(&full).unwrap();
        generate_full(&test_args(ProjectTemplate::Full, &full), &full).unwrap();
        let cargo_toml = fs::read_to_string(full.join("Cargo.toml")).unwrap();
        let main_rs = fs::read_to_string(full.join("src/main.rs")).unwrap();
        assert!(cargo_toml.contains(&format!("version = \"{}\"", SDK_VERSION)));
        assert!(!main_rs.contains("ResourceError"));
    }

    #[test]
    fn generated_worker_templates_use_current_versions_and_panic_hook() {
        let dir = tempfile::tempdir().unwrap();
        let cases = [
            (
                ProjectTemplate::CloudflareWorkers,
                generate_cloudflare_workers as fn(&NewArgs, &Path) -> CliResult<()>,
            ),
            (
                ProjectTemplate::CloudflareWorkersOauth,
                generate_cloudflare_workers_oauth as fn(&NewArgs, &Path) -> CliResult<()>,
            ),
            (
                ProjectTemplate::CloudflareWorkersDurableObjects,
                generate_cloudflare_workers_do as fn(&NewArgs, &Path) -> CliResult<()>,
            ),
        ];

        for (template, generate) in cases {
            let output = dir.path().join(template.to_string());
            fs::create_dir_all(&output).unwrap();
            generate(&test_args(template, &output), &output).unwrap();
            let cargo_toml = fs::read_to_string(output.join("Cargo.toml")).unwrap();
            assert!(cargo_toml.contains(&format!("version = \"{}\"", SDK_VERSION)));
            assert!(cargo_toml.contains(&format!("worker = \"{}\"", WORKER_VERSION)));
            assert!(cargo_toml.contains("console_error_panic_hook = \"0.1\""));
            assert!(!cargo_toml.contains("3.0"));
        }
    }
}