Converting to Async Mode
This guide takes a server and a client written in sync mode and converts them to async mode. The server keeps notes: a tool adds one, a resource lists them and tells its subscribers when they change, and a prompt asks for a summary. The client subscribes to the notes, adds one, waits for the change, then reads the notes and gets the prompt. Both talk over stdio. Async Servers and Clients describes async mode in full.
The Sync Programs
#include <mcp/mcp.hpp>
#include <mutex>
#include <string>
#include <vector>
int main() {
mcp::Server server("notes", "1.0.0");
std::mutex mutex;
std::vector<std::string> notes;
const std::string notes_uri = "notes://all";
// The resource: the notes, read again on each request. Clients may subscribe to it.
server.add_text_resource(notes_uri, "All notes", [&mutex, ¬es] {
const std::scoped_lock lock(mutex);
std::string text;
for (const auto& note : notes) {
text += "- " + note + "\n";
}
return text;
});
server.capabilities().resources->subscribe = true;
// The tool: adds a note and tells the resource's subscribers.
server.add_tool(
"add_note", "Adds a note", mcp::tool_params({{"text", "string", "The note"}}),
[&server, &mutex, ¬es, ¬es_uri](const nlohmann::json& args) -> nlohmann::json {
{
const std::scoped_lock lock(mutex);
notes.push_back(args.at("text").get<std::string>());
}
server.sync().notify_resource_updated(notes_uri);
return "Added";
});
// The prompt: asks the model to summarize the notes.
server.add_text_prompt("summarize", "Asks for a summary of the notes", {},
[&mutex, ¬es](const mcp::Server::PromptArguments&) {
const std::scoped_lock lock(mutex);
return "Summarize these " + std::to_string(notes.size()) + " notes.";
});
// The handler pool: handlers run on two threads of their own, where server.sync() can wait for
// the notification it sends from the server's event loop.
mcp::Runtime pool;
pool.start(2);
server.set_handler_executor(pool.executor());
// The event loop: run_stdio() runs it until standard input closes or a signal arrives.
server.run_stdio();
}
#include <mcp/mcp.hpp>
#include <iostream>
#include <string>
#include <variant>
int main(int argc, char** argv) {
// The client launches the server and runs its own event loop.
const std::string command = argc > 1 ? argv[1] : "./notes_server";
mcp::Client client(mcp::Endpoint::stdio({command}));
// The calls: each one blocks until it is answered.
client.sync().connect("notes-client", "1.0.0");
mcp::SubscriptionFilter filter;
filter.resourceSubscriptions = {"notes://all"};
auto subscription = client.sync().listen(filter);
client.sync().call_tool("add_note", {{"text", "Buy milk"}});
const auto event = subscription.sync().next();
if (event) {
std::cout << "changed: " << event->params.value("uri", std::string()) << "\n";
}
subscription.sync().close();
const auto read = client.sync().read_resource("notes://all");
std::cout << std::get<mcp::TextResourceContents>(read.contents.at(0)).text;
const auto prompt = client.sync().get_prompt("summarize");
std::cout << std::get<mcp::TextContent>(prompt.messages.at(0).content).text << "\n";
}
Converting the Server
Include the Coroutine Header
Code that defines or awaits a coroutine includes <mcp/core/async.hpp>,
which defines mcp::Task. The server below also includes
<mcp/transport/stdio.hpp> for the StdioTransport it serves.
Make the Handlers Coroutines
A handler that returns a value becomes a coroutine that returns mcp::Task
of that value and ends with co_return. The registration calls stay as they
are: add_tool(), add_text_resource() and add_text_prompt() take
either form.
server.add_text_resource(notes_uri, "All notes", [&mutex, ¬es] {
const std::scoped_lock lock(mutex);
std::string text;
for (const auto& note : notes) {
text += "- " + note + "\n";
}
return text;
});
server.capabilities().resources->subscribe = true;
server.add_text_resource(notes_uri, "All notes", [¬es]() -> mcp::Task<std::string> {
std::string text;
for (const auto& note : notes) {
text += "- " + note + "\n";
}
co_return text;
});
server.capabilities().resources->subscribe = true;
A blocking call in a handler becomes an awaited one. The tool sends its
notification with co_await server.notify_resource_updated() instead of the
blocking server.sync().notify_resource_updated():
server.add_tool(
"add_note", "Adds a note", mcp::tool_params({{"text", "string", "The note"}}),
[&server, &mutex, ¬es, ¬es_uri](const nlohmann::json& args) -> nlohmann::json {
{
const std::scoped_lock lock(mutex);
notes.push_back(args.at("text").get<std::string>());
}
server.sync().notify_resource_updated(notes_uri);
return "Added";
});
server.add_tool(
"add_note", "Adds a note", mcp::tool_params({{"text", "string", "The note"}}),
[&server, ¬es, ¬es_uri](const nlohmann::json& args) -> mcp::Task<nlohmann::json> {
notes.push_back(args.at("text").get<std::string>());
co_await server.notify_resource_updated(notes_uri);
co_return "Added";
});
The prompt changes the same way:
server.add_text_prompt("summarize", "Asks for a summary of the notes", {},
[&mutex, ¬es](const mcp::Server::PromptArguments&) {
const std::scoped_lock lock(mutex);
return "Summarize these " + std::to_string(notes.size()) + " notes.";
});
server.add_text_prompt("summarize", "Asks for a summary of the notes", {},
[¬es](const mcp::Server::PromptArguments&) -> mcp::Task<std::string> {
co_return "Summarize these " + std::to_string(notes.size()) + " notes.";
});
Remove the Handler Pool
The sync server runs its handlers on a pool of threads, so that
server.sync() can wait for the notification it sends from the server’s event
loop:
// The handler pool: handlers run on two threads of their own, where server.sync() can wait for
// the notification it sends from the server's event loop.
mcp::Runtime pool;
pool.start(2);
server.set_handler_executor(pool.executor());
The coroutines await the notification instead, so the async server needs no pool. Its handlers run one at a time on the thread that runs the event loop, and the notes need no mutex. A server whose handlers block or compute for long keeps a handler pool in async mode too; see Async Servers and Clients.
Run the Event Loop
run_stdio() runs an event loop of its own. In async mode the program runs
it: Server::run() is a coroutine that serves one transport, here a
StdioTransport, which runtime.spawn() starts on an mcp::Runtime.
runtime.run() runs the loop until standard input closes. A
boost::asio::io_context can take the place of the Runtime, as in
Async Servers and Clients.
server.run_stdio();
mcp::Runtime runtime;
runtime.spawn(
server.run(std::make_shared<mcp::StdioTransport>(runtime.executor()), runtime.executor()));
runtime.run();
run_stdio() also handled SIGINT and SIGTERM. A program that runs the event
loop handles them itself, for instance with mcp::graceful_shutdown(); see
Signal Handling.
Converting the Client
Make the Transport on the Program’s Event Loop
Endpoint::stdio() gives the client an event loop of its own. In async mode
the program makes a StdioClientTransport from StdioProcessOptions on its
event loop, and constructs the client with the transport and the loop’s
executor. The code that defines the coroutine includes
<mcp/core/async.hpp> and <mcp/transport/stdio_client.hpp>.
const std::string command = argc > 1 ? argv[1] : "./notes_server";
mcp::Client client(mcp::Endpoint::stdio({command}));
mcp::Runtime runtime;
mcp::StdioProcessOptions process;
process.command = argc > 1 ? argv[1] : "./notes_server";
mcp::Client client(std::make_shared<mcp::StdioClientTransport>(runtime.executor(), process),
runtime.executor());
Await the Calls in a Coroutine
Each blocking call of client.sync() becomes an awaited call of the
Client, and the subscription’s sync().next() and sync().close()
become co_await subscription.next() and co_await subscription.close().
The calls move into a coroutine, which runtime.spawn() starts. The coroutine
closes the client when it is done, after which runtime.run() returns. The
arguments of each co_await are built in named variables first, as GCC 11 to
13 need; see Known Issues.
client.sync().connect("notes-client", "1.0.0");
mcp::SubscriptionFilter filter;
filter.resourceSubscriptions = {"notes://all"};
auto subscription = client.sync().listen(filter);
client.sync().call_tool("add_note", {{"text", "Buy milk"}});
const auto event = subscription.sync().next();
if (event) {
std::cout << "changed: " << event->params.value("uri", std::string()) << "\n";
}
subscription.sync().close();
const auto read = client.sync().read_resource("notes://all");
std::cout << std::get<mcp::TextResourceContents>(read.contents.at(0)).text;
const auto prompt = client.sync().get_prompt("summarize");
std::cout << std::get<mcp::TextContent>(prompt.messages.at(0).content).text << "\n";
const auto use_notes = [&client]() -> mcp::Task<void> {
co_await client.connect("notes-client", "1.0.0");
mcp::SubscriptionFilter filter;
filter.resourceSubscriptions = {"notes://all"};
auto subscription = co_await client.listen(filter);
const nlohmann::json note{{"text", "Buy milk"}};
co_await client.call_tool("add_note", note);
const auto event = co_await subscription.next();
if (event) {
std::cout << "changed: " << event->params.value("uri", std::string()) << "\n";
}
co_await subscription.close();
const auto read = co_await client.read_resource("notes://all");
std::cout << std::get<mcp::TextResourceContents>(read.contents.at(0)).text;
const std::map<std::string, std::string> no_arguments;
const auto prompt = co_await client.get_prompt("summarize", no_arguments);
std::cout << std::get<mcp::TextContent>(prompt.messages.at(0).content).text << "\n";
client.close();
};
runtime.spawn(use_notes());
runtime.run();
sync() throws std::logic_error on a client constructed with a transport
and an executor.
Coroutines in a Sync-Mode Client
A client constructed from an Endpoint can also run a coroutine on its own
event loop: client.run() blocks until the coroutine ends and rethrows what
it throws. Inside it the client’s calls are awaited as in async mode:
const auto greet_in_a_coroutine = [&client]() -> mcp::Task<void> {
const nlohmann::json linus{{"name", "Linus"}};
const auto result = co_await client.call_tool("greet", linus);
std::cout << "from a coroutine: " << mcp::result_text(result) << "\n";
};
client.run(greet_in_a_coroutine);
The Async Programs
#include <mcp/core/async.hpp>
#include <mcp/mcp.hpp>
#include <mcp/transport/stdio.hpp>
#include <memory>
#include <string>
#include <vector>
int main() {
mcp::Server server("notes", "1.0.0");
std::vector<std::string> notes;
const std::string notes_uri = "notes://all";
// The resource: the notes, read again on each request. Clients may subscribe to it.
server.add_text_resource(notes_uri, "All notes", [¬es]() -> mcp::Task<std::string> {
std::string text;
for (const auto& note : notes) {
text += "- " + note + "\n";
}
co_return text;
});
server.capabilities().resources->subscribe = true;
// The tool: adds a note and tells the resource's subscribers.
server.add_tool(
"add_note", "Adds a note", mcp::tool_params({{"text", "string", "The note"}}),
[&server, ¬es, ¬es_uri](const nlohmann::json& args) -> mcp::Task<nlohmann::json> {
notes.push_back(args.at("text").get<std::string>());
co_await server.notify_resource_updated(notes_uri);
co_return "Added";
});
// The prompt: asks the model to summarize the notes.
server.add_text_prompt("summarize", "Asks for a summary of the notes", {},
[¬es](const mcp::Server::PromptArguments&) -> mcp::Task<std::string> {
co_return "Summarize these " + std::to_string(notes.size()) + " notes.";
});
// The event loop: Server::run() serves stdio on it until standard input closes.
mcp::Runtime runtime;
runtime.spawn(
server.run(std::make_shared<mcp::StdioTransport>(runtime.executor()), runtime.executor()));
runtime.run();
}
#include <mcp/core/async.hpp>
#include <mcp/mcp.hpp>
#include <mcp/transport/stdio_client.hpp>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <variant>
int main(int argc, char** argv) {
// The client launches the server and runs on the program's event loop.
mcp::Runtime runtime;
mcp::StdioProcessOptions process;
process.command = argc > 1 ? argv[1] : "./notes_server";
mcp::Client client(std::make_shared<mcp::StdioClientTransport>(runtime.executor(), process),
runtime.executor());
// The calls: a coroutine awaits each one, then closes the client.
const auto use_notes = [&client]() -> mcp::Task<void> {
co_await client.connect("notes-client", "1.0.0");
mcp::SubscriptionFilter filter;
filter.resourceSubscriptions = {"notes://all"};
auto subscription = co_await client.listen(filter);
const nlohmann::json note{{"text", "Buy milk"}};
co_await client.call_tool("add_note", note);
const auto event = co_await subscription.next();
if (event) {
std::cout << "changed: " << event->params.value("uri", std::string()) << "\n";
}
co_await subscription.close();
const auto read = co_await client.read_resource("notes://all");
std::cout << std::get<mcp::TextResourceContents>(read.contents.at(0)).text;
const std::map<std::string, std::string> no_arguments;
const auto prompt = co_await client.get_prompt("summarize", no_arguments);
std::cout << std::get<mcp::TextContent>(prompt.messages.at(0).content).text << "\n";
client.close();
};
runtime.spawn(use_notes());
runtime.run();
}
Each page of Core Concepts shows its feature in both modes.