sdforge 0.3.1

Multi-protocol SDK framework with unified macro configuration
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
<div align="center" id="readme">

<img src="docs/asset/sdforge.png" alt="SDForge Logo" width="200" height="200">

[![Crates.io](https://img.shields.io/crates/v/sdforge)](https://crates.io/crates/sdforge) [![Documentation](https://img.shields.io/docsrs/sdforge)](https://docs.rs/sdforge) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Build Status](https://img.shields.io/github/actions/workflow/status/Kirky-X/sdforge/ci.yml?branch=main)](https://github.com/Kirky-X/sdforge/actions) [![Rust Version](https://img.shields.io/badge/rust-2021%2B-orange.svg)](https://www.rust-lang.org)

**SDForge** is a Rust-based declarative SDK framework that uses procedural macros to automatically generate multi-protocol service interfaces (HTTP + MCP) from unified function annotations. The key innovation is compile-time protocol selection via Cargo featuresβ€”unused protocols produce zero compiled code.

</div>

## πŸ“‹ Table of Contents

<style>
.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  text-decoration: none;
  border-radius: 5px;
  font-size: 14px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  transition: background-color 0.3s;
  z-index: 1000;
}

.back-to-top:hover {
  background-color: #0056b3;
}

.doc-nav {
  padding: 10px 0;
  margin-top: 20px;
  border-top: 1px solid #e1e4e8;
}
</style>

- [✨ Features]#features
- [πŸ“¦ Installation]#installation
- [πŸš€ Quick Start]#quick-start
- [βš™οΈ Feature System]#feature-system
- [πŸ’‘ Usage Examples]#usage-examples
- [πŸ“ Module Prefixes]#module-prefixes
- [πŸ”’ Version Management]#version-management
- [⚠️ Error Handling]#error-handling
- [πŸ›€οΈ Path Parameters]#path-parameters
- [πŸ”¨ Building and Testing]#building-and-testing
- [πŸ“š Documentation]#documentation
- [πŸ”’ Security Configuration]#security-configuration
- [⚑ Performance Optimization]#performance-optimization
- [πŸ“œ OpenAPI Auto-Generation]#openapi-generation
- [πŸ”„ MCP 2026-07-28 Migration Guide]#mcp-migration
- [πŸš€ Production Deployment]#deployment-guide
- [πŸ› Troubleshooting]#troubleshooting
- [🀝 Contributing]#contributing
- [πŸ“œ License]#license
- [πŸ“‚ Project Structure]#-project-structure
- [πŸ”— Links]#-links

---

## <span id="features">✨ Features</span>

<div style="border-radius:8px; padding:16px; border:1px solid #E2E8F0;">

- **🎯 Unified Interface Definition** - Single macro configuration for both HTTP and MCP protocols
- **⚑ Compile-Time Protocol Selection** - Feature-gated code generation with zero runtime overhead for unused protocols
- **πŸ”’ Type Safety** - Compile-time validation of interface definitions
- **🌐 Multi-Protocol Support** - HTTP (Axum), MCP, gRPC, WebSocket, SSE streaming
- **🧩 Modular Design** - Feature-based architecture allows selecting only needed functionality
- **πŸ›‘οΈ Security Features** - Built-in authentication, rate limiting, and request validation
- **πŸ’Ύ Caching** - In-memory caching (oxcache 0.3.2), no external database required
- **πŸ”§ Configuration Management** - Self-contained TOML configuration (no external config center)
- **πŸ“Š Versioning** - Built-in API version management

</div>

### πŸ†• Phase 1 Architecture Improvements (v0.1.0)

Recent architectural enhancements include:

- **πŸ”„ Unified Registration System** - Eliminated 95+ lines of duplicate code across HTTP, MCP, WebSocket, and gRPC modules using trait-based abstraction and procedural macros
- **βš™οΈ Modular Configuration Management** - Refactored configuration into dedicated modules (app, cache, security) with centralized defaults and Builder pattern support
- **πŸ” Enhanced Security Module** - API Key versioning, LRU caching, key rotation with audit logging, and comprehensive security headers configuration
- **πŸ’Ύ Advanced Caching** - Pattern-based cache invalidation, key normalization, batch operations, and statistics tracking

---

## <span id="installation">πŸ“¦ Installation</span>

<div style="border-radius:8px; padding:16px; border:1px solid #E2E8F0;">

Add SDForge to your `Cargo.toml`:

```toml
[dependencies]
sdforge = { version = "0.3", features = ["http"] }
```

</div>

---

## <span id="quick-start">πŸš€ Quick Start</span>

<div style="border-radius:8px; padding:16px; border:1px solid #E2E8F0;">

Define your API with a single macro:

```rust
use sdforge::prelude::*;

#[service_api(
    name = "get_user",
    version = "v1",
    path = "/users/:id",
    method = "GET",
    tool_name = "get_user",
    description = "Get a user by ID"
)]
async fn get_user(id: u64) -> Result<User, ApiError> {
    Ok(User { id, name: "Test".into() })
}

#[tokio::main]
async fn main() {
    let app = sdforge::http::build();
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
```

</div>

---

## <span id="feature-system">βš™οΈ Feature System</span>

SDForge uses Cargo features for compile-time protocol selection and feature composition.

### πŸ”§ Core Features

| Feature      | Description                              | Dependencies                                   |
|--------------|------------------------------------------|-----------------------------------------------|
| `http`       | HTTP server (Axum 0.8.8)                 | axum, tower, tower-http                        |
| `mcp`        | MCP protocol (rmcp 0.16, 2026-07-28 spec) | rmcp |
| `streaming`  | SSE streaming support                    | tokio-stream, futures-util                    |
| `timestamp`  | Auto-add timestamp to responses          | chrono                                        |
| `logging`    | Structured request logging                | chrono, tokio                                 |
| `security`   | Security features (auth, rate limiting)   | http, cache, uuid, hmac, sha2, chrono, tokio, secrets, zeroize, subtle, once_cell, argon2, password-hash, rand, regex, oxcache/memory, bincode, hex, base64 |
| `websocket`  | WebSocket support                        | tokio-tungstenite, axum-extra                |
| `grpc`       | gRPC support                             | tonic, prost                                 |
| `cache`      | Caching support                          | dep:http, oxcache/memory, async-trait         |
| `openapi`    | Automatic OpenAPI 3.1 spec generation    | utoipa, http                                  |
| `simd-json`  | SIMD-accelerated JSON serialization      | simd-json                                     |
| `hex`        | Hexadecimal encoding utility             | hex                                           |
| `full`       | All runtime features (excludes simd-json/hex tooling) | -                                |

### πŸ”— Feature Dependencies

- `default`: [`http`]
- `mcp`: Independent protocol (depends on external http crate for stateless HTTP header parsing, not sdforge http feature)
- `streaming`: Requires `http`
- `timestamp`: No dependencies
- `logging`: No dependencies
- `security`: Requires `http`, `cache`
- `websocket`: Requires `http`, `streaming`
- `grpc`: Requires `http`
- `cache`: Independent (uses http crate types, not sdforge http feature)
- `openapi`: Requires `http`

---

## πŸ’‘ Usage Examples

### 🌐 HTTP Only

For traditional REST APIs:

```toml
[dependencies]
sdforge = { version = "0.3", features = ["http"] }
```

### πŸ€– MCP Only

For AI tool integration:

```toml
[dependencies]
sdforge = { version = "0.3", features = ["mcp"] }
```

### πŸ”„ Both Protocols

Exposure via both HTTP and MCP from the same code:

```toml
[dependencies]
sdforge = { version = "0.3", features = ["http", "mcp"] }
```

### 🎯 Full Features

All capabilities enabled:

```toml
[dependencies]
sdforge = { version = "0.3", features = ["full"] }
```

---

## <span id="module-prefixes">πŸ“ Module Prefixes</span>

Group related APIs with module prefixes for better organization:

```rust
#[service_module(prefix = "/auth")]
mod auth_api {
    use super::*;

    #[service_api(
        name = "login",
        version = "v1",
        path = "/login",
        method = "POST"
    )]
    async fn login(credentials: Credentials) -> Result<Token, ApiError> {
        // Implementation
        Ok(Token::new())
    }

    #[service_api(
        name = "logout",
        version = "v1",
        path = "/logout",
        method = "POST"
    )]
    async fn logout() -> Result<(), ApiError> {
        // Implementation
        Ok(())
    }
}
```

This creates the endpoints:
- `/auth/api/v1/login`
- `/auth/api/v1/logout`

---

## <span id="version-management">πŸ”’ Version Management</span>

Support multiple API versions simultaneously:

```rust
#[service_api(
    name = "get_user",
    version = "v1",
    path = "/users/:id",
    method = "GET",
    tool_name = "get_user_v1"
)]
async fn get_user_v1(id: u64) -> Result<UserV1, ApiError> {
    Ok(UserV1 { id, name: "John Doe".into() })
}

#[service_api(
    name = "get_user",
    version = "v2",
    path = "/users/:id",
    method = "GET",
    tool_name = "get_user_v2"
)]
async fn get_user_v2(id: u64) -> Result<UserV2, ApiError> {
    Ok(UserV2 { id, first_name: "John".into(), last_name: "Doe".into() })
}
```

This creates versioned endpoints:
- `/api/v1/users/:id` β†’ `get_user_v1`
- `/api/v2/users/:id` β†’ `get_user_v2`

---

## <span id="error-handling">⚠️ Error Handling</span>

Define custom error types and convert them to `ServiceError`:

```rust
use thiserror::Error;

#[derive(Debug, Error)]
pub enum MyError {
    #[error("Resource not found: {resource}")]
    NotFound { resource: String },

    #[error("Validation failed: {field}")]
    ValidationError { field: String },

    #[error("Unauthorized access")]
    Unauthorized,
}

impl From<MyError> for ServiceError {
    fn from(err: MyError) -> Self {
        match err {
            MyError::NotFound { resource } => ServiceError::with_details(
                "NOT_FOUND",
                format!("Resource not found: {}", resource),
                serde_json::json!({ "resource": resource }),
                404,
            ),
            MyError::ValidationError { field } => ServiceError::with_details(
                "VALIDATION_ERROR",
                format!("Validation failed for field: {}", field),
                serde_json::json!({ "field": field }),
                400,
            ),
            MyError::Unauthorized => ServiceError::new(
                "UNAUTHORIZED",
                "Authentication required",
                401,
            ),
        }
    }
}
```

---

## <span id="path-parameters">πŸ›€οΈ Path Parameters</span>

Extract path parameters using Rust naming conventions. The macro automatically maps path segments to function parameters:

```rust
#[service_api(
    name = "get_user",
    version = "v1",
    path = "/users/:id",
    method = "GET"
)]
async fn get_user(id: u64) -> Result<User, ApiError> {
    // `id` is automatically extracted from `/users/:id`
    Ok(User { id, name: "John".into() })
}

#[service_api(
    name = "get_comment",
    version = "v1",
    path = "/posts/:post_id/comments/:comment_id",
    method = "GET"
)]
async fn get_comment(
    post_id: u64,
    comment_id: u64
) -> Result<Comment, ApiError> {
    // Both parameters are extracted from the path
    Ok(Comment { post_id, comment_id, text: "Test".into() })
}
```

### πŸ”Ή Multiple Path Parameters

For nested resources:

```rust
#[service_api(
    name = "get_nested_resource",
    version = "v1",
    path = "/orgs/:org_id/projects/:project_id/tasks/:task_id",
    method = "GET"
)]
async fn get_task(
    org_id: u64,
    project_id: u64,
    task_id: u64
) -> Result<Task, ApiError> {
    Ok(Task { org_id, project_id, task_id, title: "Task".into() })
}
```

---

## <span id="building-and-testing">πŸ”¨ Building and Testing</span>

### πŸ”§ Build Commands

```bash
# Build with HTTP only
cargo build --features http

# Build with MCP only
cargo build --features mcp

# Build with all features
cargo build --features full

# Build with custom feature set
cargo build --features "http,cache,security"

# Release build
cargo build --release --features http
```

### πŸ§ͺ Test Commands

```bash
# Run tests with HTTP
cargo test --features http

# Run tests with MCP
cargo test --features mcp

# Run tests with both protocols
cargo test --features "http,mcp"

# Run tests with all features
cargo test --features full

# Run specific test
cargo test test_get_user --features http

# Run tests with output
cargo test --features http -- --nocapture

# Run tests in release mode
cargo test --release --features http
```

### ✨ Formatting and Linting

```bash
# Format code
cargo fmt

# Check formatting
cargo fmt --check

# Run Clippy
cargo clippy --all-features

# Run Clippy with all targets
cargo clippy --all-features --all-targets
```

---

## <span id="documentation">πŸ“š Documentation</span>

- [πŸ“– API Documentation]https://docs.rs/sdforge
- [πŸ’‘ Examples]./examples/

---

## <span id="contributing">🀝 Contributing</span>

We welcome contributions! Please submit pull requests with clear descriptions of your changes.

### πŸ› οΈ Development Setup

```bash
# Clone the repository
git clone https://github.com/Kirky-X/sdforge.git
cd sdforge

# Install pre-commit hooks
./scripts/install-pre-commit.sh

# Install development tools
cargo install cargo-watch cargo-edit

# Run tests
cargo test --all-features
```

### πŸ“ Code Style

- Format code with `cargo fmt` before committing
- Run `cargo clippy --all-features` to check for issues
- Follow the existing code style and patterns
- Add tests for new features
- Update documentation as needed

---

## <span id="license">πŸ“œ License</span>

Licensed under the MIT License:

- [MIT License]LICENSE or http://opensource.org/licenses/MIT

---

## <span id="project-structure">πŸ“‚ Project Structure</span>

```
sdforge/
β”œβ”€β”€ src/                # Main framework crate
β”‚   β”œβ”€β”€ core/         # Core types and error handling
β”‚   β”œβ”€β”€ http/         # HTTP protocol implementation
β”‚   β”œβ”€β”€ mcp/          # MCP protocol implementation
β”‚   β”œβ”€β”€ security/     # Security features
β”‚   β”œβ”€β”€ cache/        # Caching implementation
β”‚   β”œβ”€β”€ websocket/    # WebSocket support
β”‚   β”œβ”€β”€ grpc/         # gRPC support
β”‚   β”œβ”€β”€ streaming/    # SSE streaming support
β”‚   β”œβ”€β”€ config/       # Configuration management
β”‚   └── lib.rs        # Library entry point
β”œβ”€β”€ macros/            # Procedural macros crate
β”‚   β”œβ”€β”€ src/
β”‚   └── Cargo.toml
β”œβ”€β”€ docs/              # Documentation
β”œβ”€β”€ .github/           # GitHub workflows
└── scripts/           # Build and utility scripts
```

---

## <span id="links">πŸ”— Links</span>

- **🏠 Repository**: https://github.com/Kirky-X/sdforge
- **πŸ“– Documentation**: https://docs.rs/sdforge
- **πŸ› Issues**: https://github.com/Kirky-X/sdforge/issues
- **πŸ’¬ Discussions**: https://github.com/Kirky-X/sdforge/discussions

---

## <span id="security-configuration">πŸ”’ Security Configuration</span>

SDForge provides comprehensive security features out of the box. Here's how to configure them:

### πŸ›‘οΈ Authentication Setup

```rust
use sdforge::prelude::*;

#[service_api(
    name = "secure_endpoint",
    version = "v1",
    path = "/secure",
    method = "GET",
    auth_required = true
)]
async fn secure_endpoint(
    auth_context: AuthContext
) -> Result<String, ApiError> {
    // Only authenticated users can access this
    Ok(format!("Hello, {}!", auth_context.user_id().unwrap_or("Anonymous")))
}
```

### ⚑ Rate Limiting

```toml
# config.toml
[rate_limit]
enabled = true
requests_per_minute = 60
burst_size = 10
```

### πŸ” API Key Authentication

```rust
use sdforge::security::{ApiKeyAuth, auth_middleware};

let app = Router::new()
    .route("/api/*path", get(handler))
    .layer(auth_middleware(ApiKeyAuth::new("your-secret-key")));
```

### ⚠️ Security Defaults (v0.3.0+)

> **Note**: v0.3.0 tightened security defaults. Please check during migration:
> - **JWT secret minimum length**: `MIN_SECRET_LENGTH=32`. Secrets shorter than 32 characters are rejected with an error
> - **ServerConfig default host**: Changed from `"0.0.0.0"` (fail-open) to `"127.0.0.1"` (fail-safe loopback). Production deployments must explicitly configure host
> - **CORS validation tightened**: `"http://"` (scheme only, no host) is now rejected

---

## <span id="performance-optimization">⚑ Performance Optimization</span>

### πŸš€ Caching Configuration

```toml
# config.toml
[cache]
enabled = true
default_ttl_secs = 600
max_items = 5000
track_stats = true
```

### πŸ“Š Memory Management

```rust
use sdforge::config::CacheConfig;

let cache_config = CacheConfig {
    enabled: true,
    default_ttl_secs: 600,
    max_items: 5000,
    track_stats: true,
};
```

### βš™οΈ Connection Pooling

```rust
use sdforge::config::AppConfig;
use sdforge::http::build_with_config;

let config = AppConfig::default();
let app = build_with_config(&config)?;
```

---

## <span id="openapi-generation">πŸ“œ OpenAPI Auto-Generation</span>

SDForge v0.2.0 introduces automatic OpenAPI 3.1 specification generation based on [utoipa 5.5](https://crates.io/crates/utoipa). When the `openapi` feature is enabled, each `#[service_api]` macro registers an `OpenApiRouteInfo` at compile time via `inventory`. At runtime, calling `generate_openapi_spec()` collects all routes and generates a complete specification.

### πŸ”§ Enabling

```toml
[dependencies]
sdforge = { version = "0.3", features = ["http", "openapi"] }
```

### πŸš€ Basic Usage

```rust
use sdforge::openapi::generate_openapi_spec;

// Collect all routes registered via #[service_api] and generate the OpenAPI specification
let spec = generate_openapi_spec();

// Serialize to JSON to write to a file or return to the client
let json = serde_json::to_string_pretty(&spec).unwrap();
println!("{json}");
```

### 🎨 Custom Metadata

Use the `OpenApiBuilder` chainable calls to customize the `info` section (title, version, description). Routes are always collected from the global `inventory` registry:

```rust
use sdforge::openapi::OpenApiBuilder;

let spec = OpenApiBuilder::new()
    .title("My Service")
    .version("2.0.0")
    .description("User-facing API for the billing domain")
    .build();
```

### πŸ”— Macro Integration

When the `openapi` feature is enabled, `#[service_api]` automatically generates registration codeβ€”no manual maintenance required:

```rust
#[service_api(
    name = "get_user",
    version = "v1",
    path = "/users/:id",
    method = "GET",
    description = "Get a user by ID"
)]
async fn get_user(id: u64) -> Result<User, ApiError> { /* ... */ }
```

The above code automatically submits an `OpenApiRouteInfo { path: "/users/{id}", method: "GET", ... }` to the global registry at compile time. `generate_openapi_spec()` will include it in the generated specification.

> **Note**: When the `openapi` feature is not enabled, the macro does not generate any utoipa-related codeβ€”zero runtime overhead.

---

## <span id="mcp-migration">πŸ”„ MCP 2026-07-28 Migration Guide</span>

v0.2.0 fully migrates the MCP implementation from `mcp-sdk 0.0.3` to [`rmcp 0.16`](https://crates.io/crates/rmcp), adapting to the MCP 2026-07-28 specification. This migration is a **BREAKING** change.

### ⚠️ BREAKING Changes

| Old Version (v0.1.x)                  | New Version (v0.2.0)                          |
|----------------------------------------|-----------------------------------------------|
| `mcp-sdk = "0.0.3"` dependency          | `rmcp = "0.16"` dependency                    |
| `initialize` handshake flow             | Removed, replaced with `server/discover` endpoint |
| Stateful sessions (`StatefulServerHandler`) | Stateless adapter layer (`StatelessServerHandler`) |
| `register_mcp(&mut Server)` signature   | `register_mcp(&mut dyn McpToolRegistry)`      |

### πŸ› οΈ Stateless Adapter Layer

`StatelessServerHandler` implements the `rmcp::ServerHandler` trait. None of its methods depend on session state, adapting to the stateless protocol model of the 2026-07-28 specification:

```rust
use sdforge::mcp::stateless::StatelessServerHandler;

let handler = StatelessServerHandler::new();
// Mount to HTTP routes via rmcp's axum integration
```

### πŸ“¨ HTTP Header Protocol

The stateless protocol passes methods and tool names through HTTP headers, parsed by `parse_mcp_headers`:

```rust
use sdforge::mcp::headers::parse_mcp_headers;

// Client requests must carry:
//   Mcp-Method: tools/call
//   Mcp-Name: get_user
let info = parse_mcp_headers(&headers)?;
```

Missing headers return `400 Bad Request`, consistent with the 2026-07-28 specification.

### πŸ” Multi Round-Trip Requests (MRTR)

New MRTR support is added. Tools can suspend execution via `InputRequiredResult` and wait for the client to provide additional input. It is automatically canceled after a 300-second timeout:

```rust
use sdforge::mcp::mrtr::MrtrSessionManager;

let manager = MrtrSessionManager::new();
let result = manager.create_session("session-1", "get_user")?;
// The client later resumes execution via session_id
```

### πŸ’Ύ Cache Semantics

The `cache_semantics` module handles the `ttlMs` and `cacheScope` fields, supporting both `global` and `request` cache scopes. It integrates with oxcache to implement tool result caching.

### πŸ“š Migration Steps

1. Replace the `mcp-sdk` dependency in `Cargo.toml` with `rmcp` (`features = ["server"]`)
2. Change the `register_mcp(&mut Server)` call to `register_mcp(&mut dyn McpToolRegistry)`
3. Remove the `initialize` handshake-related code and use the `server/discover` endpoint instead
4. If you need MRTR or cache semantics, import the corresponding modules

> For the complete migration example, see `examples/src/mcp/migration_2026.rs`.

---

## <span id="deployment-guide">πŸš€ Production Deployment</span>

### 🐳 Docker Deployment

```dockerfile
FROM rust:1.75 as builder
WORKDIR /app
COPY . .
RUN cargo build --release --features full

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/sdforge /usr/local/bin/
EXPOSE 3000
CMD ["sdforge", "serve", "--port", "3000"]
```

### ☸️ Kubernetes Deployment

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: sdforge-api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: sdforge-api
  template:
    metadata:
      labels:
        app: sdforge-api
    spec:
      containers:
      - name: sdforge
        image: sdforge:latest
        ports:
        - containerPort: 3000
        env:
        - name: FEATURES
          value: "full"
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"
```

### πŸ”§ Environment Configuration

```bash
# Production environment variables
export RUST_LOG=info
export SD_FORGE_PORT=3000
export SD_FORGE_HOST=0.0.0.0
export SD_FORGE_CONFIG_PATH=/etc/sdforge/config.toml
export SD_FORGE_FEATURES=full
```

---

## <span id="troubleshooting">πŸ› Troubleshooting</span>

### πŸ” Common Issues

#### **Compilation Errors**
```bash
# Error: Feature not found
# Solution: Check available features
cargo check --help | grep features

# Enable specific features
cargo build --features "http,security,cache"
```

#### **Runtime Issues**
```bash
# Check logs with tracing
RUST_LOG=debug cargo run --features logging

# Common port conflicts
# Solution: Change port or kill existing process
lsof -i :3000
kill -9 <PID>
```

#### **Performance Issues**
```bash
# Profile with cargo-flamegraph
cargo install flamegraph
cargo flamegraph --bin sdforge --features full

# Memory usage analysis
valgrind --tool=massif target/release/sdforge
```

### πŸ“‹ Health Check Endpoint

```rust
#[service_api(
    name = "health_check",
    version = "v1",
    path = "/health",
    method = "GET"
)]
async fn health_check() -> Result<HealthStatus, ApiError> {
    Ok(HealthStatus {
        status: "healthy".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        uptime: get_uptime(),
    })
}
```

### πŸ†˜ Getting Help

- πŸ“– [Documentation]https://docs.rs/sdforge
- πŸ› [Issue Tracker]https://github.com/Kirky-X/sdforge/issues
- πŸ’¬ [Discussions]https://github.com/Kirky-X/sdforge/discussions
- πŸ“§ [Support Email]mailto:support@sdforge.dev

---

<div align="center">

**Built with ❀️ using Rust**

</div>

---

<div align="center">

[πŸ” Back To Top]#readme | [πŸ‡¨πŸ‡³ δΈ­ζ–‡η‰ˆ]./README.md

</div>

<style>
.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  text-decoration: none;
  border-radius: 5px;
  font-size: 14px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  transition: background-color 0.3s;
  z-index: 1000;
}

.back-to-top:hover {
  background-color: #0056b3;
}
</style>