Leveraging Gemini CLI and the underlying Gemini LLM to build Model Context Protocol (MCP) AI applications in C++ with a local development environment.
Why not just use Python?
Python has traditionally been the main coding language for ML and AI tools. One of the strengths of the MCP protocol is that the actual implementation details are independent of the development language. The reality is that not every project is coded in Python- and MCP allows you to use the latest AI approaches with other coding languages.
C++? Doesn’t that leak Memory and Crash?
The goal of this article is to provide a minimal viable basic working MCP stdio server in C++ that can be run locally without any unneeded extra code or extensions.
There are a few options for C++ MCP libraries. The C++ MCP library used for the demo is here:
GitHub - hkr04/cpp-mcp: Lightweight C++ MCP (Model Context Protocol) SDK
What Is C++?
C++ is a powerful, high-performance, general-purpose programming language that supports multiple programming paradigms, including object-oriented , procedural , and generic programming. Developed by Bjarne Stroustrup in the early 1980s as an extension of the C language (initially called “C with Classes”), C++ gives developers a high level of control over system resources and memory.
There are several C++ sites but this page is a good starter:
Installing C++
The step by step instructions vary by platform- for a basic Debian system here are the steps:
sudo apt update
sudo apt install build-essential
g++ --version
xbill@penguin:~$ g++ --version
g++ (Debian 12.2.0-14+deb12u1) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
xbill@penguin:~$
Gemini CLI
If not pre-installed you can download the Gemini CLI to interact with the source files and provide real-time assistance:
npm install -g @google/gemini-cli
Testing the Gemini CLI Environment
Once you have all the tools and the correct Node.js version in place- you can test the startup of Gemini CLI. You will need to authenticate with a Key or your Google Account:
gemini
Node Version Management
Gemini CLI needs a consistent, up to date version of Node. The nvm command can be used to get a standard Node environment:
C++ MCP Documentation
The MCP C++ page provides samples and documentation for getting started:
cpp-mcp/examples/server_example.cpp at main · hkr04/cpp-mcp
Where do I start?
The strategy for starting MCP development is a incremental step by step approach.
First, the basic development environment is setup with the required system variables, and a working Gemini CLI configuration.
Then, a minimal Hello World Style C++ MCP Server is built with stdio transport. This server is validated with Gemini CLI in the local environment.
This setup validates the connection from Gemini CLI to the local process via MCP. The MCP client (Gemini CLI) and the MCP server both run in the same local environment.
Next- the basic MCP server is extended with Gemini CLI to add several new tools in standard code.
Setup the Basic Environment
At this point you should have a working C environment and a working Gemini CLI installation. The next step is to clone the GitHub samples repository with support scripts:
cd ~
git clone https://github.com/xbill9/gemini-cli-codeassist
Then run init.sh from the cloned directory.
The script will attempt to determine your shell environment and set the correct variables:
cd gemini-cli-codeassist
source init.sh
If your session times out or you need to re-authenticate- you can run the set_env.sh script to reset your environment variables:
cd gemini-cli-codeassist
source set_env.sh
Variables like PROJECT_ID need to be setup for use in the various build scripts- so the set_env script can be used to reset the environment if you time-out.
Hello World with STDIO Transport
One of the key features that the standard MCP libraries provide is abstracting various transport methods.
The high level MCP tool implementation is the same no matter what low level transport channel/method that the MCP Client uses to connect to a MCP Server.
The simplest transport that the SDK supports is the stdio (stdio/stdout) transport — which connects a locally running process. Both the MCP client and MCP Server must be running in the same environment.
The connection over stdio will look similar to this:
// Ensure stdout is unbuffered
std::setvbuf(stdout, nullptr, _IONBF, 0);
StdioServer server("mcp-stdio-cplus", "1.0.0");
C++ Package Information
The code depends on several standard C libraries for MCP and logging:
#include <chrono>
#include <ctime>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
#include "json.hpp"
#include "mcp_message.h"
#include "mcp_tool.h"
Installing and Running the C++ Code
Run the install make release target on the local system:
xbill@penguin:~/gemini-cli-codeassist/mcp-stdio-cplus$ make
c++ -std=c++17 -Wall -Wextra -Icpp-mcp/include -Icpp-mcp/common -O2 -c main.cpp
c++ -o server main.o cpp-mcp/build/src/libmcp.a -lpthread
xbill@penguin:~/gemini-cli-codeassist/mcp-stdio-cplus$
To lint the code:
xbill@penguin:~/gemini-cli-codeassist/mcp-stdio-cplus$ make lint
clang-format --dry-run --Werror main.cpp
To test the code:
xbill@penguin:~/gemini-cli-codeassist/mcp-stdio-cplus$ make test
c++ -std=c++17 -Wall -Wextra -Icpp-mcp/include -Icpp-mcp/common -O2 -c main.cpp
c++ -o server main.o cpp-mcp/build/src/libmcp.a -lpthread
python3 test_server.py
Testing 'greet' tool...
✓ initialize successful
✓ notifications/initialized sent
✓ tools/list successful
✓ tools/call (greet) successful
All tests passed!
Gemini CLI settings.json
In this example — the C source code uses a compiled binary that can be called directly from Gemini CLI.
The default Gemini CLI settings.json has an entry for the source:
{
"mcpServers": {
"mcp-stdio-cplus": {
"command": "$HOME/gemini-cli-codeassist/mcp-stdio-cplus/server"
}
}
}
Validation with Gemini CLI
Finally- Gemini CLI is restarted and the MCP connection over stdio to the C Code is validated, The full Gemini CLI Session will start:
> /mcp list
Configured MCP servers:
🟢 mcp-stdio-cplus - Ready (1 tool)
Tools:
- greet
> greet Keith!
✦ I will call the greet tool with the parameter "Keith!".
╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓ greet (mcp-stdio-cplus MCP Server) {"param":"Keith!"} │
│ │
│ Keith! │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ OK. I've greeted Keith! Let me know if there's anything else I can help you with.
Extending the MCP Server with Gemini CLI
Now that the basic MCP functionality has been tested and verified with Gemini CLI- the C server code can be extended with new MCP tools:
> with the C++ project add new MCP tools -
one that gets detailled C++ system information,
one that gets server information
and one that gets the current time
Gemini CLI will get right to work:
│ 225 + server.register_tool( │
│ 226 + mcp::tool_builder("get_system_info") │
│ 227 + .with_description("Get detailed C++ system information.") │
│ 228 + .build(), │
│ 229 + [](const json & /* args */, const std::string & /* session_id */) -> json { │
│ 230 + log_json("INFO", "Executed get_system_info tool"); │
│ 231 + std::ostringstream oss; │
│ 232 + oss << "C++ Standard: " << __cplusplus << "\n"; │
│ 233 + #ifdef __VERSION__ │
│ 234 + oss << "Compiler Version: " << __VERSION__ << "\n"; │
│ 235 + #endif │
│ 236 + return json::array({{{"type", "text"}, {"text", oss.str()}}}); │
│ 237 + }); │
│ 238 + │ │ │
Once completed — the changes will be summarized:
✦ I have added the three new tools (get_system_info, get_server_info, get_current_time) to the C++ MCP server and verified them
with tests.
* get_system_info: Returns the C++ Standard version and Compiler version.
* get_server_info: Returns the server name and version.
* get_current_time: Returns the current time in UTC.
The project has been rebuilt and tested successfully.
Restart Gemini CLI and check for the new MCP tools:
xbill@penguin:~/gemini-cli-codeassist/mcp-stdio-cplus$ make
c++ -std=c++17 -Wall -Wextra -Icpp-mcp/include -Icpp-mcp/common -O2 -c main.cpp
c++ -o server main.o cpp-mcp/build/src/libmcp.a -lpthread
xbill@penguin:~/gemini-cli-codeassist/mcp-stdio-cplus$
And list the new MCP Tools:
> /mcp list
Configured MCP servers:
🟢 mcp-stdio-cplus - Ready (4 tools)
Tools:
- get_current_time
- get_server_info
- get_system_info
- greet
to run the tools:
> get_current_time
╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓ get_current_time (mcp-stdio-cplus MCP Server) {} │
│ │
│ 2026-01-14 22:51:11 UTC │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
and C++ information:
> get_system_info
╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓ get_system_info (mcp-stdio-cplus MCP Server) {} │
│ │
│ C++ Standard: 201703 │
│ Compiler Version: 12.2.0 │
│ │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ The system is currently using C++17 (standard version 201703) with GCC version 12.2.0.
and system information:
> get_server_info
╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓ get_server_info (mcp-stdio-cplus MCP Server) {} │
│ │
│ Server: mcp-stdio-cplus │
│ Version: 1.0.0 │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ The server is mcp-stdio-cplus version 1.0.0.
Use the MCP Tools in the Gemini CLI Context
The new MCP tools can be used within the LLM context in Gemini CLI:
> use get_system_info and highlight some of the C++ language
features in the codebase at that system level
✦ I will read main.cpp and cpp-mcp/include/mcp_server.h to identify usage of modern C++ features, particularly those introduced in
C++17.
╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓ ReadFile main.cpp │
│ │
│ │
│ ✓ ReadFile cpp-mcp/include/mcp_server.h │
│ │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ Based on the system information (C++17 / GCC 12.2.0) and my analysis of main.cpp and cpp-mcp/include/mcp_server.h, here are the
key C++ language features being utilized:
C++17 Specific Features
* Structured Bindings:
Used in main.cpp to iterate over the tools_ map cleanly, unpacking the key and value directly:
1 for (const auto &[name, entry] : tools_) { ... }
* `std::optional`:
Found in mcp_server.h to handle optional SSL configuration paths:
1 std::optional<std::string> server_cert_path{ std::nullopt };
* `std::string_view` (Implied):
While not explicitly used in the snippets read, the project is linked against C++17, making this efficient string handling
available and likely used within the nlohmann::json or httplib dependencies.
Modern C++ (C++11/14) Core Features
* Lambda Expressions:
Extensively used in main.cpp for defining tool handlers inline:
1 [](const json &args, const std::string & /* session_id */) -> json { ... }
* Smart Pointers:
The library header mcp_server.h uses std::unique_ptr for exclusive ownership (e.g., the HTTP server instance) and
std::shared_ptr for shared resources:
1 std::unique_ptr<httplib::Server> http_server_;
2 std::shared_ptr<resource> resource;
* Concurrency Primitives:
The library makes use of standard threading features like std::mutex, std::condition_variable, std::atomic, and std::future
for managing the server's event loop and thread pool.
* Move Semantics:
Used to efficiently transfer ownership of handlers:
1 tools_[tool.name] = {tool, std::move(handler)};
The codebase effectively leverages the modern C++ capabilities provided by your GCC 12.2.0 environment.
After all this- then what?
Let’s see what Gemini has to say in a code review:
Code Review: mcp-stdio-cplus
This C++ implementation of a Model Context Protocol (MCP) server is clean, idiomatic, and adheres to key protocol best practices.
Strengths:
* Correct Transport Separation: The most critical aspect of a stdio-based MCP server is ensuring protocol messages go to stdout while logs go
to stderr. Your log_json function correctly directs structured logs to std::cerr, preventing protocol corruption.
* Structured Logging: Using JSON for logs (timestamp, level, message, data) is excellent for observability and debugging, especially when the
server is running in the background as a subprocess.
* Clean Architecture: The StdioServer class nicely encapsulates the state (tools, initialization status) and logic. The separation of
handle_request, handle_notification, and handle_tool_call makes the main loop easy to follow.
* Robust JSON Handling: You are using nlohmann::json, the industry standard for C++ JSON parsing. Your manual validation of JSON-RPC versions
and existence checks for id and params adds necessary robustness.
* Unbuffered Output: The std::setvbuf(stdout, nullptr, _IONBF, 0); call in main() is a crucial detail often missed. It ensures that MCP
messages are flushed immediately to the client, preventing "hanging" interactions.
Potential Improvements (for the article or code):
* Error Handling in Tool Logic: While the handle_tool_call catches exceptions, the lambda for the greet tool doesn't explicitly check if
param exists or is valid before using it (though args.value handles the missing key safely). Adding explicit validation examples would be
valuable for readers.
* Concurrency: The current implementation processes requests synchronously in a single thread. For a "production" C++ server handling heavy
workloads, you might want to mention or implement a thread pool or async handling, though the single-threaded approach is perfectly fine
for this example.
Summary:
The code provides a solid foundation for C++ developers looking to build MCP tools. It effectively demonstrates how to wrap a C++ logic (the
greet function) into a compliant MCP server interface without overcomplicating the implementation.
Summary
The strategy for using C++ with MCP development with Gemini CLI was validated with an incremental step by step approach.
A minimal stdio transport MCP Server was started from C++ source code and validated with Gemini CLI running as a MCP client in the same local environment.
Gemini CLI was then used to extend the sample C++ code with several MCP tools and use these tools inside the context for the underlying LLM.


Top comments (0)