Async Servers and Clients
In async mode the program runs a Boost.Asio event loop, and handlers and client
calls are C++20 coroutines that return mcp::Task. While a handler waits, the
server answers other requests on the same thread; a client has several calls in
flight at once; and the program chooses its executors and transports and runs
other work on the same loop.
This guide walks through examples/async/server.cpp and
examples/async/client.cpp, a server and a client that use every feature.
Each feature is described on its page in Core Concepts, and
Examples shows how to run the programs.
Coroutines
<mcp/core/async.hpp> defines mcp::Task<T>, the return type of a
coroutine that produces a T. A Task is a boost::asio::awaitable<T>:
it awaits Boost.Asio operations through boost::asio::use_awaitable, and
boost::asio::co_spawn starts it, or a callable that returns it, on an
executor.
GCC 11, 12 and 13 have coroutine bugs that the programs avoid, for instance by
building each argument of a co_await in a named variable first;
Known Issues lists them.
The Server
Coroutine Handlers
server.add_tool("greet", "Greets someone by name",
mcp::tool_params({{"name", "string", "Who to greet"}}),
[](const nlohmann::json& args) -> mcp::Task<nlohmann::json> {
co_return "Hello, " + args.at("name").get<std::string>() + "!";
});
// Logging and progress. A server that logs declares the logging capability.
server.capabilities().logging = nlohmann::json::object();
server.add_tool("compose_greeting", "Composes a greeting, logging and reporting progress",
mcp::tool_params({{"name", "string", "Who to greet"}}),
[](mcp::Context& ctx, const nlohmann::json& args) -> mcp::Task<nlohmann::json> {
co_await ctx.log_info("Composing a greeting");
// While it waits, the server answers other requests.
const auto executor = co_await boost::asio::this_coro::executor;
boost::asio::steady_timer pause(executor, std::chrono::milliseconds(100));
co_await pause.async_wait(boost::asio::use_awaitable);
co_await ctx.report_progress(1, 1);
co_return "Hello, " + args.at("name").get<std::string>() + "!";
});
The server runs each request in a coroutine of its own. A handler that returns
mcp::Task suspends at each co_await, and the server answers other
requests until it resumes. compose_greeting waits on a timer of the executor
it runs on, which boost::asio::this_coro::executor gives. A handler that blocks
instead holds up the thread it runs on. The Context carries the request’s
log messages and progress (Server Context).
Resources, Prompts and Requests to the Client
server.add_text_resource("greeter://motd", "Message of the day",
[]() -> mcp::Task<std::string> { co_return "Be kind to each other."; });
// Resource subscriptions: the remember tool changes a resource and tells its subscribers.
// Registering a resource declares the resources capability; this flag adds subscriptions.
const std::string last_uri = "greeter://last";
auto last = std::make_shared<std::string>("nobody");
auto last_mutex = std::make_shared<std::mutex>();
server.add_text_resource(last_uri, "The last name remembered",
[last, last_mutex]() -> mcp::Task<std::string> {
const std::scoped_lock lock(*last_mutex);
co_return *last;
});
server.capabilities().resources->subscribe = true;
server.add_tool("remember", "Remembers a name", mcp::tool_params({{"name", "string", "The name"}}),
[&server, &last_uri, last,
last_mutex](const nlohmann::json& args) -> mcp::Task<nlohmann::json> {
{
const std::scoped_lock lock(*last_mutex);
*last = args.at("name").get<std::string>();
}
co_await server.notify_resource_updated(last_uri);
co_return "Remembered";
});
// Prompts.
server.add_text_prompt("welcome", "Welcomes a new user",
{{.name = "name", .description = "The user's name", .required = true}},
[](const mcp::Server::PromptArguments& args) -> mcp::Task<std::string> {
co_return "Write a short welcome message for " + args.at("name") + ".";
});
// Completions.
server.set_completion_provider([](const mcp::CompleteParams&) -> mcp::Task<mcp::CompleteResult> {
mcp::CompleteResult result;
result.completion.values = {"Ada", "Grace", "Linus"};
co_return result;
});
// Elicitation: a tool asks the user, through the client, to fill in a form.
server.add_tool("greet_formally", "Greets someone by the title the user gives",
mcp::tool_params({{"name", "string", "Who to greet"}}),
[](mcp::Context& ctx, const nlohmann::json& args) -> mcp::Task<nlohmann::json> {
mcp::ElicitRequestFormParams form;
form.message = "How should they be addressed?";
form.requestedSchema =
mcp::tool_params({{"title", "string", "Such as Dr. or Ms."}});
const mcp::ElicitRequestParams question = form;
const auto answer = co_await ctx.elicit(question);
const auto title = answer.action == mcp::ElicitAction::eAccept && answer.content
? answer.content->value("title", std::string()) + " "
: std::string();
co_return "Hello, " + title + args.at("name").get<std::string>() + "!";
});
// Sampling: a tool asks the client's model for a reply.
server.add_tool(
"write_greeting", "Asks the client's model to write a greeting",
mcp::tool_params({{"name", "string", "Who to greet"}}),
[](mcp::Context& ctx, const nlohmann::json& args) -> mcp::Task<nlohmann::json> {
mcp::CreateMessageRequestParams request;
request.maxTokens = 100;
request.messages.push_back({
.role = mcp::Role::eUser,
.content =
mcp::TextContent{
.text = "Write a greeting for " + args.at("name").get<std::string>(),
},
.meta = std::nullopt,
});
const auto reply = co_await ctx.sample_llm(request);
const auto* block = std::get_if<mcp::ContentBlock>(&reply.content);
const auto* text = block != nullptr ? std::get_if<mcp::TextContent>(block) : nullptr;
co_return text != nullptr ? text->text : std::string("(no text)");
});
// Roots: a tool asks for the client's roots.
server.add_tool("count_roots", "Counts the client's roots", nlohmann::json{{"type", "object"}},
[](mcp::Context& ctx, const nlohmann::json&) -> mcp::Task<nlohmann::json> {
const auto listed = co_await ctx.request_roots();
co_return "The client has " + std::to_string(listed.roots.size()) + " root(s)";
});
Text resources, prompts and the completion provider take coroutines as tools do. See Resources, Notifications and Subscriptions, Prompts, Completions, Elicitation, Roots, and Server Context for requests to the client’s model.
A Pool for Handlers
// Handler pool: tool, resource and prompt handlers run on four threads of their own, and the
// server's own work stays on its event loop.
mcp::Runtime pool;
pool.start(4);
server.set_handler_executor(pool.executor());
set_handler_executor() moves the call of each tool, resource and prompt
handler to the pool’s threads, and the server goes back to its own executor when
the handler returns. Reading, parsing and answering messages stay on the event
loop, so a handler that blocks or computes for long does not hold it up. A
handler that only awaits needs no pool. Handlers that run on the pool share
state through a mutex, as remember does. The pool’s Runtime is
constructed before the io_context, so that it is destroyed after it, as
set_handler_executor() requires.
Middleware, Pages, Tasks, Apps and Skills
std::atomic<int> calls{0};
server.use([&calls](mcp::Context& ctx, const nlohmann::json& params,
mcp::TypeErasedHandler next) -> mcp::Task<nlohmann::json> {
std::cerr << "handler call " << ++calls << "\n";
co_return co_await next(ctx, params);
});
// Pagination: lists answer two items at a time.
server.set_page_size(2);
// Tasks: a call of greet may become a task, whose handler runs on the handler pool.
server.enable_tasks();
server.set_tool_task_mode("greet", mcp::ToolTaskMode::eAuto);
// MCP Apps: an HTML view, and a tool linked to it.
mcp::apps::ViewResource view;
view.uri = "ui://greeter/card";
view.name = "Greeting card";
view.html = "<!doctype html><html><body><h1 id=\"greeting\"></h1></body></html>";
mcp::apps::add_view_resource(server, view);
mcp::Tool card;
card.name = "greeting_card";
card.description = "Shows a greeting card";
card.inputSchema = mcp::tool_params({{"name", "string", "Who to greet"}});
mcp::apps::add_view_tool(
server, card, {.resourceUri = view.uri, .visibility = std::nullopt},
[](mcp::Context&, const nlohmann::json& args) -> mcp::Task<nlohmann::json> {
co_return mcp::make_tool_text_result("A card for " + args.at("name").get<std::string>());
});
// Agent Skills.
mcp::skills::SkillsExtension skills(server);
mcp::skills::SkillDefinition greeting;
greeting.path = "greeting";
greeting.frontmatter = {
{"name", "greeting"},
{"description", "How to greet people with the greet tool"},
};
greeting.files.push_back({
.path = "SKILL.md",
.content = "---\nname: greeting\ndescription: How to greet people with the "
"greet tool\n---\nCall greet with the person's name.\n",
.mime_type = std::nullopt,
.generate = {},
});
skills.add_skill(std::move(greeting));
See Middleware, Pagination, Tasks, MCP Apps and Skills.
The Event Loop
// The event loop: HTTP through a session manager that serves this server, until a signal.
boost::asio::io_context io;
const auto port = static_cast<std::uint16_t>(argc > 1 ? std::stoi(argv[1]) : 8080);
mcp::StreamableHttpSessionManager http(io.get_executor(), "127.0.0.1", port, server);
http.set_bearer_token_validator(
[](std::string_view token) { return token == "greeter-secret-token"; });
http.set_allowed_origins({"http://localhost:3000"});
boost::asio::signal_set signals(io, SIGINT, SIGTERM);
signals.async_wait([&http](const boost::system::error_code& error, int) {
if (!error) {
http.close();
}
});
boost::asio::co_spawn(io, http.listen(), [&signals](const std::exception_ptr& failure) {
signals.cancel();
if (failure) {
std::rethrow_exception(failure);
}
});
io.run();
A StreamableHttpSessionManager constructed with the server serves it as
run_http() does (Deployment Guide), and the settings that run_http()’s
callback makes are made on it before listen(). listen() accepts
connections until close(), which the program calls on SIGINT or SIGTERM, as
run_http() does itself; io.run() then returns once the handlers still
running have finished.
Signal Handling shows a shutdown that also sets a deadline for them. A
stdio server runs server.run(transport, executor) on the loop instead, as
in Another Event Loop.
The Client
Construction and Handlers
// The connection: the transport and the client run on the program's event loop, and the
// transport sends a bearer token.
boost::asio::io_context io;
auto transport = std::make_shared<mcp::HttpClientTransport>(io.get_executor(), url);
transport->set_bearer_token_provider([] { return std::string("greeter-secret-token"); });
mcp::Client client(transport, io.get_executor());
// Logging: the server's log messages arrive as notifications.
client.on_notification("notifications/message", [](const nlohmann::json& params) {
std::cout << "log: " << params.value("data", nlohmann::json()).dump() << "\n";
});
// Elicitation: this handler answers the server's questions for the user.
client.on_elicitation([](const mcp::ElicitRequestParams&) -> mcp::Task<mcp::ElicitResult> {
co_return mcp::ElicitResult{
.action = mcp::ElicitAction::eAccept,
.content = nlohmann::json{{"title", "Dr."}},
.meta = std::nullopt,
};
});
// Sampling: this handler answers the server's requests for model output.
client.on_sampling(
[](const mcp::CreateMessageRequestParams&) -> mcp::Task<mcp::CreateMessageResult> {
mcp::CreateMessageResult reply;
reply.role = mcp::Role::eAssistant;
reply.content = mcp::ContentBlock{mcp::TextContent{.text = "Greetings, friend!"}};
reply.model = "example-model";
co_return reply;
});
// Roots: this handler lists the client's roots.
client.on_roots_list([](const nlohmann::json&) -> mcp::Task<mcp::ListRootsResult> {
mcp::ListRootsResult roots;
roots.roots.push_back({"file:///home/user/projects", "projects", std::nullopt});
co_return roots;
});
A client constructed with a transport and an executor runs on the program’s
event loop and is used through its coroutines; sync() and run() are for
a client that runs a loop of its own (Converting to Async Mode). The handlers for
the server’s requests are coroutines in both modes.
Starting the Coroutine
// co_spawn hands what a coroutine throws to this handler; rethrowing it makes io.run() throw.
const auto rethrow = [](const std::exception_ptr& failure) {
if (failure) {
std::rethrow_exception(failure);
}
};
// The calls: connect, use every feature, then make the two calls together.
boost::asio::co_spawn(
io,
[&client, greet_together]() -> mcp::Task<void> {
co_await client.connect("greeter-client", "1.0.0");
co_await use_every_feature(client);
greet_together();
},
rethrow);
io.run();
co_spawn is given the lambda itself, not the result of calling it: it keeps
the lambda, and so the captures its coroutine reads, alive until the coroutine
finishes. What the coroutine throws goes to the completion handler.
boost::asio::detached ignores it; rethrow makes io.run() throw it.
io.run() returns once no work is left, here after the client is closed.
Awaiting Calls
// Every feature of the client, one awaited call after another. The arguments of each co_await are
// built in named variables first, as GCC 11 to 13 need.
mcp::Task<void> use_every_feature(mcp::Client& client) {
const nlohmann::json ada{{"name", "Ada"}};
// Tools.
const auto greeted = co_await client.call_tool("greet", ada);
std::cout << mcp::result_text(greeted) << "\n";
// Logging and progress: the options ask for the call's progress and log messages.
mcp::RequestOptions options;
options.on_progress = [](const mcp::ProgressNotificationParams& progress) {
std::cout << "progress: " << progress.progress << "\n";
};
options.log_level = mcp::LoggingLevel::eInfo;
const auto composed = co_await client.call_tool("compose_greeting", ada, options);
std::cout << mcp::result_text(composed) << "\n";
// Resources.
const auto motd = co_await client.read_resource("greeter://motd");
std::cout << std::get<mcp::TextResourceContents>(motd.contents.at(0)).text << "\n";
// Prompts.
const std::map<std::string, std::string> prompt_args{{"name", "Ada"}};
const auto welcome = co_await client.get_prompt("welcome", prompt_args);
std::cout << std::get<mcp::TextContent>(welcome.messages.at(0).content).text << "\n";
// Completions.
mcp::CompleteParams completing;
completing.ref = mcp::PromptReference{.name = "welcome"};
completing.argument = {.name = "name", .value = "A"};
const auto completed = co_await client.complete(completing);
std::cout << "completion: " << completed.completion.values.at(0) << "\n";
// Elicitation, sampling and roots: tools that ask this client's handlers.
const auto formal = co_await client.call_tool("greet_formally", ada);
std::cout << mcp::result_text(formal) << "\n";
const auto written = co_await client.call_tool("write_greeting", ada);
std::cout << mcp::result_text(written) << "\n";
const nlohmann::json no_arguments = nlohmann::json::object();
const auto roots = co_await client.call_tool("count_roots", no_arguments);
std::cout << mcp::result_text(roots) << "\n";
// Tasks: start_tool() returns a handle when the server makes the call a task.
const nlohmann::json grace{{"name", "Grace"}};
auto started = co_await client.start_tool("greet", grace);
if (auto* task = std::get_if<mcp::TaskHandle>(&started)) {
std::cout << "task: " << task->id() << "\n";
started = co_await task->result();
}
std::cout << mcp::result_text(std::get<mcp::CallToolResult>(started)) << "\n";
// Resource subscriptions: the remember tool changes the resource.
mcp::SubscriptionFilter filter;
filter.resourceSubscriptions = {"greeter://last"};
auto subscription = co_await client.listen(filter);
if (!subscription.unhonored().resourceSubscriptions.empty()) {
throw std::runtime_error("the server does not offer subscriptions to greeter://last");
}
co_await client.call_tool("remember", ada);
const auto event = co_await subscription.next();
if (event) {
std::cout << "updated: " << event->method << "\n";
}
co_await subscription.close();
// Errors: a tool error is a result; a request error is an McpError.
const auto refused = co_await client.call_tool("greet", no_arguments);
if (refused.isError.value_or(false)) {
std::cout << "tool error: " << mcp::result_text(refused) << "\n";
}
try {
co_await client.read_resource("greeter://missing");
} catch (const mcp::McpError& error) {
std::cout << "request error " << error.code() << "\n";
}
// Pagination: each page's nextCursor asks for the next one.
std::optional<std::string> cursor;
do {
const auto page = co_await client.list_tools(cursor);
for (const auto& tool : page.tools) {
std::cout << "tool: " << tool.name << "\n";
}
cursor = page.nextCursor;
} while (cursor);
}
Each call is awaited in turn. See Server Context for progress and log messages, Resources, Prompts, Completions, Tasks, Notifications and Subscriptions, Error Handling and Pagination.
Calls in Flight Together
// Two calls in flight at the same time: each runs in a coroutine of its own, so neither waits
// for the other's answer. The client closes once both have returned.
const auto greet_together = [&io, &client, rethrow] {
auto calls_left = std::make_shared<int>(2);
for (const char* name : {"Ada", "Grace"}) {
boost::asio::co_spawn(
io,
[&client, calls_left, args = nlohmann::json{{"name", name}}]() -> mcp::Task<void> {
const auto result = co_await client.call_tool("greet", args);
std::cout << "together: " << mcp::result_text(result) << "\n";
if (--*calls_left == 0) {
client.close();
}
},
rethrow);
}
};
Each co_spawn starts a coroutine that runs on its own, so both calls wait
for their answers at the same time. The last one to return closes the client.
Another Event Loop
The programs run a boost::asio::io_context. mcp::Runtime is an event
loop that the SDK provides: its executor() takes the place of
io.get_executor(), spawn() starts a Task, and run() runs the loop
until no work is left. examples/async/notes_server.cpp serves stdio on one:
mcp::Runtime runtime;
runtime.spawn(
server.run(std::make_shared<mcp::StdioTransport>(runtime.executor()), runtime.executor()));
runtime.run();
run() returns once Server::run() has returned, when standard input
closes. start(threads) runs the loop on threads of its own instead, until
stop().