From 76ac796464947fd0800c83f9b8b924a4d73c5b10 Mon Sep 17 00:00:00 2001 From: hkr04 Date: Sun, 9 Mar 2025 17:24:46 +0800 Subject: [PATCH] add ping --- include/mcp_client.h | 6 ++++++ src/mcp_client.cpp | 20 ++++++++++++++++++++ src/mcp_server.cpp | 3 +++ test/test_mcp_client.cpp | 10 +++++++++- 4 files changed, 38 insertions(+), 1 deletion(-) diff --git a/include/mcp_client.h b/include/mcp_client.h index 0266c91..48dbf7d 100644 --- a/include/mcp_client.h +++ b/include/mcp_client.h @@ -52,6 +52,12 @@ public: * @return True if initialization was successful */ bool initialize(const std::string& client_name, const std::string& client_version); + + /** + * @brief Ping request + * @return True if the server is alive + */ + bool ping(); /** * @brief Set authentication token diff --git a/src/mcp_client.cpp b/src/mcp_client.cpp index 9049cdc..52b99c0 100644 --- a/src/mcp_client.cpp +++ b/src/mcp_client.cpp @@ -60,6 +60,26 @@ bool client::initialize(const std::string& client_name, const std::string& clien } } +bool client::ping() { + // Create ping request + request req = request::create("ping", {}); + + try { + // Send the request + json result = send_jsonrpc(req); + + // The receiver MUST respond promptly with an empty response + if (result.empty()) { + return true; + } else { + return false; + } + } catch (const std::exception& e) { + // Ping failed + return false; + } +} + void client::set_auth_token(const std::string& token) { std::lock_guard lock(mutex_); auth_token_ = token; diff --git a/src/mcp_server.cpp b/src/mcp_server.cpp index 0e781c2..046cc70 100644 --- a/src/mcp_server.cpp +++ b/src/mcp_server.cpp @@ -287,6 +287,9 @@ json server::process_request(const request& req) { // Special case for initialize if (req.method == "initialize") { return handle_initialize(req); + } else if (req.method == "ping") { + // The receiver MUST respond promptly with an empty response + return response::create_success(req.id, {}).to_json(); } // Look for registered method handler diff --git a/test/test_mcp_client.cpp b/test/test_mcp_client.cpp index cbc6256..612b277 100644 --- a/test/test_mcp_client.cpp +++ b/test/test_mcp_client.cpp @@ -239,4 +239,12 @@ TEST_F(ClientTest, CancellationTest) { EXPECT_EQ(result["content"][0]["type"], "text"); EXPECT_EQ(result["content"][0]["text"], "This call should be cancelled"); -} \ No newline at end of file +} + +TEST_F(ClientTest, PingTest) { + // Initialize client + client->initialize("TestClient", mcp::MCP_VERSION); + + // Send ping + EXPECT_TRUE(client->ping()); +} \ No newline at end of file