FastRMCP
FastRMCP: The high-level, ergonomic, and production-focused framework for building Model Context Protocol (MCP) servers in Rust. Inspired by FastMCP and FastAPI.
Ask AI about FastRMCP
Powered by Claude Β· Grounded in docs
I know everything about FastRMCP. Ask me about installation, configuration, usage, or troubleshooting.
0/500
Reviews
Documentation
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 -
fastrmcpcommand 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
connectionIdevent; include that ID in subsequent POSTs. - WebSocket: server-initiated requests target the current connection unless a
connectionIdis provided in request metadata.
Design Philosophy
FastRMCP follows these principles:
- Type Safety First: Leverage Rust's type system to prevent errors at compile time
- Zero Cost Abstractions: High-level API with no runtime overhead
- Explicit Over Implicit: Clear, predictable behavior
- Performance: Built for production use with async I/O
- 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
- Inspired by fastmcp by James Lowin
- Built on the Model Context Protocol specification
Related Projects
- fastmcp - Python implementation
- MCP Specification
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:
- README.md - This file, main overview and quick start
- QUICKSTART.md - 5-minute getting started guide
- fastrmcp-cli/README.md - CLI tool for project scaffolding (new in v0.3.0)
- docs/MIDDLEWARE.md - Complete middleware system guide (v0.2.0)
- docs/SUBSCRIPTIONS.md - Resource subscriptions and real-time updates guide (v0.2.0)
- docs/HTTP2.md - HTTP/2 support and configuration guide (new in v0.3.0)
- WEB_TRANSPORTS.md - Complete guide for SSE and WebSocket transports
- FEATURES.md - Full feature matrix and comparison
- STATUS.md - Project status and metrics
- IMPLEMENTATION_SUMMARY.md - Technical architecture details
- WEB_TRANSPORTS_SUMMARY.md - Web transport implementation notes
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.
