MCP服务器模板

一个用于构建Model Context Protocol (MCP)服务器的Rust模板,提供生产就绪的基础设施、灵活的配置和多种传输支持。

  • by furbyhaxx
  • Rust
  • 本地部署
  • 更新于
在 GitHub 查看 furbyhaxx/mcp-server-rs-template

使用说明

Rust MCP服务器启动模板

🎉 现在货物生成兼容! 使用单个命令生成自定义MCP服务器。

用于构建的生产就绪、记录良好的入门模板 模型上下文协议(MCP) Rust中的服务器。此模板提供了一个完整的基础,包括工作示例、生产日志和灵活的配置。

✨ 特性

  • 🚀 生产就绪:通过全面的错误处理和日志记录完成实施
  • 🔧 灵活的配置:TOML文件+环境变量+CLI参数(基于图形)
  • 📝 结构化日志记录:具有文件轮换和多个输出的生产日志记录(跟踪生态系统)
  • 🌐 多个传输:
    • 标准 子进程通信传输
    • HTTP/SSE 优雅关机的网络通信传输
  • 🛠️ 完整的MCP支持:
    • 工具:具有参数和结构化响应的可调用函数
    • 资源:服务器元数据的只读数据访问
    • 提示:人工智能助手交互的用户控制模板
  • 📊 示例实现:
    • 回声工具(简单的字符串输入/输出)
    • 计算器工具(带JSON结果的结构化参数)
    • 状态计数器工具(演示与共享的状态 Arc<Mutex<T>>)
  • 🏗️ 模块化架构:库+二进制模式,便于扩展和测试
  • 🧪 综合测试:两种运输工具的单元测试和集成测试

🚀 快速开始

先决条件

  • 锈蚀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"

⚙️ 配置

该模板支持三层配置(按优先级顺序):

  1. CLI参数 (最高优先级)
  2. 环境变量 (前缀: MCP_)
  3. TOML文件 (默认值: config/default.toml)

配置文件

环境变量

# 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,
}

🔧 扩展模板

添加新工具

  1. 定义参数 (可选,用于结构化输入):
// 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<String>,
}
  1. 机具功能:
// 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<CallToolResult, ErrorData> {
    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)]))
}
  1. 工具被自动发现 通过 #[tool] 宏

添加新资源

// In src/service.rs, override the ServerHandler methods
async fn list_resources(&self) -> Result<Vec<Annotated<RawResource>>, Error> {
    vec![
        Annotated::new(
            RawResource::new("my://resource".into(), "My custom resource".into()),
        ),
    ]
}

async fn read_resource(&self, uri: &str) -> Result<ReadResourceResult, Error> {
    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<Vec<Annotated<Prompt>>, 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<GetPromptArguments>) -> Result<GetPromptResult, Error> {
    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")),
    }
}

添加新传输

  1. 创建传输模块 在 src/transport/my_transport.rs
  2. 实现服务功能:
pub async fn serve<S>(service: S) -> Result<()>
where
    S: ServerHandler + Send + Sync + Clone + 'static,
{
    // Your transport implementation here
    todo!("Implement your transport")
}
  1. 添加枚举变量 到 Transport 枚举在 src/cli.rs
  2. 更新出厂功能 在 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

获取帮助

调试模式

# 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 异步实用程序(用于取消令牌) 标准库

🤝 贡献

欢迎投稿!拜托:

  1. 复刻仓库
  2. 创建要素分支(git checkout -b feature/amazing-feature)
  3. 遵循Rust 2024惯例
  4. 添加新功能的测试
  5. 更新文档
  6. 跑 cargo fmt && cargo clippy -- -D warnings && cargo test
  7. 提交拉取请求

代码风格

  • 使用 cargo fmt 用于格式化
  • 使用 cargo clippy -- -D warnings 用于棉绒(不允许警告)
  • 遵循Rust 2024版本约定
  • 添加 /// 所有公共API的文档
  • 在有帮助的地方包括doctest示例

📄 许可证

根据以下任一方式获得许可:

由您选择。

🎨 模板定制

此模板支持通过以下方式进行广泛的自定义 货物生成:

可用的自定义设置

  • 项目配置:姓名、描述、作者、许可证
  • 运输选项: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

🔗 资源

🙏 致谢

内置于 rmcp,模型上下文协议的官方Rust实现,由 货物生成 便于定制。


版本: 0.1.0 状态:生产就绪✅