turbomcp-protocol 3.1.3

Complete MCP protocol implementation with types, traits, context management, and message handling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! # TurboMCP Protocol
//!
//! Complete Model Context Protocol (MCP) implementation in Rust, providing all protocol types,
//! traits, context management, and message handling for building MCP applications.
//!
//! ## MCP Version Support
//!
//! TurboMCP v3.0 fully implements MCP 2025-11-25 with all specification features enabled
//! by default. No feature flags needed for core protocol capabilities.
//!
//! | Specification | Status | Notes |
//! |---------------|--------|-------|
//! | **MCP 2025-11-25** | ✅ Full Support | Canonical v3 protocol surface |
//!
//! **Quick Start:**
//! ```toml
//! turbomcp-protocol = "3.0"
//! ```
//!
//! Only the experimental Tasks API (SEP-1686) requires a feature flag:
//! ```toml
//! turbomcp-protocol = { version = "3.0", features = ["experimental-tasks"] }
//! ```
//!
//! ## What's Inside
//!
//! This crate provides everything needed for MCP:
//!
//! - **Types**: All MCP 2025-11-25 request/response types
//! - **Traits**: `ServerToClientRequests` for bidirectional communication
//! - **Context**: Request and response context management with full observability
//! - **JSON-RPC**: JSON-RPC 2.0 implementation with batching and notifications
//! - **Validation**: JSON Schema validation with comprehensive constraints
//! - **Error Handling**: Rich error types with context and tracing
//! - **Message Handling**: Optimized message processing with zero-copy support
//! - **Session Management**: Configurable LRU eviction and lifecycle management
//! - **Zero-Copy**: Optional zero-copy optimizations for high performance
//!
//! ## Features
//!
//! ### Core Protocol Support (MCP 2025-11-25)
//! - Complete MCP 2025-11-25 protocol implementation
//! - JSON-RPC 2.0 support with batching and notifications
//! - Type-safe capability negotiation and compatibility checking
//! - Strict exact-version protocol negotiation
//! - Fast serialization with SIMD acceleration
//!
//! ### Advanced Protocol Features
//! - **Elicitation Protocol** - Server-initiated user input requests with rich schema validation
//! - **Sampling Support** - Bidirectional LLM sampling with fully-typed interfaces
//! - **Roots Protocol** - Filesystem boundaries with `roots/list` support
//! - **Server-to-Client Requests** - Fully typed trait for sampling, elicitation, and roots
//! - **Comprehensive Schema Builders** - Type-safe builders for all schema types
//!
//! ### MCP 2025-11-25 Features (Always Enabled)
//!
//! All core MCP 2025-11-25 specification features are now always available:
//!
//! | Feature | SEP | Description |
//! |---------|-----|-------------|
//! | URL Elicitation | SEP-1036 | URL mode for OAuth/sensitive data collection |
//! | Sampling Tools | SEP-1577 | Tool calling in LLM sampling requests |
//! | Icons | SEP-973 | Icon metadata for tools, resources, prompts |
//! | Enum Improvements | SEP-1330 | Standards-based JSON Schema enum patterns |
//!
//! **Experimental Feature (requires feature flag):**
//! - `experimental-tasks` - Tasks API (SEP-1686) for long-running operations
//!
//! **Authentication & Security** (always enabled):
//! - SSRF protection for URL validation
//! - Client ID Metadata Documents (CIMD) for OAuth 2.1
//! - OpenID Connect Discovery (RFC 8414 + OIDC 1.0)
//! - Incremental consent with WWW-Authenticate (SEP-835)
//!
//! ### Performance & Observability
//! - **SIMD-Accelerated JSON** - Fast processing with `simd-json` and `sonic-rs`
//! - **Zero-Copy Processing** - Memory-efficient message handling with `Bytes`
//! - **Request Context** - Full request/response context tracking for observability
//! - **Session Management** - Memory-bounded state management with cleanup tasks
//! - **Observability Ready** - Built-in support for tracing and metrics collection
//!
//! ## Version Selection
//!
//! TurboMCP v3.0 targets MCP 2025-11-25 only. Runtime negotiation is exact-match:
//! clients and servers must agree on the current protocol version.
//!
//! **Typical Usage:**
//! ```toml
//! [dependencies]
//! turbomcp-protocol = "3.0"  # All core features included
//! ```
//!
//! **With Experimental Tasks API:**
//! ```toml
//! [dependencies]
//! turbomcp-protocol = { version = "3.0", features = ["experimental-tasks"] }
//! ```
//!
//! ### Runtime Version Negotiation
//!
//! Clients and servers negotiate protocol versions during initialization:
//!
//! ```rust,no_run
//! use turbomcp_protocol::{InitializeRequest, InitializeResult, ClientCapabilities};
//! use turbomcp_protocol::types::{Implementation, ServerCapabilities}; // Corrected import path
//!
//! // Client requests the current protocol version
//! let request = InitializeRequest {
//!     protocol_version: "2025-11-25".into(),  // Request draft
//!     capabilities: ClientCapabilities::default(),
//!     client_info: Implementation {
//!         name: "my-client".to_string(),
//!         title: None,
//!         version: "1.0.0".to_string(),
//!         ..Default::default()
//!     },
//!     meta: None,
//! };
//!
//! // Server responds with the same supported version
//! let response = InitializeResult {
//!     protocol_version: "2025-11-25".into(),
//!     capabilities: ServerCapabilities::default(),
//!     server_info: Implementation {
//!         name: "my-server".to_string(),
//!         title: None,
//!         version: "1.0.0".to_string(),
//!         ..Default::default()
//!     },
//!     instructions: None,
//!     meta: None,
//! };
//! ```
//!
//! **Key Principle:** clients request the current protocol version, and servers
//! must either accept it exactly or fail initialization.
//!
//! ## Architecture
//!
//! ```text
//! turbomcp-protocol/
//! ├── error/              # Error types and handling
//! ├── message/            # Message types and serialization
//! ├── context/            # Request/response context with server capabilities
//! ├── types/              # MCP protocol types
//! ├── jsonrpc/            # JSON-RPC 2.0 implementation
//! ├── validation/         # Schema validation
//! ├── session/            # Session management
//! ├── registry/           # Component registry
//! └── utils/              # Utility functions
//! ```
//!
//! ## Server-to-Client Communication
//!
//! The unified `RequestContext` exposes bidirectional operations directly —
//! tools call `ctx.sample(...)`, `ctx.elicit_form(...)`,
//! `ctx.elicit_url(...)`, or `ctx.notify_client(...)` and they succeed
//! whenever the transport attached a session.
//!
//! ```rust,ignore
//! use turbomcp_protocol::RequestContext;
//! use turbomcp_core::McpError;
//! use turbomcp_types::CreateMessageRequest;
//!
//! async fn my_tool(ctx: &RequestContext) -> Result<(), McpError> {
//!     let request = CreateMessageRequest {
//!         max_tokens: 100,
//!         ..Default::default()
//!     };
//!     let _response = ctx.sample(request).await?;
//!     Ok(())
//! }
//! ```

