83 lines
2.2 KiB
C++
83 lines
2.2 KiB
C++
#pragma once
|
|
|
|
#include <Void/Functional/Result.hpp>
|
|
#include <Void/MCP/Types.hpp>
|
|
|
|
#include <cstddef>
|
|
#include <optional>
|
|
#include <string>
|
|
#include <string_view>
|
|
|
|
namespace Void::MCP
|
|
{
|
|
/// Newline-delimited JSON-RPC framing used by the stdio transport
|
|
/// (and any custom transport built on a reliable byte stream).
|
|
///
|
|
/// A frame is one JSON-RPC message followed by `\n`; embedded newlines
|
|
/// are not allowed. A trailing `\r` is tolerated before the newline.
|
|
class LineFramer
|
|
{
|
|
public:
|
|
|
|
explicit LineFramer(McpLimits limits = {});
|
|
|
|
/// Append bytes from the stream. Fails when the unterminated
|
|
/// tail exceeds `limits.max_line_bytes`.
|
|
[[nodiscard]] Void::Result::Result<void>
|
|
append(std::string_view bytes);
|
|
|
|
/// Pop the next complete line (without the newline). Empty
|
|
/// lines are skipped. `nullopt` means more bytes are needed.
|
|
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
|
|
next();
|
|
|
|
[[nodiscard]] std::size_t buffered() const noexcept;
|
|
void reset() noexcept;
|
|
|
|
private:
|
|
|
|
McpLimits m_limits;
|
|
std::string m_buffer;
|
|
};
|
|
|
|
/// One Server-Sent Events event used by Streamable HTTP responses.
|
|
struct SseEvent {
|
|
std::string event{};
|
|
std::string data{};
|
|
std::string id{};
|
|
};
|
|
|
|
/// Serialize one SSE event (`event:`/`id:`/`data:` lines terminated by
|
|
/// a blank line). Multi-line data is split into multiple `data:` lines.
|
|
[[nodiscard]] Void::Result::Result<std::string>
|
|
encode_sse_event(const SseEvent& event, const McpLimits& limits = {});
|
|
|
|
/// Bounded incremental SSE parser. Comment lines and unknown fields
|
|
/// are ignored; `data` lines are joined with `\n`.
|
|
class SseParser
|
|
{
|
|
public:
|
|
|
|
explicit SseParser(McpLimits limits = {});
|
|
|
|
[[nodiscard]] Void::Result::Result<void>
|
|
append(std::string_view bytes);
|
|
|
|
[[nodiscard]] Void::Result::Result<std::optional<SseEvent>>
|
|
next();
|
|
|
|
[[nodiscard]] std::size_t buffered() const noexcept;
|
|
void reset() noexcept;
|
|
|
|
private:
|
|
|
|
McpLimits m_limits;
|
|
std::string m_buffer;
|
|
};
|
|
|
|
/// Append the stdio frame terminator and validate the line bound.
|
|
[[nodiscard]] Void::Result::Result<std::string>
|
|
frame_line(std::string_view json, const McpLimits& limits = {});
|
|
|
|
} // namespace Void::MCP
|