Rust MCP服务器启动模板
  
🎉 现在货物生成兼容! 使用单个命令生成自定义MCP服务器。
用于构建的生产就绪、记录良好的入门模板 模型上下文协议(MCP) Rust中的服务器。此模板提供了一个完整的基础,包括工作示例、生产日志和灵活的配置。
✨ 特性
- 🚀 生产就绪:通过全面的错误处理和日志记录完成实施
- 🔧 灵活的配置:TOML文件+环境变量+CLI参数(基于图形)
- 📝 结构化日志记录:具有文件轮换和多个输出的生产日志记录(跟踪生态系统)
- 🌐 多个传输:
- 标准 子进程通信传输 - HTTP/SSE 优雅关机的网络通信传输
- 🛠️ 完整的MCP支持:
- 工具:具有参数和结构化响应的可调用函数 - 资源:服务器元数据的只读数据访问 - 提示:人工智能助手交互的用户控制模板
- 📊 示例实现:
- 回声工具(简单的字符串输入/输出) - 计算器工具(带JSON结果的结构化参数) - 状态计数器工具(演示与共享的状态 Arc>)
- 🏗️ 模块化架构:库+二进制模式,便于扩展和测试
- 🧪 综合测试:两种运输工具的单元测试和集成测试
🚀 快速开始
先决条件
- 锈蚀1.85+ (Rust 2024版)
- 货物
🚀 快速开始
推荐:使用货物生成
# Install cargo-generate if you don't have it
cargo install cargo-generate
# Generate your custom MCP server
cargo generate --git https://github.com/furbyhaxx/mcp-server-rs-template
# Follow the prompts to customize your project!手动安装
# Clone the template
git clone https://github.com/yourusername/rmcp-starter-template.git
cd rmcp-starter-template
# Build the project
cargo build --release
# Run with stdio transport (default)
cargo run -- serve
# Run with explicit transport selection
cargo run -- serve --transport stdio
cargo run -- serve --transport http测试工具
运行后,您可以与内置工具进行交互:
回声工具:
# Example MCP client interaction (simplified)
{
"tool": "echo",
"arguments": {
"message": "Hello, MCP!"
}
}
# Returns: "Echo: Hello, MCP!"计算器工具:
{
"tool": "calculate",
"arguments": {
"a": 10.5,
"b": 5.2,
"operation": "add"
}
}
# Returns: {"result": 15.7, "operation": "add", "operands": [10.5, 5.2]}计数器工具:
{
"tool": "get_counter"
}
# Returns: "Current counter value: 0"
{
"tool": "increment_counter",
"arguments": {
"amount": 3
}
}
# Returns: "Counter incremented by 3. New value: 3"
{
"tool": "reset_counter"
}
# Returns: "Counter reset to 0"⚙️ 配置
该模板支持三层配置(按优先级顺序):
- CLI参数 (最高优先级)
- 环境变量 (前缀:
MCP_) - TOML文件 (默认值:
config/default.toml)
配置文件
config/default.toml:具有合理默认值的默认配置.env.example:环境变量模板
环境变量
# Override server name
MCP_SERVER_NAME="my-mcp-server"
# Set log level to debug
MCP_LOGGING_LEVEL="debug"
# Configure HTTP transport port
MCP_TRANSPORT_HTTP_PORT="8080"
# Use only console logging (no file output)
MCP_LOGGING_TARGETS="console"CLI使用情况
# Run with custom transport
cargo run -- serve --transport http
# View help and all options
cargo run -- --help🏗️ 建筑
项目结构
rmcp-starter-template/
├── src/
│ ├── lib.rs # Public library API with prelude
│ ├── main.rs # CLI entry point
│ ├── cli.rs # Command-line interface (clap)
│ ├── config/ # Configuration management (figment)
│ │ ├── mod.rs # Config struct and loading logic
│ │ └── tests.rs # Configuration tests
│ ├── logging/ # Production logging setup (tracing)
│ │ └── mod.rs # Logging initialization with rotation
│ ├── transport/ # Transport layer
│ │ ├── mod.rs # Transport factory and abstraction
│ │ ├── stdio.rs # stdio transport implementation
│ │ └── http.rs # HTTP/SSE transport implementation
│ ├── service.rs # MCP service with tools/resources/prompts
│ ├── service/
│ │ ├── tools.rs # Tool parameter types and schemas
│ │ ├── resources.rs # Resource implementations
│ │ ├── prompts.rs # Prompt implementations
│ │ └── tests.rs # Service tests
│ ├── error.rs # Comprehensive error handling (thiserror)
│ └── prelude.rs # Common imports for convenience
├── config/
│ └── default.toml # Default configuration
├── tests/ # Integration tests
│ ├── stdio_integration.rs # stdio transport tests
│ └── http_integration.rs # HTTP transport tests
├── .env.example # Environment variable template
└── CHANGELOG.md # Version history运输工厂模式
该模板使用传输工厂模式进行扩展:
// Dynamic transport creation
let transport_future = create_transport(transport, &config, service)?;
// Supports both stdio and HTTP transports
match transport {
Transport::Stdio => stdio::serve(service).await,
Transport::Http => http::serve(service, &config).await,
}🔧 扩展模板
添加新工具
- 定义参数 (可选,用于结构化输入):
// In src/service/tools.rs
use rmcp::schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MyToolParams {
/// Input text to process
pub input: String,
/// Optional processing mode
pub mode: Option,
}- 机具功能:
// In src/service.rs
use rmcp_starter_template::service::tools::MyToolParams;
#[tool(description = "Process input text with optional mode")]
pub async fn my_tool(&self, #[arg] params: MyToolParams) -> Result {
let mode = params.mode.as_deref().unwrap_or("default");
let result = format!("Processed '{}' with mode '{}'", params.input, mode);
Ok(CallToolResult::success(vec![Content::text(result)]))
}- 工具被自动发现 通过
#[tool]宏
添加新资源
// In src/service.rs, override the ServerHandler methods
async fn list_resources(&self) -> Result>, Error> {
vec![
Annotated::new(
RawResource::new("my://resource".into(), "My custom resource".into()),
),
]
}
async fn read_resource(&self, uri: &str) -> Result {
match uri {
"my://resource" => {
let content = Content::text("This is my resource content".to_string());
Ok(ReadResourceResult {
contents: vec![content],
})
}
_ => Err(Error::invalid_params("Unknown resource URI")),
}
}添加新提示
// In src/service.rs, extend the ServerHandler implementation
async fn list_prompts(&self) -> Result, Error> {
vec![
Annotated::new(Prompt {
name: "my_prompt".into(),
description: Some("My custom prompt template".into()),
arguments: vec![
PromptArgument {
name: "topic".into(),
description: Some("The topic to discuss".into()),
required: Some(true),
},
],
}),
]
}
async fn get_prompt(&self, name: &str, arguments: Option) -> Result {
match name {
"my_prompt" => {
let args = arguments.ok_or_else(|| Error::invalid_params("Arguments required"))?;
let topic = args.arguments
.get("topic")
.and_then(|v| v.as_str())
.ok_or_else(|| Error::invalid_params("Missing 'topic' argument"))?;
let message = PromptMessage {
role: PromptRole::User,
content: Content::text(format!("Tell me about {}", topic)),
};
Ok(GetPromptResult {
description: Some(format!("Prompt about {}", topic)),
messages: vec![message],
})
}
_ => Err(Error::invalid_params("Unknown prompt name")),
}
}添加新传输
- 创建传输模块 在
src/transport/my_transport.rs - 实现服务功能:
pub async fn serve(service: S) -> Result
where
S: ServerHandler + Send + Sync + Clone + 'static,
{
// Your transport implementation here
todo!("Implement your transport")
}- 添加枚举变量 到
Transport枚举在src/cli.rs - 更新出厂功能 在
src/transport/mod.rs
🧪 发展
建筑
cargo build
cargo build --release # Optimized release build测试
# Run all tests
cargo test
# Run specific test
cargo test test_config_loading
# Run with output
cargo test -- --nocapture
# Run integration tests only
cargo test --test integration代码质量
# Format code
cargo fmt
# Run linter (will fail on warnings)
cargo clippy -- -D warnings
# Check for formatting issues
cargo fmt -- --check
# Generate documentation
cargo doc --open开发工作流程示例
# 1. Create development configuration
cp .env.example .env
echo 'MCP_LOGGING_LEVEL="debug"' >> .env
echo 'MCP_LOGGING_TARGETS="console"' >> .env
# 2. Run with console logging for development
cargo run -- serve --transport stdio
# 3. Test changes
cargo test
# 4. Run quality checks
cargo fmt && cargo clippy -- -D warnings🔍 故障排除
常见问题
“不支持传输”错误:
- 确保您正在使用
--transport stdio或--transport http - 检查运输模块是否正确导入
配置未加载:
- 验证中的TOML语法
config/default.toml - 检查环境变量名称的使用情况
MCP_前缀 - 使用
RUST_LOG=debug查看配置加载详细信息
日志未显示:
- 存放WorkerGuard:
let _guard = init_logging(&config)?; - 检查日志级别:设置
MCP_LOGGING_LEVEL=debug用于详细输出 - 验证日志目标:
MCP_LOGGING_TARGETS=console+file
日志文件位置
- 默认:
logs/mcp-server.log(相对于项目根) - 可定制的:设置
MCP_LOGGING_FILE环境变量 - 旋转:默认情况下为每日,通过配置
MCP_LOGGING_ROTATION
获取帮助
- 依赖指南:参见
.agents/instruction/external-dependencies/有关所有依赖关系的详细信息 - MCP规范: 模型上下文协议规范
- rmcp文件: 官方Rust SDK
调试模式
# Enable debug logging
RUST_LOG=debug cargo run -- serve
# Show configuration details
MCP_LOGGING_LEVEL=debug cargo run -- serve📚 文档
🛠️ 依赖项
| 依赖关系 | 版本 | 目的 | 文档 |
|---|---|---|---|
| rmcp | 0.8.5 | MCP协议实现 | 指南 |
| 拍手 | 4.5.53 | CLI参数解析 | 指南 |
| 虚构 | 0.10.19 | 配置管理 | 指南 |
| 东京 | 1.48.0 | 异步运行时 | 指南 |
| 追踪 | 0.1.41 | 结构化日志记录 | 指南 |
| 追踪订户 | 0.3.20 | 日志格式化/过滤 | 指南 |
| 追踪附录 | 0.2.3 | 带旋转的文件记录 | 指南 |
| 这个错误 | 2.0.17 | 错误处理 | 指南 |
| 序列化与反序列化 | 1.0.228 | 序列化 | 标准库 |
| Serde JSON | 1.0.145 | JSON处理 | 标准库 |
| 东京-有用 | 0.7.17 | 异步实用程序(用于取消令牌) | 标准库 |
🤝 贡献
欢迎投稿!拜托:
- 复刻仓库
- 创建要素分支(
git checkout -b feature/amazing-feature) - 遵循Rust 2024惯例
- 添加新功能的测试
- 更新文档
- 跑
cargo fmt && cargo clippy -- -D warnings && cargo test - 提交拉取请求
代码风格
- 使用
cargo fmt用于格式化 - 使用
cargo clippy -- -D warnings用于棉绒(不允许警告) - 遵循Rust 2024版本约定
- 添加
///所有公共API的文档 - 在有帮助的地方包括doctest示例
📄 许可证
根据以下任一方式获得许可:
- Apache许可证,版本2.0(特许通行证 或http://www.apache.org/licenses/LICENSE-2.0)
- MIT许可证(许可证-麻省理工学院 或http://opensource.org/licenses/MIT)
由您选择。
🎨 模板定制
此模板支持通过以下方式进行广泛的自定义 货物生成:
可用的自定义设置
- 项目配置:姓名、描述、作者、许可证
- 运输选项:stdio,带可配置端口的HTTP
- 工具选择:选择要包含的示例工具
- 日志记录设置:日志级别、文件日志记录、轮换
- 功能标志:可选组件和功能
- 开发vs生产:优化了每个环境的默认值
自定义示例
# Minimal CLI server
cargo generate --git https://github.com/furbyhaxx/mcp-server-rs-template \
--enable-http-transport=false \
--enable-file-logging=false
# Full-featured HTTP server
cargo generate --git https://github.com/furbyhaxx/mcp-server-rs-template \
--default-transport http \
--http-port 8080 \
--enable-all-features
# Production-ready setup
cargo generate --git https://github.com/furbyhaxx/mcp-server-rs-template \
--log-level warn \
--author-name "Production Team" \
--license MIT📖 获取完整的自定义选项,请参阅 模板_USAGE.md
🔗 资源
- 模型上下文协议规范:官方MCP协议规范
- MCP官方文件:MCP通用文件和指南
- ****:官方Rust MCP实现
- Rust 2024版指南:最新的Rust特性和约定
- 货物生成:模板生成工具
🙏 致谢
______________________________________________________________________
版本: 0.1.0 状态:生产就绪✅
