Enterprise-Ready MCP SDK

TurboMCP

Production-ready Rust SDK for the Model Context Protocol with progressive enhancement architecture, clean minimal core, and zero-cost abstractions. Build from minimal STDIO servers to enterprise-grade AI infrastructure with opt-in features.

2-3x
Faster JSON
5
Transport Options
Zero
Overhead Macros
v2.3.0
Current Version
MIT
License

Full MCP 2025-11-25 Specification

Complete protocol support including Tasks API, URL-mode elicitation, and tool calling in sampling.

✓ Complete
Tools
Full tool lifecycle with schema generation
✓ Complete
Resources
URI templates & subscriptions
✓ Complete
Prompts
Dynamic templates with parameters
✓ Complete
Sampling
Server-initiated LLM requests
✓ Complete
Completion
Intelligent autocompletion
✓ Complete
Elicitation
Form + URL mode elicitation
✓ Complete
Logging
Structured bidirectional logs
✓ Complete
Roots
Filesystem boundary configuration

Developer Experience First

Write production-ready MCP servers in minutes with ergonomic APIs, automatic schema generation, and OAuth 2.1 support.

Zero Boilerplate

Schemas auto-generated from function signatures

Type-Safe

Compile-time validation, runtime safety

Context Injection

Automatic dependency resolution

Error Ergonomics

McpError::invalid_request() helpers

Progressive Enhancement

Start minimal with STDIO only, opt-in to advanced features as needed. Clean separation of concerns.

Minimal by default
Opt-in features
Pay for what you use
stdio → http → websocket
Feature flags
Production patterns

Clean Minimal Core

Complete architectural overhaul with focused modules and zero technical debt.

10 specialized crates
Zero compiler warnings
Zero clippy warnings
Module decomposition
Clean code patterns
13 fewer dependencies

Security Hardening

Pre-release security audit with 2,900 lines of placeholder code removed and proper secret management.

1 mitigated vulnerability
CORS production-safe
No hardcoded secrets
Environment-based config
P-256 recommended
Honest codebase

Modular Architecture

Independent auth and DPoP crates for flexible security integration.

turbomcp-auth crate
turbomcp-dpop crate
OAuth 2.1 support
RFC 9449 DPoP
HSM integration
Progressive security

Performance Excellence

Zero-copy message processing with SIMD acceleration and optimized memory handling.

SIMD JSON parsing
Zero-copy patterns
Bytes integration
Lazy deserialization
sonic-rs & simd-json
Minimal allocations

Multi-Tenant SaaS

Enterprise multi-tenancy infrastructure with per-tenant configuration, metrics, and isolation.

TenantConfigProvider
Per-tenant rate limits
Tenant metrics w/ LRU
Header/subdomain extraction
Cross-tenant protection
Production examples

Modular Architecture

Clean, layered architecture with 10 specialized crates for maximum flexibility and maintainability.

turbomcp

Main SDK with ergonomic APIs

Procedural macros
Prelude module
Progressive features
turbomcp-protocol

Foundation with SIMD acceleration

Zero-copy messages
Security validation
Session management
turbomcp-transport

Multi-protocol transport layer

5 transport protocols
Circuit breakers
Graceful shutdown
turbomcp-server

Server framework

Handler registry
Middleware
Application-layer auth
turbomcp-client

MCP client (clean)

Connection mgmt
2,900 lines removed
Honest API
turbomcp-macros

Procedural macro definitions

Zero-overhead
Type-safe APIs
Compile-time schema
turbomcp-cli

Development tools

Server testing
Schema export
Debugging
turbomcp-auth

OAuth 2.1 authentication

Multi-provider
PKCE support
1,824 LOC
turbomcp-dpop

RFC 9449 DPoP tokens

Cryptographic proof
Multi-store
7,160 LOC

Zero Boilerplate, Maximum Power

Automatic schema generation from function signatures. Type-safe from compilation to runtime.

60-Second Quickstart
examples/hello_world.rs
The absolute simplest MCP server - 25 lines total
use turbomcp::prelude::*;

#[derive(Clone)]
struct HelloServer;

#[server(name = "hello", version = "1.0.0")]
impl HelloServer {
    #[tool("Say hello to someone")]
    async fn hello(&self, name: String) -> McpResult<String> {
        Ok(format!("Hello, {}!", name))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    HelloServer.run_stdio().await?;
    Ok(())
}

// That's it! Just 25 lines for a complete MCP server.
// JSON schemas automatically generated from function signatures.
Advanced: Resources & Prompts
examples/04_resources_and_prompts.rs
Full protocol support: Tools, Resources, Prompts, Roots
use turbomcp::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(Clone)]
struct KnowledgeServer {
    documents: Arc<RwLock<HashMap<String, String>>>,
}

