ultrafast_mcp_server/lib.rs
1//! # UltraFast MCP Server
2//!
3//! High-performance server implementation for the Model Context Protocol (MCP).
4//!
5//! This crate provides a complete, production-ready server implementation for the MCP
6//! 2025-06-18 specification. It offers ergonomic APIs, comprehensive error handling,
7//! and high-performance characteristics suitable for both development and production use.
8//!
9//! ## Overview
10//!
11//! The UltraFast MCP Server is designed to be the definitive server implementation
12//! for the Model Context Protocol, providing:
13//!
14//! - **Ergonomic APIs**: Simple, intuitive interfaces for server development
15//! - **Type Safety**: Compile-time guarantees for protocol compliance
16//! - **High Performance**: Optimized for throughput and low latency
17//! - **Full Feature Support**: Complete MCP specification implementation
18//! - **Production Ready**: Comprehensive error handling, logging, and monitoring
19//! - **Extensible Architecture**: Modular design for easy customization
20//!
21//! ## Key Features
22//!
23//! ### Core Server Functionality
24//! - **Lifecycle Management**: Connection initialization, shutdown, and state management
25//! - **Capability Negotiation**: Feature discovery and negotiation with clients
26//! - **Message Handling**: Request/response/notification processing
27//! - **Error Handling**: Comprehensive error types and recovery mechanisms
28//! - **State Management**: Thread-safe server state and context management
29//!
30//! ### Handler System
31//! - **Tool Handler**: Execute tools and provide results
32//! - **Resource Handler**: Manage resources and content delivery
33//! - **Prompt Handler**: Generate dynamic prompts and content
34//! - **Sampling Handler**: LLM sampling and message generation
35//! - **Completion Handler**: Autocompletion and suggestion support
36//! - **Elicitation Handler**: User input collection and validation
37//! - **Roots Handler**: Filesystem boundary management
38//!
39//! ### Transport Support
40//! - **STDIO Transport**: Local communication with minimal overhead
41//! - **HTTP Transport**: Web-based communication with OAuth support
42//! - **Streamable HTTP**: High-performance HTTP transport (recommended)
43//! - **Custom Transport**: Extensible transport layer architecture
44//!
45//! ## Architecture
46//!
47//! The server is built around several core components:
48//!
49//! ```text
50//! ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
51//! │ Transport │ │ Protocol │ │ Handlers │
52//! │ Layer │◄──►│ Protocol │◄──►│ Layer │
53//! └─────────────────┘ └─────────────────┘ └─────────────────┘
54//! │ │ │
55//! │ │ │
56//! ▼ ▼ ▼
57//! ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
58//! │ Context │ │ State │ │ Utilities │
59//! │ Management │ │ Management │ │ & Helpers │
60//! └─────────────────┘ └─────────────────┘ └─────────────────┘
61//! ```
62//!
63//! ## Modules
64//!
65//! - **[`server`]**: Core server implementation and state management
66//! - **[`handlers`]**: Trait definitions for all handler types
67//! - **[`context`]**: Context management for request processing
68//!
69//! ## Usage Examples
70//!
71//! ### Basic Server Setup
72//!
73//! ```rust,ignore
74//! use ultrafast_mcp_server::{UltraFastServer, ToolHandler};
75//! use ultrafast_mcp_core::types::tools::{ToolCall, ToolResult, ToolContent, Tool, ListToolsRequest, ListToolsResponse};
76//! use ultrafast_mcp_core::types::server::ServerInfo;
77//! use ultrafast_mcp_core::protocol::capabilities::{ServerCapabilities, ToolsCapability};
78//! use ultrafast_mcp_core::error::{MCPError, MCPResult};
79//! use std::sync::Arc;
80//! // Add anyhow as a dev-dependency for doctests
81//! // [dev-dependencies]
82//! // anyhow = "1"
83//!
84//! struct MyToolHandler;
85//!
86//! #[async_trait::async_trait]
87//! impl ToolHandler for MyToolHandler {
88//! async fn handle_tool_call(&self, call: ToolCall) -> MCPResult<ToolResult> {
89//! match call.name.as_str() {
90//! "echo" => {
91//! let message = call.arguments
92//! .and_then(|args| args.get("message").cloned())
93//! .and_then(|v| v.as_str().map(|s| s.to_string()))
94//! .unwrap_or_else(|| "Hello, World!".to_string());
95//! Ok(ToolResult {
96//! content: vec![ToolContent::text(message)],
97//! is_error: Some(false),
98//! })
99//! }
100//! _ => Err(MCPError::method_not_found(
101//! format!("Unknown tool: {}", call.name)
102//! )),
103//! }
104//! }
105//! async fn list_tools(&self, _request: ListToolsRequest) -> MCPResult<ListToolsResponse> {
106//! Ok(ListToolsResponse {
107//! tools: vec![Tool {
108//! name: "echo".to_string(),
109//! description: "Echo a message back".to_string(),
110//! input_schema: serde_json::json!({
111//! "type": "object",
112//! "properties": {
113//! "message": {"type": "string", "default": "Hello, World!"}
114//! },
115//! "required": ["message"]
116//! }),
117//! output_schema: Some(serde_json::json!({
118//! "type": "object",
119//! "properties": {
120//! "output": {"type": "string"}
121//! }
122//! })),
123//! annotations: None,
124//! }],
125//! next_cursor: None,
126//! })
127//! }
128//! }
129//!
130//! #[tokio::main]
131//! async fn main() -> anyhow::Result<()> {
132//! let server_info = ServerInfo {
133//! name: "example-server".to_string(),
134//! version: "1.0.0".to_string(),
135//! description: Some("An example MCP server".to_string()),
136//! authors: None,
137//! homepage: None,
138//! license: None,
139//! repository: None,
140//! };
141//! let capabilities = ServerCapabilities {
142//! tools: Some(ToolsCapability { list_changed: Some(true) }),
143//! ..Default::default()
144//! };
145//! let server = UltraFastServer::new(server_info, capabilities)
146//! .with_tool_handler(Arc::new(MyToolHandler));
147//! // Start the server with STDIO transport
148//! server.run_stdio().await?;
149//! Ok(())
150//! }
151//! ```
152//!
153//! ### Advanced Server with Multiple Handlers
154//!
155//! ```rust,ignore
156//! use ultrafast_mcp_server::{UltraFastServer, ToolHandler, ResourceHandler, PromptHandler};
157//! use ultrafast_mcp_core::types::tools::{ToolCall, ToolResult, ListToolsRequest, ListToolsResponse, ToolContent};
158//! use ultrafast_mcp_core::types::resources::{ReadResourceRequest, ReadResourceResponse};
159//! use ultrafast_mcp_core::types::prompts::{GetPromptRequest, GetPromptResponse};
160//! use ultrafast_mcp_core::error::{MCPError, MCPResult};
161//! use std::sync::Arc;
162//!
163//! struct AdvancedToolHandler;
164//!
165//! #[async_trait::async_trait]
166//! impl ToolHandler for AdvancedToolHandler {
167//! async fn handle_tool_call(&self, _call: ToolCall) -> MCPResult<ToolResult> {
168//! Ok(ToolResult {
169//! content: vec![ToolContent::text("Tool executed successfully".to_string())],
170//! is_error: Some(false),
171//! })
172//! }
173//! async fn list_tools(&self, _request: ListToolsRequest) -> MCPResult<ListToolsResponse> {
174//! Ok(ListToolsResponse {
175//! tools: vec![],
176//! next_cursor: None,
177//! })
178//! }
179//! }
180//!
181//! struct FileResourceHandler;
182//!
183//! #[async_trait::async_trait]
184//! impl ResourceHandler for FileResourceHandler {
185//! async fn read_resource(&self, _request: ReadResourceRequest) -> MCPResult<ReadResourceResponse> {
186//! Ok(ReadResourceResponse {
187//! contents: vec![],
188//! })
189//! }
190//! async fn list_resources(&self, _request: ultrafast_mcp_core::types::resources::ListResourcesRequest) -> MCPResult<ultrafast_mcp_core::types::resources::ListResourcesResponse> {
191//! Ok(ultrafast_mcp_core::types::resources::ListResourcesResponse {
192//! resources: vec![],
193//! next_cursor: None,
194//! })
195//! }
196//! async fn list_resource_templates(&self, _request: ultrafast_mcp_core::types::resources::ListResourceTemplatesRequest) -> MCPResult<ultrafast_mcp_core::types::resources::ListResourceTemplatesResponse> {
197//! Ok(ultrafast_mcp_core::types::resources::ListResourceTemplatesResponse {
198//! resource_templates: vec![],
199//! next_cursor: None,
200//! })
201//! }
202//! async fn validate_resource_access(&self, _uri: &str, _operation: ultrafast_mcp_core::types::roots::RootOperation, _roots: &[ultrafast_mcp_core::types::roots::Root]) -> MCPResult<()> {
203//! Ok(())
204//! }
205//! }
206//!
207//! struct TemplatePromptHandler;
208//!
209//! #[async_trait::async_trait]
210//! impl PromptHandler for TemplatePromptHandler {
211//! async fn get_prompt(&self, _request: GetPromptRequest) -> MCPResult<GetPromptResponse> {
212//! Ok(GetPromptResponse {
213//! description: None,
214//! messages: vec![],
215//! })
216//! }
217//! async fn list_prompts(&self, _request: ultrafast_mcp_core::types::prompts::ListPromptsRequest) -> MCPResult<ultrafast_mcp_core::types::prompts::ListPromptsResponse> {
218//! Ok(ultrafast_mcp_core::types::prompts::ListPromptsResponse {
219//! prompts: vec![],
220//! next_cursor: None,
221//! })
222//! }
223//! }
224//!
225//! #[tokio::main]
226//! async fn main() -> anyhow::Result<()> {
227//! let server_info = ultrafast_mcp_core::types::server::ServerInfo {
228//! name: "example-server".to_string(),
229//! version: "1.0.0".to_string(),
230//! description: Some("An example MCP server".to_string()),
231//! authors: None,
232//! homepage: None,
233//! license: None,
234//! repository: None,
235//! };
236//! let capabilities = ultrafast_mcp_core::protocol::capabilities::ServerCapabilities::default();
237//! let server = UltraFastServer::new(server_info, capabilities)
238//! .with_tool_handler(Arc::new(AdvancedToolHandler))
239//! .with_resource_handler(Arc::new(FileResourceHandler))
240//! .with_prompt_handler(Arc::new(TemplatePromptHandler));
241//! // Start with STDIO transport (or replace with HTTP if available)
242//! server.run_stdio().await?;
243//! Ok(())
244//! }
245//! ```
246//!
247//! ### Context and Progress Tracking
248//!
249//! ```rust
250//! use ultrafast_mcp_server::{Context};
251//! use ultrafast_mcp_core::utils::ProgressTracker;
252//! use ultrafast_mcp_core::error::{MCPError, MCPResult};
253//!
254//! async fn long_running_operation(ctx: &Context) -> MCPResult<()> {
255//! let mut progress = ProgressTracker::new();
256//! for i in 0..100 {
257//! progress.update(&format!("Processing item {}", i), i);
258//! if ctx.is_cancelled().await {
259//! return Err(MCPError::request_timeout());
260//! }
261//! tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
262//! }
263//! progress.complete("All items processed");
264//! Ok(())
265//! }
266//! ```
267//!
268//! ## Server States
269//!
270//! The server operates in several distinct states:
271//!
272//! - **Uninitialized**: Server created but not yet connected
273//! - **Initializing**: Protocol negotiation in progress
274//! - **Initialized**: Ready for normal operation
275//! - **Shutdown**: Connection termination in progress
276//!
277//! ## Handler System
278//!
279//! The server uses a trait-based handler system for extensibility:
280//!
281//! ### Tool Handler
282//! Handles tool execution requests and provides results:
283//! - `handle_tool_call`: Execute a specific tool with parameters
284//! - `list_tools`: Provide available tools and their schemas
285//!
286//! ### Resource Handler
287//! Manages resource access and content delivery:
288//! - `read_resource`: Read resource content by URI
289//! - `list_resources`: List available resources
290//! - `list_resource_templates`: Provide resource templates
291//!
292//! ### Prompt Handler
293//! Generates dynamic prompts and content:
294//! - `get_prompt`: Generate a prompt with arguments
295//! - `list_prompts`: List available prompts
296//!
297//! ### Additional Handlers
298//! - **Sampling Handler**: LLM sampling and message generation
299//! - **Completion Handler**: Autocompletion and suggestions
300//! - **Elicitation Handler**: User input collection
301//! - **Roots Handler**: Filesystem boundary management
302//!
303//! ## Error Handling
304//!
305//! The server provides comprehensive error handling:
306//!
307//! - **Protocol Errors**: Invalid requests, unsupported methods
308//! - **Handler Errors**: Tool execution failures, resource access issues
309//! - **Transport Errors**: Connection failures, timeout issues
310//! - **Internal Errors**: Server implementation issues
311//!
312//! ## Performance Considerations
313//!
314//! - **Concurrent Processing**: Multiple requests processed simultaneously
315//! - **Efficient Memory Usage**: Minimal allocations in hot paths
316//! - **Optimized Serialization**: Fast JSON serialization/deserialization
317//! - **Resource Management**: Efficient cleanup and resource reuse
318//! - **Caching**: Intelligent caching of frequently accessed data
319//!
320//! ## Thread Safety
321//!
322//! All server components are designed to be thread-safe:
323//! - Handler implementations must be `Send + Sync`
324//! - Server state is protected by appropriate synchronization
325//! - Concurrent access to shared resources is safe
326//! - No mutable global state is used
327//!
328//! ## Monitoring and Observability
329//!
330//! The server supports comprehensive monitoring:
331//!
332//! - **Metrics**: Request counts, response times, error rates
333//! - **Logging**: Structured logging with different levels
334//! - **Tracing**: Distributed tracing for request flows
335//! - **Health Checks**: Server health and readiness endpoints
336//!
337//! ## Best Practices
338//!
339//! ### Handler Implementation
340//! - Implement proper error handling and recovery
341//! - Provide meaningful error messages
342//! - Use appropriate timeouts for operations
343//! - Implement progress tracking for long operations
344//! - Handle cancellation requests gracefully
345//!
346//! ### Performance Optimization
347//! - Use efficient data structures and algorithms
348//! - Minimize allocations in hot paths
349//! - Implement appropriate caching strategies
350//! - Use async/await for I/O operations
351//! - Profile and optimize critical paths
352//!
353//! ### Security Considerations
354//! - Validate all input parameters
355//! - Implement proper access controls
356//! - Use secure transport options
357//! - Handle sensitive data appropriately
358//! - Implement rate limiting where appropriate
359//!
360//! ## Examples
361//!
362//! See the `examples/` directory for complete working examples:
363//! - Basic echo server
364//! - File operations server
365//! - HTTP operations server
366//! - Advanced features server
367
368pub mod context;
369pub mod handlers;
370pub mod server;
371
372pub use context::{Context, ContextLogger, LoggerConfig};
373pub use handlers::*;
374/// All re-exports for convenience
375pub use server::{ServerLoggingConfig, ServerState, ToolRegistrationError, UltraFastServer};
376
377// Re-export transport types for convenience
378pub use ultrafast_mcp_transport::{Transport, TransportConfig, create_transport};
379
380#[cfg(feature = "http")]
381pub use ultrafast_mcp_transport::streamable_http::server::HttpTransportConfig;
382
383#[cfg(feature = "monitoring")]
384pub use ultrafast_mcp_monitoring::metrics::RequestTimer;
385#[cfg(feature = "monitoring")]
386pub use ultrafast_mcp_monitoring::{HealthStatus, MonitoringConfig, MonitoringSystem};
387
388pub use ultrafast_mcp_core::{
389 error::{MCPError, MCPResult},
390 protocol::{
391 capabilities::ServerCapabilities,
392 jsonrpc::{JsonRpcError, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse},
393 },
394 types::{
395 completion::{CompleteRequest, CompleteResponse},
396 elicitation::{ElicitationRequest, ElicitationResponse},
397 notifications::{
398 CancelledNotification, LogLevel, LogLevelSetRequest, LogLevelSetResponse,
399 LoggingMessageNotification, PingRequest, ProgressNotification,
400 },
401 prompts::{
402 GetPromptRequest, GetPromptResponse, ListPromptsRequest, ListPromptsResponse, Prompt,
403 },
404 resources::{
405 ListResourceTemplatesRequest, ListResourceTemplatesResponse, ListResourcesRequest,
406 ListResourcesResponse, ReadResourceRequest, ReadResourceResponse, Resource,
407 ResourceTemplate,
408 },
409 roots::Root,
410 sampling::{CreateMessageRequest, CreateMessageResponse},
411 server::ServerInfo,
412 tools::{ListToolsRequest, ListToolsResponse, Tool, ToolCall, ToolResult},
413 },
414 utils::{CancellationManager, PingManager},
415};