using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using System.Buffers;
using System.Net.ServerSentEvents;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace ModelContextProtocol.AspNetCore;
///
/// Provides extension methods for .
///
internal static class SseEventStreamReaderExtensions
{
///
/// Copies all events from the reader to the destination stream in SSE format.
///
/// The event stream reader to copy events from.
/// The destination stream to write SSE-formatted events to.
/// A token to cancel the operation.
/// A task that represents the asynchronous copy operation.
/// Thrown when or is null.
public static async Task CopyToAsync(this ISseEventStreamReader reader, Stream destination, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(reader);
ArgumentNullException.ThrowIfNull(destination);
Utf8JsonWriter? jsonWriter = null;
var jsonTypeInfo = (JsonTypeInfo)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage));
var events = reader.ReadEventsAsync(cancellationToken);
await SseFormatter.WriteAsync(events, destination, FormatEvent, cancellationToken).ConfigureAwait(false);
void FormatEvent(SseItem item, IBufferWriter writer)
{
if (item.Data is null)
{
return;
}
if (jsonWriter is null)
{
jsonWriter = new Utf8JsonWriter(writer);
}
else
{
jsonWriter.Reset(writer);
}
JsonSerializer.Serialize(jsonWriter, item.Data, jsonTypeInfo);
}
}
}