Server Context

The mcp::Context object is a fundamental construct in the MCP C++ SDK. It is passed as a reference to every handler for tools, resources, and prompts that takes one. Think of the Context as the per-request interface between your server’s logic and the connected client.

Core Responsibilities

The Context object handles three main categories of interaction:

  1. Downstream Communication: Sending real-time updates to the client (logging and progress).

  2. Request Lifecycle: Managing state specific to the current request (cancellation).

  3. Reverse RPC: Initiating requests from the server back to the client (sampling, elicitation, and roots). In a 2026-07-28 session these calls work in the handler of a tools/call, prompts/get or resources/read: the server answers the request with an input_required result and the handler resumes when the client retries with the answer (see Protocol Revisions). Any other 2026-07-28 request cannot ask the client anything, and the calls throw std::runtime_error.

Lifecycle and Safety

A Context is valid only for the duration of the request handler. It should never be stored beyond the co_return of the handler. The SDK ensures that the underlying transport and state required by the Context remain valid while the handler’s coroutine is active.

Note

The Context is designed to be coroutine-safe. You can safely pass it by reference into nested coroutines or helper functions, provided they are awaited within the main handler.

Logging

Note

Protocol revision 2026-07-28 deprecates logging; the SDK keeps it for peers that use it. See Deprecated Features.

You can send log messages to the client using various log levels. The SDK respects the server’s current log level, automatically filtering messages that are less severe than the configured threshold. For a request of protocol revision 2026-07-28 the threshold is the io.modelcontextprotocol/logLevel in the request’s _meta; without one nothing is sent.

Available log levels (from most to least severe):

  • Emergency (LoggingLevel::eEmergency): System is unusable.

  • Alert (LoggingLevel::eAlert): Action must be taken immediately.

  • Critical (LoggingLevel::eCritical): Critical conditions.

  • Error (LoggingLevel::eError): Error conditions.

  • Warning (LoggingLevel::eWarning): Warning conditions.

  • Notice (LoggingLevel::eNotice): Normal but significant conditions.

  • Info (LoggingLevel::eInfo): Informational messages.

  • Debug (LoggingLevel::eDebug): Debug-level messages.

#include <mcp/core/async.hpp>
#include <mcp/mcp.hpp>

server.add_tool<nlohmann::json, nlohmann::json>("debug_tool", "Tool with logging", schema,
                [](mcp::Context& ctx, nlohmann::json args) -> mcp::Task<nlohmann::json> {
                    // Direct level helpers
                    co_await ctx.log_info("Executing debug tool...");

                    // Generic log method
                    co_await ctx.log(mcp::LoggingLevel::eDebug, "Parameters: " + args.dump());

                    if (args.contains("error")) {
                        co_await ctx.log(mcp::LoggingLevel::eError,
                                         "An intentional error occurred");
                    }

                    co_return nlohmann::json{{"status", "ok"}};
                });

Logging is an asynchronous operation but generally returns quickly as it just pushes to the transport buffer. It’s a non-blocking way to provide visibility into server-side operations without affecting the final tool output.

Progress Reporting

For long-running tasks, you can report progress to the client. This is essential for providing feedback during operations like heavy computation, large file transfers, or multi-step API interactions.

Prerequisites

Progress reporting requires the client to provide a progressToken in the request metadata (_meta), as RequestOptions::on_progress does for one request.

If no token is provided in the request, ctx.report_progress() calls are silently ignored.

Usage Details

The report_progress method accepts: * progress: The current progress value (double). * total: An optional total progress value (double). * message: An optional human-readable progress message string.

nlohmann::json tool_schema = {
    {"type", "object"},
    {"properties", {{"duration_ms", {{"type", "integer"}}}}},
    {"required", nlohmann::json::array({"duration_ms"})},
};

server.add_tool<nlohmann::json, CallToolResult>(
    "long_task", "A long-running task that reports progress and can be cancelled", tool_schema,
    [&tool_saw_cancel](Context& ctx, const nlohmann::json& args) -> Task<CallToolResult> {
        int duration_ms = args.at("duration_ms").get<int>();
        int steps = 10;
        int step_duration_ms = duration_ms / steps;

        std::cout << "Tool: Starting long_task for " << duration_ms << "ms\n";

        // One timer stands in for the work of every step.
        auto executor = co_await asio::this_coro::executor;
        asio::steady_timer work_timer(executor);
        for (int i = 0; i < steps; ++i) {
            if (ctx.is_cancelled()) {
                std::cout << "Tool: Cancellation detected at step " << i << "\n";
                tool_saw_cancel = true;
                co_return make_tool_error_result("Task cancelled at step " + std::to_string(i) +
                                                 "/" + std::to_string(steps));
            }

            work_timer.expires_after(std::chrono::milliseconds(step_duration_ms));
            co_await work_timer.async_wait(asio::use_awaitable);

            int progress = (i + 1) * 100 / steps;
            std::string message =
                "Processing step " + std::to_string(i + 1) + "/" + std::to_string(steps);
            co_await ctx.report_progress(progress, 100, message);
            std::cout << "Tool: Reported progress " << progress << "%\n";
            // Reaches the client only because its request set RequestOptions::log_level.
            co_await ctx.log_info(message);
        }

        std::cout << "Tool: Completed all steps\n";
        co_return make_tool_text_result("Task completed successfully with " +
                                        std::to_string(steps) + " steps");
    });

