ultrafast_mcp/lib.rs
1//! # UltraFast MCP
2//!
3//! High-performance, ergonomic Model Context Protocol (MCP) implementation for Rust.
4//!
5//! This crate provides the primary APIs for building MCP servers and clients with
6//! exceptional performance, type safety, and developer experience. It implements
7//! the MCP 2025-06-18 specification with modern Rust patterns and async/await support.
8//!
9//! ## Overview
10//!
11//! UltraFast MCP is designed to be the definitive Rust implementation of the Model
12//! Context Protocol, providing:
13//!
14//! - **Ergonomic APIs**: Simple, intuitive interfaces for server and client 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//! - **Modern Rust**: Async/await, traits, and zero-cost abstractions
19//! - **Production Ready**: Comprehensive error handling, logging, and monitoring
20//!
21//! ## Primary APIs
22//!
23//! ### Server Development
24//! - **`UltraFastServer`**: Create MCP servers with ergonomic, type-safe APIs
25//! - **`ToolHandler`**: Implement tool functionality with trait-based interfaces
26//! - **`ResourceHandler`**: Manage resources and content delivery
27//! - **`PromptHandler`**: Generate dynamic prompts and content
28//!
29//! ### Client Development
30//! - **`UltraFastClient`**: Connect to MCP servers with async/await APIs
31//! - **`Transport`**: Flexible transport layer with HTTP, STDIO, and custom options
32//! - **`ResourceSubscriptionHandler`**: Handle resource updates and notifications
33//!
34//! ## Quick Start
35//!
36//! ### Creating an MCP Server
37//!
38//! ```rust,ignore
39//! #![cfg(feature = "core")]
40//! use ultrafast_mcp::{
41//! UltraFastServer, ToolHandler, ToolCall, ToolResult, ToolContent,
42//! ListToolsRequest, ListToolsResponse, ServerInfo, ServerCapabilities,
43//! ToolsCapability, MCPError, MCPResult
44//! };
45//! use ultrafast_mcp_core::Tool;
46//! use serde::{Deserialize, Serialize};
47//! use std::sync::Arc;
48//!
49//! // Define your tool input/output types
50//! #[derive(Deserialize)]
51//! struct GreetRequest {
52//! name: String,
53//! greeting: Option<String>,
54//! }
55//!
56//! #[derive(Serialize)]
57//! struct GreetResponse {
58//! message: String,
59//! timestamp: String,
60//! }
61//!
62//! // Implement the tool handler
63//! struct GreetToolHandler;
64//!
65//! #[async_trait::async_trait]
66//! impl ToolHandler for GreetToolHandler {
67//! async fn handle_tool_call(&self, call: ToolCall) -> MCPResult<ToolResult> {
68//! match call.name.as_str() {
69//! "greet" => {
70//! // Parse the arguments
71//! let args: GreetRequest = serde_json::from_value(
72//! call.arguments.unwrap_or_default()
73//! )?;
74//!
75//! // Generate the response
76//! let greeting = args.greeting.unwrap_or_else(|| "Hello".to_string());
77//! let message = format!("{}, {}!", greeting, args.name);
78//!
79//! Ok(ToolResult {
80//! content: vec![ToolContent::text(message)],
81//! is_error: Some(false),
82//! })
83//! }
84//! _ => Err(MCPError::method_not_found(
85//! format!("Unknown tool: {}", call.name)
86//! )),
87//! }
88//! }
89//!
90//! async fn list_tools(&self, _request: ListToolsRequest) -> MCPResult<ListToolsResponse> {
91//! Ok(ListToolsResponse {
92//! tools: vec![Tool {
93//! name: "greet".to_string(),
94//! description: "Greet a person by name".to_string(),
95//! input_schema: serde_json::json!({
96//! "type": "object",
97//! "properties": {
98//! "name": {"type": "string"},
99//! "greeting": {"type": "string", "default": "Hello"}
100//! },
101//! "required": ["name"]
102//! }),
103//! output_schema: None,
104//! }],
105//! next_cursor: None,
106//! })
107//! }
108//! }
109//!
110//! #[tokio::main]
111//! async fn main() -> anyhow::Result<()> {
112//! // Create server configuration
113//! let server_info = ServerInfo {
114//! name: "greeting-server".to_string(),
115//! version: "1.0.0".to_string(),
116//! description: Some("A simple greeting server".to_string()),
117//! authors: None,
118//! homepage: None,
119//! license: None,
120//! repository: None,
121//! };
122//!
123//! let capabilities = ServerCapabilities {
124//! tools: Some(ToolsCapability { list_changed: Some(true) }),
125//! ..Default::default()
126//! };
127//!
128//! // Create and configure the server
129//! let server = UltraFastServer::new(server_info, capabilities)
130//! .with_tool_handler(Arc::new(GreetToolHandler));
131//!
132//! // Start the server with STDIO transport
133//! server.run_stdio().await?;
134//!
135//! Ok(())
136//! }
137//! ```
138//!
139//! ### Creating an MCP Client
140//!
141//! ```rust,ignore
142//! #![cfg(feature = "core")]
143//! use ultrafast_mcp::{
144//! UltraFastClient, ClientInfo, ClientCapabilities, ToolCall, ToolResult
145//! };
146//! use serde_json::json;
147//!
148//! #[tokio::main]
149//! async fn main() -> anyhow::Result<()> {
150//! // Create client configuration
151//! let client_info = ClientInfo {
152//! name: "greeting-client".to_string(),
153//! version: "1.0.0".to_string(),
154//! authors: None,
155//! description: Some("A simple greeting client".to_string()),
156//! homepage: None,
157//! repository: None,
158//! license: None,
159//! };
160//!
161//! let capabilities = ClientCapabilities::default();
162//!
163//! // Create the client
164//! let client = UltraFastClient::new(client_info, capabilities);
165//!
166//! // Connect to the server using STDIO
167//! client.connect_stdio().await?;
168//!
169//! // Call a tool
170//! let tool_call = ToolCall {
171//! name: "greet".to_string(),
172//! arguments: Some(json!({
173//! "name": "Alice",
174//! "greeting": "Hello there"
175//! })),
176//! };
177//!
178//! let result = client.call_tool(tool_call).await?;
179//! println!("Server response: {:?}", result);
180//!
181//! // Disconnect
182//! client.disconnect().await?;
183//!
184//! Ok(())
185//! }
186//! ```
187//!
188//! ## Advanced Features
189//!
190//! ### Resource Management
191//!
192//! ```rust,ignore
193//! #![cfg(feature = "core")]
194//! use ultrafast_mcp::{ResourceHandler, ReadResourceRequest, ReadResourceResponse, MCPResult};
195//! use ultrafast_mcp_core::ResourceContent;
196//!
197//! struct FileResourceHandler;
198//!
199//! #[async_trait::async_trait]
200//! impl ResourceHandler for FileResourceHandler {
201//! async fn read_resource(&self, request: ReadResourceRequest) -> MCPResult<ReadResourceResponse> {
202//! // Implement file reading logic
203//! let content = std::fs::read_to_string(&request.uri)?;
204//!
205//! Ok(ReadResourceResponse {
206//! contents: vec![ResourceContent::text(request.uri.clone(), content)],
207//! })
208//! }
209//!
210//! async fn list_resources(&self, _request: ultrafast_mcp_core::types::resources::ListResourcesRequest) -> MCPResult<ultrafast_mcp_core::types::resources::ListResourcesResponse> {
211//! Ok(ultrafast_mcp_core::types::resources::ListResourcesResponse {
212//! resources: vec![],
213//! next_cursor: None,
214//! })
215//! }
216//!
217//! async fn list_resource_templates(&self, _request: ultrafast_mcp_core::types::resources::ListResourceTemplatesRequest) -> MCPResult<ultrafast_mcp_core::types::resources::ListResourceTemplatesResponse> {
218//! Ok(ultrafast_mcp_core::types::resources::ListResourceTemplatesResponse {
219//! resource_templates: vec![],
220//! next_cursor: None,
221//! })
222//! }
223//! }
224//! ```
225//!
226//! ### Progress Tracking
227//!
228//! ```rust,ignore
229//! #![cfg(feature = "core")]
230//! use ultrafast_mcp::{Context, MCPResult, MCPError};
231//!
232//! async fn long_running_operation(ctx: &Context) -> MCPResult<()> {
233//! for i in 0..100 {
234//! // Check for cancellation
235//! if ctx.is_cancelled().await {
236//! return Err(MCPError::request_timeout());
237//! }
238//!
239//! // Do work...
240//! tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
241//! }
242//!
243//! Ok(())
244//! }
245//! ```
246//!
247//! ### Transport Configuration
248//!
249//! ```rust,ignore
250//! #![cfg(all(feature = "core", feature = "stdio"))]
251//! use ultrafast_mcp::{TransportConfig, ClientInfo, ClientCapabilities};
252//!
253//! #[tokio::main]
254//! async fn main() -> anyhow::Result<()> {
255//! // Configure custom transport
256//! let transport_config = TransportConfig::Stdio;
257//!
258//! // Create client info
259//! let client_info = ClientInfo {
260//! name: "example-client".to_string(),
261//! version: "1.0.0".to_string(),
262//! authors: None,
263//! description: None,
264//! homepage: None,
265//! repository: None,
266//! license: None,
267//! };
268//! let capabilities = ClientCapabilities::default();
269//!
270//! // Note: Client implementation is available in ultrafast-mcp-client crate
271//!
272//! Ok(())
273//! }
274//! ```
275//!
276//! ## Architecture
277//!
278//! The crate is built on several foundational components:
279//!
280//! - **[`ultrafast-mcp-core`]**: Core protocol implementation and types
281//! - **[`ultrafast-mcp-server`]**: Server implementation and handler traits
282//! - **[`ultrafast-mcp-transport`]**: Transport layer with HTTP, STDIO, and custom options
283//! - **[`ultrafast-mcp-auth`]**: Authentication and authorization support
284//! - **[`ultrafast-mcp-monitoring`]**: Observability and monitoring capabilities
285//!
286//! ## Performance Characteristics
287//!
288//! - **High Throughput**: Optimized for handling thousands of requests per second
289//! - **Low Latency**: Sub-millisecond response times for simple operations
290//! - **Memory Efficient**: Minimal allocations and efficient data structures
291//! - **Scalable**: Designed for concurrent access and horizontal scaling
292//! - **Resource Aware**: Efficient resource usage and cleanup
293//!
294//! ## Transport Options
295//!
296//! ### Streamable HTTP (Recommended)
297//! - **Performance**: 10x faster than HTTP+SSE under load
298//! - **Compatibility**: Works with all HTTP proxies and load balancers
299//! - **Features**: Session management, authentication, compression
300//! - **Use Case**: Production deployments and high-performance scenarios
301//!
302//! ### HTTP+SSE (Legacy)
303//! - **Compatibility**: Backward compatibility with existing MCP implementations
304//! - **Features**: Server-sent events for real-time updates
305//! - **Use Case**: Legacy systems and gradual migration
306//!
307//! ### STDIO
308//! - **Performance**: Minimal overhead for local communication
309//! - **Security**: Process isolation and simple deployment
310//! - **Use Case**: Local development and simple integrations
311//!
312//! ## Error Handling
313//!
314//! The crate provides comprehensive error handling:
315//!
316//! ```rust,ignore
317//! #![cfg(feature = "core")]
318//! use ultrafast_mcp::{MCPError, MCPResult};
319//!
320//! async fn robust_operation() -> MCPResult<String> {
321//! // Simulate an operation that might fail
322//! let result = "success".to_string();
323//!
324//! match result.as_str() {
325//! "success" => Ok(result),
326//! _ => Err(MCPError::internal_error("Operation failed".to_string())),
327//! }
328//! }
329//! ```
330//!
331//! ## Monitoring and Observability
332//!
333//! ```rust
334//! #[cfg(feature = "monitoring")]
335//! use ultrafast_mcp::{MonitoringSystem, MonitoringConfig};
336//!
337//! #[cfg(feature = "monitoring")]
338//! async fn setup_monitoring() -> anyhow::Result<()> {
339//! let config = MonitoringConfig::default();
340//!
341//! let monitoring = MonitoringSystem::new(config);
342//!
343//! Ok(())
344//! }
345//! ```
346//!
347//! ## Best Practices
348//!
349//! ### Server Development
350//! - Use strongly-typed request/response structures
351//! - Implement proper error handling and recovery
352//! - Provide meaningful progress updates for long operations
353//! - Use appropriate transport options for your use case
354//! - Implement comprehensive logging and monitoring
355//!
356//! ### Client Development
357//! - Handle connection errors gracefully
358//! - Implement retry logic for transient failures
359//! - Use appropriate timeouts for operations
360//! - Validate responses before processing
361//! - Clean up resources properly
362//!
363//! ### Performance Optimization
364//! - Use Streamable HTTP for high-performance scenarios
365//! - Implement efficient resource management
366//! - Minimize allocations in hot paths
367//! - Use appropriate concurrency levels
368//! - Monitor and profile your applications
369//!
370//! ## Examples
371//!
372//! See the `examples/` directory for complete working examples:
373//! - Basic echo server and client
374//! - File operations with resource management
375//! - HTTP server with network operations
376//! - Advanced features with comprehensive MCP capabilities
377//!
378//! ## Contributing
379//!
380//! When contributing to this crate:
381//! - Follow the established patterns and conventions
382//! - Ensure comprehensive test coverage
383//! - Consider performance implications
384//! - Maintain backward compatibility
385//! - Update documentation for new features
386
387// =========================
388// Core Protocol and Types
389// =========================
390// Re-export core protocol types, errors, schema, and utilities
391#[cfg(feature = "core")]
392pub use ultrafast_mcp_core::{
393 // Re-export specific error types
394 MCPError,
395 MCPResult,
396 // Errors (re-export as McpCoreError to avoid conflicts)
397 error as McpCoreError,
398 // Protocol types
399 protocol,
400 // Schema
401 schema,
402 // Types
403 types,
404 // Utils
405 utils,
406};
407
408// Re-export utility functions from core
409#[cfg(feature = "core")]
410pub use ultrafast_mcp_core::utils::identifiers::{generate_session_id, generate_state};
411
412// Prelude module for convenient imports
413pub mod prelude;
414
415// Re-export commonly used types directly for convenience
416#[cfg(feature = "core")]
417pub use ultrafast_mcp_core::types::{
418 // Client types
419 client::{ClientCapabilities, ClientInfo},
420 // Completion types
421 completion::{CompleteRequest, CompleteResponse, Completion, CompletionValue},
422 // Elicitation types
423 elicitation::{ElicitationRequest, ElicitationResponse},
424 // Notification types
425 notifications::{LogLevel, PingResponse},
426 // Prompt types
427 prompts::{
428 GetPromptRequest, GetPromptResponse, ListPromptsRequest, ListPromptsResponse, Prompt,
429 PromptArgument, PromptContent, PromptMessages, PromptRole,
430 },
431 // Resource types
432 resources::{
433 ListResourcesRequest, ListResourcesResponse, ReadResourceRequest, ReadResourceResponse,
434 Resource, ResourceContent, ResourceTemplate,
435 },
436 // Roots types
437 roots::Root,
438 // Sampling types
439 sampling::{
440 CreateMessageRequest, CreateMessageResponse, ModelPreferences, SamplingContent,
441 SamplingRequest, SamplingResponse,
442 },
443 // Server types
444 server::{ServerCapabilities, ServerInfo},
445 // Tool types
446 tools::{
447 ListToolsRequest, ListToolsResponse, Tool, ToolAnnotations, ToolCall, ToolContent,
448 ToolResult,
449 },
450};
451
452// Re-export capability types from protocol
453#[cfg(feature = "core")]
454pub use ultrafast_mcp_core::protocol::capabilities::{
455 CompletionCapability, LoggingCapability, PromptsCapability, ResourcesCapability,
456 ToolsCapability,
457};
458
459// =========================
460// Server API
461// =========================
462// Use handler traits from server crate
463#[cfg(feature = "core")]
464#[cfg(not(doc))]
465pub use ultrafast_mcp_server::{
466 CompletionHandler, Context, ContextLogger, ElicitationHandler, LoggerConfig, PromptHandler,
467 ResourceHandler, ResourceSubscriptionHandler, RootsHandler, SamplingHandler,
468 ServerLoggingConfig, ServerState, ToolHandler, ToolRegistrationError, UltraFastServer,
469};
470
471// =========================
472// Client API
473// =========================
474#[cfg(feature = "core")]
475pub use ultrafast_mcp_client::{ClientElicitationHandler, UltraFastClient};
476
477// =========================
478// Transport Layer
479// =========================
480#[cfg(feature = "stdio")]
481pub use ultrafast_mcp_transport::{
482 Transport,
483 TransportConfig,
484 create_recovering_transport,
485 create_transport,
486 // Middleware (moved to streamable_http module)
487 streamable_http::middleware::{
488 LoggingMiddleware, MiddlewareTransport, ProgressMiddleware, RateLimitMiddleware,
489 TransportMiddleware, ValidationMiddleware,
490 },
491 // STDIO
492 stdio::StdioTransport,
493};
494
495// Streamable HTTP (feature = "http")
496#[cfg(feature = "http")]
497pub use ultrafast_mcp_transport::streamable_http;
498
499// Streamable HTTP (feature = "http")
500#[cfg(feature = "http")]
501pub use ultrafast_mcp_transport::streamable_http::{
502 HttpTransportConfig, HttpTransportServer, HttpTransportState, StreamableHttpClient,
503 StreamableHttpClientConfig, create_streamable_http_client_default,
504 create_streamable_http_client_with_middleware, create_streamable_http_server_default,
505 create_streamable_http_server_with_middleware,
506};
507
508// =========================
509// Authentication (feature = "oauth")
510// =========================
511#[cfg(feature = "oauth")]
512pub use ultrafast_mcp_auth::{
513 ApiKeyAuth,
514 AuthContext,
515 AuthError,
516 AuthMethod,
517 AuthResult,
518 AuthorizationServerMetadata,
519 BasicAuth,
520 BearerAuth,
521 ClientAuthMiddleware,
522 ClientRegistrationRequest,
523 ClientRegistrationResponse,
524 CustomHeaderAuth,
525 OAuthClient,
526 // Re-export specific types
527 OAuthConfig,
528 // Re-export as AuthConfig for convenience
529 OAuthConfig as AuthConfig,
530 PkceParams,
531 ServerAuthMiddleware,
532 TokenClaims,
533 TokenResponse,
534 TokenValidator,
535 // Re-export auth types (avoiding conflicts with core types)
536 error as McpAuthError,
537 extract_bearer_token,
538 generate_pkce_params,
539 oauth,
540 pkce,
541 types as AuthTypes,
542 validation,
543};
544
545// =========================
546// Monitoring (feature = "monitoring")
547// =========================
548#[cfg(feature = "monitoring")]
549pub use ultrafast_mcp_monitoring::{
550 MonitoringSystem,
551 config::MonitoringConfig,
552 // Re-export specific modules
553 exporters,
554 // Re-export monitoring types explicitly for better discoverability
555 health::{HealthCheck, HealthCheckResult, HealthChecker, HealthStatus},
556 metrics::{MetricsCollector, RequestMetrics, RequestTimer, SystemMetrics, TransportMetrics},
557 middleware,
558 tracing,
559};
560
561// =========================
562// Macros - REMOVED
563// =========================
564// Macros have been removed as they provided no immediate benefit
565// and were only stub implementations. The current API is already
566// ergonomic and production-ready.