TurboMCP
Rust SDK for the Model Context Protocol (MCP) with comprehensive specification support and performance optimizations.
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-deny
policy - 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
- Intuitive APIs - 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 Protocol Compliance: When using STDIO transport (the default), avoid any logging or output to stdout. The MCP protocol requires stdout to contain only JSON-RPC messages. Any other output will break client communication. Use stderr for debugging if needed.
🌟 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
🔄 Shared Wrappers for Async Concurrency (New in v1.1.0)
- SharedClient - Thread-safe client access with clean APIs
- SharedTransport - Concurrent transport sharing across async tasks
- SharedServer - Server lifecycle management with consumption pattern
- 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-core - Performance-critical types and SIMD acceleration
- turbomcp-protocol - MCP specification implementation
- 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
:
[]
= "1.1.0"
= { = "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 (New in v1.1.0)
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 type safety
let client_caps = new
.enable_roots // Enable filesystem roots
.enable_sampling // Enable LLM sampling
.enable_elicitation // Enable interactive forms
.enable_roots_list_changed // ✅ Only available when roots enabled
.build;
// Convenience builders for common patterns
let full_server = full_featured.build;
let minimal_server = minimal.build;
let sampling_client = sampling_focused.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 (New in v1.1.0)
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
Shared Wrappers for Async Concurrency (v1.1.0)
TurboMCP v1.1.0 introduces comprehensive shared wrapper system that eliminates Arc/Mutex complexity from public APIs:
SharedClient - Thread-Safe Client Access
use ;
use StdioTransport;
// Create shared client for concurrent access
let transport = new;
let client = new;
let shared = new;
// Initialize once
shared.initialize.await?;
// Clone for concurrent usage
let shared1 = shared.clone;
let shared2 = shared.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
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
Ergonomic Error Creation
Use the mcp_error!
macro for easy error creation:
async
async
Error Types
TurboMCP provides comprehensive error types:
use McpError;
match result
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:
[]
= { = "1.1.0", = ["simd"] }
Configure performance settings:
use ;
let config = high_performance
.with_simd_acceleration
.with_connection_pooling
.with_circuit_breakers;
let server = new
.with_session_config
.with_compression;
Testing
Unit Testing
Test your tools directly:
Integration Testing
Use the TurboMCP CLI for integration testing:
# Install CLI
# Test server functionality
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) | ❌ |
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 & Architectural Excellence
🚀 Leapfrog Architecture Advantage
TurboMCP's compile-time first design philosophy delivers measurable performance advantages over traditional MCP implementations:
Compile-Time Optimization Strategy
- Macro-driven efficiency -
#[server]
,#[tool]
, and#[resource]
macros pre-compute all metadata at build time - Zero runtime reflection - Tool schemas, parameter validation, and handler dispatch tables generated statically
- Type-system leveraged - Rust's ownership model eliminates common performance pitfalls (no GC, predictable memory)
- Intelligent feature gating - Comprehensive codebase with surgical binary optimization through compile-time feature selection
Runtime Performance Benefits
- JSON Processing: 2-3x faster than
serde_json
with SIMD acceleration - Memory Efficiency: 40% reduction through zero-copy processing and pre-allocated buffers
- Cold Start Performance: Faster initialization due to pre-computed schemas and handler registration
- Request Latency: Sub-millisecond tool dispatch with O(1) handler lookup
- Concurrent Scaling: Linear performance scaling with Tokio's async runtime
- Predictable Performance: No garbage collection pauses or dynamic allocation surprises
Architectural Superiority
Compile-Time vs Runtime Trade-offs:
// Other frameworks: Runtime overhead
// TurboMCP: Compile-time optimization
// Pre-computed at build
async
Key Differentiators:
- Direct Dispatch: Tool calls resolve to function pointers, not string lookups
- Pre-computed Schemas: JSON schemas generated once at compile time, not per request
- Zero Reflection Overhead: All type information resolved statically
- Optimized Binary Size: Feature flags eliminate unused transport and protocol code
Why Compile-Time Architecture Matters
While runtime-based frameworks offer flexibility, TurboMCP's compile-time approach provides:
- Guaranteed Performance: No performance degradation as tool count increases
- Resource Predictability: Memory usage determined at compile time
- Production Reliability: Errors caught at build time, not in production
- Developer Experience: Rich IDE support with full type checking and autocompletion
The TurboMCP Philosophy: "Handle complexity at compile time so runtime can be blazingly fast."
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
- Performance Guide - Optimization strategies
- 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. Ready for production, optimized for performance, designed for developers.