The example above demonstrates a typical pattern where a tool loops through several steps, reporting the percentage completion and a descriptive message at each stage.

Using Logging and Progress

A handler that logs or reports progress takes the request’s Context and awaits each message, so it is a coroutine in both modes. In async mode it can also await other work, here a timer, while the server answers other requests:

Sync mode
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");
                    co_await ctx.report_progress(1, 1);
                    co_return "Hello, " + args.at("name").get<std::string>() + "!";
                });
Async mode
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>() + "!";
                });

A client asks for the progress of one call with RequestOptions::on_progress, which sends a progress token with the request and is called for each report until the answer arrives. RequestOptions::log_level asks the server for the log messages of that call at that level and above; a session of protocol revision 2025-11-25 or earlier sets one level for all its requests with a logging/setLevel request instead.

Sync mode
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 = client.sync().call_tool("compose_greeting", {{"name", "Ada"}}, options);
std::cout << mcp::result_text(composed) << "\n";
Async mode
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";

on_notification() registers a function for a notification method, here the server’s log messages. It is the same in both modes:

client.on_notification("notifications/message", [](const nlohmann::json& params) {
    std::cout << "log: " << params.value("data", nlohmann::json()).dump() << "\n";
});

Cancellation

MCP supports cooperative cancellation, allowing clients to stop execution of requests that are no longer needed. This is particularly important for expensive LLM operations or long-running background tasks.

How it works

  1. A client sends a notifications/cancelled message for a specific request ID.

  2. The server marks the corresponding Context as cancelled, for tool, resource and prompt handlers alike.

  3. The tool handler checks ctx.is_cancelled() and exits gracefully.

Cancelling from the client

A client cancels requests by giving them a mcp::CancellationToken in RequestOptions::cancellation and calling cancel() on a copy of the token, from any thread. The client tells the server about each request given the token that is still waiting, with notifications/cancelled (over HTTP, a 2026-07-28 request’s response stream is closed instead), and each call throws McpError with g_REQUEST_CANCELLED at once; a response that arrives afterwards is dropped. A request given a token that is already cancelled is not sent. Client::call_tool() and Client::send_request() take the options.

mcp::CancellationToken cancellation;  // kept to cancel with, from any thread
mcp::RequestOptions options;
options.cancellation = cancellation;
try {
    auto result = co_await client.call_tool("long_task", arguments, options);
} catch (const mcp::McpError& error) {
    if (error.code() == mcp::constants::jsonrpc::g_REQUEST_CANCELLED) {
        // cancellation.cancel() was called while the call waited.
    }
}

examples/features/progress_cancellation.cpp cancels its call from its progress callback. Client::cancel() sends the notification for a request id the application already knows.

Implementation Pattern

Handlers should periodically check ctx.is_cancelled() during long-running operations. Since cancellation is cooperative, the server doesn’t forcibly terminate the coroutine; it’s the handler’s responsibility to stop work.

A plain-function handler can take the Context too, [](mcp::Context& ctx, const nlohmann::json& args) -> nlohmann::json, and call ctx.is_cancelled(). The server reads the cancellation on its event loop, so such a handler sees it only when it runs on the handler executor (see Server::set_handler_executor()).

for (int i = 0; i < steps; ++i) {
    // Check for cancellation at the start of each iteration
    if (ctx.is_cancelled()) {
        co_await ctx.log_info("Task cancelled by client. Cleaning up...");
        // Perform any necessary cleanup (closing files, etc.)
        co_return nlohmann::json{
            {"content", {{{"type", "text"}, {"text", "Task cancelled"}}}},
            {"isError", true}
        };
    }

    // ... perform expensive work ...
    co_await ctx.report_progress(i + 1, steps, "Step " + std::to_string(i+1));
}

Sampling (Reverse RPC)

Note

Protocol revision 2026-07-28 deprecates sampling; the SDK keeps it for peers that use it. See Deprecated Features.

Sampling allows the server to request a completion from the LLM via the client. This “Reverse RPC” capability enables servers to build complex, multi-step workflows where the server uses the client’s LLM to process data or make decisions.

