MCP客户端Rust-模型上下文协议客户端
Rust的全面实现 模型上下文协议(MCP) 客户。该项目为构建可以与MCP兼容服务器交互的AI应用程序提供了一个强大的、类型安全的基础。
📋 目录
✨ 特性
核心功能
- ✅ 完全支持MCP协议 -基于JSON-RPC 2.0的MCP的完整实现
- ✅ 类型安全客户端 -利用Rust的类型系统实现编译时安全
- ✅ 异步/等待 -使用Tokio运行时完全异步
- ✅ 多服务器支持 -同时管理多个MCP服务器连接
- ✅ 工具管理 -发现、验证和执行服务器公开的工具
- ✅ 资源访问 -从MCP服务器读取和管理资源
- ✅ 快速支持 -利用来自服务器的预定义LLM提示
安全功能
- 🔒 输入验证 -全面的输入验证和净化
- 🔒 错误隔离 -安全的错误处理,防止信息泄露
高级功能
- 📊 日志记录和调试 -综合结构化测井系统
- 🔄 重新连接逻辑 -指数回退自动重新连接
- 🛠️ 工具执行 -执行具有验证和错误处理功能的MCP工具
- 📱 流媒体支持 -处理长时间运行操作的流式响应
📦 先决条件
系统要求
- 锈:1.70或更高版本(安装Rust)
- 操作系统:macOS、Linux或Windows
验证安装
# Check Rust installation
rustc --version
cargo --version🚀 安装
步骤1:克隆存储库
git clone https://github.com/yourusername/mcp-client-rust.git
cd mcp-client-rust步骤2:安装依赖项
# Update Rust toolchain
rustup update
# Build the project
cargo build --release步骤3:配置环境
创建一个 .env 项目根目录中的文件:
# Logging
LOG_LEVEL=info
LOG_FILE=./mcp-client.log
# MCP Configuration
MCP_TIMEOUT_SECONDS=30💡 快速开始
基本用法
use mcp_client_rust::client::MCPClient;
use mcp_client_rust::transport::StdioTransport;
use mcp_client_rust::types::ClientInfo;
#[tokio::main]
async fn main() -> Result> {
// Initialize MCP client
let transport = Box::new(StdioTransport::new("./mcp-server", &[])?);
let client_info = ClientInfo {
name: "MyClient".to_string(),
version: "1.0.0".to_string(),
};
let mut client = MCPClient::new(transport, client_info);
client.initialize().await?;
// List tools
let tools = client.list_tools().await?;
for tool in tools {
println!("Tool: {} - {}", tool.name, tool.description.unwrap_or_default());
}
// Call a tool
let result = client.call_tool(
"greet",
serde_json::json!({
"name": "Alice"
})
).await?;
println!("Result: {:?}", result);
client.close().await?;
Ok(())
}🏗️ 建筑
项目结构
mcp-client-rust/
├── src/
│ ├── lib.rs # Library entry point
│ ├── types.rs # MCP type definitions
│ ├── transport.rs # Transport layer (Stdio, HTTP/SSE)
│ ├── client.rs # Core MCP client
│ ├── tool_manager.rs # Tool management and validation
│ ├── multi_server.rs # Multi-server connection manager
│ ├── security.rs # Security policies and validation
│ ├── logging.rs # Logging utilities
│ ├── validation.rs # Input validation
│ └── errors.rs # Error types
├── examples/
│ ├── basic_example.rs
│ └── multi_server_example.rs
├── tests/
│ └── integration_tests.rs
├── Cargo.toml
├── README.md
└── .env.example📖 使用示例
示例1:连接到服务器并列出工具
use mcp_client_rust::client::MCPClient;
use mcp_client_rust::transport::StdioTransport;
use mcp_client_rust::types::ClientInfo;
#[tokio::main]
async fn main() -> Result> {
// Create transport to connect to the server
let transport = Box::new(StdioTransport::new(
"/Users/sudhirkumar/Desktop/sudhir/gitsudhir/mcp-server-rust/target/release/mcp-server-rust",
&[]
)?);
let client_info = ClientInfo {
name: "TestClient".to_string(),
version: "1.0.0".to_string(),
};
let mut client = MCPClient::new(transport, client_info);
client.initialize().await?;
// List available tools
let tools = client.list_tools().await?;
println!("Available tools:");
for tool in tools {
println!("- {} ({})", tool.name, tool.description.unwrap_or_default());
}
client.close().await?;
Ok(())
}示例2:执行工具
use mcp_client_rust::client::MCPClient;
use serde_json::json;
#[tokio::main]
async fn main() -> Result> {
let mut client = create_client().await?;
// Execute a greeting tool
let result = client.call_tool(
"greet",
json!({
"name": "Alice"
})
).await?;
match &result.content[0] {
mcp_client_rust::types::ToolResultContent::Text { text } => {
println!("Greeting result: {}", text);
}
_ => println!("Received non-text result"),
}
client.close().await?;
Ok(())
}
async fn create_client() -> Result> {
let transport = Box::new(StdioTransport::new(
"/Users/sudhirkumar/Desktop/sudhir/gitsudhir/mcp-server-rust/target/release/mcp-server-rust",
&[]
)?);
let client_info = mcp_client_rust::types::ClientInfo {
name: "TestClient".to_string(),
version: "1.0.0".to_string(),
};
let mut client = MCPClient::new(transport, client_info);
client.initialize().await?;
Ok(client)
}示例3:读取资源
#[tokio::main]
async fn main() -> Result> {
let mut client = create_client().await?;
// Read a resource
let content = client.read_resource("config://app").await?;
for item in content.contents {
match item {
mcp_client_rust::types::ContentItem::Text { text } => {
println!("Content: {}", text);
}
mcp_client_rust::types::ContentItem::Blob { blob } => {
println!("Binary data: {} bytes", blob.len());
}
}
}
client.close().await?;
Ok(())
}🔌 API 文档
MCP客户端
与MCP服务器交互的主要客户端。
方法
impl MCPClient {
// Initialize connection with server
pub async fn initialize(&mut self) -> ClientResult
// List available tools
pub async fn list_tools(&mut self) -> ClientResult>
// List available resources
pub async fn list_resources(&mut self)
-> ClientResult, Vec)>
// List available prompts
pub async fn list_prompts(&mut self) -> ClientResult
// Execute a tool
pub async fn call_tool(
&mut self,
tool_name: &str,
arguments: Value
) -> ClientResult
// Read a resource
pub async fn read_resource(&mut self, uri: &str)
-> ClientResult
// Get a prompt with arguments
pub async fn get_prompt(
&mut self,
name: &str,
arguments: Option>
) -> ClientResult
// Close connection
pub async fn close(&mut self) -> ClientResult
}⚙️ 配置
环境变量
创建一个 .env 项目根目录中的文件:
# Logging Configuration
LOG_LEVEL=info
LOG_FILE=./mcp-client.log
# MCP Configuration
MCP_TIMEOUT_SECONDS=30
MCP_MAX_RETRIES=3🔒 安全
最佳实践
- 验证所有输入
use mcp_client_rust::validation::InputValidator;
if !InputValidator::validate_file_path(user_path) {
return Err("Invalid file path".into());
}- 综合录井
let logger = mcp_client_rust::logging::McpLogger::new(mcp_client_rust::logging::LogLevel::Info)
.with_file("./mcp-client.log".to_string());
logger.info("Tool execution attempt");
logger.error("Unauthorized access");🐛 故障排除
服务器连接问题
问题:无法连接到MCP服务器
解决方案:
// Verify server path exists
let path = "/Users/sudhirkumar/Desktop/sudhir/gitsudhir/mcp-server-rust/target/release/mcp-server-rust";
if !std::path::Path::new(path).exists() {
eprintln!("Server executable not found at: {}", path);
}
// Check server permissions
#[cfg(unix)]
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))?;超时问题
问题:“请求超时”错误
解决方案:
# Increase timeout
MCP_TIMEOUT_SECONDS=60📋 从源头构建
# Clone repository
git clone https://github.com/yourusername/mcp-client-rust.git
cd mcp-client-rust
# Build debug version
cargo build
# Build release version (optimized)
cargo build --release
# Run tests
cargo test
# Run with logging
RUST_LOG=debug cargo run --example basic_example🧪 测试
# Run all tests
cargo test
# Run specific test
cargo test test_name
# Run with output
cargo test -- --nocapture📚 例子
所有示例均位于 examples/ 目录:
- 基本示例 -简单的工具执行
- 多服务器示例 -管理多个MCP服务器
运行任何示例:
cargo run --example 🤝 贡献
欢迎投稿!请按照以下步骤操作:
- 分叉存储库
- 创建要素分支(
git checkout -b feature/amazing-feature) - 提交您的更改(
git commit -m 'Add amazing feature') - 推到分支(
git push origin feature/amazing-feature) - 打开拉取请求
编码标准
- 遵循Rust命名约定
- 使用
cargo fmt用于格式化 - 跑
cargo clippy对于linting - 为新功能添加测试
- 更新文档
📝 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
🔗 资源
官方文件
相关项目
📞 支持
有关帮助和问题:
- 检查 故障排除 部分
- 搜索现有
- 创建包含详细信息的新问题
🙏 致谢
- 模型上下文协议 规范团队
- Rust社区提供令人惊叹的库和支持
______________________________________________________________________
最后更新: 2026-02-13\ 版本: 0.1.0
由...制作❤️ 在Rust
