返回市场
MCP框架

MCP框架

作者:koki7o9 星标更新:2025-11-12

项目介绍

<div align="center"> <!-- Banner Image - Add your banner.png to docs/ directory --> <img src="assets/banner.png" alt="MCP 框架 Banner" width="800" style="margin-bottom: 20px;">

🚀 MCP 框架 - Rust 实现

<picture> <source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/badge/MCP%20Framework-Rust-orange?style=for-the-badge&logo=rust&logoColor=white"> <img alt="MCP 框架" src="https://img.shields.io/badge/MCP%20Framework-Rust-orange?style=for-the-badge&logo=rust&logoColor=white"> </picture>

生产就绪的 Rust 实现模型上下文协议,具有极快的性能、全面的工具和基于 Web 的检查器。


<p> <a href="https://github.com/koki7o/mcp-framework/blob/main/LICENSE"> <img alt="许可证" src="https://img.shields.io/badge/license-MIT-green" /> </a> <a href="https://spec.modelcontextprotocol.io/"> <img alt="MCP 规范" src="https://img.shields.io/badge/MCP-2025--11--11-blue" /> </a> <a href="https://www.rust-lang.org/"> <img alt="Rust" src="https://img.shields.io/badge/rust-1.70%2B-orange?logo=rust" /> </a> </p> </div>

🌐 MCP 框架是什么?

mcp-framework 是一个完整的、生产就绪的 Rust 实现的模型上下文协议,它使您能够:

  • 🤖 构建 AI 代理 - 创建与大型语言模型集成(Claude,OpenAI)并具备多步推理能力的智能代理
  • 🛠️ 创建 MCP 服务器 - 轻松注册工具、资源和提示
  • 📡 连接到 MCP 服务器 - 基于 HTTP 的客户端用于程序化工具访问
  • 🔍 使用检查器调试 - 美观的基于 Web 的仪表板用于测试工具
  • 高性能 - 极速的 Rust 实现
  • 🛡️ 类型安全 - 利用 Rust 的类型系统确保安全性和可靠性

✨ 主要特性

🎯 核心组件

功能状态详情
MCP 服务器✅ 完成注册工具,处理执行,JSON-RPC 协议
MCP 客户端✅ 完成基于 HTTP 的客户端用于调用远程工具
AI 代理✅ 完成具有可插拔 LLM 提供者的代理循环
Web 检查器✅ 完成http://localhost:8123 上的交互式 UI
Claude 集成✅ 完成AnthropicAdapter 用于 Claude 模型
OpenAI 集成✅ 完成OpenAIAdapter 用于 GPT 模型
协议类型✅ 完成工具和消息(核心 MCP 协议)
会话管理✅ 完成代理中的对话历史记录
资源⏳ 计划中用于向客户端提供文件和数据
提示⏳ 计划中可调用的动态生成提示模板
认证⏳ 计划中承载令牌,OAuth 2.0 支持
配置⏳ 计划中文件加载配置
.env 支持✅ 完成从环境文件加载 API 密钥

🛠️ 内置 8 个示例工具

• echo           - 字符串回声工具
• calculator     - 数学:加法、减法、乘法、除法、幂、平方根
• get_weather    - 查询全球城市的天气
• search_text    - 查找文本中的模式出现次数
• string_length  - 获取字符数
• text_reverse   - 反转文本字符串
• json_parser    - 验证和格式化 JSON
• http_status    - 查询 HTTP 状态码

📦 快速开始

先决条件

# 需要 Rust 1.70+
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

1. 克隆 & 设置

git clone https://github.com/koki7o/mcp-framework
cd mcp-framework

# 创建 .env 文件以存放 API 密钥(可选但推荐)
cp .env.example .env
# 编辑 .env 并添加 ANTHROPIC_API_KEY 或 OPENAI_API_KEY

2. 运行示例

最小服务器(1 个工具):

cargo run

带有 8 个工具和检查器 UI 的服务器:

cargo run --example server_with_tools
# 访问:http://localhost:8123

使用 Claude 的 AI 代理:

# 需要在 .env 中设置 ANTHROPIC_API_KEY
cargo run --example anthropic_agent_demo_with_tools --release

使用 OpenAI 的 AI 代理:

# 需要在 .env 中设置 OPENAI_API_KEY
cargo run --example openai_agent_demo_with_tools --release

🎯 想要构建什么?

🤖 构建 AI 代理

创建可以使用 MCP 工具完成复杂任务的智能代理。

快速示例:

use mcp_framework::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<()> {
    mcp_framework::load_env();

    let client = McpClient::new("http://localhost:3000");
    let llm = AnthropicAdapter::from_env("claude-sonnet-4-5-20250929".to_string())?;
    let mut agent = Agent::new(client, Arc::new(llm), AgentConfig::default());

    let response = agent.run("15 加 27 等于多少?").await?;
    println!("{}", response);

    Ok(())
}

运行示例:

  • cargo run --example anthropic_agent_demo_with_tools --release - Claude 示例
  • cargo run --example openai_agent_demo_with_tools --release - OpenAI 示例

🛠️ 创建 MCP 服务器

构建自己的 MCP 服务器,并带有自定义工具。

快速示例:

use mcp_framework::prelude::*;
use mcp_framework::server::{McpServer, ServerConfig, ToolHandler};
use std::sync::Arc;

struct MyToolHandler;