Usage Example

The server sends a sampling/createMessage request back to the client. The client (e.g., Claude Desktop) then handles the request, often by prompting the user or using its own internal model.

server.add_tool<nlohmann::json, nlohmann::json>("generate_summary", "Requests text from LLM", schema,
                [](mcp::Context& ctx, nlohmann::json args) -> mcp::Task<nlohmann::json> {
                    mcp::SamplingMessage msg;
                    msg.role = mcp::Role::eUser;
                    msg.content = mcp::SamplingMessageContentBlock{
                        mcp::TextContent{.text = "Summarize this: " + args["text"].get<std::string>()}};

                    mcp::CreateMessageRequestParams params;
                    params.messages.push_back(std::move(msg));
                    params.maxTokens = 100;

                    // A json, not a std::string, which must not live across co_await on GCC 11.
                    nlohmann::json failure;
                    try {
                        auto result = co_await ctx.sample_llm(params);
                        std::string summary;
                        if (auto* block = std::get_if<mcp::SamplingMessageContentBlock>(&result.content)) {
                            if (auto* tc = std::get_if<mcp::TextContent>(block)) {
                                summary = tc->text;
                            }
                        }
                        co_return nlohmann::json{
                            {"content", nlohmann::json::array(
                                {nlohmann::json{{"type", "text"}, {"text", summary}}})}};
                    } catch (const std::exception& e) {
                        failure = std::string("Sampling failed: ") + e.what();
                    }
                    // A catch block cannot contain co_await, so the failure is logged after it.
                    co_await ctx.log(mcp::LoggingLevel::eError, failure.get_ref<const std::string&>());
                    co_return nlohmann::json{
                        {"content", nlohmann::json::array(
                            {nlohmann::json{{"type", "text"}, {"text", "Sampling failed"}}})}};
                });

In both modes the tool that asks is a coroutine, and so is the client’s handler, which on_sampling() registers: it passes the messages to the client’s model and returns the reply. Registered before connect(), the handler also declares the sampling capability:

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)");
    });
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;
    });

Elicitation

Elicitation enables the server to request additional information or confirmation from the user. It’s often used when a tool needs parameters that weren’t initially provided or when a sensitive action requires explicit user approval.

Modes of Elicitation

  1. Form Mode: Requests the user to fill out a structured form defined by a JSON schema.

  2. URL Mode: Directs the user to an external URL (e.g., for OAuth flows).

nlohmann::json tool_schema = {
    {"type", "object"},
    {"properties", {{"task", {{"type", "string"}}}}},
    {"required", nlohmann::json::array({"task"})},
};

server.add_tool<nlohmann::json, nlohmann::json>(
    "request_user_info", "A tool that elicits user information via form-based elicitation",
    tool_schema, [](Context& ctx, const nlohmann::json& args) -> Task<nlohmann::json> {
        std::string task = args.at("task").get<std::string>();
        std::cout << "Tool: Starting request_user_info for task: " << task << "\n";

        const auto& form = contact_form();

        ElicitRequestFormParams form_params;
        form_params.mode = "form";
        form_params.message = "Please provide your contact information";
        form_params.requestedSchema = form;

        std::cout << "Tool: Sending elicitation request\n";
        ElicitRequestParams params = form_params;
        auto result = co_await ctx.elicit(params);

        std::cout << "Tool: Received elicitation result\n";

        auto make_result = [](const std::string& text) {
            return nlohmann::json{
                {
                    "content",
                    nlohmann::json::array({
                        nlohmann::json{
                            {"type", "text"},
                            {"text", text},
                        },
                    }),
                },
            };
        };

        if (result.action == ElicitAction::eAccept) {
            std::cout << "Tool: User accepted the form\n";
            if (result.content) {
                // Context::elicit() has checked the content against the schema; decode()
                // reads it as typed values.
                const auto values = form.decode(*result.content);
                const auto name = values.get<std::string>("name").value_or("");
                const auto topics = values.get<std::vector<std::string>>("topics").value_or(
                    std::vector<std::string>{});
                std::cout << "Tool: Form data: " << result.content->dump() << "\n";
                co_return make_result(
                    "Accepted: task=" + task + " name=" + name +
                    " priority=" + values.get<std::string>("priority").value_or("-") +
                    " topics=" + std::to_string(topics.size()));
            }
            co_return make_result("Accepted: task=" + task + " (no form data)");
        } else if (result.action == ElicitAction::eDecline) {
            std::cout << "Tool: User declined the form\n";
            co_return make_result("Declined: task=" + task);
        } else {
            std::cout << "Tool: User cancelled the form\n";
            co_return make_result("Cancelled: task=" + task);
        }
    });

