API Reference

This section provides a complete API reference for the mcp-cpp-sdk, automatically generated from the source code documentation using Doxygen and Breathe.

Overview

The mcp-cpp-sdk is organized into several key namespaces and components:

  • mcp::Server - MCP server implementation for hosting tools, resources, and prompts

  • mcp::Client - MCP client implementation for connecting to servers

  • mcp::SyncServer / mcp::SyncClient - Blocking calls, from sync()

  • mcp::Endpoint - The server a Client launches or connects to

  • mcp::Runtime - An event loop, or a pool of threads for handlers

  • mcp::ITransport - Transport abstraction for communication (stdio, WebSocket, Streamable HTTP)

  • mcp::HttpClientTransport / mcp::HttpServerTransport - Streamable HTTP transport implementations

  • mcp::StreamableHttpSessionManager - Multi-session HTTP endpoint manager

  • mcp::Context - Execution context providing logging and reverse RPC

  • mcp::Task<T> - Coroutine return type for async operations

  • mcp::auth::Authenticator - Abstract interface for token providers

  • mcp::RequestId - JSON-RPC request identifier wrapper

  • Protocol Types - Request/response types for JSON-RPC messages

  • mcp::auth - OAuth 2.1 helpers, discovery client, token store, and authenticated transport wrapper

Core Classes

Server

class Server

MCP server that handles client requests over a transport.

Manages the JSON-RPC message loop, dispatching incoming requests to registered handlers. Supports the MCP initialize handshake and shutdown flow, as well as tool, resource, and prompt handler registration. Creates a Context per request for handler use.

Public Types

using PromptArguments = std::map<std::string, std::string>

The arguments of a prompts/get request, by name.

using SubscriptionHandler = std::function<void(const std::string &uri)>

Callback invoked when a client subscribes to or unsubscribes from a resource URI.

Public Functions

template<typename Name, typename Version>
inline Server(const Name &name, const Version &version)

Construct a Server named name at version version, such as Server server("hello", "1.0.0");.

The server advertises what its registrations imply: tools once a tool is registered, resources for a resource or resource template, prompts for a prompt and completions for a completion provider. capabilities() adjusts what registration cannot imply, such as list-changed notifications, resource subscriptions or logging.

Server(const Implementation &server_info, const ServerCapabilities &capabilities)

Construct a Server.

Parameters:
  • server_info – Information about this server implementation.

  • capabilities – The capabilities this server advertises; each registration adds the capability of its kind when capabilities does not set it, as the constructor above describes.

~Server()
Server(const Server&) = delete
Server &operator=(const Server&) = delete
Server(Server&&) = delete
Server &operator=(Server&&) = delete
template<JsonSerializable In, JsonSerializable Out, typename Fn>
inline void add_tool(const std::string &name, const std::string &description, const nlohmann::json &input_schema, Fn handler)

Register a tool with the server.

Template Parameters:
  • In – Handler input type (must satisfy JsonSerializable).

  • Out – Handler output type (must satisfy JsonSerializable).

  • Fn – Handler callable (sync/async, with/without Context).

Parameters:
  • name – Tool name.

  • description – Human-readable description.

  • input_schema – JSON schema for the tool’s input parameters.

  • handler – Handler invoked on tools/call requests.

Throws:
  • SchemaError – when a schema is not a JSON Schema the SDK can use (see CompiledSchema), the input schema does not declare "type": "object", or an x-mcp-header annotation breaks the rules of the 2026-07-28 tools specification (not a string, empty or not an HTTP token, repeated ignoring case, on a property that is not a string, integer or boolean, or on a property not reached through properties alone).

  • std::invalid_argument – when a tool with the same name is already registered, or when the name is empty, longer than 128 characters or holds a character other than A-Z, a-z, 0-9, _, - and ..

template<JsonSerializable In, JsonSerializable Out, typename Fn>
inline void add_tool(const std::string &name, const std::string &description, const nlohmann::json &input_schema, const nlohmann::json &output_schema, Fn handler)

Register a tool with an output schema for structured output.

Like add_tool(), but also sets the tool’s outputSchema so results include a structuredContent field alongside content.

Throws:
  • SchemaError – when a schema is not a JSON Schema the SDK can use (see CompiledSchema), the input schema does not declare "type": "object", or an x-mcp-header annotation breaks the rules of the 2026-07-28 tools specification (not a string, empty or not an HTTP token, repeated ignoring case, on a property that is not a string, integer or boolean, or on a property not reached through properties alone).

  • std::invalid_argument – when a tool with the same name is already registered, or when the name is empty, longer than 128 characters or holds a character other than A-Z, a-z, 0-9, _, - and ..

void add_tool(const std::string &name, const std::string &description, const nlohmann::json &input_schema, std::function<nlohmann::json(const nlohmann::json&)> handler)

Register a tool with a simple synchronous JSON handler.

Accepts raw JSON params and returns a raw JSON result. Exceptions thrown by the handler become a tool error result (isError=true) rather than a JSON-RPC protocol error.

Parameters:
  • name – Tool name.

  • description – Human-readable description.

  • input_schema – JSON schema for the tool’s input parameters.

  • handler – Synchronous handler: takes JSON params, returns JSON result.

Throws:
  • SchemaError – when a schema is not a JSON Schema the SDK can use (see CompiledSchema), the input schema does not declare "type": "object", or an x-mcp-header annotation breaks the rules of the 2026-07-28 tools specification (not a string, empty or not an HTTP token, repeated ignoring case, on a property that is not a string, integer or boolean, or on a property not reached through properties alone).

  • std::invalid_argument – when a tool with the same name is already registered, or when the name is empty, longer than 128 characters or holds a character other than A-Z, a-z, 0-9, _, - and ..

void add_tool(const std::string &name, const std::string &description, const nlohmann::json &input_schema, std::function<nlohmann::json(Context&, const nlohmann::json&)> handler)

As add_tool() above, with a synchronous handler that takes the request’s Context first, such as for Context::is_cancelled() or, in a task, Context::report_progress_sync().

template<typename Fn>
inline void add_tool(const std::string &name, const std::string &description, const nlohmann::json &input_schema, Fn handler)

As add_tool() above, with a coroutine handler, such as [](mcp::Context& ctx, const nlohmann::json& args) -> mcp::Task<nlohmann::json>.

The handler takes the JSON arguments, after the request’s Context if it wants it. A coroutine needs <mcp/core/async.hpp>.

void add_tool(const Tool &tool, std::function<nlohmann::json(const nlohmann::json&)> handler)

Register the tool tool describes, with its title, annotations, icons, output schema and _meta (such as an Apps link) as given.

The handler takes the JSON arguments and returns a JSON value. A string becomes the result’s text. An object that is not already a CallToolResult becomes its structuredContent, with the object’s JSON text as its text, so a tool with an output schema returns an object. Any other value is sent as its JSON text.

Throws:

SchemaError – and std::invalid_argument as add_tool() above.

void add_tool(const Tool &tool, std::function<nlohmann::json(Context&, const nlohmann::json&)> handler)

As add_tool() above, with a synchronous handler that takes the request’s Context first.

template<typename Fn>
inline void add_tool(const Tool &tool, Fn handler)

As add_tool() above, with a coroutine handler, with or without the Context.

template<typename Fn>
inline void add_raw_tool(const Tool &tool, Fn handler)

Register a low-level tool whose handler returns a complete CallToolResult JSON object.

Unlike add_tool(), this escape hatch never normalizes arbitrary output. Every returned value is validated as a complete CallToolResult before it is sent to the client.

Parameters:
  • tool – Tool metadata.

  • handler – Coroutine raw handler receiving tool arguments, after the request’s Context if it wants it, such as a TypeErasedHandler.

Throws:
  • SchemaError – when a schema is not a JSON Schema the SDK can use (see CompiledSchema), the input schema does not declare "type": "object", or an x-mcp-header annotation breaks the rules of the 2026-07-28 tools specification (not a string, empty or not an HTTP token, repeated ignoring case, on a property that is not a string, integer or boolean, or on a property not reached through properties alone).

  • std::invalid_argument – when a tool with the same name is already registered, or when the name is empty, longer than 128 characters or holds a character other than A-Z, a-z, 0-9, _, - and ..

void add_raw_tool(const Tool &tool, std::function<nlohmann::json(const nlohmann::json&)> handler)

Register a synchronous low-level tool returning complete CallToolResult JSON.

Parameters:
  • tool – Tool metadata.

  • handler – Synchronous raw handler receiving tool arguments.

Throws:
  • SchemaError – when a schema is not a JSON Schema the SDK can use (see CompiledSchema), the input schema does not declare "type": "object", or an x-mcp-header annotation breaks the rules of the 2026-07-28 tools specification (not a string, empty or not an HTTP token, repeated ignoring case, on a property that is not a string, integer or boolean, or on a property not reached through properties alone).

  • std::invalid_argument – when a tool with the same name is already registered, or when the name is empty, longer than 128 characters or holds a character other than A-Z, a-z, 0-9, _, - and ..

template<JsonSerializable In, JsonSerializable Out, typename Fn>
inline void add_resource(const Resource &resource, Fn handler)

Register a resource with the server.

Template Parameters:
  • In – Handler input type (must satisfy JsonSerializable).

  • Out – Handler output type (must satisfy JsonSerializable).

  • Fn – Handler callable (sync/async, with/without Context).

Parameters:
  • resource – Resource metadata.

  • handler – Handler invoked on resources/read requests.

void add_resource_template(const ResourceTemplate &tmpl)

Register a resource template for listing via resources/templates/list.

Parameters:

tmpl – Resource template metadata.

template<JsonSerializable In, JsonSerializable Out, typename Fn>
inline void add_resource_template(const ResourceTemplate &tmpl, Fn handler)

Register a resource template and its resources/read handler.

Exact resources registered with add_resource() take precedence over template matches. Duplicate and structurally identical templates are rejected, and a URI matching more than one template is reported as an ambiguous request.

Template Parameters:
  • In – Handler input type, normally ReadResourceRequestParams.

  • Out – Handler result type, normally ReadResourceResult.

  • Fn – Handler callable (sync/async, with/without Context).

Parameters:
  • tmpl – Resource template metadata.

  • handler – Handler invoked when resources/read matches the template.

template<JsonSerializable In, JsonSerializable Out, typename Fn>
inline void add_prompt(const Prompt &prompt, Fn handler)

Register a prompt with the server.

Template Parameters:
  • In – Handler input type (must satisfy JsonSerializable).

  • Out – Handler output type (must satisfy JsonSerializable).

  • Fn – Handler callable (sync/async, with/without Context).

Parameters:
  • prompt – Prompt metadata.

  • handler – Handler invoked on prompts/get requests.

void add_text_resource(const std::string &uri, const std::string &name, std::function<std::string()> read, const std::string &mime_type = "text/plain")

Register a text resource at uri named name, whose text read returns on each read, such as server.add_text_resource("config://motd", "Message of the day", [] { return std::string("hi"); });.

Parameters:

mime_type – The MIME type the resource and its contents report.

Throws:

std::invalid_argument – When a resource with the same URI is already registered.

void add_text_resource(const Resource &resource, std::function<std::string()> read)

As add_text_resource() above, for the resource resource describes, with its title, description, annotations, icons and size as given and its MIME type text/plain when unset.

template<typename Fn>
inline void add_text_resource(const std::string &uri, const std::string &name, Fn read, const std::string &mime_type = "text/plain")

As add_text_resource() above, with a coroutine that returns the text.

template<typename Fn>
inline void add_text_resource(const Resource &resource, Fn read)

As add_text_resource() above, with a coroutine that returns the text.

void add_text_prompt(const std::string &name, const std::string &description, std::vector<PromptArgument> arguments, std::function<std::string(const PromptArguments&)> render)

Register a prompt named name whose one message, from the user, is the text render makes of the request’s arguments, such as server.add_text_prompt("review", "Review code", {{"code", "The code", true}}, render);.

render gets the arguments the request gave, an empty map when it gave none. A request that leaves out an argument arguments marks as required is answered with mcp::constants::jsonrpc::g_INVALID_PARAMS, and render does not run.

Throws:

std::invalid_argument – When a prompt with the same name is already registered.

void add_text_prompt(const Prompt &prompt, std::function<std::string(const PromptArguments&)> render)

As add_text_prompt() above, for the prompt prompt describes, with its title, icons and arguments as given.

template<typename Fn>
inline void add_text_prompt(const std::string &name, const std::string &description, std::vector<PromptArgument> arguments, Fn render)

As add_text_prompt() above, with a coroutine that makes the text.

template<typename Fn>
inline void add_text_prompt(const Prompt &prompt, Fn render)

As add_text_prompt() above, with a coroutine that makes the text.

void use(Middleware mw)

Register a middleware function to intercept handler invocations.

Middleware executes in registration order (first registered = outermost). Each middleware receives the context, request parameters, and a continuation to call the next in the chain or the final handler. It runs for every request that reaches an application handler: tools/call, resources/read, prompts/get, resources/subscribe, resources/unsubscribe and completion/complete. Requests the server answers itself, such as the list methods, ping and logging/setLevel, do not pass through it.

Parameters:

mw – Middleware function to register.

void set_completion_provider(CompletionHandler handler)

Register a completion handler for completion/complete requests.

Parameters:

handler – The handler that provides completion results.

void set_tool_validation(const ToolValidationOptions &options)

Set which checks apply to tool calls.

Read unsynchronized by request handlers; must be called before run().

void set_notification_rate_limit(const NotificationRateLimit &limit)

Limit the progress and log notifications each request may send.

Each request gets its own buckets of limit, one for Context::report_progress() and one for Context::log(); a notification over the limit is dropped and counted in dropped_notifications(). By default there is no limit. Read unsynchronized by request handlers; must be called before run().

Throws:

std::invalid_argument – If per_second is negative or not a number.

std::uint64_t dropped_notifications() const

Progress and log notifications dropped by set_notification_rate_limit() since this server was created.

void set_handler_executor(const Executor &executor)

Run tool, resource, prompt and extension method handlers on executor instead of the executor the server runs on.

The server’s own work (reading, parsing and answering protocol messages) stays on the executor passed to run(), and so do middleware and the completion provider; only the call of one of those handlers moves to executor, and the server resumes on its own executor when it returns. A tool call made as a task runs on executor whole, its middleware included. A handler that blocks then ties up a thread of executor rather than one the transport needs. Read unsynchronized by request handlers; must be called before run().

The execution context of executor must be destroyed after the one the server runs on: a program that runs its own event loop constructs the Runtime that gives executor before that loop’s io_context. Destroying the server’s execution context waits for the handlers on executor that its requests still wait for; from the start of that destruction their Context calls throw std::runtime_error, and what they return goes nowhere. run_stdio() and run_http() return at the shutdown deadline all the same (see stop()), and destroy their event loop on a thread of its own once those handlers have returned.

Throws:

std::invalid_argument – If executor holds none.

void declare_extension(const std::string &id, nlohmann::json settings = nlohmann::json::object())

Declare support for an extension in the capabilities this server advertises.

Adds extensions[id] to the capabilities that initialize and server/discover return, replacing an earlier declaration of the same extension. Extensions are off until a server declares them. Must be called before the server serves its first request.

Parameters:
  • id – Extension identifier, {vendor-prefix}/{extension-name}.

  • settings – The extension’s settings object; an empty object declares support with no settings.

Throws:

std::invalid_argument – If id is empty or settings is not an object.

ServerCapabilities &capabilities()

The capabilities this server advertises: those it was constructed with, what its registrations imply and the declared extensions.

Change them before the server serves its first request, such as server.capabilities().tools->listChanged = true; after registering a tool, or server.capabilities().logging = nlohmann::json::object();. A registration does not replace a capability that is already set.

