MCP协议服务器

一个基于Rust实现的MCP协议服务器,支持HTTP和STDIO传输,提供完整的MCP协议功能,包括资源管理、工具执行、提示生成等。

  • by Jeetulsamaiya
  • Rust
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 Jeetulsamaiya/mcp-server

使用说明

MCP服务器-Rust实现

Rust中的测试模型上下文协议(MCP)服务器实现,遵循官方MCP规范(2025-03-26)。此服务器提供了MCP协议的完整实现,支持HTTP和STDIO传输、全面的错误处理和所有核心MCP功能。

特性

核心MCP协议支持

  • 完成MCP 2025-03-26的实施:完全符合最新的MCP规范
  • JSON-RPC 2.0:正确的消息格式和错误处理
  • 服务器能力协商:动态能力发现和配置
  • 请求/响应验证:根据规范进行全面验证

传输层

  • HTTP传输:可流式传输HTTP,可选SSE流式传输
  • STDIO传输:子流程通信的标准输入/输出
  • 会话管理:具有自动清理功能的HTTP会话跟踪
  • CORS支持:可配置的跨源资源共享

服务器功能

  • 资源:支持订阅的文件系统和HTTP资源提供程序
  • 工具:具有验证功能的可扩展工具执行框架
  • 提示:基于模板的提示生成,支持Handlebars
  • 日志记录:具有多个级别和格式的结构化日志记录
  • 完成:提示和资源的参数完成

客户端功能

  • 采样:LLM采样与多个提供商的集成
  • 根:用于安全文件访问的根目录管理

安全与生产特性

  • 认证:API密钥和JWT令牌支持
  • 授权:基于角色的访问控制
  • 配置管理:基于TOML的配置和验证
  • 错误处理:使用适当的MCP错误代码进行全面的错误处理
  • 日志记录:具有可配置级别和格式的结构化日志记录

快速开始

安装

# Clone the repository
git clone <repository-url>
cd mcp-server

# Build the project
cargo build --release

# Install the binary (optional)
cargo install --path .

基本用法

启动HTTP服务器

# Start with default settings (HTTP on localhost:8080)
mcp-server start

# Start with custom settings
mcp-server start --bind 0.0.0.0 --port 9090 --name "My MCP Server"

启动STDIO服务器

# Start STDIO transport for subprocess communication
mcp-server start --stdio

生成配置

# Generate default configuration file
mcp-server config --output mcp-server.toml

# Validate configuration
mcp-server validate mcp-server.toml

# Show server information
mcp-server info

配置

创建配置文件(mcp-server.toml):

[server]
name = "My MCP Server"
version = "1.0.0"
instructions = "A helpful MCP server"
max_connections = 100
request_timeout = 30

[transport]
transport_type = "http"

[transport.http]
bind_address = "127.0.0.1"
port = 8080
endpoint_path = "/mcp"
enable_cors = true
cors_origins = ["*"]
session_timeout = 3600

[auth]
enabled = false
method = "none"

[logging]
level = "info"
format = "pretty"
enable_request_logging = false

[features]
resources = true
tools = true
prompts = true
sampling = true
logging = true
completion = true
roots = true

API使用

HTTP传输

服务器在配置的端点公开可流式HTTP传输API(默认值: /mcp):

  • POST /mcp -发送JSON-RPC消息(单个请求或批处理)
  • GET /mcp -建立服务器发送事件(SSE)连接以进行流式传输
  • DELETE /mcp -终止会话并清理资源

会话管理

服务器通过以下方式自动管理HTTP会话:

  • 通过以下方式跟踪会话ID Mcp-Session-Id 头球
  • 为新客户端自动创建会话
  • 可配置的会话超时(默认值:1小时)
  • 终止时的会话清理

请求示例

初始化连接:

curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": "1",
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-03-26",
      "capabilities": {},
      "clientInfo": {
        "name": "example-client",
        "version": "1.0.0"
      }
    }
  }'

列出可用工具:

curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": "2",
    "method": "tools/list"
  }'

建立SSE流:

curl -X GET http://localhost:8080/mcp \
  -H "Accept: text/event-stream" \
  -H "Cache-Control: no-cache"

STDIO传输

对于子流程通信,使用STDIO传输:

# Start STDIO server
mcp-server start --stdio

# Send JSON-RPC messages via stdin
echo '{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"stdio-client","version":"1.0.0"}}}' | mcp-server start --stdio

发展

项目结构

