Tools

Tools are one of the core primitives in MCP. They allow an LLM to take actions on the user’s behalf, such as performing calculations, interacting with external APIs, or managing local files.

In mcp-cpp-sdk, tools are defined using the add_tool method on the Server class. Each tool requires:

  • Name: A unique identifier for the tool.

  • Description: A human-readable explanation of what the tool does.

  • Input Schema: A JSON Schema object defining the input parameters. It must declare "type": "object", since tool arguments are always an object.

  • Handler: A C++ function or lambda that executes the tool logic.

Using Tools

A server registers a tool with add_tool(): a name, a description, an input schema and a handler. In sync mode the handler is a plain function that returns the result; in async mode it is a coroutine that returns mcp::Task<nlohmann::json>:

Sync mode
server.add_tool("greet", "Greets someone by name",
                mcp::tool_params({{"name", "string", "Who to greet"}}),
                [](const nlohmann::json& args) -> nlohmann::json {
                    return "Hello, " + args.at("name").get<std::string>() + "!";
                });
Async mode
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>() + "!";
                });

mcp::tool_params() writes the input schema from one ParamSpec per argument: its name, JSON Schema type and description, and whether it is required, which it is by default. {"title", "string", "Such as Dr. or Ms.", false} adds an optional argument.

A client calls the tool with call_tool(), through client.sync() in sync mode and with co_await in async mode:

Sync mode
const auto greeted = client.sync().call_tool("greet", {{"name", "Ada"}});
std::cout << mcp::result_text(greeted) << "\n";
Async mode
const auto greeted = co_await client.call_tool("greet", ada);
std::cout << mcp::result_text(greeted) << "\n";

Basic Tool Registration

The simplest way to register a tool is with a synchronous handler that takes nlohmann::json and returns nlohmann::json. A returned object made only of CallToolResult members (content, structuredContent, isError, _meta) that decodes as one is sent as the result, as in the example below. Any other value is turned into a CallToolResult: a string becomes the text block, an object becomes structuredContent with its serialization as the text block, and anything else is serialized into the text block. An object whose only member is an empty content array is treated as data and wrapped.

#include <mcp/mcp.hpp>

nlohmann::json schema = {
    {"type", "object"},
    {"properties", {
        {"a", {{"type", "number"}}},
        {"b", {{"type", "number"}}}
    }},
    {"required", nlohmann::json::array({"a", "b"})}
};

server.add_tool("add", "Add two numbers", std::move(schema),
                [](const nlohmann::json& args) -> nlohmann::json {
                    double a = args.at("a").get<double>();
                    double b = args.at("b").get<double>();
                    std::string text = "Result: " + std::to_string(a + b);
                    return {{"content", nlohmann::json::array(
                        {nlohmann::json{{"type", "text"}, {"text", std::move(text)}}})}};
                });

Typed Handlers

For better type safety and cleaner code, you can use custom C++ structs for tool input and output. Any type that implements to_json and from_json (using NLOHMANN_DEFINE_TYPE_INTRUSIVE or manual implementation) can be used.

Using typed handlers provides several advantages:

  1. Automatic Validation: The SDK automatically deserializes the incoming JSON into your struct, validating the presence and types of required fields.

  2. Type Safety: Your handler logic works with native C++ types rather than dynamic JSON objects.

  3. Self-Documentation: The input and output structures serve as clear documentation of the tool’s interface.

The following example demonstrates defining input and output structures for a calculator tool:

struct AddInput {
    double a;
    double b;
};

inline void to_json(nlohmann::json& j, const AddInput& v) {
    j = nlohmann::json{{"a", v.a}, {"b", v.b}};
}

inline void from_json(const nlohmann::json& j, AddInput& v) {
    j.at("a").get_to(v.a);
    j.at("b").get_to(v.b);
}

struct AddOutput {
    double result;
};

inline void to_json(nlohmann::json& j, const AddOutput& v) { j = nlohmann::json{{"result", v.result}}; }

inline void from_json(const nlohmann::json& j, AddOutput& v) { j.at("result").get_to(v.result); }

You then register the tool by providing these types as template arguments to add_tool:

// Tool: add — sync handler, no context
nlohmann::json add_schema = {
    {"type", "object"},
    {"properties", {{"a", {{"type", "number"}}}, {"b", {{"type", "number"}}}}},
    {"required", nlohmann::json::array({"a", "b"})},
};

server.add_tool<AddInput, AddOutput>(
    "add", "Add two numbers", add_schema,
    [](AddInput in) -> AddOutput { return AddOutput{.result = in.a + in.b}; });

When using typed handlers, the SDK uses the template parameters to automatically wrap your handler in a layer that performs the conversion between nlohmann::json and your custom types.

Async Handlers with Context

Many tools need to perform asynchronous work, such as network requests or long-running computations. mcp-cpp-sdk supports coroutine-based handlers returning mcp::Task<T>.

Additionally, handlers can accept a mcp::Context& parameter to access server-level features:

  • Logging: Send real-time logs back to the client.

  • Progress Reporting: Inform the client about long-running task status.

  • Cancellation: Check if the client has requested to abort the task.