const ServerCapabilities &capabilities() const

The capabilities this server advertises: those it was constructed with, what its registrations imply and the declared extensions.

Change them before the server serves its first request, such as server.capabilities().tools->listChanged = true; after registering a tool, or server.capabilities().logging = nlohmann::json::object();. A registration does not replace a capability that is already set.

void add_extension_method(const std::string &method, TypeErasedHandler handler)

Serve an extension’s request method to clients of protocol revision 2026-07-28.

The handler receives the request’s params (including _meta) and returns the result object; the server adds resultType and the members every 2026-07-28 result carries. A result that sets ttlMs and cacheScope keeps them. The handler reports invalid parameters by throwing std::invalid_argument, which the client receives as -32602, and any other exception as an internal error. Middleware registered with use() wraps these handlers as it wraps resources/read, so a request it refuses never reaches the handler. Earlier revisions answer the method with -32601. Must be called before the server serves its first request.

Parameters:
  • method – The method name, for example skills/list.

  • handler – Handler invoked for each request of that method.

Throws:

std::invalid_argument – If method is empty, names a method the SDK serves itself, or is already registered.

ToolValidationStats tool_validation_stats() const

Tool calls refused by validation since this server was created.

void set_page_size(std::size_t size)

Set the page size for paginated list responses.

A list request whose cursor is not one a nextCursor of this server could have held, including one past the end of a list that has since become shorter, is answered with -32602 (Invalid params).

Parameters:

size – The maximum number of items per page. 0 means no pagination.

void set_max_in_flight_requests(std::size_t limit)

Set how many requests of one session may run at once.

A request past the limit is answered with an error instead of being queued, so a peer that sends requests faster than they finish cannot grow the process without bound. The same answer goes to a request past the memory limit, set_max_in_flight_bytes(). Requests given to dispatch_request_direct(), such as 2026-07-28 requests, belong to no session and share one such limit; each counts until its handler ends, even when its client has gone. A handler waiting for client input is bounded by MrtrOptions instead, and counts here again when it goes on after being given up.

Parameters:

limit – The limit, at least 1. The default is 1024.

Throws:

std::invalid_argument – If limit is 0.

void set_max_in_flight_bytes(std::size_t bytes)

Set how much memory the requests of one session that are running, and their answers that are not written yet, may take.

A request is counted as its parsed JSON takes memory, which can be far more than its text: an array of empty objects takes about 27 times its length. An answer is counted by its length until the peer has taken it, so a peer that stops reading stops the session from reading more requests. A request that would go past the limit is answered with an error, as one past set_max_in_flight_requests() is. The handlers’ own copies of a request are not counted. Requests given to dispatch_request_direct() share one such limit.

Parameters:

bytes – The limit, at least 1. The default is 256 MiB.

Throws:

std::invalid_argument – If bytes is 0.

void set_reverse_request_timeout(std::chrono::milliseconds timeout)

Set how long a request the server sends the client may wait for its answer.

The request then fails in the handler that made it, as a client that never answers would otherwise hold that handler for as long as the session lasts.

Parameters:

timeout – The timeout, longer than zero. The default is ten minutes.

Throws:

std::invalid_argument – If timeout is not positive.

void set_instructions(std::string instructions)

Set the instructions string returned by initialize and server/discover.

Read unsynchronized by request handlers; must be called before run().

Parameters:

instructions – Natural-language guidance for LLMs on how to use this server.

void set_cache_hints(CacheTarget target, CacheHint hint)

Set the ttlMs and cacheScope hints of one kind of result.

Applies to results of 2026-07-28 requests; a result of an earlier revision carries no hints. Until set, a target uses the CacheHint defaults. A handler’s result that already carries ttlMs or cacheScope keeps its own value. Read unsynchronized by request handlers, so it must be called before the server serves its first request: before run() or the first dispatch_request_direct(). With StreamableHttpSessionManager, configure the Server in the factory, before passing it to set_modern_server(), or through modern_server() before listen().

Parameters:
  • target – The result the hints apply to.

  • hint – The hints.

Throws:

std::invalid_argument – If hint.ttlMs is negative.

void set_report_server_info(bool report)

Choose whether results of 2026-07-28 requests name this server.

When true (the default), every such result carries the server’s name and version under _meta (io.modelcontextprotocol/serverInfo), as the revision recommends. Results of earlier revisions never do. Must be called before the server serves its first request: before run() or the first dispatch_request_direct(). With StreamableHttpSessionManager, configure the Server in the factory, before passing it to set_modern_server(), or through modern_server() before listen().

void set_protocol_policy(ServerProtocolPolicy policy)

Choose which protocol revisions this server serves.

Takes effect for every transport. Must be called before the server serves its first request; afterwards only the policy in effect may be set again, as run_http() does when its configure sets the same policy on every run.

Parameters:

policy – The revisions to serve.

Throws:
  • std::invalid_argument – If ServerProtocolPolicy::validate() refuses the policy.

  • std::logic_error – If the server has already served a request or run() has started, and policy differs from the policy in effect.

ProtocolRejectionStats protocol_rejection_stats() const

Requests refused for their protocol version or per-request protocol fields since this server was created.

void set_mrtr_options(MrtrOptions options)

Set the limits on 2026-07-28 requests that wait for client input.

With MrtrStateMode::eStored (the default) the waiting handlers live in this server, so a client’s retry must reach the same server instance (and process) as the request it retries; one that does not is answered as for an unknown requestState. When run() ends, its transport can bring no more retries, and the waiting handlers are given up. Takes effect for requests parked afterwards.

With MrtrStateMode::eSealed nothing waits in the server: requestState carries the state, sealed with MrtrOptions::sealing_keys, and a retry may reach any server instance that has the key. The instance runs the handler again from the start and the questions earlier rounds answered return their answers at once (see Context::is_replay()), so a handler must ask the same questions in the same order when given the same answers. Progress and log notifications a handler sends before the question it asks again are sent again. A retry is refused as an unknown requestState when its state is expired, was sealed by another key, or belongs to another principal, method or arguments.

A sealed state is not single-use: until it expires the client (or anyone holding the state) can send it again, and each time the handler runs again from the start with the same answers. The steps after the handler’s last question then run once more, so make them idempotent or set MrtrOptions::consume to refuse a state it has seen. A handler is released at its first unanswered question without running any more of its code (its locals are destroyed), so no catch of the handler sees the release. The expiry is a wall-clock time; instances that share keys need reasonably synchronized clocks. Context::is_replay() is true only while earlier answers remain to be replayed.

The secrets in options are overwritten once the key ring is built and the server keeps none of them.

Parameters:

options – The limits.

Throws:

std::invalid_argument – when sealed mode has no key, a key is shorter than 32 bytes, two keys are the same secret or share a 4-byte key id, max_rounds is 0, state_ttl is zero or negative, or max_state_bytes is below 512.

MrtrStats mrtr_stats() const

Counters of the 2026-07-28 requests that wait, or waited, for client input.

void enable_tasks(TaskOptions options = {})

Serve the tasks extension (io.modelcontextprotocol/tasks) of protocol revision 2026-07-28.

A tool whose mode is not ToolTaskMode::eNever answers a client that declared the extension with a task handle at once, runs the tool apart from the request, and keeps its outcome in the task store for the client to fetch with tasks/get. The server then also answers tasks/get, tasks/update and tasks/cancel, advertises the extension in server/discover, and sends notifications/tasks to a subscriptions/listen stream that asks for a task’s id. Clients of earlier protocol revisions never see tasks.

The task’s handler runs on the executor set with set_handler_executor(), or else on the executor of the request. A handler that blocks stalls whatever else runs there, so a server that serves task tools needs a handler executor with threads of its own. Inside a task, Context::report_progress() sets the task’s status message, and Context::elicit(), sample_llm() and request_roots() put the question in the task’s inputRequests and wait until the client answers with tasks/update.

A task is bound to the principal (Context::principal()) that started it, and only that principal can fetch, answer or cancel it. When the transport authenticates no principal, every caller shares one anonymous scope, and the task id, which is random and not guessable, is all that protects a task: serve tasks to anonymous callers only when that is acceptable.

Tasks last as long as their time to live, and with the default store only as long as the process: a task does not survive a restart, and the store’s other limits apply. The handler of a task whose time to live passes is asked to stop, like one whose task is cancelled (Context::is_cancelled()), but a handler that ignores that keeps running, and keeps counting against TaskOptions::max_tasks_per_principal and TaskOptions::max_tasks until it returns.

Parameters:

options – The store and the limits.

Throws:

std::logic_error – If the server already serves requests.

void set_tool_task_mode(const std::string &name, ToolTaskMode mode)

Set whether calls of tool name may become tasks.

A tool’s mode is ToolTaskMode::eNever until set. The mode may be set before enable_tasks(); it takes effect once tasks are enabled.

Throws:
  • std::logic_error – If the server already serves requests.

  • std::invalid_argument – If no tool is registered under name.

void set_tool_task_preparation(const std::string &name, ToolTaskPreparation preparation)

Let tool name ask the client for input before its task is created.

The preparation runs only for a tools/call that would create a task: tasks are enabled, the tool’s mode is not ToolTaskMode::eNever and the client declared the tasks extension. It runs inside that request with the Context a synchronous handler of the tool would get, so it may call Context::elicit(), Context::sample_llm() and Context::request_roots(): the client answers them through the multi round-trip flow of the request, and the call returns a task only once the preparation has returned. The preparation receives the tool’s arguments. When it returns TaskPreparation::result the call is answered with that result and no task is created; otherwise the task is created and its handler is called with TaskPreparation::arguments. A preparation that throws answers the call the way a handler that throws does.

Middleware sees the call twice: once around the preparation, where it may reject the call, rewrite the parameters or answer without calling the next handler (no task is created then), and later around the task’s handler. When the preparation returns arguments, middleware around it sees an empty CallToolResult as the answer, since no result exists yet.

The task limits of TaskOptions are checked before the preparation runs, so a principal at its limit is answered without being asked anything, and again when the task is created. A request cancelled while the preparation runs creates no task.

Throws:
  • std::logic_error – If the server already serves requests.

  • std::invalid_argument – If no tool is registered under name.

void abandon_waiting_handlers()

Give up every handler waiting for the retry of a 2026-07-28 request.

Each stops at its question and its frame unwinds (a stored handler throws from the question, a sealed handler is destroyed without running more of its code), and its answer is discarded. For when no retry can arrive any more: run() does this when it ends, and StreamableHttpSessionManager::close() for its modern server.

Task<nlohmann::json> send_request(const std::string &method, const std::optional<nlohmann::json> &params)

Send a JSON-RPC request to the connected client and await its response.

Parameters:
  • method – JSON-RPC method name.

  • params – Optional request parameters.

Throws:

std::runtime_error – If the client returns an error response.

Returns:

A task that resolves to the result JSON.

Task<nlohmann::json> invoke_tool(const std::string &tool_name, const nlohmann::json &args)

Invoke a tool directly by name with the provided arguments.

Bypasses the JSON-RPC message loop and calls the tool handler directly. Intended for high-performance json_only mode where transport overhead is unnecessary.

Parameters:
  • tool_name – The name of the tool to invoke.

  • args – The arguments to pass to the tool.

Throws:

std::runtime_error – If the tool is not found.

Returns:

A task that resolves to the tool result JSON.

Task<void> run(std::shared_ptr<ITransport> transport, const Executor &executor)

Start the server session loop on the given transport.

Runs until the transport is closed or an error occurs, then waits for request handlers already dispatched by this session to finish. The returned task keeps the server’s state alive, so the Server object may be destroyed before it completes; a reverse request that a handler issues after that throws std::runtime_error.

The session enforces the initialization sequence. When transport is an HttpServerTransport, or wraps one and returns it from ITransport::http_server_transport(), a session the client ends with HTTP DELETE is over and the next client must initialize again, the Mcp-Param-* headers of 2026-07-28 tools/call requests are checked, and notifications of 2026-07-28 requests are dropped. A wrapper that does not return it is served like any other transport.

Parameters:
  • transport – The transport to use for message exchange. Ownership is shared.

  • executor – The executor to use for async operations.

void run_stdio()

Run the server on stdio (stdin/stdout), blocking until shutdown.

Handles SIGINT and SIGTERM for clean shutdown. Exceptions from the server session are propagated to the caller.

void run_stdio(std::istream &input, std::ostream &output)

Run the server on custom streams, blocking until shutdown.

Same as run_stdio() but reads from / writes to the given streams instead of stdin / stdout.

input and output are used until the run’s handlers have finished: when the shutdown deadline ends the run while a handler on the set_handler_executor() executor still runs, that is after this returns.

Parameters:
  • input – Stream to read JSON-RPC messages from.

  • output – Stream to write JSON-RPC responses to.

void run_http(const std::string &host, uint16_t port, const std::function<void(StreamableHttpSessionManager&)> &configure = {})

Run the server over HTTP, blocking until shutdown.

Binds to the given host and port, accepts HTTP connections, and processes JSON-RPC requests from any number of clients. Handles SIGINT and SIGTERM for clean shutdown. Exceptions from listening are propagated to the caller.

A client of protocol revision 2025-11-25 or earlier gets a session of its own (MCP-Session-Id), served with this server’s tools, resources, prompts, handlers and settings; notify_tools_list_changed() and the other notify_ calls reach every session. The members of this server that belong to one session, send_request(), is_initialized(), is_shutdown_requested() and get_log_level(), stand for none of them: a handler reaches its client through its Context. A 2026-07-28 request belongs to no session and is answered by this server with plain JSON, or, when its handler sends a notification and the client accepts text/event-stream, with an SSE stream of the notifications and then the response. subscriptions/listen is served as a stream.

The server listens through a StreamableHttpSessionManager, which configure, when given, receives before it listens: its setters choose the allowed origins, bearer token validation, protected resource metadata, limits and stream options, such as server.run_http("127.0.0.1", 8080, [](mcp::StreamableHttpSessionManager& http) { http.set_allowed_origins({"https://app.example"}); });. A program that passes configure includes <mcp/transport/http_session_manager.hpp>, which declares the manager. Without configure the endpoint keeps its default settings, so a request carrying an Origin header is answered with 403.

stop() ends the call as SIGINT does, and bound_port() gives the port it listens on.

Parameters:
  • host – Local address to bind (e.g. “0.0.0.0” or “127.0.0.1”).

  • port – TCP port to listen on, or 0 for one the system chooses.

  • configure – Called with the session manager before it listens; an exception it throws ends run_http() before anything is served.

void stop()

Ends the runs of this server in progress: run_stdio() and run_http() return as they do on SIGINT, run() closes its transport and completes as it does when the transport closes, and a StreamableHttpSessionManager constructed with this server closes.

May be called from any thread, including from a handler. As on SIGINT, the transport closes at once, so a request still being served is not answered, and run_stdio() and run_http() return once the handlers still running have finished, or after mcp::constants::shutdown::g_TIMEOUT_MS. A synchronous handler that runs on the server’s own loop holds that loop, and with it the deadline, until it returns; one on the set_handler_executor() executor is left running. The handler of a tool call made as a task is not waited for either: it goes on, and a question it asks the client afterwards is never answered. Does nothing when the server is not running: a run that starts after the call is not ended by it.

std::uint16_t bound_port() const

The TCP port run_http() listens on, which is the one the system chose when it was given port 0.

Returns:

The port while run_http() runs and from before the first connection is accepted, and 0 before and after; may be called from any thread.

SyncServer sync()

A view of this server whose members block the calling thread until the matching coroutine finishes, for threads other than the event loop of run_stdio() and run_http(), such as server.sync().notify_resource_updated("file:///notes.txt");.

See SyncServer.

Task<void> dispatch(nlohmann::json json_msg)