#[async_trait::async_trait]
impl ToolHandler for MyToolHandler {
    async fn execute(&self, name: &str, arguments: serde_json::Value)
        -> Result<Vec<ResultContent>> {
        match name {
            "greet" => Ok(vec![ResultContent::Text {
                text: format!("你好,{}!", arguments.get("name").and_then(|v| v.as_str()).unwrap_or("陌生人"))
            }]),
            _ => Err(Error::ToolNotFound(name.to_string())),
        }
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let config = ServerConfig {
        name: "我的服务器".to_string(),
        version: "1.0.0".to_string(),
        capabilities: ServerCapabilities {
            tools: Some(ToolsCapability { list_changed: Some(false) }),
            resources: None,  // 尚未实现
            prompts: None,    // 尚未实现
        },
    };

    let server = McpServer::new(config, Arc::new(MyToolHandler));

    server.register_tool(Tool {
        name: "greet".to_string(),
        description: Some("问候某人".to_string()),
        input_schema: None,
    });

    Ok(())
}

示例:

  • cargo run - 最小服务器(1 个工具)
  • cargo run --example server_with_tools - 综合示例(8 个工具 + 检查器)

📡 使用 MCP 客户端

连接到 MCP 服务器并程序化地调用工具。

快速示例:

use mcp_framework::prelude::*;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let client = McpClient::new("http://localhost:3000");

    // 列出所有工具
    let tools = client.list_tools().await?;
    println!("可用工具:{:?}", tools);

    // 调用工具
    let result = client.call_tool("echo", json!({
        "message": "你好,MCP!"
    })).await?;
    println!("结果:{:?}", result);

    Ok(())
}

示例:

  • cargo run --example client_usage - 完整的客户端使用示例

🔍 使用检查器调试

通过基于 Web 的 UI 交互式地测试和调试 MCP 服务器。

cargo run --example server_with_tools
# 在浏览器中打开:http://localhost:8123

检查器提供了:

  • 📋 查看所有已注册的工具及其描述
  • 🧪 交互式测试工具,自动生成表单
  • 📊 查看完整的请求/响应历史记录
  • 🔍 实时检查工具输出和错误

📁 项目结构

mcp-framework/
├── src/
│   ├── lib.rs                ← 主库入口点(预设 + 导出)
│   ├── protocol.rs           ← MCP 类型定义(工具、消息、协议)
│   ├── server.rs             ← McpServer 实现及工具注册
│   ├── client.rs             ← McpClient 实现(基于 HTTP)
│   ├── agent.rs              ← AI 代理,具有代理循环及 LLM 集成
│   ├── inspector.rs          ← 基于 Web 的调试 UI(localhost:8123)
│   ├── error.rs              ← 错误类型和 JSON-RPC 码
│   └── adapters/
│       ├── mod.rs
│       ├── anthropic.rs      ← Claude (Anthropic) LLM 适配器
│       └── openai.rs         ← OpenAI GPT LLM 适配器
├── examples/
│   ├── server_with_tools.rs              ← 带有检查器的 8 个工具服务器
│   ├── anthropic_agent_demo_with_tools.rs ← Claude 代理示例
│   ├── openai_agent_demo_with_tools.rs    ← OpenAI 代理示例
│   └── client_usage.rs                    ← 客户端使用示例
├── assets/
│   └── banner.png           
├── Cargo.toml
├── Cargo.lock
├── LICENSE                   ← MIT 许可证
├── .env.example              ← 环境变量模板
├── .gitignore
└── README.md

🚀 核心 API 参考

创建服务器

let config = ServerConfig {
    name: "我的服务器".to_string(),
    version: "1.0.0".to_string(),
    capabilities: ServerCapabilities {
        tools: Some(ToolsCapability { list_changed: Some(false) }),
        resources: None,  // 尚未实现
        prompts: None,    // 尚未实现
    },
};

let handler = Arc::new(MyToolHandler);
let server = McpServer::new(config, handler);

注册工具

use std::collections::HashMap;
use serde_json::json;

let mut properties = HashMap::new();
properties.insert("param".to_string(), json!({"type": "string"}));

server.register_tool(Tool {
    name: "my_tool".to_string(),
    description: Some("做一些有用的事情".to_string()),
    input_schema: Some(ToolInputSchema {
        schema_type: "object".to_string(),
        properties,
        required: Some(vec!["param".to_string()]),
    }),
});

实现 ToolHandler

#[async_trait::async_trait]
impl ToolHandler for MyHandler {
    async fn execute(&self, name: &str, arguments: Value)
        -> Result<Vec<ResultContent>> {
        match name {
            "my_tool" => {
                // 提取并验证参数
                let param = arguments.get("param")
                    .and_then(|v| v.as_str())?;

                // 实现你的逻辑
                let result = do_something(param);

                Ok(vec![ResultContent::Text {
                    text: result.to_string()
                }])
            }
            _ => Err(Error::ToolNotFound(name.to_string())),
        }
    }
}

创建代理

use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<()> {
    mcp_framework::load_env();

    let client = McpClient::new("http://localhost:3000");
    let llm = AnthropicAdapter::from_env("claude-sonnet-4-5-20250929".to_string())?;

    let mut agent = Agent::new(client, Arc::new(llm), AgentConfig {
        max_iterations: 10,
        max_tokens: Some(2048),
    });

    let response = agent.run("在这里输入你的查询").await?;
    println!("响应:{}", response);

    Ok(())
}

使用客户端

let client = McpClient::new("http://localhost:3000");

// 列出可用工具
let tools = client.list_tools().await?;

// 调用工具
let result = client.call_tool("echo", json!({
    "message": "你好!"
})).await?;

🧪 测试

# 运行所有测试
cargo test

# 运行带输出
cargo test -- --nocapture

# 运行特定测试
cargo test test_name

# 使用发布优化运行
cargo test --release

🤝 贡献

欢迎贡献!请随时提交拉取请求。


📄 许可证

MIT 许可证 - 详见 LICENSE 文件


🔗 资源


<div align="center">

为 MCP 社区制作 ❤️

报告问题讨论

</div>