using ModelContextProtocol.Protocol; using System.Buffers; using System.Net.ServerSentEvents; using System.Text.Json; namespace ModelContextProtocol.Server; /// /// Provides MCP extension methods for . /// internal static class McpSseEventWriterExtensions { [ThreadStatic] private static Utf8JsonWriter? _jsonWriter; /// /// Writes an SSE item containing a . /// /// The . /// The SSE item containing the . /// The token to monitor for cancellation requests. /// A task representing the asynchronous write operation. public static ValueTask WriteAsync(this SseEventWriter writer, SseItem item, CancellationToken cancellationToken = default) => writer.WriteAsync(item, FormatJsonRpcMessage, cancellationToken); /// /// Writes an SSE item containing a . /// /// The . /// The SSE item containing the string. /// The token to monitor for cancellation requests. /// A task representing the asynchronous write operation. public static ValueTask WriteAsync(this SseEventWriter writer, SseItem item, CancellationToken cancellationToken = default) => writer.WriteAsync(item, FormatString, cancellationToken); /// /// Formats a message by writing it as JSON to the buffer writer. /// private static void FormatJsonRpcMessage(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, McpJsonUtilities.JsonContext.Default.JsonRpcMessage!); } /// /// Formats a string by writing it as UTF-8 to the buffer writer. /// private static void FormatString(SseItem item, IBufferWriter writer) { if (item.Data is null) { return; } writer.WriteUtf8String(item.Data); } }