TurboMCP Server
MCP server framework with OAuth 2.1 MCP compliance, middleware pipeline, and lifecycle management.
Overview
turbomcp-server provides a comprehensive server framework for Model Context Protocol implementations. It handles all server-side concerns including request routing, authentication, middleware processing, session management, and production lifecycle operations.
Security Hardened
- Zero Known Vulnerabilities - Comprehensive security audit and hardening
- Dependency Security - Eliminated all vulnerable dependency paths
- MIT-Compatible Licensing - Strict open-source license compliance
Key Features
Handler Registry & Routing
- Type-safe registration - Compile-time handler validation and automatic discovery
- Efficient routing - O(1) method dispatch with parameter injection
- Schema generation - Automatic JSON schema creation from handler signatures
- Hot reloading - Dynamic handler registration and updates (development mode)
OAuth 2.1 MCP Compliance
- Multiple providers - Google, GitHub, Microsoft, and custom OAuth 2.1 providers
- PKCE security - Proof Key for Code Exchange enabled by default
- All OAuth flows - Authorization Code, Client Credentials, Device Code
- Session management - Secure user session tracking with automatic cleanup
Middleware Pipeline
- Request processing - Configurable middleware chain with error handling
- Security middleware - CORS, CSP, rate limiting, security headers
- Authentication - JWT validation, API key, OAuth token verification
- Observability - Request logging, metrics collection, distributed tracing
Health & Metrics
- Health endpoints - Readiness, liveness, and custom health checks
- Performance metrics - Request timing, error rates, resource utilization
- Prometheus integration - Standard metrics format with custom labels
- Circuit breaker status - Transport and dependency health monitoring
Graceful Shutdown
- Signal handling - SIGTERM/SIGINT graceful shutdown with timeout
- Connection draining - Active request completion before shutdown
- Resource cleanup - Proper cleanup of connections, files, and threads
- Health status - Shutdown status reporting for load balancers
Clone Pattern for Server Sharing (Axum/Tower Standard)
- Cheap cloning - All heavy state is Arc-wrapped (just atomic increments)
- Tower compatible - Same pattern as Axum's Router and Tower services
- No wrapper types - Server is directly Clone (no Arc needed)
- Concurrent access - Share across multiple async tasks for monitoring
- Zero overhead - Same performance as direct server usage
- Type safe - Same type whether cloned or not
Architecture
┌─────────────────────────────────────────────┐
│ TurboMCP Server │
├─────────────────────────────────────────────┤
│ Request Processing Pipeline │
│ ├── Middleware chain │
│ ├── Authentication layer │
│ ├── Request routing │
│ └── Handler execution │
├─────────────────────────────────────────────┤
│ Handler Registry │
│ ├── Type-safe registration │
│ ├── Schema generation │
│ ├── Parameter validation │
│ └── Response serialization │
├─────────────────────────────────────────────┤
│ Authentication & Session │
│ ├── OAuth 2.0 providers │
│ ├── JWT token validation │
│ ├── Session lifecycle │
│ └── Security middleware │
├─────────────────────────────────────────────┤
│ Observability & Lifecycle │
│ ├── Health check endpoints │
│ ├── Metrics collection │
│ ├── Graceful shutdown │
│ └── Resource management │
└─────────────────────────────────────────────┘
Server Builder
Basic Server Setup
use ;
// Simple server creation
let server = new
.name
.version
.build;
// Run with STDIO transport
server.run_stdio.await?;
Production Server Configuration
use ;
let server = new
.name
.version
.description
// Authentication middleware
.middleware
// Security middleware
.middleware
// Rate limiting
.middleware
// Health and metrics
.with_health_checks
.with_metrics
// Graceful shutdown
.with_graceful_shutdown
.build;
Handler Registry
Manual Handler Registration
use ;
let mut registry = new;
// Register tool handlers
registry.register_tool.await?;
// Register resource handlers
registry.register_resource.await?;
// Attach to server
let server = new
.with_registry
.build;
Schema Validation
use ;
let validator = new;
let server = new
.with_schema_validation
.build;
OAuth 2.1 MCP Authentication
Google OAuth Setup
use ;
let google_config = OAuth2Config ;
let google_provider = new.await?;
GitHub OAuth Setup
let github_config = OAuth2Config ;
let github_provider = new.await?;
Multi-Provider Authentication
use AuthenticationManager;
let auth_manager = new
.add_provider
.add_provider
.add_provider
.with_session_store
.with_token_validation;
let server = new
.with_authentication
.build;
Middleware System
Custom Middleware
use ;
use async_trait;
;
// Register middleware
let server = new
.middleware
.build;
Error Handling Middleware
use ErrorHandlerMiddleware;
let error_handler = new
.handle_authentication_error
.handle_validation_error
.handle_internal_error;
let server = new
.middleware
.build;
Session Management
Session Configuration
use ;
let session_config = new
.ttl // 1 hour
.max_sessions
.cleanup_interval // 5 minutes
.secure_cookies
.same_site_strict;
let session_store = redis.await?;
// or
let session_store = memory_with_persistence.await?;
let session_manager = new;
let server = new
.with_session_management
.build;
Health Checks
Built-in Health Checks
use ;
let health_checker = new
.add_check
.add_check
.add_check
.add_check; // 1GB minimum
let server = new
.with_health_checks
.build;
Custom Health Checks
use ;
use async_trait;
let server = new
.with_health_check
.build;
Metrics & Observability
Prometheus Metrics
use ;
let metrics = prometheus;
let server = new
.with_metrics
.build;
// Metrics are automatically collected:
// - turbomcp_server_requests_total{method, status}
// - turbomcp_server_request_duration_seconds{method}
// - turbomcp_server_active_connections
// - turbomcp_server_errors_total{error_type}
Custom Metrics
use ;
let server = new
.with_custom_metrics
.build;
Integration Examples
With TurboMCP Framework
Server functionality is automatically provided when using the framework:
use *;
async
Direct Server Usage
For advanced server customization:
use ;
async
Feature Flags
| Feature | Description | Default |
|---|---|---|
oauth |
Enable OAuth 2.0 authentication | ✅ |
metrics |
Enable metrics collection | ✅ |
health-checks |
Enable health check endpoints | ✅ |
session-redis |
Enable Redis session storage | ❌ |
session-postgres |
Enable PostgreSQL session storage | ❌ |
tracing |
Enable distributed tracing | ✅ |
compression |
Enable response compression | ✅ |
Server Sharing with Clone (Axum/Tower Pattern)
TurboMCP follows the Axum/Tower Clone pattern for sharing server instances across tasks and threads. All heavy state is Arc-wrapped internally, making cloning cheap (just atomic reference count increments).
Basic Server Cloning
use ;
// Create server (Clone-able)
let server = new
.name
.version
.build;
// Clone for monitoring tasks (cheap - just Arc increments)
let monitor1 = server.clone;
let monitor2 = server.clone;
// Concurrent monitoring operations
let health_task = spawn;
let metrics_task = spawn;
// Run the server
server.run_stdio.await?;
Advanced Server Monitoring
use ;
use Arc;
use Notify;
let server = new.build;
let shutdown_notify = new;
// Health monitoring task
let monitor = server.clone;
let notify = shutdown_notify.clone;
let health_task = spawn;
// Metrics collection task
let metrics_monitor = server.clone;
let metrics_task = spawn;
// Run server with monitoring
let server_task = spawn;
// Wait for shutdown signal or server completion
select!
Benefits of the Clone Pattern
- Cheap Cloning: Just atomic reference count increments (Arc-wrapped state)
- Tower Compatible: Follows the same pattern as Axum's Router
- No Arc Wrappers: No need for
Arc<McpServer>- server is directly Clone - Type Safe: Same type whether cloned or not (no wrapper types)
- Zero Overhead: Same performance as direct server usage
- Ecosystem Standard: Matches Axum, Tower, Hyper conventions
Development
Building
# Build with all features
# Build minimal server
# Build with OAuth only
Testing
# Run server tests
# Test with OAuth providers (requires environment variables)
GOOGLE_CLIENT_ID=test GOOGLE_CLIENT_SECRET=test
# Integration tests
# Test graceful shutdown
Development Server
# Run development server with hot reloading
# Run with debug logging
RUST_LOG=debug
Related Crates
- turbomcp - Main framework (uses this crate)
- turbomcp-protocol - Protocol implementation and core utilities
- turbomcp-transport - Transport layer
Note: In v2.0.0, turbomcp-core was merged into turbomcp-protocol to eliminate circular dependencies.
External Resources
- OAuth 2.0 Specification - OAuth 2.0 authorization framework
- PKCE Specification - Proof Key for Code Exchange
- Prometheus Metrics - Metrics format specification
License
Licensed under the MIT License.
Part of the TurboMCP high-performance Rust SDK for the Model Context Protocol.