#![warn(
    missing_docs,
    missing_debug_implementations,
    rust_2018_idioms,
    unreachable_pub,
    clippy::all
)]
#![cfg_attr(
    all(not(feature = "mmap"), not(feature = "lock-free")),
    deny(unsafe_code)
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![allow(
    clippy::module_name_repetitions,
    clippy::cast_possible_truncation,  // Intentional in metrics/performance code
    clippy::cast_possible_wrap,  // Intentional in metrics/performance code
    clippy::cast_precision_loss,  // Intentional for f64 metrics
    clippy::cast_sign_loss,  // Intentional for metrics
    clippy::must_use_candidate,  // Too pedantic for library APIs
    clippy::return_self_not_must_use,  // Constructor methods don't need must_use
    clippy::struct_excessive_bools,  // Sometimes bools are the right design
    clippy::missing_panics_doc,  // Panic docs added where genuinely needed
    clippy::default_trait_access,  // Default::default() is sometimes clearer
    clippy::significant_drop_tightening,  // Overly pedantic about drop timing
    clippy::used_underscore_binding,  // Sometimes underscore bindings are needed
    clippy::wildcard_imports  // Used in test modules
)]

// v3.0: Re-export turbomcp-core foundation types
/// Re-export of turbomcp-core, the no_std foundation layer
pub use turbomcp_core as mcp_core;