Dispatch a parsed JSON-RPC message to the appropriate handler.

The Server object must outlive the returned task.

Parameters:

json_msg – The parsed JSON-RPC message.

Task<std::string> dispatch_request_direct(nlohmann::json json_msg)

Dispatch a parsed JSON-RPC request and return its serialized response.

Used by stateless HTTP JSON mode to avoid creating a transport-backed server session for request/response messages. The request envelope is validated, but no stateful initialize/initialized handshake is required. A request that carries its protocol version in _meta is served as a 2026-07-28 request: its version and per-request fields are checked.

Request parameter decoding failures are returned as mcp::constants::jsonrpc::g_INVALID_PARAMS (-32602). Exceptions thrown by middleware, or by resource, prompt and completion handlers, are returned as mcp::constants::jsonrpc::g_INTERNAL_ERROR (-32603); a tool handler’s exception becomes a tool error result (isError: true).

The Server object must outlive the returned task.

Parameters:

json_msg – The parsed JSON-RPC request object.

Returns:

A task that resolves to the serialized JSON-RPC response.

Task<std::string> dispatch_request_direct(nlohmann::json json_msg, RequestContext request_context)

Dispatch a parsed JSON-RPC request with per-call state and return its serialized response.

As the one-argument overload. A tools/call is cancelled through request_context.cancelled, never through notifications/cancelled, so concurrent calls that reuse a request id stay independent.

The Server object must outlive the returned task.

Parameters:
  • json_msg – The parsed JSON-RPC request object.

  • request_context – Per-call state.

Returns:

A task that resolves to the serialized JSON-RPC response.

bool is_initialized() const

Check whether the server has been initialized.

Returns:

true if an initialize request has been handled.

bool is_shutdown_requested() const

Check whether a shutdown has been requested.

Returns:

true if a shutdown request has been handled.

Task<void> notify_tools_list_changed()

Send a notifications/tools/list_changed notification to the client.

Also sent, tagged with its subscription id, to each open subscriptions/listen stream that asked for it; the same holds for the three notify methods below.

The Server object must outlive the returned task.

Task<void> notify_resources_list_changed()

Send a notifications/resources/list_changed notification to the client.

The Server object must outlive the returned task.

Task<void> notify_prompts_list_changed()

Send a notifications/prompts/list_changed notification to the client.

The Server object must outlive the returned task.

Task<void> notify_resource_updated(const std::string &uri)

Send a notifications/resources/updated notification to all subscribers.

The Server object must outlive the returned task.

Parameters:

uri – The URI of the resource that was updated.

void close_subscriptions()

Ends every open subscriptions/listen stream gracefully.

Each stream’s request is answered with its empty resultType: "complete" result carrying the stream’s io.modelcontextprotocol/subscriptionId, which the transport that carried the request then delivers. Returns at once and may be called from any thread. Streams opened later are not affected. A stream that ends because its client cancelled it, or its transport closed, gets no response.

std::size_t subscription_count() const

The number of subscriptions/listen streams currently open on this server.

void on_subscribe(const SubscriptionHandler &handler)

Register a callback invoked after a successful resource subscription.

Parameters:

handler – Callback receiving the subscribed resource URI.

void on_unsubscribe(const SubscriptionHandler &handler)

Register a callback invoked after a successful resource unsubscription.

Parameters:

handler – Callback receiving the unsubscribed resource URI.

LoggingLevel get_log_level() const

Get the currently active server log level.

Returns:

The log level used when filtering context log messages of requests of 2025-11-25 and earlier. A 2026-07-28 request is filtered by its own io.modelcontextprotocol/logLevel.

Client

class Client

MCP client that communicates with a server over a transport.

Manages the JSON-RPC request/response lifecycle, including an asynchronous read loop that dispatches incoming responses to their corresponding pending requests. connect() settles on a protocol era (ClientOptions::protocol): a legacy session starts with an initialize request followed by an initialized notification, a modern one sends no handshake and carries its protocol fields in each request’s _meta.

Runtime I/O and request state are serialized on a boost::asio::strand.

Public Types

using NotificationCallback = std::function<void(const nlohmann::json&)>

Type for notification callback: receives the notification params JSON.

using RequestHandler = std::function<Task<nlohmann::json>(const nlohmann::json&)>

Type for request handler: receives params JSON, returns result JSON.

using ProgressCallback = std::function<void(const ProgressNotificationParams&)>

Callback invoked for a deserialized progress notification.

Public Functions

Client(std::shared_ptr<ITransport> transport, const Executor &executor, ClientOptions options = {})

Construct a Client.

Parameters:
  • transport – The transport to use for message exchange. Ownership is shared with the client.

  • executor – The executor to use for async operations.

  • options – Default timeout and protocol-validation behavior.

explicit Client(const Endpoint &endpoint, ClientOptions options = {})

Construct a client of the server endpoint names, running its own event loop.

The client starts a thread that runs an event loop for it, makes the endpoint’s transport on that loop, and needs no executor from the application: use it through sync() or run(), or await its coroutines from run(). The destructor closes the connection, waits for the loop to finish (a launched server exits and its StdioProcessOptions::on_exit runs) up to mcp::constants::client::g_CLOSE_WAIT_MS, or as long as a launched server’s stdin_close_wait and terminate_wait when they add up to more, and joins the thread. A Client constructed this way must not be destroyed on its own loop’s thread, such as from a notification callback.

Parameters:
Throws:
  • std::runtime_error – When the server of Endpoint::stdio() cannot be launched.

  • std::invalid_argument – When options holds a limit that is not positive, or the transport factory of Endpoint::custom() returns null.

SyncClient sync()

Blocking calls to this client: each method runs the coroutine member of the same name on the client’s event loop and waits for it.

For a Client constructed from an Endpoint. A blocking call made on the client’s own event loop thread, such as from a notification callback or a coroutine awaiting the client, would wait for itself and throws std::logic_error instead. Blocking calls, run() and coroutines may be mixed on one client.

Throws:

std::logic_error – If the client runs on the application’s executor, whose event loop it cannot run itself: such a client is used through its coroutines.

void run(std::function<Task<void>()> body)

Run body, a coroutine that uses this client, on the client’s event loop and wait for it to finish.

For a Client constructed from an Endpoint. The coroutine’s exception, if it throws, is rethrown here. body is kept alive until the coroutine has finished, so a lambda may capture what the coroutine uses.

Throws:
  • std::logic_error – If the client runs on the application’s executor, or the call is made on the client’s own event loop thread.

  • std::invalid_argument – If body is empty or returns an empty Task.

Executor executor() const

The executor the Client was constructed with.

Coroutines that use this Client can be spawned on it; get() returns it as a boost::asio::any_io_executor.

~Client()

Destructor.

Closes the transport and clears pending requests so that asio-tied objects (timers, streams) are destroyed while the io_context is still alive.

Client(const Client&) = delete
Client &operator=(const Client&) = delete
Client(Client&&) = delete
Client &operator=(Client&&) = delete
Task<ConnectResult> connect(std::string_view name, std::string_view version)

Connect with default capabilities.

Parameters:
  • name – Client implementation name.

  • version – Client implementation version.

Returns:

A task that resolves to what the server declared; see the overload below.

Task<ConnectResult> connect(const Implementation &client_info, const ClientCapabilities &capabilities)

Connect to the server and settle on a protocol era.

Starts the read loop, then follows ClientOptions::protocol. The capabilities the client declares are capabilities plus what the registered handlers imply: roots, sampling and elicitation when a handler answers roots/list, sampling/createMessage or elicitation/create (on_roots_list(), set_roots(), on_sampling(), on_elicitation() or on_request()). A legacy session sends them in initialize, and then notifications/initialized. A modern session sends server/discover once to learn the server’s capabilities and sends nothing else; from then on every request carries io.modelcontextprotocol/protocolVersion, the capabilities, counting handlers registered since connect(), and client_info in its _meta, merged with the _meta entries the caller supplied. The era is fixed for the client’s lifetime.

In a modern session ping() and the removed subscription and log-level methods fail locally, set_roots() sends no list-changed notification, and a result whose resultType is neither absent nor “complete” fails with McpError.

Parameters:
  • client_info – Information about this client implementation.

  • capabilities – Capabilities supported by this client.

Throws:

McpError – If the server cannot be reached, closes the connection while it is probed (pin ClientProtocol::legacy() for such a server), or shares no protocol version.

Returns:

A task that resolves to what the server declared.

Task<nlohmann::json> send_request(std::string_view method, const std::optional<nlohmann::json> &params, const RequestOptions &request_options = {})

Send a JSON-RPC request and await its response.

Assigns a unique integer ID, serializes the request on the stack, and delegates to a coroutine that handles transport and suspension. This is done to avoid GCC 11 SSO bugs and dangling references.

Parameters:
  • method – JSON-RPC method name.

  • params – Optional parameters for the request.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Throws:

McpError – If the peer returns an error response or the request times out.

Returns:

A task that resolves to the result JSON object.

Task<Subscription> listen(const SubscriptionFilter &filter, const RequestOptions &request_options = {})

Open a subscriptions/listen stream (protocol revision 2026-07-28 and later).

Sends the request and waits for the server’s notifications/subscriptions/acknowledged, then returns a handle for the stream. The acknowledged filter may be a subset of filter; see Subscription::unhonored(). The request is never answered while the stream is open, so ClientOptions::request_timeout (or RequestOptions::timeout) limits only the wait for the acknowledgment. Any number of streams may be open at once; each receives only the notifications that carry its id. The handlers registered with on_notification() still run for these notifications as well.

Parameters:
  • filter – The notification types wanted.

  • request_options – Per-request options; RequestOptions::timeout bounds the wait for the acknowledgment.

Throws:

McpError – mcp::constants::jsonrpc::g_METHOD_NOT_FOUND when the session is not modern (a legacy session, or connect() has not finished), mcp::constants::jsonrpc::g_INVALID_REQUEST before connect(), mcp::constants::jsonrpc::g_REQUEST_TIMEOUT when no acknowledgment arrives in time, mcp::constants::jsonrpc::g_CONNECTION_CLOSED when the connection ends first, or the server’s error (for example mcp::constants::jsonrpc::g_INVALID_PARAMS for a malformed filter, mcp::constants::jsonrpc::g_METHOD_NOT_FOUND for a server or transport without streams).

Returns:

A task that resolves to the open stream.

Task<void> send_notification(std::string_view method, const std::optional<nlohmann::json> &params)

Send a JSON-RPC notification (no response expected).

Parameters:
  • method – The notification method name.

  • params – Optional parameters for the notification.

Returns:

A task that completes when the notification has been written to the transport.

std::size_t pending_request_count() const

Get the number of pending (in-flight) requests.

Returns:

The count of requests awaiting responses.

void clear_response_cache()

Drop every result the response cache holds, so each cacheable call asks the server again.

Safe from any thread.

std::uint64_t dropped_notifications() const

Progress and log notifications dropped by ClientOptions::notification_rate_limit.

void close()

Close the client, stopping the read loop and releasing resources.

template<JsonSerializable Args, typename Self = Client>
inline auto call_tool(const std::string &name, const Args &arguments, const RequestOptions &request_options = {})

Call a tool on the server.

Serializes the arguments to JSON, sends a “tools/call” request, and deserializes the response into a CallToolResult.

Template Parameters:

Args – A JsonSerializable type for the tool arguments.

Parameters:
  • name – The name of the tool to call.

  • arguments – The arguments to pass to the tool.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Throws:
  • StructuredContentError – when the result’s structuredContent does not conform to the tool’s output schema (see ClientOptions::validate_tool_schemas).

  • McpError – with mcp::constants::jsonrpc::g_REQUEST_CANCELLED for a cancelled call.

Returns:

A task that resolves to the server’s CallToolResult.

Task<CallToolResult> call_tool(const std::string &name, const nlohmann::json &arguments, const RequestOptions &request_options = {})

Call a tool with JSON arguments.

As call_tool() above. Null arguments, which {} makes, are sent as an empty object. Build other arguments in a variable before the co_await, such as nlohmann::json arguments{{"a", 1}, {"b", 2}}; co_await client.call_tool("add", arguments);: GCC 12 and 13 crash on a braced list inside a co_await (see the README’s compiler notes).

template<JsonSerializable Args, typename Self = Client>
inline auto start_tool(const std::string &name, const Args &arguments, const RequestOptions &request_options = {})

Call a tool, taking a task if the server starts one (protocol revision 2026-07-28).

Declares the tasks extension for this call whatever ClientOptions::tasks is set to. The server decides whether the call becomes a task.

Template Parameters:

Args – A JsonSerializable type for the tool arguments.

Parameters:

request_options – Per-request options, such as a deadline or a CancellationToken.

Throws:

StructuredContentError – as call_tool() does for a result.

Returns:

The tool’s result when the server ran the call to its end, or a TaskHandle when it answered with a task. A legacy session always gets the result.

Task<std::variant<CallToolResult, TaskHandle>> start_tool(const std::string &name, const nlohmann::json &arguments, const RequestOptions &request_options = {})

Start a tool call with JSON arguments.

As start_tool() above, with the arguments as call_tool() takes JSON ones.

TaskHandle task_handle(std::string id)

A handle to a task by its id, for a task started earlier.

The handle’s created() holds nothing but the id until get() or wait() fetches the task’s state.

Task<ListToolsResult> list_tools(const std::optional<std::string> &cursor = std::nullopt, const RequestOptions &request_options = {})

List available tools from the server.

Tools whose schemas cannot be used are left out (see ClientOptions::validate_tool_schemas).

Parameters:
  • cursor – Optional pagination cursor.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Returns:

A task that resolves to the server’s ListToolsResult.

Task<ListResourcesResult> list_resources(const std::optional<std::string> &cursor = std::nullopt, const RequestOptions &request_options = {})

List available resources from the server.

Parameters:
  • cursor – Optional pagination cursor.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Returns:

A task that resolves to the server’s ListResourcesResult.

Task<ReadResourceResult> read_resource(const std::string &uri, const RequestOptions &request_options = {})

Read a resource from the server by URI.

Parameters:
  • uri – The URI of the resource to read.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Returns:

A task that resolves to the server’s ReadResourceResult.

Task<ListResourceTemplatesResult> list_resource_templates(const std::optional<std::string> &cursor = std::nullopt, const RequestOptions &request_options = {})

List available resource templates from the server.

Parameters:
  • cursor – Optional pagination cursor.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Returns:

A task that resolves to the server’s ListResourceTemplatesResult.

Task<ListPromptsResult> list_prompts(const std::optional<std::string> &cursor = std::nullopt, const RequestOptions &request_options = {})

List available prompts from the server.

Parameters:
  • cursor – Optional pagination cursor.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Returns:

A task that resolves to the server’s ListPromptsResult.

Task<GetPromptResult> get_prompt(const std::string &name, const std::map<std::string, std::string> &arguments = {}, const RequestOptions &request_options = {})

Get a specific prompt from the server.

Parameters:
  • name – The name of the prompt.

  • arguments – The arguments that fill in the prompt, by name; the request carries none when the map is empty. As for call_tool(), build them in a variable before the co_await.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Returns:

A task that resolves to the server’s GetPromptResult.

Task<CompleteResult> complete(const CompleteParams &params, const RequestOptions &request_options = {})

Request completions from the server.

Parameters:
  • params – The completion parameters.

  • request_options – Per-request options, such as a deadline or a CancellationToken.

Returns:

A task that resolves to the server’s CompleteResult.

Task<void> ping()

Send a ping request to the connected server.

Fails with McpError (mcp::constants::jsonrpc::g_METHOD_NOT_FOUND) without sending anything in a modern session: protocol revision 2026-07-28 has no ping.

Returns:

A task that completes once the ping round-trip succeeds.

Task<void> cancel(const RequestId &request_id, const std::optional<std::string> &reason = std::nullopt)

Send a cancellation notification for an in-flight request.

To cancel a request without knowing its id, give it a CancellationToken in RequestOptions::cancellation instead.

Parameters:
  • request_id – The ID of the request to cancel.

  • reason – Optional human-readable reason for the cancellation.

Returns:

A task that completes when the cancellation notification has been sent.

void on_notification(const std::string &method, NotificationCallback callback)

Register a callback for incoming notifications from the server.

When the server sends a notification with the given method, the callback is invoked with the notification’s params JSON.

Parameters:
  • method – The notification method to listen for (e.g. “notifications/progress”).

  • callback – The callback to invoke when the notification arrives.

void on_progress(ProgressCallback callback)

Register a callback for progress notifications.

A notification whose token belongs to a request in flight with RequestOptions::on_progress set goes to that request’s callback instead.

Parameters:

callback – The callback invoked when a notifications/progress message arrives.

void on_request(const std::string &method, RequestHandler handler)

Register a handler for incoming requests from the server (reverse RPC).

When the server sends a request with the given method (e.g. “ping”, “sampling/createMessage”, “elicitation/create”, “roots/list”), the handler is invoked and its return value is sent back as the JSON-RPC response.

Parameters:
  • method – The request method to handle.

  • handler – The async handler that returns a result JSON.

void on_elicitation(std::function<Task<ElicitResult>(const ElicitRequestParams&)> handler)

Register a handler for incoming elicitation requests from the server.

Convenience wrapper that registers a request handler for “elicitation/create”. The handler receives ElicitRequestParams and returns ElicitResult. Accepted form content is checked against the request’s schema first, see ClientOptions::validate_elicitation_content.

Parameters:

handler – Async handler: receives ElicitRequestParams, returns ElicitResult.

void on_sampling(std::function<Task<CreateMessageResult>(const CreateMessageRequestParams&)> handler)

Register a handler for sampling requests from the server.

Deprecated:

doc-only: protocol revision 2026-07-28 deprecates sampling; see Deprecated Features on the Specification Support page for why the SDK keeps it.

Registers a request handler for “sampling/createMessage”: the handler receives the request’s CreateMessageRequestParams and returns the CreateMessageResult sent back. A modern server’s input_required sampling questions are answered by it too. Registering it declares the sampling capability, see connect().

Parameters:

handler – Async handler: receives CreateMessageRequestParams, returns CreateMessageResult.

void set_roots(const std::vector<Root> &roots, bool notify = false)

Set static roots and auto-register the roots/list handler.

Deprecated:

doc-only: protocol revision 2026-07-28 deprecates roots; see Deprecated Features on the Specification Support page for why the SDK keeps it.

Stores the given roots and registers a request handler for “roots/list” that returns them. If notify is true, sends a notifications/roots/list_changed notification to inform the server. A modern session has no such notification, and nothing is sent.

Parameters:
  • roots – The list of roots to provide.

  • notify – Whether to send a roots-changed notification.

void on_roots_list(std::function<Task<ListRootsResult>(const nlohmann::json&)> handler)

Register a dynamic handler for roots/list requests.

Deprecated:

doc-only: protocol revision 2026-07-28 deprecates roots; see Deprecated Features on the Specification Support page for why the SDK keeps it.

Parameters:

handler – Async handler that returns a ListRootsResult.

Blocking Calls

class SyncServer

Blocking twins of the Server’s notify_ coroutines, from Server::sync().

Each member runs the coroutine on the event loop of run_stdio() or run_http() and blocks the calling thread until it finishes, rethrowing what it throws. When the server is not running there is no client to notify, and the member returns at once; a run that ends before the notification is sent ends the wait as well.

Throws std::logic_error:

From each member when called on that event loop’s thread, where synchronous handlers run (except those set_handler_executor() moves) and waiting would never end; and when the server runs only through Server::run() or a StreamableHttpSessionManager, whose coroutines are awaited instead.

Public Functions

explicit SyncServer(Server &server)
void notify_tools_list_changed()

Blocking Server::notify_tools_list_changed().

void notify_resources_list_changed()

Blocking Server::notify_resources_list_changed().

void notify_prompts_list_changed()

Blocking Server::notify_prompts_list_changed().

void notify_resource_updated(const std::string &uri)

Blocking Server::notify_resource_updated().

class SyncClient

Blocking calls to a Client; see Client::sync().

Each method runs the Client coroutine member of the same name, with the same arguments, on the client’s event loop and returns its result or throws its exception. A SyncClient refers to its Client, which must outlive it.

Public Functions

explicit SyncClient(Client &client)
ConnectResult connect(std::string_view name, std::string_view version)

As Client::connect().

ConnectResult connect(const Implementation &client_info, const ClientCapabilities &capabilities)

As Client::connect().

nlohmann::json send_request(std::string_view method, const std::optional<nlohmann::json> &params, const RequestOptions &request_options = {})

As Client::send_request().

Subscription listen(const SubscriptionFilter &filter, const RequestOptions &request_options = {})

As Client::listen(); read the stream through Subscription::sync().

void send_notification(std::string_view method, const std::optional<nlohmann::json> &params)

As Client::send_notification().

void close()

As Client::close().

CallToolResult call_tool(const std::string &name, const nlohmann::json &arguments, const RequestOptions &request_options = {})

As Client::call_tool().

template<JsonSerializable Args>
inline CallToolResult call_tool(const std::string &name, const Args &arguments, const RequestOptions &request_options = {})

As Client::call_tool(), with arguments of a type that converts to JSON.

std::variant<CallToolResult, TaskHandle> start_tool(const std::string &name, const nlohmann::json &arguments, const RequestOptions &request_options = {})

As Client::start_tool(); follow a task through TaskHandle::sync().

ListToolsResult list_tools(const std::optional<std::string> &cursor = std::nullopt, const RequestOptions &request_options = {})

As Client::list_tools().

ListResourcesResult list_resources(const std::optional<std::string> &cursor = std::nullopt, const RequestOptions &request_options = {})

As Client::list_resources().

ReadResourceResult read_resource(const std::string &uri, const RequestOptions &request_options = {})

As Client::read_resource().

ListResourceTemplatesResult list_resource_templates(const std::optional<std::string> &cursor = std::nullopt, const RequestOptions &request_options = {})

As Client::list_resource_templates().

ListPromptsResult list_prompts(const std::optional<std::string> &cursor = std::nullopt, const RequestOptions &request_options = {})

As Client::list_prompts().

GetPromptResult get_prompt(const std::string &name, const std::map<std::string, std::string> &arguments = {}, const RequestOptions &request_options = {})

As Client::get_prompt().

CompleteResult complete(const CompleteParams &params, const RequestOptions &request_options = {})

As Client::complete().

void ping()

As Client::ping().

void cancel(const RequestId &request_id, const std::optional<std::string> &reason = std::nullopt)

As Client::cancel().

class SyncTaskHandle

Blocking calls to a TaskHandle; see TaskHandle::sync().

Public Functions

explicit SyncTaskHandle(TaskHandle handle)
DetailedTask get(const RequestOptions &request_options = {}) const

As TaskHandle::get().

void update(const nlohmann::json &input_responses, const RequestOptions &request_options = {}) const

As TaskHandle::update().

void cancel(const RequestOptions &request_options = {}) const

As TaskHandle::cancel().

DetailedTask wait(const RequestOptions &request_options = {}) const

As TaskHandle::wait().

CallToolResult result(const RequestOptions &request_options = {}) const

As TaskHandle::result().

class SyncSubscription

Blocking calls to a Subscription; see Subscription::sync().

Public Functions

explicit SyncSubscription(Subscription subscription)
std::optional<SubscriptionEvent> next()

As Subscription::next(), waiting for the next event or the end of the stream.

void close()

As Subscription::close().

Endpoint

class Endpoint

The server a Client connects to: a process it launches, an HTTP URL, or a transport the application makes.

A Client constructed from an Endpoint runs its own event loop on a thread of its own, so it can be used without an executor, through Client::sync() or Client::run().

Public Types

using TransportFactory = std::function<std::shared_ptr<ITransport>(const Executor&)>

Makes the transport for the event loop whose executor it is given.

Public Functions

std::shared_ptr<ITransport> make_transport(const Executor &executor) const

Make the transport for the event loop executor belongs to.

Public Static Functions

static Endpoint stdio(std::vector<std::string> command)

Launch command, the program followed by its arguments, and talk to it over its standard input and output.

A program without a directory is searched for in PATH; one with a directory is taken relative to the working directory.

Throws:

std::invalid_argument – If command is empty.

static Endpoint stdio(std::initializer_list<std::string> command)

As stdio() above, for a command written in place, such as Endpoint::stdio({"./server", "--verbose"}) or Endpoint::stdio({"./server"}).

static Endpoint stdio(StdioProcessOptions process)

Launch the process process describes, with its environment, working directory and standard error handling.

Throws:

std::invalid_argument – If process.command is empty.

static Endpoint stdio(std::vector<std::string> command, StdioRestartPolicy restart)

Launch a server as stdio() above, and start it again as restart allows when it ends without the client having asked it to, such as Endpoint::stdio({"./server"}, {.max_restarts = 3}).

The same Client goes on with the new process, keeping its handlers, callbacks and sync() view. The requests waiting for an answer when the process ended fail with McpError (mcp::constants::jsonrpc::g_CONNECTION_CLOSED); requests made while it starts again wait for it, within their own timeouts. A legacy session sends its initialize request to the new process again. Each open subscriptions/listen request is sent to the new process again, so its Subscription goes on. What the old process kept for a legacy session, such as a log level, resource subscriptions or tasks, is gone. A start that fails uses one of the restarts the policy allows; when it allows no more, the client closes as it does without a restart. StdioProcessOptions::on_exit runs for each process that ends.

static Endpoint stdio(std::initializer_list<std::string> command, StdioRestartPolicy restart)

As the stdio() overload above that takes a restart policy.

static Endpoint stdio(StdioProcessOptions process, StdioRestartPolicy restart)

As the stdio() overload above that takes a restart policy.

static Endpoint http(std::string url, HttpEndpointOptions options = {})

Talk to the server at url over Streamable HTTP.

static Endpoint custom(TransportFactory factory)

Use the transport factory makes, such as a WebSocketClientTransport or a transport of the application’s own.

Throws:

std::invalid_argument – If factory is empty.

Runtime

class Runtime

Manages the asynchronous I/O event loop used by transports and servers.

Public Functions

Runtime()
~Runtime()
Runtime(Runtime&&) noexcept
Runtime &operator=(Runtime&&) noexcept
Runtime(const Runtime&) = delete
Runtime &operator=(const Runtime&) = delete
void run()

Run the event loop (blocks until stop() or no more work).

Each call runs the loop again after an earlier run ended, unless start() has run it. A stop() made while nothing runs the loop makes the next run(), run(threads) or start() return without running it.

Throws:

What – a task given to spawn() throws, after which the loop may be run again.

void run(std::size_t threads)

Run the event loop on the calling thread and threads - 1 threads more, until stop() or no more work, and join them.

A task given to spawn() that throws stops the loop; its exception is rethrown here once every thread has returned. As with run(), each call runs the loop again after an earlier run ended.

Throws:

std::invalid_argument – When threads is 0.

void start(std::size_t threads)

Run the event loop on threads new threads until stop() or the Runtime’s destruction, which joins them, even while it has no work.

For an executor that waits for work, such as a pool of handler threads: pool.start(4); server.set_handler_executor(pool.executor());. An exception that a task given to spawn() throws on one of these threads is not caught there, so it ends the program, as an exception leaving any std::thread does. Starts no thread when a stop() came while nothing ran the loop (see run()).

Throws:
  • std::invalid_argument – When threads is 0.

  • std::logic_error – When the Runtime has been started already.

void stop()

Request the event loop to stop; threads start() made end once their current work does.

Made while nothing runs the loop, it ends the next run(), run(threads) or start() instead.

Executor executor()

The executor of the event loop, for Server::run(), Client(transport, executor), a transport’s constructor or Server::set_handler_executor().

void spawn(Task<void> task)

Start task on the event loop, such as runtime.spawn(server.run(transport, runtime.executor()));.

The task runs when run() does. An exception it throws comes out of run(). A program that calls spawn() includes <mcp/core/async.hpp>, which defines Task.

Throws:

std::invalid_argument – If task is empty.

Context

class Context

Request-scoped context provided to server handlers.

Each incoming request receives a Context that provides utilities for interacting with the client, such as sending log messages, reporting progress, checking cancellation, and performing reverse RPC (e.g. sampling). The Context holds a non-owning reference to the transport and a request sender callable, both of which must outlive the Context.

Public Functions

inline explicit Context(ITransport &transport)

Construct a Context with transport only (no reverse RPC support).

Parameters:

transport – Non-owning reference to the transport for sending notifications back to the client.

inline Context(ITransport &transport, RequestSender sender)

Construct a Context with transport and request sender.

Parameters:
  • transport – Non-owning reference to the transport.

  • sender – A callable that sends a JSON-RPC request and returns the result.

inline Context(ITransport &transport, RequestSender sender, std::shared_ptr<std::atomic<bool>> cancelled, std::optional<ProgressToken> progress_token, const std::atomic<LoggingLevel> *log_level, MessageSender message_sender = {}, std::shared_ptr<const RequestMetadata> request_meta = nullptr, std::shared_ptr<const std::string> principal = nullptr, std::shared_ptr<const std::atomic<bool>> replaying = nullptr)

Construct a full-featured Context with cancellation, progress, and log level.

Parameters:
  • transport – Non-owning reference to the transport.

  • sender – A callable that sends a JSON-RPC request and returns the result.

  • cancelled – Shared cancellation flag set by the server on notifications/cancelled.

  • progress_token – Optional progress token from the request’s _meta.

  • log_level – Pointer to the server’s current log level (shared across all contexts).

  • message_sender – Optional serialized notification sender. When omitted, Context writes directly to the transport.

  • request_meta – The per-request protocol fields of a 2026-07-28 request, or null for a request of an earlier revision.

  • principal – Who sent the request, or null when unknown.

  • replaying – True while the handler re-executes work an earlier round of the request already did, or null when it never does.

inline const RequestMetadata *request_meta() const

The per-request protocol fields of this request.

Returns:

The protocol version, client capabilities, client info, log level and whole _meta of a 2026-07-28 request, or null for a request of an earlier revision, which negotiated these at initialize.

inline std::string_view principal() const

Who sent this request.

Over HTTP with a bearer token validator, this is the principal the validator named in its TokenValidation; without one, h: followed by the hex SHA-256 of the request’s Authorization header, which never reveals the token and changes when the token does. It is empty for a transport that does not authenticate its peer (stdio, WebSocket, memory), for a request without an Authorization header, and for the requests of a StreamableHttpSessionManager session, which are attributed to the session.

Returns:

The principal, or an empty view when it is unknown.

inline bool is_replay() const

Whether the handler is re-executing work an earlier round of the request did.

With sealed request state (MrtrStateMode::eSealed) every retry of a multi round-trip request runs the handler again from the start, and the questions earlier rounds answered return their answers at once. This is true from the start of such a run until the handler has taken the last of those answers or asks a question they do not answer; what the handler does after that is new. A handler that does not ask again sees true until it ends. Guard side effects, such as writes or charges, with if (!ctx.is_replay()). It is always false for a first run, for stored request state, and for every other kind of request.

Returns:

True while the handler is replaying.

Task<void> log_info(std::string_view msg)

Sends an informational log message to the client.

Deprecated:

doc-only: protocol revision 2026-07-28 deprecates logging; see Deprecated Features on the Specification Support page for why the SDK keeps it.

