turbomcp_core/
lib.rs

1//! # TurboMCP Core
2//!
3//! Foundation crate for the Model Context Protocol (MCP) SDK providing core types,
4//! error handling, and optimized abstractions for building MCP applications.
5//!
6//! ## Features
7//!
8//! - **SIMD-Accelerated JSON** - Fast processing with `simd-json` and `sonic-rs`
9//! - **Rich Error Handling** - Comprehensive error types with context information
10//! - **Session Management** - Configurable LRU eviction and lifecycle management
11//! - **Zero-Copy Processing** - Memory-efficient message handling with `Bytes`
12//! - **Request Context** - Full request/response context tracking for observability
13//! - **Performance Optimized** - Memory-bounded state management with cleanup tasks
14//! - **Observability Ready** - Built-in support for tracing and metrics collection
15//!
16//! ## Architecture
17//!
18//! ```text
19//! turbomcp-core/
20//! ├── error/          # Error types and handling
21//! ├── message/        # Message types and serialization
22//! ├── types/          # Core protocol types
23//! ├── context/        # Request/response context
24//! ├── session/        # Session management
25//! ├── registry/       # Component registry
26//! ├── state/          # State management
27//! └── utils/          # Utility functions
28//! ```
29//!
30//! ## Usage
31//!
32//! This crate provides the foundation types and utilities used by other `TurboMCP` crates.
33//! It is typically not used directly but imported by the main `turbomcp` SDK.
34
35#![warn(
36    missing_docs,
37    missing_debug_implementations,
38    rust_2018_idioms,
39    unreachable_pub,
40    clippy::all
41)]
42#![cfg_attr(
43    all(not(feature = "mmap"), not(feature = "lock-free")),
44    deny(unsafe_code)
45)]
46#![cfg_attr(docsrs, feature(doc_cfg))]
47#![allow(
48    clippy::module_name_repetitions,
49    clippy::missing_errors_doc,  // Error documentation in progress
50    clippy::cast_possible_truncation,  // Intentional in metrics/performance code
51    clippy::cast_possible_wrap,  // Intentional in metrics/performance code  
52    clippy::cast_precision_loss,  // Intentional for f64 metrics
53    clippy::cast_sign_loss,  // Intentional for metrics
54    clippy::must_use_candidate,  // Too pedantic for library APIs
55    clippy::return_self_not_must_use,  // Constructor methods don't need must_use
56    clippy::struct_excessive_bools,  // Sometimes bools are the right design
57    clippy::missing_panics_doc,  // Panic docs added where genuinely needed
58    clippy::default_trait_access,  // Default::default() is sometimes clearer
59    clippy::significant_drop_tightening,  // Overly pedantic about drop timing
60    clippy::used_underscore_binding  // Sometimes underscore bindings are needed
61)]
62
63pub mod context;
64pub mod enhanced_registry;
65pub mod error;
66pub mod error_utils;
67pub mod handlers;
68pub mod lock_free;
69pub mod message;
70pub mod registry;
71pub mod session;
72pub mod state;
73pub mod types;
74pub mod utils;
75pub mod zero_copy;
76
77#[cfg(feature = "fancy-errors")]
78pub mod config;
79
80// Re-export commonly used types
81pub use context::{
82    BidirectionalContext, ClientCapabilities, ClientId, ClientIdExtractor, ClientSession,
83    CommunicationDirection, CommunicationInitiator, CompletionCapabilities, CompletionContext,
84    CompletionOption, CompletionReference, ConnectionMetrics, ElicitationContext, ElicitationState,
85    PingContext, PingOrigin, RequestContext, RequestContextExt, RequestInfo,
86    ResourceTemplateContext, ResponseContext, ServerInitiatedContext, ServerInitiatedType,
87    TemplateParameter,
88};
89pub use enhanced_registry::{EnhancedRegistry, HandlerStats};
90pub use error::{Error, ErrorKind, Result};
91pub use handlers::{
92    CompletionItem, CompletionProvider, ElicitationHandler, ElicitationResponse,
93    HandlerCapabilities, PingHandler, PingResponse, ResolvedResource, ResourceTemplate,
94    ResourceTemplateHandler, ServerInitiatedCapabilities, TemplateParam,
95};
96pub use message::{Message, MessageId, MessageMetadata};
97pub use session::{SessionAnalytics, SessionConfig, SessionManager};
98pub use state::StateManager;
99pub use types::{ContentType, ProtocolVersion, Timestamp};
100
101/// Current MCP protocol version supported by this SDK
102pub const PROTOCOL_VERSION: &str = "2025-06-18";
103
104/// Supported protocol versions for compatibility
105pub const SUPPORTED_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
106
107/// Maximum message size in bytes (16MB)
108pub const MAX_MESSAGE_SIZE: usize = 16 * 1024 * 1024;
109
110/// Default timeout for operations in milliseconds
111pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
112
113/// SDK version information
114pub const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
115
116/// SDK name identifier
117pub const SDK_NAME: &str = "turbomcp";
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn test_version_constants() {
125        // These constants are compile-time defined and should never be empty
126        assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
127    }
128
129    #[test]
130    fn test_size_constants() {
131        // Constants are statically verified at compile-time
132        // These tests document our design constraints
133
134        // Verify message size is reasonable for MCP protocol
135        const _: () = assert!(
136            MAX_MESSAGE_SIZE > 1024,
137            "MAX_MESSAGE_SIZE must be larger than 1KB"
138        );
139        const _: () = assert!(
140            MAX_MESSAGE_SIZE == 16 * 1024 * 1024,
141            "MAX_MESSAGE_SIZE must be 16MB"
142        );
143
144        // Verify timeout allows for reasonable operation completion
145        const _: () = assert!(
146            DEFAULT_TIMEOUT_MS > 1000,
147            "DEFAULT_TIMEOUT_MS must be larger than 1 second"
148        );
149        const _: () = assert!(
150            DEFAULT_TIMEOUT_MS == 30_000,
151            "DEFAULT_TIMEOUT_MS must be 30 seconds"
152        );
153    }
154}