// v3.0: McpError is THE error type - re-export at crate root
pub use turbomcp_core::error::{ErrorContext as McpErrorContext, ErrorKind, McpError, McpResult};
/// v3.0 Result alias using McpError
pub type Result<T> = McpResult<T>;
/// v3.0 Error alias for migration (prefer McpError directly)
pub type Error = McpError;

// v3.0: Unified handler response types from core
// These enable the IntoToolResponse pattern for ergonomic tool handlers
pub use turbomcp_core::response::{Image, IntoToolError, IntoToolResponse, Json, Text, ToolError};

// Core abstractions (merged from turbomcp-core in v2.0.0)
/// Configuration for protocol components.
pub mod config;
/// Request/response context, including server-to-client capabilities.
pub mod context;
/// An advanced handler registry with metrics and enhanced features.
pub mod enhanced_registry;
/// Error types and handling for the protocol.
pub mod error;
/// Traits and types for handling different MCP requests (tools, prompts, etc.).
pub mod handlers;
/// Lock-free data structures for high-performance concurrent scenarios.
#[cfg(feature = "lock-free")]
pub mod lock_free;
/// Core message types and serialization logic.
pub mod message;
/// Basic handler registration and lookup.
pub mod registry;
/// Security-related utilities, such as path validation.
pub mod security;
/// Session management for client connections.
pub mod session;
/// Utilities for shared, concurrent state management.
pub mod shared;
/// State management for the protocol.
pub mod state;
/// General utility functions.
pub mod utils;
/// Zero-copy data handling utilities for performance-critical operations.
pub mod zero_copy;

/// Zero-copy rkyv bridge for internal message routing.
///
/// This module is only available when the `rkyv` feature is enabled.
/// It provides efficient conversion between JSON-RPC and rkyv internal formats.
#[cfg(feature = "rkyv")]
#[cfg_attr(docsrs, doc(cfg(feature = "rkyv")))]
pub mod rkyv_bridge;

/// Wire codec integration for message serialization.
///
/// This module provides a unified interface for encoding/decoding MCP messages
/// using the [`turbomcp_wire`] codec abstraction.
///
/// Enable with the `wire` feature flag. Optional SIMD acceleration available
/// with `wire-simd`, and MessagePack support with `wire-msgpack`.
#[cfg(feature = "wire")]
#[cfg_attr(docsrs, doc(cfg(feature = "wire")))]
pub mod codec;

// Protocol-specific modules
/// Capability negotiation and management.
pub mod capabilities;
// Old elicitation module removed; use types::elicitation instead.
/// JSON-RPC 2.0 protocol implementation.
pub mod jsonrpc;
/// All MCP protocol types (requests, responses, and data structures).
pub mod types;
/// Schema validation for protocol messages.
pub mod validation;
/// Protocol version management and compatibility checking.
pub mod versioning;

// Test utilities (public to allow downstream crates to use them in tests)
// Following the pattern from axum and tokio
/// Public test utilities for use in downstream crates.
pub mod test_helpers;

