Ai::Mcp

Beta

Turns a C++ app into a Model Context Protocol server in a few lines, checked against the official SDKs and the MCP Inspector. It also connects to any existing MCP server.

Optional module: turn it on with -DETHEREAL_AI_MCP=ONInclude #include <ethereal/cpp/ai/mcp/mcp_inc.hpp>C layer

mcp_inc.hpp

#include <ethereal/cpp/ai/mcp/mcp_inc.hpp>

Aggregated entry point of Ai::Mcp (AI-05): the Model Context Protocol, server and client.

The vocabulary (mcp_types.hpp), JSON-RPC (mcp_jsonrpc.hpp), the server (mcp_server.hpp), the URI templates (mcp_uritemplate.hpp), the progress of a request (mcp_progress.hpp), the transports (mcp_transport.hpp), the client (mcp_client.hpp) and the sampling through Ai::Llm (mcp_llm.hpp). Behind ETHEREAL_AI_MCP, which needs ETHEREAL_AI_TOOLS.

mcp_client.hpp

#include <ethereal/cpp/ai/mcp/mcp_client.hpp>

The MCP client: connect to any MCP server (stdio, in process, HTTP), find its revision, list and call tools, read resources, get prompts, complete, listen to its notifications, answer what it asks (roots, sampling, elicitation), and expose its tools as an Ai::Tools registry.

The revision (protocolo.md, section 3): the client probes with server/discover (2026-07-28). A recognized modern error ends there; any other error, or no answer in time, falls back to the initialize handshake of the 2025-11-25.

In the 2026-07-28 every request carries the _meta (the revision, the capabilities, the client info), and a tools/call, resources/read or prompts/get may answer input_required (MRTR): the client builds the inputs with the callbacks and retries, with the request state, up to a few rounds. In the 2025-11-25 the server asks the same things as requests, answered with the same callbacks.

Thread safe: several threads may call at once.

alias

EStatus

Ethereal::Ai::Mcp#
using PFN_InputRequest = EStatus ( * )( void * pUser, std::string_view sParamsJson, CJsonBuilder & Result );

Answers something the server asks (sampling/createMessage or elicitation/create): the params as JSON in, the result object written to Result.

eOk with the result written, or another status (the server gets an error, or in the MRTR the retry is not made).
alias

void

Ethereal::Ai::Mcp#
using PFN_ServerNotification = void ( * )( void * pUser, std::string_view sMethod, std::string_view sParamsJson );

A notification of the server (progress, log, list changed, resource updated).

struct

SRoot

Ethereal::Ai::Mcp#
C++
struct   SRoot
{
    std::string        sUri;
    std::string        sName;
};

