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-json
andsonic-rs
for 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.1 MCP Compliance - RFC 8707/9728/7591 compliant with MCP resource binding
- Multi-Provider OAuth - Google, GitHub, Microsoft with PKCE and security hardening
- Security Headers - CORS, CSP, HSTS protection with redirect attack prevention
- Rate Limiting - Token bucket algorithm with configurable strategies
- Middleware Stack - Authentication, logging, security headers
ยงQuick Start
use turbomcp::prelude::*;
#[derive(Clone)]
struct Calculator;
#[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?;
Ok(a + b)
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let server = Calculator;
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").into())
}
}
}
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 Selection Guide
Choose the right feature set for your use case to minimize dependencies:
ยงFor Basic Tool Servers (Recommended for Beginners)
[dependencies]
turbomcp = { version = "1.0", default-features = false, features = ["minimal"] }
What you get: STDIO transport, core macros, basic error handling
Perfect for: Simple MCP tools, CLI integrations, getting started
Transport: server.run_stdio().await
ยงFor Production Web Servers
[dependencies]
turbomcp = { version = "1.0", features = ["full"] }
What you get: All transports, authentication, databases, full feature set
Perfect for: Production deployments, web applications, enterprise usage
Transports: HTTP/SSE, WebSocket, TCP, Unix, STDIO
ยงCustom Feature Selection
[dependencies]
turbomcp = {
version = "1.0",
default-features = false,
features = ["minimal", "http", "schema-generation"]
}
Mix and match: Start with minimal
and add only what you need
Available feature combinations:
minimal
- Just STDIO (works everywhere, ๐ฆ smallest footprint)network
- STDIO + TCP (network deployment ready)server-only
- TCP + Unix (headless servers, no STDIO)full
- Everything included (โก maximum functionality)
For more examples and advanced usage, see the examples directory.
ยง๐ Generated Methods Reference
The #[server]
macro generates several key methods for your server implementation:
ยงTransport Methods
The macro automatically generates transport methods that let you run your server over different protocols. All transport changes are one-line swaps:
// Each transport method consumes the server, so choose one:
// STDIO (standard MCP transport)
MyServer.run_stdio().await?;
// Or HTTP with Server-Sent Events (web-compatible)
// MyServer.run_http("127.0.0.1:8080").await?;
// MyServer.run_http_with_path("0.0.0.0:3000", "/api/mcp").await?;
// Or TCP sockets (high-performance)
// MyServer.run_tcp("127.0.0.1:9000").await?;
// Or Unix domain sockets (local IPC)
// MyServer.run_unix("/tmp/mcp.sock").await?;
ยงMetadata and Testing Methods
// Get server information (name, version, description)
let (name, version, description) = MyServer::server_info();
// Get tool metadata for testing and introspection
let metadata = MyServer::__turbomcp_tool_metadata_test();
// Test tool handlers directly (bypasses transport layer)
use turbomcp::CallToolRequest;
let server = MyServer;
let request = CallToolRequest {
name: "test".to_string(),
arguments: None
};
let result = server.__turbomcp_tool_handler_test(request, Default::default()).await;
ยงHandler Registration
The macro implements the HandlerRegistration
trait automatically:
use turbomcp::{HandlerRegistration, ServerBuilder};
let server = MyServer;
let mut builder = ServerBuilder::new();
// All #[tool], #[resource], and #[prompt] methods are registered automatically
server.register_handlers(&mut builder).unwrap();
ยงFeature-Gated Methods
Some methods are only available when the corresponding features are enabled:
run_http()
,run_http_with_path()
- Requireshttp
featurerun_tcp()
- Requirestcp
featurerun_unix()
- Requiresunix
feature (Unix systems only)
ยงContext Injection
The macro automatically detects Context
parameters and injects them properly:
#[tool("Context can appear anywhere in parameters")]
async fn flexible_context(&self, name: String, ctx: Context, age: u32) -> McpResult<String> {
ctx.info("Context works at any position").await?;
Ok(format!("Hello {} ({})", name, age))
}
#[tool("Context is optional")]
async fn no_context(&self, message: String) -> McpResult<String> {
Ok(format!("Received: {}", message))
}
This generates the correct handler functions that extract parameters and inject context appropriately.
ยง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
TurboMCP
servers - 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
TurboMCP
applications - progress
- Progress reporting and notification system
- registry
- Handler registration system using inventory for compile-time discovery
- router
TurboMCP
Tool Router - Ergonomic wrapper over mcp-server routing- schema
- Comprehensive JSON Schema generation and validation
- server
TurboMCP
server implementation- session
TurboMCP
Session 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
TurboMCP
Transport 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
- Complete
Request - Request for argument completion
- Complete
Result - Serverโs response to a completion request
- Completion
Response - Completion response information
- Context
- Context for
TurboMCP
handlers with dependency injection - Elicit
Request - Request to elicit user input (server-initiated)
- Elicit
Result - Clientโs response to an elicitation request
- 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
- Ping
Request - A ping request to check connection health
- Ping
Result - Response to a ping request (usually empty)
- 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ยง
- Elicitation
Action - Action taken by user in response to elicitation
- Handler
Type - Handler type enumeration
- McpError
TurboMCP
error type- Message
Id - Unique identifier for messages
- Server
Error - Comprehensive server error types
Traitsยง
- Handler
Registration - Helper trait for handler registration
- McpError
Ext - Extension trait for convenient error conversion
- Turbo
McpServer - TurboMCP server trait for ergonomic server definition
Type Aliasesยง
- Content
- Compatibility alias for the old Content enum
- McpResult
TurboMCP
result 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