cpp-mcp/examples/stdio_client_example.cpp

91 lines
3.1 KiB
C++
Raw Normal View History

2025-03-13 21:46:49 +08:00
/**
* @file stdio_client_example.cpp
* @brief Example of using the MCP stdio client
*
* This example demonstrates how to use the MCP stdio client to connect to a server
* using standard input/output as the transport mechanism.
*/
#include "mcp_stdio_client.h"
#include "mcp_logger.h"
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
int main(int argc, char** argv) {
// 设置日志级别
mcp::set_log_level(mcp::log_level::info);
// 检查命令行参数
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <server_command>" << std::endl;
2025-03-13 23:57:46 +08:00
std::cerr << "Example: " << argv[0] << " \"npx -y @modelcontextprotocol/server-everything\"" << std::endl;
2025-03-13 21:46:49 +08:00
return 1;
}
std::string command = argv[1];
2025-03-13 23:57:46 +08:00
// 设置环境变量
mcp::json env_vars = {
{"MCP_DEBUG", "1"},
{"MCP_LOG_LEVEL", "debug"},
{"CUSTOM_VAR", "custom_value"}
};
// 创建客户端,直接在构造函数中传入环境变量
mcp::stdio_client client(command, env_vars);
2025-03-13 21:46:49 +08:00
// 初始化客户端
if (!client.initialize("MCP Stdio Client Example", "1.0.0")) {
std::cerr << "Failed to initialize client" << std::endl;
return 1;
}
std::cout << "Client initialized successfully" << std::endl;
try {
// 获取服务器能力
auto capabilities = client.get_server_capabilities();
std::cout << "Server capabilities: " << capabilities.dump(2) << std::endl;
// 列出可用工具
auto tools = client.get_tools();
std::cout << "Available tools: " << tools.size() << std::endl;
for (const auto& tool : tools) {
std::cout << " - " << tool.name << ": " << tool.description << std::endl;
}
// 列出可用资源
auto resources = client.list_resources();
std::cout << "Available resources: " << resources.dump(2) << std::endl;
// 如果有资源,读取第一个资源
if (resources.contains("resources") && resources["resources"].is_array() && !resources["resources"].empty()) {
auto resource = resources["resources"][0];
if (resource.contains("uri")) {
std::string uri = resource["uri"];
std::cout << "Reading resource: " << uri << std::endl;
auto content = client.read_resource(uri);
std::cout << "Resource content: " << content.dump(2) << std::endl;
}
}
// 保持连接一段时间
std::cout << "Keeping connection alive for 5 seconds..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
// 发送ping请求
bool ping_result = client.ping();
std::cout << "Ping result: " << (ping_result ? "success" : "failure") << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
std::cout << "Example completed successfully" << std::endl;
return 0;
}