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//! - **Server Capabilities** - Support for server-initiated requests (sampling, elicitation)
14//! - **Performance Optimized** - Memory-bounded state management with cleanup tasks
15//! - **Observability Ready** - Built-in support for tracing and metrics collection
16//!
17//! ## Architecture
18//!
19//! ```text
20//! turbomcp-core/
21//! ├── error/          # Error types and handling
22//! ├── message/        # Message types and serialization
23//! ├── types/          # Core protocol types
24//! ├── context/        # Request/response context with server capabilities
25//! ├── session/        # Session management
26//! ├── registry/       # Component registry
27//! ├── state/          # State management
28//! └── utils/          # Utility functions
29//! ```
30//!
31//! ## Server Capabilities
32//!
33//! The core provides a `ServerCapabilities` trait that enables server-initiated requests
34//! to clients, supporting bidirectional communication patterns like sampling and elicitation:
35//!
36//! ```rust,no_run
37//! use turbomcp_core::{RequestContext, ServerCapabilities};
38//!
39//! // Tools can access server capabilities through the context
40//! async fn my_tool(ctx: RequestContext) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
41//!     if let Some(capabilities) = ctx.server_capabilities() {
42//!         // Make a sampling request to the client
43//!         let request = serde_json::json!({
44//!             "messages": [{"role": "user", "content": "Hello"}],
45//!             "max_tokens": 100
46//!         });
47//!         let response = capabilities.create_message(request).await?;
48//!     }
49//!     Ok(())
50//! }
51//! ```
52//!
53//! ## Usage
54//!
55//! This crate provides the foundation types and utilities used by other `TurboMCP` crates.
56//! It is typically not used directly but imported by the main `turbomcp` SDK.
57
58#![warn(
59    missing_docs,
60    missing_debug_implementations,
61    rust_2018_idioms,
62    unreachable_pub,
63    clippy::all
64)]
65#![cfg_attr(
66    all(not(feature = "mmap"), not(feature = "lock-free")),
67    deny(unsafe_code)
68)]
69#![cfg_attr(docsrs, feature(doc_cfg))]
70#![allow(
71    clippy::module_name_repetitions,
72    clippy::missing_errors_doc,  // Error documentation in progress
73    clippy::cast_possible_truncation,  // Intentional in metrics/performance code
74    clippy::cast_possible_wrap,  // Intentional in metrics/performance code  
75    clippy::cast_precision_loss,  // Intentional for f64 metrics
76    clippy::cast_sign_loss,  // Intentional for metrics
77    clippy::must_use_candidate,  // Too pedantic for library APIs
78    clippy::return_self_not_must_use,  // Constructor methods don't need must_use
79    clippy::struct_excessive_bools,  // Sometimes bools are the right design
80    clippy::missing_panics_doc,  // Panic docs added where genuinely needed
81    clippy::default_trait_access,  // Default::default() is sometimes clearer
82    clippy::significant_drop_tightening,  // Overly pedantic about drop timing
83    clippy::used_underscore_binding  // Sometimes underscore bindings are needed
84)]
85
86pub mod context;
87pub mod enhanced_registry;
88pub mod error;
89pub mod error_utils;
90pub mod handlers;
91pub mod lock_free;
92pub mod message;
93pub mod registry;
94pub mod session;
95pub mod shared;
96pub mod state;
97pub mod types;
98pub mod utils;
99pub mod zero_copy;
100
101#[cfg(feature = "fancy-errors")]
102pub mod config;
103
104// Re-export commonly used types
105pub use context::{
106    BidirectionalContext, ClientCapabilities, ClientId, ClientIdExtractor, ClientSession,
107    CommunicationDirection, CommunicationInitiator, CompletionCapabilities, CompletionContext,
108    CompletionOption, CompletionReference, ConnectionMetrics, ElicitationContext, ElicitationState,
109    PingContext, PingOrigin, RequestContext, RequestContextExt, RequestInfo,
110    ResourceTemplateContext, ResponseContext, ServerCapabilities, ServerInitiatedContext,
111    ServerInitiatedType, TemplateParameter,
112};
113pub use enhanced_registry::{EnhancedRegistry, HandlerStats};
114pub use error::{Error, ErrorKind, Result};
115pub use handlers::{
116    CompletionItem, CompletionProvider, ElicitationHandler, ElicitationResponse,
117    HandlerCapabilities, PingHandler, PingResponse, ResolvedResource, ResourceTemplate,
118    ResourceTemplateHandler, ServerInitiatedCapabilities, TemplateParam,
119};
120pub use message::{Message, MessageId, MessageMetadata};
121pub use session::{SessionAnalytics, SessionConfig, SessionManager};
122pub use shared::{ConsumableShared, Shareable, Shared, SharedError};
123pub use state::StateManager;
124pub use types::{ContentType, ProtocolVersion, Timestamp};
125
126/// Alias for RequestContext for backward compatibility
127pub type Context = RequestContext;
128
129/// Current MCP protocol version supported by this SDK
130pub const PROTOCOL_VERSION: &str = "2025-06-18";
131
132/// Supported protocol versions for compatibility
133pub const SUPPORTED_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
134
135/// Maximum message size in bytes (1MB) - Reduced for security (DoS protection)
136pub const MAX_MESSAGE_SIZE: usize = 1024 * 1024;
137
138/// Default timeout for operations in milliseconds
139pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
140
141/// SDK version information
142pub const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
143
144/// SDK name identifier
145pub const SDK_NAME: &str = "turbomcp";
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn test_version_constants() {
153        // These constants are compile-time defined and should never be empty
154        assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
155    }
156
157    #[test]
158    fn test_size_constants() {
159        // Constants are statically verified at compile-time
160        // These tests document our design constraints
161
162        // Verify message size is reasonable for MCP protocol
163        const _: () = assert!(
164            MAX_MESSAGE_SIZE > 1024,
165            "MAX_MESSAGE_SIZE must be larger than 1KB"
166        );
167        const _: () = assert!(
168            MAX_MESSAGE_SIZE == 1024 * 1024,
169            "MAX_MESSAGE_SIZE must be 1MB for security"
170        );
171
172        // Verify timeout allows for reasonable operation completion
173        const _: () = assert!(
174            DEFAULT_TIMEOUT_MS > 1000,
175            "DEFAULT_TIMEOUT_MS must be larger than 1 second"
176        );
177        const _: () = assert!(
178            DEFAULT_TIMEOUT_MS == 30_000,
179            "DEFAULT_TIMEOUT_MS must be 30 seconds"
180        );
181    }
182}