prism-mcp-rs

mcp
Guvenlik Denetimi
Basarisiz
Health Gecti
  • License — License: MIT
  • Description — Repository has a description
  • Active repo — Last push 0 days ago
  • Community trust — 44 GitHub stars
Code Basarisiz
  • rm -rf — Recursive force deletion command in .github/workflows/ci.yml
Permissions Gecti
  • Permissions — No dangerous permissions requested

Bu listing icin henuz AI raporu yok.

SUMMARY

Enterprise-grade Rust implementation of Anthropic's MCP protocol

README.md

Prism MCP SDK for Rust

Crates.io
Downloads
Documentation
CI
Rust
MCP
Performance
Security Audit
codecov

License: MIT
MSRV
dependency status
Total Downloads
API Stability

Contributors
Last Commit
Release
Discord

prism-mcp-rs is a production-grade Rust SDK for building MCP servers and clients with typed protocol models, multi-transport support, and operational controls for real deployments.

Safety note: core library paths are safe Rust; plugin loading uses a narrow, audited unsafe FFI boundary.

Why prism-mcp-rs

This SDK targets teams that need more than baseline protocol wiring. It combines MCP conformance with reliability, observability, and security defaults expected in enterprise environments.

MCP 2025-11-25 Compliance Snapshot

Area Status
Core JSON-RPC + lifecycle Implemented
Metadata/UI fields (title, icons, _meta) Implemented
Sampling updates (tool_choice, stopReason) Implemented
Elicitation (form + URL modes) + completion notification Implemented
Task status updates + cancellation notifications Implemented
Auth challenge handling (HTTP 401/403) Implemented

What Differentiates It

  1. Production-first runtime controls: Circuit breakers, adaptive retries, and health checks are part of the SDK, not external glue code.
  2. Rust-native typed protocol surface: Strong typing and convenience builders reduce runtime drift from MCP message contracts.
  3. Transport flexibility: STDIO, HTTP/SSE, WebSocket, and HTTP/2 support are available under one crate.
  4. Supply-chain and quality gates: CI, clippy (-D warnings), security workflows, and audit tooling are built into the project baseline.
  5. Optional plugin runtime: Hot-reloadable plugin capabilities for extensible deployments without forcing plugin complexity on all users.

How It Fits with Agent Frameworks

prism-mcp-rs complements orchestration frameworks; it does not replace them.

Layer Responsibility
Agent framework (LangGraph, CrewAI, AutoGen, OpenAI Agents SDK, etc.) Planning, orchestration, workflow logic
prism-mcp-rs MCP protocol runtime, transport handling, server/client implementation, reliability primitives

Use this SDK when your services are in Rust and need deterministic MCP behavior under real operational load.

Detailed Capabilities

1. Advanced Resilience Patterns

  • Circuit Breaker Pattern: Automatic failure isolation preventing cascading failures
  • Adaptive Retry Policies: Smart backoff with jitter and error-based retry decisions
  • Health Check System: Multi-level health monitoring for transport, protocol, and resources
  • Graceful Degradation: Automatic fallback strategies when services become unavailable

2. Enterprise Transport Features

  • Streaming HTTP/2: Full multiplexing, server push, and flow control support
  • Adaptive Compression: Dynamic selection of Gzip, Brotli, or Zstd based on content analysis
  • Chunked Transfer Encoding: Efficient handling of large payloads with streaming
  • Connection Pooling: Intelligent connection reuse with keep-alive management
  • TLS/mTLS Support: Enterprise-grade security with certificate validation

3. Plugin System Architecture

  • Hot Reload Support: Update plugins without service interruption
  • C ABI Plugin Boundary: Dynamic plugin interface with runtime compatibility checks
  • Plugin Isolation: Sandboxed execution with resource limits
  • Dynamic Discovery: Runtime plugin loading with dependency resolution
  • Lifecycle Management: Automated plugin health monitoring and recovery

4. Protocol Extensions

  • Schema Introspection: Complete runtime discovery of server capabilities
  • Batch Operations: Efficient bulk request processing with transaction support
  • Progressive Content Delivery: Streaming responses for large datasets
  • Rich Metadata Support: Comprehensive annotations and capability negotiation
  • Custom Method Extensions: Seamless protocol extensibility

5. Production Observability

  • Structured Logging: Contextual tracing with correlation IDs
  • Metrics Collection: Performance counters, histograms, and gauges
  • Distributed Tracing: OpenTelemetry integration for request flow analysis
  • Error Forensics: Detailed error context with stack traces and recovery hints

Technical Architecture

Core Components