A root the client exposes (a file:// URI).

struct

SClientConfig

Ethereal::Ai::Mcp#
C++
struct   SClientConfig
{
    /// @brief  Who the client is.
    std::string                        sName = "ethereal-mcp-client";
    std::string                        sVersion = "1.0.0";
    std::string                        sTitle;

    /// @brief  Time limit of each request. Zero: none.
    ETL_UINT32                        uTimeoutMs = 30000u;

    /// @brief  How long server/discover may wait before falling back to initialize.
    ETL_UINT32                        uDiscoverTimeoutMs = 3000u;

    /// @brief  Accept a 2025-11-25 server.
    bool                            bLegacy = true;

    /// @brief  The roots (declares the capability when not empty).
    std::vector< SRoot >            Roots;

    /// @brief  Sampling (declares the capability when set). Ai::Llm through SampleWithLlm.
    PFN_InputRequest                pfnSampling = nullptr;
    void *                            pSamplingUser = nullptr;

    /// @brief  Elicitation, form mode (declares the capability when set).
    PFN_InputRequest                pfnElicitation = nullptr;
    void *                            pElicitationUser = nullptr;

    /// @brief  The notifications of the server. May be null.
    PFN_ServerNotification            pfnNotification = nullptr;
    void *                            pNotificationUser = nullptr;

    /// @brief  Most MRTR rounds of one call.
    ETL_UINT32                        uMaxInputRounds = 8u;
};
struct

SToolInfo

Ethereal::Ai::Mcp#
C++
struct   SToolInfo
{
    std::string        sName;
    std::string        sTitle;
    std::string        sDescription;
    std::string        sInputSchema;        /// JSON.
    std::string        sOutputSchema;        /// JSON, or empty.
    bool            bReadOnly = false;
    bool            bDestructive = true;
    bool            bIdempotent = false;
    bool            bOpenWorld = true;
};

A tool of the server.

struct

SCallResult

Ethereal::Ai::Mcp#
C++
struct   SCallResult
{
    bool            bIsError = false;
    std::string        sText;                /// The text blocks, joined with newlines.
    std::string        sContentJson;        /// The content array as it came.
    std::string        sStructured;        /// structuredContent as JSON, or empty.
};

The result of tools/call.

struct

SResourceInfo

Ethereal::Ai::Mcp#
C++
struct   SResourceInfo
{
    std::string        sUri;                /// Or the template, for a template.
    std::string        sName;
    std::string        sTitle;
    std::string        sDescription;
    std::string        sMimeType;
};

A resource, or a resource template, of the server.

class

CClient

Ethereal::Ai::Mcp#
class CClient
constructor

CClient

#
CClient() noexcept;
function

Connect

#
EStatus Connect( std::unique_ptr< IClientTransport > Transport, const SClientConfig & Config ) noexcept;

Starts the transport and finds the revision of the server.

eOk, eUnsupportedVersion (no revision in common), eTimedOut, eTransport, eRemoteError (the server refused the handshake), eOutOfMemory.
function

ConnectStdio

#
EStatus ConnectStdio( const SProcessSpec & Spec, const SClientConfig & Config ) noexcept;

Connect over the stdio of a child process.

function

ConnectHttp

#
EStatus ConnectHttp( const SHttpClientSpec & Spec, const SClientConfig & Config ) noexcept;

Connect over Streamable HTTP (eInvalidArgument for a URL that is not http or https).

function

Close

#
void Close( void ) noexcept;

Ends the connection.

function

Revision

#
ERevision Revision( void ) const noexcept;

The revision found by Connect.

function

ServerCapabilities

#
std::string ServerCapabilities( void ) const noexcept;

The capabilities of the server, as JSON.

function

ServerInfo

#
std::string ServerInfo( void ) const noexcept;

The server info (name, version...), as JSON, or empty.

function

Instructions

#
std::string Instructions( void ) const noexcept;

The instructions of the server, or empty.

function

Request

#
EStatus Request( std::string_view sMethod, std::string_view sParamsJson, std::string & sResult, const std::atomic< bool > * pCancel = nullptr ) noexcept;

Any request: sParamsJson is the params object without the _meta (the client adds it in the 2026-07-28), or empty. sResult gets the result object. A JSON-RPC error is eRemoteError, with the code and the message in LastError.

function

LastErrorCode

#
ETL_INT64 LastErrorCode( void ) const noexcept;

The code and the message of the last eRemoteError of this thread.

function

LastErrorMessage

#
std::string LastErrorMessage( void ) const noexcept;
function

Notify

#
EStatus Notify( std::string_view sMethod, std::string_view sParamsJson ) noexcept;

A notification to the server.

function

ListTools

#
EStatus ListTools( std::vector< SToolInfo > & Out ) noexcept;

Every tool (the pages followed).

function

CallTool

#
EStatus CallTool( std::string_view sName, std::string_view sArgumentsJson, SCallResult & Out, const std::atomic< bool > * pCancel = nullptr ) noexcept;

Calls a tool. A tool that failed is eOk with bIsError (the model reads it).

function

ListResources

#
EStatus ListResources( std::vector< SResourceInfo > & Out ) noexcept;

Every resource, and every resource template.

function

ListResourceTemplates

#
EStatus ListResourceTemplates( std::vector< SResourceInfo > & Out ) noexcept;
function

ReadResource

#
EStatus ReadResource( std::string_view sUri, std::string & sContentsJson ) noexcept;

Reads a resource: the contents array as JSON. eNotFound when the server says so.

function

GetPrompt

#
EStatus GetPrompt( std::string_view sName, std::string_view sArgumentsJson, std::string & sResultJson ) noexcept;

Gets a prompt: the result (description, messages) as JSON.

function

ListPrompts

#
EStatus ListPrompts( std::string & sPromptsJson ) noexcept;

The prompts, as the JSON array of the list (the pages joined).

function

Complete

#
EStatus Complete( bool bPrompt, std::string_view sRef, std::string_view sArgument, std::string_view sValue, std::vector< std::string > & Values ) noexcept;

completion/complete: the values.

function

Listen

#
EStatus Listen( bool bTools, bool bPrompts, bool bResources, const std::vector< std::string > & ResourceUris ) noexcept;

Opens a subscriptions/listen stream (2026-07-28) or, in the 2025-11-25, subscribes to the resources (resources/subscribe). The notifications go to pfnNotification.

function

AsToolRegistry

#
EStatus AsToolRegistry( Tools::CToolRegistry & Registry ) noexcept;

Adds every tool of the server to Registry (not final), as JSON tools whose handler calls the server: the AI-03 and the AI-08 use the server with no extra code. A schema the AI-02 does not compile goes as {"type":"object"} (the server validates anyway). The client must outlive the registry.

eOk, or the first refusal of the registry (a name its rules do not take: use Tools::ENameRules::eMcp for names with a dot).
alias

bool

Ethereal::Ai::Mcp#
using PFN_ApproveSampling = bool ( * )( void * pUser, std::string_view sParamsJson );

The approval of a sampling request (the human in the loop the protocol asks for): return true to let it go to the model.

mcp_http.hpp

#include <ethereal/cpp/ai/mcp/mcp_http.hpp>

The Streamable HTTP transport of Ai::Mcp: a small HTTP/1.1 server for a CServer (CHttpServer), and the client transport over Http::CClient (CreateHttpTransport).

2026-07-28 (protocolo.md, section 17): one endpoint, POST only. Each POST carries one request or one notification. A notification is answered 202 with no body. A request is answered with application/json (the response alone) or with text/event-stream (the notifications of that request, then the response, which ends the stream). Closing the stream cancels the request. Every POST carries MCP-Protocol-Version, Mcp-Method and, for tools/call, resources/read and prompts/get, Mcp-Name: a header that disagrees with the body is a 400 with -32020. GET and DELETE are 405.

2025-11-25 (kept for the clients of that revision): the initialize opens a session, whose id goes back in Mcp-Session-Id and must come on every later request (404 once it is gone). A GET with the id opens the stream of the messages that belong to no request (list changed, resource updated), and a DELETE ends the session. The server sends no event ids, so a stream is not resumed (the revision allows it).

Security, on by default: Origin is checked on every request (403 when it is not allowed), a server on the loopback also checks Host (the defence against DNS rebinding), and the listener binds only to 127.0.0.1 unless told otherwise. Authorization is optional: a bearer validator turns it on (SHttpAuth).

The server is one thread per connection plus one watcher thread, which notices a client that closed its stream (and cancels the request) and keeps the idle streams alive with SSE comments. A connection holds its thread for its whole life, so the number of connections is capped (SHttpServerConfig::uMaxConnections).

enum

EAuthResult

Ethereal::Ai::Mcp#
C++
enum class   EAuthResult : ETL_UINT8
{
    eAllow = 0,                /// The token is good for this server and this request.
    eInvalidToken,            /// Missing, malformed, expired, or issued for another audience: 401.
    eInsufficientScope        /// Good, but without the scope the request needs: 403.
};

What a bearer validator decides.

struct

SAuthRequest

Ethereal::Ai::Mcp#
C++
struct   SAuthRequest
{
    std::string_view    sToken;            /// The bearer token, without the "Bearer " prefix.
    std::string_view    sHttpMethod;    /// POST, GET or DELETE.
    std::string_view    sMcpMethod;        /// The Mcp-Method header (2026-07-28), or empty.
    std::string_view    sMcpName;        /// The Mcp-Name header, or empty.
};

What a validator sees of the request. The views live during the call only.

alias

EAuthResult

Ethereal::Ai::Mcp#
using PFN_ValidateBearer = EAuthResult ( * )( void * pUser, const SAuthRequest & Request );

Validates a bearer token. Called on every request, from the connection's thread (several at once). It must check the audience (RFC 8707): a token issued for another resource is eInvalidToken.

struct

SHttpAuth

Ethereal::Ai::Mcp#
C++
struct   SHttpAuth
{
    /// @brief  Null turns authorization off.
    PFN_ValidateBearer    pfnValidate = nullptr;
    void *                pUser = nullptr;

    /// @brief  The absolute URL of the protected resource metadata (RFC 9728), for the
    ///             WWW-Authenticate header. Required with a validator.
    std::string            sResourceMetadataUrl;

    /// @brief  The scopes the server asks for (the scope parameter of the header). May be
    ///             empty.
    std::string            sScope;

    /// @brief  The protected resource metadata document (a JSON object). When not empty it is
    ///             served, with no authorization, at /.well-known/oauth-protected-resource and at
    ///             that path followed by the endpoint path.
    std::string            sResourceMetadataJson;
};

Optional authorization of a CHttpServer (protocolo.md, section 18). With a validator, a request without a valid bearer token gets 401 with 'WWW-Authenticate: Bearer resource_metadata="..."', and one without the scope gets 403 with error="insufficient_scope".

The token is never logged nor kept by the server, and it is never sent on to another service.
struct

SHttpServerConfig

Ethereal::Ai::Mcp#
C++
struct   SHttpServerConfig
{
    /// @brief  The port. Zero lets the system choose (see CHttpServer::Port).
    ETL_UINT16                        uPort = 0u;

    /// @brief  Listen on every interface instead of 127.0.0.1 only. A server reachable from
    ///             the network should also set Auth.
    bool                            bAnyInterface = false;

    /// @brief  The path of the endpoint. The query is ignored.
    std::string                        sPath = "/mcp";

    /// @brief  The origins allowed besides the local ones (http or https, with any port, on
    ///             localhost, 127.0.0.1 or [::1]). Exact, case insensitive (as
    ///             "https://app.example.com"). A request without Origin is allowed (it does not
    ///             come from a browser), and the literal "null" origin never is.
    std::vector< std::string >        AllowedOrigins;

    /// @brief  Check that Host names the loopback when the server listens on it. Turn it off
    ///             only behind a proxy that rewrites Host.
    bool                            bCheckHost = true;

    /// @brief  The most connections at once. One more is answered 503 and closed.
    ETL_UINT32                        uMaxConnections = 64u;

    /// @brief  The longest request head (the request line and the headers).
    ETL_UINT32                        uMaxHeadBytes = 16u * 1024u;

    /// @brief  How long a connection may take to send a request, and stay idle between two.
    ETL_UINT32                        uIdleTimeoutMs = 30000u;

    /// @brief  An SSE stream silent for this long gets a comment, so proxies keep it open.
    ///             Zero sends none.
    ETL_UINT32                        uKeepAliveMs = 15000u;

    /// @brief  2025-11-25: how long a session lives without a request, and how many at once.
    ETL_UINT32                        uSessionIdleMs = 30u * 60u * 1000u;
    ETL_UINT32                        uMaxSessions = 256u;

    /// @brief  Authorization (off by default).
    SHttpAuth                        Auth;
};
class

CHttpServer

Ethereal::Ai::Mcp#

Serves a CServer over Streamable HTTP.

class CHttpServer
C++
Mcp::CHttpServer Http;
Mcp::SHttpServerConfig Config;
Config.uPort = 8765;
if( Http.Start( Server, Config ) == Mcp::EStatus::eOk )
    WaitForShutdown();
Http.Stop();

The CServer must outlive the CHttpServer (or its Stop).

constructor

CHttpServer

#
CHttpServer() noexcept = default;
function

Start

#
EStatus Start( CServer & Server, const SHttpServerConfig & Config ) noexcept;

Binds and starts accepting, on threads of its own. Returns at once.

eOk, eInvalidArgument (a path that does not start with '/', auth without the metadata URL, already started), eTransport (the port could not be bound), eOutOfMemory, eNotLicensed.
function

Stop

#
void Stop( void ) noexcept;

Stops accepting, closes every connection (the requests running are cancelled and the streams end) and waits for the threads. Safe to call twice.

function

Port

#
ETL_UINT16 Port( void ) const noexcept;

The port it listens on (the one the system chose when the config said zero), or zero when not started.

function

ConnectionCount

#
ETL_UINT32 ConnectionCount( void ) const noexcept;

The connections open now and the 2025-11-25 sessions alive (for the tests).

function

SessionCount

#
ETL_UINT32 SessionCount( void ) const noexcept;
alias

bool

Ethereal::Ai::Mcp#
using PFN_GetToken = bool ( * )( void * pUser, std::string & sToken );

Gives the bearer token for the next request (it may refresh it). Return false to send none. Called from the transport's threads.

struct

SHttpClientSpec

Ethereal::Ai::Mcp#
C++
struct   SHttpClientSpec
{
    /// @brief  The URL of the endpoint (http or https).
    std::string                                                    sUrl;

    /// @brief  Headers added to every request. Never put the token here: use pfnToken or
    ///             sBearerToken, which are not echoed in errors.
    std::vector< std::pair< std::string, std::string > >        Headers;

    /// @brief  A fixed bearer token, used when pfnToken is null. Empty sends none.
    std::string                                                    sBearerToken;
    PFN_GetToken                                                pfnToken = nullptr;
    void *                                                        pTokenUser = nullptr;

    /// @brief  The OAuth flow (mcp_oauth.hpp), which wins over sBearerToken and pfnToken:
    ///             the token comes from it, and a 401 (or a 403 with insufficient_scope) runs
    ///             the flow and sends the request again. Null: none.
    std::shared_ptr< COAuthClient >                                pOAuth;

    /// @brief  The connection timeout, and the most connections to the server at once (each
    ///             request and each open stream holds one).
    ETL_UINT32                                                    uConnectTimeoutMs = 10000u;
    ETL_UINT32                                                    uMaxConnections = 16u;

    /// @brief  2025-11-25: open the GET stream after the initialize, for the messages of the
    ///             server that belong to no request.
    bool                                                        bOpenGetStream = true;
};
function

CreateHttpTransport

Ethereal::Ai::Mcp#
std::unique_ptr< IClientTransport > CreateHttpTransport( const SHttpClientSpec & Spec ) noexcept;

A transport to a server over Streamable HTTP. Each message goes out in a POST of its own, on a thread of its own, and what comes back (the JSON or every event of the stream) goes to the client. An answer that is not JSON-RPC (403, 500, a failed connection) comes back as an error response for that request, with code -32603, the message "HTTP <status>" (or the transport error), and the data { "httpStatus": n, "wwwAuthenticate": "..." }, so a 401 can start the authorization flow of the application. With SHttpClientSpec::pOAuth the transport runs the flow itself, and only a flow that failed comes back so (with "oauthError" in the data).

A notifications/cancelled is not sent on 2026-07-28: the transport closes the stream of that request, which is how the revision cancels. Close ends the streams, and on 2025-11-25 sends the DELETE of the session.

The transport, or null (out of memory, an invalid URL, not licensed).

mcp_jsonrpc.hpp

#include <ethereal/cpp/ai/mcp/mcp_jsonrpc.hpp>

JSON-RPC 2.0 for Ai::Mcp: a message read in one pass with no DOM (the parts are views into the input), a builder for the messages that go out, and the table of the requests waiting for an answer, with time limits and cancellation.

The rules of MCP over JSON-RPC (protocolo.md, section 1): an id is a string or an integer and never null, a notification has no id, an error may come without an id when the request could not be read. No supported revision has batching: an array is an invalid request.

enum

EMessageKind

Ethereal::Ai::Mcp#
C++
enum class   EMessageKind : ETL_UINT8
{
    eRequest = 0,        /// method and id.
    eNotification,        /// method, no id.
    eResult,            /// id and result.
    eError                /// error, and an id unless the request could not be read.
};
enum

EIdKind

Ethereal::Ai::Mcp#
C++
enum class   EIdKind : ETL_UINT8
{
    eNone = 0,            /// No id (a notification, or an error with no id or a null id).
    eNumber,            /// An integer.
    eString                /// A string.
};
const

kMaxMethodBytes

Ethereal::Ai::Mcp#
inline constexpr std::size_t kMaxMethodBytes = 127u;

The longest method name the reader keeps (longer ones are unknown methods).

struct

SMessage

Ethereal::Ai::Mcp#
C++
struct   SMessage
{
    SMessage() noexcept = default;

    SMessage( const SMessage & Other ) noexcept
    {
        *this = Other;
    }

    SMessage & operator=( const SMessage & Other ) noexcept
    {
        if( this == &Other )
            return *this;

        eKind = Other.eKind;
        eIdKind = Other.eIdKind;
        sId = Other.sId;
        iId = Other.iId;
        std::memcpy( aMethod, Other.aMethod, sizeof( aMethod ) );
        bMethodTooLong = Other.bMethodTooLong;
        sParams = Other.sParams;
        sResult = Other.sResult;
        iErrorCode = Other.iErrorCode;
        sErrorMessage = Other.sErrorMessage;
        sErrorData = Other.sErrorData;
        sRaw = Other.sRaw;

        /// The method in the source buffer moves to this buffer, any other view stays.
        const std::uintptr_t uView = reinterpret_cast< std::uintptr_t >( Other.sMethod.data() );
        const std::uintptr_t uBuffer = reinterpret_cast< std::uintptr_t >( Other.aMethod );
        const bool bInBuffer = uView >= uBuffer && uView < uBuffer + sizeof( Other.aMethod );
        sMethod = bInBuffer ? std::string_view( aMethod + ( uView - uBuffer ), Other.sMethod.size() ) : Other.sMethod;
        return *this;
    }

    EMessageKind        eKind = EMessageKind::eRequest;

    /// @brief  The id as it came (the JSON token: 42 or "abc", quotes and escapes kept),
    ///             to answer with it unchanged. iId holds it when it is a number.
    EIdKind                eIdKind = EIdKind::eNone;
    std::string_view    sId;
    ETL_INT64            iId = 0;

    /// @brief  The method, unescaped. Empty for the responses.
    std::string_view    sMethod;
    char                aMethod[ kMaxMethodBytes + 1u ] = {};
    bool                bMethodTooLong = false;

    /// @brief  The params, the result and the error data as raw JSON (empty when absent).
    std::string_view    sParams;
    std::string_view    sResult;

    /// @brief  The error: the code, the message (the raw string token, quotes included)
    ///             and the data.
    ETL_INT64            iErrorCode = 0;
    std::string_view    sErrorMessage;
    std::string_view    sErrorData;

    /// @brief  The whole message.
    std::string_view    sRaw;
};

One JSON-RPC message. The views point into the text given to ParseMessage (the method is copied, unescaped, into aMethod).

A copy keeps sMethod on its own aMethod: the default copy would leave it pointing into the source, which may be a temporary.

struct

SParseError

Ethereal::Ai::Mcp#
C++
struct   SParseError
{
    /// @brief  eParseError (not JSON) or eInvalidMessage.
    EStatus                eStatus = EStatus::eOk;

    /// @brief  The JSON-RPC code of the answer: kParseError or kInvalidRequest.
    ETL_INT32            iCode = 0;

    /// @brief  The id, when it could be read (the answer carries it), or empty.
    std::string_view    sId;

    /// @brief  A short message for the answer. Never null.
    const char *        pMessage = "";
};

Why a text is not a message, and how to answer it.

function

ParseMessage

Ethereal::Ai::Mcp#
EStatus ParseMessage( std::string_view sJson, SMessage & Out, SParseError * pError = nullptr, std::size_t uMax = kDefaultMaxMessageBytes ) noexcept;

Reads one JSON-RPC message, with no DOM, checking the rules of MCP.

sJson
The message (one line of the stdio transport, one HTTP body).
Out
Receives the message.
pError
Receives why it is not one. May be null.
uMax
Most bytes of a message (eLimitExceeded above it).
eOk, eParseError, eInvalidMessage, eLimitExceeded or eNotLicensed.
function

FindMember

Ethereal::Ai::Mcp#
bool FindMember( std::string_view sObject, std::string_view sKey, std::string_view & sValue ) noexcept;

The raw value of the member sKey of the JSON object sObject (top level only), or false when there is no such member or sObject is not an object.

function

StringValue

Ethereal::Ai::Mcp#
bool StringValue( std::string_view sToken, std::string & Out ) noexcept;

The text of a raw JSON string token ("..." with escapes) into Out. False when it is not a string, or invalid.

function

StringEquals

Ethereal::Ai::Mcp#
bool StringEquals( std::string_view sToken, std::string_view sText ) noexcept;

A raw JSON string token compared with a plain text (escapes decoded).

function

Int64Value

Ethereal::Ai::Mcp#
bool Int64Value( std::string_view sToken, ETL_INT64 & Out ) noexcept;

A raw JSON integer. False when it is not one, or out of range.

function

DoubleValue

Ethereal::Ai::Mcp#
bool DoubleValue( std::string_view sToken, double & Out ) noexcept;

A raw JSON number (integer or not). False when it is not one.

function

BoolValue

Ethereal::Ai::Mcp#
bool BoolValue( std::string_view sToken, bool & Out ) noexcept;

A raw JSON true or false. False when it is neither.

function

IsObject

Ethereal::Ai::Mcp#
bool IsObject( std::string_view sValue ) noexcept;

True when the raw value is a JSON object (it starts with '{').

function

ForEachMember

Ethereal::Ai::Mcp#
bool ForEachMember( std::string_view sObject, bool ( *pfn )( void * pUser, std::string_view sKey, std::string_view sValue ), void * pUser ) noexcept;

Calls pfn for each member of a JSON object: the key (unescaped into the callback's view, valid during the call) and the raw value. Stops when it returns false. False when sObject is not a valid object.

function

ForEachItem

Ethereal::Ai::Mcp#
bool ForEachItem( std::string_view sArray, bool ( *pfn )( void * pUser, std::string_view sValue ), void * pUser ) noexcept;

Calls pfn for each item of a JSON array (the raw value). False when sArray is not a valid array.

class

CJsonBuilder

Ethereal::Ai::Mcp#

Writes JSON into a string that keeps its memory between messages.

class CJsonBuilder

The commas are placed by the builder. Strings are escaped by the JSON writer of the library, and a byte sequence that is not UTF-8 becomes U+FFFD, so the output is always valid JSON. Raw writes the caller's JSON as it is (checked only when asked). Once warm, building a message does not allocate.

constructor

CJsonBuilder

#
CJsonBuilder() noexcept = default;
function

Clear

#
void Clear( void ) noexcept;

Forgets the text, keeps the memory.

function

BeginObject

#
CJsonBuilder & BeginObject( void ) noexcept;
function

EndObject

#
CJsonBuilder & EndObject( void ) noexcept;
function

BeginArray

#
CJsonBuilder & BeginArray( void ) noexcept;
function

EndArray

#
CJsonBuilder & EndArray( void ) noexcept;
function

Key

#
CJsonBuilder & Key( std::string_view sKey ) noexcept;
function

String

#
CJsonBuilder & String( std::string_view sValue ) noexcept;
function

Int

#
CJsonBuilder & Int( ETL_INT64 iValue ) noexcept;
function

Double

#
CJsonBuilder & Double( double dValue ) noexcept;
function

Bool

#
CJsonBuilder & Bool( bool bValue ) noexcept;
function

Null

#
CJsonBuilder & Null( void ) noexcept;
function

Raw

#
CJsonBuilder & Raw( std::string_view sJson, bool bCheck = false ) noexcept;

A value given as JSON text. With bCheck it must be one valid JSON value.

function

Base64

#
CJsonBuilder & Base64( std::string_view sBytes ) noexcept;

Base64 of bytes, as a string value.

function

Ok

#
bool Ok( void ) const noexcept

False after a failure (no memory, a raw value that is not JSON, unbalanced).

function

View

#
std::string_view View( void ) const noexcept

The text so far.

function

Text

#
std::string & Text( void ) noexcept

The string itself (to move it out).

function

BeginResult

Ethereal::Ai::Mcp#
void BeginResult( CJsonBuilder & B, std::string_view sIdRaw ) noexcept;

{"jsonrpc":"2.0","id":<sId raw>,"result": (the caller writes the result and EndObject).

function

WriteError

Ethereal::Ai::Mcp#
void WriteError( CJsonBuilder & B, std::string_view sIdRaw, ETL_INT32 iCode, std::string_view sMessage, std::string_view sDataRaw = {} ) noexcept;

A whole error response. An empty sIdRaw writes "id":null. sDataRaw may be empty.

function

BeginRequest

Ethereal::Ai::Mcp#
void BeginRequest( CJsonBuilder & B, ETL_INT64 iId, std::string_view sMethod ) noexcept;

{"jsonrpc":"2.0","id":N,"method":"m","params": (the caller writes the params and EndObject).

function

BeginNotification

Ethereal::Ai::Mcp#
void BeginNotification( CJsonBuilder & B, std::string_view sMethod ) noexcept;

{"jsonrpc":"2.0","method":"m","params": (the caller writes the params and EndObject).

class

CPendingRequests

Ethereal::Ai::Mcp#

The requests sent and waiting for an answer: the ids (integers, from 1, never reused while pending), the time limit, cancellation, and the close that wakes every waiter.

class CPendingRequests

Thread safe: one thread reads the answers (Complete), the senders wait (Wait). An answer for an id that is not pending (late, after a cancel or a time out) is ignored, as the protocol asks.

constructor

CPendingRequests

#
explicit CPendingRequests( ETL_UINT32 uMaxPending = 1024u ) noexcept;
function

Begin

#
ETL_INT64 Begin( void ) noexcept;

Reserves a new id. 0 when the table is full or closed.

function

Complete

#
bool Complete( const SMessage & Answer ) noexcept;

Delivers an answer (a result or an error with a numeric id). The raw message is copied for the waiter. False when no request waits for that id.

function

Wait

#
EStatus Wait( ETL_INT64 iId, ETL_UINT32 uTimeoutMs, std::string & sAnswer, const std::atomic< bool > * pCancel = nullptr, const std::atomic< bool > * pHold = nullptr ) noexcept;

Waits for the answer to iId and takes it (the raw message).

uTimeoutMs
Zero: no limit.
pCancel
Set to true from any thread to stop waiting. May be null.
pHold
While true, the time limit starts over (the user is authorizing). May be null.
eOk, eTimedOut, eCancelled, eClosed, eNotFound (no such pending id) or eOutOfMemory. On any status but eOk the id is no longer pending.
function

Abandon

#
void Abandon( ETL_INT64 iId ) noexcept;

Forgets a pending id (the answer, if it comes, is ignored).

function

Close

#
void Close( EStatus eWhy = EStatus::eClosed ) noexcept;

Wakes every waiter with eWhy (eClosed by default) and refuses new ids until Reopen.

function

Reopen

#
void Reopen( void ) noexcept;

Takes new ids again after Close.

function

Count

#
ETL_UINT32 Count( void ) const noexcept;

Ids pending now.

mcp_llm.hpp

#include <ethereal/cpp/ai/mcp/mcp_llm.hpp>

The sampling of an MCP client answered by Ai::Llm: the server's sampling/createMessage becomes a request to a provider, behind an approval hook (the human in the loop the protocol asks for).

Sampling is deprecated in the 2026-07-28 but still part of both supported revisions (M3). Give SampleWithLlm and an SLlmSampler to SClientConfig::pfnSampling and pSamplingUser.

struct

SLlmSampler

Ethereal::Ai::Mcp#
C++
struct   SLlmSampler
{
    /// @brief  The provider client. Must outlive the MCP client.
    Llm::CClient *            pClient = nullptr;

    /// @brief  The model. The server's hints are advisory: they are not followed.
    std::string                sModel;

    /// @brief  The most tokens the client allows, whatever the server asks. Zero: the server's maxTokens.
    ETL_UINT32                uMaxTokensCap = 4096u;

    /// @brief  The approval: false refuses the request. Null approves everything (not
    ///             recommended: the protocol asks for a person able to deny).
    PFN_ApproveSampling        pfnApprove = nullptr;
    void *                    pApproveUser = nullptr;
};
function

SampleWithLlm

Ethereal::Ai::Mcp#
EStatus SampleWithLlm( void * pUser, std::string_view sParamsJson, CJsonBuilder & Result ) noexcept;

A PFN_InputRequest: pUser is an SLlmSampler. The messages (text and image blocks), the system prompt, maxTokens, temperature and the stop sequences go to the provider; the answer comes back as role, content (text), model and stopReason.

eOk, eCancelled (not approved), eInvalidArgument (params the request cannot take), or eRemoteError (the provider failed).

mcp_oauth.hpp

#include <ethereal/cpp/ai/mcp/mcp_oauth.hpp>

The OAuth 2.1 flow of the Ai::Mcp client (the authorization of the 2026-07-28 and 2025-11-25 revisions, protocolo.md, section 18, and oauth.md).

C++
Mcp::SOAuthConfig Auth;
Auth.pfnOpenUrl = []( void *, std::string_view sUrl ) { return OpenBrowser( sUrl ); };
Auth.sClientMetadataUrl = "https://app.example.com/oauth/client.json";
auto pAuth = Mcp::COAuthClient::Create( "https://mcp.example.com/mcp", Auth );

Mcp::SHttpClientSpec Spec;
Spec.sUrl = "https://mcp.example.com/mcp";
Spec.pOAuth = pAuth;                  /// the transport asks it for the token
Mcp::CClient Client;
Client.ConnectHttp( Spec, Mcp::SClientConfig{} );

When the server answers 401 (or 403 with insufficient_scope), the transport hands the WWW-Authenticate header to the COAuthClient, which runs the flow and the request goes again:

1. The protected resource metadata (RFC 9728): the resource_metadata URL of the header, or the well-known URLs of the endpoint (the path inserted first, then the root). The resource it names must be the endpoint or a parent of it on the same origin. 2. The authorization server metadata (RFC 8414 and OpenID Connect discovery, in the order of the specification), whose issuer must be the one the URL was built from, with S256 in code_challenge_methods_supported. 3. The client: a registration given for that issuer, else a Client ID Metadata Document (when the server says it takes them), else dynamic registration (RFC 7591), kept per issuer. 4. The authorization request with PKCE (S256), state and resource (RFC 8707), opened in the browser by the application. The redirect comes to a listener on 127.0.0.1 (or to DeliverRedirect, for a redirect URI of the application). The state is checked, and the iss of the response (RFC 9207). 5. The token request (with the resource), and later the refresh, shortly before the token expires.

The scope is the one of the challenge, else the scopes_supported of the resource metadata, else SOAuthConfig::Scopes. A 403 with insufficient_scope asks for the union of what was asked before and what the challenge names, a few times at most.

struct

SOAuthTokens

Ethereal::Ai::Mcp#
C++
struct   SOAuthTokens
{
    std::string        sAccessToken;
    std::string        sRefreshToken;        /// Empty when the server gave none.
    std::string        sScope;                /// The scope granted (or asked, when the server did not say).
    ETL_INT64        iExpiresAt = 0;        /// Unix time, in seconds. Zero: the server did not say.
};

The tokens of one resource at one authorization server.

struct

SOAuthClientInfo

Ethereal::Ai::Mcp#
C++
struct   SOAuthClientInfo
{
    /// @brief  The issuer of the server (the exact string of its metadata).
    std::string        sIssuer;

    std::string        sClientId;

    /// @brief  Empty for a public client.
    std::string        sClientSecret;

    /// @brief  "none", "client_secret_basic" or "client_secret_post". Empty: basic with a
    ///             secret, none without.
    std::string        sAuthMethod;

    /// @brief  The redirect URI the registration was made with (dynamic registration). A
    ///             registration made for another redirect URI is made again.
    std::string        sRedirectUri;
};

A client registered at one authorization server.

class

IOAuthStore

Ethereal::Ai::Mcp#

Where the tokens and the registrations live. The tokens are keyed by the resource and the issuer, the registrations by the issuer (a credential of one server is never offered to another). Called from the transport's threads, one call at a time per COAuthClient.

class IOAuthStore
The tokens and the client secrets must be kept confidential: an implementation that writes them down encrypts them (the keychain of the system, DPAPI on Windows).
destructor

~IOAuthStore

#
virtual ~IOAuthStore() = default;
function

LoadTokens

#
virtual bool LoadTokens( std::string_view sResource, std::string_view sIssuer, SOAuthTokens & Out ) = 0;
function

SaveTokens

#
virtual void SaveTokens( std::string_view sResource, std::string_view sIssuer, const SOAuthTokens & Tokens ) = 0;
function

ClearTokens

#
virtual void ClearTokens( std::string_view sResource, std::string_view sIssuer ) = 0;
function

LoadClient

#
virtual bool LoadClient( std::string_view sIssuer, SOAuthClientInfo & Out ) = 0;
function

SaveClient

#
virtual void SaveClient( const SOAuthClientInfo & Client ) = 0;
function

CreateMemoryOAuthStore

Ethereal::Ai::Mcp#
std::shared_ptr< IOAuthStore > CreateMemoryOAuthStore( void ) noexcept;

A store in memory (the default): gone with the process.

alias

bool

Ethereal::Ai::Mcp#
using PFN_OpenAuthorizationUrl = bool ( * )( void * pUser, std::string_view sUrl );

Opens the authorization URL for the user (the system browser). It returns at once: the flow waits for the redirect. Return false when it could not open it. Called from a transport's thread.

struct

SOAuthConfig

Ethereal::Ai::Mcp#
C++
struct   SOAuthConfig
{
    /// @brief  Required: how the authorization URL reaches the user.
    PFN_OpenAuthorizationUrl            pfnOpenUrl = nullptr;
    void *                                pOpenUser = nullptr;

    /// @brief  Clients registered beforehand, one per issuer (the first choice).
    std::vector< SOAuthClientInfo >        Registered;

    /// @brief  The URL of the Client ID Metadata Document of this application (https, with
    ///             a path): the client_id, used with a server whose metadata has
    ///             client_id_metadata_document_supported. Its redirect_uris must have the
    ///             redirect URI of the flow. Empty: not used.
    std::string                            sClientMetadataUrl;

    /// @brief  Dynamic registration (RFC 7591), the last choice. The revision 2026-07-28
    ///             deprecates it, and keeps it for the servers that only have it.
    bool                                bDynamicRegistration = true;
    std::string                            sClientName = "Ethereal MCP client";
    std::string                            sClientUri;
    std::string                            sApplicationType = "native";

    /// @brief  The redirect URI. Empty: the listener of the flow, on
    ///             http://127.0.0.1:<uLoopbackPort><sLoopbackPath>. Anything else (a scheme of
    ///             the application, its own server) comes back by DeliverRedirect.
    std::string                            sRedirectUri;
    ETL_UINT16                            uLoopbackPort = 0u;        /// Zero lets the system choose.
    std::string                            sLoopbackPath = "/callback";

    /// @brief  The scopes when neither the challenge nor the resource metadata names any.
    std::vector< std::string >            Scopes;

    /// @brief  Ask for offline_access when the server lists it (for a refresh token).
    bool                                bOfflineAccess = true;

    /// @brief  The issuer for a server that publishes no resource metadata. Empty: such a
    ///             server cannot be authorized.
    std::string                            sAuthorizationServer;

    /// @brief  Accept http (no TLS) for the metadata and the endpoints on 127.0.0.1,
    ///             localhost and [::1] (development and tests). Anything else must be https.
    bool                                bAllowLoopbackHttp = true;

    /// @brief  The time the user has to authorize, the limit of each request to the
    ///             servers, how many step ups a request may cause, and how long before the
    ///             expiry the token is refreshed.
    ETL_UINT32                            uFlowTimeoutMs = 300000u;
    ETL_UINT32                            uHttpTimeoutMs = 15000u;
    ETL_UINT32                            uMaxStepUps = 2u;
    ETL_UINT32                            uRefreshMarginSeconds = 60u;

    /// @brief  Where tokens and registrations live. Null: in memory.
    std::shared_ptr< IOAuthStore >        pStore;
};
class

COAuthClient

Ethereal::Ai::Mcp#

The authorization of one MCP server. Shared by the transport (which asks for the token and reports the challenges) and the application. Every member is safe from any thread, and two challenges at once run one flow.

class COAuthClient
function

Create

#
static std::shared_ptr< COAuthClient > Create( std::string_view sServerUrl, const SOAuthConfig & Config ) noexcept;

For sServerUrl, the URL of the MCP endpoint (http or https).

The client, or null (no pfnOpenUrl, an invalid URL, out of memory, not licensed).
function

AccessToken

#
bool AccessToken( std::string & sToken, ETL_UINT64 * pGeneration = nullptr ) noexcept;

The token for the next request, refreshed first when it is about to expire.

sToken
Receives the token.
pGeneration
Receives the number of the token (see OnChallenge).
false when there is none yet (the request goes without one).
function

OnChallenge

#
EStatus OnChallenge( ETL_UINT32 uHttpStatus, std::string_view sWwwAuthenticate, ETL_UINT64 uGeneration, ETL_UINT32 uStepUps = 0u ) noexcept;

The server refused a request: runs the flow, unless another call already got a newer token than uGeneration (the one the request carried).

uHttpStatus
401 or 403.
sWwwAuthenticate
The header, as it came (may be empty).
uGeneration
The number of the token the request carried (zero: none).
uStepUps
The step ups this request already caused (a 403 past SOAuthConfig::uMaxStepUps is refused).
eOk when a token is ready (send the request again), eUnauthorized when the flow failed (LastError says why), eCancelled, eTimedOut.
function

Authorize

#
EStatus Authorize( void ) noexcept;

Runs the flow now, before the first request: the resource metadata comes from the well-known URLs of the endpoint. Does nothing when a token is already there.

function

DeliverRedirect

#
void DeliverRedirect( std::string_view sRedirectUrl ) noexcept;

The redirect that came to the redirect URI of the application (the whole URL, with the query). Ignored when no flow waits for one.

function

Cancel

#
void Cancel( void ) noexcept;

Stops the flow in progress (it returns eCancelled).

function

Logout

#
void Logout( void ) noexcept;

Forgets the tokens of this resource (the store included).

function

AuthorizingFlag

#
const std::atomic< bool > & AuthorizingFlag( void ) const noexcept;

A flow is running (the user is authorizing). The client does not count the time of a request while it is raised.

function

LastError

#
std::string LastError( void ) const noexcept;

Why the last flow failed, in English, never with a secret. Empty after a success.

function

Issuer

#
std::string Issuer( void ) const noexcept;

The issuer and the scope of the current tokens (empty without them).

function

GrantedScope

#
std::string GrantedScope( void ) const noexcept;
function

Resource

#
std::string Resource( void ) const noexcept;

The resource the tokens are for (RFC 8707): the endpoint, or the resource its metadata names.

function

MaxStepUps

#
ETL_UINT32 MaxStepUps( void ) const noexcept;

SOAuthConfig::uMaxStepUps (the transport stops resending past it).

mcp_progress.hpp

#include <ethereal/cpp/ai/mcp/mcp_progress.hpp>

The progress of the MCP request a handler is running in.

A tool handler (Ai::Tools), a resource read or a prompt runs on the thread of its MCP request. ReportProgress sends the notifications/progress of that request when the client asked for progress (a progressToken in the _meta), and does nothing otherwise. The progress must grow from one call to the next, as the protocol asks: a value that does not grow is not sent (M12).

function

ReportProgress

Ethereal::Ai::Mcp#
bool ReportProgress( double dProgress, double dTotal = 0.0, std::string_view sMessage = {} ) noexcept;
dProgress
Grows with each call.
dTotal
The total, or 0 when unknown.
sMessage
A human readable message, or empty.
True when a notification went out.

mcp_server.hpp

#include <ethereal/cpp/ai/mcp/mcp_server.hpp>

The MCP server: tools from an Ai::Tools registry, resources and resource templates, prompts, completion, pagination, subscriptions, logging, progress and cancellation, in the two revisions the module speaks.

The core (CServer::Handle) takes one message of one connection and writes the answers and notifications to the connection's output. It knows nothing of the transport (M8): the stdio and HTTP transports only frame and deliver.

The revision of each message (M2): a request whose _meta carries io.modelcontextprotocol/protocolVersion is of the 2026-07-28 (stateless, every request self-contained); the initialize request opens a 2025-11-25 session on the connection.

Threads: Handle may be called from several threads at once for the same connection (the transports run each request on its own worker, so a cancellation can arrive while a tool runs). The registration (Attach, Add) happens before the first Handle.

struct

SServerInfo

Ethereal::Ai::Mcp#
C++
struct   SServerInfo
{
    std::string_view    sName;
    std::string_view    sVersion;
    std::string_view    sTitle;            /// May be empty.
    std::string_view    sInstructions;    /// May be empty: how a model should use the server.
};

Who the server is (the Implementation of the protocol). Copied.

struct

SServerConfig

Ethereal::Ai::Mcp#
C++
struct   SServerConfig
{
    /// @brief  Most bytes of one message.
    std::size_t                    uMaxMessageBytes = kDefaultMaxMessageBytes;

    /// @brief  Items per page of the lists (tools, resources, templates, prompts).
    ETL_UINT32                    uPageSize = 100u;

    /// @brief  The cache hints of the 2026-07-28: ttlMs of the lists and of discover, and of
    ///             resources/read. cacheScope is "public" for the lists and "private" for reads.
    ETL_UINT32                    uListTtlMs = 300000u;
    ETL_UINT32                    uReadTtlMs = 0u;

    /// @brief  Accept the 2025-11-25 (the initialize session).
    bool                        bLegacy = true;

    /// @brief  The policies of the tools (approval, lists, rate limit, output size).
    Tools::SRunnerOptions        ToolPolicies;

    /// @brief  Most requests running at once on one connection (the transports).
    ETL_UINT32                    uMaxConcurrent = 16u;
};
enum

ELogLevel

Ethereal::Ai::Mcp#
C++
enum class   ELogLevel : ETL_UINT8
{
    eDebug = 0,
    eInfo,
    eNotice,
    eWarning,
    eError,
    eCritical,
    eAlert,
    eEmergency,
    eNone = 0xFF        /// No logging asked.
};

The levels of the logging of MCP (RFC 5424), from the least severe.

function

LogLevelName

Ethereal::Ai::Mcp#
const char * LogLevelName( ELogLevel eLevel ) noexcept;

The text of a level ("debug"...).

function

ParseLogLevel

Ethereal::Ai::Mcp#
ELogLevel ParseLogLevel( std::string_view sText ) noexcept;

The level of a text, or eNone.

struct

SResourceDesc

Ethereal::Ai::Mcp#
C++
struct   SResourceDesc
{
    std::string_view    sUri;
    std::string_view    sName;
    std::string_view    sTitle;
    std::string_view    sDescription;
    std::string_view    sMimeType;
    ETL_INT64            iSize = -1;        /// -1: unknown.
};

A resource with a fixed URI. Copied.

struct

SResourceTemplateDesc

Ethereal::Ai::Mcp#
C++
struct   SResourceTemplateDesc
{
    std::string_view    sUriTemplate;
    std::string_view    sName;
    std::string_view    sTitle;
    std::string_view    sDescription;
    std::string_view    sMimeType;
};

A family of resources by URI template (RFC 6570, see mcp_uritemplate.hpp). Copied.

struct

SUriVariable

Ethereal::Ai::Mcp#
C++
struct   SUriVariable
{
    std::string_view    sName;
    std::string_view    sValue;        /// Percent-decoded.
};

A variable taken from the URI by a template.

class

CResourceOut

Ethereal::Ai::Mcp#

Where a read callback writes the contents.

class CResourceOut
function

Text

#
EStatus Text( std::string_view sUri, std::string_view sMimeType, std::string_view sText ) noexcept;

A text content.

function

Blob

#
EStatus Blob( std::string_view sUri, std::string_view sMimeType, std::string_view sBytes ) noexcept;

A binary content (the bytes: base64 is done by the server).

alias

EStatus

Ethereal::Ai::Mcp#
using PFN_ReadResource = EStatus ( * )( void * pUser, std::string_view sUri, std::span< const SUriVariable > Vars, CResourceOut & Out );

Reads a resource.

Vars
The variables of the template that matched (empty for a fixed resource).
eOk with at least one content, eNotFound, or another status (an internal error).
struct

SPromptArgument

Ethereal::Ai::Mcp#
C++
struct   SPromptArgument
{
    std::string_view    sName;
    std::string_view    sDescription;
    bool                bRequired = false;
};

An argument of a prompt.

struct

SPromptDesc

Ethereal::Ai::Mcp#
C++
struct   SPromptDesc
{
    std::string_view                        sName;
    std::string_view                        sTitle;
    std::string_view                        sDescription;
    std::span< const SPromptArgument >        Arguments;
};

A prompt template. Copied.

class

CPromptOut

Ethereal::Ai::Mcp#

Where a prompt callback writes the messages.

class CPromptOut
function

Description

#
EStatus Description( std::string_view sText ) noexcept;

The description of the result.

function

Text

#
EStatus Text( bool bAssistant, std::string_view sText ) noexcept;

A message with a text block. bAssistant picks the role.

function

Image

#
EStatus Image( bool bAssistant, std::string_view sBytes, std::string_view sMimeType ) noexcept;

A message with an image block (the bytes).

function

Resource

#
EStatus Resource( bool bAssistant, std::string_view sUri, std::string_view sMimeType, std::string_view sText ) noexcept;

A message with an embedded text resource.

alias

EStatus

Ethereal::Ai::Mcp#
using PFN_GetPrompt = EStatus ( * )( void * pUser, std::string_view sName, std::string_view sArgumentsJson, CPromptOut & Out );

Builds a prompt. sArgumentsJson is the object of the arguments (strings), already checked for the required ones. Return eOk, eNotFound or eInvalidArgument (the client gets -32602).

struct

SCompleteRequest

Ethereal::Ai::Mcp#
C++
struct   SCompleteRequest
{
    bool                bPrompt = true;        /// ref/prompt (sRef is the name) or ref/resource (sRef is the template).
    std::string_view    sRef;
    std::string_view    sArgument;            /// The name of the argument.
    std::string_view    sValue;                /// What was typed so far.
    std::string_view    sContextJson;        /// context.arguments as JSON, or empty.
};
class

CCompletionOut

Ethereal::Ai::Mcp#
class CCompletionOut
function

Value

#
EStatus Value( std::string_view sValue ) noexcept;

One more value (at most 100 go out: the rest set hasMore).

function

Total

#
void Total( ETL_UINT32 uTotal ) noexcept

The total of values, when known.

function

HasMore

#
void HasMore( bool b ) noexcept

More values exist than the ones given.

alias

EStatus

Ethereal::Ai::Mcp#
using PFN_Complete = EStatus ( * )( void * pUser, const SCompleteRequest & Request, CCompletionOut & Out );
class

IOutput

Ethereal::Ai::Mcp#

Where the server writes the messages of one connection (a line of stdout, the body or an SSE event of an HTTP response). Called from several threads: an implementation must be thread safe (the session serializes its own calls, and a transport may also write an error of its own).

class IOutput
function

Send

#
virtual EStatus Send( std::string_view sMessage ) noexcept = 0;

One whole message.

destructor

~IOutput

#
virtual ~IOutput() = default;
class

CSession

Ethereal::Ai::Mcp#

One connection to the server: the 2025-11-25 state (initialized, the revision, the client capabilities, the log level, the resource subscriptions), the requests running (to cancel them), and the subscriptions/listen streams of the 2026-07-28.

class CSession
constructor

CSession

#
explicit CSession( IOutput & Output ) noexcept;
function

Revision

#
ERevision Revision( void ) const noexcept;

The revision of the session (eNone until initialize, or a 2026-07-28 message).

function

IsLegacyInitialized

#
bool IsLegacyInitialized( void ) const noexcept;

True after the 2025-11-25 initialize.

function

CancelAll

#
void CancelAll( void ) noexcept;

Cancels every request running on the session (the connection closed).

class

CServer

Ethereal::Ai::Mcp#
class CServer
constructor

CServer

#
explicit CServer( const SServerInfo & Info, const SServerConfig & Config = {} ) noexcept;
function

Status

#
EStatus Status( void ) const noexcept

eOk, or eOutOfMemory.

function

AttachTools

#
EStatus AttachTools( const Tools::CToolRegistry & Registry ) noexcept;

Serves the tools of a final registry (the MCP list of AI-04, ToolsJson( eMcp )). The registry must outlive the server. Once.

eOk, eInvalidArgument (not final, or a list the MCP dialect cannot carry), eOutOfMemory.
function

AddResource

#
EStatus AddResource( const SResourceDesc & Desc, PFN_ReadResource pfnRead, void * pUser ) noexcept;

A resource with a fixed URI.

function

AddResourceTemplate

#
EStatus AddResourceTemplate( const SResourceTemplateDesc & Desc, PFN_ReadResource pfnRead, void * pUser ) noexcept;

A resource template (eInvalidArgument when the template does not parse).

function

AddPrompt

#
EStatus AddPrompt( const SPromptDesc & Desc, PFN_GetPrompt pfnGet, void * pUser ) noexcept;

A prompt.

function

SetCompletion

#
EStatus SetCompletion( PFN_Complete pfnComplete, void * pUser ) noexcept;

The completion of prompt and template arguments (declares the capability).

function

Handle

#
EStatus Handle( CSession & Session, std::string_view sMessage ) noexcept;

One message of one connection. The answers and the notifications go to the session's output, maybe before Handle returns (a tool's progress), maybe later (a subscriptions/listen stream).

eOk when the message was handled (an error answer included), or the status of the output that failed.
function

Attach

#
EStatus Attach( CSession & Session ) noexcept;

Registers a session for the notifications (list changed, resource updated). The transports call it when the connection opens, and Detach when it closes.

function

Detach

#
void Detach( CSession & Session ) noexcept;
function

NotifyToolsChanged

#
void NotifyToolsChanged( void ) noexcept;

The tool, resource and prompt lists changed: the subscribers are told.

function

NotifyResourcesChanged

#
void NotifyResourcesChanged( void ) noexcept;
function

NotifyPromptsChanged

#
void NotifyPromptsChanged( void ) noexcept;
function

NotifyResourceUpdated

#
void NotifyResourceUpdated( std::string_view sUri ) noexcept;

A resource changed: the subscribers of sUri are told.

function

EndSubscriptions

#
void EndSubscriptions( void ) noexcept;

Ends every subscriptions/listen stream (the server shuts down).

function

CapabilitiesJson

#
std::string_view CapabilitiesJson( void ) const noexcept;

The capabilities the server declares, as JSON (for the transports and the tests).

function

Config

#
const SServerConfig & Config( void ) const noexcept

The configuration.

mcp_transport.hpp

#include <ethereal/cpp/ai/mcp/mcp_transport.hpp>

The transports of Ai::Mcp: the newline framing of stdio for the server (CLineServer, and RunStdio over the process's own stdin and stdout), and the client transports (the child process over stdio, and an in-process connection to a CServer).

stdio (protocolo.md, section 17): one message per line, no newline inside a message, nothing but messages on stdout, logs on stderr. On Windows the streams go to binary mode, so "\r\n" is never translated.

The server reads on one thread and answers the requests on a small pool of workers: a long tool does not hold the others, and a notifications/cancelled is handled at once, on the reading thread, while the tool runs.

class

CLineServer

Ethereal::Ai::Mcp#

The stdio framing of the server, over any byte stream: Feed the bytes read, the complete lines go to the server, and the answers go to the output (one line each).

class CLineServer

Requests run on the workers (SServerConfig::uMaxConcurrent of them, at least one). Notifications run on the thread of Feed. A line longer than the limit is answered with an invalid request and dropped up to its newline.

constructor

CLineServer

#
CLineServer( CServer & Server, IOutput & Output ) noexcept;
Server
The server (it must outlive this object).
Output
Where the messages go: Send receives the message without the newline.
function

Feed

#
EStatus Feed( std::string_view sBytes ) noexcept;

Bytes read from the stream, in any slicing.

function

Finish

#
void Finish( void ) noexcept;

The stream ended: the last line (without newline) is handled, the requests running finish, and the subscriptions end. Returns when all is done.

function

Session

#
CSession & Session( void ) noexcept;

The session of the connection (for the tests).

function

RunStdio

Ethereal::Ai::Mcp#
EStatus RunStdio( CServer & Server ) noexcept;

Serves Server on the process's stdin and stdout until stdin closes (the client's way to end it). Puts both streams in binary mode on Windows. Each answer goes out in one write.

eOk when stdin closed, eTransport when reading or writing failed.
alias

void

Ethereal::Ai::Mcp#
using PFN_OnMessage = void ( * )( void * pUser, std::string_view sMessage );

Receives each message that arrives (on the transport's thread).

alias

void

Ethereal::Ai::Mcp#
using PFN_OnClosed = void ( * )( void * pUser, EStatus eWhy );

The transport ended (closed by the other side, or failed).

class

IClientTransport

Ethereal::Ai::Mcp#

How a CClient reaches a server.

class IClientTransport
function

Start

#
virtual EStatus Start( PFN_OnMessage pfnMessage, PFN_OnClosed pfnClosed, void * pUser ) noexcept = 0;

Starts delivering the messages that arrive. Once.

function

Send

#
virtual EStatus Send( std::string_view sMessage ) noexcept = 0;

Sends one message (thread safe).

function

Close

#
virtual void Close( void ) noexcept = 0;

Ends the connection (for stdio: close the child's stdin, wait, then kill).

function

HoldFlag

#
virtual const std::atomic< bool > * HoldFlag( void ) const noexcept

A flag raised while the transport waits on the user (the OAuth flow of the HTTP transport): the client does not count the time limit of a request then. Null: never.

destructor

~IClientTransport

#
virtual ~IClientTransport() = default;
struct

SProcessSpec

Ethereal::Ai::Mcp#
C++
struct   SProcessSpec
{
    std::string                                                    sExecutable;
    std::vector< std::string >                                    Args;
    std::vector< std::pair< std::string, std::string > >        Environment;        /// Added to (or replacing) the inherited one.
    bool                                                        bInheritEnvironment = true;
    std::string                                                    sWorkingDirectory;

    /// @brief  How long Close waits for the server to exit after its stdin closes, before
    ///             killing it.
    ETL_UINT32                                                    uExitWaitMs = 2000u;

    /// @brief  Receives what the server writes on stderr (its log), line by line. May be null.
    void ( *pfnStderr )( void * pUser, std::string_view sLine ) = nullptr;
    void *                                                        pStderrUser = nullptr;
};

The server process a stdio client starts.

function

CreateStdioTransport

Ethereal::Ai::Mcp#
std::unique_ptr< IClientTransport > CreateStdioTransport( const SProcessSpec & Spec ) noexcept;

A transport that starts the server as a child process and talks over its stdio.

function

CreateInProcessTransport

Ethereal::Ai::Mcp#
std::unique_ptr< IClientTransport > CreateInProcessTransport( CServer & Server ) noexcept;

A transport to a server in the same process (embedding, tests): the messages go through a CLineServer, with no process and no pipe.

mcp_types.hpp

#include <ethereal/cpp/ai/mcp/mcp_types.hpp>

The vocabulary of Ai::Mcp: the status codes, the JSON-RPC and MCP error codes, and the protocol revisions.

Everything here was taken from the specification pages of the two supported revisions, not from memory.

enum

EStatus

Ethereal::Ai::Mcp#
C++
enum class   EStatus : ETL_UINT32
{
    eOk = 0,
    eInvalidArgument,
    eOutOfMemory,
    eNotLicensed,
    eBufferTooSmall,
    eParseError,            /// Not JSON.
    eInvalidMessage,        /// JSON, but not a JSON-RPC message (or a batch, which no supported revision has).
    eLimitExceeded,            /// A message larger than the limit, too many pending requests.
    eTimedOut,                /// The request had no answer in time.
    eCancelled,                /// The request was cancelled.
    eClosed,                /// The connection closed.
    eTransport,                /// The transport failed (a pipe, a socket, a process).
    eRemoteError,            /// The other side answered with a JSON-RPC error.
    eUnsupportedVersion,    /// No protocol revision in common.
    eNotFound,                /// No such request, tool, resource or prompt.
    eUnauthorized            /// The OAuth flow of the client failed (COAuthClient::LastError says why).
};

The result of the functions of the module.

function

StatusName

Ethereal::Ai::Mcp#
const char * StatusName( EStatus eStatus ) noexcept;

The name of a status ("ok", "parse error"...). Never null.

const

kParseError

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kParseError = -32700;
const

kInvalidRequest

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kInvalidRequest = -32600;
const

kMethodNotFound

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kMethodNotFound = -32601;
const

kInvalidParams

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kInvalidParams = -32602;
const

kInternalError

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kInternalError = -32603;
const

kHeaderMismatch

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kHeaderMismatch = -32020;

2026-07-28: a header that does not match the body (HTTP 400).

const

kMissingRequiredClientCapability

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kMissingRequiredClientCapability = -32021;

2026-07-28: a client capability the request needs (HTTP 400), data.requiredCapabilities.

const

kUnsupportedProtocolVersion

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kUnsupportedProtocolVersion = -32022;

2026-07-28: a revision the server does not support (HTTP 400), data.supported and data.requested.

const

kResourceNotFoundLegacy

Ethereal::Ai::Mcp::ErrorCode#
inline constexpr ETL_INT32 kResourceNotFoundLegacy = -32002;

2025-11-25: resource not found (the 2026-07-28 uses kInvalidParams). Clients accept both.

enum

ERevision

Ethereal::Ai::Mcp#
C++
enum class   ERevision : ETL_UINT8
{
    eNone = 0,
    e2025_11_25,        /// The previous one: the initialize handshake, sessions.
    e2026_07_28            /// The current one, the target: stateless, per request _meta.
};

The protocol revisions the module speaks (M1).

const

kLatestRevision

Ethereal::Ai::Mcp#
inline constexpr ERevision kLatestRevision = ERevision::e2026_07_28;

The newest revision the module speaks.

function

RevisionName

Ethereal::Ai::Mcp#
const char * RevisionName( ERevision eRevision ) noexcept;

The text of a revision ("2026-07-28"), or "" for eNone.

function

ParseRevision

Ethereal::Ai::Mcp#
ERevision ParseRevision( std::string_view sText ) noexcept;

The revision of a text, or eNone when the module does not speak it.

const

size_t

Ethereal::Ai::Mcp#
inline constexpr std::size_t kDefaultMaxMessageBytes = std::size_t( 4u ) << 20;

The default limit of one message, in bytes (4 MiB).

mcp_uritemplate.hpp

#include <ethereal/cpp/ai/mcp/mcp_uritemplate.hpp>

URI templates (RFC 6570) for the resource templates of MCP: the template parsed once, and a URI matched against it with the variables taken out.

MCP uses the templates in the other direction from the RFC: the client asks for a URI, and the server finds the template that produced it. The RFC defines only the expansion, and matching is ambiguous in general, so the rules are these (M11):

  • {var} takes the characters up to the next literal of the template, and never '/', '?' or '#';
  • {+var} and {#var} take any characters up to the next literal ({#var} after a '#');
  • {/var} is '/' and one segment, {/var*} is one or more segments;
  • {.var} is '.' and a label;
  • {?a,b} and {&a,b} read the query (in any order, each name at most once, all optional);
  • {x,y} (several names in a simple expression) are separated by commas.

The values are percent-decoded. A literal compares byte for byte.

class

CUriTemplate

Ethereal::Ai::Mcp#
class CUriTemplate
struct

SMatch

#
C++
struct   SMatch
{
    std::string        sName;
    std::string        sValue;
};

A variable taken out of a URI.

constructor

CUriTemplate

#
CUriTemplate() = default;
function

Parse

#
EStatus Parse( std::string_view sTemplate ) noexcept;

Parses sTemplate. eInvalidArgument when it is not a template this matcher takes.

function

Match

#
bool Match( std::string_view sUri, std::vector< SMatch > & Out ) const noexcept;

True when sUri is one this template produces. Out gets the variables.

function

Names

#
const std::vector< std::string > & Names( void ) const noexcept

The names of the variables, in order.

function

Text

#
std::string_view Text( void ) const noexcept

The template.

function

PercentDecode

Ethereal::Ai::Mcp#
bool PercentDecode( std::string_view s, std::string & Out ) noexcept;

Percent-decodes s into Out. False on a bad escape.