src/
├── main.rs              # CLI application entry point
├── lib.rs               # Library exports and public API
├── config.rs            # Configuration management (TOML/JSON)
├── error.rs             # Error handling and MCP error codes
├── protocol/            # MCP protocol implementation
│   ├── mod.rs           # Protocol exports
│   ├── messages.rs      # MCP message types and serialization
│   ├── validation.rs    # Request/response validation
│   └── handler.rs       # Central protocol message handler
├── transport/           # Transport layer implementations
│   ├── mod.rs           # Transport abstractions
│   ├── http.rs          # HTTP transport with SSE streaming
│   ├── stdio.rs         # STDIO transport for subprocess
│   └── session.rs       # HTTP session lifecycle management
├── server/              # Server-side MCP features
│   ├── mod.rs           # Server implementation
│   └── features/        # Feature managers
│       ├── mod.rs       # Feature exports
│       ├── resources.rs # Resource management (file/HTTP)
│       ├── tools.rs     # Tool execution framework
│       ├── prompts.rs   # Prompt template engine
│       ├── logging.rs   # Logging feature
│       └── completion.rs # Argument completion
├── client/              # Client-side MCP features
│   └── features/        # Client feature managers
│       ├── mod.rs       # Client feature exports
│       ├── sampling.rs  # LLM sampling integration
│       └── roots.rs     # Root directory management
└── utils/               # Shared utilities
    ├── mod.rs           # Utility exports
    ├── logging.rs       # Logging configuration
    ├── auth.rs          # Authentication helpers
    └── validation.rs    # Additional validation utilities

docs/                    # Comprehensive documentation
├── README.md            # Documentation index
├── architecture-overview.md
├── http-request-flow.md
├── http-streaming-flow.md
├── protocol-message-flow.md
├── tool-registration-flow.md
├── error-handling-flow.md
├── authentication-flow.md
├── state-management.md
├── session-management.md
├── concurrency-model.md
├── system-initialization-flow.md
└── sequence-interaction-flow.md

examples/                # Usage examples
├── basic_server.rs      # Basic server setup example
└── mcp-server.toml      # Example configuration file

建造和测试

# Development build
cargo build

# Release build
cargo build --release

# Run all tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Run specific test module
cargo test protocol::validation

# Run with debug logging
RUST_LOG=debug cargo run -- start --verbose

# Check code formatting
cargo fmt --check

# Run clippy lints
cargo clippy -- -D warnings

添加自定义功能

自定义工具处理程序

use mcp_server::server::features::{ToolHandler, ToolResult};
use async_trait::async_trait;

pub struct MyToolHandler;

#[async_trait]
impl ToolHandler for MyToolHandler {
    fn name(&self) -> &str {
        "my_tool"
    }

    async fn execute(&self, arguments: Option<serde_json::Value>) -> mcp_server::Result<ToolResult> {
        // Your tool implementation
        Ok(ToolResult::text("Tool executed successfully".to_string()))
    }
}

自定义资源提供程序

use mcp_server::server::features::{ResourceProvider, ResourceContents};
use async_trait::async_trait;

pub struct MyResourceProvider;

#[async_trait]
impl ResourceProvider for MyResourceProvider {
    fn name(&self) -> &str {
        "my_provider"
    }

    fn can_handle(&self, uri: &str) -> bool {
        uri.starts_with("my://")
    }

    async fn read_resource(&self, uri: &str) -> mcp_server::Result<Vec<ResourceContents>> {
        // Your resource implementation
        Ok(vec![])
    }
}

测试

该项目包括涵盖所有主要组成部分的全面测试:

单元测试

# Run all unit tests
cargo test

# Run specific module tests
cargo test protocol::validation
cargo test transport::http
cargo test server::features

# Run with output for debugging
cargo test -- --nocapture

集成测试

# Run integration tests (if available)
cargo test --test integration

# Test with MCP Inspector client
# 1. Start the server: cargo run -- start
# 2. Connect MCP Inspector to http://localhost:8080/mcp
# 3. Test protocol compliance and feature functionality

手动测试

# Test HTTP transport
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}'

# Test STDIO transport
echo '{"jsonrpc":"2.0","id":"1","method":"tools/list"}' | cargo run -- start --stdio

贡献

  1. 分叉存储库
  2. 创建要素分支(git checkout -b feature/amazing-feature)
  3. 提交您的更改(git commit -m 'Add amazing feature')
  4. 推到分支(git push origin feature/amazing-feature)
  5. 打开拉取请求

代码的风格

  • 遵循Rust标准格式(cargo fmt)
  • 确保所有测试通过(cargo test)
  • 为公共API添加文档
  • 遵循现有的错误处理模式

许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

文档

有关详细的技术文档,请参阅 docs/ 目录:

致谢

支持

  • 文档:参见 docs/ 综合指南目录
  • 例子:检查 示例/ 使用示例目录
  • 问题:通过存储库问题报告错误和功能请求
  • 配置:使用 mcp-server config 生成示例配置文件