Parameters:

msg – The log message to send.

Returns:

A task that completes when the message is sent.

Task<void> log(LoggingLevel level, std::string_view msg, const std::optional<std::string> &logger = std::nullopt)

Send a log message at a specific level.

Deprecated:

doc-only: protocol revision 2026-07-28 deprecates logging; see Deprecated Features on the Specification Support page for why the SDK keeps it.

Respects the server’s current log level. Messages with a level higher (less severe) than the current threshold are silently dropped. LoggingLevel ordering: Emergency(0) < Alert(1) < … < Debug(7). A message is sent only if its level <= current server log level.

A 2026-07-28 request has no session level: its threshold is the io.modelcontextprotocol/logLevel in its _meta, and without one nothing is sent. A message over the limit of Server::set_notification_rate_limit() is dropped.

Parameters:
  • level – The severity level of the log message.

  • msg – The log message to send.

  • logger – Optional logger name.

Returns:

A task that completes when the message is sent (or immediately if filtered).

inline bool is_cancelled() const

Check whether the current request has been cancelled.

Returns:

true once the request has been cancelled: by notifications/cancelled for this request’s ID, by the client disconnecting while a 2026-07-28 request runs on StreamableHttpSessionManager, or through the cancellation flag given to Server::dispatch_request_direct(). The server reads a cancellation on its event loop, which a synchronous handler running there holds up: such a handler sees it only on the executor of Server::set_handler_executor().

Task<void> report_progress(double progress, std::optional<double> total = std::nullopt, const std::optional<std::string> &message = std::nullopt)

Report progress for the current request.

Sends a notifications/progress notification to the client. Uses the progress token extracted from the request’s _meta.progressToken. If no progress token was provided in the request, this is a no-op. A notification over the limit of Server::set_notification_rate_limit() is dropped.

In a task (see Server::enable_tasks()) the progress becomes the task’s status message instead, and no notification is sent.

Parameters:
  • progress – The current progress value.

  • total – Optional total progress value.

  • message – Optional human-readable progress message.

Returns:

A task that completes when the notification is sent.

inline bool report_progress_sync(double progress, std::optional<double> total = std::nullopt, const std::optional<std::string> &message = std::nullopt)

Report progress without suspending, for a handler that is not a coroutine.

In a task (see Server::enable_tasks()) the progress becomes the task’s status message, as report_progress() does. Elsewhere the report would need a write, which a call that does not suspend cannot make, so nothing is sent: use report_progress().

Parameters:
  • progress – The current progress value.

  • total – Optional total progress value.

  • message – Optional human-readable progress message.

Returns:

Whether the progress was reported.

inline void set_progress_sink(ProgressSink sink)

Sets where this context’s progress goes instead of the client, which the server does for the handler of a task.

Task<CreateMessageResult> sample_llm(const CreateMessageRequestParams &request, InputOptions options = {})

Request the client to sample an LLM (reverse RPC).

Deprecated:

doc-only: protocol revision 2026-07-28 deprecates sampling; see Deprecated Features on the Specification Support page for why the SDK keeps it.

Sends a “sampling/createMessage” request to the client and awaits the response. Requires the Context to be constructed with a RequestSender.

For a 2026-07-28 tools/call, prompts/get or resources/read, the question goes back to the client in the request’s input_required result, and the call returns once the client retries the request with the answer; see Server::set_mrtr_options(). If the client did not declare the capability the question needs (sampling.context for an includeContext other than “none”), the request is answered with mcp::constants::jsonrpc::g_MISSING_REQUIRED_CLIENT_CAPABILITY and the call throws, as it does when the client never retries in time; the handler’s own answer then goes nowhere. Any other 2026-07-28 request cannot ask the client anything, and the call throws std::runtime_error.

Parameters:
  • request – The sampling request parameters.

  • options – How the question is named in a multi round-trip request; see InputOptions.

Throws:
  • std::runtime_error – If no request sender is available.

  • std::invalid_argument – If options.key is empty, reserved or already used, in a 2026-07-28 request (other requests ignore the key), or if includeContext is other than “none” in a session whose client did not declare sampling.context in its initialize request.

Returns:

A task that resolves to the client’s CreateMessageResult.

Task<ElicitResult> elicit(const ElicitRequestParams &params, InputOptions options = {})

Elicit additional information from the user via the client (reverse RPC).

Sends an “elicitation/create” request to the client and awaits the response. Supports both form mode (ElicitRequestFormParams) and URL mode (ElicitRequestURLParams) via the ElicitRequestParams variant.

Before 2026-07-28 a URL-mode request needs an elicitationId, and one is generated when the request leaves it unset; a 2026-07-28 question carries none.

A form-mode answer with action accept is checked against the request’s requestedSchema before it is returned, as the specification asks servers to do; a URL-mode answer carries no content and is not checked.

For a 2026-07-28 tools/call, prompts/get or resources/read, the question goes back to the client in the request’s input_required result, and the call returns once the client retries the request with the answer; see Server::set_mrtr_options(). If the client did not declare the capability the question needs, the request is answered with mcp::constants::jsonrpc::g_MISSING_REQUIRED_CLIENT_CAPABILITY and the call throws, as it does when the client never retries in time; the handler’s own answer then goes nowhere. Any other 2026-07-28 request cannot ask the client anything, and the call throws std::runtime_error.

Parameters:
  • params – The elicitation request parameters (form or URL mode).

  • options – How the question is named in a multi round-trip request, and whether an accepted form answer is checked; see InputOptions.

Throws:
  • std::invalid_argument – If options.key is empty, reserved or already used, in a 2026-07-28 request (other requests ignore the key).

  • std::runtime_error – If no request sender is available, or the accepted content does not conform to the schema (the message lists the violations). A schema the SDK cannot compile leaves the content unchecked.

Returns:

A task that resolves to the client’s ElicitResult.

Task<ListRootsResult> request_roots(InputOptions options = {})

Request the list of roots from the client (reverse RPC).

Deprecated:

doc-only: protocol revision 2026-07-28 deprecates roots; see Deprecated Features on the Specification Support page for why the SDK keeps it.

Sends a “roots/list” request to the client and awaits the response. The client provides its configured root URIs.

For a 2026-07-28 tools/call, prompts/get or resources/read, the question goes back to the client in the request’s input_required result, and the call returns once the client retries the request with the answer; see Server::set_mrtr_options(). If the client did not declare the capability the question needs, the request is answered with mcp::constants::jsonrpc::g_MISSING_REQUIRED_CLIENT_CAPABILITY and the call throws, as it does when the client never retries in time; the handler’s own answer then goes nowhere. Any other 2026-07-28 request cannot ask the client anything, and the call throws std::runtime_error.

Parameters:

options – How the question is named in a multi round-trip request; see InputOptions.

Throws:
  • std::runtime_error – If no request sender is available.

  • std::invalid_argument – If options.key is empty, reserved or already used, in a 2026-07-28 request (other requests ignore the key).

Returns:

A task that resolves to the client’s ListRootsResult.

Friends

friend struct detail::ContextRouting

Transport Interface

class ITransport

Abstract transport interface for MCP message exchange.

Implementations handle the underlying I/O mechanism (stdio, WebSocket, etc.) for reading and writing JSON-RPC messages.

Subclassed by mcp::HttpClientTransport, mcp::HttpServerTransport, mcp::MemoryTransport, mcp::StdioClientTransport, mcp::StdioTransport, mcp::WebSocketClientTransport, mcp::WebSocketServerTransport, mcp::auth::OAuthClientTransport

Public Types

using InteractionObserver = std::function<void(std::string_view request_key, bool waiting)>

Callback with which a transport reports that the write of a request is waiting for a person.

Param request_key:

Correlation key of the JSON-RPC request being written (RequestId::correlation_key()).

Param waiting:

True when the wait begins, false when it ends. Every call with true is followed by exactly one call with false for the same key, on every path including a failed or cancelled write.

Public Functions

virtual ~ITransport() = default
ITransport() = default
ITransport(const ITransport&) = delete
ITransport &operator=(const ITransport&) = delete
ITransport(ITransport &&other) = default

Move-construct the transport interface.

Parameters:

other – Transport interface state to move from.

ITransport &operator=(ITransport &&other) = default

Move-assign the transport interface.

Parameters:

other – Transport interface state to move from.

Returns:

A reference to this transport interface.

virtual Task<std::string> read_message() = 0

Read the next serialized MCP message from the transport.

Throws:

TransportError – If the transport is closed while waiting, or the read fails.

Returns:

A task that resolves to the next complete JSON-RPC message.

virtual Task<IncomingMessage> read_incoming()

Read the next message together with the principal that sent it.

Server::run() reads through this. A transport that authenticates each message, such as HttpServerTransport with a bearer token validator, overrides it so that every message stays bound to its own sender, however many senders’ messages are queued. A transport that wraps another forwards this as well as read_message(), or its messages arrive without a principal.

Throws:

TransportError – If the transport is closed while waiting, or the read fails.

Returns:

A task that resolves to the next message; the default reads read_message() and gives it an empty principal.

virtual Task<void> write_message(std::string_view message) = 0

Write a serialized MCP message to the transport.

Parameters:

message – The complete JSON-RPC message to send.

Throws:

TransportError – If the transport is closed, or the write fails.

Returns:

A task that completes once the message has been accepted by the transport.

Write a message a server sends while it serves a client request of protocol revision 2025-11-25 or earlier: a notification about that request, or a request of its own.

A transport that answers each client request on a stream of its own, such as StreamableHttpSessionManager and HttpServerTransport, sends the message on the stream of that request, as the specification asks. A transport that wraps another forwards this as well as write_message().

Parameters:
  • message – The complete JSON-RPC message to send.

  • related_request – The id of the client request, as JSON text, such as 7 or "seven".

Throws:

TransportError – If the transport is closed, or the write fails.

Returns:

A task that completes once the message has been accepted by the transport; the default writes it with write_message().

virtual void close() = 0

Close the transport and release underlying resources.

Implementations should wake any pending readers and make future read/write operations fail fast.

inline virtual HttpServerTransport *http_server_transport() noexcept

The HttpServerTransport whose messages this transport carries, if any.

Server::run() serves an HttpServerTransport specially: an HTTP DELETE ends the session, the Mcp-Param-* headers of 2026-07-28 tools/call requests are checked against their arguments, and the notifications of 2026-07-28 requests are not sent. A transport that wraps an HttpServerTransport overrides this to return the wrapped one, so it is served the same way.

Returns:

This transport when it is an HttpServerTransport, the wrapped one for a wrapper, and null otherwise (the default).

inline virtual StdioTransport *stdio_transport() noexcept

The StdioTransport whose messages this transport carries, if any.

When the input of a StdioTransport ends, Server::run() tells the running handlers to stop and writes their answers, and every answer already queued, before it closes the transport. A transport that wraps a StdioTransport overrides this to return the wrapped one, so it is served the same way; otherwise the transport is closed first and those answers are lost.

Returns:

This transport when it is a StdioTransport, the wrapped one for a wrapper, and null otherwise (the default).

inline virtual bool overlapping_writes() const noexcept

Whether write_message() calls may overlap.

True for a transport that gives each message its own exchange, so one that waits for its answer holds nothing else back. Client writes each message beside the queue of the others on such a transport.

inline virtual void set_interaction_observer(InteractionObserver observer)

Install the observer a transport tells when a write waits for a person.

Client installs one so that the time a request spends waiting for a person, such as an OAuth consent prompt run by OAuthClientTransport, does not count against that request’s deadline. The observer may be called from any thread. A transport that never waits for a person ignores it (the default).

Parameters:

observer – The observer, replacing any earlier one; empty to remove it.

HTTP Transports

class HttpClientTransport : public mcp::ITransport

HTTP transport implementation for MCP client message exchange.

Sends JSON-RPC messages via HTTP POST to an MCP Streamable HTTP endpoint. Supports both application/json and text/event-stream response content types.

An https:// URL is reached over TLS, with the server’s certificate checked against the system’s certificate authorities (see set_tls()).

Each message goes on an exchange of its own, so requests overlap, and an event stream is read as it comes: a request the server sends while it handles one of the client’s reaches the client at once. In a session of protocol revision 2025-11-25 or earlier, the transport opens the session’s GET stream after notifications/initialized, for what the server sends outside any request, and opens it again from its last event when it ends; a server that answers that GET with 405 is not asked again. A request’s stream that ends before its response is resumed with a GET that names its last event.

An exchange goes on a connection that an earlier one read to the end, when the server left it open. Up to four such connections are kept; one that sat idle for 90 seconds, or that the server has closed, is not used again.

Public Functions

HttpClientTransport(const Executor &executor, const std::string &url)

Construct an HTTP client transport.

Parameters:
Throws:

std::invalid_argument – If the URL is malformed, carries credentials, or uses another scheme.

~HttpClientTransport() override
HttpClientTransport(const HttpClientTransport&) = delete
HttpClientTransport &operator=(const HttpClientTransport&) = delete
HttpClientTransport(HttpClientTransport&&) = delete
HttpClientTransport &operator=(HttpClientTransport&&) = delete
std::string session_id() const

Get the currently active MCP session identifier.

Returns:

The session identifier captured from server responses, or an empty string if no session exists.

std::string last_event_id() const

Get the id of the last whole event in an event stream of a session of protocol revision 2025-11-25 or earlier, which a resume sends as Last-Event-ID.

The event streams of 2026-07-28 requests are not resumed, so their event ids are not kept.

Returns:

The event id, or an empty string if no event named one.

void set_reinitialize_on_expired_session(bool enabled)

Whether to start a new session when the server answers 404 for the current one.

On by default. A server ends a session it has forgotten, for instance after its idle timeout, and answers its requests 404; the client must then start a new one. The transport sends the initialize request that began the session again, then notifications/initialized, and sends the failed request once more in the new session. What the server kept for the old session, such as resource subscriptions and the log level, is gone. When this is off, the request fails with HttpStatusError 404. When the new session cannot be started, the request fails with the error that start met, and the next request tries to start one again. When the server answers the new initialize with another protocol version or other capabilities, the request fails as well, since the Client still knows the server by the old ones; connect again to use the new session.

void set_bearer_token_provider(std::function<std::string()> provider)

Configure a provider for HTTP Authorization: Bearer headers.

Returning an empty string omits the header. Safe to call at any time, including while requests are in flight: each request pins the provider installed when it started, so a request already running keeps its provider and the next one picks up the new value. With an http:// URL whose host is not a loopback one, the warning handler is told once that tokens travel without TLS.

void set_warning_handler(std::function<void(const std::string&)> handler)

Configure a receiver for warnings about the connection and what the server sent.

A tool whose x-mcp-header annotations break the rules of the Streamable HTTP specification is left out of the result of tools/list when the client speaks protocol revision 2026-07-28; the handler is told which tool and why, on the transport’s executor. A bearer token provider on an http:// URL whose host is not a loopback one gets one warning, on the thread that starts the first request. The handler must not block.

void set_response_timeout(std::chrono::milliseconds timeout)

Limit the wait for the response to a request sent to a server of an older protocol.

Past it the connection that waits is closed and the request fails. The default is ten minutes; ClientOptions::request_timeout still decides how long a caller waits. Zero, a negative value, or one too long for the clock to represent disables it. Requests of protocol revision 2026-07-28 have no such limit.

void set_tls(const TlsClientOptions &options)

Use these TLS settings for the connections opened from now on.

Without a call, an https:// server’s certificate is checked against the system’s certificate authorities.

Throws:
  • std::invalid_argument – If the URL is not https://.

  • TlsConfigError – If the options cannot be used.

void set_tls(std::shared_ptr<const TlsClientContext> context)

