Error Handling ============== This guide covers error handling patterns in the MCP C++ SDK, focusing on both server-side and client-side strategies. Proper error handling ensures that your MCP applications are resilient, informative, and provide a smooth user experience even when things go wrong. Overview -------- The MCP C++ SDK leverages a combination of JSON-RPC error codes, C++ exceptions, and structured result flags to communicate errors between servers and clients. The primary goals of the error handling system are: 1. **Clarity**: Provide meaningful error messages and codes to identify the source of the problem. 2. **Isolation**: Prevent a single failure from crashing the entire server or client session. 3. **Graceful Degradation**: Allow clients to handle errors and continue functioning where possible. JSON-RPC Error Codes -------------------- The SDK follows the JSON-RPC 2.0 specification for error reporting. Standard error codes include: - ``-32700``: Parse error (Invalid JSON received) - ``-32600``: Invalid Request - ``-32601``: Method not found - ``-32602``: Invalid params - ``-32603``: Internal error Additionally, the SDK defines MCP-specific codes used throughout the library: - ``-32000``: Unauthorized - ``-32001``: Request timed out - ``-32002``: Resource not found (``g_RESOURCE_NOT_FOUND``), in protocol revisions 2025-11-25 and earlier, with the URI in ``data``. Revision 2026-07-28 answers ``-32602`` instead, also with the URI in ``data``. - ``-32020``: Header mismatch (``g_HEADER_MISMATCH``) - ``-32021``: Missing required client capability (``g_MISSING_REQUIRED_CLIENT_CAPABILITY``) - ``-32022``: Unsupported protocol version (``g_UNSUPPORTED_PROTOCOL_VERSION``) - ``-32800``: Request cancelled - ``-31000``: Connection closed (``g_CONNECTION_CLOSED``, generated by the client). It lies outside the range JSON-RPC reserves, so it cannot be mistaken for an error the peer sent. A transport that fails to reach the server throws it too: a refused or dropped connection, and an HTTP error status, which ``data()`` holds as ``httpStatus``. The transport's exception, such as an ``mcp::HttpStatusError``, is nested in it and rethrown by ``std::rethrow_if_nested()``, except when the server answers with an event stream that breaks off: the message alone says why then. A failure the transport detects itself is an ``mcp::TransportError``, whose ``kind()`` says whether the transport was closed, could not connect or start the server, failed to read or write, or received what it cannot carry; a TLS failure is an ``mcp::TlsError``, which derives from it. The built-in transports report the network library's errors as ``TransportError`` too, with the error, such as ``std::errc::connection_refused``, in ``code()``. An ``mcp::auth::OAuthClientTransport`` passes on a failed authorization as its authenticator reports it, such as an ``mcp::auth::MetadataPolicyError``. The codes ``-32020`` to ``-32022`` belong to protocol revision 2026-07-28. See `Protocol Errors`_. When implementing custom tools, you should prefer using standard error codes where they apply, or use codes in the range ``-32000`` to ``-32099`` for application-specific protocol errors. Protocol Errors --------------- A server that serves protocol revision 2026-07-28 answers a request it cannot serve with one of these errors. The client throws them as ``mcp::McpError`` like any other error response, and ``McpError::data()`` holds the ``data`` member. ``g_UNSUPPORTED_PROTOCOL_VERSION`` (-32022) The request names a protocol version the server does not serve. This includes a legacy version named in the ``_meta`` of a request, and any version when the server's ``ServerProtocolPolicy`` has ``serve_modern`` set to false. ``data`` is an ``UnsupportedProtocolVersionData`` with ``supported``, the versions the server serves, and ``requested``. ``g_MISSING_REQUIRED_CLIENT_CAPABILITY`` (-32021) A handler asked the client a question (elicitation, sampling or roots) that needs a capability the request did not declare. ``data.requiredCapabilities`` names what is needed. ``g_HEADER_MISMATCH`` (-32020) Over HTTP, a required header is missing or repeated, or does not match the body. See :doc:`deployment`. ``g_INVALID_PARAMS`` (-32602) A required ``_meta`` field is missing or malformed, ``server/discover`` has no protocol version, or a ``requestState`` is unknown, expired or already used. A ``tools/call`` of an unknown tool and a ``prompts/get`` of an unknown prompt are answered with it as well. ``g_METHOD_NOT_FOUND`` (-32601) The method does not exist in 2026-07-28: ``ping``, ``logging/setLevel``, ``resources/subscribe``, ``resources/unsubscribe`` and ``shutdown``. A server that serves only 2026-07-28 also answers ``initialize`` with it, naming the versions it serves in the message and in ``data.supported``. .. code-block:: cpp try { auto result = co_await client.call_tool("echo", args); } catch (const mcp::McpError& error) { if (error.code() == mcp::constants::jsonrpc::g_UNSUPPORTED_PROTOCOL_VERSION && error.data()) { auto data = error.data()->get(); // data.supported lists the versions the server serves } } In a 2026-07-28 session ``Client::ping()`` fails with ``g_METHOD_NOT_FOUND`` without sending anything, because the revision has no ``ping``. Connecting to Servers of Unknown Era ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default a client sends ``server/discover`` to find out which protocol a server speaks (``ClientProtocol::automatic()``). Against a server of 2025-11-25 or earlier this costs one extra round trip before the client sends ``initialize``. A legacy server that ignores the request instead of answering it with an error makes the client wait for ``ClientOptions::probe_timeout`` (3 seconds by default) before it falls back. A server that closes the connection when it receives the probe fails ``connect()`` with an ``McpError`` whose message names ``ClientProtocol::legacy()`` as the remedy. To avoid the probe, pin the protocol with ``ClientOptions::protocol`` set to ``ClientProtocol::legacy()`` or ``ClientProtocol::pinned(...)``. Server-side Error Handling -------------------------- Server handlers (tools, resources, prompts) can report errors in two primary ways: 1. **Throwing Exceptions**: Exceptions from a tool handler — typed, asynchronous or raw — are converted into tool results with ``isError: true``, because a tool that cannot complete has failed at its own task rather than at the protocol. Exceptions from resource and prompt handlers, which have no such result channel, propagate as JSON-RPC ``Internal error (-32603)`` responses, and so do exceptions from middleware: middleware decides whether a call may proceed at all, so refusing one is a protocol-level answer rather than a tool outcome. Exception messages are flattened and length-bounded before they reach the peer. 2. **Returning Error Results**: For application-level errors (e.g., "File not found" or "Invalid input"), handlers can return a ``CallToolResult`` with the ``isError`` flag set to ``true``. This allows the client to distinguish between a technical failure (like a crash or timeout) and a logical error within the tool's execution. Choosing Between Exceptions and Error Results ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Use **Exceptions** for: - Unexpected system failures (e.g., memory allocation failure, disk I/O errors). - Programming errors (e.g., out-of-bounds access, logic errors). - Conditions that prevent the handler from fulfilling its contract at all. - Use **Error Results** for: - Expected failure modes (e.g., user not found, validation errors). - Situations where the tool successfully ran but couldn't produce the desired output. - Providing detailed, structured error information back to the LLM. Example: Throwing an Exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. literalinclude:: ../../examples/features/error_handling.cpp :language: cpp :start-after: // Tool 1: Throws std::runtime_error :end-before: // Tool 2: Returns error JSON explicitly Example: Returning an Error Result ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. literalinclude:: ../../examples/features/error_handling.cpp :language: cpp :start-after: // Tool 2: Returns error JSON explicitly :end-before: // Tool 3: Accesses invalid argument (nlohmann::json throws) Implicit Exceptions ~~~~~~~~~~~~~~~~~~~ It's important to be aware that some library calls might throw exceptions that you don't explicitly catch. For instance, ``nlohmann::json`` throws an exception if you try to access a non-existent key using ``at()``. In a tool handler such an exception becomes a tool error result like any other; in a resource or prompt handler it becomes a JSON-RPC internal error. .. literalinclude:: ../../examples/features/error_handling.cpp :language: cpp :start-after: // Tool 3: Accesses invalid argument (nlohmann::json throws) :end-before: // Tool 4: Successful tool (for comparison) Client-side Error Handling -------------------------- Clients should always wrap server calls in ``try-catch`` blocks to handle potential network issues, protocol violations, or server-side errors. A tool that fails says so in its result, with ``isError`` set; a request the server refuses throws ``mcp::McpError``, whose ``code()`` is the JSON-RPC error code. The blocking calls of sync mode throw the same exceptions as the awaited calls of async mode: .. literalinclude:: ../../examples/sync/client.cpp :language: cpp :caption: Sync mode :start-after: // Errors: :end-before: // Pagination: :dedent: 4 .. literalinclude:: ../../examples/async/client.cpp :language: cpp :caption: Async mode :start-after: // Errors: :end-before: // Pagination: :dedent: 4 A failed connection throws ``McpError`` with code ``-31000``, as `JSON-RPC Error Codes`_ describes. .. literalinclude:: ../../examples/features/error_handling.cpp :language: cpp :start-after: // ========== TEST 1: Catch exception from thrown error ========== :end-before: // ========== TEST 2: Handle error JSON response ========== Request Timeouts ~~~~~~~~~~~~~~~~ .. important:: **Every client request carries a 30-second deadline by default.** Nothing opts into it: ``ClientOptions::request_timeout`` starts at ``std::chrono::seconds(30)``, and a default-constructed ``Client`` uses it for ``call_tool``, ``read_resource``, ``list_tools`` and every other request. A tool that legitimately runs longer than that — a large model call, a slow build, a batch job — fails on the client side while the server is still working on it. Raise it for the whole client by passing ``ClientOptions`` to the constructor, after the ``Endpoint`` in sync mode or after the transport and executor in async mode: .. code-block:: cpp :caption: Sync mode mcp::ClientOptions options; options.request_timeout = std::chrono::minutes(5); mcp::Client client(mcp::Endpoint::http(url), options); .. code-block:: cpp :caption: Async mode mcp::ClientOptions options; options.request_timeout = std::chrono::minutes(5); mcp::Client client(transport, io.get_executor(), options); A single request can be given its own deadline through ``RequestOptions``, which ``call_tool()``, ``send_request()``, ``read_resource()``, ``get_prompt()``, ``complete()``, ``start_tool()`` and the ``list_*()`` members take as their last argument, as do their blocking forms on ``client.sync()``. A client that makes one slow call among many fast ones gives that call a longer deadline: .. code-block:: cpp mcp::RequestOptions slow; slow.timeout = std::chrono::minutes(30); auto result = co_await client.call_tool("render", args, slow); When the deadline expires the awaiting coroutine throws :cpp:class:`mcp::McpError` with code ``-32001`` (:cpp:var:`mcp::constants::jsonrpc::g_REQUEST_TIMEOUT`) and the message ``Request timed out``. Catch it the same way as any other ``McpError``. .. warning:: A timeout is a local decision. A request whose bytes have not been written yet is dropped before transmission, but once transport I/O has started the server may still run the call to completion after the client has given up. The client sends ``notifications/cancelled`` for a request that times out, other than ``initialize``, which a handler sees as ``ctx.is_cancelled()``, but that cannot undo work the handler has already done. Treat a timed-out non-idempotent request as having an unknown outcome, and see the retry guidance below before repeating it. A non-positive timeout is rejected rather than treated as "no deadline": constructing a ``Client`` with one, or passing one in ``RequestOptions``, throws ``std::invalid_argument``. The SDK offers no way to disable the deadline entirely — use a duration long enough for the slowest call you expect. Catching Server Errors ~~~~~~~~~~~~~~~~~~~~~~ When a server returns a JSON-RPC error response, the ``Client`` methods (like ``call_tool`` or ``read_resource``) throw ``mcp::McpError``, a ``std::runtime_error`` that carries the error code and message. This simplifies the client logic, as you can use standard C++ exception handling for both local and remote failures. Schema Validation Errors ~~~~~~~~~~~~~~~~~~~~~~~~ The client checks a tool result's ``structuredContent`` against the ``outputSchema`` the server listed for the tool and throws ``mcp::StructuredContentError`` when it does not conform. It is an ``mcp::McpError`` with code ``-32603``; ``data()`` holds ``{"violations": [{"instancePath": ..., "message": ...}]}``. An ``outputSchema`` the client cannot use is reported through ``ClientOptions::on_tool_schema_error``, and the tool stays listed. See :doc:`../concepts/tools` for what a call of such a tool does and for the server-side checks, which answer invalid arguments with an ``isError`` result. Handling Application Errors ~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the server returns a successful JSON-RPC response but the tool itself failed (indicated by ``isError: true``), the client receives the result normally and must check the flag. This is common when the tool executes correctly but encounters a business logic error that the LLM should be aware of. .. literalinclude:: ../../examples/features/error_handling.cpp :language: cpp :start-after: // ========== TEST 2: Handle error JSON response ========== :end-before: // ========== TEST 3: Catch exception from invalid JSON access ========== Graceful Degradation Patterns ----------------------------- To ensure your application remains usable during partial failures, consider the following patterns: - **Feature Toggling**: If a specific tool call fails consistently, your client application can temporarily disable or hide the functionality associated with that tool. - **Fallback Content**: When reading a resource fails, provide sensible default content or previously cached values. This is particularly useful for configuration or preference resources. - **UI Feedback**: Instead of showing a generic "Server Error," use the detailed error message from the server to inform the user about what went wrong (e.g., "The search service is currently down, please try again later"). - **Partial Results**: In operations that return lists or multiple pieces of data, consider returning the successfully retrieved parts even if some encountered errors. Retry Strategies ---------------- For transient errors, such as network timeouts or temporary server busy states (indicated by specific error codes), implementing a retry strategy is highly beneficial. - **Exponential Backoff**: Increase the wait time between retries (e.g., 100ms, 200ms, 400ms) to avoid overwhelming a struggling server. - **Max Retries**: Always define a maximum number of attempts to avoid infinite loops. - **Idempotency**: Only retry operations that are idempotent (safe to repeat), such as reading resources or pings. Avoid retrying tools that perform side effects (like making a purchase or deleting a file) unless you are certain it's safe. Logging and Monitoring ---------------------- The SDK provides a built-in logging system that is essential for debugging and monitoring production systems. Use the ``Context`` object in your handlers to log errors and warnings. .. code-block:: cpp server.add_tool("example", "...", schema, [](mcp::Context& ctx, nlohmann::json args) -> mcp::Task { // A json, not a std::string, which must not live across co_await on GCC 11. nlohmann::json message; try { co_return do_work(args); } catch (const std::exception& e) { message = std::string("Tool failed: ") + e.what(); } // A catch block cannot contain co_await, so the error is logged after it. co_await ctx.log(mcp::LoggingLevel::eError, message.get_ref()); throw std::runtime_error(message.get()); }); By logging at the server level, you can aggregate errors across multiple clients and identify systemic issues. For more details on logging, see the :doc:`../concepts/context` guide. Example Walkthrough ------------------- The ``examples/features/error_handling.cpp`` file provides a complete, runnable example of these patterns. It demonstrates: 1. A server with multiple tools that fail in different ways. 2. A client that catches these failures and continues to function. 3. Successful recovery where a subsequent tool call succeeds after previous failures. Run the example to see the output: .. code-block:: bash ./build/release/example-feature-error-handling