This directory contains high-performance Rust implementations of compute-intensive MCP Gateway plugins, built with PyO3 for seamless Python integration.
| Plugin | Python (baseline) | Rust | Speedup |
|---|---|---|---|
| PII Filter | ~10ms/request | ~1-2ms/request | 5-10x |
| Secrets Detection | ~5ms/request | ~0.8ms/request | 5-8x |
| SQL Sanitizer | ~3ms/request | ~0.6ms/request | 4-6x |
Overall Impact: 3-5x gateway throughput improvement with all Rust plugins enabled.
# Install MCP Gateway with Rust acceleration
pip install mcpgateway[rust]Supported platforms:
- Linux x86_64 (glibc 2.17+)
- macOS x86_64 (10.12+)
- macOS ARM64 (11.0+)
- Windows x86_64
# Install Rust toolchain
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Install maturin
pip install maturin
# Build and install
cd plugins_rust
maturin develop --releaseplugins_rust/
βββ Cargo.toml # Rust dependencies and build config
βββ pyproject.toml # Python packaging config
βββ README.md # This file - Quick start guide
βββ QUICKSTART.md # Getting started guide
βββ Makefile # Build automation
βββ src/
β βββ lib.rs # PyO3 module entry point
β βββ pii_filter/ # PII Filter implementation
β βββ mod.rs # Module exports
β βββ detector.rs # Core detection logic
β βββ patterns.rs # Regex pattern compilation
β βββ masking.rs # Masking strategies
β βββ config.rs # Configuration types
βββ benches/ # Rust criterion benchmarks
β βββ pii_filter.rs
βββ benchmarks/ # Python vs Rust comparison
β βββ README.md # Benchmarking guide
β βββ compare_pii_filter.py
β βββ results/ # JSON benchmark results
β βββ docs/ # Benchmark documentation
βββ tests/ # Integration tests
β βββ integration.rs
βββ docs/ # Development documentation
βββ implementation-guide.md # Implementation details
βββ build-and-test.md # Build and test results
Rust plugins are automatically detected at runtime with graceful fallback:
# Python side (plugins/pii_filter/pii_filter.py)
try:
from plugins_rust import PIIDetectorRust
detector = PIIDetectorRust(config) # 5-10x faster
except ImportError:
detector = PythonPIIDetector(config) # FallbackNo code changes needed! The plugin automatically uses the fastest available implementation.
# Fast debug build
maturin develop
# Optimized release build
maturin develop --release# Rust unit tests
cargo test
# Python integration tests
pytest ../tests/unit/mcpgateway/plugins/test_pii_filter_rust.py
# Differential tests (Rust vs Python)
pytest ../tests/differential/# Criterion benchmarks (HTML reports in target/criterion/)
cargo bench
# Python comparison benchmarks
python benchmarks/compare_pii_filter.py# Format code
cargo fmt
# Lint with clippy
cargo clippy -- -D warnings
# Check for security vulnerabilities
cargo audit// Instead of testing each pattern sequentially (Python):
// O(N patterns Γ M text length)
for pattern in patterns {
if pattern.search(text) { ... }
}
// Use RegexSet for single-pass matching (Rust):
// O(M text length)
let set = RegexSet::new(patterns)?;
let matches = set.matches(text); // All patterns in one pass!Result: 5-10x faster regex matching
use std::borrow::Cow;
fn mask(text: &str, detections: &[Detection]) -> Cow<str> {
if detections.is_empty() {
Cow::Borrowed(text) // Zero-copy when no PII
} else {
Cow::Owned(apply_masking(text, detections))
}
}Result: Zero allocations for clean payloads
fn traverse(value: &Value) -> Vec<Detection> {
match value {
Value::String(s) => detect_in_string(s),
Value::Object(map) => {
map.values().flat_map(|v| traverse(v)).collect()
}
// No cloning, just references
}
}Result: 3-5x faster nested structure processing
[profile.release]
opt-level = 3
lto = "fat" # Whole-program optimization
codegen-units = 1 # Maximum optimization
strip = true # Remove debug symbolsResult: Additional 10-20% speedup
cargo bench --bench pii_filterOutput:
PII Filter/detect/1KB time: [450.23 Β΅s 452.45 Β΅s 454.89 Β΅s]
PII Filter/detect/10KB time: [1.8234 ms 1.8456 ms 1.8701 ms]
PII Filter/detect/100KB time: [14.234 ms 14.567 ms 14.901 ms]
Compare to Python baseline:
- 1KB: 450Β΅s (Rust) vs 5ms (Python) = 11x faster
- 10KB: 1.8ms (Rust) vs 50ms (Python) = 27x faster
- 100KB: 14.5ms (Rust) vs 500ms (Python) = 34x faster
cargo install flamegraph
cargo flamegraph --bench pii_filter
# Opens flamegraph in browserEnsures Rust and Python produce identical outputs:
pytest ../tests/differential/test_pii_filter_differential.py -vThis runs 1000+ test cases through both implementations and asserts byte-for-byte identical results.
Uses proptest to generate random inputs:
proptest! {
#[test]
fn test_never_crashes(text in ".*") {
let _ = detect_pii(&text, &patterns);
// Should never panic
}
}# Check for known vulnerabilities
cargo audit
# Review dependency tree
cargo treeAll dependencies are from crates.io with:
- >1000 downloads/month
- Active maintenance
- Security audit history
Rust provides guaranteed memory safety:
- β No buffer overflows
- β No use-after-free
- β No data races
- β No null pointer dereferences
# Address sanitizer (memory errors)
RUSTFLAGS="-Z sanitizer=address" cargo test --target x86_64-unknown-linux-gnu
# Thread sanitizer (data races)
RUSTFLAGS="-Z sanitizer=thread" cargo test --target x86_64-unknown-linux-gnuRust plugins export the same Prometheus metrics as Python:
pii_filter_detections_duration_seconds{implementation="rust"}
pii_filter_masking_duration_seconds{implementation="rust"}
pii_filter_detections_total{implementation="rust"}Compare Rust vs Python in Grafana dashboards.
Cause: Rust extension not built or not on Python path
Solution:
cd plugins_rust
maturin develop --releaseCause: ABI mismatch between Python versions
Solution:
# Use Python 3.11+ with stable ABI
pip install maturin
maturin develop --releaseCause: Debug build instead of release build
Solution:
# Always use --release for benchmarks
maturin develop --releaseexport MCPGATEWAY_FORCE_PYTHON_PLUGINS=true
python -m mcpgateway.main# Dockerfile
FROM python:3.11-slim
# Install Rust toolchain
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"
# Install maturin
RUN pip install maturin
# Copy and build Rust plugins
COPY plugins_rust/ /app/plugins_rust/
WORKDIR /app/plugins_rust
RUN maturin build --release
RUN pip install target/wheels/*.whl
# Rest of Dockerfile...- Build with
--releaseflag - Run
cargo audit(no vulnerabilities) - Run differential tests (100% compatibility)
- Benchmark in staging (verify 5-10x speedup)
- Monitor metrics (Prometheus)
- Gradual rollout (canary deployment)
- Quick Start Guide - Get started in 5 minutes
- Benchmarking Guide - Performance testing
- Implementation Guide - Architecture and design
- Build & Test Results - Test coverage and benchmarks
See main CONTRIBUTING.md for general guidelines.
Rust-specific requirements:
- Run
cargo fmtbefore committing - Run
cargo clippyand fix all warnings - Add tests for new functionality
- Add benchmarks for performance-critical code
- Update documentation
Apache License 2.0 - See LICENSE file for details.