httpmcp-rust 0.1.4

A fast, simple library for building MCP servers using Streamable HTTP (Beta)
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
# httpmcp-rust

[![CI](https://github.com/renaiss-ai/httpmcp-rust/workflows/CI/badge.svg)](https://github.com/renaiss-ai/httpmcp-rust/actions)
[![Crates.io](https://img.shields.io/crates/v/httpmcp-rust.svg)](https://crates.io/crates/httpmcp-rust)
[![Documentation](https://docs.rs/httpmcp-rust/badge.svg)](https://docs.rs/httpmcp-rust)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](LICENSE-MIT)
[![Rust Version](https://img.shields.io/badge/rust-1.70%2B-orange.svg)](https://www.rust-lang.org)

> ⚠️ **Beta Status**: This library is currently in beta. The API is still evolving and may have breaking changes. Not recommended for production use yet.

A **fast** and **simple** Rust library for building MCP (Model Context Protocol) servers using Streamable HTTP.

## Features

- **Simple API** - Function-based registration with builder pattern
-**Fast** - Built on actix-web with async/await
-**Type-safe** - Strong typing throughout
-**Extensible** - Easy to add custom resources, tools, and prompts
-**Full MCP Support** - All protocol features (resources, tools, prompts, logging)
-**Custom HTTP Endpoints** - Add REST API endpoints on the same port as MCP
-**Multipart File Uploads** - Handle file uploads with `.multipart_endpoint()`
-**Headers & Context** - Access request headers, remote IP, request ID
-**Middleware** - Built-in CORS and OAuth 2.0 configuration
- 🚧 **Beta Features** - SSE resumption, OAuth validation (in development)

## Quick Start

```toml
[dependencies]
httpmcp-rust = "0.1"
tokio = { version = "1", features = ["full"] }
serde_json = "1.0"
```

```rust
use httpmcp_rust::{HttpMcpServer, RequestContext, ResourceMeta, ToolMeta, Result};
use httpmcp_rust::protocol::{Resource, ResourceContents};
use serde_json::{json, Value};
use std::collections::HashMap;

// Define handler functions
async fn list_resources(
    _cursor: Option<String>,
    _ctx: RequestContext,
) -> Result<(Vec<Resource>, Option<String>)> {
    Ok((vec![Resource {
        uri: "file:///example.txt".to_string(),
        name: "Example".to_string(),
        description: Some("Example file".to_string()),
        mime_type: Some("text/plain".to_string()),
    }], None))
}

async fn read_resource(uri: String, _ctx: RequestContext) -> Result<Vec<ResourceContents>> {
    Ok(vec![ResourceContents {
        uri,
        mime_type: Some("text/plain".to_string()),
        text: Some("Hello, MCP!".to_string()),
        blob: None,
    }])
}

async fn echo_tool(args: HashMap<String, Value>, _ctx: RequestContext) -> Result<Value> {
    Ok(json!({"echo": args.get("message")}))
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    HttpMcpServer::builder()
        .name("my-server")
        .version("1.0.0")
        // Register resource with metadata
        .resource(
            "file:///example.txt",
            ResourceMeta::new().name("Example").mime_type("text/plain"),
            list_resources,
            read_resource,
        )
        // Register tool with metadata
        .tool(
            "echo",
            ToolMeta::new()
                .description("Echo a message")
                .param("message", "string", "Message to echo")
                .required(&["message"]),
            echo_tool,
        )
        .build()?
        .run("127.0.0.1:8080")
        .await
}
```

## Usage Guide

### Server Builder

Configure your MCP server using the builder pattern:

```rust
let server = HttpMcpServer::builder()
    .name("my-server")           // Server name
    .version("1.0.0")             // Server version
    // Register resources with metadata
    .resource(
        "file:///example.txt",
        ResourceMeta::new().name("Example").mime_type("text/plain"),
        list_resources,
        read_resource,
    )
    // Register tools with metadata
    .tool(
        "add",
        ToolMeta::new()
            .description("Add two numbers")
            .param("a", "number", "First number")
            .param("b", "number", "Second number")
            .required(&["a", "b"]),
        add_tool,
    )
    // Register prompts with metadata
    .prompt(
        "code_review",
        PromptMeta::new()
            .description("Review code")
            .arg("code", "Code to review", true),
        code_review_prompt,
    )
    .enable_cors(true)            // Enable CORS
    .build()?;

server.run("127.0.0.1:8080").await?;
```

### Implementing Handlers

#### Resource Handlers

```rust
use httpmcp_rust::{RequestContext, ResourceMeta, Result};
use httpmcp_rust::protocol::{Resource, ResourceContents};

// List handler - returns available resources
async fn list_resources(
    _cursor: Option<String>,
    ctx: RequestContext,
) -> Result<(Vec<Resource>, Option<String>)> {
    // Access headers if needed
    let auth = ctx.get_authorization();

    Ok((vec![
        Resource {
            uri: "file:///example.txt".to_string(),
            name: "Example".to_string(),
            description: Some("Example file".to_string()),
            mime_type: Some("text/plain".to_string()),
        }
    ], None))
}

// Read handler - returns resource contents
async fn read_resource(
    uri: String,
    ctx: RequestContext,
) -> Result<Vec<ResourceContents>> {
    Ok(vec![ResourceContents {
        uri,
        mime_type: Some("text/plain".to_string()),
        text: Some("Hello, MCP!".to_string()),
        blob: None,
    }])
}
```

#### Tool Handlers

```rust
use httpmcp_rust::{RequestContext, ToolMeta, Result};
use std::collections::HashMap;
use serde_json::{json, Value};

async fn add_tool(
    args: HashMap<String, Value>,
    ctx: RequestContext,
) -> Result<Value> {
    let a = args.get("a").and_then(|v| v.as_f64()).unwrap_or(0.0);
    let b = args.get("b").and_then(|v| v.as_f64()).unwrap_or(0.0);

    Ok(json!({
        "result": a + b
    }))
}
```

#### Prompt Handlers

```rust
use httpmcp_rust::{RequestContext, PromptMeta, Result};
use httpmcp_rust::protocol::{PromptMessage, PromptContent};
use std::collections::HashMap;

async fn code_review_prompt(
    _name: String,
    args: Option<HashMap<String, String>>,
    ctx: RequestContext,
) -> Result<(Option<String>, Vec<PromptMessage>)> {
    let code = args.and_then(|mut a| a.remove("code")).unwrap_or_default();

    let messages = vec![PromptMessage {
        role: "user".to_string(),
        content: PromptContent::Text {
            text: format!("Review this code:\n\n{}", code),
        },
    }];

    Ok((Some("Code review".to_string()), messages))
}
```

#### Custom HTTP Endpoint Handlers (JSON)

Add REST API endpoints alongside MCP protocol on the same port:

```rust
use httpmcp_rust::{EndpointMeta, HttpMcpServer, RequestContext, Result};
use actix_web::HttpResponse;
use serde_json::json;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    HttpMcpServer::builder()
        .name("my-server")
        .version("1.0.0")
        // Add custom GET endpoint
        .endpoint(
            EndpointMeta::new()
                .route("/health")
                .method("GET")
                .description("Health check endpoint"),
            |_ctx: RequestContext, _body| async move {
                Ok(HttpResponse::Ok().json(json!({
                    "status": "healthy",
                    "version": "1.0.0"
                })))
            },
        )
        // Add custom POST endpoint
        .endpoint(
            EndpointMeta::new()
                .route("/api/data")
                .method("POST")
                .description("Create data"),
            |_ctx: RequestContext, body| async move {
                Ok(HttpResponse::Created().json(json!({
                    "message": "Created successfully",
                    "data": body
                })))
            },
        )
        .build()?
        .run("127.0.0.1:8080")
        .await
}
```

#### Multipart File Upload Endpoints

Handle file uploads using multipart/form-data:

```rust
use httpmcp_rust::{EndpointMeta, HttpMcpServer, RequestContext};
use actix_multipart::Multipart;
use actix_web::HttpResponse;
use futures::stream::StreamExt;
use serde_json::json;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    HttpMcpServer::builder()
        .name("upload-server")
        .version("1.0.0")
        .multipart_endpoint(
            EndpointMeta::new()
                .route("/upload")
                .method("POST")
                .description("Upload CSV file"),
            |_ctx: RequestContext, multipart: Multipart| {
                async move {
                    let mut multipart = multipart;
                    let mut file_contents = Vec::new();
                    let mut filename = String::from("unknown");

                    // Process multipart form fields
                    while let Some(field) = multipart.next().await {
                        let mut field = field.map_err(|e| {
                            httpmcp_rust::McpError::InvalidParams(format!("Multipart error: {}", e))
                        })?;

                        // Get filename
                        if let Some(content_disposition) = field.content_disposition() {
                            if let Some(fname) = content_disposition.get_filename() {
                                filename = fname.to_string();
                            }
                        }

                        // Read field data
                        while let Some(chunk) = field.next().await {
                            let data = chunk.map_err(|e| {
                                httpmcp_rust::McpError::InvalidParams(format!("Chunk error: {}", e))
                            })?;
                            file_contents.extend_from_slice(&data);
                        }
                    }

                    // Process file contents
                    let content = String::from_utf8(file_contents).map_err(|e| {
                        httpmcp_rust::McpError::InvalidParams(format!("Invalid UTF-8: {}", e))
                    })?;

                    Ok(HttpResponse::Ok().json(json!({
                        "success": true,
                        "filename": filename,
                        "size_bytes": content.len()
                    })))
                }
            },
        )
        .build()?
        .run("127.0.0.1:8080")
        .await
}
```

Test custom endpoints:

```bash
# Health check
curl http://localhost:8080/health

# POST JSON data
curl -X POST http://localhost:8080/api/data \
  -H "Content-Type: application/json" \
  -d '{"name": "test"}'

# Upload file
curl -X POST http://localhost:8080/upload \
  -F "file=@data.csv"

# MCP protocol still works on /mcp
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"ping"}'
```

### Request Context

Access headers and request metadata in all handlers:

```rust
async fn read_resource(uri: String, ctx: RequestContext) -> Result<Vec<ResourceContents>> {
    // Get authorization header
    let auth = ctx.get_authorization();

    // Get bearer token
    let token = ctx.get_bearer_token();

    // Get custom headers
    let tenant = ctx.get_custom_header("x-tenant-id");

    // Access request metadata
    println!("Request ID: {}", ctx.request_id);
    println!("Method: {}", ctx.method);
    println!("Path: {}", ctx.path);
    println!("Remote: {:?}", ctx.remote_addr);

    // Your logic here
    Ok(vec![])
}
```

### Headers Example

Use headers for authentication, tenant isolation, or custom metadata:

```rust
use httpmcp_rust::{HttpMcpServer, RequestContext, ToolMeta, Result};
use serde_json::{json, Value};
use std::collections::HashMap;

async fn secure_tool(args: HashMap<String, Value>, ctx: RequestContext) -> Result<Value> {
    // Check authorization
    let token = ctx.get_bearer_token()
        .ok_or_else(|| httpmcp_rust::McpError::Unauthorized("Missing token".to_string()))?;

    // Validate token (pseudo-code)
    if !validate_token(token) {
        return Err(httpmcp_rust::McpError::Unauthorized("Invalid token".to_string()));
    }

    // Get tenant ID for multi-tenancy
    let tenant_id = ctx.get_custom_header("x-tenant-id")
        .unwrap_or("default");

    // Log request details
    tracing::info!(
        "Request {} from {:?} for tenant {}",
        ctx.request_id,
        ctx.remote_addr,
        tenant_id
    );

    // Your logic here
    Ok(json!({"status": "success"}))
}

fn validate_token(token: &str) -> bool {
    // Token validation logic
    !token.is_empty()
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    HttpMcpServer::builder()
        .name("secure-server")
        .version("1.0.0")
        .tool(
            "secure_tool",
            ToolMeta::new().description("Tool with auth"),
            secure_tool,
        )
        .build()?
        .run("127.0.0.1:8080")
        .await
}
```

### Middleware Configuration

Enable CORS and OAuth 2.0:

```rust
use httpmcp_rust::HttpMcpServer;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let server = HttpMcpServer::builder()
        .name("middleware-example")
        .version("1.0.0")
        // Enable CORS for browser-based clients
        .enable_cors(true)
        // Configure OAuth 2.0 (basic setup)
        .with_oauth(
            "your-client-id",
            "your-client-secret",
            "https://auth.example.com/token",
            "https://auth.example.com/authorize",
        )
        .build()?;

    server.run("127.0.0.1:8080").await
}
```

Test with headers:

```bash
# Call with authorization
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-token" \
  -H "x-tenant-id: acme-corp" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "secure_tool",
      "arguments": {}
    }
  }'
```

## Examples

### Available Examples

**1. Simple Server** (`simple_server.rs`)
- Basic resources and tools
- Minimal setup

**2. Full Server** (`full_server.rs`)
- All MCP capabilities
- Custom headers
- File system resources
- Calculator tools
- Code review prompts

**3. Travel Planner** (`travel_planner.rs`) 🌟
- Real-world domain example
- Complete travel planning system
- Resources: destinations, itineraries, bookings, guides
- Tools: flight search, hotel search, weather, budget calculator, currency converter
- Prompts: trip planning, budget advice, packing lists
- Includes custom health endpoint

**4. Endpoint Example** (`endpoint_example.rs`)
- Custom HTTP REST API endpoints
- Health check, user list, data creation endpoints
- Shows how to mix MCP protocol with custom REST APIs on the same port

**5. Multipart Upload Example** (`multipart_upload.rs`)
- File upload handling with multipart/form-data
- CSV file processing and parsing
- Demonstrates `.multipart_endpoint()` usage

### Run Examples

```bash
# Simple server
cargo run --example simple_server

# Full-featured server
cargo run --example full_server

# Travel planner (recommended to see full capabilities)
cargo run --example travel_planner

# Endpoint example (custom REST API + MCP)
cargo run --example endpoint_example

# Multipart upload example
cargo run --example multipart_upload

# Test travel planner with automated suite
./examples/travel_planner_test.sh
```

### Testing with curl

```bash
# Initialize connection
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2024-11-05",
      "capabilities": {},
      "clientInfo": {"name": "test", "version": "1.0"}
    }
  }'

# List resources
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "resources/list"
  }'

# Call a tool
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "echo",
      "arguments": {"message": "Hello"}
    }
  }'

# SSE stream
curl -N http://localhost:8080/mcp \
  -H "Accept: text/event-stream"
```

## Architecture

```
httpmcp-rust/
├── src/
│   ├── lib.rs              # Public API
│   ├── server.rs           # HttpMcpServer builder
│   ├── transport.rs        # HTTP + SSE handlers
│   ├── jsonrpc.rs          # JSON-RPC types
│   ├── protocol.rs         # MCP protocol types
│   ├── context.rs          # RequestContext
│   ├── error.rs            # Error handling
│   ├── handlers/           # Trait definitions
│   │   ├── resources.rs
│   │   ├── tools.rs
│   │   ├── prompts.rs
│   │   └── lifecycle.rs
│   ├── auth/               # OAuth 2.0
│   ├── sse/                # Server-Sent Events
│   └── middleware/         # CORS, validation
└── examples/
    ├── simple_server.rs
    └── full_server.rs
```

## Features

### ✅ Completed

- JSON-RPC 2.0 support
- All MCP protocol methods (resources, tools, prompts)
- HTTP POST endpoint
- SSE GET endpoint with event IDs
- RequestContext with headers access
- OAuth 2.0 configuration
- CORS middleware
- Request validation
- Type-safe error handling
- Comprehensive examples

### 🚧 TODO

- Full OAuth token validation
- SSE resumption logic
- Rate limiting
- Metrics/observability
- More examples
- Integration tests

## MCP Protocol Support

This library implements the [Model Context Protocol](https://modelcontextprotocol.io) specification:

- ✅ Initialization & lifecycle
- ✅ Resources (list, read, templates, subscribe)
- ✅ Tools (list, call)
- ✅ Prompts (list, get)
- ✅ Logging (setLevel)
- ✅ Ping/pong
- ✅ JSON-RPC 2.0
- ✅ HTTP with SSE transport

## Contributing

Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests.

### Development

```bash
# Clone the repository
git clone https://github.com/renaiss-ai/httpmcp-rust.git
cd httpmcp-rust

# Run tests
cargo test

# Run examples
cargo run --example simple_server
cargo run --example full_server
cargo run --example travel_planner

# Format code
cargo fmt

# Run clippy
cargo clippy -- -D warnings
```

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT]LICENSE-MIT or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

## Resources

- [Model Context Protocol Specification]https://modelcontextprotocol.io
- [Documentation]https://docs.rs/httpmcp-rust
- [Crates.io]https://crates.io/crates/httpmcp-rust
- [Examples]examples/
- [Changelog]CHANGELOG.md