Files
Library/tests/standalone/MCP/Transport.cpp
T

483 lines
17 KiB
C++

#include <Void/MCP/Codec.hpp>
#include <Void/MCP/Envelope.hpp>
#include <Void/MCP/Transport.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <variant>
#if !defined(_WIN32)
#include <fcntl.h>
#include <unistd.h>
#endif
namespace
{
using namespace std::chrono_literals;
using Void::MCP::HttpRequest;
using Void::MCP::HttpResponse;
using Void::MCP::JsonRpcId;
using Void::MCP::JsonValue;
using Void::MCP::Message;
using Void::MCP::Request;
using Void::MCP::RequestMetadata;
using Void::MCP::Response;
[[nodiscard]] JsonValue object_of(std::string_view json)
{
auto value = Void::MCP::decode_json(json);
Void::Testing::require(value.has_value());
return *value;
}
[[nodiscard]] std::string encode_request(
std::string_view method,
std::string version = std::string{Void::MCP::kProtocolVersion},
std::optional<JsonValue> params = std::nullopt)
{
Request request;
request.id = JsonRpcId{std::int64_t{1}};
request.method = method;
request.params = std::move(params);
request.metadata.protocol_version = std::move(version);
auto encoded = Void::MCP::encode_message(Message{request});
Void::Testing::require(encoded.has_value());
return *encoded;
}
[[nodiscard]] HttpRequest post_request(std::string body,
std::string_view method,
std::string version =
std::string{Void::MCP::
kProtocolVersion})
{
HttpRequest request;
request.method = "POST";
request.target = "/mcp";
request.body = std::move(body);
request.headers = {
{"Content-Type", "application/json"},
{"Accept", "application/json, text/event-stream"},
{"MCP-Protocol-Version", std::move(version)},
{"Mcp-Method", std::string{method}},
};
return request;
}
[[nodiscard]] std::optional<std::int64_t>
error_code(const HttpResponse& response)
{
auto value = Void::MCP::decode_json(response.body);
if (!value.has_value()) {
return std::nullopt;
}
const auto* object = std::get_if<JsonValue::Object>(&value->value);
if (object == nullptr) {
return std::nullopt;
}
const auto error = object->find("error");
if (error == object->end()) {
return std::nullopt;
}
const auto* error_object =
std::get_if<JsonValue::Object>(&error->second.value);
if (error_object == nullptr) {
return std::nullopt;
}
const auto code = error_object->find("code");
if (code == error_object->end()) {
return std::nullopt;
}
if (const auto* number =
std::get_if<std::int64_t>(&code->second.value);
number != nullptr) {
return *number;
}
return std::nullopt;
}
[[nodiscard]] Void::Result::Result<Message>
echo_handler(const Request& request)
{
JsonValue::Object result;
result["method"] = JsonValue{request.method};
return Response{request.id, JsonValue{std::move(result)},
std::nullopt};
}
} // namespace
Void::Testing::Test mcp_http_post_validation_and_header_mismatch()
{
Void::MCP::StreamableHttpOptions options;
Void::MCP::StreamableHttpEndpoint endpoint{echo_handler, {}, options};
const std::string body = encode_request("tools/list");
auto request = post_request(body, "tools/list");
auto response = endpoint.handle(request);
Void::Testing::expect_eq(response.status, 200);
auto decoded = Void::MCP::decode_message(response.body);
Void::Testing::require(decoded.has_value());
Void::Testing::expect(std::holds_alternative<Response>(*decoded));
// GET/DELETE are not part of the 2026-07-28 shape.
request.method = "GET";
Void::Testing::expect_eq(endpoint.handle(request).status, 405);
request.method = "DELETE";
Void::Testing::expect_eq(endpoint.handle(request).status, 405);
// Content negotiation.
request = post_request(body, "tools/list");
request.headers[0].value = "text/plain";
Void::Testing::expect_eq(endpoint.handle(request).status, 415);
request = post_request(body, "tools/list");
request.headers[1].value = "application/json";
Void::Testing::expect_eq(endpoint.handle(request).status, 406);
// Missing / mismatched protocol header.
request = post_request(body, "tools/list");
request.headers.erase(request.headers.begin() + 2);
response = endpoint.handle(request);
Void::Testing::expect_eq(response.status, 400);
Void::Testing::expect_eq(error_code(response), std::int64_t{-32020});
request = post_request(body, "tools/list", "2025-06-18");
response = endpoint.handle(request);
Void::Testing::expect_eq(response.status, 400);
Void::Testing::expect_eq(error_code(response), std::int64_t{-32020});
// Missing method header.
request = post_request(body, "tools/list");
request.headers.erase(request.headers.begin() + 3);
response = endpoint.handle(request);
Void::Testing::expect_eq(response.status, 400);
Void::Testing::expect_eq(error_code(response), std::int64_t{-32020});
// Unsupported protocol version: -32022 with supported/requested data.
request = post_request(encode_request("tools/list", "1900-01-01"),
"tools/list", "1900-01-01");
response = endpoint.handle(request);
Void::Testing::expect_eq(response.status, 400);
Void::Testing::expect_eq(error_code(response), std::int64_t{-32022});
auto value = Void::MCP::decode_json(response.body);
Void::Testing::require(value.has_value());
const auto* object = std::get_if<JsonValue::Object>(&value->value);
Void::Testing::require(object != nullptr);
const auto* error_object = std::get_if<JsonValue::Object>(
&object->at("error").value);
Void::Testing::require(error_object != nullptr);
const auto* data =
std::get_if<JsonValue::Object>(&error_object->at("data").value);
Void::Testing::require(data != nullptr);
Void::Testing::expect(data->contains("supported"));
Void::Testing::expect(
std::get<std::string>(data->at("requested").value) == "1900-01-01");
}
Void::Testing::Test mcp_http_authorization_boundary()
{
Void::MCP::StreamableHttpOptions options;
options.require_authorization = true;
Void::MCP::StreamableHttpEndpoint required{echo_handler, {}, options};
auto request = post_request(encode_request("tools/list"), "tools/list");
Void::Testing::expect_eq(required.handle(request).status, 401);
options.authorize = [](const HttpRequest& http) {
if (Void::MCP::header_value(http, "Authorization") ==
std::optional<std::string_view>{"Bearer good"}) {
return Void::Result::Result<Void::MCP::AuthContext>{
Void::MCP::AuthContext{"user-1", {"tools:read"}}};
}
return Void::Result::Result<Void::MCP::AuthContext>{
std::unexpected{Void::MCP::make_mcp_error(
Void::MCP::McpErrorCode::unauthorized,
"MCP: missing token")}};
};
Void::MCP::StreamableHttpEndpoint guarded{echo_handler, {}, options};
Void::Testing::expect_eq(guarded.handle(request).status, 401);
request.headers.push_back({"Authorization", "Bearer good"});
Void::Testing::expect_eq(guarded.handle(request).status, 200);
}
Void::Testing::Test mcp_http_notification_sse_and_name_header()
{
bool notified = false;
Void::MCP::StreamableHttpOptions options;
Void::MCP::StreamableHttpEndpoint endpoint{
echo_handler,
[&notified](const Void::MCP::Notification&) {
notified = true;
return Void::Result::Result<void>{};
},
options};
Void::MCP::Notification notification;
notification.method = "notifications/initialized";
auto encoded = Void::MCP::encode_message(Message{notification});
Void::Testing::require(encoded.has_value());
auto response = endpoint.handle(
post_request(*encoded, "notifications/initialized"));
Void::Testing::expect_eq(response.status, 202);
Void::Testing::expect(response.body.empty());
Void::Testing::expect(notified);
// Mcp-Name is required for tools/call.
const std::string call_body = encode_request(
"tools/call", std::string{Void::MCP::kProtocolVersion},
object_of(R"({"name":"echo"})"));
auto call_request = post_request(call_body, "tools/call");
response = endpoint.handle(call_request);
Void::Testing::expect_eq(response.status, 400);
Void::Testing::expect_eq(error_code(response), std::int64_t{-32020});
call_request.headers.push_back({"Mcp-Name", "echo"});
Void::Testing::expect_eq(endpoint.handle(call_request).status, 200);
// SSE response mode.
options.prefer_sse = true;
Void::MCP::StreamableHttpEndpoint sse_endpoint{
echo_handler, {}, options};
response = sse_endpoint.handle(
post_request(encode_request("tools/list"), "tools/list"));
Void::Testing::expect_eq(response.status, 200);
HttpRequest header_probe;
header_probe.headers = response.headers;
auto content_type =
Void::MCP::header_value(header_probe, "Content-Type");
Void::Testing::require(content_type.has_value());
Void::Testing::expect_eq(*content_type,
std::string_view{"text/event-stream"});
Void::MCP::SseParser parser;
Void::Testing::require(parser.append(response.body).has_value());
auto event = parser.next();
Void::Testing::require(event.has_value());
Void::Testing::require(event->has_value());
Void::Testing::expect_eq((*event)->event, std::string{"message"});
auto message = Void::MCP::decode_message((*event)->data);
Void::Testing::require(message.has_value());
Void::Testing::expect(std::holds_alternative<Response>(*message));
}
Void::Testing::Test mcp_line_framer_bounds_and_crlf()
{
Void::MCP::McpLimits limits;
limits.max_line_bytes = 16;
Void::MCP::LineFramer framer{limits};
Void::Testing::require(framer.append("{\"a\":1}\r\n").has_value());
Void::Testing::require(framer.append("\n{\"b\":2}").has_value());
auto first = framer.next();
Void::Testing::require(first.has_value());
Void::Testing::require(first->has_value());
Void::Testing::expect_eq(**first, std::string{"{\"a\":1}"});
auto second = framer.next();
Void::Testing::require(second.has_value());
Void::Testing::expect(!second->has_value());
Void::Testing::expect(!framer.append(std::string(17, 'x')).has_value());
Void::MCP::SseParser parser;
Void::Testing::require(
parser.append(": comment\nevent: message\nid: 4\n"
"data: first\ndata: second\n\n")
.has_value());
auto event = parser.next();
Void::Testing::require(event.has_value());
Void::Testing::require(event->has_value());
Void::Testing::expect_eq((*event)->event, std::string{"message"});
Void::Testing::expect_eq((*event)->id, std::string{"4"});
Void::Testing::expect_eq((*event)->data,
std::string{"first\nsecond"});
}
#if !defined(_WIN32)
Void::Testing::Test mcp_stdio_framing_dispatch_and_parse_error()
{
int input[2]{};
int output[2]{};
Void::Testing::require(::pipe(input) == 0);
Void::Testing::require(::pipe(output) == 0);
const std::string frames =
encode_request("tools/list") + "\n" + "not json\n";
Void::Testing::require(::write(input[1], frames.data(), frames.size()) ==
static_cast<ssize_t>(frames.size()));
::close(input[1]);
bool notified = false;
Void::MCP::StdioTransport transport{
input[0], output[1], echo_handler,
[&notified](const Void::MCP::Notification&) {
notified = true;
return Void::Result::Result<void>{};
},
{}, 2s};
auto run = transport.run();
Void::Testing::require(run.has_value());
::close(output[1]);
std::string received;
char buffer[4096];
ssize_t count = 0;
while ((count = ::read(output[0], buffer, sizeof(buffer))) > 0) {
received.append(buffer, static_cast<std::size_t>(count));
}
::close(output[0]);
Void::MCP::LineFramer framer;
Void::Testing::require(framer.append(received).has_value());
auto first = framer.next();
Void::Testing::require(first.has_value());
Void::Testing::require(first->has_value());
auto response = Void::MCP::decode_message(**first);
Void::Testing::require(response.has_value());
Void::Testing::expect(std::holds_alternative<Response>(*response));
auto second = framer.next();
Void::Testing::require(second.has_value());
Void::Testing::require(second->has_value());
auto parse_error = Void::MCP::decode_message(**second);
Void::Testing::require(parse_error.has_value());
const auto* error_response = std::get_if<Response>(&*parse_error);
Void::Testing::require(error_response != nullptr);
Void::Testing::require(error_response->error.has_value());
Void::Testing::expect_eq(error_response->error->code,
std::int32_t{-32700});
}
Void::Testing::Test mcp_stdio_cancellation_and_slow_reader()
{
// Cancellation while waiting on an empty, non-blocking input pipe.
{
int input[2]{};
int output[2]{};
Void::Testing::require(::pipe(input) == 0);
Void::Testing::require(::pipe(output) == 0);
const int flags = ::fcntl(input[0], F_GETFL, 0);
Void::Testing::require(flags >= 0);
Void::Testing::require(
::fcntl(input[0], F_SETFL, flags | O_NONBLOCK) == 0);
Void::MCP::StdioTransport transport{
input[0], output[1], echo_handler, {}, {}, 2s};
std::stop_source stop;
std::jthread killer([&stop] {
std::this_thread::sleep_for(50ms);
stop.request_stop();
});
const auto start = std::chrono::steady_clock::now();
auto message = transport.read_message(stop.get_token());
const auto elapsed = std::chrono::steady_clock::now() - start;
killer.join();
Void::Testing::require(!message.has_value());
Void::Testing::expect(
message.error().code().value ==
static_cast<std::int32_t>(
Void::MCP::McpErrorCode::cancelled));
Void::Testing::expect(elapsed < 1s);
::close(input[0]);
::close(input[1]);
::close(output[0]);
::close(output[1]);
}
// Slow reader: a full non-blocking pipe makes the write time out.
{
int input[2]{};
int output[2]{};
Void::Testing::require(::pipe(input) == 0);
Void::Testing::require(::pipe(output) == 0);
const int flags = ::fcntl(output[1], F_GETFL, 0);
Void::Testing::require(flags >= 0);
Void::Testing::require(
::fcntl(output[1], F_SETFL, flags | O_NONBLOCK) == 0);
Void::MCP::StdioTransport transport{
input[0], output[1], echo_handler, {}, {}, 150ms};
Void::MCP::Response large;
large.id = JsonRpcId{std::int64_t{9}};
large.result = JsonValue{std::string(256U * 1024U, 'x')};
auto written = transport.write_message(Message{large});
Void::Testing::require(!written.has_value());
Void::Testing::expect(
written.error().code().value ==
static_cast<std::int32_t>(Void::MCP::McpErrorCode::timeout));
::close(input[0]);
::close(input[1]);
::close(output[0]);
::close(output[1]);
}
}
#endif
Void::Testing::Test mcp_legacy_session_fixtures()
{
Void::MCP::LegacySessionOptions options;
options.session_id_factory = [] { return std::string{"sess-1"}; };
Void::MCP::LegacySessionAdapter adapter{options};
Request initialize;
initialize.id = JsonRpcId{std::int64_t{1}};
initialize.method = "initialize";
initialize.params =
object_of(R"({"protocolVersion":"2025-06-18",)"
R"("clientInfo":{"name":"legacy","version":"0.1"}})");
auto reply = adapter.handle(Message{initialize});
Void::Testing::require(reply.has_value());
Void::Testing::require(reply->has_value());
const auto* response = std::get_if<Response>(&**reply);
Void::Testing::require(response != nullptr);
Void::Testing::require(response->result.has_value());
const auto* result =
std::get_if<JsonValue::Object>(&response->result->value);
Void::Testing::require(result != nullptr);
Void::Testing::expect(
std::get<std::string>(result->at("protocolVersion").value) ==
"2025-06-18");
Void::Testing::require(adapter.find("sess-1") != nullptr);
Void::Testing::expect(!adapter.find("sess-1")->initialized);
Void::Testing::expect_eq(adapter.session_count(), std::size_t{1});
Void::MCP::Notification initialized;
initialized.method = "initialized";
auto ready = adapter.handle(Message{initialized}, "sess-1");
Void::Testing::require(ready.has_value());
Void::Testing::expect(!ready->has_value());
Void::Testing::expect(adapter.find("sess-1")->initialized);
Request tools;
tools.id = JsonRpcId{std::int64_t{2}};
tools.method = "tools/list";
auto forwarded = adapter.handle(Message{tools}, "sess-1");
Void::Testing::require(forwarded.has_value());
Void::Testing::require(forwarded->has_value());
Void::Testing::expect(
std::get_if<Request>(&**forwarded) != nullptr);
// Unknown session is rejected.
Void::Testing::expect(!adapter.handle(Message{tools}, "missing").has_value());
// Unknown requested version negotiates the newest supported revision.
Request legacy_initialize;
legacy_initialize.id = JsonRpcId{std::int64_t{3}};
legacy_initialize.method = "initialize";
legacy_initialize.params =
object_of(R"({"protocolVersion":"1900-01-01"})");
auto negotiated = adapter.handle(Message{legacy_initialize});
Void::Testing::require(negotiated.has_value());
Void::Testing::require(negotiated->has_value());
const auto* negotiated_response =
std::get_if<Response>(&**negotiated);
Void::Testing::require(negotiated_response != nullptr);
const auto* negotiated_result =
std::get_if<JsonValue::Object>(&negotiated_response->result->value);
Void::Testing::require(negotiated_result != nullptr);
Void::Testing::expect(
std::get<std::string>(negotiated_result->at("protocolVersion").value) ==
"2025-11-25");
Void::Testing::expect(adapter.terminate("sess-1"));
Void::Testing::expect_eq(adapter.session_count(), std::size_t{0});
}