Contributing ============ Thank you for your interest in contributing to mcp-cpp-sdk! This document provides guidelines for contributing code, documentation, and bug reports. Development Setup ----------------- To set up your development environment: .. code-block:: bash # Clone the repository git clone https://github.com/yurirocha15/mcp-cpp-sdk.git cd mcp-cpp-sdk # Initialize development environment python scripts/init.py --dev # Build python scripts/build.py # Build with tests and run them python scripts/build.py --test The ``python scripts/init.py --dev`` target installs all development dependencies including: * Conan packages (Boost, nlohmann_json, GTest) * Git hooks for pre-commit checks * Development tools (clang-format, clang-tidy, gcovr for coverage reports) Code Style ---------- C++20 Standards ^^^^^^^^^^^^^^^ The SDK uses modern C++20 features: * **Coroutines**: Use ``co_await`` and ``co_return`` for async operations * **Concepts**: Define type requirements with concepts, not SFINAE * **Ranges**: Use range-based algorithms where appropriate * **Modules**: Not currently used; the SDK has public headers and compiled sources Follow these guidelines: * Prefer value semantics and move semantics over raw pointers * Use RAII for all resource management * Avoid manual memory management (``new``/``delete``) * Use ``std::unique_ptr`` for ownership, ``std::shared_ptr`` only when necessary * Prefer ``constexpr`` for compile-time constants Naming Conventions ^^^^^^^^^^^^^^^^^^ Follow these naming conventions, which ``.clang-tidy`` enforces with ``readability-identifier-naming``: * **Classes/Structs/Enums/Unions/Concepts**: ``CamelCase`` (e.g., ``Server``, ``ITransport``, ``CallToolRequest``) * **Functions/Methods**: ``lower_case`` (e.g., ``add_tool()``, ``call_tool()``, ``log_info()``) * **Variables**: ``lower_case`` (e.g., ``request_id``, ``tool_name``, ``json_result``) * **Class members**: ``lower_case_`` with a trailing underscore (e.g., ``transport_``, ``strand_``) * **Global variables and namespace-scope constants**: ``g_`` prefix; constants are ``g_UPPER_CASE`` (e.g., ``g_INVALID_PARAMS``), declared in ``mcp/core/constants.hpp`` or ``src/include/mcp/detail/constants.hpp`` * **Static variables**: ``s_`` prefix (e.g., ``s_cache`` for a function-local static) * **Enum values**: ``eCamelCase`` (e.g., ``eServerError``) * **Class constants** (static data members): ``lower_case`` (e.g., ``max_repeat_count``) * **Macros**: ``UPPER_CASE`` (e.g., ``MCP_DEPRECATED``) * **Namespaces**: ``lower_case`` (e.g., ``namespace mcp { namespace detail { ... } }``) ``make lint`` runs clang-tidy locally over ``include/`` and ``src/`` with the checks ``.clang-tidy`` enables, and fails on any warning. The CI ``clang-tidy`` job runs the same checks over the same directories, and checks ``examples/`` for identifier naming only. It runs when a change touches those directories, ``.clang-tidy`` or the CMake files. CI uses clang-tidy 23.1.4 (``python3 -m pip install clang-tidy==23.1.4``); older versions report findings that it does not. Code Formatting ^^^^^^^^^^^^^^^ Use ``make format`` to automatically format your code with clang-format. The CI pipeline will reject PRs with formatting violations. Doxygen Comments ^^^^^^^^^^^^^^^^ All public APIs must have Doxygen documentation: .. code-block:: cpp /** * @brief Register a tool with the server. * * @details Tools are callable functions exposed to MCP clients. The handler * will be invoked when a client sends a CallToolRequest with matching name. * * @param name Tool name (must be unique) * @param description Human-readable description * @param input_schema JSON schema for tool parameters * @param handler Callable that processes the tool request * * @throws std::invalid_argument if tool name is empty or already registered */ void add_tool(std::string name, std::string description, nlohmann::json input_schema, TypeErasedHandler handler); Required Doxygen tags: * ``@brief`` - One-line summary * ``@param`` - For each parameter * ``@return`` - For non-void returns (or ``@returns``) * ``@throws`` - For exceptions that may be thrown * ``@details`` - Extended description (optional but recommended) Testing ------- All contributions must include tests. The SDK uses Google Test (GTest). Writing Tests ^^^^^^^^^^^^^ Place tests in ``test/`` directory, mirroring the library surface area: .. code-block:: bash include/mcp/server/server.hpp → test/server/server_core_test.cpp include/mcp/client/client.hpp → test/client/client_core_test.cpp Example test structure: .. code-block:: cpp #include #include #include TEST(ServerTest, AddToolRegistersCorrectly) { mcp::Server server(/* ... */); server.add_tool("test", "A test tool", {{"type", "object"}}, [](const nlohmann::json&) -> mcp::Task { co_return nlohmann::json{{"result", "ok"}}; }); // Assertions... } The test program compiles its files a few at a time in one translation unit (a unity build). Put the contents of a test file in a namespace named after the file, for example ``namespace server_core_test { ... }``, so that its helpers, aliases and using-declarations cannot collide with, or silently overload, those of another file compiled with it. Running Tests ^^^^^^^^^^^^^ .. code-block:: bash # Run all tests python scripts/build.py --test # Run the full suite with ctest output on failures ctest --preset conan-release --output-on-failure # Run the GoogleTest binary directly with a filter ./build/release/mcp-sdk-tests --gtest_filter=ServerCoreTest.* A test build from a checkout needs Python 3.9+ for the peer-input matrix check; opt out with ``-DMCP_CPP_SDK_CHECK_JSON_MATRIX=OFF``. The unity build of the test program is controlled by two CMake options: ``-DMCP_CPP_SDK_TEST_UNITY_BUILD=OFF`` compiles every test file on its own, and ``-DMCP_CPP_SDK_TEST_UNITY_BATCH_SIZE=`` sets how many files share a translation unit (the default is 4). Editing a test file recompiles all the files in its group. Code Coverage ^^^^^^^^^^^^^ Aim for >80% code coverage for new features: .. code-block:: bash # Generate coverage report (needs gcovr) python scripts/build.py --coverage --test # View report open build/coverage/coverage.html CI collects the report in its GCC sanitizer build (``python scripts/build.py --sanitize --coverage --test``, which writes ``build/sanitize/coverage.xml``) and uploads it to `Codecov `_, which comments on pull requests with the coverage of the changed lines. That report leaves out the branches of lines without an ``if``, loop, ``switch``, ``?:``, ``&&`` or ``||``: they come from code the compiler generates or inlines there, such as exception and cleanup paths. ``build/sanitize/coverage.json``, kept as the ``coverage-report`` artifact of the CI run, has every branch. Sanitizers ^^^^^^^^^^ CI runs the test suite under each sanitizer on pushes to ``main`` and on pull requests into it. The same builds run locally: .. code-block:: bash # AddressSanitizer + UndefinedBehaviorSanitizer python scripts/build.py --sanitize --test # ThreadSanitizer python scripts/build.py --tsan --test # Either of the two, compiled with Clang python scripts/build.py --tsan --compiler clang --test # MemorySanitizer (Clang only) python scripts/build.py --msan --test Run ThreadSanitizer for code that runs on several threads or is closed from another thread. The two reports that are not defects (Asio's fence-based reference count and its signal handler) are suppressed in ``test/tsan.supp``, each with its reason. MemorySanitizer reports a read of any memory that uninstrumented code wrote, so ``--msan`` builds its own libc++ from a pinned LLVM commit into ``build/msan-libcxx`` on first use, and has Conan rebuild Boost, OpenSSL and GoogleTest against it. The first run is slow; later runs reuse both. It needs ``clang-18`` and ``git``. Its tests run many times slower than in a debug build, so each may take 600 seconds instead of 120. The ThreadSanitizer and MemorySanitizer builds run under ``setarch -R`` where it is available, because neither can start on kernels with a high ASLR entropy. Distribution Builds ^^^^^^^^^^^^^^^^^^^ The builds above use Conan's Boost. When a push to ``main`` changes the source or the packaging, CI also builds the Homebrew formula, the Windows payload and the native ``.deb`` and ``.rpm`` packages. Pull requests skip these builds; running the CI workflow by hand on a branch includes them. The native packages cover every x86_64 release route, built exactly as a release does: inside the locked release builder images (``release/native-builders/lock.json``), with each distribution's compiler, Boost, Python and packaging flags, from Boost 1.74 on Ubuntu 22.04 and Debian 12 up. Each build runs the test suite, then builds and runs a consumer against the extracted packages and another against the installed ones. It needs Docker: .. code-block:: bash python scripts/package_build.py core --output build/package-core python scripts/package_build.py build debian-bookworm-amd64 \ --core build/package-core --output build/package-out For a faster loop over the C++ build alone, ``scripts/distro_build.py`` runs CMake, CTest and the release tooling's tests in one image: .. code-block:: bash # Cap the container on a workstation python scripts/distro_build.py el-9-x86_64 --jobs 4 --docker-arg=--memory=12g Pull Request Process -------------------- 1. Fork and Branch ^^^^^^^^^^^^^^^^^^ Fork the repository and create a feature branch: .. code-block:: bash git checkout -b feature/my-awesome-feature Use descriptive branch names: * ``feature/websocket-compression`` - New features * ``fix/client-timeout-bug`` - Bug fixes * ``docs/api-reference`` - Documentation * ``refactor/handler-dispatch`` - Refactoring 2. Make Changes ^^^^^^^^^^^^^^^ * Write code following the style guide * Add tests for new functionality * Update documentation (Doxygen comments, .rst files) * Run tests locally: ``python scripts/build.py --test`` * Format code: ``make format`` * Add a changelog entry for a change users notice (see `Changelog`_) 3. Commit ^^^^^^^^^ Write clear, atomic commit messages: .. code-block:: bash # Good commit messages git commit -m "feat: Add WebSocket compression support" git commit -m "fix: Fix client timeout handling for large responses" git commit -m "docs: Update architecture.rst with transport details" # Bad commit messages git commit -m "fix bug" git commit -m "WIP" git commit -m "asdf" Follow these guidelines: * First line: Use conventional commit format, imperative mood, <80 chars (e.g., "feat: Add X", "fix: Fix Y") * Body: Explain **why**, not **what** (code shows what) * Reference issues: "Fixes #123" or "Relates to #456" 4. Push and Create PR ^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: bash git push origin feature/my-awesome-feature Then create a pull request on GitHub with: * **Title**: Clear, descriptive summary * **Description**: What, why, and how * **Tests**: Describe test coverage * **Breaking changes**: Call out any API changes PR Template ^^^^^^^^^^^ .. code-block:: markdown ## Summary Brief description of the change. ## Motivation Why is this change needed? What problem does it solve? ## Changes - Bullet list of changes - Include any API modifications - Note breaking changes ## Testing - Unit tests added: [Yes/No] - Integration tests added: [Yes/No] - Manual testing performed: [Yes/No] ## Documentation - Doxygen comments updated: [Yes/No] - User documentation (RST) updated: [Yes/No] Fixes #123 5. Code Review ^^^^^^^^^^^^^^ Maintainers will review your PR. Be prepared to: * Answer questions about design decisions * Make requested changes * Add additional tests * Update documentation All PRs require: * Passing CI checks (build, tests, format) * At least one approving review * No unresolved comments 6. Merge ^^^^^^^^ Once approved, a maintainer will merge your PR. The project uses squash merging to keep the main branch history clean. Changelog --------- A change that users notice gets one entry in the ``[Unreleased]`` section of ``CHANGELOG.md``: under ``Added``, ``Changed``, ``Deprecated``, ``Removed``, ``Fixed`` or ``Security``, and also under ``Migrating from X.Y.Z`` when code written for the last release needs a change to compile. * Write one sentence about what changed for users, and name the API it concerns. The documentation and the commit message hold the details. * Keep each entry to 200 characters. The release tests check this. * Before a release, a ``Highlights`` part lists the few changes the release page shows. Reporting Bugs -------------- Use GitHub Issues to report bugs. Include: * **Environment**: OS, compiler version, Boost version * **Steps to reproduce**: Minimal example code * **Expected behavior**: What should happen * **Actual behavior**: What actually happens * **Stack trace**: If applicable (crashes, exceptions) Example bug report: .. code-block:: markdown **Environment** - OS: Ubuntu 22.04 - Compiler: GCC 11.3 - Boost: 1.80 - SDK Version: 0.1.0 **Steps to Reproduce** ```cpp mcp::Client client(transport, executor); co_await client.call_tool("nonexistent", nlohmann::json::object()); // Hangs forever ``` **Expected**: Exception thrown or timeout **Actual**: Hangs indefinitely **Stack Trace** (gdb output if available) .. _known-issues: Known Issues ------------ GCC 11 SSO Coroutine Bug ------------------------ **When writing coroutines (``Task`` functions), never store ``std::string`` locals in the coroutine frame across a ``co_await`` suspension on GCC 11.** There is a confirmed GCC 11 compiler bug: * `GCC Bug #107288 `_ * `GCC Bug #100611 `_ * `Boost.Asio Issue #1027 `_ GCC 11 corrupts the internal self-pointer of ``std::string`` (SSO — Small String Optimization) when the string lives in a heap-allocated coroutine frame and survives across a suspension point. The corruption happens at destructor time, causing ``munmap_chunk(): invalid pointer`` crashes. **Affected types** (unsafe across ``co_await`` in GCC 11): * ``std::string`` (including moved-from empty strings) * ``std::optional`` with short values * Any struct containing ``std::string`` (e.g. ``JSONRPCRequest``, ``RequestId`` with string variant) **Safe types** across ``co_await``: * ``nlohmann::json`` (heap-allocated internally) * ``std::string_view`` (trivially copyable pointer+size) * ``int64_t``, raw pointers (trivially copyable) **Fix patterns used in this codebase:** **Scope-before-await**: Build SSO-prone objects inside a ``{}`` scope, serialize to ``std::string wire`` (long output, > 15 chars, heap-allocated), close scope (destroying all SSO strings), then ``co_await transport->write_message(wire)``. .. code-block:: cpp std::string wire; { JSONRPCNotification notification; notification.method = std::move(method); // SSO risk notification.params = std::move(params); wire = nlohmann::json(std::move(notification)).dump(); } // SSO strings destroyed here co_await transport_->write_message(wire); // safe: wire is always > 15 chars **int64_t for IDs**: Store the request ID as ``int64_t`` across suspensions (trivially copyable), reconstruct the string after all ``co_await`` calls. .. code-block:: cpp int64_t id = next_id_.fetch_add(1); // safe across suspension // ... co_await ... auto id_str = std::to_string(id); // reconstruct after suspension **No named temporaries**: Pass ``params.get()`` directly as a function argument instead of storing it in a named local, so no SSO string ever enters the frame. .. code-block:: cpp // DO NOT: auto input = params.get(); // named local stays in frame Out output = co_await handler(ctx, params.get()); // direct: never in frame **Named aggregate arguments**: GCC releases before 13 can destroy a temporary built inside a ``co_await`` expression twice (`GCC Bug #101367 `_). On GCC 11 this hits braced aggregates (``T{...}``, ``T{.field = ...}`` or a bare ``{...}``) and the result of a conditional expression passed as coroutine arguments. Build such an argument as a named local and move it in. .. code-block:: cpp // DO NOT: co_await dispatch(msg, RequestScope{nullptr, std::move(cancelled)}); RequestScope scope{nullptr, std::move(cancelled)}; co_await dispatch(msg, std::move(scope)); **Rule for wire builders**: ``make_result_wire()`` and ``make_error_wire()`` are **synchronous** static helpers. Do NOT convert them to ``Task`` coroutines — that would force callers to store ``RequestId`` (SSO risk) in their frames across the callee's suspensions. **Detection**: Run tests on Ubuntu 22.04 / GCC 11. The crash manifests as ``munmap_chunk(): invalid pointer`` at process exit, not at the point of access, making it hard to debug without valgrind. GCC 12 and 13 Initializer-List Coroutine ICE --------------------------------------------- **Never write an initializer list inside a co_await expression when its elements have non-trivial destructors.** GCC 12 and GCC 13 crash outright: .. code-block:: text internal compiler error: in build_special_member_call, at cp/call.cc:11096 That is GCC 13.3's line number; GCC 12.4 reports ``cp/call.cc:10556``. Unlike the GCC 11 bug above, this is a compile-time failure, not a runtime one, and the diagnostic points at the closing brace of the enclosing lambda rather than the offending argument. GCC 13 is the default compiler on Ubuntu 24.04. **Affected** (each crashes GCC 12 and 13): .. code-block:: cpp co_await client.call_tool("hello", nlohmann::json{{"name", "World"}}); co_await client.call_tool("hello", nlohmann::json({{"name", "World"}})); // parens do not help co_await client.get_prompt("greet", std::map{{"who", "you"}}); co_await client.call_tool("e", std::vector{"a", "b"}); **Not affected**: ``nlohmann::json::object()``, ``std::vector{1, 2, 3}`` (trivially destructible elements), a ``std::string`` temporary, and aggregate initialization such as ``mcp::ClientCapabilities{}`` or ``AddArgs{.a = 3.0, .b = 4.0}``. The trigger is the initializer-list backing array, not the type. **Fix pattern — hoist-before-await**: bind the value to a named variable before the co_await expression. .. code-block:: cpp // DO NOT: co_await client.call_tool("hello", nlohmann::json{{"name", "World"}}); nlohmann::json arguments{{"name", "World"}}; auto result = co_await client.call_tool("hello", arguments); Changing the SDK's own signatures does not help: a parameter taken by value instead of by const reference still crashes. Avoiding the construct at the call site is the only fix. **Detection**: ``scripts/check_readme_snippets.py`` compiles the README's complete examples with the toolchain that built the SDK, and CI runs it on every matrix entry except Windows: GCC on Linux and Clang on macOS. A change to the README's C++ alone runs it once, in the README snippets job, with GCC on Ubuntu. GCC 12 co_await in a Condition ------------------------------ **Never co_await inside an** ``if`` **condition.** GCC 12.2, the compiler of Debian 12, miscompiles a coroutine whose ``if`` condition contains a ``co_await``: the coroutine crashes or never completes, at ``-O0`` and ``-O2`` alike, even when it ends with a ``throw`` before reaching that condition. GCC 11.4 and 13.3 compile the same code correctly. .. code-block:: cpp // DO NOT: if (!co_await validator(token)) { ... } const bool valid = co_await validator(token); if (!valid) { ... } **Detection**: the ``debian-bookworm-amd64`` distribution build in CI. Feature Requests ---------------- Feature requests are welcome! Use GitHub Issues with the "enhancement" label. Include: * **Use case**: Why do you need this feature? * **Proposed API**: What should the API look like? * **Alternatives considered**: Other approaches you evaluated * **Breaking changes**: Would this break existing code? Community Guidelines -------------------- * Be respectful and inclusive * Provide constructive feedback * Help newcomers get started * Celebrate contributions from others Thank you for contributing to mcp-cpp-sdk!