From 32569bbfef4a39ef80a1c09387e52ad70a174164 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Thu, 3 Dec 2026 16:55:20 +0300 Subject: [PATCH] MCP: add reusable protocol and transport foundations (closes #45) --- include/Void/MCP/Codec.hpp | 82 ++++ include/Void/MCP/Envelope.hpp | 88 ++++ include/Void/MCP/Transport.hpp | 180 +++++++ include/Void/MCP/Types.hpp | 213 +++++++++ src/MCP/Codec.cpp | 208 ++++++++ src/MCP/Envelope.cpp | 493 +++++++++++++++++++ src/MCP/Legacy.cpp | 170 +++++++ src/MCP/Transport.cpp | 729 +++++++++++++++++++++++++++++ src/MCP/module.cmake | 3 + tests/standalone/MCP/Envelope.cpp | 171 +++++++ tests/standalone/MCP/Transport.cpp | 482 +++++++++++++++++++ 11 files changed, 2819 insertions(+) create mode 100644 include/Void/MCP/Codec.hpp create mode 100644 include/Void/MCP/Envelope.hpp create mode 100644 include/Void/MCP/Transport.hpp create mode 100644 include/Void/MCP/Types.hpp create mode 100644 src/MCP/Codec.cpp create mode 100644 src/MCP/Envelope.cpp create mode 100644 src/MCP/Legacy.cpp create mode 100644 src/MCP/Transport.cpp create mode 100644 src/MCP/module.cmake create mode 100644 tests/standalone/MCP/Envelope.cpp create mode 100644 tests/standalone/MCP/Transport.cpp diff --git a/include/Void/MCP/Codec.hpp b/include/Void/MCP/Codec.hpp new file mode 100644 index 0000000..feccfc2 --- /dev/null +++ b/include/Void/MCP/Codec.hpp @@ -0,0 +1,82 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::MCP +{ + /// Newline-delimited JSON-RPC framing used by the stdio transport + /// (and any custom transport built on a reliable byte stream). + /// + /// A frame is one JSON-RPC message followed by `\n`; embedded newlines + /// are not allowed. A trailing `\r` is tolerated before the newline. + class LineFramer + { + public: + + explicit LineFramer(McpLimits limits = {}); + + /// Append bytes from the stream. Fails when the unterminated + /// tail exceeds `limits.max_line_bytes`. + [[nodiscard]] Void::Result::Result + append(std::string_view bytes); + + /// Pop the next complete line (without the newline). Empty + /// lines are skipped. `nullopt` means more bytes are needed. + [[nodiscard]] Void::Result::Result> + next(); + + [[nodiscard]] std::size_t buffered() const noexcept; + void reset() noexcept; + + private: + + McpLimits m_limits; + std::string m_buffer; + }; + + /// One Server-Sent Events event used by Streamable HTTP responses. + struct SseEvent { + std::string event{}; + std::string data{}; + std::string id{}; + }; + + /// Serialize one SSE event (`event:`/`id:`/`data:` lines terminated by + /// a blank line). Multi-line data is split into multiple `data:` lines. + [[nodiscard]] Void::Result::Result + encode_sse_event(const SseEvent& event, const McpLimits& limits = {}); + + /// Bounded incremental SSE parser. Comment lines and unknown fields + /// are ignored; `data` lines are joined with `\n`. + class SseParser + { + public: + + explicit SseParser(McpLimits limits = {}); + + [[nodiscard]] Void::Result::Result + append(std::string_view bytes); + + [[nodiscard]] Void::Result::Result> + next(); + + [[nodiscard]] std::size_t buffered() const noexcept; + void reset() noexcept; + + private: + + McpLimits m_limits; + std::string m_buffer; + }; + + /// Append the stdio frame terminator and validate the line bound. + [[nodiscard]] Void::Result::Result + frame_line(std::string_view json, const McpLimits& limits = {}); + +} // namespace Void::MCP diff --git a/include/Void/MCP/Envelope.hpp b/include/Void/MCP/Envelope.hpp new file mode 100644 index 0000000..f6ef2ca --- /dev/null +++ b/include/Void/MCP/Envelope.hpp @@ -0,0 +1,88 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::MCP +{ + using JsonValue = Void::Json::Strict::Value; + + /// JSON-RPC request id: null, an integer, or a string. + struct JsonRpcId { + std::variant value{}; + + [[nodiscard]] bool is_null() const noexcept + { + return std::holds_alternative(value); + } + + [[nodiscard]] bool + operator==(const JsonRpcId&) const noexcept = default; + }; + + struct ErrorObject { + std::int32_t code{0}; + std::string message{}; + std::optional data{}; + }; + + struct Request { + JsonRpcId id{}; + std::string method{}; + std::optional params{}; + RequestMetadata metadata{}; + }; + + struct Notification { + std::string method{}; + std::optional params{}; + RequestMetadata metadata{}; + }; + + struct Response { + JsonRpcId id{}; + std::optional result{}; + std::optional error{}; + }; + + using Message = std::variant; + + /// Encode one JSON-RPC message. Request/notification metadata is merged + /// into `params._meta`; responses carry exactly one of result or error. + [[nodiscard]] Void::Result::Result + encode_message(const Message& message, const McpLimits& limits = {}); + + /// Decode exactly one JSON-RPC message, rejecting malformed envelopes, + /// duplicate keys, unknown id types, and limit violations. + [[nodiscard]] Void::Result::Result + decode_message(std::string_view text, const McpLimits& limits = {}); + + /// Parse `_meta` metadata out of a params object (or a `_meta` object). + [[nodiscard]] Void::Result::Result + parse_metadata(const JsonValue& params, const McpLimits& limits = {}); + + /// Build the `_meta` object for a request metadata value. + [[nodiscard]] Void::Result::Result + metadata_to_json(const RequestMetadata& metadata, + const McpLimits& limits = {}); + + [[nodiscard]] Void::Result::Result + encode_json(const JsonValue& value, const McpLimits& limits = {}); + + [[nodiscard]] Void::Result::Result + decode_json(std::string_view text, const McpLimits& limits = {}); + + /// Error response helper (null id is used for transport-level failures). + [[nodiscard]] Response + make_error_response(const JsonRpcId& id, std::int32_t code, + std::string message, + std::optional data = {}); + +} // namespace Void::MCP diff --git a/include/Void/MCP/Transport.hpp b/include/Void/MCP/Transport.hpp new file mode 100644 index 0000000..dea343d --- /dev/null +++ b/include/Void/MCP/Transport.hpp @@ -0,0 +1,180 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::MCP +{ + struct HttpHeader { + std::string name{}; + std::string value{}; + }; + + struct HttpRequest { + std::string method{}; + std::string target{}; + std::vector headers{}; + std::string body{}; + }; + + struct HttpResponse { + int status{200}; + std::vector headers{}; + std::string body{}; + }; + + /// Case-insensitive header lookup. Returns the first match. + [[nodiscard]] std::optional + header_value(const HttpRequest& request, std::string_view name); + + /// Authorization boundary: validate the bearer token (or any scheme the + /// application chooses) and return an authenticated principal. MCP does + /// not implement OAuth, consent, or scope mapping itself. + using AuthorizationCallback = + std::function(const HttpRequest&)>; + + using RequestHandler = + std::function(const Request&)>; + using NotificationHandler = + std::function(const Notification&)>; + + struct StreamableHttpOptions { + McpLimits limits{}; + /// Called for every POST before the message is dispatched. + AuthorizationCallback authorize{}; + bool require_authorization{false}; + /// Respond to requests with `text/event-stream` instead of a + /// single `application/json` object. + bool prefer_sse{false}; + /// Protocol revisions accepted in `_meta`/headers. + std::vector supported_versions{ + std::string{kProtocolVersion}}; + }; + + /// Streamable HTTP binding for the 2026-07-28 revision: one MCP endpoint + /// accepting POST only (GET/DELETE answer 405), protocol/method/name + /// header validation, JSON or request-scoped SSE responses, and no + /// session ids or resumability. + class StreamableHttpEndpoint + { + public: + + StreamableHttpEndpoint(RequestHandler requests, + NotificationHandler notifications, + StreamableHttpOptions options = {}); + ~StreamableHttpEndpoint(); + StreamableHttpEndpoint(const StreamableHttpEndpoint&) = delete; + StreamableHttpEndpoint& + operator=(const StreamableHttpEndpoint&) = delete; + + [[nodiscard]] HttpResponse + handle(const HttpRequest& request) const; + + private: + + struct Impl; + std::unique_ptr m_impl; + }; + + /// Newline-delimited stdio (or any reliable bidirectional byte stream) + /// transport. Reads are bounded by `McpLimits::max_line_bytes`; writes + /// honour cancellation and a bounded timeout on non-blocking fds. + class StdioTransport + { + public: + + StdioTransport(int read_fd, int write_fd, + RequestHandler requests, + NotificationHandler notifications, + McpLimits limits = {}, + std::chrono::milliseconds io_timeout = + std::chrono::seconds{30}); + ~StdioTransport(); + StdioTransport(const StdioTransport&) = delete; + StdioTransport& operator=(const StdioTransport&) = delete; + + /// Read one message. `nullopt` means clean end of stream. + [[nodiscard]] Void::Result::Result> + read_message(std::stop_token stop = {}); + + [[nodiscard]] Void::Result::Result + write_message(const Message& message, + std::stop_token stop = {}); + + /// Read-dispatch-write until EOF, cancellation, or an I/O error. + /// Malformed JSON frames are answered with a parse-error + /// response and do not terminate the loop. + [[nodiscard]] Void::Result::Result + run(std::stop_token stop = {}); + + private: + + struct Impl; + std::unique_ptr m_impl; + }; + + struct LegacySession { + std::string id{}; + std::string protocol_version{}; + bool initialized{false}; + }; + + struct LegacySessionOptions { + /// Revisions of the initialize/session era this adapter accepts, + /// newest first. + std::vector supported_versions{ + "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"}; + std::string server_name{"Void MCP"}; + std::string server_version{"1.0"}; + std::function session_id_factory{}; + }; + + /// Explicit compatibility adapter for the pre-2026-07-28 + /// initialization/session semantics: `initialize` negotiation, + /// `initialized` notification, and session ids. Kept separate from the + /// modern transport so the two behaviors cannot bleed into each other. + class LegacySessionAdapter + { + public: + + explicit LegacySessionAdapter(LegacySessionOptions options = {}); + ~LegacySessionAdapter(); + LegacySessionAdapter(const LegacySessionAdapter&) = delete; + LegacySessionAdapter& + operator=(const LegacySessionAdapter&) = delete; + + /// Handle one inbound message. `initialize` creates a session and + /// returns the negotiated response; `initialized` marks it ready and + /// returns no reply; everything else is rejected until a session is + /// initialized. + [[nodiscard]] Void::Result::Result> + handle(const Message& inbound, + std::string_view session_id = {}); + + [[nodiscard]] const LegacySession* + find(std::string_view session_id) const; + + bool terminate(std::string_view session_id); + + [[nodiscard]] std::size_t session_count() const; + + private: + + struct Impl; + std::unique_ptr m_impl; + }; + +} // namespace Void::MCP diff --git a/include/Void/MCP/Types.hpp b/include/Void/MCP/Types.hpp new file mode 100644 index 0000000..b9dea02 --- /dev/null +++ b/include/Void/MCP/Types.hpp @@ -0,0 +1,213 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::MCP +{ + /// Protocol revision this module pins its modern behavior to. + inline constexpr std::string_view kProtocolVersion{"2026-07-28"}; + inline constexpr std::string_view kJsonRpcVersion{"2.0"}; + + /// `_meta` keys defined by the MCP 2026-07-28 revision. + inline constexpr std::string_view kMetaProtocolVersion{ + "io.modelcontextprotocol/protocolVersion"}; + inline constexpr std::string_view kMetaClientInfo{ + "io.modelcontextprotocol/clientInfo"}; + inline constexpr std::string_view kMetaClientCapabilities{ + "io.modelcontextprotocol/clientCapabilities"}; + inline constexpr std::string_view kMetaServerInfo{ + "io.modelcontextprotocol/serverInfo"}; + inline constexpr std::string_view kMetaSubscriptionId{ + "io.modelcontextprotocol/subscriptionId"}; + inline constexpr std::string_view kMetaProgressToken{"progressToken"}; + + /// Streamable HTTP request metadata headers (2026-07-28). + inline constexpr std::string_view kProtocolHeader{"MCP-Protocol-Version"}; + inline constexpr std::string_view kMethodHeader{"Mcp-Method"}; + inline constexpr std::string_view kNameHeader{"Mcp-Name"}; + /// Legacy session/resumption headers; ignored by the modern transport. + inline constexpr std::string_view kSessionHeader{"Mcp-Session-Id"}; + inline constexpr std::string_view kLastEventIdHeader{"Last-Event-ID"}; + + inline constexpr std::string_view kJsonContentType{"application/json"}; + inline constexpr std::string_view kSseContentType{"text/event-stream"}; + + /// Error domain owned by the MCP module. + inline constexpr std::int32_t kMcpErrorDomain{33}; + + enum class McpErrorCode : std::int32_t { + none = 0, + parse_error = 1, + invalid_request = 2, + method_not_found = 3, + invalid_params = 4, + internal_error = 5, + header_mismatch = 6, + unsupported_protocol_version = 7, + unauthorized = 8, + forbidden = 9, + not_acceptable = 10, + unsupported_media_type = 11, + method_not_allowed = 12, + payload_too_large = 13, + cancelled = 14, + timeout = 15, + transport_closed = 16, + protocol_error = 17, + session_not_found = 18, + }; + + [[nodiscard]] inline Void::Result::Error + make_mcp_error(McpErrorCode code, std::string message) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case McpErrorCode::none: + case McpErrorCode::internal_error: + kind = ErrorKind::internal; + break; + case McpErrorCode::parse_error: + case McpErrorCode::invalid_request: + case McpErrorCode::invalid_params: + case McpErrorCode::header_mismatch: + case McpErrorCode::protocol_error: + kind = ErrorKind::corrupt; + break; + case McpErrorCode::method_not_found: + kind = ErrorKind::not_found; + break; + case McpErrorCode::unsupported_protocol_version: + case McpErrorCode::not_acceptable: + case McpErrorCode::unsupported_media_type: + case McpErrorCode::method_not_allowed: + kind = ErrorKind::unsupported; + break; + case McpErrorCode::unauthorized: + case McpErrorCode::forbidden: + kind = ErrorKind::invalid_argument; + break; + case McpErrorCode::payload_too_large: + kind = ErrorKind::exhausted; + break; + case McpErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case McpErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case McpErrorCode::transport_closed: + case McpErrorCode::session_not_found: + kind = ErrorKind::conflict; + break; + } + return Error{kind, std::move(message), + ErrorCode{kMcpErrorDomain, + static_cast(code)}}; + } + + /// JSON-RPC 2.0 error code emitted for an MCP error. + [[nodiscard]] inline std::int32_t + json_rpc_error_code(McpErrorCode code) noexcept + { + switch (code) { + case McpErrorCode::parse_error: + return -32700; + case McpErrorCode::invalid_request: + return -32600; + case McpErrorCode::method_not_found: + return -32601; + case McpErrorCode::invalid_params: + return -32602; + case McpErrorCode::header_mismatch: + return -32020; + case McpErrorCode::unsupported_protocol_version: + return -32022; + case McpErrorCode::unauthorized: + return -32001; + default: + return -32603; + } + } + + struct MetadataEntry { + std::string key{}; + std::string value{}; + + [[nodiscard]] bool operator==( + const MetadataEntry&) const noexcept = default; + }; + + struct ClientInfo { + std::string name{}; + std::string version{}; + + [[nodiscard]] bool operator==( + const ClientInfo&) const noexcept = default; + }; + + /// Per-request metadata carried inline in `_meta` (stdio) or mirrored in + /// HTTP headers (Streamable HTTP). Unknown entries are preserved as + /// bounded key/value strings. + struct RequestMetadata { + std::string protocol_version{std::string{kProtocolVersion}}; + ClientInfo client_info{}; + std::optional progress_token{}; + std::optional subscription_id{}; + /// Compact JSON object for `clientCapabilities` (empty when + /// absent). Kept as text so Types.hpp stays independent of Data. + std::string client_capabilities_json{}; + std::vector extra{}; + + [[nodiscard]] bool operator==( + const RequestMetadata&) const noexcept = default; + }; + + struct ServerInfo { + std::string name{}; + std::string version{}; + + [[nodiscard]] bool operator==( + const ServerInfo&) const noexcept = default; + }; + + /// Authenticated principal produced by the authorization callback. The + /// MCP module only defines the boundary; token validation, scopes, and + /// consent remain application concerns. + struct AuthContext { + std::string subject{}; + std::vector scopes{}; + + [[nodiscard]] bool operator==( + const AuthContext&) const noexcept = default; + }; + + struct McpLimits { + /// Maximum bytes in one encoded JSON-RPC message. + std::size_t max_message_bytes{4ULL * 1024 * 1024}; + /// Maximum bytes in one newline-delimited stdio frame. + std::size_t max_line_bytes{1ULL * 1024 * 1024}; + /// Maximum metadata entries accepted from `_meta`. + std::size_t max_metadata_entries{16}; + /// Maximum bytes in one metadata key or value. + std::size_t max_metadata_value_bytes{4096}; + /// Maximum bytes in one SSE event. + std::size_t max_sse_event_bytes{1ULL * 1024 * 1024}; + /// Maximum compiled SSE events buffered by the parser. + std::size_t max_sse_events{1024}; + /// Maximum JSON nesting depth accepted by the codec. + std::size_t max_json_depth{64}; + }; + +} // namespace Void::MCP diff --git a/src/MCP/Codec.cpp b/src/MCP/Codec.cpp new file mode 100644 index 0000000..52a8c3b --- /dev/null +++ b/src/MCP/Codec.cpp @@ -0,0 +1,208 @@ +#include + +#include +#include +#include + +namespace Void::MCP +{ + LineFramer::LineFramer(McpLimits limits) : m_limits(std::move(limits)) + { + } + + std::size_t LineFramer::buffered() const noexcept + { + return m_buffer.size(); + } + + void LineFramer::reset() noexcept + { + m_buffer.clear(); + } + + Void::Result::Result + LineFramer::append(std::string_view bytes) + { + m_buffer.append(bytes); + const std::size_t last_newline = m_buffer.rfind('\n'); + const std::size_t tail = + last_newline == std::string::npos + ? m_buffer.size() + : m_buffer.size() - last_newline - 1U; + if (tail > m_limits.max_line_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + std::format("MCP: stdio frame exceeds {} bytes", + m_limits.max_line_bytes))}; + } + return {}; + } + + Void::Result::Result> + LineFramer::next() + { + for (;;) { + const std::size_t newline = m_buffer.find('\n'); + if (newline == std::string::npos) { + return std::optional{}; + } + std::string line = m_buffer.substr(0, newline); + m_buffer.erase(0, newline + 1U); + if (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + if (line.empty()) { + continue; + } + if (line.size() > m_limits.max_line_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + std::format("MCP: stdio frame exceeds {} bytes", + m_limits.max_line_bytes))}; + } + return std::optional{std::move(line)}; + } + } + + Void::Result::Result + frame_line(std::string_view json, const McpLimits& limits) + { + if (json.size() > limits.max_line_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + std::format("MCP: stdio frame {} bytes exceeds {}", + json.size(), limits.max_line_bytes))}; + } + std::string frame{json}; + frame.push_back('\n'); + return frame; + } + + Void::Result::Result + encode_sse_event(const SseEvent& event, const McpLimits& limits) + { + std::string out; + if (!event.event.empty()) { + out += "event: "; + out += event.event; + out.push_back('\n'); + } + if (!event.id.empty()) { + out += "id: "; + out += event.id; + out.push_back('\n'); + } + std::size_t begin = 0; + for (;;) { + const std::size_t newline = event.data.find('\n', begin); + out += "data: "; + if (newline == std::string::npos) { + out.append(event.data, begin, std::string::npos); + out.push_back('\n'); + break; + } + out.append(event.data, begin, newline - begin); + out.push_back('\n'); + begin = newline + 1U; + } + out.push_back('\n'); + if (out.size() > limits.max_sse_event_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + std::format("MCP: SSE event {} bytes exceeds {}", + out.size(), limits.max_sse_event_bytes))}; + } + return out; + } + + SseParser::SseParser(McpLimits limits) : m_limits(std::move(limits)) + { + } + + std::size_t SseParser::buffered() const noexcept + { + return m_buffer.size(); + } + + void SseParser::reset() noexcept + { + m_buffer.clear(); + } + + Void::Result::Result + SseParser::append(std::string_view bytes) + { + m_buffer.append(bytes); + if (m_buffer.size() > m_limits.max_sse_event_bytes && + m_buffer.find("\n\n") == std::string::npos) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + std::format("MCP: SSE buffer exceeds {} bytes", + m_limits.max_sse_event_bytes))}; + } + return {}; + } + + Void::Result::Result> + SseParser::next() + { + for (;;) { + const std::size_t separator = m_buffer.find("\n\n"); + if (separator == std::string::npos) { + return std::optional{}; + } + const std::string block = m_buffer.substr(0, separator); + m_buffer.erase(0, separator + 2U); + + SseEvent event; + bool has_data = false; + std::size_t begin = 0; + while (begin <= block.size()) { + const std::size_t newline = block.find('\n', begin); + const std::string_view line = + newline == std::string::npos + ? std::string_view{block}.substr(begin) + : std::string_view{block}.substr( + begin, newline - begin); + begin = newline == std::string::npos ? block.size() + 1U + : newline + 1U; + if (line.empty() || line.front() == ':') { + continue; + } + const std::size_t colon = line.find(':'); + const std::string_view field = + colon == std::string_view::npos + ? line + : line.substr(0, colon); + std::string_view value = + colon == std::string_view::npos + ? std::string_view{} + : line.substr(colon + 1U); + if (!value.empty() && value.front() == ' ') { + value.remove_prefix(1U); + } + if (field == "event") { + event.event = value; + } else if (field == "id") { + event.id = value; + } else if (field == "data") { + if (has_data) { + event.data.push_back('\n'); + } + event.data += value; + has_data = true; + } + } + if (!has_data) { + continue; + } + if (event.data.size() > m_limits.max_sse_event_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + "MCP: SSE event data exceeds limit")}; + } + return std::optional{std::move(event)}; + } + } + +} // namespace Void::MCP diff --git a/src/MCP/Envelope.cpp b/src/MCP/Envelope.cpp new file mode 100644 index 0000000..99de33d --- /dev/null +++ b/src/MCP/Envelope.cpp @@ -0,0 +1,493 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::MCP +{ + namespace + { + using Object = JsonValue::Object; + using Array = JsonValue::Array; + + [[nodiscard]] const Object* as_object(const JsonValue& value) noexcept + { + return std::get_if(&value.value); + } + + [[nodiscard]] const std::string* + as_string(const JsonValue& value) noexcept + { + return std::get_if(&value.value); + } + + [[nodiscard]] const std::int64_t* + as_integer(const JsonValue& value) noexcept + { + return std::get_if(&value.value); + } + + [[nodiscard]] Void::Result::Error + invalid(std::string message) + { + return make_mcp_error(McpErrorCode::invalid_request, + std::move(message)); + } + + [[nodiscard]] Void::Result::Result + serialize_value(const JsonValue& value, const McpLimits& limits) + { + auto text = Void::Json::Strict::serialize(value, + limits.max_json_depth); + if (!text.has_value()) { + return std::unexpected{make_mcp_error( + McpErrorCode::invalid_params, + std::format("MCP: JSON serialize failed: {}", + text.error().message))}; + } + if (text->size() > limits.max_message_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + std::format("MCP: encoded message {} bytes exceeds {}", + text->size(), limits.max_message_bytes))}; + } + return std::move(*text); + } + + [[nodiscard]] JsonValue encode_id(const JsonRpcId& id) + { + return std::visit( + [](const auto& value) -> JsonValue { + using T = std::decay_t; + if constexpr (std::same_as) { + return JsonValue{nullptr}; + } else if constexpr (std::same_as) { + return JsonValue{value}; + } else { + return JsonValue{value}; + } + }, + id.value); + } + + [[nodiscard]] Void::Result::Result + decode_id(const JsonValue& value) + { + if (std::holds_alternative(value.value)) { + return JsonRpcId{}; + } + if (const auto* number = as_integer(value); number != nullptr) { + return JsonRpcId{*number}; + } + if (const auto* text = as_string(value); text != nullptr) { + return JsonRpcId{*text}; + } + return std::unexpected{invalid( + "MCP: JSON-RPC id must be null, an integer, or a string")}; + } + + [[nodiscard]] Void::Result::Result + merge_metadata(std::optional params, + const RequestMetadata& metadata, + const McpLimits& limits) + { + auto meta = metadata_to_json(metadata, limits); + if (!meta.has_value()) { + return std::unexpected{std::move(meta.error())}; + } + Object object; + if (params.has_value()) { + if (const auto* existing = as_object(*params); + existing != nullptr) { + object = *existing; + } else if (!std::holds_alternative( + params->value)) { + return std::unexpected{invalid( + "MCP: params must be an object when present")}; + } + } + object[std::string{"_meta"}] = std::move(*meta); + return JsonValue{std::move(object)}; + } + + [[nodiscard]] JsonValue encode_error(const ErrorObject& error) + { + Object object; + object["code"] = JsonValue{static_cast(error.code)}; + object["message"] = JsonValue{error.message}; + if (error.data.has_value()) { + object["data"] = *error.data; + } + return JsonValue{std::move(object)}; + } + + [[nodiscard]] Void::Result::Result + decode_error(const JsonValue& value) + { + const auto* object = as_object(value); + if (object == nullptr) { + return std::unexpected{invalid( + "MCP: JSON-RPC error must be an object")}; + } + const auto code_it = object->find("code"); + const auto message_it = object->find("message"); + if (code_it == object->end() || message_it == object->end()) { + return std::unexpected{invalid( + "MCP: JSON-RPC error requires code and message")}; + } + const auto* code = as_integer(code_it->second); + const auto* message = as_string(message_it->second); + if (code == nullptr || message == nullptr || + *code < INT32_MIN || *code > INT32_MAX) { + return std::unexpected{invalid( + "MCP: malformed JSON-RPC error code or message")}; + } + ErrorObject error; + error.code = static_cast(*code); + error.message = *message; + if (const auto data_it = object->find("data"); + data_it != object->end()) { + error.data = data_it->second; + } + return error; + } + + [[nodiscard]] Void::Result::Result + parse_meta_object(const JsonValue& meta, const McpLimits& limits) + { + const auto* object = as_object(meta); + if (object == nullptr) { + return std::unexpected{make_mcp_error( + McpErrorCode::invalid_params, + "MCP: _meta must be an object")}; + } + RequestMetadata metadata; + std::size_t entries = 0; + for (const auto& [key, value] : *object) { + ++entries; + if (entries > limits.max_metadata_entries) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + std::format("MCP: _meta exceeds {} entries", + limits.max_metadata_entries))}; + } + if (key == kMetaProtocolVersion) { + const auto* text = as_string(value); + if (text == nullptr || + text->size() > + limits.max_metadata_value_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::invalid_params, + "MCP: protocolVersion must be a bounded string")}; + } + metadata.protocol_version = *text; + } else if (key == kMetaClientInfo) { + const auto* info = as_object(value); + if (info == nullptr) { + return std::unexpected{make_mcp_error( + McpErrorCode::invalid_params, + "MCP: clientInfo must be an object")}; + } + if (const auto name = info->find("name"); + name != info->end()) { + if (const auto* text = as_string(name->second); + text != nullptr) { + metadata.client_info.name = *text; + } + } + if (const auto version = info->find("version"); + version != info->end()) { + if (const auto* text = as_string(version->second); + text != nullptr) { + metadata.client_info.version = *text; + } + } + } else if (key == kMetaClientCapabilities) { + auto text = serialize_value(value, limits); + if (!text.has_value()) { + return std::unexpected{ + std::move(text.error())}; + } + metadata.client_capabilities_json = std::move(*text); + } else if (key == kMetaProgressToken) { + if (const auto* text = as_string(value); + text != nullptr) { + metadata.progress_token = *text; + } + } else if (key == kMetaSubscriptionId) { + if (const auto* text = as_string(value); + text != nullptr) { + metadata.subscription_id = *text; + } + } else if (const auto* text = as_string(value); + text != nullptr) { + if (key.size() > limits.max_metadata_value_bytes || + text->size() > limits.max_metadata_value_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + "MCP: _meta entry exceeds size limit")}; + } + metadata.extra.push_back({key, *text}); + } + } + return metadata; + } + } // namespace + + Void::Result::Result + encode_json(const JsonValue& value, const McpLimits& limits) + { + return serialize_value(value, limits); + } + + Void::Result::Result + decode_json(std::string_view text, const McpLimits& limits) + { + if (text.size() > limits.max_message_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + std::format("MCP: message {} bytes exceeds {}", + text.size(), limits.max_message_bytes))}; + } + auto value = Void::Json::Strict::parse( + text, Void::Json::Strict::ParseOptions{ + .maximumDepth = limits.max_json_depth, + .allowDecimals = true}); + if (!value.has_value()) { + return std::unexpected{make_mcp_error( + McpErrorCode::parse_error, + std::format("MCP: invalid JSON at {}: {}", + value.error().offset, value.error().message))}; + } + return std::move(*value); + } + + Void::Result::Result + parse_metadata(const JsonValue& params, const McpLimits& limits) + { + const auto* object = as_object(params); + if (object == nullptr) { + return RequestMetadata{}; + } + const auto meta = object->find("_meta"); + if (meta == object->end()) { + return RequestMetadata{}; + } + return parse_meta_object(meta->second, limits); + } + + Void::Result::Result + metadata_to_json(const RequestMetadata& metadata, + const McpLimits& limits) + { + if (metadata.protocol_version.size() > + limits.max_metadata_value_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + "MCP: protocol version exceeds metadata limit")}; + } + Object meta; + meta[std::string{kMetaProtocolVersion}] = + JsonValue{metadata.protocol_version}; + if (!metadata.client_info.name.empty() || + !metadata.client_info.version.empty()) { + Object info; + info["name"] = JsonValue{metadata.client_info.name}; + info["version"] = JsonValue{metadata.client_info.version}; + meta[std::string{kMetaClientInfo}] = + JsonValue{std::move(info)}; + } + if (!metadata.client_capabilities_json.empty()) { + auto capabilities = + decode_json(metadata.client_capabilities_json, limits); + if (!capabilities.has_value()) { + return std::unexpected{std::move(capabilities.error())}; + } + if (as_object(*capabilities) == nullptr) { + return std::unexpected{make_mcp_error( + McpErrorCode::invalid_params, + "MCP: clientCapabilities must be a JSON object")}; + } + meta[std::string{kMetaClientCapabilities}] = + std::move(*capabilities); + } + if (metadata.progress_token.has_value()) { + meta[std::string{kMetaProgressToken}] = + JsonValue{*metadata.progress_token}; + } + if (metadata.subscription_id.has_value()) { + meta[std::string{kMetaSubscriptionId}] = + JsonValue{*metadata.subscription_id}; + } + if (metadata.extra.size() > limits.max_metadata_entries) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + "MCP: too many metadata entries")}; + } + for (const auto& entry : metadata.extra) { + if (entry.key.size() > limits.max_metadata_value_bytes || + entry.value.size() > limits.max_metadata_value_bytes) { + return std::unexpected{make_mcp_error( + McpErrorCode::payload_too_large, + "MCP: metadata entry exceeds size limit")}; + } + meta[entry.key] = JsonValue{entry.value}; + } + return JsonValue{std::move(meta)}; + } + + Void::Result::Result + encode_message(const Message& message, const McpLimits& limits) + { + Object object; + object["jsonrpc"] = JsonValue{std::string{kJsonRpcVersion}}; + if (const auto* request = std::get_if(&message); + request != nullptr) { + object["id"] = encode_id(request->id); + object["method"] = JsonValue{request->method}; + auto params = merge_metadata(request->params, + request->metadata, limits); + if (!params.has_value()) { + return std::unexpected{std::move(params.error())}; + } + object["params"] = std::move(*params); + } else if (const auto* notification = + std::get_if(&message); + notification != nullptr) { + object["method"] = JsonValue{notification->method}; + auto params = merge_metadata(notification->params, + notification->metadata, limits); + if (!params.has_value()) { + return std::unexpected{std::move(params.error())}; + } + object["params"] = std::move(*params); + } else { + const auto& response = std::get(message); + object["id"] = encode_id(response.id); + if (response.error.has_value() && + response.result.has_value()) { + return std::unexpected{invalid( + "MCP: response cannot carry both result and error")}; + } + if (response.error.has_value()) { + object["error"] = encode_error(*response.error); + } else if (response.result.has_value()) { + object["result"] = *response.result; + } else { + return std::unexpected{invalid( + "MCP: response requires result or error")}; + } + } + return serialize_value(JsonValue{std::move(object)}, limits); + } + + Void::Result::Result + decode_message(std::string_view text, const McpLimits& limits) + { + auto value = decode_json(text, limits); + if (!value.has_value()) { + return std::unexpected{std::move(value.error())}; + } + const auto* object = as_object(*value); + if (object == nullptr) { + return std::unexpected{invalid( + "MCP: JSON-RPC message must be an object")}; + } + const auto version = object->find("jsonrpc"); + if (version == object->end() || + as_string(version->second) == nullptr || + *as_string(version->second) != kJsonRpcVersion) { + return std::unexpected{invalid( + "MCP: jsonrpc must be \"2.0\"")}; + } + const auto method = object->find("method"); + const auto id = object->find("id"); + if (method != object->end()) { + if (object->contains("result") || object->contains("error")) { + return std::unexpected{invalid( + "MCP: message cannot mix method with result/error")}; + } + const auto* method_text = as_string(method->second); + if (method_text == nullptr || method_text->empty() || + method_text->size() > limits.max_metadata_value_bytes) { + return std::unexpected{invalid( + "MCP: method must be a bounded non-empty string")}; + } + std::optional params; + if (const auto params_it = object->find("params"); + params_it != object->end()) { + if (as_object(params_it->second) == nullptr) { + return std::unexpected{invalid( + "MCP: params must be an object when present")}; + } + params = params_it->second; + } + RequestMetadata metadata; + if (params.has_value()) { + auto parsed = parse_metadata(*params, limits); + if (!parsed.has_value()) { + return std::unexpected{std::move(parsed.error())}; + } + metadata = std::move(*parsed); + } + if (id != object->end()) { + auto decoded_id = decode_id(id->second); + if (!decoded_id.has_value()) { + return std::unexpected{ + std::move(decoded_id.error())}; + } + return Request{std::move(*decoded_id), + std::move(*method_text), + std::move(params), std::move(metadata)}; + } + return Notification{std::move(*method_text), + std::move(params), std::move(metadata)}; + } + + if (id == object->end()) { + return std::unexpected{invalid( + "MCP: response requires an id")}; + } + auto decoded_id = decode_id(id->second); + if (!decoded_id.has_value()) { + return std::unexpected{std::move(decoded_id.error())}; + } + const auto result = object->find("result"); + const auto error = object->find("error"); + if (result != object->end() && error != object->end()) { + return std::unexpected{invalid( + "MCP: response cannot carry both result and error")}; + } + if (result != object->end()) { + return Response{std::move(*decoded_id), result->second, + std::nullopt}; + } + if (error != object->end()) { + auto decoded_error = decode_error(error->second); + if (!decoded_error.has_value()) { + return std::unexpected{ + std::move(decoded_error.error())}; + } + return Response{std::move(*decoded_id), std::nullopt, + std::move(*decoded_error)}; + } + return std::unexpected{invalid( + "MCP: response requires result or error")}; + } + + Response make_error_response(const JsonRpcId& id, std::int32_t code, + std::string message, + std::optional data) + { + Response response; + response.id = id; + response.error = + ErrorObject{code, std::move(message), std::move(data)}; + return response; + } + +} // namespace Void::MCP diff --git a/src/MCP/Legacy.cpp b/src/MCP/Legacy.cpp new file mode 100644 index 0000000..27d681b --- /dev/null +++ b/src/MCP/Legacy.cpp @@ -0,0 +1,170 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::MCP +{ + namespace + { + [[nodiscard]] std::string default_session_id() + { + static std::atomic counter{1}; + return std::format("mcp-session-{}", + counter.fetch_add(1, + std::memory_order_relaxed)); + } + + [[nodiscard]] const JsonValue::Object* + as_object(const JsonValue& value) noexcept + { + return std::get_if(&value.value); + } + + [[nodiscard]] std::string + param_string(const Request& request, std::string_view key) + { + if (!request.params.has_value()) { + return {}; + } + const auto* object = as_object(*request.params); + if (object == nullptr) { + return {}; + } + const auto field = object->find(key); + if (field == object->end()) { + return {}; + } + if (const auto* text = std::get_if(&field->second.value); + text != nullptr) { + return *text; + } + return {}; + } + + [[nodiscard]] bool contains(const std::vector& values, + std::string_view wanted) noexcept + { + return std::ranges::any_of(values, [&](const std::string& value) { + return value == wanted; + }); + } + } // namespace + + struct LegacySessionAdapter::Impl { + LegacySessionOptions options; + std::map> sessions; + + Impl() = default; + }; + + LegacySessionAdapter::LegacySessionAdapter(LegacySessionOptions options) + : m_impl(std::make_unique()) + { + m_impl->options = std::move(options); + if (m_impl->options.supported_versions.empty()) { + m_impl->options.supported_versions.push_back("2025-11-25"); + } + if (!m_impl->options.session_id_factory) { + m_impl->options.session_id_factory = default_session_id; + } + } + + LegacySessionAdapter::~LegacySessionAdapter() = default; + + Void::Result::Result> + LegacySessionAdapter::handle(const Message& inbound, + std::string_view session_id) + { + auto& impl = *m_impl; + if (const auto* request = std::get_if(&inbound); + request != nullptr) { + if (request->method == "initialize") { + if (!session_id.empty() && + impl.sessions.contains(session_id)) { + return std::unexpected{make_mcp_error( + McpErrorCode::invalid_request, + "MCP: session is already initialized")}; + } + const std::string requested = + param_string(*request, "protocolVersion"); + const std::string negotiated = + contains(impl.options.supported_versions, requested) + ? requested + : impl.options.supported_versions.front(); + LegacySession session; + session.id = impl.options.session_id_factory(); + session.protocol_version = negotiated; + impl.sessions.emplace(session.id, session); + + JsonValue::Object capabilities; + JsonValue::Object server_info; + server_info["name"] = + JsonValue{impl.options.server_name}; + server_info["version"] = + JsonValue{impl.options.server_version}; + JsonValue::Object result; + result["protocolVersion"] = JsonValue{negotiated}; + result["capabilities"] = + JsonValue{std::move(capabilities)}; + result["serverInfo"] = JsonValue{std::move(server_info)}; + return std::optional{Response{ + request->id, JsonValue{std::move(result)}, + std::nullopt}}; + } + + const auto session = impl.sessions.find(session_id); + if (session == impl.sessions.end() || + !session->second.initialized) { + return std::unexpected{make_mcp_error( + McpErrorCode::session_not_found, + "MCP: no initialized legacy session")}; + } + return std::optional{inbound}; + } + + if (const auto* notification = std::get_if(&inbound); + notification != nullptr) { + if (notification->method == "initialized") { + const auto session = impl.sessions.find(session_id); + if (session == impl.sessions.end()) { + return std::unexpected{make_mcp_error( + McpErrorCode::session_not_found, + "MCP: initialized without a legacy session")}; + } + session->second.initialized = true; + } + return std::optional{}; + } + return std::optional{}; + } + + const LegacySession* + LegacySessionAdapter::find(std::string_view session_id) const + { + const auto session = + m_impl->sessions.find(std::string{session_id}); + if (session == m_impl->sessions.end()) { + return nullptr; + } + return &session->second; + } + + bool LegacySessionAdapter::terminate(std::string_view session_id) + { + return m_impl->sessions.erase(std::string{session_id}) > 0; + } + + std::size_t LegacySessionAdapter::session_count() const + { + return m_impl->sessions.size(); + } + +} // namespace Void::MCP diff --git a/src/MCP/Transport.cpp b/src/MCP/Transport.cpp new file mode 100644 index 0000000..7441140 --- /dev/null +++ b/src/MCP/Transport.cpp @@ -0,0 +1,729 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#else +#include +#include +#include +#endif + +namespace Void::MCP +{ + namespace + { + [[nodiscard]] bool ascii_iequals(std::string_view left, + std::string_view right) noexcept + { + if (left.size() != right.size()) { + return false; + } + for (std::size_t index = 0; index < left.size(); ++index) { + const auto a = static_cast(left[index]); + const auto b = static_cast(right[index]); + if (std::tolower(a) != std::tolower(b)) { + return false; + } + } + return true; + } + + [[nodiscard]] std::string_view trim(std::string_view text) noexcept + { + constexpr std::string_view whitespace = " \t"; + const auto begin = text.find_first_not_of(whitespace); + if (begin == std::string_view::npos) { + return {}; + } + const auto end = text.find_last_not_of(whitespace); + return text.substr(begin, end - begin + 1U); + } + + /// Whether a comma-separated header list contains `token` (media + /// type parameters are ignored). + [[nodiscard]] bool + contains_token(std::string_view list, std::string_view token) + { + std::size_t begin = 0; + while (begin <= list.size()) { + const std::size_t comma = list.find(',', begin); + std::string_view item = + comma == std::string_view::npos + ? list.substr(begin) + : list.substr(begin, comma - begin); + const std::size_t semicolon = item.find(';'); + if (semicolon != std::string_view::npos) { + item = item.substr(0, semicolon); + } + if (ascii_iequals(trim(item), token)) { + return true; + } + if (comma == std::string_view::npos) { + break; + } + begin = comma + 1U; + } + return false; + } + + [[nodiscard]] const JsonValue::Object* + as_object(const JsonValue& value) noexcept + { + return std::get_if(&value.value); + } + + [[nodiscard]] const std::string* + as_string(const JsonValue& value) noexcept + { + return std::get_if(&value.value); + } + + [[nodiscard]] HttpResponse json_response(int status, + const Message& message, + const McpLimits& limits) + { + HttpResponse response; + response.status = status; + response.headers.push_back( + {"Content-Type", std::string{kJsonContentType}}); + auto encoded = encode_message(message, limits); + if (encoded.has_value()) { + response.body = std::move(*encoded); + } else { + response.status = 500; + response.body = "{\"jsonrpc\":\"2.0\",\"id\":null," + "\"error\":{\"code\":-32603,\"message\":" + "\"failed to encode error response\"}}"; + } + return response; + } + + [[nodiscard]] HttpResponse + error_response(int status, const JsonRpcId& id, + McpErrorCode code, std::string message, + const McpLimits& limits, + std::optional data = {}) + { + return json_response( + status, + make_error_response(id, json_rpc_error_code(code), + std::move(message), std::move(data)), + limits); + } + + [[nodiscard]] std::optional + request_name(const Request& request) + { + if (!request.params.has_value()) { + return std::nullopt; + } + const auto* object = as_object(*request.params); + if (object == nullptr) { + return std::nullopt; + } + const auto field = + request.method == "resources/read" + ? object->find("uri") + : object->find("name"); + if (field == object->end()) { + return std::nullopt; + } + if (const auto* text = as_string(field->second); + text != nullptr) { + return *text; + } + return std::nullopt; + } + + [[nodiscard]] bool method_requires_name(std::string_view method) noexcept + { + return method == "tools/call" || method == "resources/read" || + method == "prompts/get"; + } + + [[nodiscard]] RequestMetadata message_metadata(const Message& message) + { + if (const auto* request = std::get_if(&message); + request != nullptr) { + return request->metadata; + } + if (const auto* notification = std::get_if(&message); + notification != nullptr) { + return notification->metadata; + } + return {}; + } + + [[nodiscard]] JsonRpcId message_id(const Message& message) + { + if (const auto* request = std::get_if(&message); + request != nullptr) { + return request->id; + } + return {}; + } + + [[nodiscard]] JsonRpcId + parse_id_from_body(std::string_view body) noexcept + { + // Best-effort id extraction for transport-level errors; the full + // message is parsed by the caller when it is valid. + const auto position = body.find("\"id\""); + if (position == std::string_view::npos) { + return {}; + } + std::size_t index = position + 4U; + while (index < body.size() && + (body[index] == ' ' || body[index] == '\t' || + body[index] == ':')) { + ++index; + } + if (index >= body.size()) { + return {}; + } + if (body[index] == '"') { + const auto end = body.find('"', index + 1U); + if (end == std::string_view::npos) { + return {}; + } + return JsonRpcId{ + std::string{body.substr(index + 1U, end - index - 1U)}}; + } + std::int64_t number = 0; + const char* begin = body.data() + index; + const auto parsed = std::from_chars(begin, body.data() + body.size(), + number); + if (parsed.ec != std::errc{}) { + return {}; + } + return JsonRpcId{number}; + } + +#if !defined(_WIN32) + [[nodiscard]] std::chrono::milliseconds + remaining(std::chrono::steady_clock::time_point deadline) noexcept + { + const auto left = deadline - std::chrono::steady_clock::now(); + if (left <= std::chrono::steady_clock::duration::zero()) { + return std::chrono::milliseconds{0}; + } + return std::chrono::duration_cast( + left); + } + + [[nodiscard]] Void::Result::Result + wait_fd(int fd, short events, + std::chrono::milliseconds timeout, std::stop_token stop, + std::string_view operation) + { + const auto deadline = + std::chrono::steady_clock::now() + timeout; + for (;;) { + if (stop.stop_requested()) { + return std::unexpected{make_mcp_error( + McpErrorCode::cancelled, + std::format("MCP: stdio {} cancelled", + operation))}; + } + auto wait = remaining(deadline); + if (timeout.count() > 0 && wait.count() == 0) { + return std::unexpected{make_mcp_error( + McpErrorCode::timeout, + std::format("MCP: stdio {} timed out", + operation))}; + } + if (stop.stop_possible() && + (wait.count() == 0 || wait.count() > 50)) { + wait = std::chrono::milliseconds{50}; + } + pollfd descriptor{ + .fd = fd, .events = events, .revents = 0}; + const int rc = ::poll(&descriptor, 1, + timeout.count() > 0 + ? static_cast(wait.count()) + : -1); + if (rc < 0) { + if (errno == EINTR) { + continue; + } + return std::unexpected{make_mcp_error( + McpErrorCode::protocol_error, + std::format("MCP: stdio poll failed: {}", + std::strerror(errno)))}; + } + if (rc > 0) { + return {}; + } + } + } +#endif + + [[nodiscard]] Void::Result::Result + fd_read(int fd, std::span destination) + { +#if defined(_WIN32) + const int rc = ::_read(fd, destination.data(), + static_cast( + std::min( + destination.size(), INT_MAX))); +#else + const ssize_t rc = ::read(fd, destination.data(), + destination.size()); +#endif + if (rc < 0) { + return std::unexpected{make_mcp_error( + McpErrorCode::protocol_error, + std::format("MCP: stdio read failed: {}", + std::strerror(errno)))}; + } + return static_cast(rc); + } + + [[nodiscard]] Void::Result::Result + write_all_fd(int fd, std::string_view data, + std::chrono::milliseconds timeout, + std::stop_token stop) + { + bool nonblocking = false; +#if !defined(_WIN32) + const int flags = ::fcntl(fd, F_GETFL, 0); + nonblocking = flags >= 0 && (flags & O_NONBLOCK) != 0; +#endif + while (!data.empty()) { + if (stop.stop_requested()) { + return std::unexpected{make_mcp_error( + McpErrorCode::cancelled, + "MCP: stdio write cancelled")}; + } +#if !defined(_WIN32) + if (nonblocking) { + auto waited = + wait_fd(fd, POLLOUT, timeout, stop, "write"); + if (!waited.has_value()) { + return std::unexpected{ + std::move(waited.error())}; + } + } +#endif + const std::size_t chunk = + std::min(data.size(), 4096U); +#if defined(_WIN32) + const int rc = ::_write( + fd, data.data(), static_cast(chunk)); +#else + const ssize_t rc = ::write(fd, data.data(), chunk); +#endif + if (rc < 0) { + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + continue; + } + return std::unexpected{make_mcp_error( + McpErrorCode::transport_closed, + std::format("MCP: stdio write failed: {}", + std::strerror(errno)))}; + } + data.remove_prefix(static_cast(rc)); + } + return {}; + } + } // namespace + + std::optional + header_value(const HttpRequest& request, std::string_view name) + { + for (const auto& header : request.headers) { + if (ascii_iequals(header.name, name)) { + return header.value; + } + } + return std::nullopt; + } + + struct StreamableHttpEndpoint::Impl { + RequestHandler requests; + NotificationHandler notifications; + StreamableHttpOptions options; + + Impl(RequestHandler request_handler, + NotificationHandler notification_handler, + StreamableHttpOptions opts) + : requests(std::move(request_handler)), + notifications(std::move(notification_handler)), + options(std::move(opts)) + { + } + }; + + StreamableHttpEndpoint::StreamableHttpEndpoint( + RequestHandler requests, NotificationHandler notifications, + StreamableHttpOptions options) + : m_impl(std::make_unique(std::move(requests), + std::move(notifications), + std::move(options))) + { + } + + StreamableHttpEndpoint::~StreamableHttpEndpoint() = default; + + HttpResponse StreamableHttpEndpoint::handle( + const HttpRequest& request) const + { + const auto& options = m_impl->options; + const auto& limits = options.limits; + + if (request.method != "POST") { + return error_response( + 405, JsonRpcId{}, McpErrorCode::method_not_allowed, + "MCP: 2026-07-28 Streamable HTTP accepts POST only", limits); + } + const auto content_type = header_value(request, "Content-Type"); + if (!content_type.has_value() || + !contains_token(*content_type, kJsonContentType)) { + return error_response( + 415, JsonRpcId{}, McpErrorCode::unsupported_media_type, + "MCP: Content-Type must be application/json", limits); + } + const auto accept = header_value(request, "Accept"); + if (!accept.has_value() || + !contains_token(*accept, kJsonContentType) || + !contains_token(*accept, kSseContentType)) { + return error_response( + 406, JsonRpcId{}, McpErrorCode::not_acceptable, + "MCP: Accept must list application/json and " + "text/event-stream", + limits); + } + if (options.authorize) { + auto authorized = options.authorize(request); + if (!authorized.has_value()) { + return error_response( + 401, JsonRpcId{}, McpErrorCode::unauthorized, + "MCP: authorization failed", limits); + } + } else if (options.require_authorization) { + return error_response( + 401, JsonRpcId{}, McpErrorCode::unauthorized, + "MCP: authorization is required", limits); + } + if (request.body.size() > limits.max_message_bytes) { + return error_response( + 413, JsonRpcId{}, McpErrorCode::payload_too_large, + "MCP: request body exceeds message limit", limits); + } + auto message = decode_message(request.body, limits); + if (!message.has_value()) { + return error_response( + 400, parse_id_from_body(request.body), + McpErrorCode::parse_error, message.error().message(), + limits); + } + if (std::holds_alternative(*message)) { + return error_response( + 400, message_id(*message), McpErrorCode::invalid_request, + "MCP: clients must not POST JSON-RPC responses", limits); + } + + const RequestMetadata metadata = message_metadata(*message); + const auto protocol_header = + header_value(request, kProtocolHeader); + if (!protocol_header.has_value() || + *protocol_header != metadata.protocol_version) { + return error_response( + 400, message_id(*message), McpErrorCode::header_mismatch, + "MCP: MCP-Protocol-Version header missing or does not " + "match _meta", + limits); + } + const bool version_supported = std::ranges::any_of( + options.supported_versions, + [&](const std::string& version) { + return version == metadata.protocol_version; + }); + if (!version_supported) { + JsonValue::Object data; + JsonValue::Array supported; + for (const auto& version : options.supported_versions) { + supported.push_back(JsonValue{version}); + } + data["supported"] = JsonValue{std::move(supported)}; + data["requested"] = JsonValue{metadata.protocol_version}; + return error_response( + 400, message_id(*message), + McpErrorCode::unsupported_protocol_version, + "MCP: unsupported protocol version", limits, + JsonValue{std::move(data)}); + } + + const std::string method = + std::holds_alternative(*message) + ? std::get(*message).method + : std::get(*message).method; + const auto method_header = header_value(request, kMethodHeader); + if (!method_header.has_value() || *method_header != method) { + return error_response( + 400, message_id(*message), McpErrorCode::header_mismatch, + "MCP: Mcp-Method header missing or does not match the " + "body method", + limits); + } + if (method_requires_name(method)) { + const auto& request_message = std::get(*message); + const auto name = request_name(request_message); + const auto name_header = header_value(request, kNameHeader); + if (!name.has_value() || !name_header.has_value() || + *name_header != *name) { + return error_response( + 400, message_id(*message), + McpErrorCode::header_mismatch, + "MCP: Mcp-Name header missing or does not match the " + "body", + limits); + } + } + + if (const auto* notification = std::get_if(&*message)) { + auto accepted = + m_impl->notifications + ? m_impl->notifications(*notification) + : Void::Result::Result{}; + if (!accepted.has_value()) { + return error_response( + 400, JsonRpcId{}, McpErrorCode::invalid_request, + accepted.error().message(), limits); + } + HttpResponse response; + response.status = 202; + return response; + } + + const auto& request_message = std::get(*message); + auto handled = + m_impl->requests + ? m_impl->requests(request_message) + : Void::Result::Result{std::unexpected{ + make_mcp_error(McpErrorCode::method_not_found, + "MCP: no request handler")}}; + if (!handled.has_value()) { + const auto& error = handled.error(); + const auto code = + error.code().domain == kMcpErrorDomain + ? static_cast(error.code().value) + : McpErrorCode::internal_error; + return json_response( + 200, + make_error_response(request_message.id, + json_rpc_error_code(code), + error.message()), + limits); + } + + auto encoded = encode_message(*handled, limits); + if (!encoded.has_value()) { + return error_response( + 500, request_message.id, McpErrorCode::internal_error, + encoded.error().message(), limits); + } + HttpResponse response; + response.status = 200; + if (options.prefer_sse) { + response.headers.push_back( + {"Content-Type", std::string{kSseContentType}}); + auto event = encode_sse_event( + SseEvent{.event = "message", .data = std::move(*encoded)}, + limits); + if (!event.has_value()) { + return error_response( + 500, request_message.id, + McpErrorCode::payload_too_large, + event.error().message(), limits); + } + response.body = std::move(*event); + } else { + response.headers.push_back( + {"Content-Type", std::string{kJsonContentType}}); + response.body = std::move(*encoded); + } + return response; + } + + struct StdioTransport::Impl { + int read_fd{-1}; + int write_fd{-1}; + RequestHandler requests; + NotificationHandler notifications; + McpLimits limits; + std::chrono::milliseconds io_timeout; + LineFramer framer; + + Impl(int reader, int writer, RequestHandler request_handler, + NotificationHandler notification_handler, McpLimits + transport_limits, + std::chrono::milliseconds timeout) + : read_fd(reader), write_fd(writer), + requests(std::move(request_handler)), + notifications(std::move(notification_handler)), + limits(std::move(transport_limits)), io_timeout(timeout), + framer(limits) + { + } + }; + + StdioTransport::StdioTransport(int read_fd, int write_fd, + RequestHandler requests, + NotificationHandler notifications, + McpLimits limits, + std::chrono::milliseconds io_timeout) + : m_impl(std::make_unique( + read_fd, write_fd, std::move(requests), + std::move(notifications), std::move(limits), io_timeout)) + { + } + + StdioTransport::~StdioTransport() = default; + + Void::Result::Result> + StdioTransport::read_message(std::stop_token stop) + { + auto& impl = *m_impl; + for (;;) { + if (stop.stop_requested()) { + return std::unexpected{make_mcp_error( + McpErrorCode::cancelled, "MCP: stdio read cancelled")}; + } + auto line = impl.framer.next(); + if (!line.has_value()) { + return std::unexpected{std::move(line.error())}; + } + if (line->has_value()) { + auto message = + decode_message(**line, impl.limits); + if (!message.has_value()) { + return std::unexpected{ + std::move(message.error())}; + } + return std::optional{std::move(*message)}; + } + std::array buffer{}; + auto count = fd_read(impl.read_fd, buffer); + if (!count.has_value()) { +#if !defined(_WIN32) + if (errno == EAGAIN || errno == EWOULDBLOCK) { + auto waited = wait_fd(impl.read_fd, POLLIN, + impl.io_timeout, stop, "read"); + if (!waited.has_value()) { + return std::unexpected{ + std::move(waited.error())}; + } + continue; + } +#endif + return std::unexpected{std::move(count.error())}; + } + if (*count == 0) { + if (impl.framer.buffered() > 0) { + return std::unexpected{make_mcp_error( + McpErrorCode::protocol_error, + "MCP: stdio stream ended mid-frame")}; + } + return std::optional{}; + } + auto appended = impl.framer.append(std::string_view{ + reinterpret_cast(buffer.data()), *count}); + if (!appended.has_value()) { + return std::unexpected{std::move(appended.error())}; + } + } + } + + Void::Result::Result + StdioTransport::write_message(const Message& message, + std::stop_token stop) + { + auto& impl = *m_impl; + auto encoded = encode_message(message, impl.limits); + if (!encoded.has_value()) { + return std::unexpected{std::move(encoded.error())}; + } + auto frame = frame_line(*encoded, impl.limits); + if (!frame.has_value()) { + return std::unexpected{std::move(frame.error())}; + } + return write_all_fd(impl.write_fd, *frame, impl.io_timeout, stop); + } + + Void::Result::Result StdioTransport::run(std::stop_token stop) + { + for (;;) { + auto message = read_message(stop); + if (!message.has_value()) { + if (message.error().kind() == + Void::Result::ErrorKind::cancelled) { + return {}; + } + // Malformed frame: answer and keep reading. + auto error_response = make_error_response( + JsonRpcId{}, json_rpc_error_code( + McpErrorCode::parse_error), + message.error().message()); + auto written = write_message(error_response, stop); + if (!written.has_value()) { + return std::unexpected{ + std::move(written.error())}; + } + continue; + } + if (!message->has_value()) { + return {}; + } + Message inbound = std::move(**message); + if (const auto* request = std::get_if(&inbound)) { + auto handled = + m_impl->requests + ? m_impl->requests(*request) + : Void::Result::Result{ + std::unexpected{make_mcp_error( + McpErrorCode::method_not_found, + "MCP: no request handler")}}; + if (!handled.has_value()) { + handled = make_error_response( + request->id, + json_rpc_error_code(McpErrorCode::internal_error), + handled.error().message()); + } + auto written = write_message(*handled, stop); + if (!written.has_value()) { + return std::unexpected{ + std::move(written.error())}; + } + } else if (const auto* notification = + std::get_if(&inbound)) { + if (m_impl->notifications) { + auto accepted = + m_impl->notifications(*notification); + if (!accepted.has_value()) { + return std::unexpected{ + std::move(accepted.error())}; + } + } + } + } + } + +} // namespace Void::MCP diff --git a/src/MCP/module.cmake b/src/MCP/module.cmake new file mode 100644 index 0000000..74f5151 --- /dev/null +++ b/src/MCP/module.cmake @@ -0,0 +1,3 @@ +void_add_module(MCP + INTERNAL_DEPS Functional Data +) diff --git a/tests/standalone/MCP/Envelope.cpp b/tests/standalone/MCP/Envelope.cpp new file mode 100644 index 0000000..9c02559 --- /dev/null +++ b/tests/standalone/MCP/Envelope.cpp @@ -0,0 +1,171 @@ +#include +#include +#include + +#include +#include +#include +#include + +namespace +{ + using Void::MCP::JsonValue; + + [[nodiscard]] const JsonValue::Object* as_object(const JsonValue& value) + { + return std::get_if(&value.value); + } + + [[nodiscard]] const std::string* as_string(const JsonValue& value) + { + return std::get_if(&value.value); + } + + [[nodiscard]] std::string json_text(const JsonValue& value) + { + auto text = Void::MCP::encode_json(value); + Void::Testing::require(text.has_value()); + return *text; + } + + [[nodiscard]] JsonValue object_of(std::string_view json) + { + auto value = Void::MCP::decode_json(json); + Void::Testing::require(value.has_value()); + return *value; + } +} // namespace + +Void::Testing::Test mcp_request_round_trip_and_metadata() +{ + Void::MCP::Request request; + request.id = Void::MCP::JsonRpcId{std::int64_t{7}}; + request.method = "tools/list"; + request.params = object_of(R"({"cursor":"abc"})"); + request.metadata.protocol_version = std::string{ + Void::MCP::kProtocolVersion}; + request.metadata.client_info = {"ExampleClient", "1.2.3"}; + request.metadata.progress_token = "progress-1"; + request.metadata.subscription_id = "sub-9"; + request.metadata.client_capabilities_json = R"({"roots":{}})"; + request.metadata.extra.push_back({"traceparent", "00-abc-def-01"}); + + const Void::MCP::Message message = request; + auto encoded = Void::MCP::encode_message(message); + Void::Testing::require(encoded.has_value()); + Void::Testing::expect(encoded->find("\"jsonrpc\":\"2.0\"") != + std::string::npos); + Void::Testing::expect(encoded->find("\"_meta\"") != std::string::npos); + + auto decoded = Void::MCP::decode_message(*encoded); + Void::Testing::require(decoded.has_value()); + const auto* round_trip = std::get_if(&*decoded); + Void::Testing::require(round_trip != nullptr); + Void::Testing::expect(round_trip->id == request.id); + Void::Testing::expect_eq(round_trip->method, std::string{"tools/list"}); + Void::Testing::expect(round_trip->metadata == request.metadata); + + Void::Testing::require(round_trip->params.has_value()); + const auto* params = as_object(*round_trip->params); + Void::Testing::require(params != nullptr); + Void::Testing::expect(params->contains("cursor")); + Void::Testing::expect(params->contains("_meta")); + const auto* meta = as_object(params->at("_meta")); + Void::Testing::require(meta != nullptr); + Void::Testing::expect(as_string(meta->at( + std::string{Void::MCP::kMetaProgressToken})) != nullptr); + Void::Testing::expect(json_text(meta->at(std::string{ + Void::MCP::kMetaClientCapabilities})) == + std::string{R"({"roots":{}})"}); +} + +Void::Testing::Test mcp_notification_and_response_round_trip() +{ + Void::MCP::Notification notification; + notification.method = "notifications/initialized"; + auto encoded = Void::MCP::encode_message(notification); + Void::Testing::require(encoded.has_value()); + Void::Testing::expect(encoded->find("\"id\"") == std::string::npos); + auto decoded = Void::MCP::decode_message(*encoded); + Void::Testing::require(decoded.has_value()); + Void::Testing::expect( + std::holds_alternative(*decoded)); + + Void::MCP::Response success; + success.id = Void::MCP::JsonRpcId{std::string{"req-1"}}; + success.result = object_of(R"({"tools":[]})"); + encoded = Void::MCP::encode_message(success); + Void::Testing::require(encoded.has_value()); + decoded = Void::MCP::decode_message(*encoded); + Void::Testing::require(decoded.has_value()); + const auto* round_trip = std::get_if(&*decoded); + Void::Testing::require(round_trip != nullptr); + Void::Testing::expect(round_trip->id == success.id); + Void::Testing::require(round_trip->result.has_value()); + Void::Testing::expect(!round_trip->error.has_value()); + + Void::MCP::Response failure; + failure.id = Void::MCP::JsonRpcId{std::int64_t{3}}; + failure.error = Void::MCP::ErrorObject{ + -32602, "invalid params", object_of(R"({"field":"name"})")}; + encoded = Void::MCP::encode_message(failure); + Void::Testing::require(encoded.has_value()); + decoded = Void::MCP::decode_message(*encoded); + Void::Testing::require(decoded.has_value()); + round_trip = std::get_if(&*decoded); + Void::Testing::require(round_trip != nullptr); + Void::Testing::require(round_trip->error.has_value()); + Void::Testing::expect_eq(round_trip->error->code, std::int32_t{-32602}); + Void::Testing::expect_eq(round_trip->error->message, + std::string{"invalid params"}); +} + +Void::Testing::Test mcp_rejects_malformed_envelopes() +{ + const std::string_view malformed[] = { + "not json", + R"({"jsonrpc":"1.0","id":1,"method":"x"})", + R"({"id":1,"method":"x"})", + R"({"jsonrpc":"2.0","id":true,"method":"x"})", + R"({"jsonrpc":"2.0","id":1,"method":""})", + R"({"jsonrpc":"2.0","id":1,"method":"x","result":{}})", + R"({"jsonrpc":"2.0","id":1,"result":{},"error":{"code":1,"message":"e"}})", + R"({"jsonrpc":"2.0","id":1})", + R"({"jsonrpc":"2.0","id":1,"error":{"message":"e"}})", + R"([{"jsonrpc":"2.0","id":1,"method":"x"}])", + R"({"jsonrpc":"2.0","id":1,"method":"x","params":[1]})", + R"({"jsonrpc":"2.0","id":1,"method":"x","params":{"_meta":[]}})", + R"({"jsonrpc":"2.0","id":1,"method":"x","method":"y"})", + }; + for (const auto text : malformed) { + auto decoded = Void::MCP::decode_message(text); + Void::Testing::expect(!decoded.has_value()); + } +} + +Void::Testing::Test mcp_enforces_bounds_and_defaults() +{ + Void::MCP::McpLimits limits; + limits.max_message_bytes = 32; + auto decoded = Void::MCP::decode_message( + R"({"jsonrpc":"2.0","id":1,"method":"x"})", limits); + Void::Testing::expect(!decoded.has_value()); + + limits = {}; + limits.max_metadata_entries = 2; + decoded = Void::MCP::decode_message( + R"({"jsonrpc":"2.0","id":1,"method":"x","params":{"_meta":)" + R"({"io.modelcontextprotocol/protocolVersion":"2026-07-28",)" + R"("progressToken":"p","extra":"e"}}})", + limits); + Void::Testing::expect(!decoded.has_value()); + + decoded = Void::MCP::decode_message( + R"({"jsonrpc":"2.0","id":1,"method":"x"})"); + Void::Testing::require(decoded.has_value()); + const auto* request = std::get_if(&*decoded); + Void::Testing::require(request != nullptr); + Void::Testing::expect_eq(request->metadata.protocol_version, + std::string{Void::MCP::kProtocolVersion}); + Void::Testing::expect(request->metadata.client_info.name.empty()); +} diff --git a/tests/standalone/MCP/Transport.cpp b/tests/standalone/MCP/Transport.cpp new file mode 100644 index 0000000..1b9bbaa --- /dev/null +++ b/tests/standalone/MCP/Transport.cpp @@ -0,0 +1,482 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#if !defined(_WIN32) +#include +#include +#endif + +namespace +{ + using namespace std::chrono_literals; + using Void::MCP::HttpRequest; + using Void::MCP::HttpResponse; + using Void::MCP::JsonRpcId; + using Void::MCP::JsonValue; + using Void::MCP::Message; + using Void::MCP::Request; + using Void::MCP::RequestMetadata; + using Void::MCP::Response; + + [[nodiscard]] JsonValue object_of(std::string_view json) + { + auto value = Void::MCP::decode_json(json); + Void::Testing::require(value.has_value()); + return *value; + } + + [[nodiscard]] std::string encode_request( + std::string_view method, + std::string version = std::string{Void::MCP::kProtocolVersion}, + std::optional params = std::nullopt) + { + Request request; + request.id = JsonRpcId{std::int64_t{1}}; + request.method = method; + request.params = std::move(params); + request.metadata.protocol_version = std::move(version); + auto encoded = Void::MCP::encode_message(Message{request}); + Void::Testing::require(encoded.has_value()); + return *encoded; + } + + [[nodiscard]] HttpRequest post_request(std::string body, + std::string_view method, + std::string version = + std::string{Void::MCP:: + kProtocolVersion}) + { + HttpRequest request; + request.method = "POST"; + request.target = "/mcp"; + request.body = std::move(body); + request.headers = { + {"Content-Type", "application/json"}, + {"Accept", "application/json, text/event-stream"}, + {"MCP-Protocol-Version", std::move(version)}, + {"Mcp-Method", std::string{method}}, + }; + return request; + } + + [[nodiscard]] std::optional + error_code(const HttpResponse& response) + { + auto value = Void::MCP::decode_json(response.body); + if (!value.has_value()) { + return std::nullopt; + } + const auto* object = std::get_if(&value->value); + if (object == nullptr) { + return std::nullopt; + } + const auto error = object->find("error"); + if (error == object->end()) { + return std::nullopt; + } + const auto* error_object = + std::get_if(&error->second.value); + if (error_object == nullptr) { + return std::nullopt; + } + const auto code = error_object->find("code"); + if (code == error_object->end()) { + return std::nullopt; + } + if (const auto* number = + std::get_if(&code->second.value); + number != nullptr) { + return *number; + } + return std::nullopt; + } + + [[nodiscard]] Void::Result::Result + echo_handler(const Request& request) + { + JsonValue::Object result; + result["method"] = JsonValue{request.method}; + return Response{request.id, JsonValue{std::move(result)}, + std::nullopt}; + } +} // namespace + +Void::Testing::Test mcp_http_post_validation_and_header_mismatch() +{ + Void::MCP::StreamableHttpOptions options; + Void::MCP::StreamableHttpEndpoint endpoint{echo_handler, {}, options}; + + const std::string body = encode_request("tools/list"); + auto request = post_request(body, "tools/list"); + auto response = endpoint.handle(request); + Void::Testing::expect_eq(response.status, 200); + auto decoded = Void::MCP::decode_message(response.body); + Void::Testing::require(decoded.has_value()); + Void::Testing::expect(std::holds_alternative(*decoded)); + + // GET/DELETE are not part of the 2026-07-28 shape. + request.method = "GET"; + Void::Testing::expect_eq(endpoint.handle(request).status, 405); + request.method = "DELETE"; + Void::Testing::expect_eq(endpoint.handle(request).status, 405); + + // Content negotiation. + request = post_request(body, "tools/list"); + request.headers[0].value = "text/plain"; + Void::Testing::expect_eq(endpoint.handle(request).status, 415); + request = post_request(body, "tools/list"); + request.headers[1].value = "application/json"; + Void::Testing::expect_eq(endpoint.handle(request).status, 406); + + // Missing / mismatched protocol header. + request = post_request(body, "tools/list"); + request.headers.erase(request.headers.begin() + 2); + response = endpoint.handle(request); + Void::Testing::expect_eq(response.status, 400); + Void::Testing::expect_eq(error_code(response), std::int64_t{-32020}); + + request = post_request(body, "tools/list", "2025-06-18"); + response = endpoint.handle(request); + Void::Testing::expect_eq(response.status, 400); + Void::Testing::expect_eq(error_code(response), std::int64_t{-32020}); + + // Missing method header. + request = post_request(body, "tools/list"); + request.headers.erase(request.headers.begin() + 3); + response = endpoint.handle(request); + Void::Testing::expect_eq(response.status, 400); + Void::Testing::expect_eq(error_code(response), std::int64_t{-32020}); + + // Unsupported protocol version: -32022 with supported/requested data. + request = post_request(encode_request("tools/list", "1900-01-01"), + "tools/list", "1900-01-01"); + response = endpoint.handle(request); + Void::Testing::expect_eq(response.status, 400); + Void::Testing::expect_eq(error_code(response), std::int64_t{-32022}); + auto value = Void::MCP::decode_json(response.body); + Void::Testing::require(value.has_value()); + const auto* object = std::get_if(&value->value); + Void::Testing::require(object != nullptr); + const auto* error_object = std::get_if( + &object->at("error").value); + Void::Testing::require(error_object != nullptr); + const auto* data = + std::get_if(&error_object->at("data").value); + Void::Testing::require(data != nullptr); + Void::Testing::expect(data->contains("supported")); + Void::Testing::expect( + std::get(data->at("requested").value) == "1900-01-01"); +} + +Void::Testing::Test mcp_http_authorization_boundary() +{ + Void::MCP::StreamableHttpOptions options; + options.require_authorization = true; + Void::MCP::StreamableHttpEndpoint required{echo_handler, {}, options}; + auto request = post_request(encode_request("tools/list"), "tools/list"); + Void::Testing::expect_eq(required.handle(request).status, 401); + + options.authorize = [](const HttpRequest& http) { + if (Void::MCP::header_value(http, "Authorization") == + std::optional{"Bearer good"}) { + return Void::Result::Result{ + Void::MCP::AuthContext{"user-1", {"tools:read"}}}; + } + return Void::Result::Result{ + std::unexpected{Void::MCP::make_mcp_error( + Void::MCP::McpErrorCode::unauthorized, + "MCP: missing token")}}; + }; + Void::MCP::StreamableHttpEndpoint guarded{echo_handler, {}, options}; + Void::Testing::expect_eq(guarded.handle(request).status, 401); + request.headers.push_back({"Authorization", "Bearer good"}); + Void::Testing::expect_eq(guarded.handle(request).status, 200); +} + +Void::Testing::Test mcp_http_notification_sse_and_name_header() +{ + bool notified = false; + Void::MCP::StreamableHttpOptions options; + Void::MCP::StreamableHttpEndpoint endpoint{ + echo_handler, + [¬ified](const Void::MCP::Notification&) { + notified = true; + return Void::Result::Result{}; + }, + options}; + + Void::MCP::Notification notification; + notification.method = "notifications/initialized"; + auto encoded = Void::MCP::encode_message(Message{notification}); + Void::Testing::require(encoded.has_value()); + auto response = endpoint.handle( + post_request(*encoded, "notifications/initialized")); + Void::Testing::expect_eq(response.status, 202); + Void::Testing::expect(response.body.empty()); + Void::Testing::expect(notified); + + // Mcp-Name is required for tools/call. + const std::string call_body = encode_request( + "tools/call", std::string{Void::MCP::kProtocolVersion}, + object_of(R"({"name":"echo"})")); + auto call_request = post_request(call_body, "tools/call"); + response = endpoint.handle(call_request); + Void::Testing::expect_eq(response.status, 400); + Void::Testing::expect_eq(error_code(response), std::int64_t{-32020}); + call_request.headers.push_back({"Mcp-Name", "echo"}); + Void::Testing::expect_eq(endpoint.handle(call_request).status, 200); + + // SSE response mode. + options.prefer_sse = true; + Void::MCP::StreamableHttpEndpoint sse_endpoint{ + echo_handler, {}, options}; + response = sse_endpoint.handle( + post_request(encode_request("tools/list"), "tools/list")); + Void::Testing::expect_eq(response.status, 200); + HttpRequest header_probe; + header_probe.headers = response.headers; + auto content_type = + Void::MCP::header_value(header_probe, "Content-Type"); + Void::Testing::require(content_type.has_value()); + Void::Testing::expect_eq(*content_type, + std::string_view{"text/event-stream"}); + Void::MCP::SseParser parser; + Void::Testing::require(parser.append(response.body).has_value()); + auto event = parser.next(); + Void::Testing::require(event.has_value()); + Void::Testing::require(event->has_value()); + Void::Testing::expect_eq((*event)->event, std::string{"message"}); + auto message = Void::MCP::decode_message((*event)->data); + Void::Testing::require(message.has_value()); + Void::Testing::expect(std::holds_alternative(*message)); +} + +Void::Testing::Test mcp_line_framer_bounds_and_crlf() +{ + Void::MCP::McpLimits limits; + limits.max_line_bytes = 16; + Void::MCP::LineFramer framer{limits}; + Void::Testing::require(framer.append("{\"a\":1}\r\n").has_value()); + Void::Testing::require(framer.append("\n{\"b\":2}").has_value()); + auto first = framer.next(); + Void::Testing::require(first.has_value()); + Void::Testing::require(first->has_value()); + Void::Testing::expect_eq(**first, std::string{"{\"a\":1}"}); + auto second = framer.next(); + Void::Testing::require(second.has_value()); + Void::Testing::expect(!second->has_value()); + Void::Testing::expect(!framer.append(std::string(17, 'x')).has_value()); + + Void::MCP::SseParser parser; + Void::Testing::require( + parser.append(": comment\nevent: message\nid: 4\n" + "data: first\ndata: second\n\n") + .has_value()); + auto event = parser.next(); + Void::Testing::require(event.has_value()); + Void::Testing::require(event->has_value()); + Void::Testing::expect_eq((*event)->event, std::string{"message"}); + Void::Testing::expect_eq((*event)->id, std::string{"4"}); + Void::Testing::expect_eq((*event)->data, + std::string{"first\nsecond"}); +} + +#if !defined(_WIN32) +Void::Testing::Test mcp_stdio_framing_dispatch_and_parse_error() +{ + int input[2]{}; + int output[2]{}; + Void::Testing::require(::pipe(input) == 0); + Void::Testing::require(::pipe(output) == 0); + + const std::string frames = + encode_request("tools/list") + "\n" + "not json\n"; + Void::Testing::require(::write(input[1], frames.data(), frames.size()) == + static_cast(frames.size())); + ::close(input[1]); + + bool notified = false; + Void::MCP::StdioTransport transport{ + input[0], output[1], echo_handler, + [¬ified](const Void::MCP::Notification&) { + notified = true; + return Void::Result::Result{}; + }, + {}, 2s}; + auto run = transport.run(); + Void::Testing::require(run.has_value()); + ::close(output[1]); + + std::string received; + char buffer[4096]; + ssize_t count = 0; + while ((count = ::read(output[0], buffer, sizeof(buffer))) > 0) { + received.append(buffer, static_cast(count)); + } + ::close(output[0]); + + Void::MCP::LineFramer framer; + Void::Testing::require(framer.append(received).has_value()); + auto first = framer.next(); + Void::Testing::require(first.has_value()); + Void::Testing::require(first->has_value()); + auto response = Void::MCP::decode_message(**first); + Void::Testing::require(response.has_value()); + Void::Testing::expect(std::holds_alternative(*response)); + auto second = framer.next(); + Void::Testing::require(second.has_value()); + Void::Testing::require(second->has_value()); + auto parse_error = Void::MCP::decode_message(**second); + Void::Testing::require(parse_error.has_value()); + const auto* error_response = std::get_if(&*parse_error); + Void::Testing::require(error_response != nullptr); + Void::Testing::require(error_response->error.has_value()); + Void::Testing::expect_eq(error_response->error->code, + std::int32_t{-32700}); +} + +Void::Testing::Test mcp_stdio_cancellation_and_slow_reader() +{ + // Cancellation while waiting on an empty, non-blocking input pipe. + { + int input[2]{}; + int output[2]{}; + Void::Testing::require(::pipe(input) == 0); + Void::Testing::require(::pipe(output) == 0); + const int flags = ::fcntl(input[0], F_GETFL, 0); + Void::Testing::require(flags >= 0); + Void::Testing::require( + ::fcntl(input[0], F_SETFL, flags | O_NONBLOCK) == 0); + + Void::MCP::StdioTransport transport{ + input[0], output[1], echo_handler, {}, {}, 2s}; + std::stop_source stop; + std::jthread killer([&stop] { + std::this_thread::sleep_for(50ms); + stop.request_stop(); + }); + const auto start = std::chrono::steady_clock::now(); + auto message = transport.read_message(stop.get_token()); + const auto elapsed = std::chrono::steady_clock::now() - start; + killer.join(); + Void::Testing::require(!message.has_value()); + Void::Testing::expect( + message.error().code().value == + static_cast( + Void::MCP::McpErrorCode::cancelled)); + Void::Testing::expect(elapsed < 1s); + ::close(input[0]); + ::close(input[1]); + ::close(output[0]); + ::close(output[1]); + } + + // Slow reader: a full non-blocking pipe makes the write time out. + { + int input[2]{}; + int output[2]{}; + Void::Testing::require(::pipe(input) == 0); + Void::Testing::require(::pipe(output) == 0); + const int flags = ::fcntl(output[1], F_GETFL, 0); + Void::Testing::require(flags >= 0); + Void::Testing::require( + ::fcntl(output[1], F_SETFL, flags | O_NONBLOCK) == 0); + + Void::MCP::StdioTransport transport{ + input[0], output[1], echo_handler, {}, {}, 150ms}; + Void::MCP::Response large; + large.id = JsonRpcId{std::int64_t{9}}; + large.result = JsonValue{std::string(256U * 1024U, 'x')}; + auto written = transport.write_message(Message{large}); + Void::Testing::require(!written.has_value()); + Void::Testing::expect( + written.error().code().value == + static_cast(Void::MCP::McpErrorCode::timeout)); + ::close(input[0]); + ::close(input[1]); + ::close(output[0]); + ::close(output[1]); + } +} +#endif + +Void::Testing::Test mcp_legacy_session_fixtures() +{ + Void::MCP::LegacySessionOptions options; + options.session_id_factory = [] { return std::string{"sess-1"}; }; + Void::MCP::LegacySessionAdapter adapter{options}; + + Request initialize; + initialize.id = JsonRpcId{std::int64_t{1}}; + initialize.method = "initialize"; + initialize.params = + object_of(R"({"protocolVersion":"2025-06-18",)" + R"("clientInfo":{"name":"legacy","version":"0.1"}})"); + auto reply = adapter.handle(Message{initialize}); + Void::Testing::require(reply.has_value()); + Void::Testing::require(reply->has_value()); + const auto* response = std::get_if(&**reply); + Void::Testing::require(response != nullptr); + Void::Testing::require(response->result.has_value()); + const auto* result = + std::get_if(&response->result->value); + Void::Testing::require(result != nullptr); + Void::Testing::expect( + std::get(result->at("protocolVersion").value) == + "2025-06-18"); + Void::Testing::require(adapter.find("sess-1") != nullptr); + Void::Testing::expect(!adapter.find("sess-1")->initialized); + Void::Testing::expect_eq(adapter.session_count(), std::size_t{1}); + + Void::MCP::Notification initialized; + initialized.method = "initialized"; + auto ready = adapter.handle(Message{initialized}, "sess-1"); + Void::Testing::require(ready.has_value()); + Void::Testing::expect(!ready->has_value()); + Void::Testing::expect(adapter.find("sess-1")->initialized); + + Request tools; + tools.id = JsonRpcId{std::int64_t{2}}; + tools.method = "tools/list"; + auto forwarded = adapter.handle(Message{tools}, "sess-1"); + Void::Testing::require(forwarded.has_value()); + Void::Testing::require(forwarded->has_value()); + Void::Testing::expect( + std::get_if(&**forwarded) != nullptr); + + // Unknown session is rejected. + Void::Testing::expect(!adapter.handle(Message{tools}, "missing").has_value()); + + // Unknown requested version negotiates the newest supported revision. + Request legacy_initialize; + legacy_initialize.id = JsonRpcId{std::int64_t{3}}; + legacy_initialize.method = "initialize"; + legacy_initialize.params = + object_of(R"({"protocolVersion":"1900-01-01"})"); + auto negotiated = adapter.handle(Message{legacy_initialize}); + Void::Testing::require(negotiated.has_value()); + Void::Testing::require(negotiated->has_value()); + const auto* negotiated_response = + std::get_if(&**negotiated); + Void::Testing::require(negotiated_response != nullptr); + const auto* negotiated_result = + std::get_if(&negotiated_response->result->value); + Void::Testing::require(negotiated_result != nullptr); + Void::Testing::expect( + std::get(negotiated_result->at("protocolVersion").value) == + "2025-11-25"); + + Void::Testing::expect(adapter.terminate("sess-1")); + Void::Testing::expect_eq(adapter.session_count(), std::size_t{0}); +}