TurboMCP
Production-ready Rust SDK for the Model Context Protocol with progressive enhancement architecture, clean minimal core, and zero-cost abstractions. Build from minimal STDIO servers to enterprise-grade AI infrastructure with opt-in features.
Full MCP 2025-06-18 Specification
Complete protocol support with world-class developer experience and zero boilerplate.
Developer Experience First
Write production-ready MCP servers in minutes with ergonomic APIs and automatic schema generation.
Zero Boilerplate
Schemas auto-generated from function signatures
Type-Safe
Compile-time validation, runtime safety
Context Injection
Automatic dependency resolution
Error Ergonomics
McpError::invalid_request() helpers
Progressive Enhancement
Start minimal with STDIO only, opt-in to advanced features as needed. Clean separation of concerns.
Clean Minimal Core
Complete architectural overhaul with focused modules and zero technical debt.
Security Hardening
Pre-release security audit with 2,900 lines of placeholder code removed and proper secret management.
Modular Architecture
Independent auth and DPoP crates for flexible security integration.
Performance Excellence
Zero-copy message processing with SIMD acceleration and optimized memory handling.
Production Ready
All examples compile, all tests pass, strict quality standards enforced.
Modular Architecture
Clean, layered architecture with 10 specialized crates for maximum flexibility and maintainability.
Main SDK with ergonomic APIs
Foundation with SIMD acceleration
Multi-protocol transport layer
Server framework
MCP client (clean)
Procedural macro definitions
Development tools
OAuth 2.1 authentication
RFC 9449 DPoP tokens
Zero Boilerplate, Maximum Power
Automatic schema generation from function signatures. Type-safe from compilation to runtime.
use turbomcp::prelude::*;
#[derive(Clone)]
struct HelloServer;
#[server(name = "hello", version = "1.0.0")]
impl HelloServer {
#[tool("Say hello to someone")]
async fn hello(&self, name: String) -> McpResult<String> {
Ok(format!("Hello, {}!", name))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
HelloServer.run_stdio().await?;
Ok(())
}
// That's it! Just 25 lines for a complete MCP server.
// JSON schemas automatically generated from function signatures.use turbomcp::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
#[derive(Clone)]
struct KnowledgeServer {
documents: Arc<RwLock<HashMap<String, String>>>,
}
#[server(
name = "KnowledgeBase",
version = "2.0.0",
root = "file:///docs:Documentation"
)]
impl KnowledgeServer {
#[tool("Store a document in the knowledge base")]
async fn store_document(
&self,
ctx: Context,
name: String,
content: String,
) -> McpResult<String> {
ctx.info(&format!("Storing document: {}", name)).await?;
let mut docs = self.documents.write().await;
docs.insert(name.clone(), content.clone());
Ok(format!("Stored {} ({} chars)", name, content.len()))
}
#[resource("kb://docs/{name}")]
async fn get_document(&self, name: String) -> McpResult<String> {
let docs = self.documents.read().await;
docs.get(&name)
.cloned()
.ok_or_else(|| mcp_error!("Document not found: {}", name))
}
#[prompt("Generate documentation")]
async fn doc_prompt(
&self,
project_type: String,
description: String,
) -> McpResult<String> {
Ok(format!(
"Generate comprehensive docs for {} project:\n{}",
project_type, description
))
}
}use turbomcp::prelude::*;
#[server(name = "SafeCalculator", version = "2.0.0")]
impl Calculator {
#[tool("Safe division with validation")]
async fn divide(
&self,
ctx: Context,
dividend: f64,
divisor: f64,
) -> McpResult<f64> {
// Context provides logging and tracing
ctx.info(&format!("Division: {} / {}", dividend, divisor))
.await?;
// Validation with helpful error messages
if divisor == 0.0 {
return Err(McpError::invalid_request(
"Division by zero is not allowed"
));
}
if dividend.is_infinite() || divisor.is_infinite() {
return Err(McpError::invalid_request(
"Cannot divide infinite numbers"
));
}
Ok(dividend / divisor)
}
#[tool("Power with range validation")]
async fn power(&self, base: f64, exponent: f64) -> McpResult<f64> {
// Prevent extremely large calculations
if !(-1000.0..=1000.0).contains(&exponent) {
return Err(McpError::invalid_request(
"Exponent too large (limit: ±1000)"
));
}
let result = base.powf(exponent);
if result.is_infinite() || result.is_nan() {
return Err(McpError::invalid_request(
"Result is not a valid number"
));
}
Ok(result)
}
}Automatic Schema Generation
Function signatures become JSON schemas. No manual schema construction.
// f64 → {"type": "number"}
// String → {"type": "string"}
// Option<T> → optional paramType-Safe Parameters
Deserialize directly to Rust types. Validation at compile time.
#[derive(Deserialize)]
struct Params {
name: String,
age: u32,
}Context Injection
Automatic dependency injection. Logging, tracing, state management.
async fn tool(
&self,
ctx: Context,
param: String
)29 focused examples covering servers, clients, transports, and complete applications
Production-Ready in Minutes
From idea to deployed MCP server with working examples and best practices.
Add Dependency
turbomcp = "2.2"
Copy Example
29 focused examples
Customize Tools
Add your logic
Deploy & Test
Claude Desktop ready
Complete Example Portfolio
29 production-ready examples covering all transport protocols and features - minimal, focused, one concept per example
Transport Examples
13 examples- STDIO Server & Client
- HTTP/SSE Server & Client
- WebSocket Server & Client
- TCP Server & Client
- Unix Socket Server & Client
- Transports Demo
Protocol Features
10 examples- Tools
- Resources & Prompts
- Elicitation Forms
- Sampling Server
- Structured Output
- Resource Links
- Validation
- Rich Descriptions
- Stateful Server
- Context Injection
Complete Apps
6 examples- Hello World
- Macro Server
- STDIO App
- HTTP App
- Type-State Demo
- Comprehensive Examples
TurboMCP 2.2.2 Philosophy: Comprehensive examples covering every transport protocol and protocol feature - zero bloat, one concept per example
Every example is production-ready, fully documented, and MCP 2025-06-18 compliant
Complete Protocol Coverage
Every MCP feature accessible through ergonomic macros with compile-time validation.
Attribute Macros #[...]
Procedural attribute macros for server definitions and method handlers.
Server Definition
Define MCP servers with automatic trait implementations
Tool Handlers
Create tool endpoints with parameter validation
Resource Providers
Handle resource requests with URI templating
Prompt Generators
Generate dynamic prompts for AI interactions
DPoP Security (NEW)
RFC 9449 token binding with cryptographic proof
Type-State Builder (NEW)
Compile-time safe capability configuration
User Input
Request structured input from clients
Autocomplete
Provide intelligent completion suggestions
Macro Invocations name!()
Helper macros for creating formatted content, errors, and responses.
DPoP Tokens (NEW)
Generate RFC 9449 cryptographically bound tokens
Text Content Blocks
Create ContentBlock structures (often used with tool_result!)
Tool Results (Advanced)
Create CallToolResult manually (usually auto-handled by #[tool])
Error Creation
Create MCP errors (use with Err(mcp_error!(...)))
Ready-to-Use Examples
Get started quickly with our comprehensive examples covering everything from basic servers to advanced use cases.
use turbomcp::prelude::*;
#[derive(Clone)]
struct Calculator {
operations: std::sync::Arc<std::sync::atomic::AtomicU64>,
}
#[server]
impl Calculator {
#[tool("Add two numbers")]
async fn add(&self, a: i32, b: i32) -> McpResult<i32> {
self.operations.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(a + b)
}
#[tool("Get server statistics")]
async fn stats(&self) -> McpResult<String> {
let ops = self.operations.load(std::sync::atomic::Ordering::Relaxed);
Ok(format!("Operations performed: {}", ops))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let server = Calculator {
operations: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
};
server.run_stdio().await?;
Ok(())
}Run any example with cargo:
Performance Benchmarks
Optimized for fast processing with measurable performance improvements. Benchmarks conducted on consumer hardware (MacBook Pro M3, 32GB RAM).
2-3x Faster
JSON processing performance vs serde_json
Zero Copy
Memory-efficient message handling
SIMD
Hardware-accelerated processing
Low Latency
Optimized for real-time applications
Ready to Build with TurboMCP?
Start building fast MCP servers today with our comprehensive Rust SDK.
Production Deployment Patterns
Real-world examples demonstrating enterprise-ready deployment strategies and best practices.
Graceful Shutdown
Signal-based cleanup with proper resource management
- SIGINT/SIGTERM handling
- Resource cleanup
- In-flight request completion
- Health check integration
OAuth 2.1 Authentication
Multi-provider auth with Google, GitHub, Microsoft
- PKCE support
- Session management
- Token refresh
- Provider abstraction
Multi-Transport Deployment
Runtime transport selection based on environment
- STDIO for Claude Desktop
- HTTP/SSE for web apps
- TCP for services
- Unix sockets for containers
Bidirectional Communication
Complete handler system with all 4 handler types
- Elicitation requests
- Progress tracking
- Structured logging
- Resource updates