turbomcp_protocol/lib.rs
1//! # TurboMCP Protocol
2//!
3//! Complete Model Context Protocol (MCP) implementation in Rust, providing all protocol types,
4//! traits, context management, and message handling for building MCP applications.
5//!
6//! ## MCP Version Support
7//!
8//! TurboMCP v3.0 fully implements MCP 2025-11-25 with all specification features enabled
9//! by default. No feature flags needed for core protocol capabilities.
10//!
11//! | Specification | Status | Notes |
12//! |---------------|--------|-------|
13//! | **MCP 2025-11-25** | ✅ Full Support | Canonical v3 protocol surface |
14//!
15//! **Quick Start:**
16//! ```toml
17//! turbomcp-protocol = "3.0"
18//! ```
19//!
20//! Only the experimental Tasks API (SEP-1686) requires a feature flag:
21//! ```toml
22//! turbomcp-protocol = { version = "3.0", features = ["experimental-tasks"] }
23//! ```
24//!
25//! ## What's Inside
26//!
27//! This crate provides everything needed for MCP:
28//!
29//! - **Types**: All MCP 2025-11-25 request/response types
30//! - **Traits**: `ServerToClientRequests` for bidirectional communication
31//! - **Context**: Request and response context management with full observability
32//! - **JSON-RPC**: JSON-RPC 2.0 implementation with batching and notifications
33//! - **Validation**: JSON Schema validation with comprehensive constraints
34//! - **Error Handling**: Rich error types with context and tracing
35//! - **Message Handling**: Optimized message processing with zero-copy support
36//! - **Session Management**: Configurable LRU eviction and lifecycle management
37//! - **Zero-Copy**: Optional zero-copy optimizations for high performance
38//!
39//! ## Features
40//!
41//! ### Core Protocol Support (MCP 2025-11-25)
42//! - Complete MCP 2025-11-25 protocol implementation
43//! - JSON-RPC 2.0 support with batching and notifications
44//! - Type-safe capability negotiation and compatibility checking
45//! - Strict exact-version protocol negotiation
46//! - Fast serialization with SIMD acceleration
47//!
48//! ### Advanced Protocol Features
49//! - **Elicitation Protocol** - Server-initiated user input requests with rich schema validation
50//! - **Sampling Support** - Bidirectional LLM sampling with fully-typed interfaces
51//! - **Roots Protocol** - Filesystem boundaries with `roots/list` support
52//! - **Server-to-Client Requests** - Fully typed trait for sampling, elicitation, and roots
53//! - **Comprehensive Schema Builders** - Type-safe builders for all schema types
54//!
55//! ### MCP 2025-11-25 Features (Always Enabled)
56//!
57//! All core MCP 2025-11-25 specification features are now always available:
58//!
59//! | Feature | SEP | Description |
60//! |---------|-----|-------------|
61//! | URL Elicitation | SEP-1036 | URL mode for OAuth/sensitive data collection |
62//! | Sampling Tools | SEP-1577 | Tool calling in LLM sampling requests |
63//! | Icons | SEP-973 | Icon metadata for tools, resources, prompts |
64//! | Enum Improvements | SEP-1330 | Standards-based JSON Schema enum patterns |
65//!
66//! **Experimental Feature (requires feature flag):**
67//! - `experimental-tasks` - Tasks API (SEP-1686) for long-running operations
68//!
69//! **Authentication & Security** (always enabled):
70//! - SSRF protection for URL validation
71//! - Client ID Metadata Documents (CIMD) for OAuth 2.1
72//! - OpenID Connect Discovery (RFC 8414 + OIDC 1.0)
73//! - Incremental consent with WWW-Authenticate (SEP-835)
74//!
75//! ### Performance & Observability
76//! - **SIMD-Accelerated JSON** - Fast processing with `simd-json` and `sonic-rs`
77//! - **Zero-Copy Processing** - Memory-efficient message handling with `Bytes`
78//! - **Request Context** - Full request/response context tracking for observability
79//! - **Session Management** - Memory-bounded state management with cleanup tasks
80//! - **Observability Ready** - Built-in support for tracing and metrics collection
81//!
82//! ## Version Selection
83//!
84//! TurboMCP v3.0 targets MCP 2025-11-25 only. Runtime negotiation is exact-match:
85//! clients and servers must agree on the current protocol version.
86//!
87//! **Typical Usage:**
88//! ```toml
89//! [dependencies]
90//! turbomcp-protocol = "3.0" # All core features included
91//! ```
92//!
93//! **With Experimental Tasks API:**
94//! ```toml
95//! [dependencies]
96//! turbomcp-protocol = { version = "3.0", features = ["experimental-tasks"] }
97//! ```
98//!
99//! ### Runtime Version Negotiation
100//!
101//! Clients and servers negotiate protocol versions during initialization:
102//!
103//! ```rust,no_run
104//! use turbomcp_protocol::{InitializeRequest, InitializeResult, ClientCapabilities};
105//! use turbomcp_protocol::types::{Implementation, ServerCapabilities}; // Corrected import path
106//!
107//! // Client requests the current protocol version
108//! let request = InitializeRequest {
109//! protocol_version: "2025-11-25".into(), // Request draft
110//! capabilities: ClientCapabilities::default(),
111//! client_info: Implementation {
112//! name: "my-client".to_string(),
113//! title: None,
114//! version: "1.0.0".to_string(),
115//! ..Default::default()
116//! },
117//! _meta: None,
118//! };
119//!
120//! // Server responds with the same supported version
121//! let response = InitializeResult {
122//! protocol_version: "2025-11-25".into(),
123//! capabilities: ServerCapabilities::default(),
124//! server_info: Implementation {
125//! name: "my-server".to_string(),
126//! title: None,
127//! version: "1.0.0".to_string(),
128//! ..Default::default()
129//! },
130//! instructions: None,
131//! _meta: None,
132//! };
133//! ```
134//!
135//! **Key Principle:** clients request the current protocol version, and servers
136//! must either accept it exactly or fail initialization.
137//!
138//! ## Architecture
139//!
140//! ```text
141//! turbomcp-protocol/
142//! ├── error/ # Error types and handling
143//! ├── message/ # Message types and serialization
144//! ├── context/ # Request/response context with server capabilities
145//! ├── types/ # MCP protocol types
146//! ├── jsonrpc/ # JSON-RPC 2.0 implementation
147//! ├── validation/ # Schema validation
148//! ├── session/ # Session management
149//! ├── registry/ # Component registry
150//! └── utils/ # Utility functions
151//! ```
152//!
153//! ## Server-to-Client Communication
154//!
155//! The protocol provides a `ServerToClientRequests` trait that enables server-initiated requests
156//! to clients, supporting bidirectional communication patterns like sampling and elicitation:
157//!
158//! ```rust,no_run
159//! use turbomcp_protocol::{RequestContext, types::CreateMessageRequest, ServerToClientRequests};
160//!
161//! // Tools can access server capabilities through the context
162//! async fn my_tool(ctx: RequestContext) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
163//! if let Some(capabilities) = ctx.clone().server_to_client() {
164//! // Make a fully-typed sampling request to the client
165//! let request = CreateMessageRequest {
166//! messages: vec![/* ... */],
167//! max_tokens: 100,
168//! model_preferences: None,
169//! system_prompt: None,
170//! include_context: None,
171//! temperature: None,
172//! stop_sequences: None,
173//! task: None,
174//! tools: None,
175//! tool_choice: None,
176//! _meta: None,
177//! };
178//! let response = capabilities.create_message(request, ctx).await?;
179//! }
180//! Ok(())
181//! }
182//! ```
183
184#![warn(
185 missing_docs,
186 missing_debug_implementations,
187 rust_2018_idioms,
188 unreachable_pub,
189 clippy::all
190)]
191#![cfg_attr(
192 all(not(feature = "mmap"), not(feature = "lock-free")),
193 deny(unsafe_code)
194)]
195#![cfg_attr(docsrs, feature(doc_cfg))]
196#![allow(
197 clippy::module_name_repetitions,
198 clippy::cast_possible_truncation, // Intentional in metrics/performance code
199 clippy::cast_possible_wrap, // Intentional in metrics/performance code
200 clippy::cast_precision_loss, // Intentional for f64 metrics
201 clippy::cast_sign_loss, // Intentional for metrics
202 clippy::must_use_candidate, // Too pedantic for library APIs
203 clippy::return_self_not_must_use, // Constructor methods don't need must_use
204 clippy::struct_excessive_bools, // Sometimes bools are the right design
205 clippy::missing_panics_doc, // Panic docs added where genuinely needed
206 clippy::default_trait_access, // Default::default() is sometimes clearer
207 clippy::significant_drop_tightening, // Overly pedantic about drop timing
208 clippy::used_underscore_binding, // Sometimes underscore bindings are needed
209 clippy::wildcard_imports // Used in test modules
210)]
211
212// v3.0: Re-export turbomcp-core foundation types
213/// Re-export of turbomcp-core, the no_std foundation layer
214pub use turbomcp_core as mcp_core;
215
216// v3.0: McpError is THE error type - re-export at crate root
217pub use turbomcp_core::error::{ErrorContext as McpErrorContext, ErrorKind, McpError, McpResult};
218/// v3.0 Result alias using McpError
219pub type Result<T> = McpResult<T>;
220/// v3.0 Error alias for migration (prefer McpError directly)
221pub type Error = McpError;
222
223// v3.0: Unified handler response types from core
224// These enable the IntoToolResponse pattern for ergonomic tool handlers
225pub use turbomcp_core::response::{Image, IntoToolError, IntoToolResponse, Json, Text, ToolError};
226
227// Core abstractions (merged from turbomcp-core in v2.0.0)
228/// Configuration for protocol components.
229pub mod config;
230/// Request/response context, including server-to-client capabilities.
231pub mod context;
232/// An advanced handler registry with metrics and enhanced features.
233pub mod enhanced_registry;
234/// Error types and handling for the protocol.
235pub mod error;
236/// Utilities for creating and working with protocol errors.
237pub mod error_utils;
238/// Traits and types for handling different MCP requests (tools, prompts, etc.).
239pub mod handlers;
240/// Lock-free data structures for high-performance concurrent scenarios.
241#[cfg(feature = "lock-free")]
242pub mod lock_free;
243/// Core message types and serialization logic.
244pub mod message;
245/// Basic handler registration and lookup.
246pub mod registry;
247/// Security-related utilities, such as path validation.
248pub mod security;
249/// Session management for client connections.
250pub mod session;
251/// Utilities for shared, concurrent state management.
252pub mod shared;
253/// State management for the protocol.
254pub mod state;
255/// General utility functions.
256pub mod utils;
257/// Zero-copy data handling utilities for performance-critical operations.
258pub mod zero_copy;
259
260/// Zero-copy rkyv bridge for internal message routing.
261///
262/// This module is only available when the `rkyv` feature is enabled.
263/// It provides efficient conversion between JSON-RPC and rkyv internal formats.
264#[cfg(feature = "rkyv")]
265#[cfg_attr(docsrs, doc(cfg(feature = "rkyv")))]
266pub mod rkyv_bridge;
267
268/// Wire codec integration for message serialization.
269///
270/// This module provides a unified interface for encoding/decoding MCP messages
271/// using the [`turbomcp_wire`] codec abstraction.
272///
273/// Enable with the `wire` feature flag. Optional SIMD acceleration available
274/// with `wire-simd`, and MessagePack support with `wire-msgpack`.
275#[cfg(feature = "wire")]
276#[cfg_attr(docsrs, doc(cfg(feature = "wire")))]
277pub mod codec;
278
279// Protocol-specific modules
280/// Capability negotiation and management.
281pub mod capabilities;
282// Old elicitation module removed; use types::elicitation instead.
283/// JSON-RPC 2.0 protocol implementation.
284pub mod jsonrpc;
285/// All MCP protocol types (requests, responses, and data structures).
286pub mod types;
287/// Schema validation for protocol messages.
288pub mod validation;
289/// Protocol version management and compatibility checking.
290pub mod versioning;
291
292// Test utilities (public to allow downstream crates to use them in tests)
293// Following the pattern from axum and tokio
294/// Public test utilities for use in downstream crates.
295pub mod test_helpers;
296
297// Re-export core types
298pub use context::{
299 BidirectionalContext, ClientCapabilities as ContextClientCapabilities, ClientId,
300 ClientIdExtractor, ClientSession, CommunicationDirection, CommunicationInitiator,
301 CompletionCapabilities, CompletionContext, CompletionOption,
302 CompletionReference as ContextCompletionReference, ConnectionMetrics, ElicitationContext,
303 ElicitationState, PingContext, PingOrigin, RequestContext, RequestContextExt, RequestInfo,
304 ResourceTemplateContext, ResponseContext, RichContextExt, ServerInitiatedContext,
305 ServerInitiatedType, ServerToClientRequests, SessionStateGuard, StateError, TemplateParameter,
306 active_sessions_count, cleanup_session_state,
307};
308// Timestamp and ContentType are now in types module
309pub use enhanced_registry::{EnhancedRegistry, HandlerStats};
310// v3.0: McpError is re-exported from turbomcp_core at crate root
311pub use error::RetryInfo;
312pub use handlers::{
313 CompletionItem, CompletionProvider, ElicitationHandler, ElicitationResponse,
314 HandlerCapabilities, JsonRpcHandler, PingHandler, PingResponse, ResolvedResource,
315 ResourceTemplate as HandlerResourceTemplate, ResourceTemplateHandler, ServerInfo,
316 ServerInitiatedCapabilities, TemplateParam,
317};
318pub use message::{Message, MessageId, MessageMetadata};
319pub use registry::RegistryError;
320pub use security::{validate_file_extension, validate_path, validate_path_within};
321pub use session::{SessionAnalytics, SessionConfig, SessionManager};
322pub use shared::{ConsumableShared, Shareable, Shared, SharedError};
323pub use state::StateManager;
324
325// Re-export ONLY essential types at root (v2.0 - improved ergonomics)
326// Everything else requires module qualification: turbomcp_protocol::types::*
327pub use types::{
328 // Most common tool operations
329 CallToolRequest,
330 CallToolResult,
331
332 ClientCapabilities,
333 // Macro API types (used by generated code - not typically imported by users)
334 GetPromptRequest,
335 GetPromptResult,
336 // Most common request/response pairs (initialization flow)
337 InitializeRequest,
338 InitializeResult,
339
340 ReadResourceRequest,
341 ReadResourceResult,
342
343 // Capability negotiation (used in every initialize)
344 ServerCapabilities,
345};
346
347// Note: types module is already declared as `pub mod types;` above
348// Users access other types via turbomcp_protocol::types::Tool, etc.
349
350pub use jsonrpc::{
351 JsonRpcError, JsonRpcErrorCode, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse,
352 JsonRpcVersion,
353};
354
355pub use capabilities::{
356 CapabilityMatcher, CapabilityNegotiator, CapabilitySet,
357 builders::{
358 ClientCapabilitiesBuilder, ClientCapabilitiesBuilderState, ServerCapabilitiesBuilder,
359 ServerCapabilitiesBuilderState,
360 },
361};
362
363pub use versioning::{VersionCompatibility, VersionManager, VersionRequirement};
364
365// Re-export constants from core (single source of truth - DRY)
366pub use turbomcp_core::{
367 DEFAULT_TIMEOUT_MS, MAX_MESSAGE_SIZE, PROTOCOL_VERSION, SDK_NAME, SDK_VERSION,
368 SUPPORTED_VERSIONS, error_codes, features, methods,
369};
370
371#[cfg(test)]
372mod tests {
373 use super::*;
374
375 #[test]
376 fn test_version_constants() {
377 assert_eq!(PROTOCOL_VERSION, "2025-11-25");
378 assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
379 // Latest should be first in supported versions
380 assert_eq!(SUPPORTED_VERSIONS[0], PROTOCOL_VERSION);
381 }
382
383 #[test]
384 fn test_size_constants() {
385 // Constants are statically verified at compile-time
386 const _: () = assert!(
387 MAX_MESSAGE_SIZE > 1024,
388 "MAX_MESSAGE_SIZE must be larger than 1KB"
389 );
390 const _: () = assert!(
391 MAX_MESSAGE_SIZE == 1024 * 1024,
392 "MAX_MESSAGE_SIZE must be 1MB for security"
393 );
394
395 const _: () = assert!(
396 DEFAULT_TIMEOUT_MS > 1000,
397 "DEFAULT_TIMEOUT_MS must be larger than 1 second"
398 );
399 const _: () = assert!(
400 DEFAULT_TIMEOUT_MS == 30_000,
401 "DEFAULT_TIMEOUT_MS must be 30 seconds"
402 );
403 }
404
405 #[test]
406 fn test_method_names() {
407 assert_eq!(methods::INITIALIZE, "initialize");
408 assert_eq!(methods::LIST_TOOLS, "tools/list");
409 assert_eq!(methods::CALL_TOOL, "tools/call");
410 }
411
412 #[test]
413 fn test_error_codes() {
414 assert_eq!(error_codes::PARSE_ERROR, -32700);
415 assert_eq!(error_codes::TOOL_NOT_FOUND, -32001);
416 }
417}