# mcp_cpp **Repository Path**: qingcaiyurou/mcp_cpp ## Basic Information - **Project Name**: mcp_cpp - **Description**: No description available - **Primary Language**: C++ - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2025-09-23 - **Last Updated**: 2025-11-25 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # MCP C++ SDK 现代 C++ 的 MCP SDK 与示例集,采用 CMake 构建,内置多种传输适配器(stdio、process、WebSocket、HTTP+SSE、in-memory),并提供一键脚本完成本地 Mock 启动与自动化回归。 ## 特性 - 会话与协议 - 统一 JSON-RPC 会话(请求/响应/通知、读线程、超时/取消、回调绑定) - 支持 `initialize`、`tools/*`、`prompts/*`、`resources/*`、`logging/*`、`completion/*`、订阅/取消订阅等核心能力 - 传输适配器 - `StdioTransport`(跨平台) - `ProcessTransport`(Windows):子进程管道 - `WebSocketTransport`(Windows/WinHTTP):支持握手诊断、PING/PONG - `HttpSseTransport`(Windows/WinHTTP):POST + SSE 推送,避免初始化竞态 - `InMemoryTransport`(跨平台):单进程内联调 - 本地 Mock - `server.js`(WS,默认 ws://localhost:3000/,禁用 perMessageDeflate,并协商 `Sec-WebSocket-Protocol: jsonrpc`) - `sse_server.js`(HTTP+SSE,默认 http://localhost:8080/mcp,返回 JSON-RPC 到 SSE 与 POST 响应体,避免竞态) - 自动化脚本(Windows PowerShell) - `scripts/test_all.ps1`:一键构建并运行所有示例 - `scripts/test_new_features.ps1`:自动拉起 Node mock(如存在并指向本机默认端口),并依次验证 `protected_client`、`ws_client`、`http_client` - 脚本可迁移:锚定仓库根目录;检测仓库移动后自动清理 `build/` 并重新配置 - 可迁移性 - 路径均相对仓库根解析;移动/重命名仓库目录后,脚本会自动刷新 CMake 缓存 ## 目录结构 - `include/mcp/`:公共头文件(会话、客户端、传输接口等) - `src/`:实现(`json_rpc.cpp`、`session.cpp`、各传输适配器与 OAuth2 客户端) - `examples/`:示例(客户端/服务端/内存通道等) - `server.js`、`sse_server.js`:Node 本地 Mock(WS 与 HTTP+SSE) - `scripts/`:自动化脚本(见下文) - `third_party/nlohmann_json/include/`:可选内置单头库备用 更多头文件说明(位于 `include/mcp/`): - `client.hpp`:客户端封装,暴露 Initialize/Tools/Prompts/Resources/Logging/Roots/Completion 等方法与通知绑定 - `server.hpp`:服务器封装,支持注册工具、提示词、资源,并内置多项处理器(如 `tools/list`、`resources/read` 等) - `session.hpp`:通用 JSON-RPC 会话(消息收发、pending 请求、读线程、回调注册) - `transport.hpp`:传输接口 `ITransport` - `stdio_transport.hpp` / `process_transport.hpp` / `websocket_transport.hpp` / `http_sse_transport.hpp` / `inmemory_transport.hpp` - `constants.hpp`:常量与方法名 - `models.hpp`:部分模型 DTO(Completion、PromptArgument、Resource 等) ## 功能详解 - 会话与传输 - 统一的 JSON-RPC 会话:读线程、pending 请求、回调注册、超时/取消 - 传输层: - `StdioTransport`(跨平台) - `ProcessTransport`(Windows):子进程管道(已优化关闭顺序,避免 `ReadFile` 阻塞导致退出卡死) - `InMemoryTransport`(跨平台):队列+条件变量,适合单进程联调 - `WebSocketTransport`(Windows/WinHTTP):支持握手诊断、PING/PONG - `HttpSseTransport`(Windows/WinHTTP):POST + SSE;避免初始化竞态(POST 同时返回 JSON-RPC 响应) - 协议方法(摘选) - `initialize`:协商 `protocolVersion`,返回 `serverInfo` 与 `capabilities`;随后客户端发送 `notifications/initialized` - Tools:`tools/list`、`tools/call`(内置 `long_task` 支持进度通知与取消) - Prompts:`prompts/list`、`prompts/get` - Resources:`resources/list`、`resources/read`、`resources/templates/list`、订阅 `resources/subscribe` / 取消 `resources/unsubscribe`,以及 `notifications/resources/updated` - Logging:`logging/setLevel` + 周期性 `notifications/logging/message` - Roots:客户端 `roots/list` 与 `notifications/roots/list_changed` - Completion:`completion/complete` - Sampling/Elicitation(Demo):`sampling/createMessage`、`elicitation/create` - Cancelled:`notifications/cancelled` 主动取消请求(可打断内置 `long_task`) - 客户端便捷封装 - `Client` 提供同步等待的便利方法(带超时):`initialize`、`list_tools`、`call_tool`、`list_prompts`、`get_prompt`、`list_resources`、`read_resource`、`list_resource_templates`、`set_logging_level`、`completion_complete`、`subscribe_resource`、`unsubscribe_resource` 等 - 事件/通知:`on_progress`、`on_logging_message`、`on_*_list_changed`、`on_resource_updated` - Roots 管理:`set_roots/add_root/notify_roots_list_changed` - 服务器安全(示例) - `ServerOptions.authToken`:若设置则 `initialize` 需要携带 `Authorization: Bearer ` 或 `auth.token`,否则返回未授权(示例用途) ## 依赖与构建 - CMake ≥ 3.20;C++20 编译器 - 依赖:`nlohmann_json` - 优先 `find_package(nlohmann_json CONFIG)` - 若未找到则回退到 `third_party/nlohmann_json/include` - 也可通过 `-DNLOHMANN_JSON_INCLUDE_DIR=...` 显式指定 - Windows 下链接 `winhttp`(HTTP/SSE、OAuth2、WebSocket 均使用 WinHTTP) 典型构建(生成 build 目录与工程文件): (要先配置编译环境https://blog.csdn.net/qq_42417071/article/details/137438374) ```powershell cmake -S . -B build ``` 如果报类似如下信息,表示缓存文件 (CMakeCache.txt) 的路径与当前路径不匹配,删除build文件夹即可。 ``` CMake Error: The current CMakeCache.txt directory E:/mcp_cpp_sdk/build/CMakeCache.txt is different than the directory /home/edge/zyq/mcp_cpp/build where CMakeCache.txt was created. This may result in binaries being created in the wrong place. If you are not sure, reedit the CMakeCache.txt CMake Error: The source "E:/10_11/mcp_cpp_sdk/CMakeLists.txt" does not match the source "/home/edge/zyq/mcp_cpp/CMakeLists.txt" used to generate cache. Re-run cmake with a different source directory. ``` 如需直接编译: ```powershell cmake --build build --config Release ``` > 脚本会自动构建,无需手动 `--build`;但首次运行建议先执行一次 `cmake -S . -B build` 以生成构建目录。 ## 快速开始与测试(Windows) 以下命令将完成一键测试;脚本会: - 自动构建 - 自动安装所需 Node 依赖(`ws@8`、`express`) - 自动启动本地 Mock(若脚本与配置指向 `localhost` 默认端口) - 运行并断言结果,打印汇总 ```powershell cmake -S . -B build powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test_all.ps1 -Config Release powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test_new_features.ps1 ``` 说明: - `scripts/test_all.ps1` 会覆盖绝大多数示例的回归; - `scripts/test_new_features.ps1` 侧重于 WS 与 HTTP+SSE 的自动拉起与校验: - 若仓库根存在 `server.js` 且配置指向 `ws://localhost:3000/`,脚本会自动安装/启动 WS Mock; - 若仓库根存在 `sse_server.js` 且配置指向 `http+sse://localhost:8080/mcp`,脚本会自动安装/启动 SSE Mock; - 结束时脚本会清理自动启动的 Node 进程。 ## 自动化回归(Windows) `scripts/test_all.ps1` 用于一键构建与回归: - **构建** `mcp` 库与所有示例(含 `inmemory_demo`、`everything_server`、`weather_server`、`quickstart_client`、`chat_with_tools`、`protected_server`、`protected_client` 等) - **运行** 全量客户端示例;对“自包含”的示例(如 `inmemory_demo`)不会注入 `echo_server` 参数 - **落盘日志**:`build/logs/.out.txt / .err.txt / .log` - **判定**:基于大小写不敏感子串进行 PASS/WARN/FAIL 判定;异常/超时也会写入空文件并记录异常 ## 配置文件(可选) `scripts/test_new_features.ps1` 会读取 `tests/config.json`(相对仓库根)。支持字段: - `ws_url`:如 `ws://localhost:3000/` - `http_sse_base`:如 `http+sse://localhost:8080/mcp` - `auth_header`:如 `Authorization: Bearer `(传给 `ws_client` 的 `--header`) - `subprotocol`:如 `jsonrpc`(传给 `ws_client` 的 `--subprotocol`) - `oauth2`:可选 `{ token_url, client_id, client_secret }` - 本地 `SSE` 测试中,若检测为占位/示例值会自动跳过以避免外网调用超时 示例(可按需精简): ```json { "ws_url": "ws://localhost:3000/", "http_sse_base": "http+sse://localhost:8080/mcp", "subprotocol": "jsonrpc", "auth_header": "Authorization: Bearer secret-token" } ``` ## 本地 Mock(Node) - `server.js`(WS) - 监听 `ws://localhost:3000/` - 关闭 `perMessageDeflate` - `handleProtocols` 优先回显 `jsonrpc` 子协议 - 打印请求/通知日志 - `sse_server.js`(HTTP+SSE) - SSE:`GET /mcp/events` - POST:`POST /mcp/message`(将 JSON-RPC 响应同时广播到 SSE,且直接作为 POST 响应返回,避免初始化竞态) > 脚本会在需要时自动执行 `npm install ws@8` 与 `npm install express`。 ## 示例清单 - 服务器(跨平台):`echo_server`、`everything_server`、`weather_server`、`protected_server` - 客户端(Windows):`echo_client`、`quickstart_client`、`chat_with_tools`、`protected_client`、`http_client`、`ws_client`、`resources_client`、`prompts_client`、`completion_client`、`list_changed_client`、`logging_roots_client`、`subscribe_client` - 内存通道(跨平台):`inmemory_demo` 运行示例(单例): ```powershell # 以 quickstart_client 为例(会拉起 echo_server 子进程) build\examples\quickstart_client\Release\quickstart_client.exe "build\examples\echo_server\Release\echo_server.exe" # 内存通道 demo(自包含) build\examples\inmemory_demo\Release\inmemory_demo.exe # WS 客户端(本地 mock) build\examples\ws_client\Release\ws_client.exe ws://localhost:3000/ --subprotocol jsonrpc # HTTP+SSE 客户端(本地 mock) build\examples\http_client\Release\http_client.exe http+sse://localhost:8080/mcp ``` ## 可迁移性说明 - 脚本以仓库根为锚点解析路径,当前工作目录无关 - 若移动/重命名仓库目录: - `scripts/test_new_features.ps1` 会检测到 `build/CMakeCache.txt` 的旧源路径并自动清空 `build/` 后重新配置 - 手动使用 CMake 时,若见到 "source ... does not match ... used to generate cache",请删除或更换 `build` 目录: ```powershell Remove-Item -Recurse -Force .\build cmake -S . -B build ``` ## 日志与排查 - 运行期日志: - `client_debug.log`:客户端会话/传输关键节点 - `server_debug.log`:服务器关键节点 - 自动化脚本会为每个用例生成 `build/logs/.out.txt / .err.txt / .log` - WS 失败时输出 WinHTTP `GetLastError=` 诊断;SSE 失败时输出响应形状异常提示 ## 与 C# 样例的映射 - Quickstart(Client/WeatherServer):`quickstart_client`、`weather_server` - EverythingServer:`everything_server`(含工具/提示词/资源/日志等) - Protected(Server/Client):`protected_server` 与 `protected_client` - ChatWithTools:`chat_with_tools` - InMemoryTransport:`inmemory_demo` - ASP.NET Core 宿主类样例不直接移植(以 stdio 服务器与多传输形态等价演示;如需多会话宿主可后续提供基于 ASIO 的样例) ## 已知限制与后续计划 - 非 Windows 平台尚未实现 WinHTTP 路径的替代后端(计划引入 `libcurl`/`Boost.Beast` 做跨平台 WS/HTTP+SSE) - CMake `install/export` 打包配置后续完善,便于 `find_package(mcp)` 集成 - 脚本默认仅在 Windows 下测试;可按需补充跨平台 Shell 脚本