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

+208
View File
@@ -0,0 +1,208 @@
#include <Void/MCP/Codec.hpp>
#include <format>
#include <string>
#include <utility>
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<void>
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<std::optional<std::string>>
LineFramer::next()
{
for (;;) {
const std::size_t newline = m_buffer.find('\n');
if (newline == std::string::npos) {
return std::optional<std::string>{};
}
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::string>{std::move(line)};
}
}
Void::Result::Result<std::string>
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<std::string>
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<void>
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<std::optional<SseEvent>>
SseParser::next()
{
for (;;) {
const std::size_t separator = m_buffer.find("\n\n");
if (separator == std::string::npos) {
return std::optional<SseEvent>{};
}
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<SseEvent>{std::move(event)};
}
}
} // namespace Void::MCP
+493
View File
@@ -0,0 +1,493 @@
#include <Void/MCP/Envelope.hpp>
#include <algorithm>
#include <cstdint>
#include <format>
#include <string>
#include <utility>
#include <variant>
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<Object>(&value.value);
}
[[nodiscard]] const std::string*
as_string(const JsonValue& value) noexcept
{
return std::get_if<std::string>(&value.value);
}
[[nodiscard]] const std::int64_t*
as_integer(const JsonValue& value) noexcept
{
return std::get_if<std::int64_t>(&value.value);
}
[[nodiscard]] Void::Result::Error
invalid(std::string message)
{
return make_mcp_error(McpErrorCode::invalid_request,
std::move(message));
}
[[nodiscard]] Void::Result::Result<std::string>
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<decltype(value)>;
if constexpr (std::same_as<T, std::monostate>) {
return JsonValue{nullptr};
} else if constexpr (std::same_as<T, std::int64_t>) {
return JsonValue{value};
} else {
return JsonValue{value};
}
},
id.value);
}
[[nodiscard]] Void::Result::Result<JsonRpcId>
decode_id(const JsonValue& value)
{
if (std::holds_alternative<std::nullptr_t>(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<JsonValue>
merge_metadata(std::optional<JsonValue> 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<std::nullptr_t>(
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<std::int64_t>(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<ErrorObject>
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<std::int32_t>(*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<RequestMetadata>
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<std::string>
encode_json(const JsonValue& value, const McpLimits& limits)
{
return serialize_value(value, limits);
}
Void::Result::Result<JsonValue>
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<RequestMetadata>
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<JsonValue>
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<std::string>
encode_message(const Message& message, const McpLimits& limits)
{
Object object;
object["jsonrpc"] = JsonValue{std::string{kJsonRpcVersion}};
if (const auto* request = std::get_if<Request>(&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<Notification>(&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<Response>(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<Message>
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<JsonValue> 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<JsonValue> data)
{
Response response;
response.id = id;
response.error =
ErrorObject{code, std::move(message), std::move(data)};
return response;
}
} // namespace Void::MCP
+170
View File
@@ -0,0 +1,170 @@
#include <Void/MCP/Transport.hpp>
#include <Void/MCP/Envelope.hpp>
#include <algorithm>
#include <atomic>
#include <format>
#include <map>
#include <string>
#include <utility>
#include <variant>
namespace Void::MCP
{
namespace
{
[[nodiscard]] std::string default_session_id()
{
static std::atomic<std::uint64_t> 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<JsonValue::Object>(&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<std::string>(&field->second.value);
text != nullptr) {
return *text;
}
return {};
}
[[nodiscard]] bool contains(const std::vector<std::string>& 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<std::string, LegacySession, std::less<>> sessions;
Impl() = default;
};
LegacySessionAdapter::LegacySessionAdapter(LegacySessionOptions options)
: m_impl(std::make_unique<Impl>())
{
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<std::optional<Message>>
LegacySessionAdapter::handle(const Message& inbound,
std::string_view session_id)
{
auto& impl = *m_impl;
if (const auto* request = std::get_if<Request>(&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<Message>{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<Message>{inbound};
}
if (const auto* notification = std::get_if<Notification>(&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<Message>{};
}
return std::optional<Message>{};
}
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
+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
+3
View File
@@ -0,0 +1,3 @@
void_add_module(MCP
INTERNAL_DEPS Functional Data
)