#[server(
    name = "KnowledgeBase",
    version = "2.0.0",
    root = "file:///docs:Documentation"
)]
impl KnowledgeServer {
    #[tool("Store a document in the knowledge base")]
    async fn store_document(
        &self,
        ctx: Context,
        name: String,
        content: String,
    ) -> McpResult<String> {
        ctx.info(&format!("Storing document: {}", name)).await?;

        let mut docs = self.documents.write().await;
        docs.insert(name.clone(), content.clone());

        Ok(format!("Stored {} ({} chars)", name, content.len()))
    }

    #[resource("kb://docs/{name}")]
    async fn get_document(&self, name: String) -> McpResult<String> {
        let docs = self.documents.read().await;
        docs.get(&name)
            .cloned()
            .ok_or_else(|| mcp_error!("Document not found: {}", name))
    }

    #[prompt("Generate documentation")]
    async fn doc_prompt(
        &self,
        project_type: String,
        description: String,
    ) -> McpResult<String> {
        Ok(format!(
            "Generate comprehensive docs for {} project:\n{}",
            project_type, description
        ))
    }
}
Built-in Validation & Context
examples/03_basic_tools.rs
Comprehensive validation with ergonomic error handling
use turbomcp::prelude::*;

#[server(name = "SafeCalculator", version = "2.0.0")]
impl Calculator {
    #[tool("Safe division with validation")]
    async fn divide(
        &self,
        ctx: Context,
        dividend: f64,
        divisor: f64,
    ) -> McpResult<f64> {
        // Context provides logging and tracing
        ctx.info(&format!("Division: {} / {}", dividend, divisor))
            .await?;

        // Validation with helpful error messages
        if divisor == 0.0 {
            return Err(McpError::invalid_request(
                "Division by zero is not allowed"
            ));
        }

        if dividend.is_infinite() || divisor.is_infinite() {
            return Err(McpError::invalid_request(
                "Cannot divide infinite numbers"
            ));
        }

        Ok(dividend / divisor)
    }

    #[tool("Power with range validation")]
    async fn power(&self, base: f64, exponent: f64) -> McpResult<f64> {
        // Prevent extremely large calculations
        if !(-1000.0..=1000.0).contains(&exponent) {
            return Err(McpError::invalid_request(
                "Exponent too large (limit: ±1000)"
            ));
        }

        let result = base.powf(exponent);

        if result.is_infinite() || result.is_nan() {
            return Err(McpError::invalid_request(
                "Result is not a valid number"
            ));
        }

        Ok(result)
    }
}

Automatic Schema Generation

Function signatures become JSON schemas. No manual schema construction.

// f64 → {"type": "number"}
// String → {"type": "string"}
// Option<T> → optional param

Type-Safe Parameters

Deserialize directly to Rust types. Validation at compile time.

#[derive(Deserialize)]
struct Params {
  name: String,
  age: u32,
}

Context Injection

Automatic dependency injection. Logging, tracing, state management.

async fn tool(
  &self,
  ctx: Context,
  param: String
)

29 focused examples covering servers, clients, transports, and complete applications

Production-Ready in Minutes

From idea to deployed MCP server with working examples and best practices.

Step 1

Add Dependency

10 sec

turbomcp = "2.3"

Step 2

Copy Example

30 sec

29 focused examples

Step 3

Customize Tools

2 min

Add your logic

Step 4

Deploy & Test

1 min

Claude Desktop ready

Complete Example Portfolio

29 production-ready examples covering all transport protocols and features - minimal, focused, one concept per example

Transport Examples

13 examples
  • STDIO Server & Client
  • HTTP/SSE Server & Client
  • WebSocket Server & Client
  • TCP Server & Client
  • Unix Socket Server & Client
  • Transports Demo

Protocol Features

10 examples
  • Tools
  • Resources & Prompts
  • Elicitation Forms
  • Sampling Server
  • Structured Output
  • Resource Links
  • Validation
  • Rich Descriptions
  • Stateful Server
  • Context Injection

Complete Apps

6 examples
  • Hello World
  • Macro Server
  • STDIO App
  • HTTP App
  • Type-State Demo
  • Comprehensive Examples

TurboMCP 2.3 Philosophy: Comprehensive examples covering every transport protocol and protocol feature - zero bloat, one concept per example

