| 1 | using System.Text.Json; |
| 2 | using System.Text.Json.Serialization; |
| 3 | |
| 4 | namespace AgentClientProtocol; |
| 5 | |
| 6 | [JsonConverter(typeof(EmbeddedResourceResourceJsonConverter))] |
| 7 | public abstract record EmbeddedResourceResource; |
| 8 | |
| 9 | public record TextResourceContents : EmbeddedResourceResource |
| 10 | { |
| 11 | [JsonPropertyName("uri")] |
| 12 | public required string Uri { get; init; } |
| 13 | |
| 14 | [JsonPropertyName("text")] |
| 15 | public required string Text { get; init; } |
| 16 | |
| 17 | [JsonPropertyName("_meta")] |
| 18 | public JsonElement? Meta { get; init; } |
| 19 | |
| 20 | [JsonPropertyName("mimeType")] |
| 21 | public string? MimeType { get; init; } |
| 22 | } |
| 23 | |
| 24 | public record BlobResourceContents : EmbeddedResourceResource |
| 25 | { |
| 26 | [JsonPropertyName("_meta")] |
| 27 | public JsonElement? Meta { get; init; } |
| 28 | |
| 29 | [JsonPropertyName("blob")] |
| 30 | public required string Blob { get; init; } |
| 31 | |
| 32 | [JsonPropertyName("uri")] |
| 33 | public required string Uri { get; init; } |
| 34 | |
| 35 | [JsonPropertyName("mimeType")] |
| 36 | public string? MimeType { get; init; } |
| 37 | } |
| 38 | |
| 39 | public class EmbeddedResourceResourceJsonConverter : JsonConverter<EmbeddedResourceResource> |
| 40 | { |
| 41 | public override EmbeddedResourceResource? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 42 | { |
| 43 | using var doc = JsonDocument.ParseValue(ref reader); |
| 44 | var root = doc.RootElement; |
| 45 | |
| 46 | if (root.TryGetProperty("text", out _)) |
| 47 | { |
| 48 | return root.Deserialize<TextResourceContents>(options); |
| 49 | } |
| 50 | else if (root.TryGetProperty("blob", out _)) |
| 51 | { |
| 52 | return root.Deserialize<BlobResourceContents>(options); |
| 53 | } |
| 54 | else |
| 55 | { |
| 56 | throw new JsonException("Unknown EmbeddedResourceResource type - missing 'text' or 'blob' property"); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | public override void Write(Utf8JsonWriter writer, EmbeddedResourceResource value, JsonSerializerOptions options) |
| 61 | { |
| 62 | JsonSerializer.Serialize(writer, value, value.GetType(), options); |
| 63 | } |
| 64 | } |