Skip to content

About

MCP Server/Client Library for C++26

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

mcp-in-cpp

An MCP server and client library for C++26. Write plain functions for tools, resources, and prompts: static reflection turns parameters into input schemas, return types into output schemas, and annotations into model-facing descriptions. No macros, no code generation, and no hand-written JSON schemas.

#include <mcp/mcp.hpp>

namespace weather {

struct Forecast {
  [[= mcp::description{"Degrees Celsius"}]] double temperature{};
  bool rain{};
};

struct Alert {
  std::string kind;
  [[= mcp::description{"Hours from now"}]] std::int32_t in_hours{};
};

[[= mcp::tool{"Get the forecast for a city"},
  = mcp::tool_info{.title = "Forecast", .read_only = true}]]
Forecast forecast([[= mcp::description{"City name"}]] std::string city,
                  [[= mcp::range{.min = 1, .max = 7}]] std::int32_t days = 1);

[[= mcp::resource{.uri = "weather://{city}/alerts", .mime_type = "application/json"}]]
std::vector<Alert> alerts(std::string city);

[[= mcp::prompt{"Plan a trip around the weather"}]]
std::string plan_trip(std::string city, std::int32_t days = 3);

}  // namespace weather

int main() {
  mcp::Server server{"weather", "1.0.0"};
  server.add<^^weather>();
  return mcp::serve_stdio(server);
}

Schemas, strict decoding, validation, and function binding come from Scrydantic — its guide covers supported types, constraints, validators, and the annotations re-exported under mcp::. examples/weather.cpp is a complete server running over stdio or HTTP.

Stateful servers

Member functions take the same annotations. Add a std::shared_ptr of the class, and its tools, resources, and prompts all reach that one object, which lives as long as the server:

class Notes {
public:
  [[= mcp::tool{"Save a note"}]]
  std::int32_t save(std::string text);

  [[= mcp::resource{.uri = "notes://{id}"}]]
  mcp::Result<std::string> note(std::int32_t id);

  [[= mcp::prompt{"Summarize the notes"}]]
  std::string summarize(std::int32_t limit = 10);

private:
  std::mutex mutex_;  // calls run side by side
  std::vector<std::string> notes_;
};

server.add(std::make_shared<Notes>());

A class may have any mix of the three. A client that shares the header calls them by declaration too: client->call<^^Notes::save>({.text = "hi"}).

Client

mcp::Client connects to any MCP server over stdio, Streamable HTTP, or in-process loopback. Call tools dynamically with JSON (for LLM hosts) or directly via a shared declaration header with full C++ type safety:

#include <mcp/client.hpp>

int main() {
  // Launch a server subprocess over stdio.
  mcp::Reply<mcp::Client> client =
      mcp::launch({.command = "weather-server"}, {.name = "app", .version = "1.0.0"});
  if (!client) {
    return 1;  // client.error() explains why
  }

  // Dynamic JSON calls (for a model host).
  auto tools = client->list_tools();
  auto result = client->call_tool("forecast", R"({"city":"Oslo","days":3})");

  // Typed calls via shared declarations (no server definitions needed in the client).
  mcp::Reply<weather::Forecast> forecast =
      client->call<^^weather::forecast>({.city = "Oslo", .days = 3});
  // Leave the arguments out when none is required.
  mcp::Reply<std::vector<std::string>> cities = client->call<^^weather::cities>();
  mcp::Reply<std::vector<weather::Alert>> alerts =
      client->read<^^weather::alerts>({.city = "Oslo"});
  mcp::Reply<mcp::PromptResult> plan =
      client->prompt<^^weather::plan_trip>({.city = "Oslo"});

  // Hear each change of a resource until the handle is destroyed.
  mcp::Reply<mcp::Subscription> watching = client->subscribe<^^weather::alerts>(
      {.city = "Oslo"}, [](std::string_view uri) { /* read it again */ });
}

Every call returns mcp::Reply<T> (std::expected<T, mcp::ClientError>) and never throws. Calls are thread-safe, support timeouts and std::stop_token cancellation, and follow list pagination automatically. A subscription works the same in both eras (subscriptions/listen or resources/subscribe): its handler runs on a thread of the client's and may call the client, and an optional second handler hears when the subscription ends on its own, so that the caller can subscribe again. See examples/client.cpp for a standalone stdio CLI client.

Streamable HTTP

The core library has no HTTP dependency. Plug into your own HTTP server or client via mcp::HttpEndpoint / mcp::HttpResponse and mcp::HttpClient, or use the optional header-only cpp-httplib adapters:

// Server
#include <httplib.h>
#include <mcp/httplib.hpp>