Component Description Key Features
Transport Layer Multi-protocol transport abstraction STDIO, HTTP/1.1, HTTP/2, WebSocket, SSE
Protocol Engine MCP 2025-11-25 implementation JSON-RPC, batch operations, streaming
Plugin Runtime Dynamic extension system Hot reload, sandboxing, versioning
Resilience Core Fault tolerance mechanisms Circuit breakers, retries, health checks
Security Module Authentication and authorization JWT, OAuth2, mTLS, rate limiting

Performance Characteristics

  • Zero-Copy Operations: Minimal memory allocation in hot paths
  • Async/Await Runtime: Tokio-based non-blocking I/O
  • Connection Multiplexing: Single TCP connection for multiple streams
  • Smart Buffering: Adaptive buffer sizing based on throughput
  • CPU Affinity: Thread pinning for cache optimization

Installation

Standard Installation

[dependencies]
prism-mcp-rs = "1"
tokio = { version = "1", features = ["full"] }
serde_json = "1.0"
async-trait = "0.1"

Feature Matrix

Feature Category Features Use Case
Core Transports stdio, http, websocket Basic connectivity
HTTP Extensions sse, http2, chunked-encoding, compression Advanced HTTP capabilities
Security auth, tls Authentication and encryption
Extensions plugin Runtime extensibility
Bundles full, minimal Convenience feature sets

Advanced Configuration

# High-performance configuration
[dependencies]
prism-mcp-rs = { 
    version = "1", 
    features = ["http2", "compression", "plugin", "auth", "tls"] 
}

# Memory-constrained environments
[dependencies]
prism-mcp-rs = { 
    version = "1", 
    default-features = false,
    features = ["stdio"] 
}

Clean & Simple API

30-Second Server Setup

use prism_mcp_rs::prelude::*;
use std::collections::HashMap;

#[derive(Clone)]
struct SystemToolHandler;

#[async_trait]
impl ToolHandler for SystemToolHandler {
    async fn call(&self, arguments: HashMap<String, Value>) -> McpResult<ToolResult> {
        match arguments.get("tool_name").and_then(|v| v.as_str()) {
            Some("system_info") => {
                let info = format!(
                    "Host: {}, OS: {}", 
                    hostname::get().unwrap_or_default().to_string_lossy(),
                    std::env::consts::OS
                );
                Ok(ToolResult {
                    content: vec![ContentBlock::text(&info)],
                    is_error: Some(false),
                    meta: None,
                    structured_content: None,
                })
            },
            _ => Err(McpError::invalid_request("Unknown tool"))
        }
    }
}

#[tokio::main]
async fn main() -> McpResult<()> {
    let mut server = McpServer::new(
        "system-server".to_string(), 
        "1.0.0".to_string()
    );
    
    // Add the system_info tool using the async add_tool method
    server.add_tool(
        "system_info",
        Some("Get system information"),
        json!({"type": "object", "properties": {}}),
        SystemToolHandler,
    ).await?;
    // Start server with STDIO transport
    let transport = StdioServerTransport::new();
    server.start(transport).await
}

Enterprise-Grade Client

use prism_mcp_rs::prelude::*;
use prism_mcp_rs::transport::StdioClientTransport;

let transport = StdioClientTransport::new("./server");
let client = McpClient::new(
    "test-client".to_string(),
    "1.0.0".to_string()
);

client.initialize().await?;
client.set_transport(Box::new(transport)).await?;

// Make requests to the server
let tools_response = client.list_tools(None, None).await?;
let tool_result = client.call_tool(
    "system_info".to_string(),
    json!({})
).await?;

println!("Available tools: {:?}", tools_response);
println!("Tool result: {:?}", tool_result);

Hot-Reloadable Plugins

use prism_mcp_rs::prelude::*;
use prism_mcp_rs::plugin::*;
use std::any::Any;

struct WeatherPlugin {
    api_key: String,
}

#[async_trait]
impl ToolPlugin for WeatherPlugin {
    fn metadata(&self) -> PluginMetadata {
        PluginMetadata {
            id: "weather-plugin".to_string(),
            name: "Weather Plugin".to_string(),
            version: "1.0.0".to_string(),
            author: Some("Example Author".to_string()),
            description: Some("Provides weather information".to_string()),
            homepage: None,
            license: Some("MIT".to_string()),
            mcp_version: "1.1.0".to_string(),
            capabilities: PluginCapabilities::default(),
            dependencies: vec![],
        }
    }

