使用说明
MCPP-现代C++MCP框架
模型上下文协议(MCP)的现代C++实现,旨在成为简单性和完整性之间的平衡框架。
特性
- 仅限100%标题 -无需编译核心库,只需包含和使用
- 完全支持MCP协议 (2025年6月18日版本)
- 多传输层:
- 工作室:通过stdin/stdout进行本地进程通信
- HTTP/SSE:与服务器发送事件的远程通信
- WebSocket:双向实时通信(客户端和服务器模式)
- 服务器功能:工具、资源、提示、采样、启发、记录
- 客户能力:完全支持客户端MCP
- 企业功能:
- 中间件/过滤链框架
- 令牌桶速率限制
- 断路器模式
- 普罗米修斯指标导出
- 基于RBAC的承载令牌认证
需求
- C++14兼容编译器(GCC 7+、Clang 5+、MSVC 2019+)
- CMake 3.10+
- OpenSSL(Ubuntu/Debian上的libssl-dev)
- 依赖关系(通过CMake FetchContent管理):
- nlohmann/json 3.10.5
- cpp httplib 0.15.3
- libwebsockets 4.3.4 版本
- 谷歌测试1.14.0
安装
快速开始
# Clone the repository
git clone https://github.com/laplaceliu/mcpp.git
cd mcpp
# Create build directory
mkdir build && cd build
# Configure with CMake
cmake ..
# Build (header-only - only examples and tests need compilation)
make -j$(nproc)
# Run tests
ctest --output-on-failure
依赖项
该项目使用CMake FetchContent下载依赖项。依赖关系管理在 _deps/CMakeLists.txt.
所需的系统包:
- Ubuntu/Debian:
sudo apt-get install libssl-dev - macOS:包含OpenSSL(或
brew install openssl如果需要) - Fedora/RHEL:
sudo dnf install openssl-devel
编译选项
| 选项 | 默认值 | 描述 |
|---|---|---|
MCPP_BUILD_TESTS |
ON | 构建单元测试 |
MCPP_BUILD_EXAMPLES |
ON | 构建示例应用程序 |
项目结构
mcpp/
├── include/mcpp/
│ ├── core/ # Core types and utilities
│ │ ├── json.hpp # JSON type aliases
│ │ ├── types.hpp # MCP protocol types
│ │ └── error.hpp # Error handling
│ ├── protocol/ # JSON-RPC protocol
│ │ ├── message.hpp # Message parsing/serialization
│ │ ├── request.hpp # Request routing
│ │ └── response.hpp
│ ├── transport/ # Transport layers
│ │ ├── itransport.hpp # ITransport interface
│ │ ├── factory.hpp # TransportFactory
│ │ ├── transport.hpp # Backwards compatibility (includes factory.hpp)
│ │ ├── stdio.hpp # stdio transport
│ │ ├── http.hpp # HTTP/SSE transport
│ │ └── websocket.hpp # WebSocket transport (libwebsockets)
│ ├── server/ # Server implementation
│ │ ├── server.hpp
│ │ ├── tool.hpp
│ │ ├── resource.hpp
│ │ └── prompt.hpp
│ ├── client/ # Client implementation
│ │ └── client.hpp
│ └── enterprise/ # Enterprise features
│ ├── middleware.hpp
│ ├── ratelimit.hpp
│ ├── circuit.hpp
│ ├── metrics.hpp
│ └── auth.hpp
├── src/ # (Empty - header-only library)
├── tests/ # Unit tests
└── examples/ # Example applications
注: 这是一个 仅限100%标题 图书馆。无需为核心库编译源文件。只需包含指向OpenSSL和libwebsockets的标头和链接。
用法
创建服务器
#include "mcpp/server/server.hpp"
#include <iostream>
using namespace mcpp;
// Define a tool handler
CallToolResult echo_tool(const std::string& name, const JsonValue& args) {
CallToolResult result;
result.is_error = false;
std::string input = args.value("message", std::string());
result.content.push_back(JsonValue::object({
{"type", "text"},
{"text", "Echo: " + input}
}));
return result;
}
int main() {
// Create server options
ServerOptions options;
options.name = "my-server";
options.version = "1.0.0";
options.capabilities.supports_tools = true;
options.capabilities.supports_resources = true;
// Create and start server
Server server(options);
// Register tools
server.register_tool(
"echo",
"Echo back the input message",
JsonValue::object({
{"type", "object"},
{"properties", JsonValue::object({
{"message", JsonValue::object({
{"type", "string"},
{"description", "Message to echo"}
})}
})},
{"required", JsonValue::array({"message"})}
}),
echo_tool
);
// Start server with stdio transport (default)
server.start();
server.wait();
return 0;
}
使用不同的交通工具
#include "mcpp/transport/transport.hpp"
using namespace mcpp;
// Create transport using factory
auto transport = TransportFactory::create(TransportFactory::Type::Stdio);
// Or by name
auto http_transport = TransportFactory::create("http");
auto ws_transport = TransportFactory::create("websocket");
// Configure WebSocket transport
WebSocketConfig ws_config;
ws_config.host = "localhost";
ws_config.port = 8080;
ws_config.path = "/mcp";
ws_config.is_server = false; // Client mode
ws_config.use_ssl = false;
WebSocketTransport ws(ws_config);
ws.on_message([](const std::string& msg) {
// Handle incoming message
});
ws.start();
创建客户端
#include "mcpp/client/client.hpp"
#include <iostream>
using namespace mcpp;
int main() {
ClientOptions options;
options.name = "my-client";
options.version = "1.0.0";
options.transport_type = TransportFactory::Type::Stdio;
auto client = std::make_shared<Client>(options);
// Handle sampling requests from server
client->on_sampling_request([](const SamplingParams& params) {
SamplingResult result;
result.is_error = false;
result.content = /* ... */;
return result;
});
// Handle elicitation requests
client->on_elicitation_request([](const ElicitationParams& params) {
ElicitationResult result;
result.is_error = false;
result.content = /* ... */;
return result;
});
client->start();
client->wait();
return 0;
}
使用企业功能
速率限制
#include "mcpp/enterprise/ratelimit.hpp"
using namespace mcpp::enterprise;
// Create rate limiter with custom config
RateLimiter::Config config;
config.tokens_per_second = 100;
config.max_tokens = 100;
config.tokens_per_request = 1;
RateLimiter limiter(config);
// Check if request is allowed
auto result = limiter.check("user_id");
if (result.allowed) {
// Process request
} else {
// Rate limited - retry_after_ms until more tokens
}
断路器
#include "mcpp/enterprise/circuit.hpp"
using namespace mcpp::enterprise;
CircuitBreaker breaker("my-service", CircuitBreaker::Config());
// Execute with circuit breaker protection
auto result = execute_with_circuit<int>(
breaker,
[]() { return call_service(); }, // Primary function
[]() { return fallback_value(); } // Fallback when circuit open
);
普罗米修斯指标
#include "mcpp/enterprise/metrics.hpp"
using namespace mcpp::enterprise;
// Register metrics
auto& registry = MetricsRegistry::instance();
registry.counter("requests_total", "Total requests")->increment();
registry.gauge("active_connections", "Active connections")->set(42);
registry.histogram("request_duration", "Request duration")->observe(0.123);
// Export metrics in Prometheus format
std::string output = registry.export_prometheus();
身份验证和RBAC
#include "mcpp/enterprise/auth.hpp"
using namespace mcpp::enterprise;
// Create authorizer with RBAC
Authorizer authorizer;
// Add roles and permissions
authorizer.add_permission("admin", "tools:*");
authorizer.add_permission("user", "tools:read");
authorizer.add_role("user1", "admin");
// Check permissions
if (authorizer.has_permission("user1", "tools:read")) {
// Access granted
}
// Generate and validate tokens
Token token = authorizer.generate_token("user1", std::chrono::hours(24));
if (authorizer.validate_token(token)) {
// Token valid
}
测试
# Run all tests
ctest --output-on-failure
# Or run tests directly
./build/bin/tests
# Run specific test suite
./build/bin/tests --gtest_filter="RateLimiterTest.*"
# Run transport tests only
./build/bin/tests --gtest_filter="*Transport*"
测试覆盖范围: 14个测试套件中的109个测试,涵盖:
- JSON解析和序列化
- JSON-RPC消息协议
- 服务器原语(工具、资源、提示)
- 传输层(标准、HTTP/SSE、WebSocket)
- 企业功能(速率限制、断路器、指标)
API 参考
服务器
Server::Server(ServerOptions)-使用选项创建服务器Server::start()-启动服务器Server::stop()-停止服务器Server::wait()-等待关机Server::register_tool(...)-注册工具Server::register_resource(...)-注册资源Server::register_prompt(...)-注册提示
客户
Client::Client(ClientOptions)-使用选项创建客户端Client::start()-启动客户端Client::stop()-停止客户端Client::on_sampling_request(...)-设置采样处理程序Client::on_elicitation_request(...)-设置启发处理程序Client::on_progress_notification(...)-设置进度处理程序Client::logging_message(...)-发送日志消息
运输
TransportFactory::create(Type)-按类型创建传输(Stdio/Http/Webocket)TransportFactory::create(string)-按名称创建传输(“stdio”/“http”/“websocket”)ITransport::start()-开始运输ITransport::stop()-停止运输ITransport::send(message)-发送消息ITransport::on_message(handler)-设置消息处理程序ITransport::on_error(handler)-设置错误处理程序WebSocketTransport::WebSocketTransport(Config)-使用配置创建WebSocketTransport::set_url(url)-设置websocket URLWebSocketFramer::frame(message)-帧WebSocket消息(RFC 6455)StdioFramer::frame/decode-帧/解码stdio消息HttpFramer::frame/frame_sse-帧HTTP消息/SSE事件
企业
RateLimiter::check(key)-检查密钥的速率限制CircuitBreaker::allow_request()-检查是否允许请求CircuitBreaker::record_success()-记录成功通话CircuitBreaker::record_failure()-记录失败的呼叫MetricsRegistry::counter(name, help)-获取/创建计数器MetricsRegistry::gauge(name, help)-获取/创建仪表MetricsRegistry::histogram(name, help)-获取/创建直方图Authorizer::has_permission(role, permission)-检查权限Authorizer::generate_token(user_id, duration)-生成令牌
文档
构建API文档
本项目将Doxygen用于API文档。要生成文档,请执行以下操作:
# Install Doxygen (if not already installed)
# Ubuntu/Debian:
sudo apt-get install doxygen
# macOS:
brew install doxygen
# Fedora/RHEL:
sudo dnf install doxygen
# Generate documentation (run from project root)
doxygen docs/Doxyfile.in
# View the documentation
# Open docs/doxygen/html/index.html in a browser
open docs/doxygen/html/index.html # macOS
xdg-open docs/doxygen/html/index.html # Linux
生成的文档将在 docs/doxygen/html/ 目录:
index.html-主文档页面classes.html-类层次结构files.html-文件列表
许可证
MIT许可证-有关详细信息,请参阅许可证文件