MCP: add reusable protocol and transport foundations (closes #45)

This commit is contained in:
faumaray committed 2026-12-03 16:55:20 +03:00
1 parent 72148da7b2
commit 32569bbfef
11 files changed
+2819

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/MCP/Types.hpp>
#include <cstddef>
#include <optional>
#include <string>
#include <string_view>
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<void>
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<std::optional<std::string>>
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<std::string>
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<void>
append(std::string_view bytes);
[[nodiscard]] Void::Result::Result<std::optional<SseEvent>>
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<std::string>
frame_line(std::string_view json, const McpLimits& limits = {});
} // namespace Void::MCP
+88
View File
@@ -0,0 +1,88 @@
#pragma once
#include <Void/Data/StrictJson.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/MCP/Types.hpp>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <variant>
namespace Void::MCP
{
using JsonValue = Void::Json::Strict::Value;
/// JSON-RPC request id: null, an integer, or a string.
struct JsonRpcId {
std::variant<std::monostate, std::int64_t, std::string> value{};
[[nodiscard]] bool is_null() const noexcept
{
return std::holds_alternative<std::monostate>(value);
}
[[nodiscard]] bool
operator==(const JsonRpcId&) const noexcept = default;
};
struct ErrorObject {
std::int32_t code{0};
std::string message{};
std::optional<JsonValue> data{};
};
struct Request {
JsonRpcId id{};
std::string method{};
std::optional<JsonValue> params{};
RequestMetadata metadata{};
};
struct Notification {
std::string method{};
std::optional<JsonValue> params{};
RequestMetadata metadata{};
};
struct Response {
JsonRpcId id{};
std::optional<JsonValue> result{};
std::optional<ErrorObject> error{};
};
using Message = std::variant<Request, Notification, Response>;
/// 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<std::string>
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<Message>
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<RequestMetadata>
parse_metadata(const JsonValue& params, const McpLimits& limits = {});
/// Build the `_meta` object for a request metadata value.
[[nodiscard]] Void::Result::Result<JsonValue>
metadata_to_json(const RequestMetadata& metadata,
const McpLimits& limits = {});
[[nodiscard]] Void::Result::Result<std::string>
encode_json(const JsonValue& value, const McpLimits& limits = {});
[[nodiscard]] Void::Result::Result<JsonValue>
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<JsonValue> data = {});
} // namespace Void::MCP
+180
View File
@@ -0,0 +1,180 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/MCP/Codec.hpp>
#include <Void/MCP/Envelope.hpp>
#include <Void/MCP/Types.hpp>
#include <chrono>
#include <cstddef>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <vector>
namespace Void::MCP
{
struct HttpHeader {
std::string name{};
std::string value{};
};
struct HttpRequest {
std::string method{};
std::string target{};
std::vector<HttpHeader> headers{};
std::string body{};
};
struct HttpResponse {
int status{200};
std::vector<HttpHeader> headers{};
std::string body{};
};
/// Case-insensitive header lookup. Returns the first match.
[[nodiscard]] std::optional<std::string_view>
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<Void::Result::Result<AuthContext>(const HttpRequest&)>;
using RequestHandler =
std::function<Void::Result::Result<Message>(const Request&)>;
using NotificationHandler =
std::function<Void::Result::Result<void>(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<std::string> 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<Impl> 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<std::optional<Message>>
read_message(std::stop_token stop = {});
[[nodiscard]] Void::Result::Result<void>
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<void>
run(std::stop_token stop = {});
private:
struct Impl;
std::unique_ptr<Impl> 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<std::string> 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<std::string()> 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<std::optional<Message>>
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<Impl> m_impl;
};
} // namespace Void::MCP
+213
View File
@@ -0,0 +1,213 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
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<std::int32_t>(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<std::string> progress_token{};
std::optional<std::string> 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<MetadataEntry> 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<std::string> 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