Rust Plugins - High-Performance Native ExtensionsΒΆ
Production Ready
Rust plugins provide 5-10x performance improvements for computationally intensive operations while maintaining 100% API compatibility with Python plugins.
OverviewΒΆ
MCP Gateway supports high-performance Rust implementations of plugins through PyO3 bindings. Each Rust plugin is fully independent with its own build configuration, providing significant performance benefits for computationally expensive operations while maintaining transparent Python integration.
Key BenefitsΒΆ
- π 5-10x Performance: Native compilation, zero-copy operations, parallel processing
- π Seamless Integration: Automatic fallback to Python when Rust unavailable
- π¦ Zero Breaking Changes: Identical API to Python plugins
- βοΈ Auto-Detection: Automatically uses Rust when available
- π‘οΈ Memory Safe: Rust's ownership system prevents common bugs
- π§ Easy Deployment: Single wheel package, no manual compilation needed
ArchitectureΒΆ
Independent Plugin StructureΒΆ
plugins_rust/
βββ [plugin_name]/ # Each plugin is fully independent
β βββ Cargo.toml # Rust dependencies
β βββ pyproject.toml # Python packaging
β βββ Makefile # Build commands
β βββ src/ # Rust source code
βββ [another_plugin]/ # Another independent plugin
Hybrid Python + Rust DesignΒΆ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Python Plugin Layer (plugins/[name]/plugin.py) β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Auto-Detection Logic β β
β β - Check Rust availability β β
β β - Select implementation β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β
β βββββββββ΄βββββββ βββββββββ΄βββββββββ β
β β Rust Wrapper β β Python Fallbackβ β
β β (5-10x fast)β β (Pure Python) β β
β βββββββββ¬βββββββ ββββββββββββββββββ β
ββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββ
β
β PyO3 Bindings
βΌ
ββββββββββββββββββββββββββββββββββββββββ
β Rust Implementation (plugins_rust/) β
β β
β ββββββββββββββββββββββββββββββββββ β
β β Plugin Engine β β
β β - Parallel processing β β
β β - Zero-copy operations β β
β β - Efficient algorithms β β
β ββββββββββββββββββββββββββββββββββ β
β β
β Compiled to: plugin_rust.so β
ββββββββββββββββββββββββββββββββββββββββ
InstallationΒΆ
Option 1: Build from Source (Recommended)ΒΆ
# Install Rust toolchain using the official instructions:
# https://rustup.rs/
# Build specific plugin
cd plugins_rust/[plugin_name]
make install
# Or build all plugins from project root
make rust-dev
Option 2: Use Python FallbackΒΆ
# Standard installation (Python-only)
pip install mcpgateway
# Rust plugins will gracefully fall back to Python implementations
ConfigurationΒΆ
Plugin ConfigurationΒΆ
No changes needed! Rust plugins use the same configuration as Python:
# plugins/config.yaml
plugins:
- name: "MyPlugin"
kind: "plugins.my_plugin.my_plugin.MyPlugin"
hooks:
- "prompt_pre_fetch"
- "tool_pre_invoke"
mode: "enforce"
priority: 50
config:
# Plugin-specific configuration
option1: true
option2: "value"
UsageΒΆ
Automatic DetectionΒΆ
The plugin system automatically detects and uses the Rust implementation:
from plugins.my_plugin.my_plugin import MyPlugin
from plugins.framework import PluginConfig
# Create plugin (automatically uses Rust if available)
config = PluginConfig(
name="my_plugin",
kind="plugins.my_plugin.my_plugin.MyPlugin",
config={}
)
plugin = MyPlugin(config)
# Check which implementation is being used
print(f"Implementation: {plugin.implementation}")
# Output: "rust" or "python"
Direct API UsageΒΆ
You can also use the implementations directly:
# Use Rust implementation explicitly
from plugin_rust.plugin_rust import PluginRust
config = {"option1": True, "option2": "value"}
plugin = PluginRust(config)
# Use plugin methods
result = plugin.process(data)
VerificationΒΆ
Check InstallationΒΆ
# Verify Rust plugin is available
python -c "from plugin_rust.plugin_rust import PluginRust; print('β Rust plugin available')"
# Check implementation being used
python -c "
from plugins.my_plugin.my_plugin import MyPlugin
from plugins.framework import PluginConfig
config = PluginConfig(name='test', kind='test', config={})
plugin = MyPlugin(config)
print(f'Implementation: {plugin.implementation}')
"
LoggingΒΆ
The gateway logs which implementation is being used:
# With Rust available
INFO - β Plugin: Using Rust implementation (5-10x faster)
# Without Rust
WARNING - Plugin: Using Python implementation
WARNING - π‘ Build Rust plugins for better performance
Building from SourceΒΆ
PrerequisitesΒΆ
- Rust 1.70+ (install via the official
rustupinstructions at https://rustup.rs/) - Python 3.11+
- maturin (
pip install maturin)
Build StepsΒΆ
# Navigate to a specific Rust plugin directory
cd plugins_rust/pii_filter
# Build in development mode (with debug symbols)
maturin develop
# Build in release mode (optimized)
maturin develop --release
# Build wheel package
maturin build --release
Using MakeΒΆ
# From project root (builds all plugins)
make rust-dev # Build and install (development mode)
make rust-build # Build release wheel
make rust-test # Run Rust unit tests
make rust-verify # Verify installation
# From individual plugin directory
cd plugins_rust/pii_filter
make develop # Build and install
make test # Run tests
make bench # Run benchmarks
make bench-compare # Compare Rust vs Python performance
Performance BenchmarkingΒΆ
Built-in BenchmarksΒΆ
# Run Rust benchmarks (Criterion) for a specific plugin
cd plugins_rust/pii_filter
make bench
# Run Python vs Rust comparison
make bench-compare
# Or from project root (runs all plugin benchmarks)
make rust-bench
Sample Benchmark OutputΒΆ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PII Filter Performance Comparison: Python vs Rust
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1. Single SSN Detection
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Python: 0.150 ms (7.14 MB/s)
Rust: 0.020 ms (53.57 MB/s)
Speedup: 7.5x faster
2. Multiple PII Types Detection
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Python: 0.300 ms (3.57 MB/s)
Rust: 0.040 ms (26.79 MB/s)
Speedup: 7.5x faster
3. Large Text Performance (1000 PII instances)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Python: 150.000 ms (0.71 MB/s)
Rust: 18.000 ms (5.95 MB/s)
Speedup: 8.3x faster
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Summary
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Average Speedup: 7.8x
β GREAT: 5-10x speedup - Recommended for production
TestingΒΆ
Running TestsΒΆ
# Rust unit tests (from a specific plugin directory)
cd plugins_rust/pii_filter
cargo test
# Python integration tests
pytest tests/unit/mcpgateway/plugins/test_pii_filter.py
# Differential tests (Rust vs Python compatibility)
pytest tests/differential/test_pii_filter_differential.py
# Or use make
make rust-test-all # Run all tests
Test CoverageΒΆ
The Rust plugin system includes comprehensive testing:
- Rust Unit Tests: 14 tests covering core Rust functionality
- Python Integration Tests: 45 tests covering PyO3 bindings
- Differential Tests: 40+ tests ensuring Rust = Python outputs
- Performance Tests: Benchmarks verifying >5x speedup
TroubleshootingΒΆ
Rust Plugin Not AvailableΒΆ
Symptom: Logs show "Using Python implementation"
Solutions:
# 1. Check if Rust extension is installed
python -c "from pii_filter import PIIDetectorRust; print('OK')"
# 2. Build from source
cd plugins_rust/pii_filter
maturin develop --release
Import ErrorsΒΆ
Symptom: ImportError: cannot import name 'PIIDetectorRust'
Solutions:
# 1. Verify installation
pip list | grep mcpgateway-pii-filter
# 2. Rebuild
cd plugins_rust/pii_filter
maturin develop --release
# 3. Check Python version (requires 3.11+)
python --version
Performance Not ImprovedΒΆ
Symptom: No performance difference between Python and Rust
Checks:
# Verify Rust implementation is being used
from plugins.my_plugin.my_plugin import MyPlugin
plugin = MyPlugin(config)
assert plugin.implementation == "rust", "Not using Rust!"
Build FailuresΒΆ
Symptom: maturin develop fails
Common Causes:
- Rust not installed: Install from https://rustup.rs
- Wrong Rust version: Update with
rustup update - Missing dependencies:
cargo clean && cargo build - Python version mismatch: Ensure Python 3.11+
Development GuideΒΆ
Creating New Rust PluginsΒΆ
-
Create Plugin Directory:
-
Initialize Rust Project:
-
Implement PyO3 Bindings:
// src/lib.rs use pyo3::prelude::*; #[pyclass] pub struct MyPluginRust { // Plugin state } #[pymethods] impl MyPluginRust { #[new] pub fn new(config: &PyDict) -> PyResult<Self> { Ok(Self { /* ... */ }) } pub fn process(&self, text: &str) -> PyResult<String> { Ok(text.to_uppercase()) } } #[pymodule] fn my_plugin_rust(_py: Python, m: &PyModule) -> PyResult<()> { m.add_class::<MyPluginRust>()?; Ok(()) } -
Create Python Wrapper:
Note: The double-nested import (my_plugin_rust.my_plugin_rust) is required because: - First my_plugin_rust = package name (from Cargo.toml [lib] name) - Second my_plugin_rust = module name (from #[pymodule] in lib.rs)
- Add Auto-Detection:
Best PracticesΒΆ
- API Compatibility: Ensure Rust and Python implementations have identical APIs
- Error Handling: Convert Rust errors to Python exceptions properly
- Type Conversions: Use PyO3's
extract()andIntoPyfor seamless conversions - Testing: Write differential tests to ensure identical behavior
- Documentation: Document performance characteristics and trade-offs
CI/CD IntegrationΒΆ
GitHub Actions WorkflowΒΆ
The repository includes automated CI/CD for Rust plugins:
# .github/workflows/rust-plugins.yml
- Multi-platform builds (Linux, macOS, Windows)
- Rust linting (clippy, rustfmt)
- Comprehensive testing (unit, integration, differential)
- Performance benchmarking
- Security audits (cargo-audit)
- Code coverage tracking
- Automatic wheel publishing to PyPI
Local CI ChecksΒΆ
# Run full CI pipeline locally
make rust-check # Format, lint, test
make rust-test-all # All test suites
make rust-bench # Performance benchmarks
make rust-audit # Security audit
make rust-coverage # Code coverage report
Performance OptimizationsΒΆ
Rust-Specific OptimizationsΒΆ
- RegexSet for Parallel Matching: All patterns matched in single pass (O(M) vs O(NΓM))
- Copy-on-Write Strings: Zero-copy when no masking needed
- Stack Allocation: Minimize heap allocations for hot paths
- Inlining: Aggressive inlining for small functions
- LTO (Link-Time Optimization): Enabled in release builds
Configuration for Best PerformanceΒΆ
# plugins_rust/Cargo.toml
[profile.release]
opt-level = 3 # Maximum optimization
lto = "fat" # Full link-time optimization
codegen-units = 1 # Better optimization, slower compile
strip = true # Strip symbols for smaller binary
Security ConsiderationsΒΆ
Memory SafetyΒΆ
- No Buffer Overflows: Rust's ownership system prevents them at compile-time
- No Use-After-Free: Borrow checker ensures memory safety
- No Data Races: Safe concurrency guarantees
- Input Validation: All Python inputs validated before processing
Audit and ComplianceΒΆ
Future Rust PluginsΒΆ
Planned Rust implementations:
- Regex Filter: Pattern matching and replacement (5-8x speedup)
- JSON Repair: Fast JSON validation and repair (10x+ speedup)
- SQL Sanitizer: SQL injection detection (8-10x speedup)
- Rate Limiter: High-throughput rate limiting (15x+ speedup)
- Compression: Fast compression/decompression (5-10x speedup)
ResourcesΒΆ
DocumentationΒΆ
Project FilesΒΆ
plugins_rust/README.md- Detailed Rust plugin documentationplugins_rust/IMPLEMENTATION_STATUS.md- Implementation status and resultsplugins_rust/BUILD_AND_TEST_RESULTS.md- Build and test report
CommunityΒΆ
- GitHub Issues: https://github.com/IBM/mcp-context-forge/issues
- Contributing: See
CONTRIBUTING.md
Migration GuideΒΆ
From Python to RustΒΆ
If you have an existing Python plugin you want to optimize:
- Measure First: Profile to identify bottlenecks
- Start Small: Convert hot paths first
- Maintain API: Keep identical interface for drop-in replacement
- Test Thoroughly: Use differential testing
- Benchmark: Verify actual performance improvements
Gradual MigrationΒΆ
You don't need to convert entire plugins at once:
class MyPlugin(Plugin):
def __init__(self, config):
# Use Rust for expensive operations
if RUST_AVAILABLE:
self.detector = RustDetector(config)
else:
self.detector = PythonDetector(config)
# Keep other logic in Python
self.cache = {}
self.stats = PluginStats()
async def process(self, payload, context):
# Rust-accelerated detection
results = self.detector.detect(payload.text)
# Python logic for everything else
self.update_stats(results)
return self.format_response(results)
SupportΒΆ
For issues, questions, or contributions related to Rust plugins:
- Check existing GitHub issues
- Review build and test documentation
-
Open a new issue with:
-
Rust/Python versions
- Build logs
- Error messages
- Minimal reproduction case
Status: Production Ready Performance: 5-10x faster than Python Compatibility: 100% API compatible Installation: pip install mcpgateway[rust]