🚀 mcp-sample-cpp-servers
這是一個用C++實現的MCP Servers示例項目,完整複製自MCP Servers入門文章中的C++實現。目前僅驗證了標準輸入輸出的功能,由於目的是演示協議的使用,因此僅實現了對函數調用的支持。計劃在博客上創建代碼發佈頁面後刪除此倉庫(n個月後)。
🚀 快速開始
前提條件
確保已安裝C++編譯器(如gcc或MSVC)以及必要的開發庫。
構建項目
將項目添加到IDE中並構建。
啟動服務器
編譯生成可執行文件後,在終端運行即可啟動MCP服務器。
✨ 主要特性
- 初始化MCP服務器並設置協議版本和服務器信息。
- 註冊一個名為
evaluate-scores
的工具,用於評估一組分數。
- 實現了對
evaluate-scores
工具的調用處理邏輯,計算總分和平均分。
- 針對Windows環境進行了二進制模式設置,以解決文件操作問題。
📦 安裝指南
- 確保已安裝C++編譯器(如gcc或MSVC)以及必要的開發庫。
- 將項目添加到IDE中並構建。
- 編譯生成可執行文件後,在終端運行即可啟動MCP服務器。
💻 使用示例
基礎用法
curl -X POST http://localhost:5000/tools/list
curl -X POST http://localhost:5000/tools/call \
-H "Content-Type: application/json" \
-d '{"tool":"evaluate-scores","params":{"scores":[1,2,3,4,5]}}'
輸出說明
- 工具列表請求返回已註冊的工具信息。
- 評估分數調用返回總分和平均分。
📚 詳細文檔
main.cpp內容
#include <iostream>
#include <fstream>
#include <chrono>
#include <unordered_map>
#include "mcp-server.hpp"
#if defined(_MSC_VER)
#include <fcntl.h>
#include <io.h>
#endif
auto getTimeString() {
const std::chrono::time_zone* tz = std::chrono::current_zone();
return std::format("[{:%Y-%m-%d %H:%M:%S}]", tz->to_local(std::chrono::system_clock::now()));
}
int main() {
#if defined(_MSC_VER)
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
#endif
mcp::MCPServer server;
server.request.onInitialize = [&](const mcp::InitializeRequest& params) {
std::cerr << getTimeString() << "initialize" << std::endl;
return mcp::InitializeResult{
.protocolVersion = params.protocolVersion,
.capabilities = {
.tools = mcp::ServerCapabilities::ToolsInner{}
},
.serverInfo = {
.name = "ABC遊戲",
.version = "1.0.0"
}
};
};
server.notification.onInitialized = [&]() {
std::cerr << getTimeString() << "notifications/initialized" << std::endl;
};
server.request.tools.onList = [&]() {
std::cerr << getTimeString() << "tools/list" << std::endl;
return mcp::ListToolsResult{
.tools = {
{
.name = "evaluate-scores",
.description = "ABC遊戲的分數評估",
.inputSchema = nlohmann::json::object({
{"type", "object"},
{"properties", {
{"score", {
{"type", "number"},
{"minimum", 0},
{"description", "得分(點)"}
}}
}},
{"required", ["score"]}
})
}
}
};
};
server.request.tools.onCall = [&](const std::string& toolName, const nlohmann::json& input) {
std::cerr << getTimeString() << "tools/call " << toolName << " " << input.dump(4) << std::endl;
if (toolName == "evaluate-scores") {
if (!input["scores"].is_array()) {
throw nlohmann::json::invalid_argument("Expected 'scores' to be an array");
}
size_t scoreCount = input["scores"].size();
double total = 0.0;
for (const auto& score : input["scores"]) {
if (!score.is_number()) {
throw nlohmann::json::invalid_argument("Each score must be a number");
}
total += score.get<double>();
}
return nlohmann::json{
{"total", static_cast<int64_t>(total)},
{"average", total / scoreCount}
};
}
throw nlohmann::json::invalid_argument("Unknown tool: " + toolName);
};
std::cerr << getTimeString() << "啟動 MCP Server" << std::endl;
server.start();
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
代碼說明
- 代碼結構:這是一個MCP服務器的完整實現,展示瞭如何初始化、註冊工具以及處理工具調用。
- 主要功能:
- 初始化MCP服務器並設置協議版本和服務器信息。
- 註冊一個名為
evaluate-scores
的工具,用於評估一組分數。
- 實現了對
evaluate-scores
工具的調用處理邏輯,計算總分和平均分。
- 平臺特定代碼:針對Windows環境進行了二進制模式設置,以解決文件操作問題。