Ce qu’il fait
- Serveur MCP en quelques lignes
- Vérifié avec les SDK officiels et le MCP Inspector
- Client MCP pour les serveurs existants
Mesuré
- Interopérabilité avec les SDK officiels et le MCP Inspector : 8 sur 8
- Couverture de lignes : 90.1%. ASan, TSan et 1 heure de libFuzzer par cible
- tools/call : 2.2 µs au p50. Objectif de 1 µs non atteint
- Aller-retour stdio : 342 µs, contre 381 µs pour le SDK TypeScript et 1,369 µs pour le SDK Python. Objectif de 10x plus rapide que les SDK officiels non atteint
Limites connues
- Ne parle que les révisions 2026-07-28 et 2025-11-25 du protocole. Un client ou serveur limité à une révision antérieure est refusé
- Le serveur HTTP est du HTTP/1.1 simple, un thread par connexion, sans TLS : hors loopback, placez un proxy devant
- Le serveur n'envoie pas de requêtes de lui-même : pas de sampling, d'elicitation ni de roots côté serveur
Ethereal::Ai::Mcp · AI pillar
The Model Context Protocol in C++, both sides. The server exposes the tools of an Ai::Tools registry, resources (fixed URI or URI template) and prompts, over stdio or Streamable HTTP, for Claude Desktop, Claude Code or any MCP client. The client connects to any MCP server over the same transports, calls its tools, reads resources, gets prompts, and can hand the server's tools to a model or an Ai::Agent as an Ai::Tools registry. The HTTP client runs the full OAuth 2.1 authorization flow.
Two protocol revisions, in the same server and client: 2026-07-28 (the current one, stateless) and 2025-11-25 (the previous one, with the initialize handshake and sessions). Older revisions (2025-06-18, 2025-03-26, 2024-11-05) are not spoken. No external dependencies.
The module is optional: ETHEREAL_AI_MCP, off by default. It needs ETHEREAL_AI_TOOLS, which needs ETHEREAL_AI_LLM, which needs ETHEREAL_AI_SCHEMA. When this SDK was built with it, BUILD_INFO.txt lists it and the Ethereal::Ethereal target carries the definition ETL_AI_MCP (find_package( Ethereal COMPONENTS Ai ) fails early without the pillar). Include mcp_inc.hpp: it brings in the whole module in the right order.
---
A server
#include <ethereal/cpp/ai/mcp/mcp_inc.hpp>
namespace Tools = Ethereal::Ai::Tools;
namespace Mcp = Ethereal::Ai::Mcp;
Tools::CToolRegistry Registry;
Registry.Add< SAddArgs >( "add", &Add, AddMeta ); // the schema comes from the type
Registry.Finalize();
Mcp::CServer Server( Mcp::SServerInfo{ "my-server", "1.0.0", "My server", "" } );
Server.AttachTools( Registry );
return Mcp::RunStdio( Server ) == Mcp::EStatus::eOk ? 0 : 1; // until stdin closesThe whole program, with two tools, is examples/ai/mcp_server_minimal.cpp. The CMake project in examples/installed builds it as example_mcp_server_minimal when the SDK has the module. Run by hand, it waits on stdin and exits when stdin closes (Ctrl+D on Linux, Ctrl+Z and Enter on Windows).
For Streamable HTTP, Mcp::CHttpServer::Start( Server, Config ) serves the same server on threads of its own (127.0.0.1 only by default, SHttpServerConfig::uPort) and returns at once. Stop() ends it. Resources and prompts are callbacks:
static Mcp::EStatus ReadNote( void *, std::string_view sUri, std::span< const Mcp::SUriVariable >, Mcp::CResourceOut & Out )
{
return Out.Text( sUri, "text/plain", "remember the milk" );
}
static const Mcp::SPromptArgument aArgs[] = { { "code", "The code to review", true } };
Server.AddResource( Mcp::SResourceDesc{ "mem://note", "note", "", "", "text/plain", -1 }, &ReadNote, nullptr );
Server.AddResourceTemplate( Mcp::SResourceTemplateDesc{ "file:///{path}", "files", "", "", "" }, &ReadFile, nullptr );
Server.AddPrompt( Mcp::SPromptDesc{ "review", "", "Reviews code", aArgs }, &GetReview, nullptr );
Server.NotifyResourceUpdated( "mem://note" ); // the subscribers are toldInside a tool handler, Mcp::ReportProgress( 1, 4, "reading" ) sends the progress of the request that runs it, when the client asked for progress. A value that does not grow is not sent, as the protocol requires. The tool sees a cancellation through Tools::CToolContext::IsCancelled.
In Claude Code and Claude Desktop
Claude Code, from a terminal (everything after -- goes to the server as its command line):
claude mcp add --transport stdio ethereal-minimal -- /home/user/example_mcp_server_minimal-s local (the default, this project only), -s project (shared through .mcp.json) and -s user (every project) choose the scope, and claude mcp list shows the state. Claude Desktop reads claude_desktop_config.json in %APPDATA%\Claude\ (Windows) or ~/Library/Application Support/Claude/ (macOS). The same JSON shape goes in a project's .mcp.json for Claude Code:
{
"mcpServers": {
"ethereal-minimal": {
"command": "C:\\path\\example_mcp_server_minimal.exe",
"args": []
}
}
}Use absolute paths (backslashes escaped) and restart Claude Desktop completely after saving. The server's stderr goes to mcp-server-ethereal-minimal.log in its log folder. This configuration follows each client's documentation. The example has been run against the official SDK clients and the MCP Inspector (below), but a run inside Claude Code and Claude Desktop is not yet recorded.
---
A client
Mcp::CClient Client;
Mcp::SClientConfig Config;
Mcp::SProcessSpec Spec;
Spec.sExecutable = "/path/to/server";
if( Client.ConnectStdio( Spec, Config ) != Mcp::EStatus::eOk ) // or ConnectHttp( SHttpClientSpec, Config )
return 1;
std::vector< Mcp::SToolInfo > List;
Client.ListTools( List );
Mcp::SCallResult R;
Client.CallTool( "add", R"({"dA":1,"dB":2})", R ); // R.sText, R.bIsError, R.sStructuredConnect finds the revision: it probes with server/discover (2026-07-28) and falls back to the initialize handshake (2025-11-25) on any other error or after uDiscoverTimeoutMs (3 s). A tool that failed is eOk with bIsError set, because the model is meant to read that error. Client.AsToolRegistry( Registry ) adds every tool of the server to a registry that is not final yet (use Tools::ENameRules::eMcp in its options for names with a dot). From there the tools go to Tools::RunAgent or to an Ai::Agent.
A server's sampling requests can go to a model: SClientConfig::pfnSampling = &Mcp::SampleWithLlm with an SLlmSampler (an Llm::CClient, the model, a maxTokens cap, the approval hook) in pSamplingUser. Model hints are not followed, and a null approval hook approves everything.
---
The API
| Piece | What it does |
|---|---|
CServer( SServerInfo, SServerConfig ) | the server core, with no transport. Status() after construction |
AttachTools( Registry ) | serves the tools of a final registry (once). The registry must outlive the server |
AddResource, AddResourceTemplate, AddPrompt, SetCompletion | resources (PFN_ReadResource writes into CResourceOut::Text/Blob), templates (RFC 6570 matching, variables percent-decoded), prompts (PFN_GetPrompt writes into CPromptOut), completion (PFN_Complete, at most 100 values) |
NotifyToolsChanged, NotifyResourcesChanged, NotifyPromptsChanged, NotifyResourceUpdated | the notifications to the subscribers |
Handle( CSession, sMessage ) | one message of one connection, for a custom transport (IOutput receives the answers) |
RunStdio( Server ) | serves on the process's stdin and stdout until stdin closes |
CLineServer | the stdio framing over any byte stream (Feed, Finish) |
CHttpServer | Start, Stop, Port (the one the system chose when the config said 0) |
ReportProgress( dProgress, dTotal, sMessage ) | progress of the request the handler runs in |
CClient | Connect, ConnectStdio, ConnectHttp, Close, Revision, ServerCapabilities, ServerInfo, Instructions, and ListTools, CallTool, ListResources, ListResourceTemplates, ReadResource, ListPrompts, GetPrompt, Complete, Listen (all pages followed) |
Request and Notify (any method), LastErrorCode and LastErrorMessage (the last eRemoteError of this thread), AsToolRegistry | |
SClientConfig | name and version, uTimeoutMs (30 s per request, 0 is none), bLegacy, Roots, pfnSampling, pfnElicitation (form mode), pfnNotification, uMaxInputRounds (8) |
CreateStdioTransport, CreateInProcessTransport, CreateHttpTransport | the transports behind Connect. In process: a client and a CServer in the same process, with no pipe |
SProcessSpec | the server process: executable, arguments, environment, working directory, uExitWaitMs (2 s before the kill on close), a callback for its stderr lines |
COAuthClient, SOAuthConfig, IOAuthStore, CreateMemoryOAuthStore | the OAuth flow of the HTTP client (below) |
Functions return an EStatus (StatusName gives its name). Besides the usual ones: eParseError (not JSON), eInvalidMessage (not JSON-RPC, or a batch), eRemoteError (a JSON-RPC error from the other side), eUnsupportedVersion (no revision in common) and eUnauthorized (the OAuth flow failed). ErrorCode:: has the JSON-RPC and MCP error codes, and RevisionName and ParseRevision convert the revisions.
---
What the protocol support covers
| Feature | Server | Client |
|---|---|---|
Tools: paginated list, call, annotations, outputSchema, structuredContent, isError | yes | yes |
| Resources: list, templates, read (text and binary), subscriptions, update notifications | yes | yes |
| Prompts, completion, cursor pagination on every list, progress, cancellation | yes | yes |
Logging (the level per request in 2026-07-28, logging/setLevel in 2025-11-25) | yes | notifications to pfnNotification |
subscriptions/listen (2026-07-28), resources/subscribe (2025-11-25) | yes | Listen |
Cache hints ttlMs and cacheScope (2026-07-28) | uListTtlMs, uReadTtlMs | |
| Roots, sampling, elicitation | not requested by the server | answered, in both revisions (in 2026-07-28 through input_required and a retry) |
| JSON-RPC batches | refused (neither revision has them) | not sent |
Tasks, resumption of a stream (Last-Event-ID) | no | no |
---
Transports
stdio. One message per line, nothing but messages on stdout. Log to stderr. On Windows both streams go to binary mode, so \r\n is never translated. The server reads on one thread and runs the requests on a pool of uMaxConcurrent workers (16), so a long tool does not hold the others, and a cancellation is handled at once while the tool runs. A line over uMaxMessageBytes (4 MiB) is answered as an invalid request and dropped.
Streamable HTTP, 2026-07-28. One endpoint (/mcp by default), POST only. A notification is answered 202. A request is answered with application/json, or with text/event-stream (the request's notifications, then the response). Closing the stream cancels the request. MCP-Protocol-Version, Mcp-Method and, for tools/call, resources/read and prompts/get, Mcp-Name are checked against the body (400 with -32020 when they disagree). GET and DELETE are 405.
Streamable HTTP, 2025-11-25. The initialize opens a session (Mcp-Session-Id). A GET opens the stream of the messages that belong to no request, DELETE ends the session, and closing a stream does not cancel. No event ids are sent, so a dropped stream is not resumed.
The HTTP server is one thread per connection plus one watcher thread. Its defaults, all in SHttpServerConfig:
| Setting | Default |
|---|---|
| Interface | 127.0.0.1 only (bAnyInterface to listen on all) |
Origin | checked on every request (403). Local origins and AllowedOrigins pass, null never does, a request without Origin passes (it is not from a browser) |
Host | checked against the loopback (the DNS rebinding defense), bCheckHost |
uMaxConnections | 64, one more gets 503 |
uMaxHeadBytes | 16 KiB. The body limit is the server's uMaxMessageBytes |
uIdleTimeoutMs / uKeepAliveMs | 30 s / an SSE comment after 15 s of silence |
uSessionIdleMs / uMaxSessions | 30 min / 256 (2025-11-25) |
A body with both Transfer-Encoding and Content-Length is refused (400). A server reachable from the network should also turn on authorization.
Server authorization. SHttpAuth::pfnValidate turns it on. The validator sees each bearer token (SAuthRequest) and must check its audience: a token issued for another resource is eInvalidToken. A request without a valid token gets 401 with WWW-Authenticate: Bearer resource_metadata="...", one without the scope gets 403 with error="insufficient_scope". sResourceMetadataJson, when set, is served without authorization at /.well-known/oauth-protected-resource and at that path followed by the endpoint path. The server never logs or keeps the token. Issuing tokens is the job of your authorization server.
---
OAuth 2.1 in the client
Mcp::SOAuthConfig Auth;
Auth.pfnOpenUrl = []( void *, std::string_view sUrl ) { return OpenSystemBrowser( sUrl ); };
Auth.pStore = MyKeychainStore(); // without it, the tokens die with the process
auto pAuth = Mcp::COAuthClient::Create( "https://mcp.example.com/mcp", Auth );
Mcp::SHttpClientSpec Spec;
Spec.sUrl = "https://mcp.example.com/mcp";
Spec.pOAuth = pAuth;
Mcp::CClient Client;
Client.ConnectHttp( Spec, Mcp::SClientConfig{} ); // the first 401 opens the browserWhen 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:
- The protected resource metadata (RFC 9728), from the challenge or the endpoint's well-known URLs. The resource it names must be the endpoint or a parent of it on the same origin.
- The authorization server metadata (RFC 8414, then OpenID Connect discovery). Its
issuermust be exactly the one the URL was built from, with S256 incode_challenge_methods_supported. - The client: a registration in
SOAuthConfig::Registeredfor that issuer, else a Client ID Metadata Document (sClientMetadataUrl), else dynamic registration (RFC 7591, kept per issuer). - The authorization request with PKCE (S256),
stateandresource(RFC 8707), opened by your application. The redirect comes to a listener on 127.0.0.1 (/callback, any free port oruLoopbackPort). Theissof the response (RFC 9207) is checked first, then thestate. - The token request, with the same
resource. The token is refresheduRefreshMarginSeconds(60 s) before it expires, and a 401 tries the refresh before the browser.offline_accessis requested when the server lists it.
The scope is the challenge's, else the scopes_supported of the resource metadata, else SOAuthConfig::Scopes. A 403 with insufficient_scope asks for the union of the previous scope and the challenge's, at most uMaxStepUps (2) times per request. Several challenges at once run one flow. While the user authorizes, the request time limit of the client does not run (AuthorizingFlag), and the user has uFlowTimeoutMs (5 min). Authorize() runs the flow before the first request, Cancel() stops it, Logout() forgets the tokens, and LastError() says in English why a flow failed, never with a secret.
What your application must do:
- Open the browser.
pfnOpenUrlis required. It receives the authorization URL and must return at once. The library does not launch anything itself. - Store the tokens securely. The default store (
CreateMemoryOAuthStore) keeps them in memory only. To keep them across runs, implementIOAuthStoreover the system keychain (DPAPI on Windows, the Keychain on macOS). Tokens are keyed by resource and issuer, and registrations by issuer, so a credential of one server is never offered to another. - Host the Client ID Metadata Document, if you use one (its
redirect_urismust contain the flow's redirect URI). With a redirect URI of your own (sRedirectUri, such as an application scheme), pass the whole URL that arrives there toCOAuthClient::DeliverRedirect.
Tokens, codes, verifiers and client secrets never go to a log or an error message. The metadata and the endpoints must be https, except on 127.0.0.1, localhost and [::1] (bAllowLoopbackHttp).
Not covered: private_key_jwt for the Client ID Metadata Document, the client_credentials grant, DPoP, OpenID id_token, token introspection, and encrypting tokens on disk (that is the store's job). A server that publishes no resource metadata (the 2025-03-26 behavior) is authorized only when SOAuthConfig::sAuthorizationServer names its issuer.
Threads, on both sides. CServer::Handle may be called from several threads at once for the same connection. Register tools, resources and prompts before the first message. Callbacks run on the transport's threads, several at once. A CClient may be called from several threads at once. IOutput and IOAuthStore implementations are called from several threads (the store one call at a time per COAuthClient).
---
C layer
Header ethereal/c/ai/mcp.h. The server (ETLC_McpServerCreate with ETLC_McpServerOptions, the tools of an ETLC_ToolRegistry, fixed resources and prompts by callback, the four notifications, ETLC_McpServerRunStdio), its HTTP transport (ETLC_McpHttpServerStart with ETLC_McpHttpOptions, including the bearer validator, and ETLC_McpHttpServerPort), the client (ETLC_McpClientConnectStdio and ETLC_McpClientConnectHttp, the revision, server info, capabilities and instructions, ETLC_McpClientListTools, ETLC_McpClientCallTool, ETLC_McpClientReadResource, ETLC_McpClientGetPrompt, the generic ETLC_McpClientRequest and ETLC_McpClientNotify, ETLC_McpClientLastError), a cancellation flag (ETLC_McpCancel*), and the OAuth flow (ETLC_McpOAuthCreate with ETLC_McpOAuthConfig, a store as two callbacks over opaque values in ETLC_McpOAuthStore, then ETLC_McpOAuthAuthorize, ETLC_McpOAuthDeliverRedirect, ETLC_McpOAuthCancel, ETLC_McpOAuthLogout, ETLC_McpOAuthLastError and ETLC_McpOAuthGrantedScope, given to the client through ETLC_McpHttpEndpoint::hOAuth). Results are JSON copied into the caller's buffer, with the size needed reported (a request whose buffer is too small loses its result: call again with more room). Three codes of its own: ETLC_AI_MCP_REMOTE_ERROR (-5813), ETLC_AI_MCP_UNSUPPORTED_VERSION (-5814) and ETLC_AI_MCP_UNAUTHORIZED (-5818).
C++ only: resource templates, completion, image and resource blocks in prompts, the client's sampling, elicitation and roots, Listen, the resource and prompt lists of the client, the bridge to a tool registry and the tool policies of the server.
---
Performance
Measured in Release on an Intel Core i7-6700 (3.4 GHz), Linux (GCC).
| Measure | Result | Target |
|---|---|---|
Server cost per tools/call (parse, dispatch, empty tool, serialization, no syscall) | p50 2.2 µs (empty tool), 2.6 µs (sum of three fields), tools/list 1.7 µs, empty tool in 2025-11-25 1.5 µs. Another run: 2.8 to 5.6 µs | p50 1 µs: not met |
| Allocations per request after warm-up | 0, enforced over 512 requests | 0: met |
| stdio round trip, Ethereal client and server, one call at a time | p50 128 µs, p99 300 µs, 6,556 calls per second | |
| stdio round trip and throughput against the official SDKs | see below | 10x better: not met |
| Idle server memory above the binary | not measured yet | 1 MB RSS |
The comparison with the official SDKs: a server with one echo tool, 2,000 sequential calls over stdio, all from the same client (the official Python SDK client, so the difference between rows is the server). Python SDK mcp 2.3.0, TypeScript SDK @modelcontextprotocol/sdk 1.32.2 on Node 24.
| Server | p50 | p99 | Calls per second |
|---|---|---|---|
| Ethereal | 342 µs | 776 µs | 2,676 |
TypeScript SDK (McpServer) | 381 µs | 722 µs | 2,438 |
Python SDK (MCPServer) | 1,369 µs | 1,796 µs | 713 |
Most of that time is the Python client and the pipes. The Ethereal server is 1.1x faster than the TypeScript one and 4x faster than the Python one in this setup, far from the 10x target.
What was verified
- Interoperability, 8 of 8: the Ethereal server over stdio and over Streamable HTTP against the official Python and TypeScript clients, the Ethereal client against the official Python server (stdio and HTTP, revision 2026-07-28) and the official TypeScript server (stdio, revision 2025-11-25), and the MCP Inspector (CLI mode) listing the Ethereal server's tools.
- OAuth: the client against the OAuth example server of the official TypeScript SDK 1.32.2 in strict mode: discovery, authorization, the tool list and calls, and a resource read. And against a local authorization server: dynamic registration, a registered client with a secret, the Client ID Metadata Document, refresh, step up, concurrent challenges, and the refusals the specification requires (no S256, a changed issuer, a changed or missing
iss, a changedstate). - GCC and MSVC (Release and Debug), AddressSanitizer, UndefinedBehaviorSanitizer and ThreadSanitizer clean, one hour of libFuzzer per parser with no finding, 90.1% line coverage.
---
Known limits
- The server never sends requests to the client nor answers
input_required: a tool cannot ask the client for sampling, roots or elicitation. No tasks, batches or stream resumption. SampleWithLlmignores thetoolsandtoolChoiceof a sampling request: only the messages go to the model.- The HTTP server is one thread per connection, so connections are capped (64 by default). It is built for the MCP endpoint, not as a general web server.
- The stdio client polls the child process's output with a short, growing wait, which adds latency on the client side only.