TurboMCP Server
MCP server framework with OAuth 2.1 MCP compliance, middleware pipeline, and lifecycle management.
Table of Contents
- Overview
- Key Features
- Architecture
- Server Builder
- Handler Registry
- Authentication & Session
- Middleware System
- Advanced Features
- Integration
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 with Handlers
use ServerBuilder;
use Root;
let server = new
.name
.version
.description
// Register filesystem roots
.root
.root
// Register tool handlers (traits implement ToolHandler)
.tool?
.tool?
// Register resource handlers
.resource?
.resource?
// Register prompt handlers
.prompt?
.build;
// Middleware, auth, and observability are configured separately
// via the MiddlewareStack (see Middleware System section)
Handler Registry
Handler Traits
Handlers implement trait interfaces for type-safe registration:
use ;
use ;
use async_trait;
use json;
// Example tool handler
;
// Register via builder
let server = new
.tool?
.build;
Authentication with turbomcp-auth
The server integrates with the turbomcp-auth crate for comprehensive authentication:
OAuth 2.1 Setup
use ;
// Configure OAuth 2.1
let oauth_config = OAuth2Config ;
// Create auth manager
let mut settings_map = new;
// Serialize OAuth config to Value, then extract as object
if let Object = to_value?
let auth_config = AuthConfig ;
let auth_manager = new;
// Add to your server implementation
// (integration varies based on transport type)
JWT Authentication via Middleware
For JWT-only authentication, use the server's built-in middleware:
use AuthConfig;
use Secret;
use Algorithm;
// JWT authentication is available via middleware (feature: auth)
let auth_config = AuthConfig ;
Middleware System
The server uses a Tower-based middleware stack for cross-cutting concerns:
use ;
use Method;
use Duration;
// Build a comprehensive middleware stack
let middleware = new
.with_security
.with_validation
.with_timeout
.with_audit;
// With auth feature enabled:
// With rate-limiting feature enabled:
// The middleware stack is automatically applied by the server
Session Management with turbomcp
Session management is provided by the main turbomcp crate:
use ;
use Duration;
// Configure session management
let session_config = SessionConfig ;
// Or use preset configurations
let session_config = high_performance;
// Create session manager
let session_manager = new;
// Session manager handles:
// - Session lifecycle (create, update, expire)
// - Per-client session limits with LRU eviction
// - Automatic cleanup of expired sessions
// - Session analytics and activity tracking
Health & Lifecycle
The server provides built-in health status and graceful shutdown:
use ServerBuilder;
let server = new
.name
.version
.build;
// Get health status
let health = server.health.await;
if health.healthy else
// Graceful shutdown
let shutdown_handle = server.shutdown_handle;
spawn;
server.run_stdio.await?;
Metrics & Observability
The server provides built-in production-grade metrics collection with lock-free atomic operations:
use ;
let server = new
.name
.version
.build;
// Access server metrics
let metrics = server.metrics;
// Metrics are automatically collected:
println!;
println!;
println!;
println!;
// Error metrics
println!;
println!;
println!;
// Tool execution metrics
println!;
println!;
// Connection metrics
println!;
println!;
// Response time statistics
let avg_response_time_us = metrics.total_response_time_us.load
/ metrics.requests_total.load.max;
println!;
// Custom metrics (use the RwLock-protected HashMap)
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 Rust SDK for the Model Context Protocol.