turbomcp_protocol/
lib.rs

1//! # MCP Protocol Implementation
2//!
3//! This crate provides a complete implementation of the Model Context Protocol (MCP)
4//! specification version 2025-06-18. It includes all protocol types, JSON-RPC integration,
5//! and capability negotiation.
6//!
7//! ## Features
8//!
9//! ### Core Protocol Support
10//! - Complete MCP 2025-06-18 protocol implementation  
11//! - JSON-RPC 2.0 support with batching and notifications
12//! - Type-safe capability negotiation and compatibility checking
13//! - Protocol versioning with backward compatibility
14//! - Fast serialization with SIMD acceleration
15//!
16//! ### Advanced Protocol Features (New in 1.0.3)
17//! - **Elicitation Protocol** - Server-initiated user input requests with rich schema validation
18//! - **Sampling Support** - Bidirectional LLM sampling message types
19//! - **Roots Protocol** - Filesystem boundaries with `roots/list` support
20//! - **Comprehensive Schema Builders** - Type-safe builders for all schema types
21//!
22//! ### Validation & Security
23//! - Comprehensive validation constraints (min/max, patterns, required fields)
24//! - Type-safe schema builders with fluent API
25//! - Protocol method validation and error handling
26//! - Security-focused design with proper boundary checking
27//!
28//! ## Usage Examples
29//!
30//! ### Basic Protocol Types
31//!
32//! ```rust
33//! use turbomcp_protocol::types::{Tool, ToolInputSchema, CallToolRequest, CallToolResult};
34//! use std::collections::HashMap;
35//!
36//! // Define a tool schema
37//! let tool = Tool {
38//!     name: "calculate".to_string(),
39//!     title: Some("Calculator".to_string()),
40//!     description: Some("Perform mathematical calculations".to_string()),
41//!     input_schema: ToolInputSchema {
42//!         schema_type: "object".to_string(),
43//!         properties: Some({
44//!             let mut props = HashMap::new();
45//!             props.insert("operation".to_string(), serde_json::json!({
46//!                 "type": "string",
47//!                 "enum": ["add", "subtract", "multiply", "divide"]
48//!             }));
49//!             props
50//!         }),
51//!         required: Some(vec!["operation".to_string()]),
52//!         additional_properties: Some(false),
53//!     },
54//!     output_schema: None,
55//!     annotations: None,
56//!     meta: None,
57//! };
58//! ```
59//!
60//! ### Elicitation Schema Building
61//!
62//! ```rust
63//! use turbomcp_protocol::elicitation::{ElicitationSchema, EnumSchema, BooleanSchema, PrimitiveSchemaDefinition};
64//!
65//! // Build an elicitation schema with validation
66//! let schema = ElicitationSchema::new()
67//!     .add_property("theme".to_string(), PrimitiveSchemaDefinition::Enum(EnumSchema {
68//!         schema_type: "string".to_string(),
69//!         title: Some("Theme".to_string()),
70//!         description: Some("UI color theme".to_string()),
71//!         enum_values: vec!["light".to_string(), "dark".to_string(), "auto".to_string()],
72//!         enum_names: None,
73//!     }))
74//!     .add_property("notifications".to_string(), PrimitiveSchemaDefinition::Boolean(BooleanSchema {
75//!         schema_type: "boolean".to_string(),
76//!         title: Some("Notifications".to_string()),
77//!         description: Some("Enable push notifications".to_string()),
78//!         default: Some(true),
79//!     }))
80//!     .require(vec!["theme".to_string()]);
81//! ```
82//!
83//! ### Type-State Capability Builders (New in 1.1.0)
84//!
85//! TurboMCP provides const-generic type-state builders that ensure capabilities
86//! are configured correctly at compile time, providing compile-time safety with
87//! zero-cost abstractions.
88//!
89//! ```rust
90//! use turbomcp_protocol::capabilities::builders::{
91//!     ServerCapabilitiesBuilder, ClientCapabilitiesBuilder
92//! };
93//!
94//! // Server capabilities with compile-time validation
95//! let server_caps = ServerCapabilitiesBuilder::new()
96//!     .enable_experimental()
97//!     .enable_tools()
98//!     .enable_prompts()
99//!     .enable_tool_list_changed()  // Only available when tools are enabled!
100//!     .enable_prompts_list_changed() // Only available when prompts are enabled!
101//!     .with_simd_optimization("avx2") // Performance optimization
102//!     .with_enterprise_security(true) // Security enhancement
103//!     .build();
104//!
105//! // Client capabilities with type safety
106//! let client_caps = ClientCapabilitiesBuilder::full_featured()
107//!     .with_llm_provider("openai", "gpt-4") // LLM integration
108//!     .with_ui_capabilities(vec!["form", "dialog"]) // UI enhancement
109//!     .build();
110//!
111//! // Convenience builders for common configurations
112//! let minimal_server = ServerCapabilitiesBuilder::minimal().build();
113//! let sampling_client = ClientCapabilitiesBuilder::sampling_focused().build();
114//! ```
115//!
116//! **Key Benefits:**
117//! - **Compile-time capability validation** - Methods only available when capabilities enabled
118//! - **Performance optimizations** - SIMD optimization hints, enterprise security, LLM metadata
119//! - **Advanced error prevention** - Impossible to misconfigure capability relationships
120//! - **Zero-cost abstractions** - All validation happens at compile time
121//! - **Backwards compatible** - Existing `ServerCapabilities::default()` still works
122//!
123
124#![warn(
125    missing_docs,
126    missing_debug_implementations,
127    rust_2018_idioms,
128    unreachable_pub,
129    clippy::all
130)]
131#![deny(unsafe_code)]
132#![allow(
133    clippy::module_name_repetitions,
134    clippy::missing_errors_doc,  // Error documentation in progress
135    clippy::wildcard_imports,  // Used in test modules
136    clippy::must_use_candidate,  // Too pedantic for library APIs
137    clippy::return_self_not_must_use,  // Constructor methods don't need must_use
138    clippy::struct_excessive_bools,  // Sometimes bools are the right design
139    clippy::missing_panics_doc,  // Panic docs added where genuinely needed
140    clippy::default_trait_access  // Default::default() is sometimes clearer
141)]
142#![cfg_attr(docsrs, feature(doc_cfg))]
143
144// Re-export core functionality
145pub use turbomcp_core::{Error, Result};
146
147// Core protocol modules
148pub mod capabilities;
149pub mod elicitation;
150pub mod jsonrpc;
151pub mod types;
152pub mod validation;
153pub mod versioning;
154
155// Re-export commonly used types
156pub use types::{
157    ArgumentInfo,
158    CallToolRequest,
159    CallToolResult,
160    // Capability types
161    ClientCapabilities,
162    ClientNotification,
163    // Core types
164    ClientRequest,
165    // Completion types
166    CompleteRequestParams,
167    CompletionReference,
168    CompletionResponse,
169    // Content types
170    Content,
171    // Sampling
172    CreateMessageRequest,
173    CreateMessageResult,
174    // Elicitation types
175    ElicitRequest,
176    ElicitRequestParams,
177    ElicitResult,
178    ElicitationAction,
179    ElicitationSchema,
180    EmbeddedResource,
181    GetPromptRequest,
182    GetPromptResult,
183    ImageContent,
184    Implementation,
185
186    InitializeRequest,
187    InitializeResult,
188    InitializedNotification,
189
190    ListPromptsRequest,
191    ListPromptsResult,
192
193    ListResourceTemplatesRequest,
194    ListResourceTemplatesResult,
195    ListResourcesRequest,
196    ListResourcesResult,
197    ListRootsRequest,
198    ListRootsResult,
199    ListToolsRequest,
200    ListToolsResult,
201
202    // Logging and progress
203    LogLevel,
204    LoggingNotification,
205    // Ping types
206    PingParams,
207    PingRequest,
208    PingResult,
209    ProgressNotification,
210    ProgressToken,
211    // Prompt types
212    Prompt,
213    PromptInput,
214    ProtocolVersion,
215    ReadResourceRequest,
216    ReadResourceResult,
217    RequestId,
218    // Resource types
219    Resource,
220    ResourceContents,
221    // Resource Template types
222    ResourceTemplate,
223    ResourceUpdatedNotification,
224    // Roots
225    Root,
226    RootsListChangedNotification,
227    SamplingMessage,
228
229    ServerCapabilities,
230    ServerNotification,
231    ServerRequest,
232    SetLevelRequest,
233    SetLevelResult,
234
235    SubscribeRequest,
236    TextContent,
237    // Tool types
238    Tool,
239    ToolInputSchema,
240    ToolOutputSchema,
241    UnsubscribeRequest,
242};
243
244pub use jsonrpc::{
245    JsonRpcBatch, JsonRpcError, JsonRpcErrorCode, JsonRpcNotification, JsonRpcRequest,
246    JsonRpcResponse, JsonRpcVersion,
247};
248
249pub use capabilities::{
250    CapabilityMatcher, CapabilityNegotiator, CapabilitySet,
251    builders::{
252        ClientCapabilitiesBuilder, ClientCapabilitiesBuilderState, ServerCapabilitiesBuilder,
253        ServerCapabilitiesBuilderState,
254    },
255};
256
257pub use versioning::{VersionCompatibility, VersionManager, VersionRequirement};
258
259/// Current MCP protocol version
260pub const PROTOCOL_VERSION: &str = "2025-06-18";
261
262/// Supported MCP protocol versions
263pub const SUPPORTED_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
264
265/// Protocol feature flags
266pub mod features {
267    /// Tool calling capability
268    pub const TOOLS: &str = "tools";
269
270    /// Prompt capability
271    pub const PROMPTS: &str = "prompts";
272
273    /// Resource capability
274    pub const RESOURCES: &str = "resources";
275
276    /// Logging capability
277    pub const LOGGING: &str = "logging";
278
279    /// Progress notifications
280    pub const PROGRESS: &str = "progress";
281
282    /// Sampling capability
283    pub const SAMPLING: &str = "sampling";
284
285    /// Roots capability
286    pub const ROOTS: &str = "roots";
287}
288
289/// Protocol method names
290pub mod methods {
291    // Initialization
292    /// Initialize handshake method
293    pub const INITIALIZE: &str = "initialize";
294    /// Initialized notification method
295    pub const INITIALIZED: &str = "notifications/initialized";
296
297    // Tools
298    /// List available tools method
299    pub const LIST_TOOLS: &str = "tools/list";
300    /// Call a specific tool method
301    pub const CALL_TOOL: &str = "tools/call";
302
303    // Prompts
304    /// List available prompts method
305    pub const LIST_PROMPTS: &str = "prompts/list";
306    /// Get a specific prompt method
307    pub const GET_PROMPT: &str = "prompts/get";
308
309    // Resources
310    /// List available resources method
311    pub const LIST_RESOURCES: &str = "resources/list";
312    /// Read a specific resource method
313    pub const READ_RESOURCE: &str = "resources/read";
314    /// Subscribe to resource updates method
315    pub const SUBSCRIBE: &str = "resources/subscribe";
316    /// Unsubscribe from resource updates method
317    pub const UNSUBSCRIBE: &str = "resources/unsubscribe";
318    /// Resource updated notification
319    pub const RESOURCE_UPDATED: &str = "notifications/resources/updated";
320    /// Resource list changed notification
321    pub const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
322
323    // Logging
324    /// Set logging level method
325    pub const SET_LEVEL: &str = "logging/setLevel";
326    /// Log message notification
327    pub const LOG_MESSAGE: &str = "notifications/message";
328
329    // Progress
330    /// Progress update notification
331    pub const PROGRESS: &str = "notifications/progress";
332
333    // Sampling
334    /// Create sampling message method
335    pub const CREATE_MESSAGE: &str = "sampling/createMessage";
336
337    // Roots
338    /// List directory roots method
339    pub const LIST_ROOTS: &str = "roots/list";
340    /// Roots list changed notification
341    pub const ROOTS_LIST_CHANGED: &str = "notifications/roots/list_changed";
342}
343
344/// Protocol error codes (JSON-RPC standard + MCP extensions)
345pub mod error_codes {
346    // JSON-RPC standard errors
347    /// Parse error - Invalid JSON was received by the server
348    pub const PARSE_ERROR: i32 = -32700;
349    /// Invalid request - The JSON sent is not a valid Request object
350    pub const INVALID_REQUEST: i32 = -32600;
351    /// Method not found - The method does not exist / is not available
352    pub const METHOD_NOT_FOUND: i32 = -32601;
353    /// Invalid params - Invalid method parameter(s)
354    pub const INVALID_PARAMS: i32 = -32602;
355    /// Internal error - Internal JSON-RPC error
356    pub const INTERNAL_ERROR: i32 = -32603;
357
358    // MCP-specific errors (application-defined range)
359    /// Tool not found error
360    pub const TOOL_NOT_FOUND: i32 = -32001;
361    /// Tool execution error
362    pub const TOOL_EXECUTION_ERROR: i32 = -32002;
363    /// Prompt not found error
364    pub const PROMPT_NOT_FOUND: i32 = -32003;
365    /// Resource not found error
366    pub const RESOURCE_NOT_FOUND: i32 = -32004;
367    /// Resource access denied error
368    pub const RESOURCE_ACCESS_DENIED: i32 = -32005;
369    /// Capability not supported error
370    pub const CAPABILITY_NOT_SUPPORTED: i32 = -32006;
371    /// Protocol version mismatch error
372    pub const PROTOCOL_VERSION_MISMATCH: i32 = -32007;
373    /// Authentication required error
374    pub const AUTHENTICATION_REQUIRED: i32 = -32008;
375    /// Rate limited error
376    pub const RATE_LIMITED: i32 = -32009;
377    /// Server overloaded error
378    pub const SERVER_OVERLOADED: i32 = -32010;
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn test_protocol_constants() {
387        assert_eq!(PROTOCOL_VERSION, "2025-06-18");
388        assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
389        #[allow(clippy::const_is_empty)]
390        {
391            assert!(!SUPPORTED_VERSIONS.is_empty());
392        }
393    }
394
395    #[test]
396    fn test_method_names() {
397        assert_eq!(methods::INITIALIZE, "initialize");
398        assert_eq!(methods::LIST_TOOLS, "tools/list");
399        assert_eq!(methods::CALL_TOOL, "tools/call");
400    }
401
402    #[test]
403    fn test_error_codes() {
404        assert_eq!(error_codes::PARSE_ERROR, -32700);
405        assert_eq!(error_codes::TOOL_NOT_FOUND, -32001);
406    }
407}