cpp-mcp/README_zh.md

3.5 KiB
Raw Blame History

MCP Protocol Framework

Model Context Protocol (MCP) 是一个开放协议为AI模型和代理提供与各种资源、工具和服务交互的标准化方式。本框架实现了MCP协议的核心功能符合2024-11-05基本协议规范。

核心特性

  • JSON-RPC 2.0通信: 基于JSON-RPC 2.0标准的请求/响应通信
  • 资源抽象: 文件、API等资源的标准接口
  • 工具注册: 注册和调用带有结构化参数的工具
  • 可扩展架构: 易于扩展新的资源类型和工具

组件

核心协议 (mcp_message.h, mcp_message.cpp)

定义MCP的基本结构和类型:

  • 请求/响应处理
  • 错误代码
  • 工具定义

服务器 (mcp_server.h, mcp_server.cpp)

实现一个HTTP服务器暴露MCP资源和工具:

  • 在特定路径注册资源
  • 注册带有处理程序的工具
  • 处理传入的HTTP请求
  • 将请求路由到适当的资源

客户端 (mcp_client.h, mcp_client.cpp)

实现连接到MCP服务器的客户端:

  • 连接到服务器
  • 发现可用的资源和工具
  • 向资源发出请求
  • 使用参数调用工具

资源 (mcp_resource.h, mcp_resource.cpp)

提供常见资源类型的基本实现:

  • 文件资源
  • API资源

工具 (mcp_tool.h, mcp_tool.cpp)

提供工具相关功能:

  • 工具构建器 (流畅API)

示例

服务器示例 (examples/server_example.cpp)

MCP服务器实现示例带有自定义工具:

  • 时间工具: 获取当前时间
  • 计算器工具: 执行数学运算
  • 回显工具: 处理和分析文本

客户端示例 (examples/client_example.cpp)

连接到服务器的MCP客户端示例:

  • 获取服务器信息
  • 列出可用工具
  • 使用参数调用工具
  • 访问资源

如何使用

设置服务器

// 创建并配置服务器
mcp::server server("localhost", 8080);
server.set_server_info("MCP Example Server", "2024-11-05");

// 注册工具
mcp::tool time_tool = mcp::tool_builder("get_time")
    .with_description("Get the current time")
    .build();

server.register_tool(time_tool, [](const mcp::json& params) {
    // 工具实现
    return mcp::json::object();
});

// 注册资源
auto file_resource = std::make_shared<mcp::file_resource>("./files");
server.register_resource("/files", file_resource);

// 启动服务器
server.start(true);  // 阻塞模式

创建客户端

// 连接到服务器
mcp::client client("localhost", 8080);

// 初始化连接
client.initialize("My Client", "1.0.0");

// 调用工具
mcp::json params = {
    {"key", "value"}
};
mcp::json result = client.call_tool("tool_name", params);

构建框架

框架依赖以下库:

  • httplib.h - HTTP服务器和客户端
  • json.hpp - JSON解析和生成

所有依赖项都包含在仓库中。

使用CMake构建示例:

cmake -B build
cmake --build build --config Release

扩展框架

添加新的资源类型

  1. 定义一个继承自mcp::resource的新类
  2. 实现所需的方法:
    • json get_metadata() const
    • json access(const json& params) const

创建自定义工具

使用工具构建器API:

// 创建工具定义
mcp::tool my_tool = mcp::tool_builder("my_tool")
    .with_description("My custom tool")
    .with_string_param("input", "Input parameter", true)
    .with_number_param("count", "Count parameter", false)
    .build();

// 注册工具处理程序
server.register_tool(my_tool, [](const mcp::json& params) {
    // 工具实现
    return mcp::json::object();
});

许可证

本框架根据MIT许可证提供。有关详细信息请参阅LICENSE文件。