MCP协议客户端库

一个现代C++20客户端库,支持Model Context Protocol (MCP),提供同步和异步API、多种传输方式及生产级功能。

  • by ArcadeAI
  • C++
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 ArcadeAI/mcpp

使用说明

mcpp

一个现代的C++20客户端库 模型上下文协议(MCP).

特性

  • 完全支持MCP协议 -工具、资源、提示、完成、订阅
  • 多个传输 -进程(stdio),带SSE的HTTP
  • 同步;异步API -封锁 McpClient 基于协程 AsyncMcpClient
  • 生产就绪 -断路器、URL验证、会话管理、重试逻辑
  • 现代C++ -C++20协程、概念, std::expected-样式错误处理
  • 综合测试 -495+测试,涵盖单元、集成和真实服务器场景

架构概述

┌─────────────────────────────────────────────────────────────────────────────┐
│                            Your Application                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│   ┌─────────────────────────────┐    ┌─────────────────────────────┐       │
│   │        McpClient            │    │      AsyncMcpClient         │       │
│   │      (synchronous)          │    │      (coroutines)           │       │
│   └──────────────┬──────────────┘    └──────────────┬──────────────┘       │
│                  │                                   │                       │
│   ┌──────────────┴───────────────────────────────────┴──────────────┐      │
│   │                        Transport Layer                           │      │
│   │  ┌─────────────────────┐        ┌─────────────────────┐         │      │
│   │  │  ProcessTransport   │        │    HttpTransport    │         │      │
│   │  │  (stdio to subprocess)       │   (HTTP + SSE)      │         │      │
│   │  └─────────────────────┘        └─────────────────────┘         │      │
│   └──────────────────────────────────────────────────────────────────┘      │
│                                                                              │
│   ┌──────────────────────────────────────────────────────────────────┐      │
│   │                      Resilience & Security                        │      │
│   │  ┌───────────────┐  ┌───────────────┐  ┌───────────────────┐    │      │
│   │  │Circuit Breaker│  │ URL Validator │  │ Session Manager   │    │      │
│   │  └───────────────┘  └───────────────┘  └───────────────────┘    │      │
│   └──────────────────────────────────────────────────────────────────┘      │
└─────────────────────────────────────────────────────────────────────────────┘
                                     │
                                     ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                              MCP Server                                      │
│  (filesystem, GitHub, Slack, custom AI agents, etc.)                        │
└─────────────────────────────────────────────────────────────────────────────┘

快速开始

需求

  • C++20编译器(GCC 11+、Clang 14+、MSVC 2022+)
  • CMake 3.20+

建筑

git clone https://github.com/your-org/mcpp.git
cd mcpp
mkdir build && cd build
cmake ..
make -j$(nproc)

基本用法

#include <mcpp/transport/process_transport.hpp>
#include <mcpp/client/mcp_client.hpp>

using namespace mcpp;

int main() {
    // Connect to an MCP server via stdio
    ProcessTransportConfig config;
    config.command = "npx";
    config.args = {"-y", "@modelcontextprotocol/server-filesystem", "/tmp"};
    
    auto transport = std::make_unique<ProcessTransport>(config);
    transport->start();
    
    McpClient client(std::move(transport));
    client.connect();
    client.initialize();
    
    // List available tools
    auto tools = client.list_tools();
    if (tools) {
        for (const auto& tool : tools->tools) {
            std::cout << "Tool: " << tool.name << "\n";
        }
    }
    
    // Call a tool
    auto result = client.call_tool("read_file", {{"path", "/tmp/test.txt"}});
    if (result) {
        for (const auto& content : result->content) {
            if (content.type == "text") {
                std::cout << content.text.value_or("") << "\n";
            }
        }
    }
    
    client.disconnect();
    return 0;
}

请求/响应流

┌────────────┐                                    ┌────────────┐
│   Client   │                                    │   Server   │
└─────┬──────┘                                    └─────┬──────┘
      │                                                 │
      │  ──────────── initialize ──────────────────►   │
      │  ◄─────────── InitializeResult ────────────    │
      │                                                 │
      │  ──────────── notifications/initialized ───►   │
      │                                                 │
      │  ──────────── tools/list ──────────────────►   │
      │  ◄─────────── ListToolsResult ─────────────    │
      │                                                 │
      │  ──────────── tools/call ──────────────────►   │
      │  ◄─────────── CallToolResult ──────────────    │
      │                                                 │
      │  ◄─────────── notifications/progress ──────    │  (optional)
      │                                                 │
      │  ──────────── ping ────────────────────────►   │
      │  ◄─────────── pong ────────────────────────    │
      │                                                 │
      ▼                                                 ▼