The following example shows a tool that logs information and performs an asynchronous operation:

    [](Context& ctx, nlohmann::json in) -> Task<nlohmann::json> {
        auto text = in.at("text").get<std::string>();
        co_await ctx.log_info("Uppercasing: " + text);
        for (auto& ch : text) {
            ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
        }
        nlohmann::json out = {{"result", text}};
        co_return out;
    });

Progress and Cancellation

For tasks that take a significant amount of time, it is good practice to report progress and periodically check for cancellation requests.

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

For work that outlasts a request, a tool can run as a task that the client polls for, see Tasks.

For more details on using the context, see Server Context.

Error Handling

There are two primary ways to handle errors in tool handlers:

  1. Throwing Exceptions: A std::exception thrown by any tool handler (synchronous, typed or asynchronous) is converted into a tool error result (isError: true) whose text is the exception message. An exception from middleware is not: it is answered as a JSON-RPC -32603 error (see Middleware).

  2. Explicit Error Returns: A handler declared with Out=mcp::CallToolResult can return a complete result whose isError field is true. add_raw_tool() provides the equivalent low-level JSON escape hatch with runtime validation.

The following example demonstrates both patterns:

// Tool 1: Throws std::runtime_error
nlohmann::json throw_error_schema = {
    {"type", "object"},
    {"properties", {{"message", {{"type", "string"}}}}},
    {"required", nlohmann::json::array({"message"})},
};

server.add_tool("throw_error", "Throws a runtime error", throw_error_schema,
                [](const nlohmann::json& args) -> nlohmann::json {
                    std::cout << "[Server] throw_error handler called\n";
                    std::string msg = args.at("message").get<std::string>();
                    throw std::runtime_error("Intentional error: " + msg);
                });

// Tool 2: Returns error JSON explicitly
nlohmann::json return_error_schema = {
    {"type", "object"},
    {"properties", {{"code", {{"type", "integer"}}}}},
    {"required", nlohmann::json::array({"code"})},
};

server.add_tool<nlohmann::json, mcp::CallToolResult>(
    "return_error", "Returns error JSON", return_error_schema,
    [](const nlohmann::json& args) -> mcp::CallToolResult {
        std::cout << "[Server] return_error handler called\n";
        int code = args.at("code").get<int>();
        mcp::CallToolResult result;
        mcp::TextContent content;
        content.text = "Application error with code " + std::to_string(code);
        result.content.emplace_back(std::move(content));
        result.isError = true;
        return result;
    });

Use isError: true when the tool completed normally but needs to report an application-level failure back to the client. Either way the client receives a normal tools/call result and the session stays open. This is a critical distinction:

  • Protocol Errors: Issues like malformed JSON, invalid method names, or disconnected transports cause JSON-RPC level errors.

  • Application Errors: Issues within your tool’s logic (e.g., “file not found”, “invalid input value”) should usually be returned as isError: true tool results so the client can inspect them as normal tool output.

Tool Output Schema

In addition to the input schema, you can provide an optional outputSchema. This allows clients to understand the structure of the data returned by the tool, enabling better integration with typed systems or UI rendering.

When an outputSchema is provided, the SDK includes it in the tool definition sent to clients. The schema is advertised as outputSchema in the tool’s metadata, enabling clients to understand the structure of the tool’s output. A tool with an outputSchema must return structuredContent (unless the result is an error), and that content must conform to the schema; otherwise the call fails with a JSON-RPC error (see Schema Validation).

nlohmann::json output_schema = {
    {"type", "object"},
    {"properties", {
        {"result", {{"type", "number"}}}
    }}
};

server.add_tool<AddInput, AddOutput>(
    "add_with_output_schema",
    "Add two numbers with defined output structure",
    input_schema,
    output_schema,
    [](AddInput in) -> AddOutput { return {in.a + in.b}; }
);

Structured Content

While simple tools can return raw JSON, more complex tools might want to return structured content blocks (text, images, or embedded resources). The mcp::CallToolResult structure provides a standard way to return multiple content blocks.

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

server.add_tool<nlohmann::json, mcp::CallToolResult>(
    "success", "Returns successfully", success_schema,
    [](const nlohmann::json& args) -> mcp::CallToolResult {
        std::cout << "[Server] success handler called\n";
        int value = args.at("value").get<int>();
        mcp::CallToolResult result;
        mcp::TextContent content;
        content.text = "Successfully doubled the value: " + std::to_string(value * 2);
        result.content.emplace_back(std::move(content));
        return result;
    });

Schema Validation

The two most recent protocol revisions (2025-11-25 and 2026-07-28) require a server to validate tool inputs and to return structured results that conform to the output schema. The SDK does both by default.

