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//! - Complete MCP 2025-06-18 protocol implementation  
10//! - JSON-RPC 2.0 support with batching
11//! - Type-safe capability negotiation
12//! - Protocol versioning and compatibility
13//! - Fast serialization
14//! - Comprehensive validation
15
16#![warn(
17    missing_docs,
18    missing_debug_implementations,
19    rust_2018_idioms,
20    unreachable_pub,
21    clippy::all
22)]
23#![deny(unsafe_code)]
24#![allow(
25    clippy::module_name_repetitions,
26    clippy::missing_errors_doc,  // Error documentation in progress
27    clippy::wildcard_imports,  // Used in test modules
28    clippy::must_use_candidate,  // Too pedantic for library APIs
29    clippy::return_self_not_must_use,  // Constructor methods don't need must_use
30    clippy::struct_excessive_bools,  // Sometimes bools are the right design
31    clippy::missing_panics_doc,  // Panic docs added where genuinely needed
32    clippy::default_trait_access  // Default::default() is sometimes clearer
33)]
34#![cfg_attr(docsrs, feature(doc_cfg))]
35
36// Re-export core functionality
37pub use turbomcp_core::{Error, Result};
38
39// Core protocol modules
40pub mod capabilities;
41pub mod jsonrpc;
42pub mod types;
43pub mod validation;
44pub mod versioning;
45
46// Re-export commonly used types
47pub use types::{
48    CallToolRequest,
49    CallToolResult,
50    // Capability types
51    ClientCapabilities,
52    ClientNotification,
53    // Core types
54    ClientRequest,
55    // Content types
56    Content,
57    // Sampling
58    CreateMessageRequest,
59    CreateMessageResult,
60    EmbeddedResource,
61
62    GetPromptRequest,
63    GetPromptResult,
64    ImageContent,
65    Implementation,
66
67    InitializeRequest,
68    InitializeResult,
69    InitializedNotification,
70
71    ListPromptsRequest,
72    ListPromptsResult,
73
74    ListResourcesRequest,
75    ListResourcesResult,
76    ListRootsRequest,
77    ListRootsResult,
78    ListToolsRequest,
79    ListToolsResult,
80
81    // Logging and progress
82    LogLevel,
83    LoggingNotification,
84    ProgressNotification,
85    ProgressToken,
86    // Prompt types
87    Prompt,
88    PromptInput,
89    ProtocolVersion,
90    ReadResourceRequest,
91    ReadResourceResult,
92    RequestId,
93    // Resource types
94    Resource,
95    ResourceContents,
96    ResourceUpdatedNotification,
97
98    // Roots
99    Root,
100    RootsListChangedNotification,
101    SamplingMessage,
102
103    ServerCapabilities,
104    ServerNotification,
105    ServerRequest,
106    SetLevelRequest,
107    SetLevelResult,
108
109    SubscribeRequest,
110    TextContent,
111    // Tool types
112    Tool,
113    ToolInputSchema,
114    ToolOutputSchema,
115    UnsubscribeRequest,
116};
117
118pub use jsonrpc::{
119    JsonRpcBatch, JsonRpcError, JsonRpcErrorCode, JsonRpcNotification, JsonRpcRequest,
120    JsonRpcResponse, JsonRpcVersion,
121};
122
123pub use capabilities::{CapabilityMatcher, CapabilityNegotiator, CapabilitySet};
124
125pub use versioning::{VersionCompatibility, VersionManager, VersionRequirement};
126
127/// Current MCP protocol version
128pub const PROTOCOL_VERSION: &str = "2025-06-18";
129
130/// Supported MCP protocol versions
131pub const SUPPORTED_VERSIONS: &[&str] = &["2025-06-18", "2024-11-05"];
132
133/// Protocol feature flags
134pub mod features {
135    /// Tool calling capability
136    pub const TOOLS: &str = "tools";
137
138    /// Prompt capability
139    pub const PROMPTS: &str = "prompts";
140
141    /// Resource capability
142    pub const RESOURCES: &str = "resources";
143
144    /// Logging capability
145    pub const LOGGING: &str = "logging";
146
147    /// Progress notifications
148    pub const PROGRESS: &str = "progress";
149
150    /// Sampling capability
151    pub const SAMPLING: &str = "sampling";
152
153    /// Roots capability
154    pub const ROOTS: &str = "roots";
155}
156
157/// Protocol method names
158pub mod methods {
159    // Initialization
160    /// Initialize handshake method
161    pub const INITIALIZE: &str = "initialize";
162    /// Initialized notification method
163    pub const INITIALIZED: &str = "notifications/initialized";
164
165    // Tools
166    /// List available tools method
167    pub const LIST_TOOLS: &str = "tools/list";
168    /// Call a specific tool method
169    pub const CALL_TOOL: &str = "tools/call";
170
171    // Prompts
172    /// List available prompts method
173    pub const LIST_PROMPTS: &str = "prompts/list";
174    /// Get a specific prompt method
175    pub const GET_PROMPT: &str = "prompts/get";
176
177    // Resources
178    /// List available resources method
179    pub const LIST_RESOURCES: &str = "resources/list";
180    /// Read a specific resource method
181    pub const READ_RESOURCE: &str = "resources/read";
182    /// Subscribe to resource updates method
183    pub const SUBSCRIBE: &str = "resources/subscribe";
184    /// Unsubscribe from resource updates method
185    pub const UNSUBSCRIBE: &str = "resources/unsubscribe";
186    /// Resource updated notification
187    pub const RESOURCE_UPDATED: &str = "notifications/resources/updated";
188    /// Resource list changed notification
189    pub const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
190
191    // Logging
192    /// Set logging level method
193    pub const SET_LEVEL: &str = "logging/setLevel";
194    /// Log message notification
195    pub const LOG_MESSAGE: &str = "notifications/message";
196
197    // Progress
198    /// Progress update notification
199    pub const PROGRESS: &str = "notifications/progress";
200
201    // Sampling
202    /// Create sampling message method
203    pub const CREATE_MESSAGE: &str = "sampling/createMessage";
204
205    // Roots
206    /// List directory roots method
207    pub const LIST_ROOTS: &str = "roots/list";
208    /// Roots list changed notification
209    pub const ROOTS_LIST_CHANGED: &str = "notifications/roots/list_changed";
210}
211
212/// Protocol error codes (JSON-RPC standard + MCP extensions)
213pub mod error_codes {
214    // JSON-RPC standard errors
215    /// Parse error - Invalid JSON was received by the server
216    pub const PARSE_ERROR: i32 = -32700;
217    /// Invalid request - The JSON sent is not a valid Request object
218    pub const INVALID_REQUEST: i32 = -32600;
219    /// Method not found - The method does not exist / is not available
220    pub const METHOD_NOT_FOUND: i32 = -32601;
221    /// Invalid params - Invalid method parameter(s)
222    pub const INVALID_PARAMS: i32 = -32602;
223    /// Internal error - Internal JSON-RPC error
224    pub const INTERNAL_ERROR: i32 = -32603;
225
226    // MCP-specific errors (application-defined range)
227    /// Tool not found error
228    pub const TOOL_NOT_FOUND: i32 = -32001;
229    /// Tool execution error
230    pub const TOOL_EXECUTION_ERROR: i32 = -32002;
231    /// Prompt not found error
232    pub const PROMPT_NOT_FOUND: i32 = -32003;
233    /// Resource not found error
234    pub const RESOURCE_NOT_FOUND: i32 = -32004;
235    /// Resource access denied error
236    pub const RESOURCE_ACCESS_DENIED: i32 = -32005;
237    /// Capability not supported error
238    pub const CAPABILITY_NOT_SUPPORTED: i32 = -32006;
239    /// Protocol version mismatch error
240    pub const PROTOCOL_VERSION_MISMATCH: i32 = -32007;
241    /// Authentication required error
242    pub const AUTHENTICATION_REQUIRED: i32 = -32008;
243    /// Rate limited error
244    pub const RATE_LIMITED: i32 = -32009;
245    /// Server overloaded error
246    pub const SERVER_OVERLOADED: i32 = -32010;
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn test_protocol_constants() {
255        assert_eq!(PROTOCOL_VERSION, "2025-06-18");
256        assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
257        #[allow(clippy::const_is_empty)]
258        {
259            assert!(!SUPPORTED_VERSIONS.is_empty());
260        }
261    }
262
263    #[test]
264    fn test_method_names() {
265        assert_eq!(methods::INITIALIZE, "initialize");
266        assert_eq!(methods::LIST_TOOLS, "tools/list");
267        assert_eq!(methods::CALL_TOOL, "tools/call");
268    }
269
270    #[test]
271    fn test_error_codes() {
272        assert_eq!(error_codes::PARSE_ERROR, -32700);
273        assert_eq!(error_codes::TOOL_NOT_FOUND, -32001);
274    }
275}