Crates.io | mcp-protocol-sdk |
lib.rs | mcp-protocol-sdk |
version | 0.5.1 |
created_at | 2025-06-12 06:12:16.569212+00 |
updated_at | 2025-08-03 06:41:38.693749+00 |
description | Production-ready Rust SDK for the Model Context Protocol (MCP) with multiple transport support |
homepage | https://mcp-rust.github.io/mcp-protocol-sdk/ |
repository | https://github.com/mcp-rust/mcp-protocol-sdk |
max_upload_size | |
id | 1709395 |
size | 1,001,135 |
A production-ready, feature-complete Rust implementation of the Model Context Protocol
π Quick Start: Getting Started | Implementation Guide | Examples
The MCP Protocol SDK enables seamless integration between AI models and external systems through a standardized protocol. Build powerful tools, resources, and capabilities that AI can discover and use dynamically.
π v0.5.0 Released - Production-ready SDK with comprehensive GitHub Actions CI/CD, enhanced documentation, and complete development infrastructure.
[dependencies]
mcp-protocol-sdk = "0.5.0"
tokio = { version = "1.0", features = ["full"] }
async-trait = "0.1"
serde_json = "1.0"
# Or with specific features only:
mcp-protocol-sdk = { version = "0.5.0", features = ["stdio", "validation"] }
use mcp_protocol_sdk::prelude::*;
use async_trait::async_trait;
use std::collections::HashMap;
use serde_json::{Value, json};
// Step 1: Create a tool handler (required by actual API)
struct CalculatorHandler;
#[async_trait]
impl ToolHandler for CalculatorHandler {
async fn call(&self, arguments: HashMap<String, Value>) -> McpResult<ToolResult> {
let a = arguments
.get("a")
.and_then(|v| v.as_f64())
.ok_or_else(|| McpError::Validation("Missing 'a' parameter".to_string()))?;
let b = arguments
.get("b")
.and_then(|v| v.as_f64())
.ok_or_else(|| McpError::Validation("Missing 'b' parameter".to_string()))?;
let result = a + b;
Ok(ToolResult {
content: vec![Content::text(result.to_string())],
is_error: None,
structured_content: Some(json!({
"operation": "addition",
"operands": [a, b],
"result": result
})),
meta: None,
})
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create server (note: requires String parameters)
let mut server = McpServer::new("my-calculator".to_string(), "1.0.0".to_string());
// Add a tool (actual working API)
server.add_tool(
"add".to_string(),
Some("Add two numbers".to_string()),
json!({
"type": "object",
"properties": {
"a": {
"type": "number",
"description": "First number"
},
"b": {
"type": "number",
"description": "Second number"
}
},
"required": ["a", "b"]
}),
CalculatorHandler,
).await?;
// Start server (compatible with Claude Desktop)
use mcp_protocol_sdk::transport::stdio::StdioServerTransport;
let transport = StdioServerTransport::new();
server.start(transport).await?;
Ok(())
}
use mcp_protocol_sdk::prelude::*;
use mcp_protocol_sdk::client::McpClient;
use mcp_protocol_sdk::transport::traits::TransportConfig;
#[cfg(feature = "http")]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
use mcp_protocol_sdk::transport::http::HttpClientTransport;
// Connect with advanced HTTP transport (45% faster!)
let config = TransportConfig {
connect_timeout_ms: Some(5_000),
read_timeout_ms: Some(30_000),
write_timeout_ms: Some(30_000),
max_message_size: Some(1024 * 1024), // 1MB
keep_alive_ms: Some(60_000), // 1 minute
compression: true,
headers: std::collections::HashMap::new(),
};
let transport = HttpClientTransport::with_config(
"http://localhost:3000",
None,
config,
).await?;
let mut client = McpClient::new("my-client".to_string(), "1.0.0".to_string());
// connect() returns InitializeResult and calls initialize() internally
let init_result = client.connect(transport).await?;
println!("Connected to: {} v{}",
init_result.server_info.name,
init_result.server_info.version
);
// Note: Use server capabilities to check what's available
if let Some(capabilities) = client.server_capabilities().await {
if capabilities.tools.is_some() {
println!("Server supports tools");
}
}
Ok(())
}
use mcp_protocol_sdk::core::tool::ToolBuilder;
// Create tools with advanced features and validation
let tool = ToolBuilder::new("enhanced_calculator")
.description("Advanced calculator with validation")
.version("1.0.0")
.schema(json!({
"type": "object",
"properties": {
"a": {"type": "number"},
"b": {"type": "number"}
},
"required": ["a", "b"]
}))
.strict_validation()
.read_only()
.idempotent()
.cacheable()
.build(CalculatorHandler)?;
ToolHandler
trait with async fn call()
String
, not &str
#[async_trait]
for all handler implementationsMcpResult<T>
and proper error handlingasync-trait
, tokio
, and serde_json
Scenario | Description | Guide |
---|---|---|
π₯οΈ Claude Desktop Integration | Add custom tools to Claude Desktop | π Guide |
β‘ Cursor IDE Enhancement | AI-powered development tools | π Guide |
π VS Code Extensions | Smart code assistance and automation | π Guide |
ποΈ Database Access | SQL queries and data analysis | π Example |
π API Integration | External service connectivity | π Example |
π File Operations | Filesystem tools and utilities | π Example |
π¬ Chat Applications | Real-time AI conversations | π Example |
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β AI Client β β MCP Protocol β β MCP Server β
β (Claude, etc.) βββββΊβ SDK βββββΊβ (Your Tools) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β
βββββββββββΌββββββββββ
β β β
ββββββββΌβββ ββββββΌββββ βββββΌβββββ
β STDIO β β HTTP β βWebSocketβ
βTransportβ βTransportβ βTransportβ
βββββββββββ ββββββββββ ββββββββββ
Optimize your binary size by selecting only needed features:
Feature | Description | Default | Size Impact |
---|---|---|---|
stdio |
STDIO transport for Claude Desktop | β | Minimal |
http |
HTTP transport for web integration | β | +2MB |
websocket |
WebSocket transport for real-time | β | +1.5MB |
validation |
Enhanced input validation | β | +500KB |
tracing-subscriber |
Built-in logging setup | β | +300KB |
Minimal Example (STDIO only):
mcp-protocol-sdk = { version = "0.5.0", default-features = false, features = ["stdio"] }
The advanced HTTP transport provides significant performance improvements:
| Transport | Requests/Second | Average Latency | Success Rate | Key Features | |-----------|-----------------|-----------------|--------------||--------------| | Advanced HTTP | 802 req/sec | 0.02ms | 100% | Connection pooling, retry logic | | Standard HTTP | 551 req/sec | 0.04ms | 100% | Basic HTTP client |
45% Performance Improvement with advanced features! π―
# Run benchmark comparison
cargo run --example transport_benchmark --all-features
# Test conservative settings (recommended)
cargo run --example conservative_http_demo --all-features
π Full Advanced Transport Guide
β Complete MCP 2024-11-05 Implementation
This SDK provides 100% verified compliance with the official MCP Protocol Schema (2025-06-18), ensuring seamless interoperability with all MCP-compatible systems.
Our comprehensive test suite validates every aspect of the MCP protocol:
# Run the full schema compliance test suite
cargo test --test comprehensive_schema_tests -- --nocapture
Results: 299 tests passing
with 100.0% compliance rate
π
Component | Status | Features Validated |
---|---|---|
Core Types | β 100% | Implementation, Capabilities, Content |
JSON-RPC | β 100% | Requests, Responses, Errors, Notifications, Batching |
Tools | β 100% | Definitions, Parameters, Annotations, Execution |
Resources | β 100% | Static/Dynamic, Templates, Subscriptions |
Prompts | β 100% | Templates, Arguments, Message Generation |
Sampling | β 100% | Message Creation, Model Preferences |
Logging | β 100% | All levels, Structured messages |
Progress | β 100% | Notifications, Cancellation |
Roots | β 100% | Discovery, List management |
Completions | β 100% | Auto-complete for prompts/resources |
Full support for all latest MCP protocol enhancements:
// Example: Schema validation in action
use mcp_protocol_sdk::protocol::types::*;
// All types are schema-compliant by construction
let tool_info = ToolInfo {
name: "calculator".to_string(),
description: Some("Performs mathematical operations".to_string()),
input_schema: ToolInputSchema {
schema_type: "object".to_string(),
properties: Some(std::collections::HashMap::new()),
required: Some(vec!["a".to_string(), "b".to_string()]),
additional_properties: std::collections::HashMap::new(),
},
annotations: None,
title: None,
meta: None,
};
// JSON serialization matches schema exactly
let json = serde_json::to_value(&tool_info)?;
You can verify schema compliance yourself:
# 1. Run comprehensive schema tests
cargo test comprehensive_schema_validation --features validation -- --nocapture
# 2. Check specific protocol components
cargo test test_protocol_version_compliance
cargo test test_tool_with_annotations_schema_compliance
cargo test test_jsonrpc_batch_schema_compliance
# 3. Validate against official schema (if available)
# The tests verify serialization matches expected JSON-RPC format
With 100% schema compliance, this SDK guarantees compatibility with:
π View Full Schema Compliance Details
Platform | Architecture | Testing | Status |
---|---|---|---|
Linux | x86_64, ARM64, musl | β Automated | β Production Ready |
macOS | Intel, Apple Silicon | β Automated | β Production Ready |
Windows | x86_64, GNU | β Automated | β Production Ready |
# Add targets for cross-compilation
rustup target add aarch64-apple-darwin # macOS Apple Silicon
rustup target add x86_64-pc-windows-gnu # Windows GNU
rustup target add x86_64-unknown-linux-musl # Linux static
rustup target add aarch64-unknown-linux-gnu # Linux ARM64
# Build for different platforms
cargo build --target aarch64-apple-darwin
cargo build --target x86_64-unknown-linux-musl
Example | Description | Transport | Features |
---|---|---|---|
Conservative HTTP Demo | Production-ready HTTP client | Advanced HTTP | Connection pooling, metrics |
Transport Benchmark | Performance comparison | Multiple | 45% speed improvement |
Advanced HTTP Client | Full-featured HTTP demo | Advanced HTTP | Retry logic, health checks |
Echo Server | Simple tool demonstration | STDIO | Basic tools |
Database Server | SQL query execution | STDIO | Database access |
HTTP Server | RESTful API integration | HTTP | Web services |
WebSocket Server | Real-time communication | WebSocket | Live updates |
File Server | File system operations | STDIO | File handling |
Basic Client | Basic client usage | STDIO | Client patterns |
# Build with all features
cargo build --all-features
# Test with different feature combinations
cargo test --no-default-features --features stdio
cargo test --all-features
# Run examples
cargo run --example echo_server --features stdio,tracing-subscriber
# Test minimal build
cargo check --no-default-features --lib
# Test specific transports
cargo check --no-default-features --features http
cargo check --no-default-features --features websocket
We welcome contributions! Please see our Contributing Guide for details.
Licensed under the MIT License.
π Read the Full Documentation | π Get Started Now | π Implementation Guide
Built with β€οΈ in Rust