惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
T
Threatpost
WordPress大学
WordPress大学
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
PCI Perspectives
PCI Perspectives
T
The Exploit Database - CXSecurity.com
Y
Y Combinator Blog
雷峰网
雷峰网
爱范儿
爱范儿
The Hacker News
The Hacker News
Last Week in AI
Last Week in AI
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
S
Securelist
宝玉的分享
宝玉的分享
L
LangChain Blog
O
OpenAI News
AI
AI
P
Privacy International News Feed
L
LINUX DO - 最新话题
D
DataBreaches.Net
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Attack and Defense Labs
Attack and Defense Labs
罗磊的独立博客
M
MIT News - Artificial intelligence
Security Archives - TechRepublic
Security Archives - TechRepublic
月光博客
月光博客
博客园 - 【当耐特】
T
Tailwind CSS Blog
C
Cybersecurity and Infrastructure Security Agency CISA
H
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
Jina AI
Jina AI
The Last Watchdog
The Last Watchdog
K
Kaspersky official blog
Webroot Blog
Webroot Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Blog — PlanetScale
Blog — PlanetScale
MyScale Blog
MyScale Blog
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
Recorded Future
Recorded Future
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog

博客园 - 南水之源

osgImage和QImage互相转换 AI助手选哪个?Cowork vs OpenClaw深度解析:程序猿、打工人、老板们看过来 "数字管家"Claude Cowork,正在接管你的桌面 Claude Code:那只被称为"代码章鱼"的AI,正在吃掉整个编程世界 “拥有数字生命的龙虾”OpenClaw的前世今生 怎么领取使用国家超算中心小龙虾tokens 使用gdal修改shp数据 保存OE中使用的高程数据用gdal保存成tif文件[完成] blender GIS介绍 使用qt读取系统字体库,并进行英文名称映射 c++开发大模型mcp服务(七)使用cpp-mcp的例子MCP-ExcelAutoCpp c++开发大模型mcp服务(五)编译c++版本的mcp库(cpp-mcp) c++开发大模型mcp服务(四)使用工具测试高德地图的MCP(流程验证) c++开发大模型mcp服务(三)一个常规的MCP调用例子(以高德地图MCP举例) c++开发大模型mcp服务(二)MCP 架构说明 c++开发大模型mcp服务(一)目的和概念 解除360首页锁定操作 辅助Visual Studio上C++开发的工具(插件) [书]清华大学DeepSeek:从入门到精通 [原]geoserver缓存切片类GeoServerMetaTile的解析UML
c++开发大模型mcp服务(六)cpp-mcp库说明
南水之源 · 2025-09-02 · via 博客园 - 南水之源

模型上下文协议 (MCP)是一个开放协议,为 AI 模型和代理与各种资源、工具和服务交互提供了标准化的方式。

cpp-mcp 该框架实现了 MCP 协议的核心功能,并符合 2024-11-05 基本协议规范。

一、核心功能

  • JSON-RPC 2.0 通信:基于 JSON-RPC 2.0 标准的请求/响应通信
  • 资源抽象:文件、API 等资源的标准接口。
  • 工具注册:使用结构化参数注册和调用工具
  • 可扩展架构:易于扩展新的资源类型和工具
  • 多传输支持:支持 HTTP 和标准输入/输出 (stdio) 通信方法

二、如何构建

1.使用 CMake 构建的示例:

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

2.通过测试构建:

git submodule update --init --recursive # Get GoogleTest

cmake -B build -DMCP_BUILD_TESTS=ON
cmake --build build --config Release

3.使用 SSL 支持进行构建:

git submodule update --init --recursive # Get GoogleTest

cmake -B build -DMCP_SSL=ON
cmake --build build --config Release

三、构成

MCP C++库包括以下主要组件:

