Skip to content

Repository files navigation

FastRMCP

A fast, ergonomic Model Context Protocol (MCP) framework for Rust, inspired by Python's fastmcp.

FastRMCP provides a high-level, type-safe API for building MCP servers in Rust, with compile-time guarantees and zero-cost abstractions.

Features

  • 🚀 High Performance: Built on Tokio for async I/O and maximum throughput
  • 🔒 Type Safe: Leverages Rust's type system for compile-time correctness
  • 🎯 Ergonomic API: Inspired by fastmcp's developer experience
  • 📦 Batteries Included: Multiple transports (STDIO, SSE, WebSocket), JSON-RPC handling, and protocol implementation
  • 🌐 Web-Ready: SSE and WebSocket transports for browser and HTTP clients
  • 🧪 Well Tested: Comprehensive test coverage for core functionality
  • 🔌 Extensible: Support for custom transports, tools, resources, and prompts
  • 🔐 Middleware: Built-in middleware for logging, authentication, and rate limiting
  • 📡 Subscriptions: Real-time resource updates with WebSocket support

Status

Production Ready: FastRMCP provides a complete, production-ready foundation for building MCP servers. The core protocol, all three transports (STDIO, SSE, WebSocket), and server infrastructure are fully implemented and tested.

Currently Implemented

  • ✅ Core MCP protocol types (JSON-RPC 2.0)
  • ✅ STDIO transport for stdin/stdout communication
  • SSE (Server-Sent Events) transport for HTTP/web clients
  • WebSocket transport for bidirectional web communication
  • ✅ Error handling with comprehensive error types
  • ✅ Server initialization and lifecycle management
  • ✅ Request routing and handling
  • ✅ Tool, Resource, and Prompt registries
  • ✅ Context system with progress reporting and logging
  • ✅ Builder pattern API
  • Procedural macros (#[tool], #[resource], #[prompt], #[on_startup], #[on_shutdown])
  • Dynamic tool execution with automatic parameter extraction via serde
  • State management for shared application state
  • Lifecycle hooks for startup and shutdown
  • URI template engine for resource path matching
  • Automatic registration via inventory pattern
  • Middleware system with logging, authentication, and rate limiting
  • Resource subscriptions for real-time resource updates
  • HTTP/2 support - Web transports support both HTTP/1.1 and HTTP/2
  • CLI tooling - fastrmcp command for project scaffolding

Planned Enhancements

  • 📋 Performance benchmarks - throughput and latency measurements
  • 📋 Enhanced observability - metrics and monitoring integration

Architecture

FastRMCP is organized into three main crates:

  • fastrmcp-core: Core types, traits, and protocol implementation
  • fastrmcp-macros: Procedural macros for ergonomic server definition
  • fastrmcp: Main library that ties everything together

Quick Start

Option 1: Using the CLI Tool (Recommended)

The fastest way to get started is using the fastrmcp CLI:

# Install the CLI tool
cargo install fastrmcp-cli

# Create a new project
fastrmcp new my-server

# Or use a template (sse, websocket, middleware, subscriptions, complete)
fastrmcp new my-server --template complete

# Navigate and run
cd my-server
cargo run

See fastrmcp-cli/README.md for more CLI options.

Option 2: Manual Setup

Add FastRMCP to your Cargo.toml:

[dependencies]
fastrmcp = "0.2"
tokio = { version = "1", features = ["full"] }

Create an MCP server with tools:

use fastrmcp::prelude::*;
use fastrmcp_macros::tool;

/// Add two numbers
#[tool]
async fn add(a: i64, b: i64) -> Result<i64> {
    Ok(a + b)
}

/// Reverse a string
#[tool]
async fn reverse_string(text: String) -> Result<String> {
    Ok(text.chars().rev().collect())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Tools are automatically registered via #[tool] macro
    let server = FastMCP::new("my-server")
        .version("1.0.0")
        .description("My MCP server");

    server.run().await?;
    Ok(())
}

That's it! The #[tool] macro automatically:

  • Generates JSON schemas from function signatures
  • Handles parameter extraction and type conversion
  • Registers tools with the server
  • Provides type-safe execution

See examples/complete/ for more advanced features including resources, prompts, state management, and lifecycle hooks.

Project Structure

FastRMCP/
├── fastrmcp/              # Main library crate
│   ├── src/
│   │   ├── server.rs      # FastMCP server implementation
│   │   ├── handler.rs     # Request handlers
│   │   ├── registry.rs    # Tool/Resource/Prompt registries
│   │   └── transport/     # Transport implementations
│   │       ├── stdio.rs   # STDIO transport (default)
│   │       ├── sse.rs     # Server-Sent Events transport
│   │       └── websocket.rs # WebSocket transport
├── fastrmcp-core/         # Core types and traits
│   ├── src/
│   │   ├── error.rs       # Error types
│   │   ├── protocol.rs    # JSON-RPC protocol
│   │   ├── types.rs       # MCP types
│   │   ├── context.rs     # Execution context
│   │   └── transport.rs   # Transport trait
├── fastrmcp-macros/       # Procedural macros
│   └── src/
│       └── lib.rs         # Macro definitions
└── examples/              # Example servers
    ├── basic/             # Basic STDIO example
    ├── sse/               # SSE transport example
    ├── websocket/         # WebSocket transport example
    └── complete/          # **Comprehensive feature demonstration**

FastMCP-style Patterns

Typed equivalents of the Python FastMCP ergonomics:

use fastrmcp::prelude::*;
use fastrmcp_macros::{tool, resource, prompt};

#[tool]
async fn greet(name: String) -> Result<String> {
    Ok(format!("Hello, {}!", name))
}

#[resource("status://{service}")]
async fn status(service: String, ctx: Context) -> Result<String> {
    let client = ctx.client_info.as_ref().map(|c| c.name.clone()).unwrap_or_default();
    Ok(format!("Service {} is healthy (client: {})", service, client))
}

#[prompt]
async fn reviewer(file: String) -> Result<PromptResult> {
    Ok(PromptResult {
        description: Some("Review code for issues".to_string()),
        messages: vec![PromptMessage {
            role: PromptRole::User,
            content: PromptMessageContent::Text { text: format!("Review:\n{}", file) },
        }],
    })
}

Custom Middleware (Auth / Rate Limit)

use fastrmcp::middleware::{AuthMiddleware, RateLimitMiddleware, LoggingMiddleware};

let server = FastMCP::new("my-server")
    .with_middleware(LoggingMiddleware::new())
    .with_middleware(AuthMiddleware::bearer_token("secret-token"))
    .with_middleware(RateLimitMiddleware::new(100, std::time::Duration::from_secs(60)));

Transport Configuration

  • STDIO (default): server.run().await?
  • SSE / WebSocket:
use fastrmcp::transport::{SseTransport, WebSocketTransport};

let (transport, router) = SseTransport::new(); // or WebSocketTransport::new()
// Serve `router` with axum/hyper while FastMCP runs with `transport`
server.run_with_transport(transport).await?;

Connection tips:

  • SSE: client receives an initial connectionId event; include that ID in subsequent POSTs.
  • WebSocket: server-initiated requests target the current connection unless a connectionId is provided in request metadata.

Design Philosophy

FastRMCP follows these principles:

  1. Type Safety First: Leverage Rust's type system to prevent errors at compile time
  2. Zero Cost Abstractions: High-level API with no runtime overhead
  3. Explicit Over Implicit: Clear, predictable behavior
  4. Performance: Built for production use with async I/O
  5. Developer Experience: Inspired by fastmcp's ergonomic API

MCP Protocol Support

FastRMCP implements the Model Context Protocol specification:

  • Protocol Version: 2024-11-05
  • Transports:
    • STDIO: stdin/stdout (default)
    • SSE: Server-Sent Events over HTTP
    • WebSocket: Full-duplex WebSocket communication
  • Message Format: JSON-RPC 2.0

Supported Methods

  • initialize - Server initialization with capability negotiation
  • initialized - Initialization complete notification
  • tools/list - List available tools
  • tools/call - Execute a tool with automatic parameter extraction
  • resources/list - List available resources
  • resources/read - Read a resource with URI template matching
  • resources/subscribe - Subscribe to resource updates
  • resources/unsubscribe - Unsubscribe from resource updates
  • resources/list_subscriptions - List active subscriptions
  • prompts/list - List available prompts
  • prompts/get - Get a prompt with metadata
  • ping - Health check

Development Roadmap

Phase 1: Foundation (✅ Complete)

  • Core types and error handling
  • JSON-RPC protocol implementation
  • STDIO transport
  • SSE transport
  • WebSocket transport
  • Basic server runtime
  • Request routing
  • Comprehensive documentation

Phase 2: Tool System (✅ Complete)

  • Tool registry with thread-safe storage
  • #[tool] proc macro - Fully functional with serde parameter extraction
  • Dynamic tool execution - Complete with type conversion
  • Schema generation from Rust types - Automatic JSON schema generation
  • Tool parameter validation - Type-safe via serde
  • Support for complex types - Vec, Option, custom structs

Status: ✅ Production ready. All macros working with comprehensive type support. Parameter extraction via serde supports all serde-compatible types.

Phase 3: Resources & Prompts (✅ Complete)

  • Resource and Prompt registries
  • #[resource] proc macro - Fully functional
  • #[prompt] proc macro - Fully functional
  • URI template engine - Pattern parsing and parameter extraction
  • Automatic registration - Via inventory pattern
  • URI template variable resolution - Complete with 7 passing tests

Status: ✅ Production ready. URI template matching implemented and tested. Resource subscriptions framework ready for future enhancement.

Phase 4: Advanced Features (✅ 95% Complete)

  • Lifecycle hooks (#[on_startup], #[on_shutdown]) - Complete
  • State management - Type-safe shared state with Arc<RwLock<>>
  • URI template engine - Pattern matching with parameter extraction
  • Middleware system - Complete with logging, auth, and rate limiting middleware (v0.2.0)
  • Resource subscriptions - Real-time updates with subscription management (v0.2.0)
  • HTTP/2 support (planned for future release)

Status: ✅ Core features complete. State management, lifecycle hooks, middleware system, and resource subscriptions fully integrated with server. HTTP/2 planned for future release.

Phase 5: Enhanced Tooling (✅ 65% Complete)

  • Comprehensive examples - 5 complete examples (basic, sse, websocket, middleware, complete)
  • Complete example - Shows all features working together
  • Comprehensive documentation - 3,000+ lines across 9 guides
  • CHANGELOG - Detailed release notes and migration guides
  • Performance benchmarks (planned)
  • CLI scaffolding tool (planned)
  • Metrics/observability integration (planned)

Status: ✅ Documentation and examples complete. See examples/complete/ for comprehensive feature demonstration and docs/MIDDLEWARE.md for middleware guide.

Testing

Run the test suite (40 tests, 100% passing):

cargo test

Run tests with specific features:

# Test with all features
cargo test --features full

# Test with SSE support
cargo test --features sse

# Test with WebSocket support
cargo test --features websocket

Build examples:

# Build all examples
cargo build --examples

# Build with specific features
cargo build --example sse-example --features sse
cargo build --example websocket-example --features websocket

Contributing

Contributions are welcome! Areas of focus:

  • Middleware system implementation
  • Performance benchmarks and optimization
  • Additional examples and use cases
  • Documentation improvements
  • Bug reports and feature requests

License

MIT License - see LICENSE file for details

Acknowledgments

Related Projects

Web Transports

FastRMCP supports web-based transports for browser and HTTP clients:

SSE (Server-Sent Events)

[dependencies]
fastrmcp = { version = "0.1", features = ["sse"] }

Use Case: Web applications needing server-to-client updates with HTTP fallback for client messages.

WebSocket

[dependencies]
fastrmcp = { version = "0.1", features = ["websocket"] }

Use Case: Real-time bidirectional communication for interactive web applications.

See WEB_TRANSPORTS.md for detailed usage guide, examples, and security considerations.

Examples

FastRMCP includes working examples for all transport types:

Basic STDIO Example

cd examples/basic
cargo run

SSE Example (Web Transport)

cd examples/sse
cargo run --features sse
# Server listens on http://localhost:3000

WebSocket Example (Web Transport)

cd examples/websocket
cargo run --features websocket
# Server listens on ws://localhost:3001

Middleware Example (New in v0.2.0)

cd examples/middleware
cargo run

This example demonstrates the middleware system:

  • LoggingMiddleware for request/response logging
  • AuthMiddleware for bearer token authentication
  • RateLimitMiddleware for rate limiting
  • Custom middleware creation
  • Middleware chain execution order

See docs/MIDDLEWARE.md for the complete middleware guide.

Subscriptions Example (New in v0.2.0)

cd examples/subscriptions
cargo run

This example demonstrates resource subscriptions:

  • Real-time resource updates via subscriptions
  • Subscribe/unsubscribe to resource URIs
  • Automatic notification on resource changes
  • Multiple subscribers per resource
  • Subscription management and tracking

See docs/SUBSCRIPTIONS.md for the complete subscriptions guide.

Complete Example (All Features)

cd examples/complete
cargo run

This example demonstrates ALL FastRMCP features:

  • 9 tools (math, string ops, complex types)
  • 2 resources (system info, server status)
  • 3 prompts (code review, docs, bug analysis)
  • State management with AppConfig
  • Lifecycle hooks (startup/shutdown)
  • Full type safety and automatic registration

See examples/complete/README.md for detailed documentation.

For detailed web transport usage, including JavaScript client examples, see WEB_TRANSPORTS.md.

Documentation

FastRMCP includes comprehensive documentation:

Performance

FastRMCP is built for performance:

  • Zero-cost abstractions - No runtime overhead
  • Async I/O - Built on Tokio for maximum throughput
  • Efficient serialization - Using serde's optimized JSON handling
  • Memory safe - Guaranteed by Rust's ownership system
  • Thread safe - Safe concurrent access to all components

Transport Comparison

Transport Latency Throughput Use Case
STDIO Very Low High CLI tools, pipes
SSE Medium Good Server → client streaming
WebSocket Low Excellent Bidirectional real-time

Security

FastRMCP is designed with security in mind:

  • Memory Safety - Guaranteed by Rust (no buffer overflows, use-after-free, etc.)
  • Type Safety - Compile-time checks prevent type errors
  • Input Validation - JSON-RPC protocol validation
  • CORS Support - Configurable for web transports
  • 🔧 Authentication - Add middleware (examples in WEB_TRANSPORTS.md)
  • 🔧 TLS/HTTPS - Configure with rustls or native-tls
  • 🔧 Rate Limiting - Add tower middleware

See WEB_TRANSPORTS.md for security best practices and production deployment guidance.

About

FastRMCP: The high-level, ergonomic, and production-focused framework for building Model Context Protocol (MCP) servers in Rust. Inspired by FastMCP and FastAPI.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages