Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
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
- Session Management
- Health & Lifecycle
- Metrics & Observability
- Integration Examples
- Feature Flags
- Development
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.1 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-protocol
Session management is provided by the turbomcp-protocol crate:
use ;
use Duration;
use Duration as StdDuration;
// Configure session management
let session_config = SessionConfig ;
// Create session manager
let session_manager = new;
// Session manager handles:
// - Session lifecycle (create, update, expire)
// - Request analytics and client behavior tracking
// - Automatic cleanup of expired sessions
// - Elicitation and completion 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 |
|---|---|---|
stdio |
Enable STDIO transport | ✅ |
http |
Enable HTTP transport | ❌ |
websocket |
Enable WebSocket transport | ❌ |
tcp |
Enable TCP transport | ❌ |
unix |
Enable Unix socket transport | ❌ |
auth |
Enable JWT authentication middleware | ❌ |
metrics |
Enable metrics collection | ❌ |
health-checks |
Enable health check endpoints | ❌ |
middleware |
Enable middleware stack (CORS, security headers, etc) | ❌ |
rate-limiting |
Enable rate limiting middleware | ❌ |
multi-tenancy |
Enable multi-tenant SaaS features (tenant extraction, per-tenant config, metrics) | ❌ |
graceful-shutdown |
DEPRECATED - Graceful shutdown is now always enabled | ❌ |
observability |
Enable observability features | ❌ |
hot-reload |
Enable hot reloading of handlers | ❌ |
all-transports |
Enable all transport types | ❌ |
full |
Enable all features | ❌ |
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
Multi-Tenancy Security Best Practices
When building multi-tenant SaaS applications with TurboMCP, follow these security practices to ensure robust tenant isolation:
1. Always Validate Tenant Ownership
Critical: Before accessing any tenant-scoped resource, validate that the requesting tenant owns it:
async
Never skip validation:
// ❌ INSECURE: No tenant validation
async
2. Use Database Row-Level Security (RLS)
Implement defense-in-depth with database-level isolation:
-- PostgreSQL Row-Level Security example
users ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON users
USING (tenant_id = current_setting('app.current_tenant')::text);
-- Set tenant context in connection
SET app.current_tenant = 'acme-corp';
3. Encrypt Tenant Credentials
Store per-tenant API keys and OAuth tokens encrypted:
use ;
async
4. Implement Per-Tenant Rate Limiting
Prevent one tenant from consuming all resources:
use TenantConfig;
let tenant_config = TenantConfig ;
5. Audit Logging for Compliance
Log all tenant operations for security audits:
async
6. Tenant Extraction Strategies
Use multiple extraction methods with fallback:
use *;
let extractor = new;
7. Migration from Single to Multi-Tenant
Gradual migration path:
// Phase 1: Add tenant_id column (nullable)
ALTER TABLE users ADD COLUMN tenant_id TEXT;
// Phase 2: Backfill existing data with default tenant
UPDATE users SET tenant_id = 'default' WHERE tenant_id IS NULL;
// Phase 3: Make non-nullable
ALTER TABLE users ALTER COLUMN tenant_id SET NOT NULL;
// Phase 4: Add tenant validation to code
ctx.validate_tenant_ownership?;
8. Testing Multi-Tenancy
Test tenant isolation thoroughly:
async
9. Security Checklist
Before deploying multi-tenant applications:
- All resource access validates
ctx.validate_tenant_ownership() - Database has row-level security (RLS) enabled
- Credentials encrypted per-tenant with separate keys
- Rate limiting configured per-tenant
- Audit logging enabled for all mutations
- Tenant extraction middleware configured
- Integration tests verify tenant isolation
- No tenant ID leakage in error messages
- Background jobs scoped to correct tenant
- Admin endpoints require super-user auth
10. Common Pitfalls
❌ Don't trust client-provided tenant IDs without validation ❌ Don't use global caches without tenant keys ❌ Don't expose tenant IDs in URLs (use opaque resource IDs) ❌ Don't log sensitive tenant data ❌ Don't share database connections across tenants without context
✅ Do validate tenant ownership before every resource access ✅ Do use database-level isolation (RLS) ✅ Do encrypt credentials per-tenant ✅ Do implement comprehensive audit logging ✅ Do test tenant isolation thoroughly
Example: Complete Secure Tool
async
For a complete working example, see examples/multi_tenant_server.rs in the TurboMCP repository.
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.1 Specification - OAuth 2.1 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.