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::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 SubscriptionHandler = std::function<void(const std::string &uri)>
Callback invoked when a client subscribes to or unsubscribes from a resource URI.
Public Functions
-
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.
-
~Server()
-
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.
-
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.
-
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.
-
void add_raw_tool(const Tool &tool, TypeErasedHandler 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 – Asynchronous raw handler receiving tool arguments.
-
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.
-
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 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.
- 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_page_size(std::size_t size)
Set the page size for paginated list responses.
- Parameters:
size – The maximum number of items per page. 0 means no pagination.
-
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_discover_ttl_ms(std::int64_t ttl_ms)
Set the
ttlMscaching hint returned by server/discover.Defaults to
0(“do not cache”) until overridden. Read unsynchronized by request handlers; must be called before run().- Parameters:
ttl_ms – How long, in milliseconds, the client MAY consider the discover result fresh.
- Throws:
std::invalid_argument – If
ttl_msis negative.
-
void set_discover_cache_scope(CacheScope scope)
Set the
cacheScopecaching hint returned by server/discover.Defaults to
CacheScope::ePrivateuntil overridden. Read unsynchronized by request handlers; must be called before run().- Parameters:
scope – The intended cache scope of the discover result.
-
Task<nlohmann::json> send_request(const std::string &method, const std::optional<nlohmann::json> ¶ms)
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.
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
transportis an HttpServerTransport, a session the client ends with HTTP DELETE is over and the next client must initialize again; a transport that wraps an HttpServerTransport is not recognized as one.- 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.
- 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)
Run the server over HTTP, blocking until shutdown.
Binds to the given host and port, accepts HTTP connections, and processes JSON-RPC requests. Handles SIGINT and SIGTERM for clean shutdown. Exceptions from the server session are propagated to the caller.
The transport keeps its default settings, so a request carrying an Origin header is answered with 403. To accept browser clients, construct an HttpServerTransport, call set_allowed_origins() on it, and pass it to run().
- Parameters:
host – Local address to bind (e.g. “0.0.0.0” or “127.0.0.1”).
port – TCP port to listen on.
-
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.
Request parameter decoding failures are returned as
g_INVALID_PARAMS(-32602). Exceptions thrown by middleware, or by resource, prompt and completion handlers, are returned asg_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.
-
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.
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 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.
-
using SubscriptionHandler = std::function<void(const std::string &uri)>
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. The client initiates the MCP handshake via connect(), which sends an initialize request followed by an initialized notification.
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
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.
-
~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.
-
Task<InitializeResult> connect(std::string_view name, std::string_view version)
Perform the MCP initialization handshake with default capabilities.
-
Task<InitializeResult> connect(const Implementation &client_info, const ClientCapabilities &capabilities)
Perform the MCP initialization handshake.
Starts the read loop, sends initialize, waits for the server response, and then sends notifications/initialized.
- Parameters:
client_info – Information about this client implementation.
capabilities – Capabilities supported by this client.
- Returns:
A task that resolves to the server’s InitializeResult.
-
Task<nlohmann::json> send_request(std::string_view method, const std::optional<nlohmann::json> ¶ms)
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.
- 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<nlohmann::json> send_request(std::string_view method, const std::optional<nlohmann::json> ¶ms, const RequestOptions &request_options)
Send a JSON-RPC request with per-request runtime options.
-
Task<void> send_notification(std::string_view method, const std::optional<nlohmann::json> ¶ms)
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 close()
Close the client, stopping the read loop and releasing resources.
-
template<JsonSerializable Args>
inline Task<CallToolResult> call_tool(const std::string &name, const Args &arguments) 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.
- Returns:
A task that resolves to the server’s CallToolResult.
-
Task<ListToolsResult> list_tools(const std::optional<std::string> &cursor = std::nullopt)
List available tools from the server.
- Parameters:
cursor – Optional pagination cursor.
- Returns:
A task that resolves to the server’s ListToolsResult.
-
Task<ListResourcesResult> list_resources(const std::optional<std::string> &cursor = std::nullopt)
List available resources from the server.
- Parameters:
cursor – Optional pagination cursor.
- Returns:
A task that resolves to the server’s ListResourcesResult.
-
Task<ReadResourceResult> read_resource(const std::string &uri)
Read a resource from the server by URI.
- Parameters:
uri – The URI of the resource to read.
- Returns:
A task that resolves to the server’s ReadResourceResult.
-
Task<ListResourceTemplatesResult> list_resource_templates(const std::optional<std::string> &cursor = std::nullopt)
List available resource templates from the server.
- Parameters:
cursor – Optional pagination cursor.
- Returns:
A task that resolves to the server’s ListResourceTemplatesResult.
-
Task<ListPromptsResult> list_prompts(const std::optional<std::string> &cursor = std::nullopt)
List available prompts from the server.
- Parameters:
cursor – Optional pagination cursor.
- Returns:
A task that resolves to the server’s ListPromptsResult.
-
Task<GetPromptResult> get_prompt(const std::string &name, const std::optional<std::map<std::string, std::string>> &arguments = std::nullopt)
Get a specific prompt from the server.
- Parameters:
name – The name of the prompt.
arguments – Optional arguments to template the prompt.
- Returns:
A task that resolves to the server’s GetPromptResult.
-
Task<CompleteResult> complete(const CompleteParams ¶ms)
Request completions from the server.
- Parameters:
params – The completion parameters.
- Returns:
A task that resolves to the server’s CompleteResult.
-
Task<void> ping()
Send a ping request to the connected server.
- 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.
- 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.
- 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.
- Parameters:
handler – Async handler: receives ElicitRequestParams, returns ElicitResult.
-
void set_roots(const std::vector<Root> &roots, bool notify = false)
Set static roots and auto-register the roots/list handler.
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.
- Parameters:
roots – The list of roots to provide.
notify – Whether to send a roots-changed notification.
-
using NotificationCallback = std::function<void(const nlohmann::json&)>
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.
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.
-
inline Task<void> log_info(std::string_view msg)
Sends an informational log message to the client.
- Parameters:
msg – The log message to send.
- Returns:
A task that completes when the message is sent.
-
inline 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.
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.
- 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 if a notifications/cancelled was received for this request’s ID.
-
inline 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.
- 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 Task<CreateMessageResult> sample_llm(const CreateMessageRequestParams &request)
Request the client to sample an LLM (reverse RPC).
Sends a “sampling/createMessage” request to the client and awaits the response. Requires the Context to be constructed with a RequestSender.
- Parameters:
request – The sampling request parameters.
- Throws:
std::runtime_error – If no request sender is available.
- Returns:
A task that resolves to the client’s CreateMessageResult.
-
inline Task<ElicitResult> elicit(const ElicitRequestParams ¶ms)
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.
- Parameters:
params – The elicitation request parameters (form or URL mode).
- Throws:
std::runtime_error – If no request sender is available.
- Returns:
A task that resolves to the client’s ElicitResult.
-
inline Task<ListRootsResult> request_roots()
Request the list of roots from the client (reverse RPC).
Sends a “roots/list” request to the client and awaits the response. The client provides its configured root URIs.
- Throws:
std::runtime_error – If no request sender is available.
- Returns:
A task that resolves to the client’s ListRootsResult.
-
inline explicit Context(ITransport &transport)
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::StdioTransport, mcp::WebSocketClientTransport, mcp::WebSocketServerTransport, mcp::auth::OAuthClientTransport
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:
std::runtime_error – If the transport is closed while waiting.
- Returns:
A task that resolves to the next complete JSON-RPC message.
-
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:
std::runtime_error – If the transport is closed.
- Returns:
A task that completes once the message has been accepted by the transport.
-
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.
-
virtual ~ITransport() = default
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/jsonandtext/event-streamresponse content types.Public Functions
-
HttpClientTransport(const boost::asio::any_io_executor &executor, const std::string &url)
Construct an HTTP client transport.
- Parameters:
executor – Executor used for async operations.
url – HTTP endpoint URL (e.g.
http://localhost:8080/mcp).
- Throws:
std::invalid_argument – If the URL is malformed or does not use the
http://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 most recent SSE event identifier seen from the server.
- Returns:
The last event ID used for resumable HTTP replay, or an empty string if none was received.
-
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.
-
virtual Task<std::string> read_message() override
Dequeue the next MCP message received from the server.
- Throws:
std::runtime_error – 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:
std::runtime_error – On transport closure or HTTP error.
-
virtual void close() override
Close the transport and release connection resources.
-
HttpClientTransport(const boost::asio::any_io_executor &executor, const std::string &url)
-
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.
Public Functions
-
HttpServerTransport(const boost::asio::any_io_executor &executor, std::string host, unsigned short port, std::size_t event_store_capacity = mcp::constants::g_event_store_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/jsonand 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_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_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.
- 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.
- 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 Largeand its connection is closed; it never reaches MCP dispatch. Defaults to mcp::constants::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_bytesis zero.std::logic_error – If listen() has already been called or the transport is closed.
-
void set_bearer_challenge(BearerChallengeConfig challenge)
Set the parameters sent in the
WWW-Authenticateheader of every 401.Without this call the transport sends the bare
Bearerchallenge. A client that has to discover where to obtain a token needs at leastresource_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_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
resourceis 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 Foundrather 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
/healthalso 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.
-
virtual Task<std::string> read_message() override
Read the next queued JSON-RPC message from HTTP POST bodies.
-
virtual Task<void> write_message(std::string_view message) override
Send a JSON-RPC response for the pending HTTP request.
- Parameters:
message – Serialized JSON-RPC response.
-
virtual void close() override
Close the transport and stop accepting connections.
-
HttpServerTransport(const boost::asio::any_io_executor &executor, std::string host, unsigned short port, std::size_t event_store_capacity = mcp::constants::g_event_store_default_capacity)
-
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-Idheader. New sessions are created oninitializerequests 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.
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 asio::any_io_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 boost::asio::any_io_executor&)>
Callback that creates a configured Server instance for a new session.
-
using CustomRequestHandler = std::function<std::optional<StringResponse>(const StringRequest&)>
Optional callback for handling non-MCP HTTP requests (e.g., health checks).
Return std::nullopt to let the session manager handle the request normally.
Public Functions
-
StreamableHttpSessionManager(const boost::asio::any_io_executor &executor, std::string host, unsigned short port, ServerFactory factory, std::size_t event_store_capacity = constants::g_event_store_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()
-
StreamableHttpSessionManager(const StreamableHttpSessionManager&) = delete
-
StreamableHttpSessionManager &operator=(const StreamableHttpSessionManager&) = delete
-
StreamableHttpSessionManager(StreamableHttpSessionManager&&) = delete
-
StreamableHttpSessionManager &operator=(StreamableHttpSessionManager&&) = delete
-
void set_custom_request_handler(CustomRequestHandler handler)
Set a custom request handler for non-MCP routes (e.g., health checks).
- Parameters:
handler – A function that receives the HTTP request and optionally returns a response. If it returns std::nullopt, the request is handled as MCP protocol.
- Throws:
std::logic_error – If listen() has already been called or the manager is closed.
-
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_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.
- 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.
- 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 Largeand its connection is closed; it never reaches MCP dispatch. Defaults to mcp::constants::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_bytesis 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-Authenticateheader of every 401.Without this call the manager sends the bare
Bearerchallenge. A client that has to discover where to obtain a token needs at leastresource_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_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
resourceis 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 Foundrather 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
/healthalso 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_json_only(bool json_only)
Enable or disable JSON-only responses for managed sessions.
When enabled, POST responses always use
application/jsonand 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-Idsessions, MemoryTransport pairs, pending-response timers, SSE event stores, GET streams, or DELETE teardown. Responses are alwaysapplication/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 boost::asio::any_io_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).
- 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 close()
Close the manager and all sessions.
-
using ServerFactory = std::function<std::unique_ptr<Server>(const boost::asio::any_io_executor&)>
Authentication
-
class OAuthHttpClient
Minimal HTTP client for OAuth token exchange and metadata retrieval.
Public Functions
-
explicit OAuthHttpClient(const net::any_io_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 followsWWW-Authenticatechallenges 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.
-
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.
-
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 theOAuthHttpClientobject it came from is destroyed.- Returns:
A scope that issues requests through this client but can be aborted on its own.
-
explicit OAuthHttpClient(const net::any_io_executor &executor)
-
class OAuthDiscoveryClient
Client for OAuth protected-resource and authorization-server discovery.
Public Functions
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_metadataURL taken from aWWW-Authenticatechallenge, 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
accepthas passed on it, andacceptruns on a cache hit as well.- Parameters:
resource_url – Resource URL whose metadata should be resolved.
challenge_metadata_url –
resource_metadataURL taken from aWWW-Authenticatechallenge, 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.
-
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 perread_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
Construct an authenticated transport wrapper.
- Parameters:
inner – Underlying transport used for MCP message exchange.
authenticator – Authenticator used to retrieve and refresh tokens.
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.
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.
-
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.
-
InMemoryTokenStore()
-
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::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.
-
inline virtual Task<bool> try_handle_challenge(const std::string &www_authenticate)
Performs challenge-driven authorization for a
WWW-Authenticateresponse.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-Authenticateheader 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.
-
virtual ~Authenticator() = default
-
class OAuthAuthenticator : public mcp::auth::Authenticator
OAuth 2.0 implementation of the Authenticator interface.
Public Functions
Construct an authenticator that refreshes tokens through
oauth_client.- Throws:
std::invalid_argument – if
oauth_clientis 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>
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 thatto_json/from_jsonare found by ADL innamespace 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)
-
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
-
RequestId() = default
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.