c++開發大模型mcp服務(六)cpp-mcp庫說明
模型上下文協議 (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 客戶端的抽象接口,所有具體的客戶端實現都從該接口繼承。
使用 HTTP 和服務器發送事件 (SSE) 與 MCP 服務器通信的客戶端實現。
客戶端實現使用標準輸入/輸出與 MCP 服務器通信,能夠啟動子進程并與其通信。
處理 JSON-RPC 消息的序列化和反序列化。
管理和調用 MCP 工具。
管理 MCP 資源。
實現 MCP 服務器功能。
使用自定義工具的 MCP 服務器實現示例:
- 時間工具:獲取當前時間
- 計算器工具:執行數學運算
- 回顯工具:回顯輸入并可選擇轉換(轉換為大寫、反轉)
- 問候工具:返回
Hello,+輸入名稱+!,默認為Hello, World!
MCP 客戶端連接到服務器的示例:
- 獲取服務器信息
- 列出可用的工具
- 調用帶參數的工具
- 訪問資源
演示如何使用 stdio 客戶端與本地服務器通信:
- 啟動本地服務器進程
- 訪問文件系統資源
- 調用服務器工具
| 選項 | 描述 |
|---|---|
--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 編譯。
// 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
// 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);
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} });
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"} });

浙公網安備 33010602011771號