示例

请参阅 examples/ 完整工作示例目录:

示例 说明
01_basic_sync 同步客户端基础
02_basic_async 异步/协程客户端
03_file系统服务器 文件操作
04_http_transport 远程HTTP服务器
05_客户处理人员 激发、取样、根
06_断路器 弹性模式
07_遥控器_工具包 Arcade AI集成

MCP协议覆盖范围

功能 状态 描述
初始化/关闭 ✅ 会话生命周期
工具(列表、调用) ✅ 执行服务器提供的工具
资源(列表、读取、订阅) ✅ 访问服务器资源
资源模板 ✅ URI模板发现
提示(列表,获取) ✅ 提示模板
完工 ✅ 自动完成API
Ping ✅ 健康检查
取消 ✅ 取消正在进行的操作
进度通知 ✅ 跟踪长时间运行的操作
日志记录控制 ✅ 服务器日志级别
激励处理程序 ✅ 用户输入请求
采样处理程序 ✅ LLM完成请求
根处理程序 ✅ 文件系统根暴露

运输

过程传输(stdio)

┌──────────────┐     stdin      ┌──────────────┐
│    Client    │───────────────►│    Server    │
│              │◄───────────────│   (process)  │
└──────────────┘     stdout     └──────────────┘
ProcessTransportConfig config;
config.command = "python";
config.args = {"-m", "my_mcp_server"};
config.use_content_length_framing = false;  // or true for framed mode
config.working_directory = "/path/to/server";
config.environment = {{"API_KEY", "secret"}};

HttpTransport(HTTP+SSE)

┌──────────────┐   POST /message   ┌──────────────┐
│    Client    │──────────────────►│    Server    │
│              │◄──────────────────│    (HTTP)    │
└──────────────┘   SSE /sse        └──────────────┘
HttpClientConfig config;
config.base_url = "https://api.example.com/mcp/";
config.headers = {{"Authorization", "Bearer token"}};
config.timeout = std::chrono::seconds(30);

错误处理

用途 tl::expected 对于无例外的显式错误处理:

auto result = client.call_tool("my_tool", args);
if (!result) {
    switch (result.error().code) {
        case ClientErrorCode::NotConnected:
            // Handle connection error
            break;
        case ClientErrorCode::TransportError:
            // Handle transport failure
            break;
        case ClientErrorCode::ProtocolError:
            // Handle protocol error
            break;
    }
    return;
}
// Use result.value()

断路器

     CLOSED ──────► OPEN ──────► HALF-OPEN
        ▲            │               │
        │            │   success     │
        └────────────┴───────────────┘
              failure: back to OPEN
McpClientConfig config;
config.enable_circuit_breaker = true;
config.circuit_breaker.failure_threshold = 5;
config.circuit_breaker.recovery_timeout = std::chrono::seconds(30);

McpClient client(std::move(transport), config);

if (client.is_circuit_open()) {
    // Fast-fail, don't wait for timeout
}

CLI工具

# List tools
./mcpp-cli -c 'npx' -a '-y' -a '@modelcontextprotocol/server-filesystem' -a '/tmp' --list-tools

# Call a tool
./mcpp-cli -c 'python' -a 'server.py' --call-tool read_file --tool-args '{"path":"/tmp/test.txt"}'

# Interactive mode
./mcpp-cli -c 'node' -a 'server.js' --interactive

# JSON output
./mcpp-cli -c 'python' -a 'server.py' --list-tools --json

项目结构

mcpp/
├── include/mcpp/
│   ├── protocol/      # MCP types and JSON serialization
│   ├── transport/     # Transport layer (Process, HTTP/SSE)
│   ├── client/        # Synchronous McpClient
│   ├── async/         # Asynchronous AsyncMcpClient
│   ├── resilience/    # Circuit breaker
│   ├── security/      # URL validation
│   └── log/           # Logging interfaces
├── src/               # Implementation files
├── tests/             # Test suite (495+ tests)
├── tools/mcpp-cli/    # Command-line interface
└── examples/          # Usage examples

依赖项

全部通过CMake FetchContent自动获取:

运行测试

cd build
ctest --output-on-failure

# Or directly
./mcpp_tests                    # All tests
./mcpp_tests "[mcp_client]"     # Client tests
./mcpp_tests "[real-server]"    # Integration tests

许可证

MIT许可证-请参阅 许可证 文件。