Use a shared TLS context for the connections opened from now on; see set_tls().

void set_server_name(std::string name)

Check the server’s certificate against name instead of the URL’s host, and send it as the TLS server name.

For a server reached by an address or an alias its certificate does not name.

Throws:

std::invalid_argument – If the URL is not https:// or name is empty.

void set_proxy(ProxyOptions options)

Send the connections opened from now on through an HTTP proxy.

Without a call the transport connects directly. Pass ProxyOptions::from_environment() to use the proxy the environment names.

Throws:

std::invalid_argument – If a proxy URL is malformed or not supported.

virtual Task<std::string> read_message() override

Dequeue the next MCP message received from the server.

Throws:

TransportError – If the transport is closed.

virtual Task<void> write_message(std::string_view message) override

Send an MCP JSON-RPC message to the server via HTTP POST.

Parameters:

message – Serialized JSON-RPC message body.

Throws:
  • TransportError – When the transport is closed or the request cannot reach the server.

  • HttpStatusError – When the server answers with an HTTP error status.

virtual void close() override

Close the transport and release connection resources.

inline virtual bool overlapping_writes() const noexcept override

True: each message has its own exchange.

class HttpServerTransport : public mcp::ITransport

HTTP server transport for MCP Streamable HTTP.

Accepts HTTP connections, processes inbound JSON-RPC messages, and routes outbound responses back to their matching HTTP requests. Supports SSE replay via an in-memory event store.

In its legacy session, a POST from a client that accepts SSE over HTTP/1.1 is answered with a stream once the server sends anything else for the request first, such as a notification or a request of its own: those go on the stream as they come, and the response ends it. A GET opens the session’s stream for messages that belong to no request, and a GET with Last-Event-ID resumes a stream from there, still live when it has not ended.

Alongside its one legacy session, it serves requests of protocol revision 2026-07-28, which need no session: their mirrored headers are checked, they are answered with the status the specification gives their errors, and they never read or receive Mcp-Session-Id. The answer is plain JSON unless a handler sends a notification (a log message, progress) while serving the request and the client accepts text/event-stream: then it becomes an SSE stream carrying those notifications and finally the response. A subscriptions/listen request is an SSE stream that lasts until the client closes it or the server ends the subscription. A client that disconnects while its request runs cancels it, and so does a reset after a half-close. A client that accepts text/event-stream and half-closes gets an SSE stream even when no notification is sent, carrying comments that probe whether it is still there, because a client that closed cleanly cannot be told from one that only half-closed until a write fails; the HTTP status of such an answer is 200 even for an error, which the JSON-RPC body still carries. Notifications wait in a queue limited by StreamOptions::max_queued_notifications and max_queued_bytes. These requests are served once a Server::run() reads from the transport; before that they reach whoever calls read_message().

Public Functions

HttpServerTransport(const Executor &executor, std::string host, unsigned short port, std::size_t event_store_capacity = mcp::constants::event_store::g_DEFAULT_CAPACITY)

Construct an HTTP server transport bound to a host and port.

Parameters:
  • executor – Executor used for asynchronous operations.

  • host – Local bind address.

  • port – Local bind port.

  • event_store_capacity – Maximum number of replayable SSE events to retain.

~HttpServerTransport() override
HttpServerTransport(const HttpServerTransport&) = delete
HttpServerTransport &operator=(const HttpServerTransport&) = delete
HttpServerTransport(HttpServerTransport&&) = delete
HttpServerTransport &operator=(HttpServerTransport&&) = delete
const EventStore &event_store() const

Access the event store used for SSE replay support.

Returns:

A const reference to the transport’s in-memory event store.

unsigned short port() const

Get the local port currently bound by the HTTP acceptor.

This is useful when the transport is constructed with port 0 and the operating system assigns an ephemeral port.

void set_json_only(bool json_only)

Enable or disable JSON-only responses.

When enabled, HTTP POST responses always use application/json and outbound responses are not copied into the SSE replay event store. This option is atomic and may be changed while the listener is running.

Parameters:

json_only – True to bypass SSE framing and event storage.

void set_stream_options(StreamOptions options)

Set how the answer to a 2026-07-28 request is streamed.

Throws:
  • std::invalid_argument – If an interval is not positive, or max_queued_notifications or max_queued_bytes is zero.

  • std::logic_error – If listen() has already been called or the transport is closed.

StreamStats stream_stats() const

What the 2026-07-28 streams of this transport have done.

void set_allowed_origins(std::vector<std::string> origins)

Replace the allowlist used for requests carrying an Origin header.

Requests without an Origin header remain valid for non-browser MCP clients. An Origin header is rejected by default until its exact value appears in this allowlist. Configure the allowlist before listen() or run() starts.

Throws:

std::logic_error – If listen() has already been called or the transport is closed.

void set_allow_all_origins(bool allow_all)

Explicitly opt into accepting every Origin header value.

Configure this before listen() or run() starts.

Throws:

std::logic_error – If listen() has already been called or the transport is closed.

void set_allowed_hosts(const std::vector<std::string> &hosts)

Serve only requests whose Host header names one of hosts.

Without a list, a request that reaches the transport through a loopback address must name a loopback host in its Host header, localhost or a loopback address, or it is answered 403; through other addresses Host is not checked. This defends a local server against DNS rebinding. A reverse proxy on the same machine that passes on the public name in Host needs that name listed. With a list, every request must name a host on it, whatever address it reached, so list localhost too if local clients use it. Names compare without the port and regardless of case. An empty list restores the loopback rule.

Throws:
  • std::invalid_argument – If an entry names no host.

  • std::logic_error – If listen() has already been called or the transport is closed.

void set_tls(const TlsServerOptions &options)

Accept connections over TLS with these settings.

Every connection must then complete a TLS handshake, within the options’ handshake_timeout, before a request is read; one that does not is closed. With ClientAuth::eRequired, a client must show a certificate from one of the named client authorities.

Throws:
  • TlsConfigError – If the options cannot be used.

  • std::logic_error – If listen() has already been called or the transport is closed.

void set_tls(std::shared_ptr<const TlsServerContext> context)

Accept connections over TLS with a context created before; see set_tls().

A null context serves plain TCP again.

Throws:

std::logic_error – If listen() has already been called or the transport is closed.

void set_bearer_token_validator(BearerTokenValidator validator)

Require and validate an HTTP Authorization: Bearer header.

Passing an empty validator disables HTTP authentication. Configure the validator before listen() or run() starts.

A request whose token the validator refuses is answered 401 with the bearer challenge. A validator that throws is answered 500, without a challenge, so a failing introspection endpoint does not send clients into re-authorization. A validator that accepts a token may name the principal it stands for (TokenValidation); handlers see it as Context::principal().

Throws:

std::logic_error – If listen() has already been called or the transport is closed.

void set_async_bearer_token_validator(AsyncBearerTokenValidator validator)

Require an Authorization: Bearer header and validate it asynchronously.

Use this when the decision needs I/O – token introspection, a JWKS fetch – so it suspends instead of blocking the executor that is concurrently serving MCP traffic.

Passing an empty validator disables HTTP authentication. Configure the validator before listen() or run() starts.

A request whose token the validator refuses is answered 401 with the bearer challenge. A validator that throws is answered 500, without a challenge, so a failing introspection endpoint does not send clients into re-authorization. A validator that accepts a token may name the principal it stands for (TokenValidation); handlers see it as Context::principal().

Throws:

std::logic_error – If a synchronous validator is already installed, or if listen() has already been called or the transport is closed.

void set_max_request_body_bytes(std::size_t max_bytes)

Cap the HTTP request body this transport will read.

A request whose body exceeds the cap is answered 413 Payload Too Large and its connection is closed; it never reaches MCP dispatch. Defaults to mcp::constants::http_server::g_DEFAULT_MAX_REQUEST_BODY_BYTES. Binary content travels as base64 inside the JSON body, so a cap near the size of the raw content rejects it.

The body is read, up to this cap, before the origin and bearer token are checked, so the cap is also what one unauthenticated connection can make the transport buffer. The body is parsed as JSON only after those checks pass.

Configure the cap before listen() or run() starts.

Throws:
  • std::invalid_argument – If max_bytes is zero.

  • std::logic_error – If listen() has already been called or the transport is closed.

void set_connection_limits(const HttpConnectionLimits &limits)

Set what the connections and requests of this transport may hold at once.

The headers of a request are read first, and the Origin and bearer token checks run on them, so a request they refuse never has its body read. See HttpConnectionLimits for the defaults. Must be called before listen().

Throws:

std::invalid_argument – If max_requests or max_request_bytes is 0.

void set_session_idle_timeout(std::chrono::milliseconds timeout)

Set how long a session may sit idle before a new client can take its place.

This transport serves one session at a time. Without this, a client that left without a DELETE would keep every other client out until the process restarts. An initialize then ends a session that has no request waiting and has been idle this long.

Parameters:

timeout – The time, or zero to keep a session until its DELETE. The default is five minutes.

void set_bearer_challenge(BearerChallengeConfig challenge)

Set the parameters sent in the WWW-Authenticate header of every 401.

Without this call the transport sends the bare Bearer challenge. A client that has to discover where to obtain a token needs at least resource_metadata; setting protected resource metadata fills that field in automatically when it is left empty here.

Configure the challenge before listen() or run() starts.

Throws:
  • std::invalid_argument – If a challenge value cannot be sent in a quoted-string.

  • std::logic_error – If listen() has already been called or the transport is closed.

void set_scope_requirements(ScopeRequirementProvider provider)

Name the scopes each request needs, so a token without them is answered 403.

After a validator accepts a token, the provider is asked about every POSTed JSON-RPC message that has a method (see ScopeRequirementProvider). When the token’s scopes (TokenValidation::scopes) lack one the provider named, the message is not dispatched and no response stream is opened: the answer is 403 with a WWW-Authenticate: Bearer error="insufficient_scope", scope="...", resource_metadata="..." challenge naming every scope the operation needs, which a client such as OAuthClientTransport answers by authorizing again with the wider scope. The challenge keeps the realm and metadata URL of set_bearer_challenge() and set_protected_resource_metadata(). A validator that reports no scopes grants none, so a request that needs a scope is refused. Requests that carry no JSON-RPC method (answers to the server’s own requests, GET and DELETE) are not checked.

The scopes the provider returns are written into the challenge as quoted header text, so each must consist of printable ASCII (0x20-0x7E); a provider that returns anything else is answered 500 with no challenge, as one that throws is.

Passing an empty provider removes the check. Configure it before listen() or run() starts. A provider needs a token validator to report the scopes a token holds, so listen() throws when one is set without the other, whichever was set first.

Throws:

std::logic_error – If listen() has already been called or the transport is closed. listen() also throws it when a provider is set and no validator is.

void set_protected_resource_metadata(ProtectedResourceMetadataConfig metadata)

Serve an RFC 9728 protected-resource metadata document.

The document answers GET requests at its configured path without an Authorization header. When the bearer challenge carries no resource_metadata, it is populated with this document’s URL.

Configure the metadata before listen() or run() starts.

Throws:
  • std::invalid_argument – If resource is empty or is not an absolute URL.

  • std::logic_error – If listen() has already been called or the transport is closed.

void set_unauthenticated_paths(std::vector<std::string> paths)

Exempt request paths from bearer validation and exclude them from MCP dispatch.

An entry is excused from the bearer check and also removed from the set of paths MCP answers: if the protected-resource metadata route does not claim it, the request is answered 404 Not Found rather than dispatched, so MCP is never served without authentication on an exempt path.

Each entry is compared for equality against the path component of the request target, with any query string or fragment removed first, so /health also exempts /health?probe=1. Empty by default.

This transport has no custom request handler, so an exempt path other than the metadata route is always answered 404. Serving a health check without a token needs StreamableHttpSessionManager, whose custom request handler can claim the path.

Configure the paths before listen() or run() starts.

Throws:

std::logic_error – If listen() has already been called or the transport is closed.

std::uint64_t header_mismatch_rejections() const

2026-07-28 requests refused with mcp::constants::jsonrpc::g_HEADER_MISMATCH because their MCP-Protocol-Version, Mcp-Method, Mcp-Name or Mcp-Param-* header was missing, malformed, repeated or did not match the body.

virtual Task<std::string> read_message() override

Read the next queued JSON-RPC message from HTTP POST bodies.

virtual Task<IncomingMessage> read_incoming() override

Read the next queued JSON-RPC message with the principal of the request that carried it.

The principal is the id the bearer token validator returned in TokenValidation, or else h: followed by the hex SHA-256 of the request’s bearer token, or of its Authorization header when that holds no bearer token, or empty when the request had none. It is kept with each queued message, so the requests of several clients waiting together are each attributed to their own sender.

virtual Task<void> write_message(std::string_view message) override

Send a JSON-RPC message: a response answers its pending HTTP request, and any other message goes on the session’s GET stream, or on the stream of the only request waiting when no GET opened one.

Parameters:

message – Serialized JSON-RPC message.

Send a message the server sends while it serves a request, on that request’s stream while it waits, or as write_message() does otherwise.

Parameters:
  • message – Serialized JSON-RPC message.

  • related_request – The id of the client request, as JSON text.

virtual void close() override

Close the transport and stop accepting connections.

Task<void> listen()

Start accepting HTTP connections.

Returns:

A task that completes when the accept loop exits.

inline virtual HttpServerTransport *http_server_transport() noexcept override

This transport, which Server::run() serves as an HttpServerTransport.

class StreamableHttpSessionManager

Multi-session HTTP endpoint for MCP Streamable HTTP.

Manages multiple concurrent MCP sessions over a single HTTP port. Each session is backed by its own Server + MemoryTransport pair. Requests are routed by the MCP-Session-Id header. New sessions are created on initialize requests that arrive without a session ID.

This matches the behavior of Python’s StreamableHTTPSessionManager and Go’s StreamableHTTPServer: session creation on initialize, 404 on unknown sessions, DELETE for session teardown.

A request of protocol revision 2026-07-28 needs no session. Its answer is plain JSON unless a handler sends a notification (a log message, progress) while serving it and the client accepts text/event-stream: then the answer becomes an SSE stream carrying those notifications and finally the response. A client that accepts text/event-stream and half-closes its connection while the request runs gets an SSE stream as well, carrying comments that probe whether the client is still there, and then the response: a client that closed cleanly cannot be told from one that only half-closed until a write fails. The HTTP status of such an answer is 200 even for an error, which the JSON-RPC body still carries. A client that disconnects while its request runs cancels it, and so does a reset after a half-close. Notifications wait in a queue limited by StreamOptions::max_queued_notifications and max_queued_bytes.

This class is NOT an ITransport. It owns the HTTP listener and manages the full lifecycle of per-session Server instances.

Usage:

asio::io_context io_ctx;

auto server_factory = [](const mcp::Executor&) {
    ServerCapabilities caps;
    caps.tools = ServerCapabilities::ToolsCapability{};
    Implementation info{"my-server", "1.0"};
auto server = std::make_unique<Server>(info, std::move(caps));
    server->add_tool<json, json>("echo", "Echo tool", schema, handler);
return server;
};

StreamableHttpSessionManager manager(io_ctx.get_executor(), "0.0.0.0", 8080,
                                      std::move(server_factory));
asio::co_spawn(io_ctx, manager.listen(), asio::detached);
io_ctx.run();

Public Types

using ServerFactory = std::function<std::unique_ptr<Server>(const Executor&)>

Callback that creates a configured Server instance for a new session.

Public Functions

StreamableHttpSessionManager(const Executor &executor, std::string host, unsigned short port, ServerFactory factory, std::size_t event_store_capacity = mcp::constants::event_store::g_DEFAULT_CAPACITY)

Construct a multi-session HTTP endpoint.

