Crate ultrafast_mcp

Crate ultrafast_mcp 

Source
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 APIs
  • ToolHandler: Implement tool functionality with trait-based interfaces
  • ResourceHandler: Manage resources and content delivery
  • PromptHandler: Generate dynamic prompts and content

§Client Development

  • UltraFastClient: Connect to MCP servers with async/await APIs
  • Transport: Flexible transport layer with HTTP, STDIO, and custom options
  • ResourceSubscriptionHandler: 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

  • 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§

AuthTypes
McpAuthError
McpCoreError
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§

ApiKeyAuth
API Key authentication
AuthConfig
OAuth 2.1 configuration
AuthContext
Authentication context for requests
AuthorizationServerMetadata
Authorization server metadata (RFC 8414)
BasicAuth
Basic authentication
BearerAuth
Bearer token authentication
ClientAuthMiddleware
Client-side authentication middleware
ClientCapabilities
Client capabilities that can be negotiated during initialization
ClientInfo
Client information
ClientRegistrationRequest
Client registration request (RFC 7591)
ClientRegistrationResponse
Client registration response (RFC 7591)
CompleteRequest
Completion request (MCP 2025-06-18 compliant)
CompleteResponse
Completion response
Completion
Completion result set
CompletionCapability
Completion capability for argument autocompletion
CompletionValue
Individual completion value
CustomHeaderAuth
Custom header authentication
ElicitationRequest
Server-initiated request for user input
ElicitationResponse
User response to elicitation request
GetPromptRequest
Get prompt request
GetPromptResponse
Get prompt response
HealthCheckResult
Result of a health check
HealthChecker
Health checker for managing multiple health checks
HttpTransportConfig
HTTP transport configuration
HttpTransportServer
HTTP transport server implementation
HttpTransportState
Shared state for HTTP transport
ListPromptsRequest
List prompts request
ListPromptsResponse
List prompts response
ListResourcesRequest
ListResourcesResponse
List resources response
ListToolsRequest
List tools request
ListToolsResponse
List tools response
LoggingCapability
Logging capability
LoggingMiddleware
Logging middleware for request/response tracking
MetricsCollector
Metrics collector for gathering and managing metrics
MiddlewareTransport
Transport wrapper that applies middleware
ModelPreferences
Model preferences for sampling
MonitoringConfig
Main monitoring configuration
MonitoringSystem
The main monitoring system that orchestrates all monitoring components
OAuthClient
OAuth 2.1 client for server discovery and registration
OAuthConfig
OAuth 2.1 configuration
PingResponse
Ping response for connection health monitoring
PkceParams
PKCE parameters for OAuth 2.1
ProgressMiddleware
Progress tracking middleware with improved error handling
Prompt
Prompt definition
PromptArgument
Prompt argument definition
PromptMessages
Helper for building prompt messages
PromptsCapability
Prompts capability
RateLimitMiddleware
Rate limiting middleware with improved error handling
ReadResourceRequest
ReadResourceResponse
Read resource response
RequestMetrics
Request-related metrics
RequestTimer
Timer for measuring request duration
Resource
Resource definition
ResourceTemplate
Resource template definition (for parameterized resources)
ResourcesCapability
Resources capability
Root
A filesystem root that defines boundary for file operations
SamplingRequest
Enhanced sampling request with context and human-in-the-loop support
SamplingResponse
Enhanced sampling response with human-in-the-loop support
ServerAuthMiddleware
Server-side authentication middleware
ServerCapabilities
Server capabilities that can be advertised during initialization
ServerInfo
Information about the server
StdioTransport
STDIO transport for MCP communication
StreamableHttpClient
Streamable HTTP client - MCP-compliant request/response implementation
StreamableHttpClientConfig
Streamable HTTP client configuration
SystemMetrics
System-related metrics
TokenClaims
JWT token claims
TokenResponse
OAuth token response
TokenValidator
Token validator for JWT access tokens
Tool
Tool definition
ToolAnnotations
Tool annotations provide metadata about tool behavior
ToolsCapability
Tools capability
TransportMetrics
Transport-related metrics
UltraFastClient
UltraFast MCP Client
ValidationMiddleware
Validation middleware for message schema validation with improved error handling and performance

Enums§

AuthError
Authentication and authorization errors
AuthMethod
Unified authentication method
HealthStatus
Health status enumeration
LogLevel
Log level - RFC 5424 compliant levels
MCPError
Main error type for MCP operations
PromptContent
Prompt content
PromptRole
Prompt message role
ResourceContent
Resource content
SamplingContent
Sampling content
ToolContent
Tool content (result of tool execution)
TransportConfig
Transport configuration

Traits§

ClientElicitationHandler
Client-side elicitation handler trait
HealthCheck
Trait for implementing custom health checks
Transport
Enhanced transport trait with lifecycle management
TransportMiddleware
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§

AuthResult
Result type for authentication operations
CreateMessageRequest
Type aliases for consistency
CreateMessageResponse
MCPResult
MCPResult is the canonical result type for all MCP operations.
ToolCall
Type aliases for consistency
ToolResult