Expand description
§TurboMCP - Model Context Protocol SDK
Rust SDK for the Model Context Protocol (MCP) with SIMD acceleration, robust transport layer, graceful shutdown, and ergonomic APIs.
§Features
§Core MCP Protocol Support
- MCP 2025-06-18 Specification - Full compliance with latest protocol including elicitation
- Type Safety - Compile-time validation with automatic schema generation
- Context Injection - Dependency injection and observability with structured logging
- Zero-Overhead Macros - Ergonomic
#[server],#[tool],#[resource],#[prompt]attributes
§Advanced Protocol Features
- Roots Support - Configurable filesystem roots via macro or builder API with OS-aware defaults
- Zero Ceremony Elicitation - Server-initiated user input with beautiful title-first builders (Enhanced 1.0.4)
- Sampling Protocol - Bidirectional LLM sampling capabilities with metadata tracking
- Compile-Time Routing - Zero-cost compile-time router generation (experimental)
§Transport & Performance
- Multi-Transport - STDIO, TCP, Unix sockets, WebSocket, HTTP/SSE with runtime selection
- SIMD-Accelerated JSON -
simd-jsonandsonic-rsfor fast processing - Robust - Circuit breakers, retry logic, graceful shutdown
- WebSocket Bidirectional - Full-duplex communication for real-time elicitation
- HTTP Server-Sent Events - Server-push capabilities for lightweight deployments
§Enterprise Features
- OAuth 2.0 Authentication - Multi-provider support (Google, GitHub, Microsoft)
- Security Headers - CORS, CSP, HSTS protection
- Rate Limiting - Token bucket algorithm with configurable strategies
- Middleware Stack - Authentication, logging, security headers
§Quick Start
use turbomcp::prelude::*;
#[derive(Clone)]
struct Calculator {
operations: std::sync::Arc<std::sync::atomic::AtomicU64>,
}
#[server(
name = "calculator-server",
version = "1.0.0",
// Configure filesystem roots directly in the macro
root = "file:///workspace:Workspace",
root = "file:///tmp:Temporary Files"
)]
impl Calculator {
#[tool("Add two numbers")]
async fn add(&self, ctx: Context, a: i32, b: i32) -> McpResult<i32> {
// Context injection provides automatic:
// - Request correlation and distributed tracing
// - Structured logging with metadata
// - Performance monitoring and metrics
ctx.info(&format!("Adding {} + {}", a, b)).await?;
self.operations.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(a + b)
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let server = Calculator {
operations: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
};
server.run_stdio().await?;
Ok(())
}§Graceful Shutdown
TurboMCP provides graceful shutdown for all transport methods:
use turbomcp::prelude::*;
use std::sync::Arc;
#[derive(Clone)]
struct Calculator {
operations: Arc<std::sync::atomic::AtomicU64>,
}
#[server]
impl Calculator {
#[tool("Add numbers")]
async fn add(&self, a: i32, b: i32) -> McpResult<i32> {
Ok(a + b)
}
}
// Example: Get shutdown handle for graceful termination
let server = Calculator {
operations: Arc::new(std::sync::atomic::AtomicU64::new(0)),
};
// This gives you a handle to gracefully shutdown the server
let (server, shutdown_handle) = server.into_server_with_shutdown().unwrap();
// In production, you'd spawn the server and wait for signals:
// tokio::spawn(async move { server.run_stdio().await });
// signal::ctrl_c().await?;
// shutdown_handle.shutdown().await;§Runtime Transport Selection
use turbomcp::prelude::*;
use std::sync::Arc;
#[derive(Clone)]
struct Calculator {
operations: Arc<std::sync::atomic::AtomicU64>,
}
#[server]
impl Calculator {
#[tool("Add numbers")]
async fn add(&self, a: i32, b: i32) -> McpResult<i32> {
Ok(a + b)
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let server = Calculator {
operations: Arc::new(std::sync::atomic::AtomicU64::new(0)),
};
// Runtime transport selection based on environment
match std::env::var("TRANSPORT").as_deref() {
Ok("tcp") => {
let port: u16 = std::env::var("PORT")
.unwrap_or_else(|_| "8080".to_string())
.parse()
.unwrap_or(8080);
server.run_tcp(format!("127.0.0.1:{}", port)).await?;
}
Ok("unix") => {
let path = std::env::var("SOCKET_PATH")
.unwrap_or_else(|_| "/tmp/mcp.sock".to_string());
server.run_unix(path).await?;
}
_ => {
server.run_stdio().await?;
}
}
Ok(())
}§Error Handling
TurboMCP provides ergonomic error handling with the mcp_error! macro:
use turbomcp::prelude::*;
use std::sync::Arc;
#[derive(Clone)]
struct Calculator {
operations: Arc<std::sync::atomic::AtomicU64>,
}
#[server]
impl Calculator {
#[tool("Divide two numbers")]
async fn divide(&self, a: f64, b: f64) -> McpResult<f64> {
if b == 0.0 {
return Err(turbomcp::McpError::Tool("Cannot divide by zero".to_string()));
}
Ok(a / b)
}
}§Elicitation Support - Zero Ceremony Builders (Enhanced in 1.0.4)
TurboMCP provides world-class ergonomic elicitation with zero ceremony builders for beautiful, intuitive APIs:
use turbomcp::prelude::*;
use turbomcp::elicitation_api::{ElicitationResult, text, checkbox, integer_field};
use turbomcp_macros::elicit;
#[derive(Clone)]
struct ConfigServer;
#[server]
impl ConfigServer {
#[tool("Configure deployment")]
async fn deploy(&self, ctx: Context, project: String) -> McpResult<String> {
// 🎯 Simple elicit macro for quick confirmations
let confirmation = elicit!(ctx, "Deploy to production?")?;
if matches!(confirmation, ElicitationResult::Decline(_)) {
return Ok("Deployment cancelled".to_string());
}
// 🚀 Zero ceremony builders - beautiful title-first constructors!
let config = elicit("Configure deployment")
.field("environment", text("Environment").options(&["dev", "staging", "production"]))
.field("auto_scale", checkbox("Enable Auto-scaling").default(true))
.field("replicas", integer_field("Replica Count").range(1.0, 10.0))
.require(vec!["environment"])
.send(&ctx.request)
.await?;
match config {
ElicitationResult::Accept(data) => {
let env = data.get::<String>("environment")?;
let replicas = data.get::<i64>("replicas").unwrap_or(1);
Ok(format!("Deployed {} to {} with {} replicas", project, env, replicas))
}
_ => Err(mcp_error!("Deployment cancelled"))
}
}
}Key Features:
- Zero Ceremony:
text("Title"),checkbox("Label"),integer_field("Name") - No Boilerplate: Field method accepts builders directly via
Into<T> - Smart Constructors: Title-first API eliminates nested parentheses
- Backward Compatible: Builder variants available as
*_builder()
§Sampling Support (New in 1.0.3)
Server-initiated sampling requests enable bidirectional LLM communication:
use turbomcp::prelude::*;
#[derive(Clone)]
struct AIAssistant;
#[server]
impl AIAssistant {
#[tool("Get AI assistance for code review")]
async fn code_review(&self, ctx: Context, code: String) -> McpResult<String> {
// Log the review request with user context
let user = ctx.user_id().unwrap_or("anonymous");
ctx.info(&format!("User {} requesting review of {} lines", user, code.lines().count())).await?;
// Example: Create a sampling request for AI analysis
let sampling_request = serde_json::json!({
"messages": [{
"role": "user",
"content": {
"type": "text",
"text": format!("Please review this code:\n\n{}", code)
}
}],
"maxTokens": 500,
"systemPrompt": "You are a senior code reviewer. Provide constructive feedback."
});
// Use the sampling API for real AI analysis (requires client LLM capability)
match ctx.create_message(sampling_request).await {
Ok(response) => Ok(format!("AI Review: {:?}", response)),
Err(_) => {
// Fallback to simple analysis if sampling unavailable
let issues = code.matches("TODO").count() + code.matches("FIXME").count();
Ok(format!("Static analysis: {} lines, {} issues found", code.lines().count(), issues))
}
}
}
}§OAuth 2.0 Authentication
Built-in OAuth 2.0 support with multiple providers and all standard flows:
use turbomcp::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
#[derive(Clone)]
struct AuthenticatedServer {
user_sessions: Arc<RwLock<HashMap<String, String>>>,
}
#[server]
impl AuthenticatedServer {
#[tool("Get authenticated user profile")]
async fn get_user_profile(&self, ctx: Context, session_token: String) -> McpResult<String> {
let sessions = self.user_sessions.read().await;
if let Some(user_id) = sessions.get(&session_token) {
Ok(format!("Authenticated user: {}", user_id))
} else {
Err(McpError::InvalidInput("Authentication required".to_string()))
}
}
#[tool("Start OAuth flow")]
async fn start_oauth_flow(&self, provider: String) -> McpResult<String> {
match provider.as_str() {
"github" | "google" | "microsoft" => {
Ok(format!("Visit: https://{}.com/oauth/authorize", provider))
}
_ => Err(McpError::InvalidInput(format!("Unknown provider: {}", provider))),
}
}
}OAuth Features:
- 🔐 Multiple Providers - Google, GitHub, Microsoft, custom OAuth 2.0
- 🛡️ Always-On PKCE - Security enabled by default
- 🔄 All OAuth Flows - Authorization Code, Client Credentials, Device Code
- 👥 Session Management - User session tracking with cleanup
§Advanced Features
TurboMCP supports resources and prompts alongside tools:
use turbomcp::prelude::*;
use std::sync::Arc;
#[derive(Clone)]
struct Calculator {
operations: Arc<std::sync::atomic::AtomicU64>,
}
#[server]
impl Calculator {
#[tool("Add numbers")]
async fn add(&self, a: i32, b: i32) -> McpResult<i32> {
Ok(a + b)
}
#[resource("calc://history")]
async fn history(&self, _uri: String) -> McpResult<String> {
Ok("Calculation history data".to_string())
}
#[prompt("Generate calculation report for {operation}")]
async fn calc_report(&self, operation: String) -> McpResult<String> {
Ok(format!("Report for {operation} operations"))
}
}§Feature-Gated Transports
Reduce binary size by selecting only the transports you need:
# Cargo.toml - TCP-only server (no STDIO)
[dependencies]
turbomcp = { version = "1.0", default-features = false, features = ["tcp"] }Available feature combinations:
minimal- Just STDIO (works everywhere)network- STDIO + TCPserver-only- TCP + Unix (no STDIO)all-transports- Maximum flexibility
For more examples and advanced usage, see the examples directory.
§Architecture
- MCP 2025-06-18 Specification - Full protocol compliance including elicitation
- Multi-Transport Support - STDIO, TCP, Unix, WebSocket, HTTP/SSE
- Bidirectional Communication - Server-initiated requests via elicitation and sampling
- Graceful Shutdown - Lifecycle management
- Zero-Overhead Macros - Ergonomic
#[server],#[tool],#[resource]attributes - Type Safety - Compile-time validation and automatic schema generation
- SIMD Acceleration - High-throughput JSON processing
Re-exports§
pub use crate::auth::SessionConfig as AuthSessionConfig;pub use crate::auth::ApiKeyProvider;pub use crate::auth::AuthConfig;pub use crate::auth::AuthContext;pub use crate::auth::AuthCredentials;pub use crate::auth::AuthManager;pub use crate::auth::AuthMiddleware;pub use crate::auth::AuthProvider;pub use crate::auth::AuthProviderConfig;pub use crate::auth::AuthProviderType;pub use crate::auth::OAuth2Config;pub use crate::auth::OAuth2FlowType;pub use crate::auth::OAuth2Provider;pub use crate::auth::TokenInfo;pub use crate::auth::UserInfo;pub use crate::context_factory::ContextCreationStrategy;pub use crate::context_factory::ContextFactory;pub use crate::context_factory::ContextFactoryConfig;pub use crate::context_factory::ContextFactoryProvider;pub use crate::context_factory::CorrelationId;pub use crate::context_factory::RequestScope;pub use crate::elicitation_api::ElicitationBuilder;pub use crate::elicitation_api::ElicitationData;pub use crate::elicitation_api::ElicitationExtract;pub use crate::elicitation_api::ElicitationManager;pub use crate::elicitation_api::ElicitationResult;pub use crate::elicitation_api::array;pub use crate::elicitation_api::boolean;pub use crate::elicitation_api::boolean_builder;pub use crate::elicitation_api::checkbox;pub use crate::elicitation_api::choices;pub use crate::elicitation_api::elicit;pub use crate::elicitation_api::enum_of;pub use crate::elicitation_api::integer;pub use crate::elicitation_api::integer_builder;pub use crate::elicitation_api::integer_field;pub use crate::elicitation_api::number;pub use crate::elicitation_api::number_builder;pub use crate::elicitation_api::number_field;pub use crate::elicitation_api::object;pub use crate::elicitation_api::options;pub use crate::elicitation_api::string;pub use crate::elicitation_api::string_builder;pub use crate::router::ToolRouter;pub use crate::router::ToolRouterExt;pub use inventory;pub use crate::context::*;pub use crate::elicitation::*;pub use crate::helpers::*;pub use crate::injection::*;pub use crate::lifespan::*;pub use crate::progress::*;pub use crate::registry::*;pub use crate::server::*;pub use crate::session::*;pub use crate::simd::*;pub use crate::sse_server::*;pub use crate::structured::*;pub use crate::transport::*;pub use crate::validation::*;
Modules§
- auth
- Authentication and Authorization system for
TurboMCPservers - context
- Context injection system with automatic dependency resolution
- context_
factory - Context Factory System
- elicitation
- Elicitation system for interactive user input in MCP tools
- elicitation_
api - Ergonomic Elicitation API for TurboMCP
- handlers
- Handler traits and implementations for MCP operations
- helpers
- Helper functions and utilities
- injection
- Advanced context injection system with type-based dependency injection
- lifespan
- Server lifespan management with startup/shutdown hooks
- prelude
- Convenient prelude for
TurboMCPapplications - progress
- Progress reporting and notification system
- registry
- Handler registration system using inventory for compile-time discovery
- router
TurboMCPTool Router - Ergonomic wrapper over mcp-server routing- schema
- Comprehensive JSON Schema generation and validation
- server
TurboMCPserver implementation- session
TurboMCPSession Management - Ergonomic wrapper over mcp-core state management- simd
- SIMD-Accelerated JSON Processing
- sse_
server - SSE Server Implementation
- structured
- Structured output support with automatic JSON schema generation
- transport
TurboMCPTransport Ergonomics- uri
- URI template matching and parameter extraction
- validation
- Parameter validation and schema generation system
Macros§
- elicit
- Ergonomic elicitation macro for server-initiated user input
- mcp_
error - Helper macro for creating MCP errors
- mcp_
text - Helper macro for creating MCP ContentBlock structures (advanced usage)
- tool_
result - Helper macro for creating CallToolResult structures (advanced usage)
- tool_
router - Ergonomic macro for creating tool routers
- transport
- Convenience macro for creating transports
Structs§
- Call
Tool Request - Call tool request
- Call
Tool Result - Call tool result
- Client
Capabilities - Client capabilities per MCP 2025-06-18 specification
- Context
- Context for
TurboMCPhandlers with dependency injection - GetPrompt
Result - Get prompt result
- Handler
Info - Handler registration information
- Handler
Metadata - Metadata about the current handler
- Image
Content - Image content per MCP 2025-06-18 specification
- Implementation
- Implementation information for MCP clients and servers
- Initialize
Request - Initialize request
- Initialize
Result - Initialize result
- Json
RpcError - JSON-RPC error object
- Json
RpcNotification - JSON-RPC notification message (no response expected)
- Json
RpcRequest - JSON-RPC request message
- Json
RpcResponse - JSON-RPC response message
- McpServer
- Main MCP server
- Prompt
Message - Prompt message
- Request
Context - Context information for request processing
- Resource
- Resource definition per MCP 2025-06-18 specification
- Server
- Main MCP server
- Server
Builder - Server builder for convenient server construction
- Server
Capabilities - Server capabilities per MCP 2025-06-18 specification
- Shutdown
Handle - Handle for triggering graceful server shutdown
- Text
Content - Text content per MCP 2025-06-18 specification
- Tool
- Tool definition per MCP 2025-06-18 specification
- Tool
Input Schema - Tool input schema definition
Enums§
- Handler
Type - Handler type enumeration
- McpError
TurboMCPerror type- Message
Id - Unique identifier for messages
- Server
Error - Comprehensive server error types
Traits§
- Handler
Registration - Helper trait for handler registration
- Turbo
McpServer - TurboMCP server trait for ergonomic server definition
Type Aliases§
- Content
- Compatibility alias for the old Content enum
- McpResult
TurboMCPresult type- Server
Result - Result type for server operations
Attribute Macros§
- async_
trait - completion
- Marks a method as a completion handler for argument autocompletion
- elicitation
- Marks a method as an elicitation handler for gathering user input
- ping
- Marks a method as a ping handler for connection health monitoring
- prompt
- Marks a method as a prompt handler
- resource
- Marks a method as a resource handler
- server
- Marks an impl block as a TurboMCP server (idiomatic Rust)
- template
- Marks a method as a resource template handler
- tool
- Marks a method as a tool handler