Parameters:
  • executor – Executor for async operations.

  • host – Local bind address.

  • port – Local bind port.

  • factory – Callback that creates a configured Server for each new session.

  • event_store_capacity – Per-session event store capacity.

StreamableHttpSessionManager(const Executor &executor, std::string host, unsigned short port, Server &server, std::size_t event_store_capacity = mcp::constants::event_store::g_DEFAULT_CAPACITY)

Construct a multi-session HTTP endpoint that serves server, as Server::run_http() does, on the program’s own event loop.

server answers the 2026-07-28 requests, and each session of an older revision is served by a server that shares its tools, resources, prompts, handlers and settings, so the members of server that belong to one session, such as Server::send_request(), stand for none of them. set_protocol_policy() and set_tool_executor() set them on server itself, and a policy set with Server::set_protocol_policy() before listen() holds for the endpoint as one set here does. While listen() runs, Server::stop() closes the manager. server must outlive the manager and the task listen() returns.

Parameters:
  • executor – Executor for async operations.

  • host – Local bind address.

  • port – Local bind port, or 0 for one the system chooses (see port()).

  • server – The server to serve.

  • event_store_capacity – Per-session event store capacity.

~StreamableHttpSessionManager()
StreamableHttpSessionManager(const StreamableHttpSessionManager&) = delete
StreamableHttpSessionManager &operator=(const StreamableHttpSessionManager&) = delete
StreamableHttpSessionManager(StreamableHttpSessionManager&&) = delete
StreamableHttpSessionManager &operator=(StreamableHttpSessionManager&&) = delete
unsigned short port() const

The local port the manager listens on: the one the constructor was given, or the one the system chose when it was given 0.

void set_allowed_origins(std::vector<std::string> origins)

Replace the allowlist used for requests carrying an Origin header.

Requests without an Origin header remain valid. Browser-originated requests are denied by default until their exact Origin value is present in this list. Configure the allowlist before listen() starts.

Throws:

std::logic_error – If listen() has already been called or the manager is closed.

void set_allow_all_origins(bool allow_all)

Explicitly opt into accepting every Origin header value before listen() starts.

Throws:

std::logic_error – If listen() has already been called or the manager is closed.

void set_allowed_hosts(const std::vector<std::string> &hosts)

Serve only requests whose Host header names one of hosts, before listen() starts.

The rule is HttpServerTransport::set_allowed_hosts()’s: without a list, a request that reaches the manager through a loopback address must name a loopback host or is answered 403, against DNS rebinding; with one, every request must name a listed host.

Throws:
  • std::invalid_argument – If an entry names no host.

  • std::logic_error – If listen() has already been called or the manager is closed.

void set_tls(const TlsServerOptions &options)

Accept connections over TLS with these settings, before listen() starts; see HttpServerTransport::set_tls().

Throws:
  • TlsConfigError – If the options cannot be used.

  • std::logic_error – If listen() has already been called or the manager is closed.

void set_tls(std::shared_ptr<const TlsServerContext> context)

Accept connections over TLS with a context created before.

A null context serves plain TCP again.

Throws:

std::logic_error – If listen() has already been called or the manager is closed.

void set_bearer_token_validator(BearerTokenValidator validator)

Require and validate an HTTP Authorization: Bearer header.

Passing an empty validator disables HTTP authentication. Configure the validator before listen() starts.

A request whose token the validator refuses is answered 401 with the bearer challenge. A validator that throws is answered 500, without a challenge, so a failing introspection endpoint does not send clients into re-authorization. A validator that accepts a token may name the principal it stands for (TokenValidation); handlers of requests served without a session see it as Context::principal(). A session belongs to the principal that created it: another principal gets 404. Without a named principal a token counts as one by itself, so a client that refreshes its token starts a new session; naming the principal avoids that. Without a validator, a session is not bound to the Authorization header.

Throws:

std::logic_error – If listen() has already been called or the manager is closed.

void set_async_bearer_token_validator(AsyncBearerTokenValidator validator)

Require an Authorization: Bearer header and validate it asynchronously.

Use this when the decision needs I/O – token introspection, a JWKS fetch – so it suspends instead of blocking the executor that is concurrently serving MCP traffic.

Passing an empty validator disables HTTP authentication. Configure the validator before listen() starts.

A request whose token the validator refuses is answered 401 with the bearer challenge. A validator that throws is answered 500, without a challenge, so a failing introspection endpoint does not send clients into re-authorization. A validator that accepts a token may name the principal it stands for (TokenValidation); handlers of requests served without a session see it as Context::principal(). A session belongs to the principal that created it: another principal gets 404. Without a named principal a token counts as one by itself, so a client that refreshes its token starts a new session; naming the principal avoids that. Without a validator, a session is not bound to the Authorization header.

Throws:

std::logic_error – If a synchronous validator is already installed, or if listen() has already been called or the manager is closed.

void set_max_request_body_bytes(std::size_t max_bytes)

Cap the HTTP request body this manager will read.

A request whose body exceeds the cap is answered 413 Payload Too Large and its connection is closed; it never reaches MCP dispatch. Defaults to mcp::constants::http_server::g_DEFAULT_MAX_REQUEST_BODY_BYTES. Binary content travels as base64 inside the JSON body, so a cap near the size of the raw content rejects it.

The body is read, up to this cap, before the origin and bearer token are checked, so the cap is also what one unauthenticated connection can make the transport buffer. The body is parsed as JSON only after those checks pass.

Configure the cap before listen() starts.

Throws:
  • std::invalid_argument – If max_bytes is zero.

  • std::logic_error – If listen() has already been called or the manager is closed.

void set_bearer_challenge(BearerChallengeConfig challenge)

Set the parameters sent in the WWW-Authenticate header of every 401.

Without this call the manager sends the bare Bearer challenge. A client that has to discover where to obtain a token needs at least resource_metadata; setting protected resource metadata fills that field in automatically when it is left empty here.

Configure the challenge before listen() starts.

Throws:
  • std::invalid_argument – If a challenge value cannot be sent in a quoted-string.

  • std::logic_error – If listen() has already been called or the manager is closed.

void set_scope_requirements(ScopeRequirementProvider provider)

Name the scopes each request needs, so a token without them is answered 403.

After a validator accepts a token, the provider is asked about every POSTed JSON-RPC message that has a method (see ScopeRequirementProvider). When the token’s scopes (TokenValidation::scopes) lack one the provider named, the message is not dispatched and no response stream is opened: the answer is 403 with a WWW-Authenticate: Bearer error="insufficient_scope", scope="...", resource_metadata="..." challenge naming every scope the operation needs, which a client such as OAuthClientTransport answers by authorizing again with the wider scope. The challenge keeps the realm and metadata URL of set_bearer_challenge() and set_protected_resource_metadata(). A validator that reports no scopes grants none, so a request that needs a scope is refused. Requests that carry no JSON-RPC method (answers to the server’s own requests, GET and DELETE) are not checked.

The scopes the provider returns are written into the challenge as quoted header text, so each must consist of printable ASCII (0x20-0x7E); a provider that returns anything else is answered 500 with no challenge, as one that throws is.

Passing an empty provider removes the check. Configure it before listen() starts. A provider needs a token validator to report the scopes a token holds, so listen() throws when one is set without the other, whichever was set first.

Throws:

std::logic_error – If listen() has already been called or the manager is closed. listen() also throws it when a provider is set and no validator is.

void set_protected_resource_metadata(ProtectedResourceMetadataConfig metadata)

Serve an RFC 9728 protected-resource metadata document.

The document answers GET requests at its configured path without an Authorization header, ahead of both the bearer check and the custom request handler. When the bearer challenge carries no resource_metadata, it is populated with this document’s URL.

Configure the metadata before listen() starts.

Throws:
  • std::invalid_argument – If resource is empty or is not an absolute URL.

  • std::logic_error – If listen() has already been called or the manager is closed.

void set_unauthenticated_paths(std::vector<std::string> paths)

Exempt request paths from bearer validation and exclude them from MCP dispatch.

An entry is excused from the bearer check and also removed from the set of paths MCP answers: an exempt request still reaches the protected-resource metadata route and the custom request handler, but if both decline it is answered 404 Not Found rather than dispatched, so MCP is never served without authentication on an exempt path.

Each entry is compared for equality against the path component of the request target, with any query string or fragment removed first, so /health also exempts /health?probe=1. Empty by default.

Configure the paths before listen() starts.

Throws:

std::logic_error – If listen() has already been called or the manager is closed.

std::size_t session_count() const

Get the number of active sessions.

Returns:

The number of live MCP sessions currently managed by this endpoint.

void set_session_limits(const SessionLimits &limits)

Set what the manager holds for clients it has not heard from.

Parameters:

limits – The limits. They apply from the next session and the next sweep.

Throws:

std::invalid_argument – If limits.max_sessions is 0.

void set_connection_limits(const HttpConnectionLimits &limits)

Set what the connections and requests of this endpoint may hold at once.

The headers of a request are read first, and the Origin and bearer token checks run on them, so a request they refuse never has its body read. See HttpConnectionLimits for the defaults.

Throws:

std::invalid_argument – If max_requests or max_request_bytes is 0.

void set_json_only(bool json_only)

Enable or disable JSON-only responses for managed sessions.

When enabled, POST responses always use application/json and session replay events are not stored. This option is atomic and may be changed while the listener is running.

Parameters:

json_only – True to bypass SSE framing and replay storage.

void set_stateless_json_mode(bool enabled)

Enable or disable stateless direct JSON handling.

When enabled, POST request/response messages are dispatched directly to a Server instance without creating Mcp-Session-Id sessions, MemoryTransport pairs, pending-response timers, SSE event stores, GET streams, or DELETE teardown. Responses are always application/json.

This mode is opt-in and leaves the default stateful Streamable HTTP behavior unchanged.

Parameters:

enabled – True to use stateless direct JSON handling.

Throws:

std::logic_error – If listen() has already been called or the manager is closed.

void set_tool_executor(const Executor &exec)

Set a separate executor for tool handlers.

When set, tool handlers will run on this executor instead of the HTTP I/O executor. This allows parallel tool execution independent of HTTP request handling. If not set, tool handlers fall back to the HTTP executor (backward compatible). A manager constructed with a Server calls that server’s Server::set_handler_executor().

Parameters:

exec – The executor to use for tool execution.

Throws:

std::logic_error – If listen() has already been called or the manager is closed.

void set_protocol_policy(ServerProtocolPolicy policy)

Choose which protocol revisions the endpoint serves.

Applied to every Server the manager builds from its factory: each session’s, the stateless one and the shared modern server (unless set_modern_server() supplied it). A manager constructed with a Server calls that server’s Server::set_protocol_policy(). When legacy clients are not served, no session is created: initialize is answered 404 with mcp::constants::jsonrpc::g_METHOD_NOT_FOUND naming the versions served, and GET and DELETE 405.

Throws:
  • std::invalid_argument – If ServerProtocolPolicy::validate() refuses the policy.

  • std::logic_error – If listen() has already been called or the manager is closed, or when Server::set_protocol_policy() refuses it.

void set_modern_server(std::shared_ptr<Server> server)

Serve every 2026-07-28 request with server.

A 2026-07-28 request belongs to no session, so one Server answers all of them on this endpoint, alongside the per-session Servers of legacy clients. Without this call it is built from the factory on the first such request. Its tools, resources and prompts are what every 2026-07-28 client sees, so they must not depend on the connection.

Throws:
  • std::invalid_argument – If server is null.

  • std::logic_error – If listen() has already been called or the manager is closed.

std::shared_ptr<Server> modern_server()

The Server that answers 2026-07-28 requests.

Returns:

The server given to set_modern_server(), or the one built from the factory, which this call builds if no request has yet. Called before listen(), it lets the server be configured before the first request.

std::uint64_t header_mismatch_rejections() const

2026-07-28 requests refused with mcp::constants::jsonrpc::g_HEADER_MISMATCH because their MCP-Protocol-Version, Mcp-Method, Mcp-Name or Mcp-Param-* header was missing, malformed or did not match the body.

void set_stream_options(StreamOptions options)

Set how the answers to 2026-07-28 requests are streamed.

Throws:
  • std::invalid_argument – If an interval is not positive, or max_queued_notifications or max_queued_bytes is zero.

  • std::logic_error – If listen() has already been called or the manager is closed.

StreamStats stream_stats() const

What the 2026-07-28 streams have done so far.

void close()

Close the manager and all sessions.

The handlers of 2026-07-28 requests that wait for a retry on the modern server are given up (Server::abandon_waiting_handlers()).

Task<void> listen()

Start accepting HTTP connections.

Returns:

A task that completes when the listener stops accepting connections.

Friends

friend struct detail::CustomRouteAccess

Authentication

class OAuthHttpClient

Minimal HTTP client for OAuth token exchange and metadata retrieval.

Public Functions

explicit OAuthHttpClient(const Executor &executor)

Construct an OAuth HTTP client.

Note

Without an explicit fetch policy the client holds a default-constructed MetadataFetchPolicy (empty origin allow list, https-only, non-loopback), so every request is refused until a policy is installed via set_metadata_policy(). A client that follows WWW-Authenticate challenges must be given a policy naming the origins it is meant to reach, because the URLs it then visits are influenced by the server it talks to.

Parameters:

executor – Executor used for asynchronous operations.

void set_metadata_policy(MetadataFetchPolicy policy)

Apply an outbound-request policy to every request this client issues.

May be called at any time: an exchange already running keeps the policy it started with, and the next one picks up the new value. Each request is validated before host resolution, every resolved address is classified before connecting and pinned for the connection, response bodies are capped, and redirects are bounded and individually re-validated.

Warning

Do not call this and set_host_resolver() in sequence to change both: an exchange started between the two calls runs with one new value and one old one. Use configure().

Parameters:

policy – Policy governing schemes, origins, resolved addresses, response size and redirect depth.

void set_host_resolver(HostResolver resolver)

Install a custom host resolver.

Warning

Do not call this and set_metadata_policy() in sequence to change both; use configure().

Parameters:

resolver – Resolver invoked in place of the system resolver.

void configure(MetadataFetchPolicy policy, HostResolver resolver)

Install an outbound-request policy and a host resolver as one indivisible change.

An exchange started around this call runs entirely with the configuration before it or entirely with the configuration after it. Use this whenever both are changed on a client that may already be serving requests.

Parameters:
  • policy – Policy governing schemes, origins, resolved addresses, response size and redirect depth.

  • resolver – Resolver invoked in place of the system resolver; an empty resolver restores the executor’s system resolver.

void configure(MetadataFetchPolicy policy, HostResolver resolver, std::shared_ptr<const TlsClientContext> tls, ProxyOptions proxy = {})

Install the policy, the resolver, the TLS settings and the proxy as one indivisible change.

The two-argument form keeps the TLS settings and proxy the client has. Without either, https servers are checked against the system’s certificate authorities and every request connects directly.

Parameters:
  • policy – As above.

  • resolver – As above.

  • tls – TLS settings for https servers; null checks them against the system’s certificate authorities.

  • proxy – The proxy requests go through. The proxy resolves the names of the servers it reaches, so the policy’s address checks apply only to addresses written in a URL. Connections to loopback hosts never use it.

Throws:

std::invalid_argument – If a proxy URL is malformed or not supported.

Task<TokenResponse> exchange_code(const OAuthConfig &config, const std::string &code, const std::string &code_verifier)

Exchange an authorization code for an access token.

Parameters:
  • config – OAuth client configuration.

  • code – Authorization code obtained from the authorization server.

  • code_verifier – PKCE verifier associated with the original request.

Returns:

A task resolving to the parsed token response.

Task<TokenResponse> refresh_token(const OAuthConfig &config, const std::string &refresh_token)

