turbomcp_core/lib.rs
1//! # TurboMCP Core
2//!
3//! Core MCP types and primitives - `no_std` compatible for WASM targets.
4//!
5//! This crate provides the foundational types for the Model Context Protocol (MCP)
6//! that can be used in `no_std` environments including WebAssembly.
7//!
8//! ## Features
9//!
10//! - `std` (default): Enable standard library support, including richer error types
11//! - `rich-errors`: Enable UUID-based error tracking (requires `std`)
12//! - `wasm`: Enable WASM-specific optimizations
13//! - `zero-copy`: Enable rkyv zero-copy serialization for internal message passing
14//!
15//! ## Unified Handler Trait
16//!
17//! The [`McpHandler`] trait is the core abstraction for MCP servers. It works on
18//! both native and WASM targets through platform-adaptive bounds:
19//!
20//! ```rust,ignore
21//! use turbomcp_core::{McpHandler, RequestContext};
22//! use turbomcp_types::*;
23//!
24//! #[derive(Clone)]
25//! struct MyServer;
26//!
27//! impl McpHandler for MyServer {
28//! fn server_info(&self) -> ServerInfo {
29//! ServerInfo::new("my-server", "1.0.0")
30//! }
31//! // ... other methods
32//! }
33//! ```
34//!
35//! ## Platform-Adaptive Bounds
36//!
37//! The [`MaybeSend`] and [`MaybeSync`] marker traits enable unified code:
38//! - **Native**: Requires `Send + Sync` for multi-threaded executors
39//! - **WASM**: No thread safety requirements (single-threaded)
40//!
41//! ## no_std Usage
42//!
43//! ```toml
44//! [dependencies]
45//! turbomcp-core = { version = "3.0", default-features = false }
46//! ```
47//!
48//! ## Module Organization
49//!
50//! - [`auth`]: Authentication traits and types (portable across native/WASM)
51//! - [`handler`]: Unified MCP handler trait
52//! - [`context`]: Request context types
53//! - [`marker`]: Platform-adaptive marker traits
54//! - [`types`]: Core MCP protocol types (tools, resources, prompts, etc.)
55//! - [`error`]: Error types and handling
56//! - [`jsonrpc`]: JSON-RPC 2.0 types
57//!
58//! ## Example
59//!
60//! ```rust
61//! use turbomcp_core::types::{Tool, ToolInputSchema};
62//! use turbomcp_core::error::{McpError, ErrorKind};
63//!
64//! // Create a tool definition
65//! let tool = Tool {
66//! name: "calculator".into(),
67//! description: Some("Performs calculations".into()),
68//! input_schema: ToolInputSchema::default(),
69//! ..Default::default()
70//! };
71//! ```
72
73#![cfg_attr(not(feature = "std"), no_std)]
74#![warn(
75 missing_docs,
76 missing_debug_implementations,
77 rust_2018_idioms,
78 unreachable_pub
79)]
80#![cfg_attr(docsrs, feature(doc_cfg))]
81
82extern crate alloc;
83
84// Core modules - unified v3 architecture
85pub mod auth;
86pub mod context;
87pub mod error;
88pub mod handler;
89pub mod jsonrpc;
90pub mod marker;
91pub mod response;
92pub mod router;
93pub mod security;
94pub mod types;
95
96/// Zero-copy message types using rkyv serialization.
97///
98/// This module is only available when the `zero-copy` feature is enabled.
99/// It provides internal message types optimized for zero-copy deserialization.
100#[cfg(feature = "zero-copy")]
101#[cfg_attr(docsrs, doc(cfg(feature = "zero-copy")))]
102pub mod rkyv_types;
103
104// Re-export commonly used types at crate root
105pub use error::{ErrorKind, McpError, McpResult};
106pub use jsonrpc::{
107 // Strict typed API
108 JSONRPC_VERSION,
109 JsonRpcError,
110 JsonRpcErrorCode,
111 // Wire format types for routers/transports
112 JsonRpcIncoming,
113 JsonRpcNotification,
114 JsonRpcOutgoing,
115 JsonRpcRequest,
116 JsonRpcResponse,
117 JsonRpcVersion,
118 RequestId,
119 ResponseId,
120};
121pub use response::{Image, IntoToolError, IntoToolResponse, Json, Text, ToolError};
122pub use security::{
123 ALLOWED_URI_SCHEMES, DEFAULT_MAX_STRING_LENGTH, DEFAULT_MAX_URI_LENGTH, InputLimits,
124 InputValidationError, sanitize_error_message, validate_uri_scheme,
125};
126
127// Re-export unified v3 architecture types
128pub use auth::{
129 AuthError, Authenticator, Credential, CredentialExtractor, HeaderExtractor, JwtAlgorithm,
130 JwtConfig, Principal, StandardClaims,
131};
132pub use context::{RequestContext, TransportType};
133pub use handler::McpHandler;
134pub use marker::{MaybeSend, MaybeSync};
135
136// Re-export types from turbomcp-types for convenience
137pub use turbomcp_types::{
138 // Content types
139 Annotations,
140 AudioContent,
141 Content,
142 EmbeddedResource,
143 // Definition types
144 Icon,
145 ImageContent,
146 // Traits
147 IntoPromptResult,
148 IntoResourceResult,
149 IntoToolResult,
150 Message,
151 Prompt,
152 PromptArgument,
153 // Result types
154 PromptResult,
155 Resource,
156 ResourceAnnotations,
157 ResourceContents,
158 ResourceResult,
159 ResourceTemplate,
160 Role,
161 ServerInfo,
162 TextContent,
163 Tool,
164 ToolAnnotations,
165 ToolInputSchema,
166 ToolResult,
167};
168
169/// MCP Protocol version supported by this SDK (latest official spec).
170///
171/// This is the canonical version string. For typed usage, see
172/// [`types::core::ProtocolVersion::LATEST`].
173pub const PROTOCOL_VERSION: &str = "2025-11-25";
174
175/// Supported protocol version strings.
176///
177/// For typed usage, see [`types::core::ProtocolVersion::STABLE`].
178pub const SUPPORTED_VERSIONS: &[&str] = &["2025-06-18", "2025-11-25"];
179
180/// Maximum message size in bytes (1MB)
181pub const MAX_MESSAGE_SIZE: usize = 1024 * 1024;
182
183/// Default timeout for operations in milliseconds
184pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
185
186/// SDK version
187pub const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
188
189/// SDK name
190pub const SDK_NAME: &str = "turbomcp";
191
192/// Protocol feature constants
193pub mod features {
194 /// Tool calling capability
195 pub const TOOLS: &str = "tools";
196 /// Prompt capability
197 pub const PROMPTS: &str = "prompts";
198 /// Resource capability
199 pub const RESOURCES: &str = "resources";
200 /// Logging capability
201 pub const LOGGING: &str = "logging";
202 /// Progress notifications
203 pub const PROGRESS: &str = "progress";
204 /// Sampling capability
205 pub const SAMPLING: &str = "sampling";
206 /// Roots capability
207 pub const ROOTS: &str = "roots";
208}
209
210/// Protocol method names (single source of truth)
211pub mod methods {
212 // Initialization
213 /// Initialize handshake method
214 pub const INITIALIZE: &str = "initialize";
215 /// Initialized notification method
216 pub const INITIALIZED: &str = "notifications/initialized";
217
218 // Tools
219 /// List available tools method
220 pub const LIST_TOOLS: &str = "tools/list";
221 /// Call a specific tool method
222 pub const CALL_TOOL: &str = "tools/call";
223
224 // Prompts
225 /// List available prompts method
226 pub const LIST_PROMPTS: &str = "prompts/list";
227 /// Get a specific prompt method
228 pub const GET_PROMPT: &str = "prompts/get";
229
230 // Resources
231 /// List available resources method
232 pub const LIST_RESOURCES: &str = "resources/list";
233 /// Read a specific resource method
234 pub const READ_RESOURCE: &str = "resources/read";
235 /// Subscribe to resource updates method
236 pub const SUBSCRIBE: &str = "resources/subscribe";
237 /// Unsubscribe from resource updates method
238 pub const UNSUBSCRIBE: &str = "resources/unsubscribe";
239 /// Resource updated notification
240 pub const RESOURCE_UPDATED: &str = "notifications/resources/updated";
241 /// Resource list changed notification
242 pub const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
243
244 // Logging
245 /// Set logging level method
246 pub const SET_LEVEL: &str = "logging/setLevel";
247 /// Log message notification
248 pub const LOG_MESSAGE: &str = "notifications/message";
249
250 // Progress
251 /// Progress update notification
252 pub const PROGRESS: &str = "notifications/progress";
253
254 // Sampling
255 /// Create sampling message method
256 pub const CREATE_MESSAGE: &str = "sampling/createMessage";
257
258 // Roots
259 /// List directory roots method
260 pub const LIST_ROOTS: &str = "roots/list";
261 /// Roots list changed notification
262 pub const ROOTS_LIST_CHANGED: &str = "notifications/roots/list_changed";
263}
264
265/// Protocol error codes (JSON-RPC standard + MCP extensions)
266pub mod error_codes {
267 /// Parse error (-32700)
268 pub const PARSE_ERROR: i32 = -32700;
269 /// Invalid request (-32600)
270 pub const INVALID_REQUEST: i32 = -32600;
271 /// Method not found (-32601)
272 pub const METHOD_NOT_FOUND: i32 = -32601;
273 /// Invalid params (-32602)
274 pub const INVALID_PARAMS: i32 = -32602;
275 /// Internal error (-32603)
276 pub const INTERNAL_ERROR: i32 = -32603;
277 /// URL elicitation required (-32042)
278 pub const URL_ELICITATION_REQUIRED: i32 = -32042;
279 /// Tool not found (-32001)
280 pub const TOOL_NOT_FOUND: i32 = -32001;
281 /// Tool execution error (-32002)
282 pub const TOOL_EXECUTION_ERROR: i32 = -32002;
283 /// Prompt not found (-32003)
284 pub const PROMPT_NOT_FOUND: i32 = -32003;
285 /// Resource not found (-32004)
286 pub const RESOURCE_NOT_FOUND: i32 = -32004;
287 /// Resource access denied (-32005)
288 pub const RESOURCE_ACCESS_DENIED: i32 = -32005;
289 /// Capability not supported (-32006)
290 pub const CAPABILITY_NOT_SUPPORTED: i32 = -32006;
291 /// Protocol version mismatch (-32007)
292 pub const PROTOCOL_VERSION_MISMATCH: i32 = -32007;
293 /// Authentication required (-32008)
294 pub const AUTHENTICATION_REQUIRED: i32 = -32008;
295 /// Rate limited (-32009)
296 pub const RATE_LIMITED: i32 = -32009;
297 /// Server overloaded (-32010)
298 pub const SERVER_OVERLOADED: i32 = -32010;
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304
305 #[test]
306 fn test_version_constants() {
307 assert_eq!(PROTOCOL_VERSION, "2025-11-25");
308 assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
309 // Latest version is last in the list (oldest to newest)
310 assert_eq!(
311 SUPPORTED_VERSIONS[SUPPORTED_VERSIONS.len() - 1],
312 PROTOCOL_VERSION
313 );
314 }
315
316 #[test]
317 fn test_size_constants() {
318 assert_eq!(MAX_MESSAGE_SIZE, 1024 * 1024);
319 assert_eq!(DEFAULT_TIMEOUT_MS, 30_000);
320 }
321}