TurboMCP Core
Core abstractions and utilities for the TurboMCP framework, providing foundational types, session management, and optimized message processing for Model Context Protocol implementations.
Overview
turbomcp-core
provides the essential building blocks for MCP implementations in Rust. It includes session management, request contexts, error handling, message types, and performance-optimized data structures.
Key Features
๐ JSON Processing with SIMD Support
- Optional SIMD acceleration with
simd-json
andsonic-rs
- Standard JSON processing with serde_json as fallback
- Bytes-based message handling for efficient memory usage
๐ฆ Optimized Data Structures
- Memory-efficient processing with careful allocation patterns
- SmallVec and CompactStr for small data optimization
- Thread-safe concurrent data structures
๐งต Session Management
- Concurrent session tracking with thread-safe state management
- Configurable session limits and cleanup policies
- Request correlation and tracing support
๐ฏ Error Handling
- Structured error types with context using
thiserror
- Error propagation with automatic conversion
- Debugging support with detailed error information
๐ Observability Integration
- Metrics hooks for performance monitoring
- Tracing integration for distributed observability
- Request correlation IDs for end-to-end tracking
๐ฏ Context Types
- ElicitationContext for server-initiated user input requests
- CompletionContext for autocompletion functionality
- PingContext for health monitoring and keepalive
- ResourceTemplateContext for dynamic resource generation
๐ Shareable Patterns for Async Concurrency
- Generic Shareable trait for thread-safe wrappers
- Shared wrapper with Arc/Mutex encapsulation
- ConsumableShared for one-time consumption patterns
- Flexible access patterns with closure-based APIs
Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TurboMCP Core โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Message Processing โ
โ โโโ JSON parsing with optional SIMD โ
โ โโโ Bytes-based message handling โ
โ โโโ Structured data types โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Session & Context Management โ
โ โโโ RequestContext lifecycle โ
โ โโโ Thread-safe session state โ
โ โโโ Correlation ID management โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Error Handling & Observability โ
โ โโโ Structured McpError types โ
โ โโโ Context preservation โ
โ โโโ Metrics & tracing hooks โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Components
Core Types
- Message parsing and serialization
- Request/response handling
- Context management for observability
Optimizations
- Optional SIMD acceleration for JSON processing
- Efficient memory allocation patterns
- Concurrent data structures for multi-threaded usage
- Small data optimization with SmallVec and CompactStr
Usage
Basic Usage
use ;
// Create a request context for correlation and observability
let mut context = new;
// Message parsing with optional SIMD acceleration
let json_data = br#"{"jsonrpc": "2.0", "method": "tools/list"}"#;
let message = parse?;
// Context provides rich observability and user information
context.info.await?;
// Context features for authentication and user information
if context.is_authenticated
Advanced Session Management
use ;
// Configure session management with LRU eviction
let config = new
.with_max_sessions
.with_ttl_seconds;
let session_manager = with_config;
// Sessions are automatically managed with efficient cleanup
let session = session_manager.create_session.await?;
Error Handling
use ;
SIMD Feature Flag
Enable SIMD acceleration for JSON processing:
[]
= { = "1.1.0", = ["simd"] }
Note: SIMD features require compatible CPU architectures (x86_64 with SSE2+ or ARM with NEON).
Feature Flags
Feature | Description | Default |
---|---|---|
simd |
Enable SIMD-accelerated JSON processing | โ |
metrics |
Enable built-in performance metrics | โ |
tracing |
Enable distributed tracing support | โ |
compression |
Enable message compression utilities | โ |
Integration
With TurboMCP Framework
turbomcp-core
is automatically included when using the main TurboMCP framework:
use *;
// Core functionality is available through the prelude
Direct Usage
For custom implementations or integrations:
use ;
Error Types
Core error types for comprehensive error handling:
use McpError;
match result
Shareable Patterns for Async Concurrency
TurboMCP Core provides abstractions for thread-safe sharing that form the foundation for SharedClient, SharedTransport, and SharedServer:
Generic Shareable Trait
The Shareable<T>
trait provides a consistent interface for creating thread-safe wrappers:
use ;
// Any type can implement Shareable
// Use with any type
let service = MyService ;
let shared = new; // Implements Shareable<MyService>
Shared - General Purpose Wrapper
The Shared<T>
wrapper provides closure-based access patterns for any type:
use Shared;
// Create shared wrapper
let db = new;
let shared_db = new;
// Read access with closures
let results = shared_db.with.await?;
// Mutable access with closures
let affected_rows = shared_db.with_mut.await?;
// Async closures also supported
let async_result = shared_db.with_async.await?;
ConsumableShared - One-Time Consumption Pattern
For types that need to be consumed (like servers), ConsumableShared<T>
provides safe extraction:
use ;
// Create consumable shared wrapper
let server = new;
let shared = new;
// Access before consumption
let status = shared.with.await?;
println!;
// Clone for monitoring while consuming
let monitor = shared.clone;
spawn;
// Consume the server (only possible once)
let server = shared.consume.await?;
server.run?; // Server is now running
Advanced Patterns
Custom Shared Implementations
Create domain-specific shared wrappers:
use Shareable;
use Arc;
use Mutex;
Error Handling Patterns
use ;
let shared_service = new;
// Handle potential errors in closures
let result = shared_service.with_mut.await;
match result
// Try operations without blocking
if let Some = shared_service.try_with else
Benefits
- Type Safety: Generic abstractions work with any type
- Flexible Access: Closure-based patterns for fine-grained control
- Zero Overhead: Same performance as manual Arc/Mutex usage
- Async Native: Built for async/await patterns
- Error Handling: Proper error propagation and handling
- Consumption Safety: Safe one-time consumption patterns
Design Principles
The Shareable patterns follow key design principles:
- Hide Complexity: Arc/Mutex details are encapsulated
- Preserve Semantics: Original type behavior is maintained
- Enable Sharing: Easy cloning for concurrent access
- Async First: Designed for async/await workflows
- Type Generic: Works with any Send + 'static type
Development
Building
# Build with all features
# Build optimized for production
Testing
# Run comprehensive tests
# Run performance benchmarks
# Test SIMD features (requires compatible CPU)
Related Crates
- turbomcp - Main framework (uses this crate)
- turbomcp-protocol - MCP protocol implementation
- turbomcp-transport - Transport layer
- turbomcp-server - Server framework
License
Licensed under the MIT License.
Part of the TurboMCP high-performance Rust SDK for the Model Context Protocol.