
pmcp
io.github.paiml/pmcp
High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
Documentation
PMCP - Pragmatic Model Context Protocol
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+.
Quick Start
Installation
Add to your Cargo.toml
:
[dependencies]
pmcp = "1.6"
Type-Safe Tools with Automatic Schema Generation (v1.6.0+)
Create tools with compile-time type safety and automatic JSON schema generation:
use pmcp::{ServerBuilder, TypedTool, TypedSyncTool, SimpleToolExt};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
// Define your argument type with JsonSchema derive
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct CalculatorArgs {
operation: String,
a: f64,
b: f64,
}
// Create a server with typed tools
let server = ServerBuilder::new()
.name("calculator-server")
.version("1.0.0")
// Use the new tool_typed builder method
.tool_typed("calculator", |args: CalculatorArgs, _extra| {
Box::pin(async move {
let result = match args.operation.as_str() {
"add" => args.a + args.b,
"subtract" => args.a - args.b,
"multiply" => args.a * args.b,
"divide" => args.a / args.b,
_ => return Err(pmcp::Error::Validation("Unknown operation".into())),
};
Ok(serde_json::json!({ "result": result }))
})
})
.build()?;
The schema is automatically generated and included in the tools/list
response, enabling:
- Type Safety: Arguments are validated at compile time
- Auto-completion: Clients can provide better UI based on schema
- Documentation: Schema includes descriptions from doc comments
- Validation: Runtime validation against the generated schema
๐ Version 1.8.0 - OAuth Auth Context & Server Middleware Enhancements!
๐ BREAKING CHANGE: OAuth Auth Context Pass-Through
-
๐ฏ Production-Ready OAuth: Full token pass-through from transport โ middleware โ tools
- โ
New Parameter:
ProtocolHandler::handle_request()
now acceptsauth_context: Option<AuthContext>
- โ
Transport Integration:
StreamableHttpServer
extracts and validates OAuth from Authorization headers - โ
Middleware Pattern: Tool middleware can inject tokens into
RequestHandlerExtra
metadata - โ DRY Tools: No repetitive auth code - tools consume tokens from metadata
- โ
New Parameter:
-
๐ Migration Guide:
// Update all handle_request calls to pass auth_context: server.handle_request(id, request, None).await // Add None for no auth // In transport layer (e.g., HTTP): let auth_context = auth_provider.validate_request(auth_header).await?; server.handle_request(id, request, auth_context).await
-
๐ New Resources:
- Example 58: Complete OAuth flow demonstration
- Integration tests:
tests/auth_context_integration_test.rs
- Updated Example 57: OAuth middleware best practices
๐ Version 1.7.0 - ClientCapabilities Schema Fix for MCP Specification Compliance!
๐ก๏ธ BREAKING CHANGE: Fixed ClientCapabilities Schema
-
๐ง Spec Compliance:
ClientCapabilities
now matches the official MCP specification- โ REMOVED:
tools
,prompts
,resources
,logging
fields (these are SERVER capabilities only) - โ
ADDED:
elicitation
field for user input support - โ
KEPT:
sampling
,roots
,experimental
(valid client capabilities)
- โ REMOVED:
-
๐ฏ Why This Matters:
- โ Cursor IDE Compatible: Fixes "Method not found: initialize" errors with spec-compliant clients
- โ TypeScript SDK Parity: Now 100% compatible with official TypeScript SDK
- โ mcp-tester Fixed: Universal testing tool now sends correct capabilities
- ๐ Clear Separation: Client capabilities (what client can do) vs Server capabilities (what server provides)
-
๐ Migration Guide:
// Before (WRONG - not spec compliant): let caps = ClientCapabilities { tools: Some(ToolCapabilities::default()), // โ Invalid for clients prompts: Some(PromptCapabilities::default()), // โ Invalid for clients ..Default::default() }; // After (CORRECT - spec compliant): let caps = ClientCapabilities { sampling: Some(SamplingCapabilities::default()), // โ Client can handle sampling requests elicitation: Some(ElicitationCapabilities::default()), // โ Client can provide user input roots: Some(RootsCapabilities::default()), // โ Client supports roots notifications ..Default::default() }; // Or simply use minimal() for most clients: let caps = ClientCapabilities::minimal();
-
๐จ What Changed:
- API: Removed
supports_tools()
,supports_prompts()
,supports_resources()
fromClientCapabilities
- API: Added
supports_elicitation()
toClientCapabilities
- All examples updated to use correct capabilities
- mcp-tester fixed to send spec-compliant capabilities
- Documentation clarifies client vs server capabilities
- API: Removed
-
โ Wire Protocol Compatibility: Existing servers remain compatible - old clients will still work, but should be updated
๐ Version 1.6.2 - Hybrid Workflow Execution & Server-Side Resource Fetching!
๐ Prompts as Workflows - Built-in Support
-
Hybrid Execution Model: Server executes deterministic steps, client continues with full context
- ๐ Compliance Improvement: ~60-70% (instruction-only) โ ~85-95% (hybrid execution)
- ๐ Server-Side Tool Execution: Tools execute during
prompts/get
, return conversation traces - ๐ Resource Embedding: Automatic fetch and embed of documentation/context
- ๐ฏ Graceful Handoff: Server does deterministic work, hands off with guidance
-
New Workflow Features:
- โจ
.with_guidance(text)
: Assistant messages explaining what steps should do - ๐ฆ
.with_resource(uri)
: Server-side resource fetching and embedding - ๐ Argument Substitution:
{arg_name}
placeholders in guidance replaced with actual values - ๐ค Client Autonomy Awareness: Designed for autonomous MCP clients that can follow, ignore, or modify instructions
- โจ
-
Complete Hybrid Execution:
- Server creates user intent + assistant plan messages
- Server executes steps with resolved parameters
- Server fetches and embeds resources as user messages
- Server stops when parameters need LLM reasoning (graceful handoff)
- Client receives: tool results + resources + guidance โ continues with complete context
๐ New Example:
54_hybrid_workflow_execution
- Logseq task creation with fuzzy matching and resource embedding
๐ Documentation:
- Updated Chapter 7 with hybrid execution model, client autonomy, and compliance metrics
๐ Version 1.6.0 - Production-Ready Type-Safe Tools & Cross-Transport Support!
๐ Type-Safe Schema Generation Enhancement
-
Production-Ready Improvements:
- ๐ Schema Normalization: Configurable depth/size limits prevent huge expanded schemas
- ๐ฏ Consistent Error Codes: Standardized validation error codes for client elicitation
- ๐ Cross-Platform Path Validation: Robust Windows/Unix path handling with security constraints
- ๐ Output Typing: Optional
TypedToolWithOutput<TIn, TOut>
for better testing and documentation
-
Cross-Transport Support ("Write Once, Run Anywhere"):
- โ Transport Compatibility: Typed tools work seamlessly across HTTP, SSE, and WebSocket
- ๐ WASM Support: Browser and Cloudflare Workers compatible typed tool API (input typing only)
- ๐งช Comprehensive Testing: E2E transport tests ensure compatibility
- ๐๏ธ Ergonomic Builder: New
tool_typed()
andtool_typed_sync()
builder methods
-
Validation Helpers:
- ๐ง Email, URL, and regex pattern validation
- ๐ข Range, length, and array size validation
- ๐ก๏ธ Path traversal protection
- ๐ค Elicitation-friendly error responses
๐ New Examples:
32_typed_tools
- Basic typed tool usage with automatic schemas33_advanced_typed_tools
- Complex validation and nested structures34_serverbuilder_typed
- Using the ergonomic builder methods35_wasm_typed_tools
- WASM-compatible typed tools for browser/edge
๐ Version 1.5.5 - Type-Safe Schema Generation & Critical Fixes!
๐ก๏ธ Type-Safe Tool Creation with Automatic Schema Generation
- ๐ฏ TypedTool & TypedSyncTool: Type-safe tool implementations with automatic JSON schema generation
- ๐ Schema Generation: Automatic schema generation from Rust types using
schemars
- โจ Extension Traits:
SimpleToolExt
andSyncToolExt
for adding schemas to existing tools - ๐ Compile-Time Validation: Type checking at compile time for tool arguments
- ๐ Example: New
32_typed_tools
example demonstrating all features
๐ Critical Bug Fix
- ๐ง Tool Description Serialization: Fixed critical bug where
SimpleTool.with_description()
wasn't properly serializing descriptions in thetools/list
response - โ
Metadata Handling: Corrected
handle_list_tools
to properly use tool metadata instead of hardcodingNone
๐ฏ Previous: Version 1.5.4 - Enhanced Testing & Metadata Support
- ๐ Schema Validation: Automatic validation of tool JSON schemas with detailed warnings
- ๐ค Scenario Generation: Auto-generate test scenarios from server capabilities
- ๐ฆ Resource Testing: Comprehensive resource discovery and validation
- ๐ฌ Prompt Testing: Full prompt template and argument validation
- ๐ Smart Value Generation: Context-aware test data based on schema definitions
๐ Version 1.4.2 - MCP Server Tester & Enhanced Compatibility!
๐งช NEW: MCP Server Tester Tool
- ๐ Protocol Compliance: Validates JSON-RPC 2.0 and MCP protocol compliance
- ๐ Multi-Transport Support: Tests HTTP, HTTPS, WebSocket, and stdio transports
- ๐ Comprehensive Diagnostics: Layer-by-layer connection troubleshooting
- ๐ฏ CI/CD Ready: JSON output for automated testing pipelines
๐ Version 1.4.1 - Enhanced Developer Experience & TypeScript Parity!
๐ง NEW: Enhanced Type Ergonomics
- โจ ToolResult Type Alias: Improved developer experience with
use pmcp::ToolResult
- ๐ Comprehensive Documentation: Enhanced API docs with 4 complete usage examples
- ๐งช 100% Test Coverage: Property tests, unit tests, and doctests for reliability
- ๐ฏ Backward Compatible: Zero breaking changes, seamless upgrade experience
๐ NEW: Complete Example Library
- ๐ค Tool-with-Sampling Server: Demonstrates LLM sampling integration for text processing
- ๐ Multiple Parallel Clients: Shows concurrent client operations and error handling
- ๐๏ธ Structured Output Schemas: Advanced data validation and structured responses
- ๐ TDD Methodology: All examples developed using Test-Driven Development
๐ญ Quality Excellence (v1.4.1)
- ๐ 72% Line Coverage: Comprehensive test coverage with 100% function coverage
- ๐ฏ Zero Defects: All quality gates passing (lint + coverage)
- ๐ Toyota Way Standards: Jidoka principles with zero tolerance for defects
- โ Full TypeScript SDK Compatibility: Complete feature parity verified
๐ Version 1.4.0 - High-Performance Enterprise Features!
๐ WebSocket Server & Advanced Transports
- ๐ Complete WebSocket Server: Production-ready server implementation with connection management
- โก HTTP/SSE Optimizations: 10x faster Server-Sent Events processing with connection pooling
- ๐ Connection Pooling: Smart load balancing across multiple transport connections
- ๐ก๏ธ Advanced Middleware: Circuit breakers, rate limiting, compression, and metrics collection
๐ง Advanced Error Recovery
- ๐ Adaptive Retry: Intelligent retry strategies with jitter and exponential backoff
- ๐ฅ Health Monitoring: Automatic cascade failure detection and prevention
- ๐ Recovery Metrics: Comprehensive error recovery analytics and monitoring
- โฑ๏ธ Deadline Management: Timeout-aware operations with deadline propagation
โก SIMD Parsing Acceleration
- ๐ฅ 10.3x SSE Parsing Speedup: Vectorized Server-Sent Events processing
- ๐ป CPU Feature Detection: Runtime AVX2/SSE4.2 optimization
- ๐ฆ Batch Processing: Parallel JSON-RPC parsing with 119% efficiency gains
- ๐ง Smart Fallbacks: Automatic scalar fallback when SIMD unavailable
๐ญ Toyota Way Quality Excellence
- ๐ PMAT Quality Analysis: Comprehensive code quality metrics with TDG scoring (0.76)
- ๐ฏ Quality Gates: Zero-tolerance defect policy with automated enforcement
- ๐ Fuzzing Infrastructure: Comprehensive fuzz testing for protocol robustness
- โ Full TypeScript SDK v1.17.5+ Compatibility: 100% protocol compatibility verified
- ๐ Performance: 16x faster than TypeScript SDK, 50x lower memory usage
Core Features
๐ Transport Layer
- ๐ Multiple Transports: stdio, HTTP/SSE, and WebSocket with auto-reconnection
- ๐ WebSocket Server: Complete server-side WebSocket transport implementation
- ๐ Connection Pooling: Smart load balancing with health monitoring
- โก HTTP/SSE Optimizations: High-performance streaming with connection pooling
- ๐พ Event Store: Connection resumability and event persistence for recovery
๐ก๏ธ Advanced Middleware & Recovery
- ๐ Middleware System: Circuit breakers, rate limiting, compression, metrics
- ๐ Adaptive Retry: Intelligent retry strategies with jitter and exponential backoff
- ๐ฅ Health Monitoring: Automatic cascade failure detection and prevention
- โฑ๏ธ Deadline Management: Timeout-aware operations with deadline propagation
- ๐ Recovery Metrics: Comprehensive error analytics and monitoring
โก High-Performance Parsing
- ๐ฅ SIMD Acceleration: 10.3x SSE parsing speedup with AVX2/SSE4.2 optimization
- ๐ฆ Batch Processing: Parallel JSON-RPC parsing with 119% efficiency gains
- ๐ง Smart CPU Detection: Runtime feature detection with automatic fallbacks
- ๐ป Zero-Copy Parsing: Efficient message handling with vectorized operations
๐ Security & Protocol
- ๐ Full Protocol Support: Complete implementation of MCP specification v1.0
- ๐ก๏ธ Type Safety: Compile-time protocol validation
- ๐ Built-in Auth: OAuth 2.0, OIDC discovery, and bearer token support
- ๐ URI Templates: Complete RFC 6570 implementation for dynamic URIs
- ๐ก SSE Parser: Full Server-Sent Events support for streaming responses
๐ค Developer Experience
- ๐ค LLM Sampling: Native support for model sampling operations
- ๐ฆ Message Batching: Efficient notification grouping and debouncing
- ๐ฌ Resource Subscriptions: Real-time resource change notifications
- โ Request Cancellation: Full async cancellation support with CancellationToken
- ๐ Roots Management: Directory/URI registration and management
- ๐ Comprehensive Testing: Property tests, fuzzing, and integration tests
- ๐๏ธ Quality First: Zero technical debt, no unwraps in production code
โ ๏ธ 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.
๐ WebAssembly Support
The SDK fully supports WebAssembly compilation for deployment to:
- Cloudflare Workers (wasm32-unknown-unknown)
- WASI Runtimes (wasm32-wasi)
- Browser Environments via wasm-bindgen
WASM Quick Start
# Build for Cloudflare Workers
cargo build --target wasm32-unknown-unknown --no-default-features --features wasm
# Deploy SDK-based Worker
make cloudflare-sdk-deploy
WASM Documentation
- WASM Target Guide - Detailed guide for different WASM targets
- WASM MCP Server Example - Write once, deploy everywhere (Cloudflare & Fermyon)
- WASM API Reference - WasmServerCore documentation
๐ Documentation
Complete PMCP Guide
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:
- Getting Started - Installation, first server/client
- Core Concepts - Tools, resources, prompts, error handling
- Advanced Features - Auth, transports, middleware, performance
- Real-World Examples - Production patterns and best practices
- TypeScript Migration - Complete compatibility guide
Examples
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
# NEW in v1.6.0 - Type-Safe Tools with Schema Generation
# Type-safe tools with automatic JSON schema generation
cargo run --example 32_typed_tools --features schema-generation
# Advanced typed tools with complex validation and nested structures
cargo run --example 33_advanced_typed_tools --features schema-generation
# ServerBuilder typed tool methods demonstration
cargo run --example 34_serverbuilder_typed --features schema-generation
# WASM-compatible typed tools for browser and edge environments
cargo run --example 35_wasm_typed_tools --target wasm32-wasi --features schema-generation
# 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
MCP Server Tester
The SDK includes a comprehensive testing tool for validating MCP server implementations. The tester ensures protocol compliance, validates capabilities, and provides detailed diagnostics.
Features
- Protocol Compliance: Validates JSON-RPC 2.0 and MCP protocol compliance
- Multi-Transport Support: Tests HTTP, HTTPS, WebSocket, and stdio transports
- Comprehensive Diagnostics: Layer-by-layer connection troubleshooting
- Tool Testing: Discover and test individual tools with custom arguments
- CI/CD Ready: JSON output for automated testing pipelines
Installation
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
Usage
# 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 (includes Cursor IDE compatibility test)
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.
๐ค Background Agents
PMCP serves as the foundation for building background agents that provide continuous AI assistance. See our Background Agents Guide for examples including:
- PMAT - Continuous code quality monitoring with Toyota Way compliance
- Ruchy - Language server agent for the Ruchy programming language
- Build your own background agent using PMCP as the transport layer
What's New in v1.4.1 - Developer Experience Improvements
๐ง ToolResult Type Alias (GitHub Issue #37)
- New:
ToolResult
type alias now available from crate root:use pmcp::ToolResult;
- Compatibility: Fully compatible with existing
CallToolResult
- they are the same type - Documentation: Comprehensive documentation with examples and usage patterns
- Testing: Full test coverage including unit tests, property tests, and doctests
- Examples: New
cargo run --example toolresult_usage
demonstrating all features
What's New in v1.4.0 - Enterprise Performance Edition
๐ Production WebSocket Server (PMCP-4001)
- Complete server-side WebSocket implementation with connection lifecycle management
- Automatic ping/pong keepalive and graceful connection handling
- WebSocket-specific middleware integration and error recovery
- Production-ready with comprehensive connection monitoring
โก HTTP/SSE Transport Optimizations (PMCP-4002)
- 10x performance improvement in Server-Sent Events processing
- Connection pooling with intelligent load balancing strategies
- Optimized SSE parser with reduced memory allocations
- Enhanced streaming performance for real-time applications
๐ Advanced Connection Management (PMCP-4003)
- Smart connection pooling with health monitoring and failover
- Load balancing strategies: round-robin, least-connections, weighted
- Automatic unhealthy connection detection and replacement
- Connection pool metrics and monitoring integration
๐ก๏ธ Enterprise Middleware System (PMCP-4004)
- Advanced middleware chain with circuit breakers and rate limiting
- Compression middleware with configurable algorithms
- Metrics collection middleware with performance monitoring
- Priority-based middleware execution with dependency management
๐ง Advanced Error Recovery (PMCP-4005)
- Adaptive retry strategies with configurable jitter patterns
- Deadline-aware recovery with timeout propagation
- Bulk operation recovery with partial failure handling
- Health monitoring with cascade failure detection and prevention
- Recovery coordination with event-driven architecture
โก SIMD Parsing Acceleration (PMCP-4006)
- 10.3x SSE parsing speedup using AVX2/SSE4.2 vectorization
- Runtime CPU feature detection with automatic fallbacks
- Parallel JSON-RPC batch processing with 119% efficiency gains
- Memory-efficient SIMD operations with comprehensive metrics
What's New in v1.0 (In Development)
๐ฏ Procedural Macros
#[tool]
attribute for automatic tool handler generation#[tool_router]
for collecting tools from impl blocks- Automatic JSON schema generation from Rust types
- 70% reduction in boilerplate code
๐ Enhanced WASM Support
- Full WebAssembly support for browser environments
- Dual transport support: WebSocket and HTTP
- HTTP transport for stateless/serverless MCP servers (AWS Lambda, Vercel, etc.)
- Cross-platform runtime abstraction
- Interactive browser example with modern UI
- CORS-enabled streamable HTTP servers
- TypeScript definitions for seamless integration
๐ Streamable HTTP Transport
- Stateful mode with session management for traditional deployments
- Stateless mode optimized for serverless (AWS Lambda, Vercel Functions)
- Server-Sent Events (SSE) support for real-time streaming
- Automatic protocol version negotiation
- Built-in CORS support for browser clients
- Examples for both client and server implementations
๐ Enhanced Developer Experience
- Type-safe parameter handling with compile-time validation
- Automatic error conversion and handling
- Improved documentation with 200+ examples
- Property-based testing for all new features
What's New in v0.6.6
๐ OIDC Discovery Support
- Full OpenID Connect discovery implementation
- Automatic retry on CORS/network errors
- Token exchange with explicit JSON accept headers
- Comprehensive auth client module
๐ Transport Response Isolation
- Unique transport IDs prevent cross-transport response routing
- Enhanced protocol safety for multiple concurrent connections
- Request-response correlation per transport instance
๐ Enhanced Documentation
- 135+ doctests with real-world examples
- Complete property test coverage
- New OIDC discovery example (example 20)
What's New in v0.2.0
๐ WebSocket Transport with Auto-Reconnection
Full WebSocket support with automatic reconnection, exponential backoff, and keep-alive ping/pong.
๐ HTTP/SSE Transport
HTTP transport with Server-Sent Events for real-time notifications and long-polling support.
๐ LLM Sampling 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?;
๐ Middleware System
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())));
๐ Message Batching & Debouncing
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()
});
Client Example
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(())
}
Server Example
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(())
}
Transport Options
stdio (Default)
let transport = StdioTransport::new();
Streamable HTTP (Stateful)
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);
Streamable HTTP (Stateless/Serverless)
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);
WebSocket
use pmcp::{WebSocketTransport, WebSocketConfig};
let config = WebSocketConfig {
url: "ws://localhost:8080".parse()?,
auto_reconnect: true,
..Default::default()
};
let transport = WebSocketTransport::new(config);
WASM (Browser)
// 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);
Development
Prerequisites
- Rust 1.80.0 or later
- Git
Setup
# 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
Quality Standards
This project maintains Toyota Way and PMAT-level quality standards:
- Zero Technical Debt: TDG score 0.76, production-ready with minimal technical debt
- Toyota Way Principles: Jidoka (stop the line), Genchi Genbutsu (go and see), Kaizen (continuous improvement)
- Quality Gates: PMAT quality gates enforce complexity limits and detect SATD
- No
unwrap()
: All errors handled explicitly with comprehensive error types - 100% Documentation: Every public API documented with examples
- Property Testing: Comprehensive invariant testing with quickcheck
- Benchmarks: Performance regression prevention with criterion
- SIMD Optimizations: High-performance parsing with reduced complexity
Testing
# 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
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Ensure all quality checks pass (
make quality-gate
) - Commit your changes (following conventional commits)
- Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Architecture
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
Compatibility
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 | โ | โ |
Performance
SIMD-Accelerated Parsing Performance (v1.4.0)
- SSE parsing: 10.3x speedup (336,921 vs 32,691 events/sec)
- JSON-RPC parsing: 195,181 docs/sec with 100% SIMD utilization
- Batch processing: 119.3% parallel efficiency with vectorized operations
- Memory efficiency: 580 bytes per document with optimized allocations
General Performance vs TypeScript SDK
- Overall performance: 16x faster than TypeScript SDK
- Message parsing: < 1ฮผs (sub-microsecond with SIMD)
- Round-trip latency: < 100ฮผs (stdio)
- Memory usage: 50x lower baseline (< 10MB)
- Base64 operations: 252+ MB/s throughput
Run benchmarks:
make bench # General benchmarks
cargo run --example 32_simd_parsing_performance # SIMD-specific benchmarks
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Model Context Protocol specification
- TypeScript SDK for reference implementation
- PAIML MCP Agent Toolkit for quality standards
- Alternative implementation - official rust sdk - created before I knew this existed.
No installation packages available.