// Re-export core types
pub use context::{
    BidirectionalContext, ClientCapabilities as ContextClientCapabilities, ClientId,
    ClientIdExtractor, ClientSession, CommunicationDirection, CommunicationInitiator,
    CompletionCapabilities, CompletionContext, CompletionOption,
    CompletionReference as ContextCompletionReference, ConnectionMetrics, ElicitationContext,
    ElicitationState, PingContext, PingOrigin, RequestContext, RequestContextExt, RequestInfo,
    ResourceTemplateContext, ResponseContext, RichContextExt, ServerInitiatedContext,
    ServerInitiatedType, SessionStateGuard, StateError, TemplateParameter, active_sessions_count,
    cleanup_session_state,
};
// Timestamp and ContentType are now in types module
pub use enhanced_registry::{EnhancedRegistry, HandlerStats};
// v3.0: McpError is re-exported from turbomcp_core at crate root
pub use error::RetryInfo;
pub use handlers::{
    CompletionItem, CompletionProvider, ElicitationHandler, ElicitationResponse,
    HandlerCapabilities, JsonRpcHandler, PingHandler, PingResponse, ResolvedResource,
    ResourceTemplate as HandlerResourceTemplate, ResourceTemplateHandler, ServerInfo,
    ServerInitiatedCapabilities, TemplateParam,
};
pub use message::{Message, MessageId, MessageMetadata};
pub use registry::RegistryError;
pub use security::{validate_file_extension, validate_path, validate_path_within};
pub use session::{SessionAnalytics, SessionConfig, SessionManager};
pub use shared::{ConsumableShared, Shareable, Shared, SharedError};
pub use state::StateManager;

// Re-export ONLY essential types at root (v2.0 - improved ergonomics)
// Everything else requires module qualification: turbomcp_protocol::types::*
pub use types::{
    // Most common tool operations
    CallToolRequest,
    CallToolResult,

    ClientCapabilities,
    // Macro API types (used by generated code - not typically imported by users)
    GetPromptRequest,
    GetPromptResult,
    // Most common request/response pairs (initialization flow)
    InitializeRequest,
    InitializeResult,

    ReadResourceRequest,
    ReadResourceResult,

    // Capability negotiation (used in every initialize)
    ServerCapabilities,
};

// Note: types module is already declared as `pub mod types;` above
// Users access other types via turbomcp_protocol::types::Tool, etc.

pub use jsonrpc::{
    JsonRpcError, JsonRpcErrorCode, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse,
    JsonRpcVersion,
};

pub use capabilities::{
    CapabilityMatcher, CapabilityNegotiator, CapabilitySet,
    builders::{
        ClientCapabilitiesBuilder, ClientCapabilitiesBuilderState, ServerCapabilitiesBuilder,
        ServerCapabilitiesBuilderState,
    },
};

pub use versioning::adapter::{VersionAdapter, adapter_for_version};
pub use versioning::{VersionCompatibility, VersionManager, VersionRequirement};

// Re-export constants from core (single source of truth - DRY)
pub use turbomcp_core::{
    DEFAULT_TIMEOUT_MS, MAX_MESSAGE_SIZE, PROTOCOL_VERSION, SDK_NAME, SDK_VERSION,
    SUPPORTED_VERSIONS, error_codes, features, methods,
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_version_constants() {
        assert_eq!(PROTOCOL_VERSION, "2025-11-25");
        assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
        // Latest should be last in supported versions (oldest to newest)
        assert_eq!(
            SUPPORTED_VERSIONS[SUPPORTED_VERSIONS.len() - 1],
            PROTOCOL_VERSION
        );
    }

    #[test]
    fn test_size_constants() {
        // Constants are statically verified at compile-time
        const _: () = assert!(
            MAX_MESSAGE_SIZE > 1024,
            "MAX_MESSAGE_SIZE must be larger than 1KB"
        );
        const _: () = assert!(
            MAX_MESSAGE_SIZE == 1024 * 1024,
            "MAX_MESSAGE_SIZE must be 1MB for security"
        );

        const _: () = assert!(
            DEFAULT_TIMEOUT_MS > 1000,
            "DEFAULT_TIMEOUT_MS must be larger than 1 second"
        );
        const _: () = assert!(
            DEFAULT_TIMEOUT_MS == 30_000,
            "DEFAULT_TIMEOUT_MS must be 30 seconds"
        );
    }

    #[test]
    fn test_method_names() {
        assert_eq!(methods::INITIALIZE, "initialize");
        assert_eq!(methods::LIST_TOOLS, "tools/list");
        assert_eq!(methods::CALL_TOOL, "tools/call");
    }

    #[test]
    fn test_error_codes() {
        assert_eq!(error_codes::PARSE_ERROR, -32700);
        assert_eq!(error_codes::TOOL_NOT_FOUND, -32001);
    }
}