TurboMCP Protocol
Model Context Protocol (MCP) specification implementation with JSON-RPC 2.0 and runtime schema validation.
Table of Contents
- Overview
- Key Features
- Version Selection Guide
- Architecture
- MCP Message Types
- Usage
- Message Flow
- Feature Flags
- Supported MCP Methods
- Integration
Overview
turbomcp-protocol provides a specification-compliant implementation of the Model Context Protocol (MCP). This crate handles protocol-level concerns including message formatting, capability negotiation, and runtime validation.
MCP Version Support
TurboMCP supports multiple MCP specification versions through feature flags:
| Spec Version | Status | Feature Flag | Description |
|---|---|---|---|
| MCP 2025-06-18 | ✅ Stable | (default) | Current stable specification |
| MCP 2025-11-25 | 🚧 Draft | mcp-draft |
Draft specification with experimental features |
Quick Start:
# Stable (MCP 2025-06-18) - Production ready
[]
= "2.2"
# Draft (MCP 2025-11-25) - Experimental features
[]
= { = "2.2", = ["mcp-draft"] }
See Version Selection Guide for detailed guidance.
Key Features
MCP Specification Support
- MCP specification implementation with current message types
- Tools, resources, prompts, and capabilities support
- Capability negotiation with feature detection and handshake
- Version compatibility support
JSON-RPC 2.0 Implementation
- Compliant message format with request, response, and notification handling
- ID correlation for automatic request/response matching
- Standard JSON-RPC error codes and extensions
- Support for batch request/response operations
Runtime Schema Validation
- JSON Schema validation using
jsonschemacrate - Rust type definitions for MCP message types
- Tool and resource parameter validation
- Schema generation from Rust types
Capability Management
- Type-State Capability Builders - Compile-time validated capability configuration
- Server capabilities for tools, resources, prompts declarations
- Client capabilities including sampling, roots, progress reporting
- Feature negotiation with capability matching
- Support for custom capability extensions
MCP Enhanced Features
- Bidirectional communication for server-initiated requests to clients
- Elicitation support for server-requested structured input from users
- Completion context with references and metadata
- Resource templates for dynamic resource generation with parameters
- Ping/keepalive for connection health monitoring
Architecture
┌─────────────────────────────────────────────┐
│ TurboMCP Protocol │
├─────────────────────────────────────────────┤
│ MCP Message Types │
│ ├── InitializeRequest/InitializeResult │
│ ├── Tool/Resource/Prompt messages │
│ ├── Capability negotiation │
│ └── Notification handling │
├─────────────────────────────────────────────┤
│ JSON-RPC 2.0 Layer │
│ ├── Request/Response correlation │
│ ├── ID generation and tracking │
│ ├── Error code standardization │
│ └── Batch message processing │
├─────────────────────────────────────────────┤
│ Schema Validation │
│ ├── Runtime JSON schema validation │
│ ├── Parameter type checking │
│ ├── Response format validation │
│ └── Custom schema extension support │
└─────────────────────────────────────────────┘
MCP Message Types
Core Message Types
use ;
use ;
MCP Enhanced Types
use ;
use ;
JSON-RPC Infrastructure
use ;
Usage
Basic Protocol Handling
use ;
// Parse incoming JSON-RPC request
let json_data = r#"{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "test-client", "version": "2.0.0"}
}
}"#;
let request: JsonRpcRequest = from_str?;
// Handle specific message types
match request.method.as_str
Message Validation
use ;
// Create a validator with default rules
let validator = default;
// Parse and validate a JSON-RPC request
let json_data = r#"{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {"name": "add", "arguments": {"a": 5, "b": 3}}
}"#;
let request: JsonRpcRequest = from_str?;
let result = validator.validate_request;
match result
Type-State Capability Builders
use ;
// Compile-time validated server capabilities
let server_caps = new
.enable_tools // Enable tools capability
.enable_resources // Enable resources capability
.enable_prompts // Enable prompts capability
.enable_tool_list_changed // ✅ Only available when tools enabled
.enable_resources_subscribe // ✅ Only available when resources enabled
.enable_resources_list_changed // ✅ Only available when resources enabled
.build;
// Opt-out client capabilities (all enabled by default)
let client_caps = new
.enable_roots_list_changed // Configure sub-capabilities
.build; // All capabilities enabled!
// Opt-in pattern for restrictive clients
let minimal_client = minimal
.enable_sampling // Only enable what you need
.enable_roots
.build;
Traditional Capability Negotiation
use ;
// Traditional approach (still supported)
let server_caps = ServerCapabilities ;
// Define client capabilities
let client_caps = ClientCapabilities ;
Error Handling
The protocol crate provides Error, a rich MCP 2025-06-18 specification-compliant error type with comprehensive context and observability support.
Understanding Box<Error>
All error constructors return Box<Error> for important architectural reasons:
use Error;
// Constructors return Box<Error>, not Error
let err: = tool_not_found;
let err: = invalid_params;
Why Box<Error>?
- Cheap Cloning: Errors clone efficiently across async boundaries
- Rich Context Preservation: Full error chain, metadata, and backtrace
- Observability Integration: Seamless tracing and metrics
- Memory Efficiency: Error type is large (contains UUID, context, backtrace) - boxing keeps it off the stack
Creating Errors
use ;
// MCP specification errors (map to standard error codes)
let err = tool_not_found; // -32001
let err = tool_execution_failed; // -32002
let err = prompt_not_found; // -32003
let err = resource_not_found; // -32004
let err = resource_access_denied; // -32005
let err = invalid_params; // -32602
let err = user_rejected; // -1
// Add rich context with builder pattern
let err = internal
.with_operation
.with_component
.with_request_id
.with_context
.with_context;
// Error chaining for root cause analysis
let database_error = internal;
let app_error = unavailable
.with_source;
Working with JSON-RPC Errors
use ;
// Create JSON-RPC errors directly
// Convert protocol Error to JSON-RPC error code
let err = tool_not_found;
let code = err.jsonrpc_error_code; // -32001
let http = err.http_status_code; // 404
// Create Error from JSON-RPC error code (preserves semantics)
let err = rpc;
assert_eq!;
Error Properties
use Error;
let err = timeout;
// Check error characteristics
if err.is_retryable
if err.is_temporary
// Get HTTP status code for REST APIs
let status = err.http_status_code; // 408
// Get MCP-compliant JSON-RPC error code
let code = err.jsonrpc_error_code; // -32012
Integration with Application Layer
If you're using the main turbomcp crate, you typically use McpError in your tool handlers. The server layer automatically converts to Box<Error>:
// In your tool handler (turbomcp crate)
use ;
async
// Server layer converts to:
// ServerError::Protocol(Error::tool_execution_failed("my_tool", "Something failed"))
See the turbomcp crate error handling docs for the complete error architecture.
Custom Message Types
use ;
use ;
// Define custom message types
// Create custom JSON-RPC messages
Message Flow
sequenceDiagram
participant Client
participant Protocol as turbomcp-protocol
participant Server
Client->>Protocol: Raw JSON message
Protocol->>Protocol: Parse JSON-RPC
Protocol->>Protocol: Validate message format
Protocol->>Protocol: Extract MCP message
Protocol->>Protocol: Validate against schema
Protocol->>Server: Typed MCP message
Server->>Protocol: Typed MCP response
Protocol->>Protocol: Serialize response
Protocol->>Protocol: Wrap in JSON-RPC
Protocol->>Client: JSON response
Version Selection Guide
Choosing the Right MCP Version
Use MCP 2025-06-18 (Stable) when:
- Building production systems
- Need maximum interoperability with existing MCP clients/servers
- Require stable, well-tested protocol features
- Want long-term API stability guarantees
Use MCP 2025-11-25 (Draft) when:
- Experimenting with cutting-edge features
- Building systems that need advanced capabilities (multi-select forms, tasks API, etc.)
- Contributing to MCP specification development
- Willing to accept potential breaking changes in future releases
Feature-by-Feature Selection
Don't need all draft features? Enable specific ones:
[]
= { = "2.2", = [
"mcp-url-elicitation", # URL mode for OAuth/sensitive data
"mcp-sampling-tools", # Tool calling in LLM sampling
"mcp-icons", # Icon metadata for UI
"mcp-enum-improvements", # Standards-compliant enum schemas
] }
Runtime Version Negotiation
Client-side:
use ;
// Request draft features (server may downgrade)
let init = InitializeRequest ;
Server-side:
use ;
// Respond with actual supported version
let result = InitializeResult ;
Key Principle: Clients request, servers decide. The server's response version is the negotiated protocol version for the session.
Migration Path
Gradual Adoption:
- Start with stable 2025-06-18
- Add specific draft features as needed
- Test with
cfg(feature = "...")guards - Upgrade to full draft when stable
Example:
use URLElicitRequestParams;
// Fallback for stable clients
Feature Flags
Default Features
| Feature | Description | Default |
|---|---|---|
std |
Standard library support | ✅ |
simd |
SIMD-accelerated JSON parsing (simd-json, sonic-rs) | ✅ |
Performance Features
| Feature | Description | Default |
|---|---|---|
zero-copy |
Zero-copy message handling with serde serialization | ❌ |
messagepack |
MessagePack serialization support | ❌ |
mmap |
Memory-mapped file support | ❌ |
lock-free |
Lock-free data structures (experimental, requires unsafe) | ❌ |
Observability Features
| Feature | Description | Default |
|---|---|---|
tracing |
OpenTelemetry tracing integration | ❌ |
metrics |
Prometheus metrics collection | ❌ |
fancy-errors |
Rich error reporting with miette | ❌ |
Platform Features
| Feature | Description | Default |
|---|---|---|
wasm |
WebAssembly support (no_std compatible) | ❌ |
MCP 2025-11-25 Draft Specification Features
Meta-Feature (Enable All Draft Features)
| Feature | Description | Default |
|---|---|---|
mcp-draft |
Enable all MCP 2025-11-25 draft features | ❌ |
Equivalent to enabling all features below.
Individual Draft Features (SEP = Specification Enhancement Proposal)
| Feature | SEP | Description | Default |
|---|---|---|---|
mcp-tasks |
SEP-1686 | Experimental Tasks API for durable long-running requests | ❌ |
mcp-url-elicitation |
SEP-1036 | URL mode elicitation for OAuth/sensitive data | ❌ |
mcp-sampling-tools |
SEP-1577 | Tool calling support in LLM sampling requests | ❌ |
mcp-icons |
SEP-973 | Icon metadata for tools/resources/prompts | ❌ |
mcp-enum-improvements |
SEP-1330 | Standards-based enum schemas (oneOf, anyOf) | ❌ |
Authentication & Security Features (Auth-Related SEPs):
| Feature | Description | Specification |
|---|---|---|
| SSRF Protection | Built-in SSRF guards for URL validation | Always enabled |
| CIMD | Client ID Metadata Documents (OAuth 2.1) | Always enabled |
| OpenID Discovery | RFC 8414 + OIDC 1.0 discovery support | Always enabled |
| Incremental Consent | WWW-Authenticate with scope expansion (SEP-835) | Always enabled |
Note: Auth features are always enabled for maximum security - no feature flag required.
Feature Flag Examples
Minimal build (stable spec only):
[]
= { = "2.2", = false, = ["std"] }
High-performance build:
[]
= { = "2.2", = ["simd", "zero-copy", "lock-free"] }
Observable production build:
[]
= { = "2.2", = ["simd", "tracing", "metrics"] }
Full draft specification:
[]
= { = "2.2", = ["mcp-draft"] }
Selective draft features (recommended):
[]
= { = "2.2", = [
"mcp-url-elicitation", # Need OAuth support
"mcp-sampling-tools", # Need tool calling in sampling
"mcp-enum-improvements", # Want standards-compliant forms
] }
Supported MCP Methods
Core Methods
initialize- Protocol initialization and capability negotiationinitialized- Initialization completion notification
Tool Methods
tools/list- List available toolstools/call- Execute a tool with parameters
Resource Methods
resources/list- List available resourcesresources/read- Read resource contentresources/updated- Resource change notification
Prompt Methods
prompts/list- List available promptsprompts/get- Get prompt content
Capability Methods
capabilities/changed- Capability change notification
Integration
With TurboMCP Framework
Protocol handling is automatic when using the main framework:
use *;
Direct Protocol Usage
For custom implementations or integrations:
use ;
;
Development
Building
# Build with all features
# Build minimal (std only)
# Build with specific features
Testing
# Run protocol compliance tests
# Test with all features enabled
# Validate against MCP specification
Schema Validation
# Run validation tests
# Run message validation tests
Related Crates
- turbomcp - Main framework (uses this crate)
- turbomcp-transport - Transport layer
- turbomcp-server - Server framework
Note: In v2.0.0, turbomcp-core was merged into this crate to eliminate circular dependencies and improve cohesion.
External Resources
- MCP Specification - Official protocol specification
- JSON-RPC 2.0 - JSON-RPC specification
- JSON Schema - Schema validation specification
License
Licensed under the MIT License.
Part of the TurboMCP Rust SDK for the Model Context Protocol.