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
- MCP 2025-06-18 Specification - Full compliance with latest protocol
- SIMD-Accelerated JSON -
simd-json
andsonic-rs
for fast processing - Multi-Transport - STDIO, TCP, Unix sockets with runtime selection
- Robust - Circuit breakers, retry logic, graceful shutdown
- Zero-Overhead Macros - Ergonomic
#[server]
,#[tool]
,#[resource]
attributes - Context Injection - Dependency injection and observability
- Type Safety - Compile-time validation with automatic schema generation
§Quick Start
use turbomcp::prelude::*;
#[derive(Clone)]
struct Calculator {
operations: std::sync::Arc<std::sync::atomic::AtomicU64>,
}
#[server]
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)
}
}
§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
- Multi-Transport Support - STDIO, TCP, Unix sockets with runtime selection
- 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::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
- 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§
- 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
TurboMCP
handlers 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
TurboMCP
error 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
TurboMCP
result type- Server
Result - Result type for server operations
Attribute Macros§
- async_
trait - 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)
- tool
- Marks a method as a tool handler