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 state;
96pub mod types;
97pub mod utils;
98pub mod zero_copy;
99
100#[cfg(feature = "fancy-errors")]
101pub mod config;
102
103// Re-export commonly used types
104pub use context::{
105    BidirectionalContext, ClientCapabilities, ClientId, ClientIdExtractor, ClientSession,
106    CommunicationDirection, CommunicationInitiator, CompletionCapabilities, CompletionContext,
107    CompletionOption, CompletionReference, ConnectionMetrics, ElicitationContext, ElicitationState,
108    PingContext, PingOrigin, RequestContext, RequestContextExt, RequestInfo,
109    ResourceTemplateContext, ResponseContext, ServerCapabilities, ServerInitiatedContext,
110    ServerInitiatedType, TemplateParameter,
111};
112pub use enhanced_registry::{EnhancedRegistry, HandlerStats};
113pub use error::{Error, ErrorKind, Result};
114pub use handlers::{
115    CompletionItem, CompletionProvider, ElicitationHandler, ElicitationResponse,
116    HandlerCapabilities, PingHandler, PingResponse, ResolvedResource, ResourceTemplate,
117    ResourceTemplateHandler, ServerInitiatedCapabilities, TemplateParam,
118};
119pub use message::{Message, MessageId, MessageMetadata};
120pub use session::{SessionAnalytics, SessionConfig, SessionManager};
121pub use state::StateManager;
122pub use types::{ContentType, ProtocolVersion, Timestamp};
123
124/// Alias for RequestContext for backward compatibility
125pub type Context = RequestContext;
126
127/// Current MCP protocol version supported by this SDK
128pub const PROTOCOL_VERSION: &str = "2025-06-18";
129
130/// Supported protocol versions for compatibility
131pub const SUPPORTED_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
132
133/// Maximum message size in bytes (16MB)
134pub const MAX_MESSAGE_SIZE: usize = 16 * 1024 * 1024;
135
136/// Default timeout for operations in milliseconds
137pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
138
139/// SDK version information
140pub const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
141
142/// SDK name identifier
143pub const SDK_NAME: &str = "turbomcp";
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn test_version_constants() {
151        // These constants are compile-time defined and should never be empty
152        assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
153    }
154
155    #[test]
156    fn test_size_constants() {
157        // Constants are statically verified at compile-time
158        // These tests document our design constraints
159
160        // Verify message size is reasonable for MCP protocol
161        const _: () = assert!(
162            MAX_MESSAGE_SIZE > 1024,
163            "MAX_MESSAGE_SIZE must be larger than 1KB"
164        );
165        const _: () = assert!(
166            MAX_MESSAGE_SIZE == 16 * 1024 * 1024,
167            "MAX_MESSAGE_SIZE must be 16MB"
168        );
169
170        // Verify timeout allows for reasonable operation completion
171        const _: () = assert!(
172            DEFAULT_TIMEOUT_MS > 1000,
173            "DEFAULT_TIMEOUT_MS must be larger than 1 second"
174        );
175        const _: () = assert!(
176            DEFAULT_TIMEOUT_MS == 30_000,
177            "DEFAULT_TIMEOUT_MS must be 30 seconds"
178        );
179    }
180}