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:
[]
= "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 ;
use JsonSchema;
use ;
// Define your argument type with JsonSchema derive
// Create a server with typed tools
let server = new
.name
.version
// Use the new tool_typed builder method
.tool_typed
.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.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:
SimpleToolExtandSyncToolExtfor adding schemas to existing tools - ð Compile-Time Validation: Type checking at compile time for tool arguments
- ð Example: New
32_typed_toolsexample demonstrating all features
ð Critical Bug Fix
- ð§ Tool Description Serialization: Fixed critical bug where
SimpleTool.with_description()wasn't properly serializing descriptions in thetools/listresponse - â
Metadata Handling: Corrected
handle_list_toolsto 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
# Deploy SDK-based Worker
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
# Other book commands
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
# Basic server with tools
# Client tool usage
# Server with resources
# Client resource access
# Server with prompts
# Client prompts usage
# Logging
# Authentication (OAuth, Bearer tokens)
# Progress notifications
# Request cancellation
# Error handling patterns
# WebSocket transport
# LLM sampling operations
# Middleware and interceptors
# OAuth server with authentication
# Completable prompts
# Resource watching with file system monitoring
# Input elicitation
# OIDC discovery and authentication
# Procedural macros for tools
# Streamable HTTP server (stateful with sessions)
# Streamable HTTP server (stateless for serverless)
# Streamable HTTP client
# WASM client (browser-based) - see examples/wasm-client/README.md
&&
# WebSocket server implementation with connection management
# MCP server tester - comprehensive testing tool for MCP servers
# HTTP/SSE transport optimizations with connection pooling
# Connection pooling and load balancing demonstration
# Advanced middleware system with circuit breakers and rate limiting
# Advanced error recovery with adaptive retry and health monitoring
# Complete advanced error recovery example with cascade detection
# NEW in v1.6.0 - Type-Safe Tools with Schema Generation
# Type-safe tools with automatic JSON schema generation
# Advanced typed tools with complex validation and nested structures
# ServerBuilder typed tool methods demonstration
# WASM-compatible typed tools for browser and edge environments
# NEW in v1.4.1 - Enhanced Examples with TypeScript SDK Parity
# Multiple parallel clients with concurrent operations and error handling
# Structured output schemas with advanced data validation
# Tool with LLM sampling integration for text processing
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:
# Binary will be at target/release/mcp-tester
Usage
# Test an MCP server
# Test with tools validation
# Protocol compliance check
# Connection diagnostics
# Compare two servers
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:
ToolResulttype 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_usagedemonstrating 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.await?;
ð Middleware System
Powerful middleware chain for request/response processing:
use ;
let mut chain = new;
chain.add;
chain.add;
ð Message Batching & Debouncing
Optimize notification delivery with batching and debouncing:
use ;
let batcher = new;
Client Example
use ;
async
Server Example
use ;
use async_trait;
use Value;
;
async
Transport Options
stdio (Default)
let transport = new;
Streamable HTTP (Stateful)
use ;
let config = StreamableHttpTransportConfig ;
let transport = new;
Streamable HTTP (Stateless/Serverless)
use ;
let config = StreamableHttpTransportConfig ;
let transport = new;
WebSocket
use ;
let config = WebSocketConfig ;
let transport = new;
WASM (Browser)
// For WebSocket in browser
use ;
let transport = connect.await?;
// For HTTP in browser
use ;
let config = WasmHttpConfig ;
let transport = new;
Development
Prerequisites
- Rust 1.80.0 or later
- Git
Setup
# Clone the repository
# Install development tools
# Run quality checks
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
# Run property tests (slower, more thorough)
# Generate coverage report
# Run mutation tests
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:
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.