TurboMCP
Rust SDK for the Model Context Protocol (MCP) with comprehensive specification support and performance optimizations.
Quick Navigation
Jump to section: Overview | Quick Start | Core Concepts | Advanced Features | Security | Performance | Deployment | Examples
Overview
turbomcp is a Rust framework for implementing the Model Context Protocol. It provides tools, servers, clients, and transport layers with MCP specification compliance, security features, and performance optimizations.
Security Features
- Zero known vulnerabilities - Security audit with
cargo-denypolicy - Dependency security - Eliminated RSA and paste crate vulnerabilities
- MIT-compatible dependencies - Permissive license enforcement
- Security hardening - Dependency optimization for security
Performance Monitoring
- Benchmarking infrastructure - Automated regression detection
- Cross-platform testing - Ubuntu, Windows, macOS CI validation
- CI/CD integration - GitHub Actions with performance tracking
Key Features
Performance Features
- Optimized JSON processing - Optional SIMD acceleration with fast libraries
- Efficient message handling - Minimal memory allocations with zero-copy patterns
- Connection management - Connection pooling and reuse strategies
- Request routing - Efficient handler lookup with parameter injection
Developer Experience
- Procedural macros -
#[server],#[tool],#[resource],#[prompt] - Type-state capability builders - Compile-time validated capability configuration
- Automatic schema generation - JSON schemas from Rust types
- Type-safe parameters - Compile-time validation and conversion
- Context injection - Request context available in handler signatures
- Builder patterns for user input and message handling
- Context API - Access to user information, authentication, and request metadata
Security Features
- OAuth 2.0 integration - Google, GitHub, Microsoft provider support
- PKCE security - Proof Key for Code Exchange implementation
- CORS protection - Cross-origin resource sharing policies
- Rate limiting - Token bucket algorithm with burst capacity
- Security headers - CSP, HSTS, X-Frame-Options configuration
Multi-Transport Support
- STDIO - Command-line integration with protocol compliance
- HTTP/SSE - HTTP streaming with session management and TLS support
- WebSocket - Real-time bidirectional communication with connection lifecycle management
- TCP - Direct socket connections with connection pooling
- Unix Sockets - Local inter-process communication with file permissions
All transport protocols provide MCP protocol compliance with bidirectional communication, automatic reconnection, and session management.
⚠️ STDIO Transport Output Constraint ⚠️
When using STDIO transport, ALL application output must go to stderr. Any writes to stdout will corrupt the MCP protocol and break client communication.
Compile-Time Safety: The
#[server(transports = ["stdio"])]macro will reject any use ofprintln!()at compile time. This is impossible to bypass - bad code simply won't compile.Correct Pattern:
// All output goes to stderr via tracing_subscriber fmt.with_writer.init; info!; // ✅ Goes to stderr eprintln!; // ✅ Explicit stderrWrong Pattern:
println!; // ❌ COMPILE ERROR in stdio servers stdout.write_all; // ❌ Won't compileSee Stdio Output Guide for comprehensive details.
🌟 MCP Enhanced Features
- 🎵 AudioContent Support - Multimedia content handling for audio data
- 📝 Enhanced Annotations - Rich metadata with ISO 8601 timestamp support
- 🏷️ BaseMetadata Pattern - Proper name/title separation for MCP compliance
- 📋 Advanced Elicitation - Interactive forms with validation support
⚡ Circuit Breaker & Reliability
- Circuit breaker pattern - Prevents cascade failures
- Exponential backoff retry - Intelligent error recovery
- Connection health monitoring - Automatic failure detection
- Graceful degradation - Fallback mechanisms
🔄 Sharing Patterns for Async Concurrency
- Client Clone Pattern - Directly cloneable (Arc-wrapped internally, no wrapper needed)
- SharedTransport - Concurrent transport sharing across async tasks
- McpServer Clone Pattern - Axum/Tower standard (cheap Arc increments, no wrappers)
- Generic Shareable Pattern - Shared and ConsumableShared abstractions
- Arc/Mutex Encapsulation - Hide synchronization complexity from public APIs
Architecture
TurboMCP is built as a layered architecture with clear separation of concerns:
┌─────────────────────────────────────────────────────────────┐
│ TurboMCP Framework │
│ Ergonomic APIs & Developer Experience │
├─────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ Server • Client • Transport • Protocol │
├─────────────────────────────────────────────────────────────┤
│ Foundation Layer │
│ Core Types • Messages • State │
└─────────────────────────────────────────────────────────────┘
Components:
- turbomcp-protocol - MCP specification implementation, core utilities, and SIMD acceleration
- turbomcp-transport - Multi-protocol transport with circuit breakers
- turbomcp-server - Server framework with OAuth 2.0
- turbomcp-client - Client implementation with error recovery
- turbomcp-macros - Procedural macros for ergonomic APIs
- turbomcp-cli - Command-line tools for development and testing
Quick Start
Installation
Add TurboMCP to your Cargo.toml:
[]
= "2.1"
= { = "1.0", = ["full"] }
Basic Server
Create a simple calculator server:
use *;
;
async
Run the Server
# Build and run
# Test with TurboMCP CLI
# For HTTP server
# For STDIO server
Type-State Capability Builders
TurboMCP provides compile-time validated capability builders that ensure correct configuration at build time:
use ;
// Server capabilities with compile-time validation
let server_caps = new
.enable_tools // Enable tools capability
.enable_prompts // Enable prompts capability
.enable_resources // Enable resources capability
.enable_tool_list_changed // ✅ Only available when tools enabled
.enable_resources_subscribe // ✅ Only available when resources enabled
.build;
// Usage in server macro
// Client capabilities with opt-out model (all enabled by default)
let client_caps = new
.enable_roots_list_changed // Configure sub-capabilities
.build; // All capabilities enabled!
// Opt-in pattern for restrictive clients
let minimal_client = minimal
.enable_sampling // Only enable what you need
.enable_roots
.build;
Benefits
- Compile-time validation - Invalid configurations caught at build time
- Zero-cost abstractions - No runtime overhead for validation
- Method availability - Sub-capabilities only available when parent capability is enabled
- Fluent API - Readable and maintainable capability configuration
- Backwards compatibility - Existing code continues to work unchanged
Core Concepts
Server Definition
Use the #[server] macro to automatically implement the MCP server trait:
use *;
Tool Handlers
Transform functions into MCP tools with automatic parameter handling:
async
Resource Handlers
Create URI template-based resource handlers:
async
Prompt Templates
Generate dynamic prompts with parameter substitution:
async
MCP 2025-06-18 Enhanced Features
Roots Support - Filesystem Boundaries
Elicitation - Server-Initiated User Input
use *;
use ElicitationSchema;
async
Sampling Support - Bidirectional LLM Communication
use *;
async
Completion - Intelligent Autocompletion
async
Resource Templates - Dynamic URIs
async
Ping - Bidirectional Health Monitoring
async
Context Injection
The Context parameter provides request correlation, authentication, and observability:
async
Authentication & Security
OAuth 2.0 Setup
TurboMCP provides built-in OAuth 2.0 support:
use *;
use *;
Security Configuration
Configure comprehensive security features:
use ;
let config = production
.with_cors_origins
.with_custom_csp
.with_rate_limit // 120 req/min, 20 burst
.with_jwt_auth;
let app = new
.route
.merge;
Transport Configuration
STDIO Transport (Default)
Perfect for Claude Desktop and local development:
async
HTTP/SSE Transport
For web applications and browser integration:
async
WebSocket Transport
For real-time bidirectional communication:
async
Multi-Transport Runtime Selection
async
Cloning & Concurrency Patterns
TurboMCP provides clean concurrency patterns with Arc-wrapped internals:
Client Clone Pattern - Direct Cloning (No Wrapper Needed)
use Client;
// Client is directly cloneable (Arc-wrapped internally)
let client = connect_http.await?;
// Clone for concurrent usage (cheap Arc increments)
let client1 = client.clone;
let client2 = client.clone;
// Both tasks can access the client concurrently
let handle1 = spawn;
let handle2 = spawn;
let = join!;
SharedTransport - Concurrent Transport Access
use ;
// Wrap any transport for sharing across multiple clients
let transport = new;
let shared = new;
// Connect once
shared.connect.await?;
// Share across tasks
let shared1 = shared.clone;
let shared2 = shared.clone;
let handle1 = spawn;
let handle2 = spawn;
Generic Shareable Pattern
use ;
// Any type can be made shareable
let counter = new;
let shared = new;
// Use with closures for fine-grained control
shared.with_mut.await;
let value = shared.with.await;
// Consumable variant for one-time use
let server = new;
let shared = new;
let server = shared.consume.await?; // Extracts the value
Benefits
- Clean APIs: No exposed Arc/Mutex types
- Easy Sharing: Clone for concurrent access
- Thread Safety: Built-in synchronization
- Zero Overhead: Same performance as direct usage
- MCP Compliant: Preserves all protocol semantics
Error Handling
Error Architecture
TurboMCP uses a layered error system designed for both simplicity and MCP specification compliance:
| Error Type | Crate | Purpose | Use When |
|---|---|---|---|
McpError |
turbomcp |
Simple application errors | Writing tools, resources, prompts |
ProtocolError |
turbomcp_protocol |
MCP-spec compliant errors with rich context | Protocol implementation, server internals |
Quick Decision Guide
Use McpError if you are:
- Writing tool handlers with
#[tool] - Implementing resource providers with
#[resource] - Building prompt handlers with
#[prompt] - Writing application-level business logic
Use ProtocolError if you are:
- Implementing custom protocol handlers
- Building server middleware
- Need observability context (request IDs, metadata, error chaining)
- Require MCP 2025-06-18 specification error codes
Key Insight: Errors automatically convert between layers. Use McpError in your handlers - the server layer converts to ProtocolError with full MCP compliance.
Architecture Flow
Your Tool Handler
↓ Returns McpError
Server Layer (turbomcp-server)
↓ Converts to ServerError::Protocol(Box<ProtocolError>)
Protocol Layer (turbomcp-protocol)
↓ Serializes with MCP error codes
JSON-RPC Response
See examples/error_patterns.rs for comprehensive examples of both error types.
Ergonomic Error Creation
Use the mcp_error! macro for easy error creation:
async
async
Application-Level Errors (McpError)
Simple enum for common error cases:
use McpError;
match result
Protocol-Level Errors (ProtocolError)
For advanced use cases requiring rich context and MCP specification compliance:
use ProtocolError; // Re-exported from turbomcp_protocol
// Constructors return Box<ProtocolError> for efficient cloning and rich context
let err = tool_not_found;
let err = invalid_params;
let err = resource_access_denied;
// Add observability context with builder pattern
let err = internal
.with_operation
.with_component
.with_request_id
.with_context;
// Maps to MCP 2025-06-18 specification error codes
assert_eq!; // Internal error
Why Box<ProtocolError>?
- Enables cheap cloning across async boundaries
- Preserves full error context and source chain
- Integrates with observability systems (tracing, metrics)
- Automatic backtrace capture in debug builds
Advanced Features
Custom Types and Schema Generation
TurboMCP automatically generates JSON schemas for custom types:
use ;
async
Graceful Shutdown
Handle shutdown signals gracefully:
use signal;
async
Performance Tuning
Enable SIMD acceleration for maximum performance:
[]
= { = "2.1", = ["simd"] }
Configure performance settings:
use *;
// Use pre-configured performance profiles
let config = high_performance;
// Other available profiles:
// SessionConfig::memory_optimized() - For resource-constrained environments
// SessionConfig::development() - For development with verbose logging
// Create server and run with selected config
let server = Calculator; // Your server implementation
server.run_stdio.await?;
Testing
Unit Testing
Test your tools directly by calling them as normal methods:
Integration Testing
Use the TurboMCP CLI for integration testing:
# Install CLI
# Test server functionality
# Test STDIO server
Client Setup
Claude Desktop
Add to your Claude Desktop configuration:
Programmatic Client
Use the TurboMCP client:
use ;
async
Examples
Explore comprehensive examples in the examples/ directory:
# Basic calculator server
# File system tools
# Database integration
# Web scraping tools
# Authentication with OAuth 2.0
# HTTP server with advanced features
Feature Flags
| Feature | Description | Default |
|---|---|---|
simd |
Enable SIMD acceleration for JSON processing | ❌ |
oauth |
Enable OAuth 2.0 authentication | ✅ |
metrics |
Enable metrics collection and endpoints | ✅ |
compression |
Enable response compression | ✅ |
all-transports |
Enable all transport protocols | ✅ |
minimal |
Minimal build (STDIO only) | ❌ |
Important: Minimum Feature Requirements
When using default-features = false, you must explicitly enable at least one transport feature to have a functional MCP server. The available transport features are:
stdio- STDIO transport (included in default features)http- HTTP/SSE transportwebsocket- WebSocket transporttcp- TCP transportunix- Unix socket transport
Example configurations:
# Minimal STDIO-only server
[]
= { = "2.1", = false, = ["stdio"] }
# HTTP-only server
[]
= { = "2.1", = false, = ["http"] }
# Multiple transports without default features
[]
= { = "2.1", = false, = ["stdio", "http", "websocket"] }
Without at least one transport feature enabled, the server will not be able to communicate using the MCP protocol.
Development
Building
# Build with all features
# Build optimized for production
# Run tests
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature-name - Make your changes and add tests
- Run the full test suite:
make test - Submit a pull request
Performance Architecture
Compile-Time Optimization
TurboMCP uses a compile-time first approach with these characteristics:
Build-Time Features:
- Macro-driven code generation pre-computes metadata at build time
- Tool schemas, parameter validation, and handler dispatch tables generated statically
- Rust's type system provides compile-time safety and optimization opportunities
- Feature flags allow selective compilation for lean binaries
Runtime Characteristics:
- Static schema generation eliminates per-request computation
- Direct function dispatch without hash table lookups
- Zero-copy message handling where possible
- Async runtime scaling with Tokio
Implementation Approach:
// Compile-time schema generation
async
Benchmarks
# Run performance benchmarks
# Test SIMD acceleration
# Profile memory usage
Documentation
- Architecture Guide - System design and components
- Security Features - Comprehensive security documentation
- API Documentation - Complete API reference
- Stdio Output Guide - STDIO transport output requirements
- Examples - Ready-to-use code examples
Related Projects
- Model Context Protocol - Official protocol specification
- Claude Desktop - AI assistant with MCP support
- MCP Servers - Official server implementations
License
Licensed under the MIT License.
Built with ❤️ by the TurboMCP team