Token导航 LogoToken导航TokenDH.com
Rs Template logo
AI代理未说明官方级别未说明来源级核验

Rs Template

MCP Server

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

工具数

3

提示词数

0

GitHub Stars

0

资源数

0
Rust服务器模板生产就绪

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

furbyhaxx

提供方

furbyhaxx

最后核验

2026/5/17 20:20

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

Rust MCP服务器启动模板

![Rust 2024](https://doc.rust-lang.org/edition-guide/rust-2024/) ![License: MIT OR Apache-2.0](LICENSE-MIT) ![cargo-generate](https://github.com/cargo-generate/cargo-generate)

🎉 现在货物生成兼容! 使用单个命令生成自定义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"

⚙️ 配置

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

  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,
}
  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 {
    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>, 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")),
    }
}

添加新传输

  1. 创建传输模块src/transport/my_transport.rs
  2. 实现服务功能:
pub async fn serve(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

📚 文档

🛠️ 依赖项

依赖关系版本目的文档
rmcp0.8.5MCP协议实现指南
拍手4.5.53CLI参数解析指南
虚构0.10.19配置管理指南
东京1.48.0异步运行时指南
追踪0.1.41结构化日志记录指南
追踪订户0.3.20日志格式化/过滤指南
追踪附录0.2.3带旋转的文件记录指南
这个错误2.0.17错误处理指南
序列化与反序列化1.0.228序列化标准库
Serde JSON1.0.145JSON处理标准库
东京-有用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

🔗 资源

🙏 致谢

______________________________________________________________________

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

目录标签

目录标签

Rust服务器模板生产就绪Rust开发本地部署MCP协议多传输支持

接入字段

传输方式(transport,传输协议)

未说明

鉴权方式(authType,认证方式)

none

工具数量(toolCount,工具数)

3

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

未说明none部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP