TurboMCP Protocol
Model Context Protocol (MCP) specification implementation with JSON-RPC 2.0 and runtime schema validation.
Table of Contents
- Overview
- Key Features
- 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.
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
Feature Flags
| Feature | Description | Default |
|---|---|---|
simd |
SIMD-accelerated JSON parsing (simd-json, sonic-rs) | ✅ |
std |
Standard library support (always enabled with no-std support via wasm feature) | ✅ |
zero-copy |
Zero-copy message handling with serde serialization | ❌ |
messagepack |
MessagePack serialization support | ❌ |
tracing |
OpenTelemetry tracing integration | ❌ |
metrics |
Prometheus metrics collection | ❌ |
mmap |
Memory-mapped file support | ❌ |
lock-free |
Lock-free data structures (experimental, requires unsafe) | ❌ |
fancy-errors |
Rich error reporting with miette | ❌ |
wasm |
WebAssembly support (no_std compatible) | ❌ |
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 (no validation)
Testing
# Run protocol compliance tests
# Test with all message types
# Validate against MCP specification
Schema Validation
# Generate JSON schemas from Rust types
# Validate example messages
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.