At registration. add_tool() and add_raw_tool() compile the input and output schemas and throw mcp::SchemaError (a std::invalid_argument) naming the tool and the field when a schema cannot be used. SchemaError::category() says why:

  • eInvalidSchema: the schema is not a JSON object, breaks the rules of its dialect’s metaschema, holds NaN or Infinity (which JSON cannot represent), has a pattern that is not a regular expression, or (for inputSchema) does not declare "type": "object", or a tool input schema holds an invalid x-mcp-header annotation.

  • eUnsupportedDialect: $schema names a dialect the SDK does not implement.

  • eUnresolvedRef: a $ref points outside the document.

  • eUnsupportedPattern: a pattern or patternProperties key is one the linear-time matcher cannot run, such as a lookahead, or the schema’s patterns exceed the matcher’s size limits. Patterns are checked after everything else, so a schema refused for this reason has no other problem.

Dialects. A schema without $schema is JSON Schema 2020-12, the default the specification sets. $schema may also name 2019-09, draft-07, draft-06 or draft-04.

References. $ref resolves within the document (JSON Pointer fragments, anchors, subschemas identified by $id). A $ref to the whole metaschema of a supported dialect checks the value as a schema of that dialect. Anything else, such as an http: or file: URI or a relative file name, is refused; the SDK never fetches a schema.

Patterns. pattern and patternProperties use a linear-time matcher for the ECMA-262 subset JSON Schema recommends. Backreferences, lookaround and Unicode property escapes (\p{...}) are not supported, and a schema using them is refused as eUnsupportedPattern. So is a pattern that is longer than 65,536 bytes, nests groups more than 64 levels deep, repeats more than 10,000 times in one {n,m}, or compiles to more than 20,000 matcher instructions; a counted repetition compiles to one copy of its operand per repetition, so ^.{1,2000}$ is well within the limit. The patterns of one schema may compile to 1,000,000 instructions in all (SchemaOptions::max_pattern_instructions). A pattern that is not a regular expression at all, such as ( or [z-a], makes the schema invalid. A client still lists a tool whose schema uses such a pattern.

Arguments. Each tools/call checks the arguments against the input schema just before the handler would run, after any middleware. Arguments that do not conform are answered with an isError: true result whose text lists the violations (Invalid arguments: /quantity: ...), and the handler does not run. Server::invoke_tool() applies the same check.

Structured results. A successful result’s structuredContent is checked against the outputSchema. A result that does not conform is a fault in the tool and is answered with Internal error (-32603) naming the violations. A NaN or Infinity in the result is checked as the null it would be sent as. Error results are not checked.

Turning checks off. An application that validates on its own can turn either check off before run(); tool_validation_stats() counts the calls each check refused:

mcp::ToolValidationOptions validation;
validation.validate_arguments = false;
validation.validate_structured_content = true;
server.set_tool_validation(validation);

auto stats = server.tool_validation_stats();
// stats.argument_rejections, stats.structured_content_rejections

Limits. Validation is bounded so that neither a schema nor a value can exhaust the stack or take time exponential in its size. A value nested deeper than 64 levels is invalid (SchemaOptions::max_instance_depth). At most 192 subschemas are evaluated one inside another, $ref targets included, which a schema recursing through anyOf, items, allOf and $ref at every level reaches at 48 levels of the value. The evaluation work allowed grows with the size of the value times the size of the schema, up to 256 million units (SchemaOptions::max_evaluation_work); a value’s size counts its nodes, their nesting, the property names above them and its text. When no branch of anyOf or oneOf matches, a few violations of the first branch are reported with it. Pattern matching runs in time linear in the text, but a pattern that keeps many alternatives open at once, such as an unanchored .{1,1000}x, costs thousands of steps per character, so matching has its own budget: 16 million steps plus 64 for every byte of string and property name in the value (SchemaOptions sets both for a CompiledSchema). Typical patterns take a handful of steps per byte. A value that exceeds a limit is reported invalid with validation stopped: .... A schema that exceeds a limit even for a trivial value, such as {"$ref": "#"}, is refused at registration. Schema documents may nest up to 64 levels.

Evaluation. Every schema, in each of the five dialects, is evaluated directly on the nlohmann::json value, without copying it. Violation messages are written for people and their wording may change.

On the client. Client::list_tools() lists every tool the server names. It compiles each outputSchema and reports one it cannot use through ClientOptions::on_tool_schema_error; inputSchema is the server’s to enforce, so the client does not compile it. Client::call_tool() checks a successful result’s structuredContent against the tool’s listed outputSchema and throws mcp::StructuredContentError when it does not conform. Calling a tool whose outputSchema is invalid, in an unsupported dialect or has a $ref outside the document throws that mcp::SchemaError without sending the request; an outputSchema that only uses a pattern the matcher cannot run leaves that tool’s results unchecked. ClientOptions::validate_tool_schemas = false turns all of this off.

mcp::CompiledSchema (mcp/protocol/schema.hpp) is the validator behind all of this and can be used directly:

auto schema = mcp::CompiledSchema::compile(
    {{"type", "object"}, {"required", {"id"}}});
auto result = schema.validate({{"name", "x"}});
// result.valid == false; result.violations[0].message names "id"

examples/features/schema_validation.cpp runs these checks end to end over an in-memory transport: refusals at registration, an argument violation, a structured result refused by the server, the same result refused by the client when the server’s check is off, and the counters.

See Also