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:
[]
= "3.1.2"
= { = "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-11-25 Enhanced Features
TurboMCP targets MCP 2025-11-25 (with 2025-06-18 accepted by default via
per-version response adapters). Protocol-level features such as resource URI
templates (RFC 6570), elicitation, sampling, tasks, and draft extensions are
implemented in turbomcp-protocol; see the crate-level docs for current
surface area. The available attribute macros for server authors are:
#[server], #[tool], #[resource], #[prompt], and #[description].
Resource Templates (RFC 6570)
async
Context Injection
Inject &RequestContext as the first parameter to access per-request
metadata (correlation IDs, transport info, session state). Auth, structured
logging, metrics, and server-initiated sampling are handled through separate
facilities (middleware, the turbomcp-telemetry crate, and the client-side
create_message API respectively) rather than on the context itself.
async
Authentication & Security
OAuth 2.1 Setup
TurboMCP ships an OAuth 2.1 + PKCE implementation in the turbomcp-auth
crate, re-exported from the main crate as turbomcp::auth when the auth
feature is enabled. DPoP (RFC 9449) proof-of-possession lives in
turbomcp-dpop and is enabled via the dpop feature (which pulls in
auth). Authenticated identity is attached to requests through
RequestContext::principal via middleware; tools read it from the context
rather than calling an authenticated_user() helper. See the
turbomcp-auth crate docs for the provider / middleware construction APIs.
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 exposes a single unified error type — McpError — defined in
turbomcp-core and re-exported as turbomcp::McpError /
turbomcp::McpResult. There is one error type across the whole stack:
handlers, middleware, transport, and protocol layers all speak the same
McpError.
This is a deliberate simplification over the earlier two-tier
(McpError → ProtocolError) design: McpError already carries
JSON-RPC error codes, HTTP status mapping, retryability metadata, and a
fluent .with_operation(...) / .with_component(...) context chain,
which is everything the old ProtocolError provided.
Flow
Your Tool Handler
↓ returns McpResult<T> (i.e. Result<T, McpError>)
Server Layer (turbomcp-server)
↓ inspects McpError metadata (jsonrpc_code, retryability, context)
Protocol / JSON-RPC Response
Use McpError everywhere. For MCP-specification error codes, the
appropriate constructor (tool_not_found, invalid_params,
resource_not_found, authentication, permission_denied,
rate_limited, timeout, transport, internal, …) picks the right
JSON-RPC / MCP code for you — see the "Error Handling" examples below.
Ergonomic Error Creation
Use McpError constructors for error creation:
async
async
Application-Level Errors (McpError)
Construct errors with fluent constructors:
use McpError;
// Construct with appropriate constructor
let err = invalid_params;
let err = authentication;
let err = resource_not_found;
let err = transport;
let err = internal
.with_operation
.with_component;
// Query error metadata
assert!;
let _code = err.jsonrpc_code;
let _status = err.http_status;
Protocol-Level Error Codes
McpError exposes its MCP / JSON-RPC semantics directly — no separate
error type is needed:
use McpError;
let err = internal
.with_operation
.with_component;
assert_eq!; // Internal error
let _http_status = err.http_status; // HTTP mapping
let _retryable = err.is_retryable; // Retry hint for clients
Constructors such as tool_not_found, invalid_params,
resource_not_found, capability_not_supported, and rate_limited
emit the MCP-spec JSON-RPC codes defined in turbomcp-core::error_codes.
Advanced Features
Custom Types and Schema Generation
TurboMCP automatically generates JSON schemas for custom types:
use ;
async
Graceful Shutdown
The HTTP transport integrates with Tokio signal handlers for graceful
shutdown. Configure the drain timeout through the server builder
(ServerBuilder::with_graceful_shutdown); the HTTP runner awaits SIGINT
(and SIGTERM on Unix) and drains in-flight requests up to the configured
deadline. For STDIO, the process exits cleanly when stdin closes.
Performance Tuning
SIMD-accelerated JSON parsing is provided by turbomcp-protocol (enabled by default via its simd feature, which selects sonic-rs). No extra flag is required on the turbomcp crate.
Configure server behavior via ServerConfig and pass it through the
server builder — the convenience methods (run_stdio, run_http, …)
use defaults and ignore any standalone ServerConfig, so reach for
.builder().with_config(...) when you need custom settings:
use *;
use ;
let config = builder
.max_message_size // 10 MB
.build;
Calculator
.builder
.with_config
.transport // or http/tcp/websocket/unix
.serve
.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 HashMap;
use Client;
async
Examples
Explore examples in the examples/ directory:
# Minimal server
# Server patterns
# Transports (require the matching feature flag)
# Capability builders & testing
Feature Flags
| Feature | Description | Default |
|---|---|---|
stdio |
STDIO transport | ✅ |
http |
HTTP / SSE (Streamable HTTP) transport | ❌ |
websocket |
WebSocket bidirectional transport | ❌ |
tcp |
Raw TCP socket transport | ❌ |
unix |
Unix domain socket transport | ❌ |
channel |
In-process channel transport (testing/benchmarks) | ❌ |
minimal |
Bundle: STDIO only (= stdio) |
❌ |
full |
Bundle: all transports + telemetry | ❌ |
full-stack |
Bundle: full + full-client |
❌ |
all-transports |
Bundle: all transports incl. channel (no telemetry) |
❌ |
telemetry |
OpenTelemetry, metrics, structured logging | ❌ |
auth |
OAuth 2.1, JWT, API key auth (turbomcp-auth) | ❌ |
dpop |
RFC 9449 DPoP (requires auth) |
❌ |
client-integration |
Re-export minimal turbomcp-client (STDIO) |
❌ |
full-client |
turbomcp-client with all transports |
❌ |
experimental-tasks |
Tasks API (SEP-1686) | ❌ |
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
[]
= { = "3.1.2", = false, = ["stdio"] }
# HTTP-only server
[]
= { = "3.1.2", = false, = ["http"] }
# Multiple transports without default features
[]
= { = "3.1.2", = 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 (SIMD JSON is enabled by default via turbomcp-protocol)
# 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:
just 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
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