### Build Server Example with CMake Source: https://github.com/hkr04/cpp-mcp/blob/main/examples/CMakeLists.txt Configures the build for the server example. Links against the 'mcp' library and includes project headers. Optionally links against OpenSSL if found. ```cmake set(TARGET server_example) add_executable(${TARGET} server_example.cpp) target_link_libraries(${TARGET} PRIVATE mcp) target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR}/include) if(OPENSSL_FOUND) target_link_libraries(${TARGET} PRIVATE ${OPENSSL_LIBRARIES}) endif() ``` -------------------------------- ### Initialization Request Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Example of an 'initialize' request message, including protocol version, client capabilities, and client information. ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": { "roots": { "listChanged": true }, "sampling": {} }, "clientInfo": { "name": "ExampleClient", "version": "1.0.0" } } } ``` -------------------------------- ### Setup C++ MCP HTTP Server Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Configure and start an MCP server. Register tools and resources to handle client requests. The server can run in blocking mode. ```cpp // Create and configure the server mcp::server::configuration srv_conf; srv_conf.host = "localhost"; srv_conf.port = 8888; mcp::server server(srv_conf); 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() : "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(""); server.register_resource("file://", file_resource); // Start the server server.start(true); // Blocking mode ``` -------------------------------- ### Initialization Response Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Example of an 'initialize' response message, detailing server capabilities and server information. ```json { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2024-11-05", "capabilities": { "logging": {}, "prompts": { "listChanged": true }, "resources": { "subscribe": true, "listChanged": true }, "tools": { "listChanged": true } }, "serverInfo": { "name": "ExampleServer", "version": "1.0.0" } } } ``` -------------------------------- ### Agent Example Usage Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Example command to run the agent application. Ensure you compile with `-DMCP_SSL=ON` if connecting to an HTTPS base URL. Replace placeholders with your specific LLM details. ```bash ./build/examples/agent_example --base-url --endpoint --api-key --model ``` -------------------------------- ### Build Standard IO Client Example with CMake Source: https://github.com/hkr04/cpp-mcp/blob/main/examples/CMakeLists.txt Configures the build for the standard IO client example. Links against the 'mcp' library and includes project headers. ```cmake set(TARGET stdio_client_example) add_executable(${TARGET} stdio_client_example.cpp) target_link_libraries(${TARGET} PRIVATE mcp) target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR}/include) ``` -------------------------------- ### Initialize and Start mcp::server Source: https://context7.com/hkr04/cpp-mcp/llms.txt Configures and starts the mcp::server for handling JSON-RPC 2.0 traffic. Supports custom method and notification registration. ```cpp #include "mcp_server.h" #include "mcp_tool.h" int main() { // Configure the server mcp::server::configuration conf; conf.host = "0.0.0.0"; conf.port = 8888; conf.max_sessions = 20; // 0 = unlimited conf.session_timeout = 60; // seconds; 0 = disabled conf.threadpool_size = 4; mcp::server server(conf); server.set_server_info("MyServer", "1.0.0"); server.set_instructions("Use the available tools to answer user questions."); // Declare capabilities exposed to clients mcp::json caps = {{"tools", mcp::json::object()}}; server.set_capabilities(caps); // Register a custom JSON-RPC method server.register_method("custom/echo", [](const mcp::json& params, const std::string& session_id) -> mcp::json { return {{"echoed", params}}; }); // Register a notification handler (fire-and-forget from the client) server.register_notification("notifications/progress", [](const mcp::json& params, const std::string& session_id) { std::cout << "Progress from " << session_id << ": " << params.dump() << '\n'; }); // Broadcast a server-initiated notification to all initialized sessions // (call after start in non-blocking mode) // auto notif = mcp::request::create_notification("resource_updated", {{"uri", "file://data.txt"}}); // server.broadcast_notification(notif); // Start blocking (returns only on Ctrl+C or stop()) server.start(true); } ``` -------------------------------- ### Build Agent Example with CMake Source: https://github.com/hkr04/cpp-mcp/blob/main/examples/CMakeLists.txt Configures the build for the agent example. Links against the 'mcp' library and includes project headers. Optionally links against OpenSSL if found. ```cmake set(TARGET agent_example) add_executable(${TARGET} agent_example.cpp) target_link_libraries(${TARGET} PRIVATE mcp) target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR}/include) if(OPENSSL_FOUND) target_link_libraries(${TARGET} PRIVATE ${OPENSSL_LIBRARIES}) endif() ``` -------------------------------- ### Build SSE Client Example with CMake Source: https://github.com/hkr04/cpp-mcp/blob/main/examples/CMakeLists.txt Configures the build for the SSE client example. Links against the 'mcp' library and includes project headers. Optionally links against OpenSSL if found. ```cmake cmake_minimum_required(VERSION 3.10) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set(TARGET sse_client_example) add_executable(${TARGET} sse_client_example.cpp) target_link_libraries(${TARGET} PRIVATE mcp) target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR}/include) if(OPENSSL_FOUND) target_link_libraries(${TARGET} PRIVATE ${OPENSSL_LIBRARIES}) endif() ``` -------------------------------- ### Progress Request Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Example of a request that includes a progress token for tracking asynchronous operations. ```json { "jsonrpc": "2.0", "id": 1, "method": "some_method", "params": { "_meta": { "progressToken": "abc123" } } } ``` -------------------------------- ### Initialization Response Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Example of an initialization response message from the server. ```APIDOC ## Initialization Response ### Description This is an example of an initialization response from the server, detailing its capabilities. ### Response Message ```json { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2024-11-05", "capabilities": { "logging": {}, "prompts": { "listChanged": true }, "resources": { "subscribe": true, "listChanged": true }, "tools": { "listChanged": true } }, "serverInfo": { "name": "ExampleServer", "version": "1.0.0" } } } ``` ``` -------------------------------- ### Tool Call Request Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Request to execute a specific tool with provided arguments. ```json { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "get_weather", "arguments": { "location": "New York" } } } ``` -------------------------------- ### Initialization Request Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Example of an initialization request message sent by a client to the server. ```APIDOC ## Initialization Request ### Description This is an example of an initialization request sent by a client to establish a connection with the server. ### Request Message ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": { "roots": { "listChanged": true }, "sampling": {} }, "clientInfo": { "name": "ExampleClient", "version": "1.0.0" } } } ``` ``` -------------------------------- ### Initialization Notification Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Example of an initialized notification sent after successful initialization. ```APIDOC ## Initialization Notification ### Description This is a notification sent by the server to indicate that initialization is complete. ### Notification Message ```json { "jsonrpc": "2.0", "method": "notifications/initialized" } ``` ``` -------------------------------- ### Tool List Request Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Request to retrieve a list of available tools, with an optional cursor for pagination. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": { "cursor": "optional-cursor-value" } } ``` -------------------------------- ### Resource List Request Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Request to retrieve a list of resources, with an optional cursor for pagination. ```json { "jsonrpc": "2.0", "id": 1, "method": "resources/list", "params": { "cursor": "optional-cursor-value" } } ``` -------------------------------- ### Ping Request Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md A simple 'ping' request to check server liveness. ```json { "jsonrpc": "2.0", "id": "123", "method": "ping" } ``` -------------------------------- ### Initialized Notification Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md A notification message indicating that the initialization process is complete. ```json { "jsonrpc": "2.0", "method": "notifications/initialized" } ``` -------------------------------- ### Initialization Error Response (Unsupported Version) Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Example of an error response when the client requests an unsupported protocol version. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32602, "message": "Unsupported protocol version", "data": { "supported": ["2024-11-05"], "requested": "1.0.0" } } } ``` -------------------------------- ### Tool List Response Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Response containing a list of tools, including their names, descriptions, and input schemas, along with a cursor for the next page. ```json { "jsonrpc": "2.0", "id": 1, "result": { "tools": [ { "name": "get_weather", "description": "Get current weather information for a location", "inputSchema": { "type": "object", "properties": { "location": { "type": "string", "description": "City name or zip code" } }, "required": ["location"] } } ], "nextCursor": "next-page-cursor" } } ``` -------------------------------- ### Initialization Error (Unsupported Version) Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Example of an error response when the client requests an unsupported protocol version. ```APIDOC ## Initialization Error (Unsupported Version) ### Description This example shows an error response when the client's requested protocol version is not supported by the server. ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32602, "message": "Unsupported protocol version", "data": { "supported": ["2024-11-05"], "requested": "1.0.0" } } } ``` ``` -------------------------------- ### Resource List Response Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Response containing a list of resources, including their URIs, names, descriptions, and MIME types, along with a cursor for the next page. ```json { "jsonrpc": "2.0", "id": 1, "result": { "resources": [ { "uri": "file:///project/src/main.rs", "name": "main.rs", "description": "Primary application entry point", "mimeType": "text/x-rust" } ], "nextCursor": "next-page-cursor" } } ``` -------------------------------- ### Ping Response Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md The expected response to a 'ping' request, indicating the server is responsive. ```json { "jsonrpc": "2.0", "id": "123", "result": {} } ``` -------------------------------- ### Resource Read Request Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Request to read the contents of a specific resource identified by its URI. ```json { "jsonrpc": "2.0", "id": 2, "method": "resources/read", "params": { "uri": "file:///project/src/main.rs" } } ``` -------------------------------- ### Error Response Resource Not Found Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md This is an example of an error response when a requested resource is not found. ```json { "jsonrpc": "2.0", "id": 5, "error": { "code": -32002, "message": "Resource not found", "data": { "uri": "file:///nonexistent.txt" } } } ``` -------------------------------- ### Resource Error (Not Found) Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md An example of an error response when a requested resource is not found. ```APIDOC ## Resource Error (Not Found) ### Description An example of an error response indicating that a requested resource could not be found. ### Method POST ### Endpoint / ### Parameters #### Request Body - **jsonrpc** (string) - Required - JSON-RPC protocol version. - **id** (integer) - Required - Unique identifier for the request that caused the error. - **error** (object) - Required - Contains error information. - **code** (integer) - Required - The error code. - **message** (string) - Required - A short description of the error. - **data** (object) - Optional - Additional error data. - **uri** (string) - The URI of the resource that was not found. ### Request Example (This is an error response, not a request. The request that led to this error would be a resource-related call.) ### Response Example ```json { "jsonrpc": "2.0", "id": 5, "error": { "code": -32002, "message": "Resource not found", "data": { "uri": "file:///nonexistent.txt" } } } ``` ``` -------------------------------- ### Tool Call Response Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Response from a tool call, containing the tool's output content or an error indication. ```json { "jsonrpc": "2.0", "id": 2, "result": { "content": [ { "type": "text", "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy" } ], "isError": false } } ``` -------------------------------- ### Interact with mcp::stdio_client Source: https://context7.com/hkr04/cpp-mcp/llms.txt Shows how to use the unified client API with a stdio client to get server capabilities, tools, resources, and call tools. ```cpp // Use the same unified client API auto caps = client.get_server_capabilities(); auto tools = client.get_tools(); auto res = client.list_resources(); if (!res["resources"].empty()) { std::string uri = res["resources"][0]["uri"].get(); auto content = client.read_resource(uri); std::cout << content.dump(2) << '\n'; } try { auto result = client.call_tool("read_file", {{"path", "/path/to/serve/readme.txt"}}); std::cout << result["content"][0]["text"].get() << '\n'; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << '\n'; } bool alive = client.ping(); bool running = client.is_running(); ``` -------------------------------- ### Setup C++ MCP SSE Client with TLS Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Instantiate an SSE client to connect to an HTTPS server using the 'https' protocol. ```cpp mcp::sse_client client("https://localhost:8888"); ``` -------------------------------- ### Resource Read Response Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Response containing the contents of a requested resource, including its URI, MIME type, and text content. ```json { "jsonrpc": "2.0", "id": 2, "result": { "contents": [ { "uri": "file:///project/src/main.rs", "mimeType": "text/x-rust", "text": "fn main() {\n println!(\"Hello world!\");\n}" } ] } } ``` -------------------------------- ### Progress Notification Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Notification providing updates on the progress of an operation, identified by a progress token. ```json { "jsonrpc": "2.0", "method": "notifications/progress", "params": { "progressToken": "abc123", "progress": 50, "total": 100 } } ``` -------------------------------- ### Tool List Changed Notification Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Notification indicating that the list of available tools has changed. ```json { "jsonrpc": "2.0", "method": "notifications/tools/list_changed" } ``` -------------------------------- ### Request Resource Template List Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Send this JSON-RPC request to get a list of available resource templates. ```json { "jsonrpc": "2.0", "id": 3, "method": "resources/templates/list" } ``` -------------------------------- ### mcp::server - HTTP/SSE Server Source: https://context7.com/hkr04/cpp-mcp/llms.txt This section demonstrates how to set up and configure the `mcp::server` class to handle JSON-RPC 2.0 traffic. It includes examples of setting server information, capabilities, registering custom methods, and handling notifications. ```APIDOC ## mcp::server - HTTP/SSE Server The `mcp::server` class starts an HTTP server that handles JSON-RPC 2.0 traffic via two transports: the legacy 2024-11-05 HTTP+SSE transport (`/sse` + `/message`) and the 2025-03-26 Streamable HTTP transport (`/mcp`). It manages sessions, dispatches tool and method calls to registered handlers using a thread pool, and optionally enforces session limits and timeouts. ### Usage Example ```cpp #include "mcp_server.h" #include "mcp_tool.h" int main() { // Configure the server mcp::server::configuration conf; conf.host = "0.0.0.0"; conf.port = 8888; conf.max_sessions = 20; // 0 = unlimited conf.session_timeout = 60; // seconds; 0 = disabled conf.threadpool_size = 4; mcp::server server(conf); server.set_server_info("MyServer", "1.0.0"); server.set_instructions("Use the available tools to answer user questions."); // Declare capabilities exposed to clients mcp::json caps = {{"tools", mcp::json::object()}}; server.set_capabilities(caps); // Register a custom JSON-RPC method server.register_method("custom/echo", [](const mcp::json& params, const std::string& session_id) -> mcp::json { return {{"echoed", params}}; }); // Register a notification handler (fire-and-forget from the client) server.register_notification("notifications/progress", [](const mcp::json& params, const std::string& session_id) { std::cout << "Progress from " << session_id << ": " << params.dump() << '\n'; }); // Broadcast a server-initiated notification to all initialized sessions // (call after start in non-blocking mode) // auto notif = mcp::request::create_notification("resource_updated", {{"uri", "file://data.txt"}}); // server.broadcast_notification(notif); // Start blocking (returns only on Ctrl+C or stop()) server.start(true); } ``` ### Methods - **`set_server_info(const std::string& name, const std::string& version)`**: Sets the server's name and version, which is returned in the initialize response. - **`set_instructions(const std::string& instructions)`**: Sets instructions for clients, describing the server's purpose. - **`set_capabilities(const mcp::json& capabilities)`**: Declares the capabilities exposed to clients, typically including available tools. - **`register_method(const std::string& method_name, std::function handler)`**: Registers a custom JSON-RPC method handler. The handler receives parameters and the session ID, and must return a JSON response. - **`register_notification(const std::string& notification_name, std::function handler)`**: Registers a handler for incoming notifications. The handler receives notification parameters and the session ID. - **`broadcast_notification(const mcp::request& notification)`**: Sends a server-initiated notification to all active sessions. (Note: This is commented out in the example and should be called after `start()` in non-blocking mode). - **`start(bool blocking = false)`**: Starts the server. If `blocking` is true, the function returns only when the server is stopped (e.g., via Ctrl+C). ``` -------------------------------- ### Setup C++ MCP HTTPs Server Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Configure an MCP server to use TLS by specifying paths to the server certificate and private key. ```cpp mcp::server::configuration srv_conf; srv_conf.host = "localhost"; srv_conf.port = 8888; srv_conf.ssl.server_cert_path = "./server.cert.pem"; srv_conf.ssl.server_private_key_path = "./server.key.pem"; ``` -------------------------------- ### Set Authentication Handler Source: https://context7.com/hkr04/cpp-mcp/llms.txt Installs a callback to handle request authentication. The handler receives the `Authorization` header and session ID, returning `true` to allow or `false` to reject requests. Ensure the expected token is correctly formatted. ```cpp server.set_auth_handler([](const std::string& auth_header, const std::string& session_id) -> bool { // auth_header is the full header value, e.g. "Bearer my-secret-token" const std::string expected = "Bearer my-secret-token"; return auth_header == expected; }); ``` -------------------------------- ### server::set_auth_handler Source: https://context7.com/hkr04/cpp-mcp/llms.txt Installs a custom authentication handler. This callback is invoked for incoming requests to validate the client's credentials. ```APIDOC ## server::set_auth_handler ### Description Installs an authentication callback that receives the HTTP `Authorization` header value and the session ID. Return `true` to allow, `false` to reject. ### Method Signature ```cpp server.set_auth_handler(std::function auth_callback); ``` ### Parameters - `auth_callback` (std::function): A callback function that takes the `Authorization` header string and the session ID. It should return `true` if authentication is successful, and `false` otherwise. ### Example Usage ```cpp server.set_auth_handler([](const std::string& auth_header, const std::string& session_id) -> bool { // auth_header is the full header value, e.g. "Bearer my-secret-token" const std::string expected = "Bearer my-secret-token"; return auth_header == expected; }); ``` ``` -------------------------------- ### Server-Initiated Messages (Request/Notification) Source: https://context7.com/hkr04/cpp-mcp/llms.txt Enables sending JSON-RPC requests or notifications from the server to connected clients. The server must be started in non-blocking mode. Use `send_request` for targeted messages and `broadcast_notification` for all clients. ```cpp // Start server in non-blocking mode server.start(false); // Send a targeted request to one session std::string target_session = server.get_active_sessions().front(); auto ping = mcp::request::create("ping", {}); server.send_request(target_session, ping); // Broadcast a notification to ALL initialized sessions auto notif = mcp::request::create_notification("resource_updated", {{"uri", "file://data.txt"}, {"reason", "file changed"}}); server.broadcast_notification(notif); // List active sessions for (const auto& sid : server.get_active_sessions()) { std::cout << "Active session: " << sid << '\n'; } ``` -------------------------------- ### Initialize and Configure mcp::stdio_client Source: https://context7.com/hkr04/cpp-mcp/llms.txt Demonstrates launching an MCP server as a child process via stdio, passing environment variables, and initializing the client. ```cpp #include "mcp_stdio_client.h" // Pass environment variables to the child process mcp::json env = { {"MCP_LOG_LEVEL", "debug"}, {"HOME", "/home/user"} }; // Launch the server-filesystem MCP server mcp::stdio_client client( "npx -y @modelcontextprotocol/server-filesystem /path/to/serve", env); // Alternatively, set env vars before initialize // client.set_environment_variables(env); if (!client.initialize("MyApp", "1.0.0")) { std::cerr << "Failed to start subprocess\n"; return 1; } ``` -------------------------------- ### Initialize and Configure mcp::sse_client Source: https://context7.com/hkr04/cpp-mcp/llms.txt Demonstrates initializing an SSE client with plain HTTP or HTTPS, setting authentication tokens, custom headers, timeouts, and server capabilities. ```cpp #include "mcp_sse_client.h" // Plain HTTP mcp::sse_client client("http://localhost:8888"); // HTTPS with custom CA cert // mcp::sse_client client("https://myserver.example.com", "/sse", // /*validate_certificates=*/true, "./ca.cert.pem"); client.set_auth_token("Bearer my-secret-token"); client.set_header("X-Tenant-ID", "acme-corp"); client.set_timeout(15); // seconds mcp::json client_caps = {{"roots", {{"listChanged", true}}}; client.set_capabilities(client_caps); if (!client.initialize("MyClient", "1.0.0")) { std::cerr << "Initialization failed\n"; return 1; } ``` -------------------------------- ### Interact with mcp::sse_client Source: https://context7.com/hkr04/cpp-mcp/llms.txt Shows how to ping the server, inspect capabilities, list and call tools, and manage resources using the SSE client. ```cpp // Ping bool alive = client.ping(); // Inspect server capabilities mcp::json srv_caps = client.get_server_capabilities(); std::cout << srv_caps.dump(2) << '\n'; // List and call tools auto tools = client.get_tools(); for (const auto& t : tools) std::cout << t.name << ": " << t.description << '\n'; try { mcp::json result = client.call_tool("calculator", {{ {"operation", "multiply"}, {"a", 6.0}, {"b", 7.0} }}); std::cout << "6 * 7 = " << result["content"][0]["text"].get() << '\n'; // Output: 6 * 7 = 42.000000 } catch (const mcp::mcp_exception& e) { std::cerr << "MCP error " << static_cast(e.code()) << ": " << e.what() << '\n'; } // List and read resources mcp::json resources = client.list_resources(); if (!resources["resources"].empty()) { std::string uri = resources["resources"][0]["uri"]; mcp::json content = client.read_resource(uri); std::cout << content.dump(2) << '\n'; } // Subscribe to resource changes client.subscribe_to_resource("file://./data.txt"); // List resource templates mcp::json templates = client.list_resource_templates(); ``` -------------------------------- ### Build and Run an LLM Agent with MCP Server Source: https://context7.com/hkr04/cpp-mcp/llms.txt This C++ code demonstrates the complete pattern for building an AI agent loop. It embeds an MCP server for tool execution, connects an LLM via an OpenAI-compatible API, and routes tool calls through MCP. Ensure you have the necessary MCP headers and httplib included. ```cpp #include "mcp_server.h" #include "mcp_sse_client.h" #include "httplib.h" // 1. Create server and register tools mcp::server::configuration srv_conf; srv_conf.port = 8889; mcp::server server(srv_conf); server.set_server_info("AgentServer", "0.1.0"); server.set_capabilities({{"tools", mcp::json::object()}}); mcp::tool calc = mcp::tool_builder("calculator") .with_description("Perform basic calculations") .with_string_param("operation", "add | subtract | multiply | divide") .with_number_param("a", "First operand") .with_number_param("b", "Second operand") .build(); server.register_tool(calc, [](const mcp::json& p, const std::string&){ double a = p["a"], b = p["b"]; std::string op = p["operation"]; double r = (op=="add") ? a+b : (op=="subtract") ? a-b : (op=="multiply") ? a*b : a/b; return {{{"type","text"}, {"text", std::to_string(r)}}}; }); server.start(false); // non-blocking // 2. Connect MCP client mcp::sse_client mcp_client("http://localhost:8889"); mcp_client.set_timeout(10); mcp_client.initialize("Agent", "0.1.0"); // 3. Convert tools for the LLM's function-calling format mcp::json llm_tools = mcp::json::array(); for (const auto& t : mcp_client.get_tools()) { llm_tools.push_back({ {"type", "function"}, {"function", { {"name", t.name}, {"description", t.description}, {"parameters", { {"type","object"}, {"properties", t.parameters_schema["properties"]}, {"required", t.parameters_schema["required"]} }} }} }); } // 4. Agent loop: call LLM, execute tool calls via MCP, feed results back mcp::json messages = {{{"role","system"}, {"content","You are a helpful agent."}}}; messages.push_back({{"role","user"}, {"content","What is 123 * 456?"}}); // POST to LLM (OpenAI-compatible) httplib::Client llm("https://api.openai.com"); llm.set_default_headers({{"Authorization", "Bearer " + api_key}}); auto llm_resp = llm.Post("/v1/chat/completions", mcp::json{{"model","gpt-4"},{"messages",messages},{"tools",llm_tools}}.dump(), "application/json"); mcp::json msg = mcp::json::parse(llm_resp->body)["choices"][0]["message"]; for (const auto& call : msg["tool_calls"]) { mcp::json args = mcp::json::parse(call["function"]["arguments"].get()); mcp::json result = mcp_client.call_tool(call["function"]["name"], args); messages.push_back({ {"role","tool"}, {"tool_call_id", call["id"]}, {"content", result["content"]} }); } // Continue the loop until the LLM produces a final text response ``` -------------------------------- ### Create C++ MCP HTTP Client Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Connect to an MCP server using an SSE client and call a registered tool with parameters. Ensure the client is initialized before making calls. ```cpp // Connect to the server mcp::sse_client client("http://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); ``` -------------------------------- ### Build MCP with CMake Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Standard CMake commands to build the MCP framework. Use the `--config Release` flag for optimized builds. ```bash cmake -B build cmake --build build --config Release ``` -------------------------------- ### Build MCP with Tests using CMake Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Build the MCP framework with GoogleTest support. Ensure GoogleTest is initialized as a submodule before configuring CMake. ```bash git submodule update --init --recursive # Get GoogleTest cmake -B build -DMCP_BUILD_TESTS=ON cmake --build build --config Release ``` -------------------------------- ### Cancellation Notification Example Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Notification sent to cancel a previously requested operation, including the request ID and reason. ```json { "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": "123", "reason": "User requested cancellation" } } ``` -------------------------------- ### Response Resource Template List Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md This is a sample response containing resource template information. ```json { "jsonrpc": "2.0", "id": 3, "result": { "resourceTemplates": [ { "uriTemplate": "file:///{path}", "name": "Project Files", "description": "Access files in the project directory", "mimeType": "application/octet-stream" } ] } } ``` -------------------------------- ### Build MCP Protocol Framework with CMake Source: https://context7.com/hkr04/cpp-mcp/llms.txt Standard build commands for the MCP Protocol Framework using CMake. Includes options for building with tests and TLS/SSL support. ```bash cmake -B build cmake --build build --config Release ``` ```bash # Build with tests (requires GoogleTest submodule) git submodule update --init --recursive cmake -B build -DMCP_BUILD_TESTS=ON cmake --build build --config Release ctest --test-dir build ``` ```bash # Build with TLS/SSL support cmake -B build -DMCP_SSL=ON cmake --build build --config Release ``` -------------------------------- ### Build MCP with SSL Support using CMake Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Build the MCP framework with SSL support enabled. This is necessary for connecting to HTTPS endpoints. Ensure GoogleTest is initialized as a submodule. ```bash git submodule update --init --recursive # Get GoogleTest cmake -B build -DMCP_SSL=ON cmake --build build --config Release ``` -------------------------------- ### Transport-Agnostic Client Functions Source: https://context7.com/hkr04/cpp-mcp/llms.txt Illustrates writing helper functions that work with the abstract `mcp::client` interface, allowing for transport-agnostic code and easy mocking. ```cpp #include "mcp_client.h" // Write transport-agnostic helper functions void run_demo(mcp::client& client) { client.initialize("Demo", "1.0.0"); client.ping(); auto caps = client.get_server_capabilities(); auto tools = client.get_tools(); for (const auto& t : tools) std::cout << "Tool: " << t.name << '\n'; // Send a raw JSON-RPC request mcp::response resp = client.send_request("tools/list", {}); if (!resp.is_error()) std::cout << resp.result.dump(2) << '\n'; // Send a notification (no response expected) client.send_notification("notifications/initialized", {}); auto resources = client.list_resources(); auto templates = client.list_resource_templates(); auto content = client.read_resource("file:///path/to/file.txt"); auto sub = client.subscribe_to_resource("file:///path/to/file.txt"); } // Works with any transport mcp::sse_client http_client("http://localhost:8888"); mcp::stdio_client proc_client("npx -y @modelcontextprotocol/server-everything"); run_demo(http_client); run_demo(proc_client); ``` -------------------------------- ### Configure C++ MCP SSE Client with TLS Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Initialize an SSE client to connect to an HTTPS server. Supports setting authentication tokens and custom headers. Ensure initialization is successful before proceeding. ```cpp #include "mcp_sse_client.h" // Create a client, specifying the server address and port 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} }); ``` -------------------------------- ### Expose Resources with server::register_resource Source: https://context7.com/hkr04/cpp-mcp/llms.txt Mount mcp::resource implementations at URIs to make them accessible to clients. Supports file, in-memory text, and binary resources. ```cpp #include "mcp_resource.h" // Expose a file from disk (MIME type auto-detected from extension) auto readme = std::make_shared("./README.md"); server.register_resource("file://./README.md", readme); // Expose a dynamic in-memory text resource auto status_res = std::make_shared( "status://current", "Server Status", "text/plain", "Live server status"); status_res->set_text("All systems operational"); server.register_resource("status://current", status_res); // Expose a binary resource (e.g. an image) auto img = std::make_shared( "img://logo", "Logo", "image/png", "Company logo"); std::vector png_bytes = load_png("logo.png"); // your loader img->set_data(png_bytes.data(), png_bytes.size()); server.register_resource("img://logo", img); ``` -------------------------------- ### Generate Test Certificates for TLS Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Commands to generate CA and server certificates for testing TLS connections on Linux using OpenSSL. ```bash openssl genrsa -out ca.key.pem 2048 ``` ```bash openssl req -x509 -new -nodes -key ca.key.pem -sha256 -days 1 -out ca.cert.pem -subj "/CN=Test CA" ``` ```bash openssl genrsa -out server.key.pem 2048 ``` ```bash openssl req -new -key server.key.pem -out server.csr.pem -subj "/O=TestServer/OU=Dev/CN=localhost" ``` ```bash openssl x509 -req -in server.csr.pem -CA ca.cert.pem -CAkey ca.key.pem -CAcreateserial -out server.cert.pem -days 1 -sha256 ``` -------------------------------- ### mcp::stdio_client Source: https://context7.com/hkr04/cpp-mcp/llms.txt Spawns an MCP server as a child process and communicates with it over stdin/stdout pipes. This is the standard way to integrate npm-published MCP servers. ```APIDOC ## `mcp::stdio_client` — Subprocess/Stdio Client Spawns an MCP server as a child process and communicates with it over stdin/stdout pipes. This is the standard way to integrate npm-published MCP servers (e.g., `@modelcontextprotocol/server-filesystem`). ```cpp #include "mcp_stdio_client.h" // Pass environment variables to the child process mcp::json env = { {"MCP_LOG_LEVEL", "debug"}, {"HOME", "/home/user"} }; // Launch the server-filesystem MCP server mcp::stdio_client client( "npx -y @modelcontextprotocol/server-filesystem /path/to/serve", env); // Alternatively, set env vars before initialize // client.set_environment_variables(env); if (!client.initialize("MyApp", "1.0.0")) { std::cerr << "Failed to start subprocess\n"; return 1; } // Use the same unified client API auto caps = client.get_server_capabilities(); auto tools = client.get_tools(); auto res = client.list_resources(); if (!res["resources"].empty()) { std::string uri = res["resources"][0]["uri"].get(); auto content = client.read_resource(uri); std::cout << content.dump(2) << '\n'; } try { auto result = client.call_tool("read_file", {{"path", "/path/to/serve/readme.txt"}}); std::cout << result["content"][0]["text"].get() << '\n'; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << '\n'; } bool alive = client.ping(); bool running = client.is_running(); ``` ``` -------------------------------- ### Configure mcp::server::configuration Source: https://context7.com/hkr04/cpp-mcp/llms.txt Defines server configuration parameters including host, port, endpoints, and thread pool size. Supports optional SSL configuration. ```cpp mcp::server::configuration conf; conf.host = "localhost"; // bind address conf.port = 8080; conf.name = "MCP Server"; // returned in initialize response conf.version = "0.0.1"; conf.sse_endpoint = "/sse"; // legacy SSE subscribe endpoint conf.msg_endpoint = "/message"; // legacy JSON-RPC POST endpoint conf.mcp_endpoint = "/mcp"; // 2025-03-26 streamable HTTP endpoint conf.threadpool_size = std::thread::hardware_concurrency(); conf.max_sessions = 10; // compile-time default MCP_MAX_SESSIONS conf.session_timeout = 30; // compile-time default MCP_SESSION_TIMEOUT #ifdef MCP_SSL conf.ssl.server_cert_path = "./server.cert.pem"; conf.ssl.server_private_key_path = "./server.key.pem"; #endif mcp::server server(conf); ``` -------------------------------- ### Configure C++ MCP Stdio Client Source: https://github.com/hkr04/cpp-mcp/blob/main/README.md Initialize an Stdio client to communicate with MCP servers via stdio transport. Supports accessing resources and calling tools. Handle initialization failures. ```cpp #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"} }); ``` -------------------------------- ### Tool List Request Source: https://github.com/hkr04/cpp-mcp/blob/main/test/testcase.md Request to retrieve a list of available tools from the server. ```APIDOC ## Tool List Request ### Description This request retrieves a list of tools that the server can execute. It supports pagination via a cursor. ### Method POST ### Endpoint /tools/list ### Parameters #### Query Parameters - **cursor** (string) - Optional - A cursor for fetching the next page of results. ### Request Example ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": { "cursor": "optional-cursor-value" } } ``` ``` -------------------------------- ### mcp::client (Abstract Interface) Source: https://context7.com/hkr04/cpp-mcp/llms.txt The abstract client interface implemented by `sse_client` and `stdio_client`, enabling transport-agnostic code and easy mocking. ```APIDOC ## `mcp::client` — Abstract Client Interface All client classes (`sse_client`, `stdio_client`) implement this interface, enabling transport-agnostic code and easy mocking. ```cpp #include "mcp_client.h" // Write transport-agnostic helper functions void run_demo(mcp::client& client) { client.initialize("Demo", "1.0.0"); client.ping(); auto caps = client.get_server_capabilities(); auto tools = client.get_tools(); for (const auto& t : tools) std::cout << "Tool: " << t.name << '\n'; // Send a raw JSON-RPC request mcp::response resp = client.send_request("tools/list", {}); if (!resp.is_error()) std::cout << resp.result.dump(2) << '\n'; // Send a notification (no response expected) client.send_notification("notifications/initialized", {}); auto resources = client.list_resources(); auto templates = client.list_resource_templates(); auto content = client.read_resource("file:///path/to/file.txt"); auto sub = client.subscribe_to_resource("file:///path/to/file.txt"); } // Works with any transport mcp::sse_client http_client("http://localhost:8888"); mcp::stdio_client proc_client("npx -y @modelcontextprotocol/server-everything"); run_demo(http_client); run_demo(proc_client); ``` ```