Crate turbomcp

Crate turbomcp 

Source
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-json and sonic-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

โ“˜
// 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:

[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() - Requires http feature
  • run_tcp() - Requires tcp feature
  • run_unix() - Requires unix 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::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;http
pub 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::*;http
pub 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 TurboMCP applications
registry
Handler registration system using inventory for compile-time discovery
router
TurboMCP Tool Router - Ergonomic wrapper over mcp-server routing
runtime
Runtime support for bidirectional MCP communication
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_serverhttp
SSE Server Implementation
structured
Structured output support with automatic JSON schema generation
transport
TurboMCP Transport Ergonomics
uriuri-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ยง

CallToolRequest
A request to execute a specific tool.
CallToolResult
The result of a CallToolRequest.
ClientCapabilities
Client capabilities per MCP 2025-11-25 specification
CompleteResult
Serverโ€™s response to a completion/complete request per MCP 2025-06-18 specification
CompletionResponse
Completion response
Context
Context for TurboMCP handlers with dependency injection
CreateMessageRequest
Create message request (for LLM sampling)
CreateMessageResult
Create message result
ElicitRequest
Elicit request wrapper
ElicitResult
Elicit result
GetPromptResult
Get prompt result
HandlerInfo
Handler registration information
HandlerMetadata
Metadata about the current handler
ImageContent
Image content per MCP 2025-06-18 specification
Implementation
Implementation information for MCP clients and servers
InitializeRequest
The initialize request is sent by the client as the first message after connection.
InitializeResult
The response to a successful initialize request.
JsonRpcError
JSON-RPC error object
JsonRpcNotification
JSON-RPC notification message (no response expected)
JsonRpcRequest
JSON-RPC request message
JsonRpcResponse
JSON-RPC response message
ListRootsResult
List roots result
McpServer
Main MCP server following the Axum/Tower Clone pattern
PingRequest
Ping request wrapper
PingResult
Ping result (echoes back the data)
ProtocolError
Comprehensive error type with rich context information
RequestContext
Context information for a single MCP request, carried through its entire lifecycle.
Resource
Resource definition per MCP 2025-06-18 specification
SamplingMessage
Sampling message structure
Server
Main MCP server following the Axum/Tower Clone pattern
ServerBuilder
Builder for constructing MCP servers with configuration and handlers
ServerCapabilities
Server capabilities per MCP 2025-11-25 specification
ShutdownHandle
Handle for triggering graceful server shutdown
TextContent
Text content per MCP 2025-06-18 specification
Tool
Represents a tool that can be executed by an MCP server
ToolInputSchema
Defines the structure of the arguments a tool accepts, as a JSON Schema object.

Enumsยง

ElicitationAction
Elicitation action taken by user
HandlerType
Handler type enumeration
McpError
TurboMCP error type
MessageId
Unique identifier for messages
ProtocolErrorKind
Error classification for programmatic handling
ServerError
Comprehensive server error types

Constantsยง

CRATE_NAME
TurboMCP crate name
VERSION
TurboMCP version from Cargo.toml

Traitsยง

HandlerRegistration
Helper trait for handler registration
McpErrorExt
Extension trait for convenient error conversion
TurboMcpServer
TurboMCP server trait for ergonomic server definition

Type Aliasesยง

Content
Backward compatibility alias for ContentBlock.
McpResult
TurboMCP result type
ProtocolResult
Result type alias for MCP operations
ServerResult
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