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

+729
View File
@@ -0,0 +1,729 @@
#include <Void/MCP/Transport.hpp>
#include <Void/MCP/Codec.hpp>
#include <Void/MCP/Envelope.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <cstring>
#include <format>
#include <limits>
#include <string>
#include <utility>
#include <variant>
#if defined(_WIN32)
#include <io.h>
#else
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#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<unsigned char>(left[index]);
const auto b = static_cast<unsigned char>(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<JsonValue::Object>(&value.value);
}
[[nodiscard]] const std::string*
as_string(const JsonValue& value) noexcept
{
return std::get_if<std::string>(&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<JsonValue> data = {})
{
return json_response(
status,
make_error_response(id, json_rpc_error_code(code),
std::move(message), std::move(data)),
limits);
}
[[nodiscard]] std::optional<std::string>
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<Request>(&message);
request != nullptr) {
return request->metadata;
}
if (const auto* notification = std::get_if<Notification>(&message);
notification != nullptr) {
return notification->metadata;
}
return {};
}
[[nodiscard]] JsonRpcId message_id(const Message& message)
{
if (const auto* request = std::get_if<Request>(&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<std::chrono::milliseconds>(
left);
}
[[nodiscard]] Void::Result::Result<void>
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<int>(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<std::size_t>
fd_read(int fd, std::span<std::byte> destination)
{
#if defined(_WIN32)
const int rc = ::_read(fd, destination.data(),
static_cast<unsigned int>(
std::min<std::size_t>(
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<std::size_t>(rc);
}
[[nodiscard]] Void::Result::Result<void>
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<std::size_t>(data.size(), 4096U);
#if defined(_WIN32)
const int rc = ::_write(
fd, data.data(), static_cast<unsigned int>(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<std::size_t>(rc));
}
return {};
}
} // namespace
std::optional<std::string_view>
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<Impl>(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<Response>(*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<Request>(*message)
? std::get<Request>(*message).method
: std::get<Notification>(*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<Request>(*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<Notification>(&*message)) {
auto accepted =
m_impl->notifications
? m_impl->notifications(*notification)
: Void::Result::Result<void>{};
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<Request>(*message);
auto handled =
m_impl->requests
? m_impl->requests(request_message)
: Void::Result::Result<Message>{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<McpErrorCode>(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<Impl>(
read_fd, write_fd, std::move(requests),
std::move(notifications), std::move(limits), io_timeout))
{
}
StdioTransport::~StdioTransport() = default;
Void::Result::Result<std::optional<Message>>
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<Message>{std::move(*message)};
}
std::array<std::byte, 8192> 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<Message>{};
}
auto appended = impl.framer.append(std::string_view{
reinterpret_cast<const char*>(buffer.data()), *count});
if (!appended.has_value()) {
return std::unexpected{std::move(appended.error())};
}
}
}
Void::Result::Result<void>
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<void> 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<Request>(&inbound)) {
auto handled =
m_impl->requests
? m_impl->requests(*request)
: Void::Result::Result<Message>{
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<Notification>(&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