    fn tool_definition(&self) -> Tool {
        Tool::new(
            "get_weather".to_string(),
            Some("Get weather information for a location".to_string()),
            json!({
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "Location to get weather for"}
                },
                "required": ["location"]
            }),
            EchoTool // Placeholder - would use actual weather handler
        )
    }

    async fn execute(&self, arguments: Value) -> McpResult<ToolResult> {
        let location = arguments["location"].as_str().unwrap_or("Unknown");
        let weather_data = json!({
            "location": location,
            "temperature": "22°C",
            "condition": "Sunny"
        });
        
        Ok(ToolResult {
            content: vec![ContentBlock::text(&format!("Weather in {}: {}", location, weather_data))],
            is_error: Some(false),
            meta: None,
            structured_content: Some(weather_data),
        })
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// Runtime plugin management
let mut plugin_manager = PluginManager::new();
plugin_manager.reload_plugin("weather_plugin").await?; // Hot reload support

Architectural Innovations

Zero-Configuration Service Discovery

Automatic capability negotiation and runtime schema introspection eliminates manual configuration:

// Client connects and discovers server capabilities
let transport = StdioClientTransport::new("./server");
let client = McpClient::new("discovery-client".to_string(), "1.0.0".to_string());

client.initialize().await?;
client.set_transport(Box::new(transport)).await?;

// Discover server capabilities through initialization
let server_info = client.get_server_info().await?;
println!("Server capabilities: {:?}", server_info.capabilities);

Fault-Tolerant by Design

Built-in resilience patterns prevent cascading failures in distributed AI systems:

// Basic tool call with proper error handling
let result = match client.call_tool("analyze".to_string(), data).await {
    Ok(result) => result,
    Err(e) => {
        eprintln!("Tool call failed: {}", e);
        // Implement your own fallback logic here
        return Err(e);
    }
};

Plugin Ecosystem Revolution

Hot-swappable plugins with ABI stability across Rust versions:

// Plugin lifecycle management
plugin_manager.unload_plugin("analyzer_v1").await?;
plugin_manager.load_plugin("analyzer_v2.so").await?;
// Plugin health monitoring
let health = plugin_manager.check_plugin_health("analyzer_v2").await?;

New Use Cases Enabled

Multi-Agent AI Orchestration

Combine multiple AI services with automatic failover and load balancing.

Enterprise Integration Hubs

Connect legacy systems to modern AI tools with protocol translation and security policies.

Real-Time AI Pipelines

Build streaming data processing pipelines with sub-millisecond latency guarantees.

Federated AI Networks

Create distributed AI service meshes with automatic service discovery and routing.

Edge AI Deployment

Deploy AI capabilities to edge devices with offline-first architecture and smart sync.

Production-Ready Performance

Metric Value Impact
Zero-downtime deployments < 100ms Keep AI services running during updates
Automatic failover < 50ms No user-visible service interruptions
Memory efficiency 2-12MB baseline Deploy to edge and resource-constrained environments
Protocol overhead < 0.5ms Sub-millisecond response times for real-time AI

Security & Supply Chain

🔒 Security-First Design

  • Memory Safety: 100% safe Rust with minimal unsafe blocks (only in plugin FFI)
  • TLS 1.3: Modern encryption with rustls and ring cryptography
  • Supply Chain Security: Comprehensive dependency auditing with cargo-audit, cargo-deny, and cargo-vet
  • Vulnerability Monitoring: Automated security scans and dependency updates
  • License Compliance: All dependencies verified against approved open-source licenses

🛡️ Security Features

  • Authentication: JWT tokens with configurable expiration and refresh
  • Authorization: Role-based access control with fine-grained permissions
  • Input Validation: Comprehensive request validation and sanitization
  • Rate Limiting: Configurable request throttling and DDoS protection
  • Audit Logging: Security event logging with structured output

📊 Supply Chain Transparency

  • Dependencies: 379 crates, all security-audited
  • Vulnerabilities: Zero known security vulnerabilities
  • License Review: MIT-compatible licensing across entire dependency tree
  • Update Frequency: Weekly automated security audits and monthly dependency updates
  • Audit Trail: Complete supply chain verification with Mozilla import chain

🔧 Security Tools

# Run security audit
./scripts/security-audit.sh

# Update dependencies safely
./scripts/update-dependencies.sh

# Check supply chain status
cargo vet check
cargo deny check all
cargo audit

Documentation

📚 Getting Started

🚀 Deployment & Production

🏗️ Development Guides

🔄 Migration & Updates

🔒 Security & Policies

Contributing

Contributions are welcome! Please review our Contributing Guidelines and Code of Conduct.

See our Contributors for a list of everyone who has contributed to this project.

License

MIT License - see LICENSE for details.

Support

Yorumlar (0)

Sonuc bulunamadi