Every example is production-ready, fully documented, and MCP 2025-11-25 compliant

Complete Protocol Coverage

Every MCP feature accessible through ergonomic macros with compile-time validation.

Attribute Macros #[...]

Procedural attribute macros for server definitions and method handlers.

#[server]

Server Definition

Define MCP servers with automatic trait implementations

#[server] impl MyServer { // methods }
#[tool]

Tool Handlers

Create tool endpoints with parameter validation

#[tool("Add numbers")] async fn add(&self, a: i32, b: i32) -> McpResult<i32>
#[resource]

Resource Providers

Handle resource requests with URI templating

#[resource("calc://history")] async fn history(&self, _uri: String) -> McpResult<String>
#[prompt]

Prompt Generators

Generate dynamic prompts for AI interactions

#[prompt("Generate a math problem")] async fn math_problem(&self) -> McpResult<String>
v2.3
#[dpop_secured]

DPoP Security (NEW)

RFC 9449 token binding with cryptographic proof

#[dpop_secured] #[tool("Secure operation")] async fn secure_op(&self) -> McpResult<String>
v2.3
CapabilityBuilder

Type-State Builder (NEW)

Compile-time safe capability configuration

let caps = CapabilityBuilder::new() .with_simd_hints() .enterprise_security() .build_const()
#[elicitation]

User Input

Request structured input from clients

#[elicitation("Get user prefs")] async fn get_prefs(&self, schema: Value) -> McpResult<Value>
#[completion]

Autocomplete

Provide intelligent completion suggestions

#[completion("Complete paths")] async fn complete(&self, partial: String) -> McpResult<Vec<String>>

Macro Invocations name!()

Helper macros for creating formatted content, errors, and responses.

v2.3
dpop_token!

DPoP Tokens (NEW)

Generate RFC 9449 cryptographically bound tokens

let token = dpop_token!( ctx, "https://api.example.com/resource", "GET" ).await?;
mcp_text!

Text Content Blocks

Create ContentBlock structures (often used with tool_result!)

// Standalone content creation let content = mcp_text!("Status: {}", status); // See tool_result! card for usage →
tool_result!

Tool Results (Advanced)

Create CallToolResult manually (usually auto-handled by #[tool])

// Single content block tool_result!(mcp_text!("Success")) // Multiple content blocks tool_result!(content = [text1, text2])
mcp_error!

Error Creation

Create MCP errors (use with Err(mcp_error!(...)))

return Err(mcp_error!("Failed: {}", reason));

Ready-to-Use Examples

Get started quickly with our comprehensive examples covering everything from basic servers to advanced use cases.

crates/turbomcp/examples/06_stateful_server.rs
Simple MCP server with STDIO transport
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, a: i32, b: i32) -> McpResult<i32> {
        self.operations.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Ok(a + b)
    }

    #[tool("Get server statistics")]
    async fn stats(&self) -> McpResult<String> {
        let ops = self.operations.load(std::sync::atomic::Ordering::Relaxed);
        Ok(format!("Operations performed: {}", ops))
    }
}

#[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(())
}

Run any example with cargo:

cargo run --example stateful

Performance Benchmarks

Optimized for fast processing with measurable performance improvements. Benchmarks conducted on consumer hardware (MacBook Pro M3, 32GB RAM).

2-3x Faster

JSON processing performance vs serde_json

Zero Copy

Memory-efficient message handling

SIMD

Hardware-accelerated processing

Low Latency

Optimized for real-time applications

Ready to Build with TurboMCP?

Start building fast MCP servers today with our comprehensive Rust SDK.

Production Deployment Patterns

Real-world examples demonstrating enterprise-ready deployment strategies and best practices.

Graceful Shutdown

Signal-based cleanup with proper resource management

  • SIGINT/SIGTERM handling
  • Resource cleanup
  • In-flight request completion
  • Health check integration
examples/transport_graceful_shutdown.rs

OAuth 2.1 Authentication

Multi-provider auth with Google, GitHub, Microsoft

  • PKCE support
  • Session management
  • Token refresh
  • Provider abstraction
examples/feature_oauth_authentication.rs

Multi-Transport Deployment

Runtime transport selection based on environment

  • STDIO for Claude Desktop
  • HTTP/SSE for web apps
  • TCP for services
  • Unix sockets for containers
examples/all_transports_demo.rs

Bidirectional Communication

Complete handler system with all 4 handler types

  • Elicitation requests
  • Progress tracking
  • Structured logging
  • Resource updates
examples/09_bidirectional_communication.rs