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)
170pub const PROTOCOL_VERSION: &str = "2025-11-25";
171
172/// Supported protocol versions in preference order (latest first)
173pub const SUPPORTED_VERSIONS: &[&str] = &["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
174
175/// Maximum message size in bytes (1MB)
176pub const MAX_MESSAGE_SIZE: usize = 1024 * 1024;
177
178/// Default timeout for operations in milliseconds
179pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
180
181/// SDK version
182pub const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
183
184/// SDK name
185pub const SDK_NAME: &str = "turbomcp";
186
187/// Protocol feature constants
188pub mod features {
189 /// Tool calling capability
190 pub const TOOLS: &str = "tools";
191 /// Prompt capability
192 pub const PROMPTS: &str = "prompts";
193 /// Resource capability
194 pub const RESOURCES: &str = "resources";
195 /// Logging capability
196 pub const LOGGING: &str = "logging";
197 /// Progress notifications
198 pub const PROGRESS: &str = "progress";
199 /// Sampling capability
200 pub const SAMPLING: &str = "sampling";
201 /// Roots capability
202 pub const ROOTS: &str = "roots";
203}
204
205/// Protocol method names (single source of truth)
206pub mod methods {
207 // Initialization
208 /// Initialize handshake method
209 pub const INITIALIZE: &str = "initialize";
210 /// Initialized notification method
211 pub const INITIALIZED: &str = "notifications/initialized";
212
213 // Tools
214 /// List available tools method
215 pub const LIST_TOOLS: &str = "tools/list";
216 /// Call a specific tool method
217 pub const CALL_TOOL: &str = "tools/call";
218
219 // Prompts
220 /// List available prompts method
221 pub const LIST_PROMPTS: &str = "prompts/list";
222 /// Get a specific prompt method
223 pub const GET_PROMPT: &str = "prompts/get";
224
225 // Resources
226 /// List available resources method
227 pub const LIST_RESOURCES: &str = "resources/list";
228 /// Read a specific resource method
229 pub const READ_RESOURCE: &str = "resources/read";
230 /// Subscribe to resource updates method
231 pub const SUBSCRIBE: &str = "resources/subscribe";
232 /// Unsubscribe from resource updates method
233 pub const UNSUBSCRIBE: &str = "resources/unsubscribe";
234 /// Resource updated notification
235 pub const RESOURCE_UPDATED: &str = "notifications/resources/updated";
236 /// Resource list changed notification
237 pub const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
238
239 // Logging
240 /// Set logging level method
241 pub const SET_LEVEL: &str = "logging/setLevel";
242 /// Log message notification
243 pub const LOG_MESSAGE: &str = "notifications/message";
244
245 // Progress
246 /// Progress update notification
247 pub const PROGRESS: &str = "notifications/progress";
248
249 // Sampling
250 /// Create sampling message method
251 pub const CREATE_MESSAGE: &str = "sampling/createMessage";
252
253 // Roots
254 /// List directory roots method
255 pub const LIST_ROOTS: &str = "roots/list";
256 /// Roots list changed notification
257 pub const ROOTS_LIST_CHANGED: &str = "notifications/roots/list_changed";
258}
259
260/// Protocol error codes (JSON-RPC standard + MCP extensions)
261pub mod error_codes {
262 /// Parse error (-32700)
263 pub const PARSE_ERROR: i32 = -32700;
264 /// Invalid request (-32600)
265 pub const INVALID_REQUEST: i32 = -32600;
266 /// Method not found (-32601)
267 pub const METHOD_NOT_FOUND: i32 = -32601;
268 /// Invalid params (-32602)
269 pub const INVALID_PARAMS: i32 = -32602;
270 /// Internal error (-32603)
271 pub const INTERNAL_ERROR: i32 = -32603;
272 /// URL elicitation required (-32042)
273 pub const URL_ELICITATION_REQUIRED: i32 = -32042;
274 /// Tool not found (-32001)
275 pub const TOOL_NOT_FOUND: i32 = -32001;
276 /// Tool execution error (-32002)
277 pub const TOOL_EXECUTION_ERROR: i32 = -32002;
278 /// Prompt not found (-32003)
279 pub const PROMPT_NOT_FOUND: i32 = -32003;
280 /// Resource not found (-32004)
281 pub const RESOURCE_NOT_FOUND: i32 = -32004;
282 /// Resource access denied (-32005)
283 pub const RESOURCE_ACCESS_DENIED: i32 = -32005;
284 /// Capability not supported (-32006)
285 pub const CAPABILITY_NOT_SUPPORTED: i32 = -32006;
286 /// Protocol version mismatch (-32007)
287 pub const PROTOCOL_VERSION_MISMATCH: i32 = -32007;
288 /// Authentication required (-32008)
289 pub const AUTHENTICATION_REQUIRED: i32 = -32008;
290 /// Rate limited (-32009)
291 pub const RATE_LIMITED: i32 = -32009;
292 /// Server overloaded (-32010)
293 pub const SERVER_OVERLOADED: i32 = -32010;
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 #[test]
301 fn test_version_constants() {
302 assert_eq!(PROTOCOL_VERSION, "2025-11-25");
303 assert!(SUPPORTED_VERSIONS.contains(&PROTOCOL_VERSION));
304 assert_eq!(SUPPORTED_VERSIONS[0], PROTOCOL_VERSION);
305 }
306
307 #[test]
308 fn test_size_constants() {
309 assert_eq!(MAX_MESSAGE_SIZE, 1024 * 1024);
310 assert_eq!(DEFAULT_TIMEOUT_MS, 30_000);
311 }
312}