Refresh an access token using a refresh token.

Parameters:
  • config – OAuth client configuration.

  • refresh_token – Refresh token issued by the authorization server.

Returns:

A task resolving to the parsed token response.

Task<nlohmann::json> get_json(const std::string &url)

Fetch a JSON document from an OAuth discovery endpoint.

Parameters:

url – HTTP URL to fetch.

Returns:

A task resolving to the parsed JSON body.

Task<nlohmann::json> post_json(const std::string &url, const nlohmann::json &body)

Post a JSON document to an OAuth endpoint and read the JSON reply.

Used for RFC 7591 dynamic client registration. The target is validated against the fetch policy exactly like every other request this client issues, and redirects are not followed for a POST.

Parameters:
  • url – HTTP URL to post to.

  • body – JSON request body.

Returns:

A task resolving to the parsed JSON response.

Task<nlohmann::json> post_form(const std::string &url, const KeyValuePairList &params, const std::string &authorization = {})

Post a form to a token endpoint and read the JSON reply.

For grants the client does not build itself, such as client credentials, token exchange and the JWT bearer grant. The target is validated against the fetch policy like every other request, redirects are not followed, and an HTTP error status fails the request.

Parameters:
  • url – Token endpoint URL.

  • params – Form parameters, sent as application/x-www-form-urlencoded.

  • authorization – Value of the Authorization header, or empty to send none.

Returns:

A task resolving to the parsed JSON reply.

void abort_pending()

Abort every HTTP exchange currently in flight on this client, and refuse every one issued afterward.

Closes the underlying socket of each active exchange, so a pending resolve, connect, write, or read completes with an error instead of hanging. Safe to call from any thread. Sticky and irreversible: a request issued afterward – even one that has not yet made its first network call – fails immediately instead of running to completion. Idempotent.

OAuthHttpClientScope make_scope()

Open an independently abortable scope on this client.

Requests issued through a scope are tracked against it; aborting it closes those and refuses later ones, leaving every other scope and the client’s own unscoped requests untouched. abort_pending() still ends everything, scopes included. A scope keeps the underlying client alive, so it stays usable even if the OAuthHttpClient object it came from is destroyed.

Returns:

A scope that issues requests through this client but can be aborted on its own.

class OAuthDiscoveryClient

Client for OAuth protected-resource and authorization-server discovery.

Public Functions

explicit OAuthDiscoveryClient(std::shared_ptr<OAuthHttpClient> http_client, std::chrono::seconds cache_ttl = std::chrono::seconds(mcp::constants::oauth::g_DEFAULT_CACHE_TTL_SECONDS))

Construct an OAuth discovery client.

Parameters:
  • http_client – HTTP helper used to fetch discovery documents.

  • cache_ttl – Time-to-live for cached discovery responses.

OAuthDiscoveryClient(const OAuthDiscoveryClient&) = delete
OAuthDiscoveryClient &operator=(const OAuthDiscoveryClient&) = delete
OAuthDiscoveryClient(OAuthDiscoveryClient&&) = delete
OAuthDiscoveryClient &operator=(OAuthDiscoveryClient&&) = delete
Task<ProtectedResourceMetadata> discover_protected_resource(const std::string &resource_url)

Discover metadata for a protected resource.

Parameters:

resource_url – Resource URL whose metadata should be resolved.

Returns:

A task resolving to the discovered protected-resource metadata.

Task<ProtectedResourceMetadata> discover_protected_resource(const std::string &resource_url, const std::optional<std::string> &challenge_metadata_url)

Discover metadata for a protected resource, honouring a challenge-supplied URL.

When the challenge supplied a URL it is fetched and nothing else is tried. Otherwise the well-known fallback runs, trying the path-based location before the root one.

Parameters:
  • resource_url – Resource URL whose metadata should be resolved.

  • challenge_metadata_url – resource_metadata URL taken from a WWW-Authenticate challenge, when the challenge supplied one.

Returns:

A task resolving to the discovered protected-resource metadata.

Task<ProtectedResourceMetadata> discover_protected_resource(const std::string &resource_url, const std::optional<std::string> &challenge_metadata_url, ProtectedResourceAcceptor accept)

Discover metadata for a protected resource, subject to the caller’s acceptance.

Identical to the two-argument form except that nothing is written to the cache until accept has passed on it, and accept runs on a cache hit as well.

Parameters:
  • resource_url – Resource URL whose metadata should be resolved.

  • challenge_metadata_url – resource_metadata URL taken from a WWW-Authenticate challenge, when the challenge supplied one.

  • accept – Called with the document before it is returned or cached; throwing rejects it.

Returns:

A task resolving to the discovered protected-resource metadata.

void forget_protected_resource(const std::string &resource_url, const std::optional<std::string> &challenge_metadata_url)

Drop the cached protected-resource metadata for one resource.

The next discover_protected_resource() call for the same arguments fetches the document again. A client that has just been challenged uses this so the authorization server it authorizes at is the one the resource names now, not the one the cached copy named.

Parameters:
  • resource_url – Resource URL the metadata was discovered for.

  • challenge_metadata_url – resource_metadata URL of the challenge the metadata was discovered through, when it supplied one.

Task<AuthServerMetadata> discover_auth_server(const std::string &issuer_url)

Discover metadata for an authorization server.

Parameters:

issuer_url – Issuer URL or base URL of the authorization server.

Returns:

A task resolving to the discovered authorization-server metadata.

void clear_cache()

Clear all cached discovery metadata.

class OAuthClientTransport : public mcp::ITransport

Transport wrapper that supplies and refreshes OAuth bearer tokens.

For HttpClientTransport, tokens are sent in the HTTP Authorization header. The legacy request-metadata mechanism is retained only for non-HTTP transports. The wrapper also handles token refresh on legacy JSON-RPC authorization failures. When the server returns -32000, the transport calls Authenticator::try_refresh_token() and, if successful, re-sends the request whose ID matches the error response and reads the new response. Only one retry attempt is made per read_message() call. Callers should ensure messages are idempotent since they may be re-sent after a token refresh. Outstanding request wires are tracked by JSON-RPC request ID in a bounded, expiring cache so an authentication error cannot replay a different concurrent request.

Public Functions

OAuthClientTransport(std::shared_ptr<ITransport> inner, std::shared_ptr<Authenticator> authenticator)

Construct an authenticated transport wrapper.

Parameters:
  • inner – Underlying transport used for MCP message exchange.

  • authenticator – Authenticator used to retrieve and refresh tokens. Its tokens go to the server inner talks to, which is not compared with any URL the authenticator holds, so it must be the authenticator for that server alone.

OAuthClientTransport(std::shared_ptr<ITransport> inner, std::shared_ptr<Authenticator> authenticator, OAuthClientTransportOptions options)

Construct an authenticated transport wrapper with replay-correlation limits.

Parameters:
  • inner – Underlying transport used for MCP message exchange.

  • authenticator – Authenticator used to retrieve and refresh tokens. Its tokens go to the server inner talks to, which is not compared with any URL the authenticator holds, so it must be the authenticator for that server alone.

  • options – Bounds and TTL for retaining outstanding request wires.

virtual Task<std::string> read_message() override

Read a message from the inner transport, retrying once on authentication errors.

If the received message contains the legacy JSON-RPC authentication error -32000, attempts one token refresh via Authenticator::try_refresh_token(). On successful refresh, replays the matching outstanding request while it remains eligible and returns the new response. If refresh fails, correlation has expired or been evicted, or a second auth error is received, returns the error response as-is. If the response cannot be parsed as JSON, the raw string is returned unchanged.

Returns:

The (possibly retried) raw message string.

virtual Task<void> write_message(std::string_view message) override

Inject the current bearer token into an outgoing MCP message.

Parameters:

message – Serialized JSON-RPC request or notification.

Returns:

A task that completes once the wrapped transport accepts the message.

virtual void close() override

Cancel the authenticator’s in-flight work and close the wrapped transport.

Calls Authenticator::cancel_pending(), not Authenticator::close(): the authenticator stays usable, so another transport built on it can still refresh and authorize. A write on this transport that is still retrying after a 401 or 403 fails. Once close() has run, the write asks the authenticator for no new refresh or authorization; one it started while close() was running is cancelled through Authenticator::cancel_pending() and waited for.

virtual bool overlapping_writes() const noexcept override

What the wrapped transport does.

virtual void set_interaction_observer(InteractionObserver observer) override

Report to observer while a write waits for Authenticator::try_handle_challenge().

The challenge can run an interactive authorization, whose time is the user’s and not the request’s. The observer is told when a write begins and ends that wait, keyed by the request’s correlation key; Client uses it to stop the request’s deadline while it lasts. A refresh runs no such prompt and is not reported.

class InMemoryTokenStore : public mcp::auth::TokenStore

Thread-safe in-memory token store implementation.

Public Functions

InMemoryTokenStore()
~InMemoryTokenStore() override
InMemoryTokenStore(const InMemoryTokenStore&) = delete
InMemoryTokenStore &operator=(const InMemoryTokenStore&) = delete
InMemoryTokenStore(InMemoryTokenStore&&) = delete
InMemoryTokenStore &operator=(InMemoryTokenStore&&) = delete
virtual void store(const std::string &server_url, TokenResponse token) override

Store or replace a token in the in-memory cache.

Parameters:
  • server_url – MCP server URL used as the storage key.

  • token – Token data to persist.

virtual std::optional<TokenResponse> load(const std::string &server_url) const override

Load a token from the in-memory cache.

Parameters:

server_url – MCP server URL used as the storage key.

Returns:

The stored token, if present.

virtual void remove(const std::string &server_url) override

Remove a token from the in-memory cache.

Parameters:

server_url – MCP server URL used as the storage key.

class Authenticator

Abstract interface for providing access tokens and handling refresh.

Implementations must be safe to call from within an asio strand context. get_access_token() must be lightweight — no network I/O. Returns the current bearer token or empty string. try_refresh_token() is a coroutine that performs network I/O to refresh the token and persists the new token via the configured token store on success.

Subclassed by mcp::auth::ClientCredentialsAuthenticator, mcp::auth::EnterpriseAuthorizationAuthenticator, mcp::auth::OAuthAuthenticator, mcp::auth::OAuthAuthorizationManager

Public Functions

virtual ~Authenticator() = default
virtual std::string get_access_token() const = 0

Returns the current bearer token without network I/O.

Returns:

The stored access token, or an empty string when none is available.

virtual Task<bool> try_refresh_token() = 0

Performs a token refresh via network I/O, persisting the new token on success.

Returns:

true if refresh succeeded and a new token was persisted; false otherwise.

virtual Task<bool> try_handle_challenge(const std::string &www_authenticate)

Performs challenge-driven authorization for a WWW-Authenticate response.

OAuthClientTransport calls it for a challenge that a renewal cannot answer: on a 401, only after try_refresh_token() was unavailable, failed, or produced a token that was refused too, and at most once per request; on a 403 whose challenge carries error="insufficient_scope", directly. An implementation can discover metadata and run a full authorization exchange rather than only renewing an existing grant. The default implementation reports that it handled nothing.

Parameters:

www_authenticate – Raw WWW-Authenticate header value from the challenge response.

Returns:

true if authorization completed and a new token was persisted; false otherwise.

inline virtual void cancel_pending()

Cancel the authorization work this authenticator has in flight and release parked callers with an error, leaving it usable for later requests.

Called by OAuthClientTransport::close(). The authenticator may be shared and outlive the transport, so later work runs as usual. The default is a no-op; an authenticator that forwards to another should forward this call too. Safe to call more than once and from any thread.

inline virtual void close()

Cancel any authorization work this authenticator has in flight, release parked callers with an error, and refuse further work.

The owner’s permanent shutdown; no transport calls it. The default is a no-op. Safe to call more than once.

class OAuthAuthenticator : public mcp::auth::Authenticator

OAuth 2.0 implementation of the Authenticator interface.

Public Functions

OAuthAuthenticator(std::shared_ptr<TokenStore> token_store, std::shared_ptr<OAuthHttpClient> oauth_client, OAuthConfig config, std::string server_url)

Construct an authenticator that refreshes tokens through oauth_client.

Throws:

std::invalid_argument – if oauth_client is null.

virtual std::string get_access_token() const override

Returns the current bearer token without network I/O.

Returns:

The stored access token, or an empty string when none is available.

virtual Task<bool> try_refresh_token() override

Performs a token refresh via network I/O, persisting the new token on success.

Returns:

true if refresh succeeded and a new token was persisted; false otherwise.

void store_token(TokenResponse token)

Stores an initial token obtained from an explicit OAuth exchange (e.g., authorization code flow).

Parameters:

token – The token response to persist via the configured TokenStore.

virtual void cancel_pending() override

Aborts this authenticator’s in-flight token-refresh HTTP exchanges.

Later refreshes run as usual. Other holders of the same OAuthHttpClient are unaffected.

virtual void close() override

Aborts this authenticator’s in-flight token-refresh HTTP exchanges and refuses later ones.

Other holders of the same OAuthHttpClient are unaffected.

Core Types

Task<T>

template<typename T>
class Task : public boost::asio::awaitable<T>

An asynchronous task: a coroutine that produces a T when awaited.

A Task is a boost::asio::awaitable<T>. It can be awaited from any awaitable coroutine, combined with Asio’s awaitable operators, and passed to boost::asio::co_spawn, either as a value or as a callable that returns one, such as [&]() -> mcp::Task<void> { ... }.

Template Parameters:

T – The type the task produces.

Public Types

using promise_type = std::coroutine_traits<boost::asio::awaitable<T>>::promise_type

The coroutine promise of boost::asio::awaitable<T>, so a Task coroutine runs as one.

Public Functions

Task() noexcept = default

An empty task that holds no coroutine.

inline Task(boost::asio::awaitable<T> &&other) noexcept

Take over the coroutine of an awaitable.

Executor

class Executor

Where asynchronous work runs: an event loop, a strand or a thread pool.

Holds a boost::asio::any_io_executor. An Asio executor such as io.get_executor() converts to an Executor implicitly, and get() returns the Asio executor; both need <mcp/core/async.hpp>. Copies share the executor they hold. A default-constructed Executor holds none, nor does one made from an empty Asio executor, and the SDK refuses it with std::invalid_argument.

Public Functions

Executor() noexcept = default

An executor that holds no Asio executor.

template<typename AsioExecutor>
inline Executor(const AsioExecutor &executor)

Wrap an Asio executor (for example io.get_executor() or a strand).

template<typename Unused = void>
inline const auto &get() const

The Asio executor held, as a const boost::asio::any_io_executor&.

Throws:

std::invalid_argument – If this Executor holds none.

inline explicit operator bool() const noexcept

Whether this Executor holds an Asio executor.

Protocol Types

The SDK includes typed protocol and supporting types for its implemented MCP surface. They are available through the generated index below, which avoids duplicating the class-level API sections above. The pinned conformance results, not this index, are the source of truth for current protocol coverage.

RequestId

struct RequestId

JSON-RPC request identifier: either a string or an integer.

Wraps std::variant<std::string, int64_t> as a named type so that to_json/from_json are found by ADL in namespace mcp.

Implicit constructors allow transparent assignment from string and integer literals:

RequestId id = "req-1";
RequestId id = int64_t{42};

Public Functions

RequestId() = default
inline RequestId(std::string s)
inline RequestId(const char *s)
inline RequestId(int64_t i)
bool operator==(const RequestId&) const = default
inline std::string to_string() const

Converts the request ID to its unadorned string representation.

inline std::string correlation_key() const

Return a type-preserving key for request correlation.

Public Members

std::variant<std::string, int64_t> value

Complete Index

For a complete alphabetical index of all classes, functions, and types, use the generated Sphinx index and search UI in the built documentation.