turul-mcp-aws-lambda 0.2.1

AWS Lambda integration for turul-mcp-framework 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
# turul-mcp-aws-lambda

[![Crates.io](https://img.shields.io/crates/v/turul-mcp-aws-lambda.svg)](https://crates.io/crates/turul-mcp-aws-lambda)
[![Documentation](https://docs.rs/turul-mcp-aws-lambda/badge.svg)](https://docs.rs/turul-mcp-aws-lambda)

AWS Lambda integration for the turul-mcp-framework, enabling serverless deployment of MCP servers with full protocol compliance.

## Overview

`turul-mcp-aws-lambda` provides seamless integration between the turul-mcp-framework and AWS Lambda runtime, enabling serverless MCP servers with proper session management, CORS handling, and SSE streaming support.

## Features

- **Zero-Cold-Start Architecture** - Optimized Lambda integration
-**MCP 2025-06-18 Compliance** - Full protocol support with SSE (snapshots or streaming)
-**DynamoDB Session Storage** - Persistent session management across invocations
-**CORS Support** - Automatic CORS header injection for browser clients
-**Type Conversion Layer** - Clean `lambda_http``hyper` conversion
- ⚠️ **SSE Support** - Snapshots via `handle()` or real streaming via `handle_streaming()`
-**Builder Pattern** - Familiar API matching `McpServer::builder()`
-**Truthful Capabilities** - Framework advertises accurate server capabilities

## Quick Start

Add this to your `Cargo.toml`:

```toml
[dependencies]
turul-mcp-aws-lambda = "0.2.0"
turul-mcp-derive = "0.2.0"
lambda_http = "0.17"
tokio = { version = "1.0", features = ["macros"] }
```

### Basic Lambda MCP Server (Snapshot-based SSE)

```rust
use lambda_http::{run, service_fn};
use turul_mcp_aws_lambda::LambdaMcpServerBuilder;
use turul_mcp_derive::McpTool;
use turul_mcp_server::{McpResult, SessionContext};

#[derive(McpTool, Clone, Default)]
#[tool(name = "echo", description = "Echo back the provided message")]
struct EchoTool {
    #[param(description = "Message to echo back")]
    message: String,
}

impl EchoTool {
    async fn execute(&self, _session: Option<SessionContext>) -> McpResult<String> {
        Ok(format!("Echo: {}", self.message))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Initialize tracing with RUST_LOG environment variable
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_target(false)
        .without_time()
        .init();

    // Create Lambda MCP server with echo tool
    let server = LambdaMcpServerBuilder::new()
        .name("echo-lambda-server")
        .version("1.0.0")
        .tool(EchoTool::default())  // Add our echo tool
        .sse(true)                  // Enable SSE (snapshot-based)
        .cors_allow_all_origins()   // Allow CORS for browser clients
        .build()
        .await?;

    // Create handler for Lambda runtime
    let handler = server.handler().await?;

    // Run with standard Lambda runtime (snapshot-based SSE)
    run(service_fn(move |req| {
        let handler = handler.clone();
        async move {
            handler.handle(req).await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
        }
    })).await
}
```

### Real-time Streaming Lambda MCP Server

For real-time SSE streaming, enable the `streaming` feature and use `handle_streaming()`:

```toml
[dependencies]
turul-mcp-aws-lambda = { version = "0.2.0", features = ["streaming"] }
```

```rust
use lambda_http::{run_with_streaming_response, service_fn};
use turul_mcp_aws_lambda::LambdaMcpServerBuilder;
// ... same tool definition ...

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // ... same server setup ...

    // Create handler for real-time streaming
    let handler = server.handler().await?;

    // Run with Lambda streaming response support for real-time SSE
    run_with_streaming_response(service_fn(move |req| {
        let handler = handler.clone();
        async move {
            handler.handle_streaming(req).await
        }
    })).await
}
```

## Architecture

### Framework Integration

The crate bridges AWS Lambda's HTTP execution model with the turul-mcp-framework:

```
┌─────────────────────────┐
│    AWS Lambda Runtime   │
├─────────────────────────┤
│  turul-mcp-aws-lambda   │  ← This crate
│  ├─ Type Conversion     │  ← lambda_http ↔ hyper
│  ├─ CORS Integration    │  ← Automatic header injection  
│  ├─ SSE Adaptation      │  ← Lambda streaming responses
│  └─ Session Management  │  ← DynamoDB persistence
├─────────────────────────┤
│   turul-mcp-server      │  ← Core framework
└─────────────────────────┘
```

### Three-Layer Discovery

Through lambda development, we discovered the framework's 3-layer architecture:

- **Layer 1**: `McpServer` - High-level builder and handler management
- **Layer 2**: `HttpMcpServer` - TCP server (incompatible with Lambda)
- **Layer 3**: `SessionMcpHandler` - Request handler (what Lambda needs)

This crate skips Layer 2 and provides clean integration to Layer 3.

## DynamoDB Session Storage

### Automatic Table Creation

```rust
use turul_mcp_aws_lambda::LambdaMcpServerBuilder;
use turul_mcp_session_storage::DynamoDbSessionStorage;
use std::sync::Arc;

let storage = Arc::new(DynamoDbSessionStorage::new().await?);

let server = LambdaMcpServerBuilder::new()
    .name("my-lambda-server")
    .storage(storage)  // Persistent session management
    .tool(/* your tools */)
    .build()
    .await?;
```

### Session Persistence

Sessions automatically persist across Lambda invocations:

```rust
#[derive(McpTool, Clone, Default)]
#[tool(name = "counter", description = "Session-persistent counter")]
struct CounterTool;

impl CounterTool {
    async fn execute(&self, session: Option<SessionContext>) -> McpResult<i32> {
        if let Some(session) = session {
            let count: i32 = session.get_typed_state("count").await.unwrap_or(0);
            let new_count = count + 1;
            session.set_typed_state("count", new_count).await?;
            Ok(new_count)
        } else {
            Ok(0)
        }
    }
}
```

## CORS Configuration

### Automatic CORS for Browser Clients

```rust
let server = LambdaMcpServerBuilder::new()
    .cors_allow_all_origins()  // Enable CORS for all origins
    .build()
    .await?;
```

### Custom CORS Configuration

```rust
use turul_mcp_aws_lambda::{LambdaMcpServerBuilder, CorsConfig};

let mut cors = CorsConfig::for_origins(vec!["https://myapp.com".to_string()]);
cors.allow_credentials = true;

let server = LambdaMcpServerBuilder::new()
    .cors(cors)
    .build()
    .await?;
```

## SSE Streaming in Lambda

### Real-time Notifications

Lambda streaming responses enable real-time SSE notifications:

```rust
#[derive(McpTool, Clone, Default)]
#[tool(name = "long_task", description = "Long-running task with progress")]
struct LongTaskTool;

impl LongTaskTool {
    async fn execute(&self, session: Option<SessionContext>) -> McpResult<String> {
        if let Some(session) = session {
            for i in 1..=5 {
                // Send progress notification via SSE
                session.notify_progress("long-task", i).await;
                
                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
            }
        }
        
        Ok("Task completed".to_string())
    }
}
```

## Deployment

### Local Testing with cargo-lambda

```bash
# Install cargo-lambda
cargo install cargo-lambda

# Run locally for testing
RUST_LOG=debug cargo lambda watch --package my-lambda-server

# Test with MCP Inspector
# Connect to: http://localhost:9000/lambda-url/my-lambda-server
```

### Deploy to AWS Lambda

```bash
# Build for Lambda
cargo lambda build --release --package my-lambda-server

# Deploy to AWS
cargo lambda deploy --package my-lambda-server
```

### Environment Configuration

```bash
# Required environment variables
export AWS_REGION=us-east-1
export MCP_SESSION_TABLE=mcp-sessions  # DynamoDB table name
export LOG_LEVEL=info
```

## Examples

### Complete AWS Integration Server

See [`examples/lambda-mcp-server`](../../examples/lambda-mcp-server) for a production-ready example with:

- DynamoDB query tools
- SNS publishing
- SQS message sending  
- CloudWatch metrics
- Full session persistence
- SSE streaming

### Builder Pattern Examples

```rust
use turul_mcp_aws_lambda::LambdaMcpServerBuilder;
use turul_mcp_builders::ToolBuilder;

// Runtime tool creation
let dynamic_tool = ToolBuilder::new("calculate")
    .description("Dynamic calculation tool")
    .number_param("x", "First number")
    .number_param("y", "Second number")
    .execute(|args| async move {
        let x = args["x"].as_f64().unwrap();
        let y = args["y"].as_f64().unwrap();
        Ok(serde_json::json!({"result": x * y}))
    })
    .build()?;

let server = LambdaMcpServerBuilder::new()
    .tool(dynamic_tool)
    .build()
    .await?;
```

## Testing

### Unit Tests

The crate includes comprehensive test coverage:

```bash
# Run all tests
cargo test --package turul-mcp-aws-lambda

# Test specific modules
cargo test --package turul-mcp-aws-lambda cors
cargo test --package turul-mcp-aws-lambda streaming
```

### Integration Testing

```bash
# Test with local Lambda runtime
cargo lambda watch &
curl -X POST http://localhost:9000/lambda-url/test \
  -H "Content-Type: application/json" \
  -H "MCP-Protocol-Version: 2025-06-18" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'
```

## Performance Optimization

### Cold Start Optimization

```rust
// Cache expensive operations at module level
static SHARED_STORAGE: tokio::sync::OnceCell<Arc<DynamoDbSessionStorage>> = tokio::sync::OnceCell::const_new();

async fn get_cached_storage() -> Arc<DynamoDbSessionStorage> {
    SHARED_STORAGE.get_or_init(|| async {
        Arc::new(DynamoDbSessionStorage::new().await.unwrap())
    }).await.clone()
}
```

### Memory Management

Lambda functions benefit from efficient memory usage:

```rust
let server = LambdaMcpServerBuilder::new()
    .tool(MyTool::default())  // Use Default for zero-sized types
    .build()
    .await?;
```

## Feature Flags

```toml
[dependencies]
turul-mcp-aws-lambda = { version = "0.2.0", features = ["cors", "sse", "dynamodb"] }
```

- `default` - Includes `cors` and `sse`
- `cors` - CORS header injection for Lambda responses
- `sse` - Server-Sent Events stream adaptation  
- `dynamodb` - DynamoDB session storage backend

## Limitations

### Lambda-Specific Considerations

- **Request Timeout**: Lambda has 15-minute maximum execution time
- **Payload Size**: 6MB maximum payload size for synchronous invocations
- **Concurrent Executions**: Subject to AWS Lambda concurrency limits
- **Cold Starts**: First invocation may have higher latency

### SSE Streaming Notes

- Lambda streaming responses have size and time limits
- Long-running SSE connections may be terminated by Lambda
- Consider using API Gateway WebSocket for persistent connections

## Error Handling

### Lambda Error Patterns

```rust
// Proper error handling for Lambda
handler.handle(req).await
    .map_err(|e| {
        tracing::error!("Lambda MCP handler error: {}", e);
        Box::new(e) as Box<dyn std::error::Error + Send + Sync>
    })
```

## Server Capabilities

### Truthful Capability Reporting

The framework automatically sets server capabilities based on registered components:

```rust
let server = LambdaMcpServerBuilder::new()
    .tool(calculator)
    .resource(user_resource)
    .build()
    .await?;

// Framework automatically advertises:
// - tools.listChanged = false (static tool list)
// - resources.subscribe = false (no subscriptions)
// - resources.listChanged = false (static resource list)
// - No prompts capability (none registered)
```

This ensures clients receive accurate information about server capabilities.

## License

Licensed under the MIT License. See [LICENSE](../../LICENSE) for details.