mcp-kit
An ergonomic, type-safe Rust library for building Model Context Protocol (MCP) servers.
MCP enables AI assistants to securely access tools, data sources, and prompts through a standardized protocol. This library provides a modern, async-first implementation with powerful procedural macros for rapid development.
Features
- 🚀 Async-first — Built on Tokio for high-performance concurrent operations
- 🛡️ Type-safe — Leverage Rust's type system with automatic JSON Schema generation
- 🎯 Ergonomic macros —
#[tool],#[resource],#[prompt]attributes for minimal boilerplate - 🔌 Multiple transports — stdio (default), SSE/HTTP, WebSocket, and HTTPS/TLS support
- 🔐 Authentication — Bearer, API Key, Basic, OAuth 2.0, and mTLS support
- 📝 Completion — Auto-complete argument values for prompts and resources
- 📊 Progress tracking — Report progress for long-running operations
- 📢 Notifications — Push updates to clients (resource changes, log messages)
- 🔄 Subscriptions — Subscribe to resource changes for real-time updates
- ⛔ Cancellation — Cancel long-running requests
- � Sampling — Server-initiated LLM requests to clients
- 📁 Roots — File system sandboxing with client-provided roots
- �🧩 Modular — Feature-gated architecture, WASM-compatible core
- 📦 Batteries included — State management, error handling, tracing integration
- 🎨 Flexible APIs — Choose between macro-based or manual builder patterns
- 📡 Client SDK —
mcp-kit-clientcrate for connecting to MCP servers
Installation
Add to your Cargo.toml:
[]
= "0.1"
= { = "1", = ["full"] }
= { = "1", = ["derive"] }
= "0.8"
= "1" # For error handling
Minimum Supported Rust Version (MSRV): 1.85
Quick Start
Using Macros (Recommended)
The fastest way to build an MCP server with automatic schema generation:
use *;
/// Add two numbers
async
async
Manual API
For more control over schema and behavior:
use *;
use JsonSchema;
use Deserialize;
async
Core Concepts
Tools
Tools are functions that AI models can invoke. Define them with the #[tool] macro or manually:
// Macro approach
async
// Manual approach
let schema = to_value?;
builder.tool;
Error Handling:
async
Resources
Resources expose data (files, APIs, databases) to AI models:
// Static resource
async
// Template resource (dynamic URIs)
async
Prompts
Prompts provide reusable templates for AI interactions:
async
Transports
Stdio (Default)
Standard input/output transport for local process communication:
server.serve_stdio.await?;
SSE (Server-Sent Events)
HTTP-based transport for web clients:
// Requires the "sse" feature
server.serve_sse.await?;
Enable in Cargo.toml:
[]
= { = "0.1", = ["sse"] }
TLS/HTTPS
Secure HTTPS transport with optional mTLS:
use ;
let tls = builder
.cert_pem
.key_pem
.client_auth_ca_pem // Enable mTLS
.build?;
server.serve_tls.await?;
WebSocket
Bidirectional WebSocket transport for real-time communication:
// Requires the "websocket" feature
server.serve_websocket.await?;
Enable in Cargo.toml:
[]
= { = "0.1", = ["websocket"] }
Authentication
Protect your MCP server with various authentication methods. All auth features are composable and can be combined.
Bearer Token Authentication
use *;
use ;
use Auth;
use Arc;
// Protected tool - requires auth parameter
async
async
Test with: curl -H "Authorization: Bearer my-secret-token" http://localhost:3000/sse
API Key Authentication
use ;
// Supports both header and query param
let provider = new;
builder
.auth
// ...
Test with:
- Header:
curl -H "X-Api-Key: api-key-123" http://localhost:3000/sse - Query:
curl "http://localhost:3000/sse?api_key=api-key-123"
Basic Authentication
use ;
let provider = new;
Test with: curl -u admin:secret http://localhost:3000/sse
OAuth 2.0 (JWT/JWKS)
use ;
// JWT validation with JWKS endpoint
let provider = new;
// Or token introspection (RFC 7662)
let provider = new;
mTLS (Mutual TLS)
use MtlsProvider;
use ;
let mtls = new;
let tls = builder
.cert_pem
.key_pem
.client_auth_ca_pem
.build?;
builder
.auth
.build
.serve_tls
.await?;
Composite Authentication
Combine multiple auth methods:
use ;
let composite = new;
builder
.auth
// ...
Auth Extractor in Tools
Access authentication info in tool handlers:
use Auth;
async
Completion
Provide auto-complete suggestions for prompt and resource arguments:
use *;
use ;
builder
.name
.version
// Prompt with completion handler
.prompt_with_completion
// Global completion for resources
.completion
.build;
Notifications
Push updates from server to clients:
use *;
// Create notification channel
let = channel;
// In a tool handler - notify about resource changes
async
Available Notifications:
resource_updated(uri)— A specific resource's content changedresources_list_changed()— Available resources list changedtools_list_changed()— Available tools list changedprompts_list_changed()— Available prompts list changedlog_debug/info/warning/error()— Log messages
Progress Tracking
Report progress for long-running operations:
use *;
async
ProgressTracker Methods:
update(progress, total, message)— Send progress updateupdate_percent(0.0..1.0, message)— Progress as percentagecomplete(message)— Mark operation completeis_tracking()— Check if progress token was provided
---
## Advanced Features
### State Management
Share state across tool invocations:
```rust
use std::sync::Arc;
use tokio::sync::Mutex;
#[derive(Clone)]
struct AppState {
counter: Arc<Mutex<i32>>,
}
// In your tool handler
let state = AppState { counter: Arc::new(Mutex::new(0)) };
builder.tool(
Tool::new("increment", "Increment counter", schema),
{
let state = state.clone();
move |_: serde_json::Value| {
let state = state.clone();
async move {
let mut counter = state.counter.lock().await;
*counter += 1;
CallToolResult::text(format!("Counter: {}", *counter))
}
}
}
);
Logging
Integrate with tracing for structured logging:
fmt
.with_writer // Log to stderr for stdio transport
.with_env_filter
.init;
info!;
Set log level:
RUST_LOG=my_server=debug
Error Handling
The library uses McpResult<T> and McpError:
use ;
async
Macro Reference
#[tool]
Generate tools from async functions:
async
Attributes:
description = "..."— Tool description (required)name = "..."— Tool name (optional, defaults to function name)
Supported return types:
String→ Converted toCallToolResult::textCallToolResult→ Used directlyResult<T, E>→ Error handling support
#[resource]
Generate resource handlers:
async
URI Templates:
Use {variable} syntax for dynamic resources:
#[prompt]
Generate prompt handlers:
async
Builder API Reference
builder
// Server metadata
.name
.version
.instructions
// Register tools
.tool // Manual API
.tool_def // From #[tool] macro
// Register resources
.resource // Static resource
.resource_template // URI template
.resource_def // From #[resource] macro
// Register prompts
.prompt
.prompt_def // From #[prompt] macro
.build
Examples
Run the included examples to see all features in action:
# Comprehensive showcase - all features
# Showcase with SSE transport on port 3000
# WebSocket transport example
# Macro-specific examples
# Completion auto-complete example
# Notifications and progress example
# Authentication examples
# Client SDK example (requires running server first)
Example Features:
- ✅ Multiple tool types (math, async, state management)
- ✅ Static and template resources
- ✅ Prompts with arguments
- ✅ Argument completion (auto-complete)
- ✅ Notifications (resource updates, logging)
- ✅ Progress tracking for long operations
- ✅ Resource subscriptions
- ✅ Request cancellation
- ✅ Error handling patterns
- ✅ State sharing between requests
- ✅ JSON content types
- ✅ Stdio, SSE, and WebSocket transports
- ✅ Bearer, API Key, Basic, OAuth 2.0, mTLS authentication
- ✅ Composite authentication (multiple methods)
- ✅ Client SDK for connecting to servers
Source code: examples/
Feature Flags
Control which features to compile:
[]
= { = "0.1", = false, = ["server", "stdio"] }
Available features:
full(default) — All features enabledserver— Core server functionalitystdio— Standard I/O transportsse— HTTP Server-Sent Events transportwebsocket— WebSocket transport
Authentication features:
auth— Core auth types and traitsauth-bearer— Bearer token authenticationauth-apikey— API key authenticationauth-basic— HTTP Basic authenticationauth-oauth2— OAuth 2.0 (JWT/JWKS + introspection)auth-mtls— Mutual TLS / client certificatesauth-full— All auth features (bearer, apikey, basic)
WASM compatibility:
Use default-features = false for WASM targets (only core protocol types).
Architecture
mcp-kit/
├── src/
│ ├── lib.rs # Public API and re-exports
│ ├── error.rs # Error types
│ ├── protocol.rs # JSON-RPC 2.0 implementation
│ ├── types/ # MCP protocol types
│ ├── server/ # Server implementation [feature = "server"]
│ └── transport/ # Transport implementations
├── macros/ # Procedural macros crate
└── client/ # Client SDK crate
Crate structure:
mcp-kit— Main server librarymcp-kit-macros— Procedural macros (#[tool], etc.)mcp-kit-client— Client SDK for connecting to MCP servers
Client SDK
The mcp-kit-client crate provides a client library for connecting to MCP servers:
[]
= "0.1"
Quick Start
use *;
async
Transport Options
// Stdio - spawn subprocess
let client = stdio.await?;
// SSE - HTTP Server-Sent Events
let client = sse.await?;
// WebSocket
let client = websocket.await?;
Available Operations
| Method | Description |
|---|---|
initialize() |
Initialize the MCP connection |
list_tools() |
List available tools |
call_tool() |
Call a tool with arguments |
list_resources() |
List available resources |
read_resource() |
Read a resource by URI |
list_prompts() |
List available prompts |
get_prompt() |
Get a prompt by name |
subscribe() |
Subscribe to resource updates |
unsubscribe() |
Unsubscribe from updates |
See client/README.md for full documentation.
Testing
# Run all tests
# Check formatting
# Run lints
# Check MSRV
Resources
- MCP Specification: https://modelcontextprotocol.io/
- Documentation: https://docs.rs/mcp-kit
- Repository: https://github.com/KSD-CO/mcp-kit
- Examples:
examples/ - CI/CD: GitHub Actions
Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Ensure
cargo fmtandcargo clippypass - Submit a pull request
See AGENTS.md for development guidelines.
License
This project is licensed under the MIT License.
Changelog
See GitHub Releases for version history.
Built with ❤️ in Rust