The elicitation result contains an action (accept, decline, or cancel) and the elicited content (form data or response).

Roots

Roots discovery allows a server to discover the files and directories the client has made available. This is crucial for servers that need to operate on local files while maintaining a security sandbox defined by the client.

The request_roots() method returns a list of roots that the client has explicitly shared. This might include: * Local project directories. * Specific documentation folders. * In-memory virtual file systems.

nlohmann::json tool_schema = {
    {"type", "object"},
    {"properties", nlohmann::json::object()},
    {"required", nlohmann::json::array()},
};

server.add_tool<nlohmann::json, nlohmann::json>(
    "discover_roots", "Discovers and displays the client's declared root URIs", tool_schema,
    [](Context& ctx, const nlohmann::json&) -> Task<nlohmann::json> {
        std::cout << "Tool: Requesting roots from client\n";

        try {
            auto roots_result = co_await ctx.request_roots();

            std::cout << "Tool: Received " << roots_result.roots.size() << " root(s)\n";

            std::string output = "Discovered roots:\n";
            for (const auto& root : roots_result.roots) {
                std::cout << "Tool:   - URI: " << root.uri;
                if (root.name) {
                    std::cout << " (name: " << *root.name << ")";
                }
                std::cout << "\n";

                output += "  - " + root.uri;
                if (root.name) {
                    output += " (" + *root.name + ")";
                }
                output += '\n';
            }

            co_return nlohmann::json{
                {
                    "content",
                    nlohmann::json::array({nlohmann::json{{"type", "text"}, {"text", output}}}),
                },
                {"isError", false},
            };
        } catch (const std::exception& e) {
            std::cout << "Tool: Error requesting roots: " << e.what() << "\n";
            std::string error_msg = "Error: " + std::string(e.what());
            co_return nlohmann::json{
                {
                    "content",
                    nlohmann::json::array({
                        nlohmann::json{
                            {"type", "text"},
                            {"text", error_msg},
                        },
                    }),
                },
                {"isError", true},
            };
        }
    });

The server calls ctx.request_roots() to get a list of Root objects, each containing a URI and an optional name. This is particularly useful for tools like “file_search” or “code_indexer” that need to know where they are allowed to look.

Advanced: Context Internal Architecture

While most developers will only use the public API of Context, understanding its internal structure can help when debugging or extending the SDK.

The Context holds: * A reference to the ITransport for sending notifications. * A RequestSender (a functional wrapper) for performing reverse RPC. * A shared atomic flag for cancellation. * A ProgressToken extracted from the request’s metadata.

This architecture ensures that Context is lightweight and efficient to pass around, while providing a rich set of capabilities.

Request Metadata and Principal

ctx.request_meta() returns the parsed _meta fields of a 2026-07-28 request (protocol version, client capabilities, client info, log level, and the whole _meta object), and a null pointer for a request of an older revision. ctx.principal() says who sent a request. Over HTTP it is the principal that a bearer token validator named in its TokenValidation result, or h: followed by the hex SHA-256 of the Authorization header, or empty when there is none. It is empty for stdio, WebSocket and memory transports, and for the requests of a StreamableHttpSessionManager session of an older revision, which are attributed to the session.

Best Practices

  • Check Cancellation Often: For any operation taking more than a few hundred milliseconds, check is_cancelled() regularly.

  • Meaningful Progress Messages: Don’t just send percentages; send messages like “Scanning files…”, “Parsing AST…”, or “Uploading results…”.

  • Log Level Discipline: Keep Info and above for significant events. Use Debug for the “firehose” of internal state.

  • Handle Reverse RPC Failures: Sampling and Elicitation can fail due to network issues, client rejection, or user cancellation. Always use try-catch blocks or check result statuses.

  • Feature Detection: Remember that some clients might not support all features (like sampling or roots). The SDK handles the protocol level, but your tool logic should be resilient to missing capabilities.

Cross-References

To further explore the MCP C++ SDK and how it integrates with other features, consider these resources:

  • Tools: Comprehensive guide to tool registration and schemas.

  • Resources: Learn how to expose read-only data via MCP URIs.

  • Prompts: Guide to creating dynamic prompt templates for LLMs.

  • Transports: Understand the underlying communication layers (Stdio, WebSocket, HTTP).

  • Elicitation: Advanced patterns for user interaction.

  • Roots: Deep dive into the roots discovery protocol.

  • Examples: The examples/features/ directory in the source tree contains self-contained code for all features discussed here.

Summary

The mcp::Context is the bridge between your tool logic and the external world. By effectively using logging, progress reporting, and reverse RPC, you can create highly interactive and intelligent MCP servers that provide a superior user experience.