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#![warn(
84 missing_docs,
85 missing_debug_implementations,
86 rust_2018_idioms,
87 unreachable_pub,
88 clippy::all
89)]
90#![deny(unsafe_code)]
91#![allow(
92 clippy::module_name_repetitions,
93 clippy::missing_errors_doc, // Error documentation in progress
94 clippy::wildcard_imports, // Used in test modules
95 clippy::must_use_candidate, // Too pedantic for library APIs
96 clippy::return_self_not_must_use, // Constructor methods don't need must_use
97 clippy::struct_excessive_bools, // Sometimes bools are the right design
98 clippy::missing_panics_doc, // Panic docs added where genuinely needed
99 clippy::default_trait_access // Default::default() is sometimes clearer
100)]
101#![cfg_attr(docsrs, feature(doc_cfg))]
102
103// Re-export core functionality
104pub use turbomcp_core::{Error, Result};
105
106// Core protocol modules
107pub mod capabilities;
108pub mod elicitation;
109pub mod jsonrpc;
110pub mod types;
111pub mod validation;
112pub mod versioning;
113
114// Re-export commonly used types
115pub use types::{
116 ArgumentInfo,
117 CallToolRequest,
118 CallToolResult,
119 // Capability types
120 ClientCapabilities,
121 ClientNotification,
122 // Core types
123 ClientRequest,
124 // Completion types
125 CompleteRequestParams,
126 CompletionReference,
127 CompletionResponse,
128 // Content types
129 Content,
130 // Sampling
131 CreateMessageRequest,
132 CreateMessageResult,
133 // Elicitation types
134 ElicitRequest,
135 ElicitRequestParams,
136 ElicitResult,
137 ElicitationAction,
138 ElicitationSchema,
139 EmbeddedResource,
140 GetPromptRequest,
141 GetPromptResult,
142 ImageContent,
143 Implementation,
144
145 InitializeRequest,
146 InitializeResult,
147 InitializedNotification,
148
149 ListPromptsRequest,
150 ListPromptsResult,
151
152 ListResourceTemplatesRequest,
153 ListResourceTemplatesResult,
154 ListResourcesRequest,
155 ListResourcesResult,
156 ListRootsRequest,
157 ListRootsResult,
158 ListToolsRequest,
159 ListToolsResult,
160
161 // Logging and progress
162 LogLevel,
163 LoggingNotification,
164 // Ping types
165 PingParams,
166 PingRequest,
167 PingResult,
168 ProgressNotification,
169 ProgressToken,
170 // Prompt types
171 Prompt,
172 PromptInput,
173 ProtocolVersion,
174 ReadResourceRequest,
175 ReadResourceResult,
176 RequestId,
177 // Resource types
178 Resource,
179 ResourceContents,
180 // Resource Template types
181 ResourceTemplate,
182 ResourceUpdatedNotification,
183 // Roots
184 Root,
185 RootsListChangedNotification,
186 SamplingMessage,
187
188 ServerCapabilities,
189 ServerNotification,
190 ServerRequest,
191 SetLevelRequest,
192 SetLevelResult,
193
194 SubscribeRequest,
195 TextContent,
196 // Tool types
197 Tool,
198 ToolInputSchema,
199 ToolOutputSchema,
200 UnsubscribeRequest,
201};
202
203pub use jsonrpc::{
204 JsonRpcBatch, JsonRpcError, JsonRpcErrorCode, JsonRpcNotification, JsonRpcRequest,
205 JsonRpcResponse, JsonRpcVersion,
206};
207
208pub use capabilities::{CapabilityMatcher, CapabilityNegotiator, CapabilitySet};
209
210pub use versioning::{VersionCompatibility, VersionManager, VersionRequirement};
211
212/// Current MCP protocol version
213pub const PROTOCOL_VERSION: &str = "2025-06-18";
214
215/// Supported MCP protocol versions
216pub const SUPPORTED_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
217
218/// Protocol feature flags
219pub mod features {
220 /// Tool calling capability
221 pub const TOOLS: &str = "tools";
222
223 /// Prompt capability
224 pub const PROMPTS: &str = "prompts";
225
226 /// Resource capability
227 pub const RESOURCES: &str = "resources";
228
229 /// Logging capability
230 pub const LOGGING: &str = "logging";
231
232 /// Progress notifications
233 pub const PROGRESS: &str = "progress";
234
235 /// Sampling capability
236 pub const SAMPLING: &str = "sampling";
237
238 /// Roots capability
239 pub const ROOTS: &str = "roots";
240}
241
242/// Protocol method names
243pub mod methods {
244 // Initialization
245 /// Initialize handshake method
246 pub const INITIALIZE: &str = "initialize";
247 /// Initialized notification method
248 pub const INITIALIZED: &str = "notifications/initialized";
249
250 // Tools
251 /// List available tools method
252 pub const LIST_TOOLS: &str = "tools/list";
253 /// Call a specific tool method
254 pub const CALL_TOOL: &str = "tools/call";
255
256 // Prompts
257 /// List available prompts method
258 pub const LIST_PROMPTS: &str = "prompts/list";
259 /// Get a specific prompt method
260 pub const GET_PROMPT: &str = "prompts/get";
261
262 // Resources
263 /// List available resources method
264 pub const LIST_RESOURCES: &str = "resources/list";
265 /// Read a specific resource method
266 pub const READ_RESOURCE: &str = "resources/read";
267 /// Subscribe to resource updates method
268 pub const SUBSCRIBE: &str = "resources/subscribe";
269 /// Unsubscribe from resource updates method
270 pub const UNSUBSCRIBE: &str = "resources/unsubscribe";
271 /// Resource updated notification
272 pub const RESOURCE_UPDATED: &str = "notifications/resources/updated";
273 /// Resource list changed notification
274 pub const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
275
276 // Logging
277 /// Set logging level method
278 pub const SET_LEVEL: &str = "logging/setLevel";
279 /// Log message notification
280 pub const LOG_MESSAGE: &str = "notifications/message";
281
282 // Progress
283 /// Progress update notification
284 pub const PROGRESS: &str = "notifications/progress";
285
286 // Sampling
287 /// Create sampling message method
288 pub const CREATE_MESSAGE: &str = "sampling/createMessage";
289
290 // Roots
291 /// List directory roots method
292 pub const LIST_ROOTS: &str = "roots/list";
293 /// Roots list changed notification
294 pub const ROOTS_LIST_CHANGED: &str = "notifications/roots/list_changed";
295}
296
297/// Protocol error codes (JSON-RPC standard + MCP extensions)
298pub mod error_codes {
299 // JSON-RPC standard errors
300 /// Parse error - Invalid JSON was received by the server
301 pub const PARSE_ERROR: i32 = -32700;
302 /// Invalid request - The JSON sent is not a valid Request object
303 pub const INVALID_REQUEST: i32 = -32600;
304 /// Method not found - The method does not exist / is not available
305 pub const METHOD_NOT_FOUND: i32 = -32601;
306 /// Invalid params - Invalid method parameter(s)
307 pub const INVALID_PARAMS: i32 = -32602;
308 /// Internal error - Internal JSON-RPC error
309 pub const INTERNAL_ERROR: i32 = -32603;
310
311 // MCP-specific errors (application-defined range)
312 /// Tool not found error
313 pub const TOOL_NOT_FOUND: i32 = -32001;
314 /// Tool execution error
315 pub const TOOL_EXECUTION_ERROR: i32 = -32002;
316 /// Prompt not found error
317 pub const PROMPT_NOT_FOUND: i32 = -32003;
318 /// Resource not found error
319 pub const RESOURCE_NOT_FOUND: i32 = -32004;
320 /// Resource access denied error
321 pub const RESOURCE_ACCESS_DENIED: i32 = -32005;
322 /// Capability not supported error
323 pub const CAPABILITY_NOT_SUPPORTED: i32 = -32006;
324 /// Protocol version mismatch error
325 pub const PROTOCOL_VERSION_MISMATCH: i32 = -32007;
326 /// Authentication required error
327 pub const AUTHENTICATION_REQUIRED: i32 = -32008;
328 /// Rate limited error
329 pub const RATE_LIMITED: i32 = -32009;
330 /// Server overloaded error
331 pub const SERVER_OVERLOADED: i32 = -32010;
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337
338 #[test]
339 fn test_protocol_constants() {
340 assert_eq!(PROTOCOL_VERSION, "2025-06-18");
341 assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
342 #[allow(clippy::const_is_empty)]
343 {
344 assert!(!SUPPORTED_VERSIONS.is_empty());
345 }
346 }
347
348 #[test]
349 fn test_method_names() {
350 assert_eq!(methods::INITIALIZE, "initialize");
351 assert_eq!(methods::LIST_TOOLS, "tools/list");
352 assert_eq!(methods::CALL_TOOL, "tools/call");
353 }
354
355 #[test]
356 fn test_error_codes() {
357 assert_eq!(error_codes::PARSE_ERROR, -32700);
358 assert_eq!(error_codes::TOOL_NOT_FOUND, -32001);
359 }
360}