mcp::HttpEndpoint endpoint{server};
httplib::Server http;
mcp::mount(http, "/mcp", endpoint);
http.listen("127.0.0.1", 8000);
// Client
#include <httplib.h>
#include <mcp/httplib_client.hpp>

mcp::HttplibClient http;
auto client = mcp::connect("http://127.0.0.1:8000/mcp", http,
                           {.name = "app", .version = "1.0.0"});

https:// URLs require cpp-httplib built with TLS.

Features

  • Dual protocol support — Serves and auto-negotiates both MCP 2026-07-28 (stateless) and 2025-11-25 / 2025-06-18 (session handshake). Passes all scored server scenarios in the official MCP conformance suite and all client scenarios except OAuth.
  • Tools, resources, and prompts — Register namespaces, single functions, or stateful toolboxes (std::shared_ptr<T>) whose member tools, resources, and prompts share one object. Tools return typed values (text + structured content) or raw mcp::Content blocks; refuse calls with mcp::fail("..."). mcp::tool_info gives a tool a display title and the hints (read-only, destructive, idempotent, open-world) a host reads to decide whether to ask before a call; Server::annotate does the same at run time. Resources support fixed URIs, {var} / {+path} URI templates, and update subscriptions in both eras (subscriptions/listen or resources/subscribe), which Server::resource_updated notifies and Client::subscribe hears.
  • Completion — [[= mcp::completes{city_names}]] on a prompt or resource-template parameter names a function (or a toolbox member, &Library::genres) that suggests values as a person types, given the other arguments already chosen. Scoped-enum parameters suggest their enumerators by default; Server::completes sets a provider at run time.
  • Context & client interaction — Take mcp::Progress, mcp::Logger, std::stop_token, mcp::Elicitation (typed forms or raw JSON Schema), mcp::Sampling, or mcp::Roots in any parameter position. They are injected by the server, omitted from input schemas, and work identically across both protocol eras.
  • Transports — mcp::serve_stdio (concurrent worker pool), mcp::launch (POSIX subprocess lifecycle), mcp::connect(in, out), mcp::HttpEndpoint and mcp::connect(url, http) (JSON + SSE streaming, a session's GET stream, resuming with Last-Event-ID, Host/Origin validation, bearer auth hook), in-process mcp::connect(server) for testing, plus mcp::Connection and mcp::Channel for custom transports.

Tools run concurrently, so they must be safe to call side by side: mcp::serve_stdio runs up to eight requests at once (StdioOptions::concurrency; set it to 1 to run them in order), and an HTTP server that handles requests on several threads calls the endpoint from each.

Not yet implemented: OAuth authorization flows, URL elicitation, and mcp::launch on Windows.

Requirements

  • GCC 16.2 or newer (C++26 reflection)
  • CMake 3.30 or newer

Scrydantic 0.6.0 is fetched automatically at configure time unless an installed Scrydantic 0.6 is found via find_package.

Add it to your project

With FetchContent:

include(FetchContent)
FetchContent_Declare(
  mcp-in-cpp
  GIT_REPOSITORY https://github.com/crybo-rybo/mcp-in-cpp.git
  GIT_TAG v0.3.0
)
FetchContent_MakeAvailable(mcp-in-cpp)
target_link_libraries(my_app PRIVATE mcp::mcp)

Or install it and use find_package:

cmake --workflow --preset release
cmake --install build/release --prefix /opt/mcp
find_package(mcp-in-cpp 0.3 REQUIRED)  # with /opt/mcp in CMAKE_PREFIX_PATH
target_link_libraries(my_app PRIVATE mcp::mcp)

Linking mcp::mcp enables C++26 and -freflection. Main headers:

  • <mcp/mcp.hpp> — server, stdio, and HTTP endpoint
  • <mcp/client.hpp> — client, loopback, and stdio transports
  • <mcp/http_client.hpp> — Streamable HTTP client interface
  • <mcp/httplib.hpp>, <mcp/httplib_client.hpp> — optional cpp-httplib adapters

This library is pre-1.0; minor releases may change the API.

Build and test

cmake --workflow --preset dev    # configure, build, and run unit tests
scripts/ci.sh                    # format check, release + asan + tsan, interop, install, conformance
scripts/ci.sh release            # format check + release preset only
scripts/format.sh --fix          # format all C++ sources

Presets: dev, release, asan, tsan. Set CXX if g++ is not GCC 16.2. The scripts install pinned clang-format and Python mcp SDK tools into build/tools on first run; scripts/conformance.sh requires Node 22+.

License

MIT

About

MCP Server/Client Library for C++26

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages