Production-ready Rust SDK for the Model Context Protocol (MCP) with zero-boilerplate development and progressive enhancement. Build MCP servers in seconds with automatic schema generation, type-safe handlers, and multiple transport protocols. - Rust 1.89.0+ (Edition 2024) - Check with rustc --version - Tokio async runtime Add to your Cargo.toml: Or with cargo: TurboMCP uses feature flags for progr
Add this skill
npx mdskills install Epistates/turbomcpComprehensive Rust SDK documentation with excellent examples, progressive features, and production-grade capabilities
1# TurboMCP23[](https://crates.io/crates/turbomcp)4[](https://docs.rs/turbomcp)5[](./LICENSE)6[](https://github.com/Epistates/turbomcp/actions/workflows/test.yml)7[](./crates/turbomcp-transport/SECURITY_FEATURES.md)8[](./benches/)910**Production-ready Rust SDK for the Model Context Protocol (MCP) with zero-boilerplate development and progressive enhancement.**1112Build MCP servers in seconds with automatic schema generation, type-safe handlers, and multiple transport protocols.1314## Requirements1516- **Rust 1.89.0+** (Edition 2024) - Check with `rustc --version`17- Tokio async runtime1819### Installation2021Add to your `Cargo.toml`:2223```toml24[dependencies]25turbomcp = "3.0.0-beta.5"26tokio = { version = "1", features = ["full"] }27```2829Or with cargo:3031```bash32cargo add turbomcp tokio --features tokio/full33```3435### Feature Presets3637TurboMCP uses feature flags for progressive enhancement. Choose a preset based on your needs:3839| Preset | Use Case | Features Included |40|--------|----------|-------------------|41| `default` | Basic tool servers | STDIO only |42| `full` | Production servers | All transports, context injection |43| `full-stack` | Server + Client | Full + client integration |44| `network` | Network services | STDIO + TCP |4546```toml47# Production server with all transports48turbomcp = { version = "3.0.0-beta.5", features = ["full"] }4950# Add authentication51turbomcp = { version = "3.0.0-beta.5", features = ["full", "auth"] }5253# With SIMD acceleration for high throughput54turbomcp = { version = "3.0.0-beta.5", features = ["full", "simd"] }55```5657### Individual Features5859| Feature | Description |60|---------|-------------|61| `stdio` | Standard MCP transport (default) |62| `http` | HTTP/SSE for web integration |63| `websocket` | WebSocket bidirectional |64| `tcp` | Raw TCP sockets |65| `unix` | Unix domain sockets |66| `auth` | OAuth 2.1 authentication |67| `dpop` | DPoP (RFC 9449) proof-of-possession |68| `simd` | SIMD-accelerated JSON processing |69| `context-injection` | Enhanced Context API |70| `middleware` | Request middleware stack |7172## Table of Contents7374- [Requirements](#requirements)75 - [Installation](#installation)76 - [Feature Presets](#feature-presets)77 - [Individual Features](#individual-features)78- [60-Second Quick Start](#60-second-quick-start)79- [Why TurboMCP?](#why-turbomcp)80- [Key Features](#key-features)81- [Quick Start](#quick-start)82- [Client Connections](#client-connections-v20)83- [Type-State Capability Builders](#type-state-capability-builders)84- [Additional Features](#additional-features)85 - [AudioContent Support](#audiocontent-support)86 - [LLM Integration](#llm-integration)87 - [Interactive Forms](#interactive-forms)88 - [Transport Protocols](#transport-protocols)89 - [Client Cloning & Shared Transport](#client-cloning--shared-transport)90 - [Filesystem Security](#filesystem-security)91 - [Resource Templates & Dynamic Content](#resource-templates--dynamic-content)92- [Security Features](#security-features)93- [Performance](#performance)94- [Deployment & Operations](#deployment--operations)95- [Development & Testing](#development--testing)96- [Example: Production Server](#example-production-server)97- [Architecture & Design Philosophy](#architecture--design-philosophy)98- [Documentation & Resources](#documentation--resources)99- [Contributing](#contributing)100- [License](#license)101- [Status](#status)102103---104105## 60-Second Quick Start106107```rust108use turbomcp::prelude::*;109110#[derive(Clone)]111struct Calculator;112113#[server(name = "calculator", version = "1.0.0", transports = ["stdio"])]114impl Calculator {115 #[tool("Add two numbers")]116 async fn add(&self, a: f64, b: f64) -> McpResult<f64> {117 Ok(a + b)118 }119120 #[tool("Multiply two numbers")]121 async fn multiply(&self, a: f64, b: f64) -> McpResult<f64> {122 Ok(a * b)123 }124}125126#[tokio::main]127async fn main() -> Result<(), Box<dyn std::error::Error>> {128 Calculator.run_stdio().await?;129 Ok(())130}131```132133**That's it.** Save as `main.rs`, run `cargo run`, and connect from Claude Desktop.134135**[Examples (26)](crates/turbomcp/examples/)** | **[API Docs](https://docs.rs/turbomcp)** | **[Transport Patterns](crates/turbomcp/examples/TRANSPORT_EXAMPLES_README.md)**136137---138139## Why TurboMCP?140141### Zero Boilerplate142143Automatic JSON schema generation from function signatures. No manual schema construction, argument parsing, or result wrapping.144145### Progressive Enhancement146147Start minimal (STDIO only), add features as needed:148- HTTP/SSE for web integration149- WebSocket for bidirectional streaming150- TCP for network services151- OAuth 2.1 for authentication152- SIMD for high throughput153154### Production Ready155156- Zero known runtime vulnerabilities157- Comprehensive error handling158- Session management with cleanup159- Rate limiting and security headers160- Type-safe from compile to runtime161- 3rd party audit (planned for Q4)162163### Developer Experience164165- Context injection for dependencies166- Interactive elicitation forms167- Automatic logging and tracing168- 25 focused examples covering all patterns169- Comprehensive documentation170171---172173## Key Features174175**Procedural Macro System**176- `#[server]` - Zero-boilerplate server definition with capability configuration177- `#[tool]` - Tool handlers with automatic parameter validation and schema generation178- `#[resource]` - Resource handlers with URI template support179- `#[prompt]` - Dynamic prompt templates with parameter substitution180- `#[completion]` - Autocompletion handlers for intelligent suggestions181- `#[ping]` - Health check endpoints with custom logic182- `#[elicitation]` - Interactive form builders with validation183- `mcp_error!` - Ergonomic error creation with context184- `elicit!` - Simple elicitation for quick user input185186**Type-State Architecture**187- ServerCapabilitiesBuilder with compile-time validation188- ClientCapabilitiesBuilder for capability negotiation189- Type-safe capability dependencies (e.g., tool_list_changed only when tools enabled)190- SharedTransport for concurrent transport access (Client is directly cloneable)191- Clone pattern for McpServer and Client (Axum/Tower standard - cheap Arc increments)192193**Protocol Features**194- Full MCP 2025-11-25 specification compliance195- Server-initiated sampling for bidirectional AI communication196- Interactive form elicitation with real-time validation197- AudioContent support for multimedia applications198- Progress tracking with correlation IDs199- Resource templates with RFC 6570 URI patterns200201**Transport & Performance**202- **MCP Standard Transports**: STDIO, HTTP/SSE (full 2025-11-25 spec compliance)203- **Custom Extensions**: WebSocket, TCP, Unix Socket (MCP-compliant bidirectional transports)204- SIMD-accelerated JSON processing (simd-json, sonic-rs)205- Zero-copy message handling with Bytes206- Circuit breakers, connection pooling, and graceful degradation207- Built-in benchmarking suite with 5% regression detection208209**Security & Authentication**210- **OAuth 2.1** with PKCE and multi-provider support:211 - Social: Google, GitHub212 - Enterprise: Microsoft, Okta, Keycloak213 - Identity Platforms: Apple Sign In, Auth0214 - Generic: Any OIDC-compliant provider215- Rate limiting with token bucket algorithm216- CORS protection and comprehensive security headers217- Session management with cleanup and timeout enforcement218- TLS support with certificate validation219220**Developer Tools**221- Context injection with dependency resolution222- Automatic JSON schema generation from Rust types223- CLI tools for testing, debugging, and schema export224- Graceful shutdown with lifecycle management225- Comprehensive error types with structured context226227---228229## Quick Start230231```toml232[dependencies]233turbomcp = "3.0.0-beta.5"234tokio = { version = "1", features = ["full"] }235```236237Create an MCP server with zero boilerplate:238239```rust240use turbomcp::prelude::*;241242#[derive(Clone)]243struct HelloServer;244245#[server(name = "hello-server", version = "1.0.0")]246impl HelloServer {247 #[tool("Say hello to someone")]248 async fn hello(&self, name: String) -> McpResult<String> {249 Ok(format!("Hello, {name}! Welcome to TurboMCP! ๐ฆโก"))250 }251}252253#[tokio::main]254async fn main() -> Result<(), Box<dyn std::error::Error>> {255 HelloServer.run_stdio().await?;256 Ok(())257}258```259260Configure in Claude Desktop:261```json262{263 "mcpServers": {264 "hello-server": {265 "command": "/path/to/your/server",266 "args": []267 }268 }269}270```271272Test with CLI:273```bash274cargo install turbomcp-cli275turbomcp-cli tools list --command "./your-server"276turbomcp-cli tools call hello --arguments '{"name": "World"}' --command "./your-server"277```278279---280281## Client Connections282283TurboMCP provides beautiful one-liner client connections with automatic initialization:284285### HTTP Client286```rust287use turbomcp_client::Client;288289// One-liner connection (auto-connects & initializes)290let client = Client::connect_http("http://localhost:8080").await?;291292// Now use it immediately293let tools = client.list_tools().await?;294let result = client.call_tool("my_tool", Some(args)).await?;295```296297### TCP Client298```rust299// Connect to TCP server300let client = Client::connect_tcp("127.0.0.1:8765").await?;301let tools = client.list_tools().await?;302```303304### Unix Socket Client305```rust306// Connect to Unix socket server307let client = Client::connect_unix("/tmp/mcp.sock").await?;308let prompts = client.list_prompts().await?;309```310311### Custom Configuration312```rust313use std::time::Duration;314315// HTTP with custom config316let client = Client::connect_http_with("http://localhost:8080", |config| {317 config.timeout = Duration::from_secs(60);318 config.endpoint_path = "/api/mcp".to_string();319}).await?;320321// WebSocket with custom config322let client = Client::connect_websocket_with("ws://localhost:8080/ws", |config| {323 config.reconnect_attempts = 5;324 config.ping_interval = Duration::from_secs(30);325}).await?;326```327328### Manual Connection (Advanced)329For full control over initialization:330331```rust332use turbomcp_transport::tcp::TcpTransport;333334let transport = TcpTransport::new_client(bind_addr, server_addr);335let client = Client::new(transport);336337// Auto-connects transport during initialize338client.initialize().await?;339340// Use client341let tools = client.list_tools().await?;342```343344### Benefits of v2.1 Client API345- **One-liner connections**: `connect_http()`, `connect_tcp()`, `connect_unix()`346- **Auto-initialization**: No need to call `.connect()` or `.initialize()` manually347- **Type-safe configuration**: Custom config functions with full IntelliSense348- **Consistent API**: Same pattern across all transports349- **OAuth 2.1 Support**: Automatic token handling with PKCE and multi-provider support350- **MCP Proxy Support**: Universal adapter for any MCP server implementation351352---353354## Type-State Capability Builders355356Compile-time validated capability configuration:357358```rust359use turbomcp_protocol::capabilities::builders::{ServerCapabilitiesBuilder, ClientCapabilitiesBuilder};360361// Server capabilities with compile-time validation362let server_caps = ServerCapabilitiesBuilder::new()363 .enable_tools() // Enable tools capability364 .enable_prompts() // Enable prompts capability365 .enable_resources() // Enable resources capability366 .enable_tool_list_changed() // โ Only available when tools enabled367 .enable_resources_subscribe() // โ Only available when resources enabled368 .build();369370// Client capabilities with opt-out model (all enabled by default)371let client_caps = ClientCapabilitiesBuilder::new()372 .enable_roots_list_changed() // Configure sub-capabilities373 .build(); // All capabilities enabled!374375// Opt-in pattern for restrictive clients376let minimal_client = ClientCapabilitiesBuilder::minimal()377 .enable_sampling() // Only enable what you need378 .enable_roots()379 .build();380```381382### Benefits383- Compile-time validation catches invalid configurations at build time384- Type safety ensures sub-capabilities are only available when parent capability is enabled385- Fluent API for readable capability configuration386- Backward compatibility with existing code387388---389390## Additional Features391392### AudioContent Support393Multimedia content handling with the AudioContent type:394395```rust396#[tool("Process audio data")]397async fn process_audio(&self, audio_data: String) -> McpResult<Content> {398 Ok(Content::Audio(AudioContent {399 data: audio_data, // Base64 encoded audio400 mime_type: "audio/wav".to_string(),401 annotations: Some(Annotations {402 audience: Some(vec!["user".to_string()]),403 priority: Some(0.9),404 last_modified: Some(iso8601_timestamp()),405 }),406 }))407}408```409410### LLM Integration411Server-initiated sampling for AI communication:412413```rust414// Server can request LLM assistance through the client415#[tool("Get AI assistance for data analysis")]416async fn ai_analyze(&self, ctx: Context, data: String) -> McpResult<String> {417 // Create sampling request for client's LLM418 let request = serde_json::json!({419 "messages": [{420 "role": "user",421 "content": {422 "type": "text",423 "text": format!("Analyze this data: {}", data)424 }425 }],426 "maxTokens": 500,427 "systemPrompt": "You are a data analyst."428 });429430 // Request LLM assistance through client431 match ctx.create_message(request).await {432 Ok(response) => Ok(format!("AI Analysis: {:?}", response)),433 Err(_) => {434 // Fallback if sampling unavailable435 Ok(format!("Static analysis: {} characters", data.len()))436 }437 }438}439```440441### Interactive Forms442Server-initiated user input with validation:443444```rust445let config = ctx.elicit("Deployment Configuration")446 .field("environment",447 select("Environment", vec!["dev", "staging", "production"])448 .description("Target deployment environment"))449 .field("replicas",450 integer("Replica Count").range(1.0, 20.0).default(3))451 .field("auto_scale",452 checkbox("Enable Auto-scaling").default(true))453 .field("notification_email",454 text("Admin Email").format("email").required())455 .section("Security")456 .field("enable_tls", checkbox("Enable TLS").default(true))457 .field("cors_origins", text("CORS Origins").placeholder("https://app.example.com"))458 .require(vec!["environment", "notification_email"])459 .validate_with(|data| {460 if data.get::<String>("environment")? == "production" && !data.get::<bool>("enable_tls")? {461 return Err("TLS required for production".into());462 }463 Ok(())464 })465 .await?;466```467468### Transport Protocols469470| Transport | Performance | Use Case | Security |471|-----------|-------------|----------|----------|472| **STDIO** | Fast | Claude Desktop, CLI tools | Process isolation |473| **HTTP/SSE** | Good | Web apps, REST APIs | TLS 1.3, session mgmt |474| **WebSocket** | Real-time | Interactive apps | Secure WebSocket |475| **TCP** | High throughput | Clusters | Optional TLS |476| **Unix Socket** | Fast | Container communication | File permissions |477478```rust479// Transport selection480match deployment_env {481 "cluster" => server.run_tcp("0.0.0.0:8080").await?,482 "container" => server.run_unix("/var/run/mcp.sock").await?,483 "web" => server.run_http("0.0.0.0:8080").await?,484 "desktop" => server.run_stdio().await?,485 _ => server.run_stdio().await?, // Default to stdio486}487```488489---490491## Security Features492493### Security Architecture494TurboMCP includes security features for production deployment:495496- **CORS Protection**: Configurable origin policies with production-safe defaults497- **Security Headers**: Standard HTTP security headers (X-Frame-Options, CSP, HSTS)498- **Session Management**: Secure session handling with timeout enforcement499- **TLS Support**: Optional TLS for transport protocols500- **OAuth 2.1**: Via optional `auth` feature (8+ providers: Google, GitHub, Microsoft, Apple, Okta, Auth0, Keycloak, Generic)501- **DPoP Support**: RFC 9449 Demonstration of Proof-of-Possession (via `dpop` feature)502- **Rate Limiting**: Request throttling configuration503- **Type-Safe Errors**: Structured error handling with context504505```rust506// Example: Enable OAuth 2.1 authentication507#[cfg(feature = "auth")]508use turbomcp::auth::*;509510// Configure with CORS security511let security = SecurityConfig::production()512 .with_origins(vec!["https://app.example.com".to_string()]);513514// See crates/turbomcp-transport/SECURITY_FEATURES.md for complete security documentation515```516517### Monitoring & Observability518```rust519#[tool("Get system metrics")]520async fn get_metrics(&self, ctx: Context) -> McpResult<SystemMetrics> {521 // Structured logging with correlation IDs522 ctx.with_trace_id().info("Metrics requested").await?;523524 // Performance monitoring525 let metrics = SystemMetrics {526 requests_per_second: self.metrics.current_rps(),527 average_latency: self.metrics.avg_latency(),528 error_rate: self.metrics.error_rate(),529 memory_usage: self.metrics.memory_usage(),530 cpu_utilization: self.metrics.cpu_usage(),531 active_connections: self.transport.active_connections(),532 };533534 // Export to Prometheus/Grafana535 self.metrics.export_prometheus().await?;536537 Ok(metrics)538}539```540541---542543## Performance544545### Benchmark Results546547```548TurboMCP Performance Characteristics549==================================================550Message Throughput: Concurrent processing (TCP transport)551Tool Execution: Fast response times (99th percentile)552JSON Processing: SIMD-accelerated (simd-json, sonic-rs)553Memory Efficiency: Zero-copy patterns (Bytes-based processing)554Cold Start Time: Fast startup (Pre-compiled schemas)555Connection Setup: Fast connection (Connection pooling)556557Regression Detection: Enabled558Cross-Platform Validation: Ubuntu | Windows | macOS559CI/CD Performance Gates: 5% threshold560```561562### Low-Overhead Architecture563```rust564// Compile-time schema generation (zero runtime cost)565#[tool("Process order")]566async fn process_order(567 &self,568 #[description("Customer order ID")] order_id: String,569 #[description("Priority level 1-10")] priority: u8,570 #[description("Processing options")] options: ProcessingOptions,571) -> McpResult<OrderResult> {572 // Schema validation happens at compile time573 // Handler dispatch is O(1) lookup574 // Zero reflection overhead575 // No runtime schema computation576577 let result = self.order_processor578 .process_with_priority(order_id, priority, options)579 .await?;580581 Ok(result)582}583584// Automatic JSON schema generated at compile time:585// {586// "type": "object",587// "properties": {588// "order_id": {"type": "string", "description": "Customer order ID"},589// "priority": {"type": "integer", "minimum": 0, "maximum": 255},590// "options": {"$ref": "#/definitions/ProcessingOptions"}591// },592// "required": ["order_id", "priority", "options"]593// }594```595596---597598## Additional Features599600### Client Cloning & Shared Transport601Thread-safe async operations with Arc-wrapped internals:602603```rust604// Client is directly cloneable (Arc-wrapped internally - no wrapper needed!)605let client = Client::connect_http("http://localhost:8080").await?;606607// Clone for concurrent usage (cheap Arc increments)608let c1 = client.clone();609let c2 = client.clone();610let c3 = client.clone();611612// All tasks can access concurrently613let results = tokio::try_join!(614 async move { c1.list_tools().await },615 async move { c2.list_prompts().await },616 async move { c3.list_resources().await },617)?;618619// For transport sharing across multiple connections, use SharedTransport620let transport = TcpTransport::connect("server:8080").await?;621let shared_transport = SharedTransport::new(transport);622shared_transport.connect().await?;623624// Multiple clients sharing the same transport625let client1 = Client::new(shared_transport.clone());626let client2 = Client::new(shared_transport.clone());627let client3 = Client::new(shared_transport.clone());628```629630### Filesystem Security631```rust632#[server(633 name = "secure-file-server",634 version = "1.0.0",635 root = "file:///workspace:Project Files",636 root = "file:///uploads:User Uploads",637 root = "file:///tmp:Temporary Files"638)]639impl SecureFileServer {640 #[tool("Read file within security boundaries")]641 async fn read_file(&self, ctx: Context, path: String) -> McpResult<String> {642 // Automatic path validation against configured roots643 // OS-aware security (Unix permissions, Windows ACLs)644 ctx.validate_file_access(&path).await?;645646 let content = tokio::fs::read_to_string(&path).await647 .map_err(|e| mcp_error!("Access denied: {}", e))?;648649 Ok(content)650 }651}652```653654### Resource Templates & Dynamic Content655```rust656#[resource("user://{user_id}/profile")]657async fn get_user_profile(&self, user_id: String) -> McpResult<Content> {658 let profile = self.database.get_user_profile(&user_id).await?;659660 Ok(Content::Text(TextContent {661 text: serde_json::to_string_pretty(&profile)?,662 mime_type: Some("application/json".to_string()),663 annotations: Some(Annotations {664 audience: Some(vec!["user".to_string(), "admin".to_string()]),665 priority: Some(0.8),666 last_modified: Some(profile.updated_at.to_rfc3339()),667 }),668 }))669}670671#[resource("file://{path}")]672async fn serve_file(&self, path: String) -> McpResult<Content> {673 // Automatic MIME type detection674 // Security validation675 // Efficient file serving676 self.file_server.serve_secure(&path).await677}678```679680---681682## Deployment & Operations683684### Container Deployment685```dockerfile686FROM rust:1.89 as builder687WORKDIR /app688COPY . .689RUN cargo build --release --features production690691FROM debian:bookworm-slim692RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*693COPY --from=builder /app/target/release/your-server /usr/local/bin/694EXPOSE 8080695HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \696 CMD curl -f http://localhost:8080/health || exit 1697CMD ["your-server"]698```699700### Kubernetes Deployment701```yaml702apiVersion: apps/v1703kind: Deployment704metadata:705 name: turbomcp-server706spec:707 replicas: 3708 selector:709 matchLabels:710 app: turbomcp-server711 template:712 metadata:713 labels:714 app: turbomcp-server715 spec:716 containers:717 - name: server718 image: your-registry/turbomcp-server:v1.0.0719 ports:720 - containerPort: 8080721 env:722 - name: TRANSPORT723 value: "http"724 - name: RUST_LOG725 value: "info"726 resources:727 requests:728 memory: "64Mi"729 cpu: "50m"730 limits:731 memory: "256Mi"732 cpu: "500m"733 livenessProbe:734 httpGet:735 path: /health736 port: 8080737 initialDelaySeconds: 10738 periodSeconds: 30739 readinessProbe:740 httpGet:741 path: /ready742 port: 8080743 initialDelaySeconds: 5744 periodSeconds: 10745```746747### Monitoring748```rust749// Prometheus metrics integration750#[tool("Process critical operation")]751async fn critical_operation(&self, ctx: Context, data: String) -> McpResult<String> {752 let _timer = ctx.start_timer("critical_operation_duration");753 ctx.increment_counter("critical_operations_total");754755 match self.process_data(data).await {756 Ok(result) => {757 ctx.increment_counter("critical_operations_success");758 ctx.record_histogram("result_size_bytes", result.len() as f64);759 Ok(result)760 }761 Err(e) => {762 ctx.increment_counter("critical_operations_error");763 ctx.add_label("error_type", &e.error_type());764 Err(e)765 }766 }767}768769// Grafana dashboard query examples:770// rate(critical_operations_total[5m]) # Operations per second771// histogram_quantile(0.95, critical_operation_duration) # 95th percentile latency772// critical_operations_error / critical_operations_total # Error rate773```774775---776777## Development & Testing778779### Testing780```bash781# Full test suite with performance validation782make test # 81 tests, zero failures783cargo test --workspace --all-features # All features tested784cargo bench --workspace # Performance benchmarks785786# Security & quality validation787cargo audit # Zero vulnerabilities788cargo clippy --all-targets # Zero warnings789cargo deny check # License compliance790791# Performance regression detection792./scripts/run_benchmarks.sh ci # CI-optimized run793./scripts/run_benchmarks.sh baseline # Update baselines794```795796### CLI Development Tools797```bash798# Install CLI tools799cargo install turbomcp-cli800801# Test your server during development802turbomcp-cli tools list --command "./target/debug/your-server"803turbomcp-cli tools call process_data --arguments '{"input": "test data"}' \804 --command "./target/debug/your-server"805806# Export schemas for documentation807turbomcp-cli tools schema --command "./target/debug/your-server" --format pretty808809# List resources and prompts810turbomcp-cli resources list --command "./target/debug/your-server"811turbomcp-cli prompts list --command "./target/debug/your-server"812```813814### Examples - All 26815816**Foundational Examples:**817| Example | Topic |818|---------|-------|819| [hello_world.rs](./crates/turbomcp/examples/hello_world.rs) | Simplest server - one tool |820| [macro_server.rs](./crates/turbomcp/examples/macro_server.rs) | Using `#[server]` macro |821| [minimal_test.rs](./crates/turbomcp/examples/minimal_test.rs) | Testing patterns |822| [tools.rs](./crates/turbomcp/examples/tools.rs) | Parameter types & validation |823| [resources.rs](./crates/turbomcp/examples/resources.rs) | Resource handlers with URIs |824| [rich_tool_descriptions.rs](./crates/turbomcp/examples/rich_tool_descriptions.rs) | Advanced tool documentation |825| [validation.rs](./crates/turbomcp/examples/validation.rs) | Input validation & error handling |826827**Stateful & Advanced Server Examples:**828| Example | Topic |829|---------|-------|830| [stateful.rs](./crates/turbomcp/examples/stateful.rs) | Arc<RwLock<T>> state pattern |831| [sampling_server.rs](./crates/turbomcp/examples/sampling_server.rs) | LLM sampling & bidirectional communication |832| [elicitation_server.rs](./crates/turbomcp/examples/elicitation_server.rs) | Interactive form elicitation |833834**Transport & Server Patterns:**835| Example | Topic |836|---------|-------|837| [stdio_app.rs](./crates/turbomcp/examples/stdio_app.rs) | Complete STDIO application |838| [stdio_server.rs](./crates/turbomcp/examples/stdio_server.rs) | STDIO server transport |839| [http_app.rs](./crates/turbomcp/examples/http_app.rs) | Complete HTTP/SSE application |840| [http_server.rs](./crates/turbomcp/examples/http_server.rs) | HTTP/SSE transport only |841| [tcp_server.rs](./crates/turbomcp/examples/tcp_server.rs) | TCP network transport |842| [unix_server.rs](./crates/turbomcp/examples/unix_server.rs) | Unix socket transport |843| [websocket_server.rs](./crates/turbomcp/examples/websocket_server.rs) | WebSocket bidirectional transport |844| [transports_demo.rs](./crates/turbomcp/examples/transports_demo.rs) | Multi-transport demonstration |845846**Client Examples:**847| Example | Topic |848|---------|-------|849| [basic_client.rs](./crates/turbomcp/examples/basic_client.rs) | Connect, list, and call tools |850| [stdio_client.rs](./crates/turbomcp/examples/stdio_client.rs) | STDIO client communication |851| [tcp_client.rs](./crates/turbomcp/examples/tcp_client.rs) | TCP client connection |852| [http_client_simple.rs](./crates/turbomcp/examples/http_client_simple.rs) | HTTP/SSE client |853| [unix_client.rs](./crates/turbomcp/examples/unix_client.rs) | Unix socket client |854| [websocket_client_simple.rs](./crates/turbomcp/examples/websocket_client_simple.rs) | WebSocket client |855| [comprehensive.rs](./crates/turbomcp/examples/comprehensive.rs) | All MCP features combined |856| [elicitation_client.rs](./crates/turbomcp/examples/elicitation_client.rs) | Interactive form responses |857858**Run examples:**859```bash860cargo run --example hello_world861cargo run --example elicitation_client862cargo run --example http_app863cargo run --example tcp_server # Then in another terminal:864cargo run --example tcp_client865```866867---868869## Example: Production Server870871Create a server with multiple features:872873```rust874use turbomcp::prelude::*;875876#[derive(Clone)]877struct ProductionServer {878 database: Arc<Database>,879 cache: Arc<Cache>,880}881882#[server(883 name = "enterprise-server",884 version = "1.0.0",885 description = "Production server with advanced features",886 capabilities = ServerCapabilities::builder()887 .enable_tools()888 .enable_prompts()889 .enable_resources()890 .enable_tool_list_changed()891 .enable_resources_subscribe()892 .build()893)]894impl ProductionServer {895 #[tool("Analyze data with AI assistance")]896 async fn ai_analyze(&self, ctx: Context, data: String) -> McpResult<String> {897 // Enterprise logging with correlation IDs898 ctx.info(&format!("Processing {} bytes", data.len())).await?;899900 // Production database query with connection pooling901 let metadata = self.database.get_metadata(&data).await?;902903 // Request AI assistance through client sampling904 let request = serde_json::json!({905 "messages": [{906 "role": "user",907 "content": {908 "type": "text",909 "text": format!("Analyze: {}", data)910 }911 }],912 "maxTokens": 500,913 "systemPrompt": "You are a data analyst."914 });915916 match ctx.create_message(request).await {917 Ok(response) => Ok(format!("AI Analysis: {:?}", response)),918 Err(_) => {919 // Fallback analysis920 let word_count = data.split_whitespace().count();921 Ok(format!("Analysis: {} words, {} bytes", word_count, data.len()))922 }923 }924 }925926 #[tool("Interactive data collection")]927 async fn collect_requirements(&self, ctx: Context) -> McpResult<String> {928 // Server-initiated interactive form with validation929 let response = ctx.elicit("Project Requirements")930 .field("project_name", text("Project Name").min_length(3))931 .field("budget", integer("Budget ($)").range(1000.0, 1000000.0))932 .field("deadline", text("Deadline").format("date"))933 .field("priority", select("Priority", vec!["low", "medium", "high", "critical"]))934 .require(vec!["project_name", "budget"])935 .await?;936937 // Process with type-safe extraction938 let name = response.get::<String>("project_name")?;939 let budget = response.get::<i64>("budget")?;940941 Ok(format!("Project '{}' with budget ${} configured", name, budget))942 }943}944945#[tokio::main]946async fn main() -> Result<(), Box<dyn std::error::Error>> {947 let server = ProductionServer {948 database: Arc::new(Database::connect().await?),949 cache: Arc::new(Cache::new()),950 };951952 // Production deployment with automatic transport selection953 match std::env::var("TRANSPORT").as_deref() {954 Ok("http") => server.run_http("0.0.0.0:8080").await?,955 Ok("tcp") => server.run_tcp("0.0.0.0:8080").await?,956 _ => server.run_stdio().await?, // Claude Desktop integration957 }958959 Ok(())960}961```962963---964965## Architecture & Design Philosophy966967### Compile-Time Optimization Approach968969TurboMCP prioritizes compile-time optimization over runtime flexibility. This creates a more complex build process but delivers better runtime performance and predictability.970971### Modular Design972973| Crate | Purpose | Key Innovation |974|-------|---------|----------------|975| [`turbomcp`](./crates/turbomcp/) | Main SDK | Zero-overhead macro integration |976| [`turbomcp-protocol`](./crates/turbomcp-protocol/) | Protocol & Foundation | SIMD-accelerated processing + compile-time schemas |977| [`turbomcp-transport`](./crates/turbomcp-transport/) | Transport layer | High throughput with circuit breakers |978| [`turbomcp-server`](./crates/turbomcp-server/) | Server framework | Enterprise security & middleware |979| [`turbomcp-client`](./crates/turbomcp-client/) | Client library | Advanced LLM integration |980| [`turbomcp-macros`](./crates/turbomcp-macros/) | Proc macros | Compile-time optimization engine |981| [`turbomcp-cli`](./crates/turbomcp-cli/) | CLI tools | Production testing & debugging |982983**Note:** In v2.0.0, `turbomcp-core` was merged into `turbomcp-protocol` to eliminate circular dependencies.984985### Performance Characteristics986987- Low-overhead abstractions - Optimizations happen at compile time988- O(1) handler dispatch - Direct function calls, no HashMap lookups989- Pre-computed schemas - No runtime schema generation overhead990- Optimized JSON processing - SIMD-accelerated parsing with simd-json and sonic-rs991- Zero-copy message handling - Minimal memory allocations with `Bytes`992- Feature gating - Lean production binaries through compile-time selection993994---995996## Documentation & Resources997998- **[API Documentation](https://docs.rs/turbomcp)** - Complete API reference with examples999- **[Benchmarking Guide](./benches/README.md)** - Performance testing and optimization1000- **[Security Documentation](./crates/turbomcp-transport/SECURITY_FEATURES.md)** - Enterprise security features1001- **[Architecture Guide](./ARCHITECTURE.md)** - System design and component interaction1002- **[Examples Guide](./crates/turbomcp/examples/README.md)** - 26 focused examples with learning paths1003- **[Transport Patterns](./crates/turbomcp/examples/TRANSPORT_EXAMPLES_README.md)** - TCP, HTTP, WebSocket, Unix socket patterns1004- **[MCP Specification](https://modelcontextprotocol.io)** - Official protocol documentation1005- **[Migration Guide](./MIGRATION.md)** - v1.x to v2.0 changes10061007---10081009## Contributing10101011We welcome contributions! TurboMCP follows high engineering standards:101210131. **Fork the repository** and create a feature branch10142. **Write comprehensive tests** - We maintain 100% test success rate10153. **Run the quality suite** - `make test && cargo clippy && cargo fmt`10164. **Ensure security compliance** - `cargo audit && cargo deny check`10175. **Submit a pull request** with detailed description10181019**Development setup:**1020```bash1021git clone https://github.com/Epistates/turbomcp.git1022cd turbomcp1023cargo build --workspace1024make test # Run full test suite1025./scripts/run_benchmarks.sh # Validate performance1026```10271028---10291030## ๐ License10311032Licensed under the [MIT License](./LICENSE) - Enterprise-friendly open source.10331034---10351036## Status10371038TurboMCP v3.0.0-beta.5 provides:10391040- Zero known security vulnerabilities with continuous monitoring1041- Performance focus with automated regression detection1042- Full MCP 2025-11-25 specification compliance1043- Production deployment patterns with container & Kubernetes support1044- 26 focused examples covering all usage patterns1045- Active development with regular security updates and performance improvements1046- **NEW**: turbomcp-proxy for universal MCP adaptation and code generation1047- **NEW**: Complete OAuth 2.1 authentication stack with PKCE and multi-provider support1048- **NEW**: RFC 9728 Protected Resource Metadata support1049- **NEW**: JWT and JWKS authentication middleware10501051**Beta Status:** TurboMCP 3.0.0-beta.5 features full MCP 2025-11-25 compliance, comprehensive test coverage, edge-native WASM support, modular transport crates, and the complete authentication stack including DPoP. The API is stabilizing toward 3.0.0 final release.10521053---10541055*Built with โค๏ธ by the TurboMCP team1056
Full transparency โ inspect the skill content before installing.