Crates.io | pmcp |
lib.rs | pmcp |
version | 1.5.3 |
created_at | 2025-07-26 02:02:07.422984+00 |
updated_at | 2025-09-26 00:17:28.549899+00 |
description | High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility |
homepage | https://github.com/paiml/pmcp |
repository | https://github.com/paiml/pmcp |
max_upload_size | |
id | 1768625 |
size | 2,605,929 |
A high-quality Rust implementation of the Model Context Protocol (MCP) SDK, maintaining full compatibility with the TypeScript SDK while leveraging Rust's performance and safety guarantees.
Code Name: Angel Rust
๐ Claude Code Compatible! Version 1.4.0+ includes full JSON-RPC 2.0 compatibility, enabling seamless integration with Claude Code and all standard MCP clients. If you're experiencing connection issues, please upgrade to v1.4.1+.
use pmcp::ToolResult
Add to your Cargo.toml
:
[dependencies]
pmcp = "1.4"
โ ๏ธ Important for Claude Code users: Version 1.4.0+ is required for Claude Code compatibility. Earlier versions use a different message format that is incompatible with standard MCP clients. See the Migration Guide if upgrading from < 1.4.0.
The SDK fully supports WebAssembly compilation for deployment to:
# Build for Cloudflare Workers
cargo build --target wasm32-unknown-unknown --no-default-features --features wasm
# Deploy SDK-based Worker
make cloudflare-sdk-deploy
The comprehensive PMCP Guide provides detailed documentation with interactive examples:
๐ Read Online - Live documentation updated automatically
# Local development
make book-serve # Serve at http://localhost:3000
# Other book commands
make book # Build the book
make book-open # Build and open in browser
make book-clean # Clean build artifacts
The guide covers everything from basic concepts to advanced patterns:
The SDK includes comprehensive examples for all major features:
# Client initialization and connection
cargo run --example 01_client_initialize
# Basic server with tools
cargo run --example 02_server_basic
# Client tool usage
cargo run --example 03_client_tools
# Server with resources
cargo run --example 04_server_resources
# Client resource access
cargo run --example 05_client_resources
# Server with prompts
cargo run --example 06_server_prompts
# Client prompts usage
cargo run --example 07_client_prompts
# Logging
cargo run --example 08_logging
# Authentication (OAuth, Bearer tokens)
cargo run --example 09_authentication
# Progress notifications
cargo run --example 10_progress_notifications
# Request cancellation
cargo run --example 11_request_cancellation
# Error handling patterns
cargo run --example 12_error_handling
# WebSocket transport
cargo run --example 13_websocket_transport
# LLM sampling operations
cargo run --example 14_sampling_llm
# Middleware and interceptors
cargo run --example 15_middleware
# OAuth server with authentication
cargo run --example 16_oauth_server
# Completable prompts
cargo run --example 17_completable_prompts
# Resource watching with file system monitoring
cargo run --example 18_resource_watcher
# Input elicitation
cargo run --example 19_elicit_input
# OIDC discovery and authentication
cargo run --example 20_oidc_discovery
# Procedural macros for tools
cargo run --example 21_macro_tools --features macros
# Streamable HTTP server (stateful with sessions)
cargo run --example 22_streamable_http_server_stateful --features streamable-http
# Streamable HTTP server (stateless for serverless)
cargo run --example 23_streamable_http_server_stateless --features streamable-http
# Streamable HTTP client
cargo run --example 24_streamable_http_client --features streamable-http
# WASM client (browser-based) - see examples/wasm-client/README.md
cd examples/wasm-client && bash build.sh
# WebSocket server implementation with connection management
cargo run --example 25_websocket_server --features full
# MCP server tester - comprehensive testing tool for MCP servers
cargo run --example 26-server-tester -- test http://localhost:8080
# HTTP/SSE transport optimizations with connection pooling
cargo run --example 26_http_sse_optimizations --features full
# Connection pooling and load balancing demonstration
cargo run --example 27_connection_pooling --features full
# Advanced middleware system with circuit breakers and rate limiting
cargo run --example 28_advanced_middleware --features full
# Advanced error recovery with adaptive retry and health monitoring
cargo run --example 29_advanced_error_recovery --features full
# Complete advanced error recovery example with cascade detection
cargo run --example 31_advanced_error_recovery --features full
# SIMD parsing performance demonstration with benchmarks
cargo run --example 32_simd_parsing_performance --features full
# NEW in v1.4.1 - Enhanced Examples with TypeScript SDK Parity
# Multiple parallel clients with concurrent operations and error handling
cargo run --example 47_multiple_clients_parallel --features full
# Structured output schemas with advanced data validation
cargo run --example 48_structured_output_schema --features full
# Tool with LLM sampling integration for text processing
cargo run --example 49_tool_with_sampling_server --features full
The SDK includes a comprehensive testing tool for validating MCP server implementations. The tester ensures protocol compliance, validates capabilities, and provides detailed diagnostics.
Pre-built binaries are available from releases:
mcp-tester-linux-x86_64
(Linux)mcp-tester-macos-x86_64
(macOS Intel/Apple Silicon via Rosetta)mcp-tester-windows-x86_64.exe
(Windows)Or build from source:
cargo build --release --package mcp-server-tester
# Binary will be at target/release/mcp-tester
# Test an MCP server
mcp-tester test http://localhost:8080
# Test with tools validation
mcp-tester test http://localhost:8080 --with-tools
# Protocol compliance check
mcp-tester compliance http://localhost:8080 --strict
# Connection diagnostics
mcp-tester diagnose http://localhost:8080
# Compare two servers
mcp-tester compare http://server1:8080 http://server2:8080
For detailed usage, see examples/26-server-tester/README.md.
See the examples directory for detailed documentation.
PMCP serves as the foundation for building background agents that provide continuous AI assistance. See our Background Agents Guide for examples including:
ToolResult
type alias now available from crate root: use pmcp::ToolResult;
CallToolResult
- they are the same typecargo run --example toolresult_usage
demonstrating all features#[tool]
attribute for automatic tool handler generation#[tool_router]
for collecting tools from impl blocksFull WebSocket support with automatic reconnection, exponential backoff, and keep-alive ping/pong.
HTTP transport with Server-Sent Events for real-time notifications and long-polling support.
Native support for model sampling operations with the createMessage
API:
let result = client.create_message(CreateMessageRequest {
messages: vec![SamplingMessage {
role: Role::User,
content: Content::Text { text: "Hello!".to_string() },
}],
..Default::default()
}).await?;
Powerful middleware chain for request/response processing:
use pmcp::{MiddlewareChain, LoggingMiddleware, AuthMiddleware};
let mut chain = MiddlewareChain::new();
chain.add(Arc::new(LoggingMiddleware::default()));
chain.add(Arc::new(AuthMiddleware::new("token".to_string())));
Optimize notification delivery with batching and debouncing:
use pmcp::{MessageBatcher, BatchingConfig};
let batcher = MessageBatcher::new(BatchingConfig {
max_batch_size: 10,
max_wait_time: Duration::from_millis(100),
..Default::default()
});
use pmcp::{Client, StdioTransport, ClientCapabilities};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create client with stdio transport
let transport = StdioTransport::new();
let mut client = Client::new(transport);
// Initialize connection
let server_info = client.initialize(ClientCapabilities::default()).await?;
println!("Connected to: {}", server_info.server_info.name);
// List available tools
let tools = client.list_tools(None).await?;
for tool in tools.tools {
println!("Tool: {} - {:?}", tool.name, tool.description);
}
// Call a tool
let result = client.call_tool("get-weather", serde_json::json!({
"location": "San Francisco"
})).await?;
Ok(())
}
use pmcp::{Server, ServerCapabilities, ToolHandler};
use async_trait::async_trait;
use serde_json::Value;
struct WeatherTool;
#[async_trait]
impl ToolHandler for WeatherTool {
async fn handle(&self, args: Value) -> pmcp::Result<Value> {
let location = args["location"].as_str()
.ok_or_else(|| pmcp::Error::validation("location required"))?;
// Implement weather fetching logic
Ok(serde_json::json!({
"temperature": 72,
"condition": "sunny",
"location": location
}))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let server = Server::builder()
.name("weather-server")
.version("1.0.0")
.capabilities(ServerCapabilities::tools_only())
.tool("get-weather", WeatherTool)
.build()?;
// Run with stdio transport
server.run_stdio().await?;
Ok(())
}
let transport = StdioTransport::new();
use pmcp::{StreamableHttpTransport, StreamableHttpTransportConfig};
let config = StreamableHttpTransportConfig {
url: "http://localhost:3000".parse()?,
enable_sse: true, // Use SSE for real-time updates
session_id: Some("my-session".to_string()),
..Default::default()
};
let transport = StreamableHttpTransport::new(config);
use pmcp::{StreamableHttpTransport, StreamableHttpTransportConfig};
let config = StreamableHttpTransportConfig {
url: "http://localhost:8081".parse()?,
enable_sse: false, // Simple request/response
session_id: None, // No session management
..Default::default()
};
let transport = StreamableHttpTransport::new(config);
use pmcp::{WebSocketTransport, WebSocketConfig};
let config = WebSocketConfig {
url: "ws://localhost:8080".parse()?,
auto_reconnect: true,
..Default::default()
};
let transport = WebSocketTransport::new(config);
// For WebSocket in browser
use pmcp::{WasmWebSocketTransport};
let transport = WasmWebSocketTransport::connect("ws://localhost:8080").await?;
// For HTTP in browser
use pmcp::{WasmHttpTransport, WasmHttpConfig};
let config = WasmHttpConfig {
url: "https://api.example.com/mcp".to_string(),
extra_headers: vec![],
};
let transport = WasmHttpTransport::new(config);
# Clone the repository
git clone https://github.com/paiml/rust-pmcp
cd rust-pmcp
# Install development tools
make setup
# Run quality checks
make quality-gate
This project maintains Toyota Way and PMAT-level quality standards:
unwrap()
: All errors handled explicitly with comprehensive error types# Run all tests
make test-all
# Run property tests (slower, more thorough)
make test-property
# Generate coverage report
make coverage
# Run mutation tests
make mutants
git checkout -b feature/amazing-feature
)make quality-gate
)git push origin feature/amazing-feature
)pmcp/
โโโ src/
โ โโโ client/ # Client implementation
โ โโโ server/ # Server implementation
โ โโโ shared/ # Shared transport/protocol code
โ โโโ types/ # Protocol type definitions
โ โโโ utils/ # Utility functions
โโโ tests/
โ โโโ integration/ # Integration tests
โ โโโ property/ # Property-based tests
โโโ benches/ # Performance benchmarks
โโโ examples/ # Example implementations
Feature | TypeScript SDK | Rust SDK |
---|---|---|
Protocol Versions | 2024-10-07+ | 2024-10-07+ |
Transports | stdio, SSE, WebSocket | stdio, SSE, WebSocket |
Authentication | OAuth 2.0, Bearer | OAuth 2.0, Bearer |
Tools | โ | โ |
Prompts | โ | โ |
Resources | โ | โ |
Sampling | โ | โ |
Run benchmarks:
make bench # General benchmarks
cargo run --example 32_simd_parsing_performance # SIMD-specific benchmarks
This project is licensed under the MIT License - see the LICENSE file for details.