xpc123/mcp_server_cpp
If you are the rightful owner of mcp_server_cpp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
The MCP C++ Minimal Core Library is a lightweight, embeddable framework for creating JSON-RPC 2.0 servers with essential features like a request loop, tool registry, and thread pool.
MCP Server C++
A robust C++ implementation of the Model Context Protocol (MCP) server with StreamableHTTP transport. This server provides a comprehensive foundation for building MCP-compatible services with excellent performance and reliability.
๐ฏ Key Features
- โ Full MCP Protocol 2025-06-18 compliance with complete handshake support
- ๐ StreamableHTTP Transport for real-time bidirectional communication
- ๐ง 6 Built-in Sample Tools demonstrating diverse functionality patterns
- โก Thread-pool Architecture for high-performance concurrent execution
- ๐ JSON-RPC 2.0 with proper MCP protocol layering
- ๐ Official MCP SDK Integration - tested with Python SDK client
- ๐งช Comprehensive Test Suite with both demo and interactive modes
- ๐ฆ Zero External Dependencies - all libraries bundled
Current Version: 0.1.0
Protocol Version: 2025-06-18
Build Status: โ
Production Ready
๐๏ธ Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MCP Clients (Python SDK, Claude Desktop, etc.) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ ๐ก StreamableHTTP Transport (JSON-RPC 2.0) โ
โ โโ POST / (main MCP endpoint) โ
โ โโ POST /rpc (legacy compatibility) โ
โ โโ Session management & streaming responses โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ ๐ฏ MCP Protocol Layer (2025-06-18) โ
โ โโ initialize/initialized handshake โ
โ โโ tools/list & tools/call methods โ
โ โโ Proper error handling & validation โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ ๐ง mcp::McpServer (Core Engine) โ
โ โโ Tool registry with dynamic discovery โ
โ โโ Thread pool for concurrent execution โ
โ โโ Extensible plugin architecture โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ ๐ ๏ธ Built-in Tools (6 Sample Implementations) โ
โ โโ time, echo, upper, sum (utility tools) โ
โ โโ getWeather (mock API simulation) โ
โ โโ slow (progress simulation) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Core Components:
- Server Core:
mcp::McpServer
with tool registry and thread pool management - Transport Layer: StreamableHTTP on port 8080 (configurable) with session support
- Protocol Implementation: Full MCP 2025-06-18 over JSON-RPC 2.0 messaging
- Tool System: Extensible framework with 6 comprehensive sample tools
- Client Integration: Official MCP SDK Python client with demo and interactive modes
๐ Requirements
Build Environment
- CMake โฅ 3.16 for modern build configuration
- C++14+ compiler (GCC 9.3+, Clang 10+, or MSVC 2019+)
- Make or Ninja build system
- Git for repository cloning
Bundled Dependencies (Zero Installation Required)
- โ
nlohmann/json (v3.11+) - bundled in
include/nlohmann/
- โ
cpp-httplib (v0.14+) - bundled in
include/httplib.h
- โ Boost detection and integration (system boost preferred)
Runtime Environment
- Platform: Linux, macOS, Windows (WSL supported)
- Shell: csh/tcsh for test scripts (bash compatibility available)
- Network: Available port for HTTP server (default: 8080)
Python Client Dependencies
- Python 3.8+ with pip package manager
- MCP SDK: Official Model Context Protocol Python library
- Virtual Environment: Automatically managed by test scripts
๐ Quick Start
1. Automated Build and Test (Recommended)
# Clone the repository
git clone https://github.com/xpc123/mcp_server_cpp.git
cd mcp_server_cpp
# Run comprehensive test suite (builds everything automatically)
./examples/scripts/test_mcp_streamable_http_server.csh
What this script does:
- ๐๏ธ Builds the project with optimal CMake configuration
- ๐ Starts MCP server on port 8080 with full logging
- ๐งช Tests Demo Mode: Automatically tests all 6 tools with realistic parameters
- ๐ฎ Tests Interactive Mode: Simulates user interaction with comprehensive commands
- ๐ Reports Results: Beautiful formatted output with success/failure indicators
- ๐ Cleans Up: Properly stops server and manages all processes
Expected Output:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Test Summary โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Demo Mode: โ
PASSED
Interactive Mode: โ
PASSED
Overall Result: โ
PASSED
2. Manual Build
mkdir -p build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -DMCP_WITH_HTTP=ON -DMCP_BUILD_EXAMPLE=ON
cmake --build . -j4
Build Artifacts:
build/libmcp.a
- Static librarybuild/mcp_streamable_http_server
- StreamableHTTP server
CMake Options:
-DMCP_WITH_HTTP=ON/OFF
- Enable StreamableHTTP transport (default: ON)-DMCP_BUILD_EXAMPLE=ON/OFF
- Build example servers (default: ON)-DMCP_ENABLE_ASAN=ON
- Enable AddressSanitizer for debugging
๐ ๏ธ Available Tools
The server includes 6 comprehensive sample tools demonstrating different MCP patterns:
Tool | Description | Parameters | Use Case |
---|---|---|---|
time | Current UTC timestamp (ISO8601) | None | System info, logging |
echo | Echo back provided text | text (string) | Input validation, debugging |
upper | Convert text to uppercase | text (string) | Text processing |
sum | Sum array of numbers | numbers (array) | Mathematical operations |
getWeather | Mock weather data | city (string) | API simulation, external services |
slow | Long-running task simulation | None | Progress tracking, async operations |
Tool Examples
# Time tool - no parameters
{"jsonrpc":"2.0","method":"tools/call","id":"1","params":{"name":"time","arguments":{}}}
โ {"utc":"2025-09-24T01:04:20Z"}
# Echo tool - simple text processing
{"jsonrpc":"2.0","method":"tools/call","id":"2","params":{"name":"echo","arguments":{"text":"Hello MCP!"}}}
โ {"echo":"Hello MCP!"}
# Sum tool - array processing
{"jsonrpc":"2.0","method":"tools/call","id":"3","params":{"name":"sum","arguments":{"numbers":[1,2,3,4,5]}}}
โ {"sum":15.0,"count":5,"avg":3.0}
# Weather tool - mock API with realistic data
{"jsonrpc":"2.0","method":"tools/call","id":"4","params":{"name":"getWeather","arguments":{"city":"Beijing"}}}
โ {"city":"Beijing","temperature":26,"condition":"Sunny","humidity":50,"note":"mock data"}
Tool Schema Validation
Each tool includes complete JSON Schema definitions for parameter validation:
- Input validation with detailed error messages
- Type checking for all parameters
- Required vs optional parameter handling
- Enum constraints where applicable
Manual Server Usage
Start the StreamableHTTP Server
# Build first (if not done already)
mkdir -p build && cd build
cmake .. -DMCP_WITH_HTTP=ON -DMCP_BUILD_EXAMPLE=ON
cmake --build . -j4
# Start server (runs on port 8080 by default)
./mcp_streamable_http_server
Environment Variables:
MCP_PORT
- Server port (default: 8080)MCP_HOST
- Server host (default: 127.0.0.1)
Test with curl
# List available tools
curl -X POST http://127.0.0.1:8080/ \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tools/list","id":"1"}'
# Call a tool (uppercase example)
curl -X POST http://127.0.0.1:8080/ \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tools/call","id":"2","params":{"name":"upper","arguments":{"text":"hello world"}}}'
๐ Python Client Integration
The project includes a production-ready MCP SDK-based Python client demonstrating best practices:
Automatic Client Setup
The test script automatically handles Python environment setup:
# Virtual environment is created and managed automatically
./examples/scripts/test_mcp_streamable_http_server.csh
Manual Client Usage
If you need to run the client manually:
cd examples/client
# Setup virtual environment (if not exists)
python3 -m venv venv
source venv/bin/activate # bash/zsh
# OR: source venv/bin/activate.csh # csh/tcsh
# Install dependencies (auto-detected by test script)
pip install -r requirements.txt
# Run client modes
python3 mcp_sdk_client.py --demo # Automated testing
python3 mcp_sdk_client.py --interactive # Manual exploration
python3 mcp_sdk_client.py --verbose # Debug output
Client Features
๐ฏ Demo Mode: Comprehensive automated testing
- Tests all 6 server tools with realistic parameters
- Validates response formats and error handling
- Measures performance and connection reliability
- Provides detailed success/failure reporting
๐ฎ Interactive Mode: Manual exploration interface
- Lists all available tools with descriptions
- Provides usage examples for each tool
- Supports real-time tool execution with JSON parameters
- Interactive help system with command completion
๐ง Advanced Options:
--host
/--port
- Custom server connection--verbose
- Detailed HTTP request/response logging--debug
- Full MCP protocol message tracing--timeout
- Custom request timeout settings
MCP Protocol Implementation
Supported Methods
initialize
- MCP handshake with protocol version negotiationnotifications/initialized
- Complete the handshaketools/list
- List all available tools with descriptions and schemastools/call
- Execute a tool with given arguments
Transport Details
- Protocol: StreamableHTTP over HTTP/1.1
- Format: JSON-RPC 2.0 messages
- Endpoint: Single
POST /
endpoint - Real-time: Streaming responses for long-running operations
JSON-RPC Examples
MCP Handshake
// 1. Initialize
{"jsonrpc":"2.0","method":"initialize","id":"1","params":{"protocolVersion":"2025-06-18","capabilities":{"roots":{"listChanged":false},"sampling":{}},"clientInfo":{"name":"mcp-client","version":"1.0.0"}}}
// 2. Initialized notification
{"jsonrpc":"2.0","method":"notifications/initialized"}
Tool Operations
// List tools
{"jsonrpc":"2.0","method":"tools/list","id":"2"}
// Call uppercase tool
{"jsonrpc":"2.0","method":"tools/call","id":"3","params":{"name":"upper","arguments":{"text":"hello world"}}}
// Call sum tool
{"jsonrpc":"2.0","method":"tools/call","id":"4","params":{"name":"sum","arguments":{"numbers":[1,2,3,4,5]}}}
Example Response
{"jsonrpc":"2.0","id":"3","result":{"upper":"HELLO WORLD"}}
๐ Project Structure
mcp_server_cpp/
โโโ ๐ include/ # Header files and bundled dependencies
โ โโโ ๐ mcp/ # Core MCP server headers
โ โ โโโ ๐ server.hpp # Main server class and API
โ โ โโโ ๐ tool.hpp # Tool interface and registry
โ โ โโโ ๐ transport_http.hpp # StreamableHTTP transport
โ โ โโโ ๐ messages.hpp # MCP protocol messages
โ โ โโโ ๐ registry.hpp # Tool registration system
โ โ โโโ ๐ *.hpp # Additional core headers
โ โโโ ๐ nlohmann/ # JSON library (bundled v3.11+)
โ โ โโโ ๐ json.hpp # Complete JSON processing
โ โโโ ๐ httplib.h # HTTP server library (bundled v0.14+)
โโโ ๐ src/ # Implementation files
โ โโโ ๐ server.cpp # Core server implementation
โ โโโ ๐ transport_http.cpp # HTTP transport layer
โ โโโ ๐ messages.cpp # Protocol message handling
โ โโโ ๐ registry.cpp # Tool registry management
โ โโโ ๐ *.cpp # Additional source files
โโโ ๐ examples/ # Complete examples and demos
โ โโโ ๐ streamable_http_server.cpp # Main server executable
โ โโโ ๐ client/ # Official MCP SDK integration
โ โ โโโ ๐ mcp_sdk_client.py # Production-ready Python client
โ โ โโโ ๐ requirements.txt # Python dependencies
โ โ โโโ ๐ venv/ # Virtual environment (auto-created)
โ โโโ ๐ scripts/ # Automated testing and utilities
โ โโโ ๐ test_mcp_streamable_http_server.csh # Comprehensive test suite
โโโ ๐ build/ # Build artifacts (generated by CMake)
โ โโโ ๐ libmcp.a # Static library
โ โโโ ๐ mcp_streamable_http_server # Main server executable
โ โโโ ๐ * # Other build artifacts
โโโ ๐ CMakeLists.txt # Build configuration
โโโ ๐ README.md # This documentation
Key Files Description
mcp_streamable_http_server
- Production server executable with all 6 toolsmcp_sdk_client.py
- Official MCP SDK client with demo and interactive modestest_mcp_streamable_http_server.csh
- Complete test automation with both client modeslibmcp.a
- Reusable static library for integration into other projects
Development Guide
Creating Custom Tools
#include "mcp/server.hpp"
#include "mcp/sample_tools.hpp"
int main() {
mcp::McpServer server;
// Add custom tool
auto custom_tool = mcp::Tool{
"my_tool",
"Custom tool description",
nlohmann::json::object(), // Input schema
[](const nlohmann::json& args, mcp::ToolContext& ctx) {
// Tool implementation
nlohmann::json result;
result["message"] = "Custom tool executed!";
return result;
}
};
server.add_tool(custom_tool);
// Start StreamableHTTP server
int port = 8080;
HttpTransportConfig cfg;
cfg.port = port;
cfg.host = "127.0.0.1";
HttpTransportServer http(server, cfg);
http.run();
return 0;
}
Integration with MCP Clients
This server is compatible with:
- Official MCP SDK (Python, TypeScript) - โ Tested
- Claude Desktop - Should work with proper configuration
- Other MCP clients - Any client supporting StreamableHTTP transport
๐ง Troubleshooting
Common Issues and Solutions
Issue | Symptoms | Solution |
---|---|---|
Port Conflict | Address already in use | kill $(lsof -ti:8080) or set MCP_PORT=8081 |
Build Failure | CMake configuration errors | Ensure CMake โฅ 3.16 and C++14+ compiler |
Client Connection | Connection refused | Verify server running: curl http://127.0.0.1:8080/ |
Test Script Hanging | Interactive mode timeout | Server logs show connection issues |
Python Dependencies | Import errors | Virtual environment auto-setup by test script |
Debug and Diagnostic Tools
๐ Server Debug Mode:
# Start server with verbose logging
MCP_PORT=8080 ./build/mcp_streamable_http_server
# Expected output:
# StreamableHTTP MCP server running on http://127.0.0.1:8080
# Endpoints: POST/GET / (main MCP endpoint), POST /rpc (legacy)
๐ Client Debug Mode:
# Full protocol tracing
python3 mcp_sdk_client.py --demo --verbose --debug
# Test specific functionality
python3 mcp_sdk_client.py --interactive --port 8080
๐งช Connection Testing:
# Test server health
curl -X POST -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tools/list","id":"1"}' \
http://127.0.0.1:8080/
# Expected response: {"jsonrpc":"2.0","id":"1","result":{"tools":[...]}}
Performance Monitoring
Resource Usage:
- Memory: ~10MB base footprint with thread pool
- CPU: Low idle usage, scales with concurrent requests
- Network: HTTP/1.1 with keep-alive support
- Concurrency: Thread-pool handles multiple simultaneous tool calls
Load Testing:
# Simple load test with curl
for i in {1..100}; do
curl -X POST -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tools/call","id":"'$i'","params":{"name":"time","arguments":{}}}' \
http://127.0.0.1:8080/ &
done
wait
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Test with the provided test script
- Submit a pull request
License
This project is provided as example code. Please respect third-party licenses:
- nlohmann/json: MIT License
- cpp-httplib: MIT License