1.客户端接口(mcp_client.h

定义 MCP 客户端的抽象接口,所有具体的客户端实现都从该接口继承。

2.SSE 客户端(mcp_sse_client.hmcp_sse_client.cpp

使用 HTTP 和服务器发送事件 (SSE) 与 MCP 服务器通信的客户端实现。

3.标准输入输出客户端(mcp_stdio_client.hmcp_stdio_client.cpp

客户端实现使用标准输入/输出与 MCP 服务器通信,能够启动子进程并与其通信。

4.消息处理(mcp_message.hmcp_message.cpp

处理 JSON-RPC 消息的序列化和反序列化。

5.工具管理(mcp_tool.hmcp_tool.cpp

管理和调用 MCP 工具。

6.资源管理(mcp_resource.hmcp_resource.cpp

管理 MCP 资源。

7.服务器 (mcp_server.hmcp_server.cpp

实现 MCP 服务器功能。

四、示例

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

使用自定义工具的 MCP 服务器实现示例:

  • 时间工具:获取当前时间
  • 计算器工具:执行数学运算
  • 回显工具:回显输入并可选择转换(转换为大写、反转)
  • 问候工具:返回Hello, +输入名称+ !,默认为Hello, World!

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

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

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

3.Stdio 客户端示例 ( examples/stdio_client_example.cpp)

演示如何使用 stdio 客户端与本地服务器通信:

  • 启动本地服务器进程
  • 访问文件系统资源
  • 调用服务器工具

4.智能体示例 ( examples/agent_example.cpp)

选项描述
--base-url LLM 基本网址(例如https://openrouter.ai
--endpoint LLM 端点(默认为/v1/chat/completions/
--api-key LLM API 密钥
--model 型号名称(例如gpt-3.5-turbo
--system-prompt 系统提示
--max-tokens 生成的最大令牌数(默认为 2048)
--temperature 温度(默认为 0.0)
--max-steps 无需用户输入调用工具的最大步骤(默认为 3)

使用示例:

./build/examples/agent_example --base-url <base_url> --endpoint <endpoint> --api-key <api_key> --model <model_name>

注意:连接到 https 基本 URL 时请记住进行 -DMCP_SSL=ON 编译。

五、如何使用

1.设置 HTTP 服务器

// Create and configure the server
mcp::server server("localhost", 8080); // Host and port
server.set_server_info("MCP Example Server", "0.1.0"); // Name and version

// Register tools
mcp::json hello_handler(const mcp::json& params, const std::string /* session_id */) {
    std::string name = params.contains("name") ? params["name"].get<std::string>() : "World";

    // Server will catch exceptions and return error contents
    // For example, you can use `throw mcp::mcp_exception(mcp::error_code::invalid_params, "Invalid name");` to report an error

    // Content should be a JSON array, see: https://modelcontextprotocol.io/specification/2024-11-05/server/tools#tool-result
    return {
        {
            {"type", "text"},
            {"text", "Hello, " + name + "!"}
        }
    };
}

mcp::tool hello_tool = mcp::tool_builder("hello")
        .with_description("Say hello")
        .with_string_param("name", "Name to say hello to", "World")
        .build();

server.register_tool(hello_tool, hello_handler);

// Register resources
auto file_resource = std::make_shared<mcp::file_resource>("<file_path>");
server.register_resource("file://<file_path>", file_resource);

// Start the server
server.start(true);  // Blocking mode

2.创建 HTTP 客户端

// Connect to the server
mcp::sse_client client("localhost", 8080);

// Initialize the connection
client.initialize("My Client", "1.0.0");

// Call a tool
mcp::json params = {
    {"name", "Client"}
};

mcp::json result = client.call_tool("hello", params);

3.使用 SSE 客户端

SSE 客户端使用 HTTP 和服务器发送事件 (SSE) 与 MCP 服务器通信。这是一种基于 Web 标准的通信方式,适用于与支持 HTTP/SSE 的服务器通信。

#include "mcp_sse_client.h"

// Create a client, specifying the server address and port
mcp::sse_client client("localhost", 8080);
// Or use a base URL
// mcp::sse_client client("http://localhost:8080");

// Set an authentication token (if needed)
client.set_auth_token("your_auth_token");

// Set custom request headers (if needed)
client.set_header("X-Custom-Header", "value");

// Initialize the client
if (!client.initialize("My Client", "1.0.0")) {
    // Handle initialization failure
}

// Call a tool
json result = client.call_tool("tool_name", {
    {"param1", "value1"},
    {"param2", 42}
});

4.使用 Stdio 客户端

Stdio 客户端可以与任何支持 stdio 传输的 MCP 服务器进行通信,例如:

  • @modelcontextprotocol/server-everything - 示例服务器
  • @modelcontextprotocol/server-filesystem - 文件系统服务器
  • 其他支持 stdio 传输的MCP 服务器
#include "mcp_stdio_client.h"

// Create a client, specifying the server command
mcp::stdio_client client("npx -y @modelcontextprotocol/server-everything");
// mcp::stdio_client client("npx -y @modelcontextprotocol/server-filesystem /path/to/directory");

// Initialize the client
if (!client.initialize("My Client", "1.0.0")) {
    // Handle initialization failure
}

// Access resources
json resources = client.list_resources();
json content = client.read_resource("resource://uri");

// Call a tool
json result = client.call_tool("tool_name", {
    {"param1", "value1"},
    {"param2", "value2"}
});