Expand description
§UltraFast MCP
High-performance, ergonomic Model Context Protocol (MCP) implementation for Rust.
This crate provides the primary APIs for building MCP servers and clients with exceptional performance, type safety, and developer experience. It implements the MCP 2025-06-18 specification with modern Rust patterns and async/await support.
§Overview
UltraFast MCP is designed to be the definitive Rust implementation of the Model Context Protocol, providing:
- Ergonomic APIs: Simple, intuitive interfaces for server and client development
- Type Safety: Compile-time guarantees for protocol compliance
- High Performance: Optimized for throughput and low latency
- Full Feature Support: Complete MCP specification implementation
- Modern Rust: Async/await, traits, and zero-cost abstractions
- Production Ready: Comprehensive error handling, logging, and monitoring
§Primary APIs
§Server Development
UltraFastServer: Create MCP servers with ergonomic, type-safe APIsToolHandler: Implement tool functionality with trait-based interfacesResourceHandler: Manage resources and content deliveryPromptHandler: Generate dynamic prompts and content
§Client Development
UltraFastClient: Connect to MCP servers with async/await APIsTransport: Flexible transport layer with HTTP, STDIO, and custom optionsResourceSubscriptionHandler: Handle resource updates and notifications
§Quick Start
§Creating an MCP Server
ⓘ
#![cfg(feature = "core")]
use ultrafast_mcp::{
UltraFastServer, ToolHandler, ToolCall, ToolResult, ToolContent,
ListToolsRequest, ListToolsResponse, ServerInfo, ServerCapabilities,
ToolsCapability, MCPError, MCPResult
};
use ultrafast_mcp_core::Tool;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
// Define your tool input/output types
#[derive(Deserialize)]
struct GreetRequest {
name: String,
greeting: Option<String>,
}
#[derive(Serialize)]
struct GreetResponse {
message: String,
timestamp: String,
}
// Implement the tool handler
struct GreetToolHandler;
#[async_trait::async_trait]
impl ToolHandler for GreetToolHandler {
async fn handle_tool_call(&self, call: ToolCall) -> MCPResult<ToolResult> {
match call.name.as_str() {
"greet" => {
// Parse the arguments
let args: GreetRequest = serde_json::from_value(
call.arguments.unwrap_or_default()
)?;
// Generate the response
let greeting = args.greeting.unwrap_or_else(|| "Hello".to_string());
let message = format!("{}, {}!", greeting, args.name);
Ok(ToolResult {
content: vec![ToolContent::text(message)],
is_error: Some(false),
})
}
_ => Err(MCPError::method_not_found(
format!("Unknown tool: {}", call.name)
)),
}
}
async fn list_tools(&self, _request: ListToolsRequest) -> MCPResult<ListToolsResponse> {
Ok(ListToolsResponse {
tools: vec![Tool {
name: "greet".to_string(),
description: "Greet a person by name".to_string(),
input_schema: serde_json::json!({
"type": "object",
"properties": {
"name": {"type": "string"},
"greeting": {"type": "string", "default": "Hello"}
},
"required": ["name"]
}),
output_schema: None,
}],
next_cursor: None,
})
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Create server configuration
let server_info = ServerInfo {
name: "greeting-server".to_string(),
version: "1.0.0".to_string(),
description: Some("A simple greeting server".to_string()),
authors: None,
homepage: None,
license: None,
repository: None,
};
let capabilities = ServerCapabilities {
tools: Some(ToolsCapability { list_changed: Some(true) }),
..Default::default()
};
// Create and configure the server
let server = UltraFastServer::new(server_info, capabilities)
.with_tool_handler(Arc::new(GreetToolHandler));
// Start the server with STDIO transport
server.run_stdio().await?;
Ok(())
}§Creating an MCP Client
ⓘ
#![cfg(feature = "core")]
use ultrafast_mcp::{
UltraFastClient, ClientInfo, ClientCapabilities, ToolCall, ToolResult
};
use serde_json::json;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Create client configuration
let client_info = ClientInfo {
name: "greeting-client".to_string(),
version: "1.0.0".to_string(),
authors: None,
description: Some("A simple greeting client".to_string()),
homepage: None,
repository: None,
license: None,
};
let capabilities = ClientCapabilities::default();
// Create the client
let client = UltraFastClient::new(client_info, capabilities);
// Connect to the server using STDIO
client.connect_stdio().await?;
// Call a tool
let tool_call = ToolCall {
name: "greet".to_string(),
arguments: Some(json!({
"name": "Alice",
"greeting": "Hello there"
})),
};
let result = client.call_tool(tool_call).await?;
println!("Server response: {:?}", result);
// Disconnect
client.disconnect().await?;
Ok(())
}§Advanced Features
§Resource Management
ⓘ
#![cfg(feature = "core")]
use ultrafast_mcp::{ResourceHandler, ReadResourceRequest, ReadResourceResponse, MCPResult};
use ultrafast_mcp_core::ResourceContent;
struct FileResourceHandler;
#[async_trait::async_trait]
impl ResourceHandler for FileResourceHandler {
async fn read_resource(&self, request: ReadResourceRequest) -> MCPResult<ReadResourceResponse> {
// Implement file reading logic
let content = std::fs::read_to_string(&request.uri)?;
Ok(ReadResourceResponse {
contents: vec![ResourceContent::text(request.uri.clone(), content)],
})
}
async fn list_resources(&self, _request: ultrafast_mcp_core::types::resources::ListResourcesRequest) -> MCPResult<ultrafast_mcp_core::types::resources::ListResourcesResponse> {
Ok(ultrafast_mcp_core::types::resources::ListResourcesResponse {
resources: vec![],
next_cursor: None,
})
}
async fn list_resource_templates(&self, _request: ultrafast_mcp_core::types::resources::ListResourceTemplatesRequest) -> MCPResult<ultrafast_mcp_core::types::resources::ListResourceTemplatesResponse> {
Ok(ultrafast_mcp_core::types::resources::ListResourceTemplatesResponse {
resource_templates: vec![],
next_cursor: None,
})
}
}§Progress Tracking
ⓘ
#![cfg(feature = "core")]
use ultrafast_mcp::{Context, MCPResult, MCPError};
async fn long_running_operation(ctx: &Context) -> MCPResult<()> {
for i in 0..100 {
// Check for cancellation
if ctx.is_cancelled().await {
return Err(MCPError::request_timeout());
}
// Do work...
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
}
Ok(())
}§Transport Configuration
ⓘ
#![cfg(all(feature = "core", feature = "stdio"))]
use ultrafast_mcp::{TransportConfig, ClientInfo, ClientCapabilities};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Configure custom transport
let transport_config = TransportConfig::Stdio;
// Create client info
let client_info = ClientInfo {
name: "example-client".to_string(),
version: "1.0.0".to_string(),
authors: None,
description: None,
homepage: None,
repository: None,
license: None,
};
let capabilities = ClientCapabilities::default();
// Note: Client implementation is available in ultrafast-mcp-client crate
Ok(())
}§Architecture
The crate is built on several foundational components:
- [
ultrafast-mcp-core]: Core protocol implementation and types - [
ultrafast-mcp-server]: Server implementation and handler traits - [
ultrafast-mcp-transport]: Transport layer with HTTP, STDIO, and custom options - [
ultrafast-mcp-auth]: Authentication and authorization support - [
ultrafast-mcp-monitoring]: Observability and monitoring capabilities
§Performance Characteristics
- High Throughput: Optimized for handling thousands of requests per second
- Low Latency: Sub-millisecond response times for simple operations
- Memory Efficient: Minimal allocations and efficient data structures
- Scalable: Designed for concurrent access and horizontal scaling
- Resource Aware: Efficient resource usage and cleanup
§Transport Options
§Streamable HTTP (Recommended)
- Performance: 10x faster than HTTP+SSE under load
- Compatibility: Works with all HTTP proxies and load balancers
- Features: Session management, authentication, compression
- Use Case: Production deployments and high-performance scenarios
§HTTP+SSE (Legacy)
- Compatibility: Backward compatibility with existing MCP implementations
- Features: Server-sent events for real-time updates
- Use Case: Legacy systems and gradual migration
§STDIO
- Performance: Minimal overhead for local communication
- Security: Process isolation and simple deployment
- Use Case: Local development and simple integrations
§Error Handling
The crate provides comprehensive error handling:
ⓘ
#![cfg(feature = "core")]
use ultrafast_mcp::{MCPError, MCPResult};
async fn robust_operation() -> MCPResult<String> {
// Simulate an operation that might fail
let result = "success".to_string();
match result.as_str() {
"success" => Ok(result),
_ => Err(MCPError::internal_error("Operation failed".to_string())),
}
}§Monitoring and Observability
#[cfg(feature = "monitoring")]
use ultrafast_mcp::{MonitoringSystem, MonitoringConfig};
#[cfg(feature = "monitoring")]
async fn setup_monitoring() -> anyhow::Result<()> {
let config = MonitoringConfig::default();
let monitoring = MonitoringSystem::new(config);
Ok(())
}§Best Practices
§Server Development
- Use strongly-typed request/response structures
- Implement proper error handling and recovery
- Provide meaningful progress updates for long operations
- Use appropriate transport options for your use case
- Implement comprehensive logging and monitoring
§Client Development
- Handle connection errors gracefully
- Implement retry logic for transient failures
- Use appropriate timeouts for operations
- Validate responses before processing
- Clean up resources properly
§Performance Optimization
- Use Streamable HTTP for high-performance scenarios
- Implement efficient resource management
- Minimize allocations in hot paths
- Use appropriate concurrency levels
- Monitor and profile your applications
§Examples
See the examples/ directory for complete working examples:
- Basic echo server and client
- File operations with resource management
- HTTP server with network operations
- Advanced features with comprehensive MCP capabilities
§Contributing
When contributing to this crate:
- Follow the established patterns and conventions
- Ensure comprehensive test coverage
- Consider performance implications
- Maintain backward compatibility
- Update documentation for new features
Modules§
- Auth
Types - McpAuth
Error - McpCore
Error - Error handling for UltraFast MCP Core
- exporters
- Metric and trace exporters for UltraFast MCP
- middleware
- Monitoring middleware for HTTP and transport layers
- oauth
- pkce
- prelude
- The ultrafast-mcp prelude.
- protocol
- Protocol Module
- schema
- JSON Schema generation and validation for the Model Context Protocol (MCP).
- streamable_
http - Streamable HTTP transport implementation
- tracing
- Distributed tracing and OpenTelemetry integration for UltraFast MCP
- types
- Types Module
- utils
- Utilities Module
- validation
Structs§
- ApiKey
Auth - API Key authentication
- Auth
Config - OAuth 2.1 configuration
- Auth
Context - Authentication context for requests
- Authorization
Server Metadata - Authorization server metadata (RFC 8414)
- Basic
Auth - Basic authentication
- Bearer
Auth - Bearer token authentication
- Client
Auth Middleware - Client-side authentication middleware
- Client
Capabilities - Client capabilities that can be negotiated during initialization
- Client
Info - Client information
- Client
Registration Request - Client registration request (RFC 7591)
- Client
Registration Response - Client registration response (RFC 7591)
- Complete
Request - Completion request (MCP 2025-06-18 compliant)
- Complete
Response - Completion response
- Completion
- Completion result set
- Completion
Capability - Completion capability for argument autocompletion
- Completion
Value - Individual completion value
- Custom
Header Auth - Custom header authentication
- Elicitation
Request - Server-initiated request for user input
- Elicitation
Response - User response to elicitation request
- GetPrompt
Request - Get prompt request
- GetPrompt
Response - Get prompt response
- Health
Check Result - Result of a health check
- Health
Checker - Health checker for managing multiple health checks
- Http
Transport Config - HTTP transport configuration
- Http
Transport Server - HTTP transport server implementation
- Http
Transport State - Shared state for HTTP transport
- List
Prompts Request - List prompts request
- List
Prompts Response - List prompts response
- List
Resources Request - List
Resources Response - List resources response
- List
Tools Request - List tools request
- List
Tools Response - List tools response
- Logging
Capability - Logging capability
- Logging
Middleware - Logging middleware for request/response tracking
- Metrics
Collector - Metrics collector for gathering and managing metrics
- Middleware
Transport - Transport wrapper that applies middleware
- Model
Preferences - Model preferences for sampling
- Monitoring
Config - Main monitoring configuration
- Monitoring
System - The main monitoring system that orchestrates all monitoring components
- OAuth
Client - OAuth 2.1 client for server discovery and registration
- OAuth
Config - OAuth 2.1 configuration
- Ping
Response - Ping response for connection health monitoring
- Pkce
Params - PKCE parameters for OAuth 2.1
- Progress
Middleware - Progress tracking middleware with improved error handling
- Prompt
- Prompt definition
- Prompt
Argument - Prompt argument definition
- Prompt
Messages - Helper for building prompt messages
- Prompts
Capability - Prompts capability
- Rate
Limit Middleware - Rate limiting middleware with improved error handling
- Read
Resource Request - Read
Resource Response - Read resource response
- Request
Metrics - Request-related metrics
- Request
Timer - Timer for measuring request duration
- Resource
- Resource definition
- Resource
Template - Resource template definition (for parameterized resources)
- Resources
Capability - Resources capability
- Root
- A filesystem root that defines boundary for file operations
- Sampling
Request - Enhanced sampling request with context and human-in-the-loop support
- Sampling
Response - Enhanced sampling response with human-in-the-loop support
- Server
Auth Middleware - Server-side authentication middleware
- Server
Capabilities - Server capabilities that can be advertised during initialization
- Server
Info - Information about the server
- Stdio
Transport - STDIO transport for MCP communication
- Streamable
Http Client - Streamable HTTP client - MCP-compliant request/response implementation
- Streamable
Http Client Config - Streamable HTTP client configuration
- System
Metrics - System-related metrics
- Token
Claims - JWT token claims
- Token
Response - OAuth token response
- Token
Validator - Token validator for JWT access tokens
- Tool
- Tool definition
- Tool
Annotations - Tool annotations provide metadata about tool behavior
- Tools
Capability - Tools capability
- Transport
Metrics - Transport-related metrics
- Ultra
Fast Client - UltraFast MCP Client
- Validation
Middleware - Validation middleware for message schema validation with improved error handling and performance
Enums§
- Auth
Error - Authentication and authorization errors
- Auth
Method - Unified authentication method
- Health
Status - Health status enumeration
- LogLevel
- Log level - RFC 5424 compliant levels
- MCPError
- Main error type for MCP operations
- Prompt
Content - Prompt content
- Prompt
Role - Prompt message role
- Resource
Content - Resource content
- Sampling
Content - Sampling content
- Tool
Content - Tool content (result of tool execution)
- Transport
Config - Transport configuration
Traits§
- Client
Elicitation Handler - Client-side elicitation handler trait
- Health
Check - Trait for implementing custom health checks
- Transport
- Enhanced transport trait with lifecycle management
- Transport
Middleware - Middleware trait for HTTP transport
Functions§
- create_
recovering_ transport - Create a transport with automatic recovery
- create_
streamable_ http_ client_ default - Create a Streamable HTTP client with default middleware stack
- create_
streamable_ http_ client_ with_ middleware - Create a Streamable HTTP client with middleware
- create_
streamable_ http_ server_ default - Create a Streamable HTTP server with default configuration
- create_
streamable_ http_ server_ with_ middleware - Create a Streamable HTTP server with middleware
- create_
transport - Create a transport from configuration
- extract_
bearer_ token - Extract bearer token from Authorization header
- generate_
pkce_ params - Generate PKCE (Proof Key for Code Exchange) parameters
- generate_
session_ id - Generate a new session ID for MCP connections
- generate_
state - Generate a new state parameter for OAuth flows
Type Aliases§
- Auth
Result - Result type for authentication operations
- Create
Message Request - Type aliases for consistency
- Create
Message Response - MCPResult
- MCPResult is the canonical result type for all MCP operations.
- Tool
Call - Type aliases for consistency
- Tool
Result