MCP: add reusable protocol and transport foundations (closes #45)
This commit is contained in:
1 parent
72148da7b2
commit
32569bbfef
11 files changed
+2819
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user