Expand description
ยงTurboMCP - Model Context Protocol SDK
Rust SDK for the Model Context Protocol (MCP) with SIMD acceleration, resilient 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 builder pattern support
- 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.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
// Note: This example requires the `tcp` and `unix` features to compile
// cargo run --features "tcp,unix"
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") => {
// Requires "tcp" feature
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") => {
// Requires "unix" feature
let path = std::env::var("SOCKET_PATH")
.unwrap_or_else(|_| "/tmp/mcp.sock".to_string());
server.run_unix(path).await?;
}
_ => {
// Always available (default feature)
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
TurboMCP provides ergonomic elicitation with zero ceremony builders for intuitive APIs:
use turbomcp::prelude::*;
use turbomcp::elicitation_api::ElicitationResult;
use turbomcp_macros::elicit;
#[derive(Clone)]
struct ConfigServer;
#[server]
impl ConfigServer {
#[tool("Configure deployment")]
async fn deploy(&self, ctx: Context, project: String) -> McpResult<String> {
// Example elicitation for deployment configuration
// Note: Actual implementation depends on client capabilities
Ok(format!("Deployed {} to production", project))
}
}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
Server-initiated sampling requests enable bidirectional LLM communication:
use turbomcp::prelude::*;
use turbomcp_protocol::CreateMessageRequest;
#[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> {
// Example: Create a sampling request for AI analysis
// Note: Requires client with LLM capability
// Fallback to simple analysis
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 = "2.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 = "2.0", features = ["full"] }What you get: All transports, authentication features, full feature set
Perfect for: Production deployments, web applications, enterprise usage
Transports: HTTP/SSE, WebSocket, TCP, Unix, STDIO
ยงCustom Feature Selection
[dependencies]
turbomcp = {
version = "2.0",
default-features = false,
features = ["minimal", "http"]
}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()- Requireshttpfeaturerun_tcp()- Requirestcpfeaturerun_unix()- Requiresunixfeature (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::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::elicit;pub use crate::router::ToolRouter;pub use crate::router::ToolRouterExt;pub use axum;httppub use tokio;pub use uuid;pub use serde_json;pub use turbomcp_protocol;pub use turbomcp_server;pub use turbomcp_transport;pub use tracing;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::registry::*;pub use crate::server::*;pub use crate::session::*;pub use crate::simd::*;pub use crate::sse_server::*;httppub use crate::structured::*;pub use crate::transport::*;pub use crate::validation::*;
Modulesยง
- 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 - registry
- Handler registration system using inventory for compile-time discovery
- router
TurboMCPTool Router - Ergonomic wrapper over mcp-server routing- runtime
- Runtime support for bidirectional MCP communication
- 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 http - SSE Server Implementation
- structured
- Structured output support with automatic JSON schema generation
- transport
TurboMCPTransport Ergonomics- uri
uri-templates - URI template matching and parameter extraction
- validation
- Parameter Validation for TurboMCP
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 - A request to execute a specific tool.
- Call
Tool Result - The result of a
CallToolRequest. - Client
Capabilities - Client capabilities per MCP 2025-11-25 specification
- Complete
Result - Serverโs response to a completion/complete request per MCP 2025-06-18 specification
- Completion
Response - Completion response
- Context
- Context for
TurboMCPhandlers with dependency injection - Create
Message Request - Create message request (for LLM sampling)
- Create
Message Result - Create message result
- Elicit
Request - Elicit request wrapper
- Elicit
Result - Elicit result
- 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 - The
initializerequest is sent by the client as the first message after connection. - Initialize
Result - The response to a successful
initializerequest. - 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
- List
Roots Result - List roots result
- McpServer
- Main MCP server following the Axum/Tower Clone pattern
- Ping
Request - Ping request wrapper
- Ping
Result - Ping result (echoes back the data)
- Protocol
Error - Comprehensive error type with rich context information
- Request
Context - Context information for a single MCP request, carried through its entire lifecycle.
- Resource
- Resource definition per MCP 2025-06-18 specification
- Sampling
Message - Sampling message structure
- Server
- Main MCP server following the Axum/Tower Clone pattern
- Server
Builder - Builder for constructing MCP servers with configuration and handlers
- Server
Capabilities - Server capabilities per MCP 2025-11-25 specification
- Shutdown
Handle - Handle for triggering graceful server shutdown
- Text
Content - Text content per MCP 2025-06-18 specification
- Tool
- Represents a tool that can be executed by an MCP server
- Tool
Input Schema - Defines the structure of the arguments a tool accepts, as a JSON Schema object.
Enumsยง
- Elicitation
Action - Elicitation action taken by user
- Handler
Type - Handler type enumeration
- McpError
TurboMCPerror type- Message
Id - Unique identifier for messages
- Protocol
Error Kind - Error classification for programmatic handling
- Server
Error - Comprehensive server error types
Constantsยง
- CRATE_
NAME - TurboMCP crate name
- VERSION
- TurboMCP version from Cargo.toml
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
- Backward compatibility alias for
ContentBlock. - McpResult
TurboMCPresult type- Protocol
Result - Result type alias for MCP operations
- 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