|
| 1 | +using System.Text.Json; |
| 2 | +using System.Text.Json.Serialization; |
| 3 | + |
| 4 | +namespace ModelContextProtocol.Protocol; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// Serializes <see cref="CacheScope"/> caching-scope hints, tolerating unknown or future values on read. |
| 8 | +/// </summary> |
| 9 | +/// <remarks> |
| 10 | +/// <para> |
| 11 | +/// SEP-2549 introduces <c>cacheScope</c> as a forward-looking caching hint. If a server sends an |
| 12 | +/// unrecognized scope string (for example, a value added in a later revision of the specification) or a |
| 13 | +/// non-string token, this converter maps it to <see langword="null"/> rather than throwing. This prevents |
| 14 | +/// a single unexpected hint from breaking deserialization of the entire result (for example, the whole |
| 15 | +/// tool list). A <see langword="null"/> result is the same as an absent field, which clients treat as |
| 16 | +/// <see cref="CacheScope.Public"/>. |
| 17 | +/// </para> |
| 18 | +/// <para> |
| 19 | +/// This converter is applied per-property on the cacheable result types. The <see cref="CacheScope"/> |
| 20 | +/// enum itself retains a standard string converter for any standalone serialization. |
| 21 | +/// </para> |
| 22 | +/// </remarks> |
| 23 | +internal sealed class CacheScopeConverter : JsonConverter<CacheScope?> |
| 24 | +{ |
| 25 | + public override CacheScope? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 26 | + { |
| 27 | + if (reader.TokenType is JsonTokenType.String) |
| 28 | + { |
| 29 | + string? value = reader.GetString(); |
| 30 | + |
| 31 | + // Match case-insensitively so a non-conforming casing of "private" (a security-relevant hint) |
| 32 | + // is honored rather than falling through to null, which clients would treat as "public" and |
| 33 | + // could cache user-specific data in a shared cache. Genuinely unknown values still map to null. |
| 34 | + if (string.Equals(value, "public", StringComparison.OrdinalIgnoreCase)) |
| 35 | + { |
| 36 | + return CacheScope.Public; |
| 37 | + } |
| 38 | + |
| 39 | + if (string.Equals(value, "private", StringComparison.OrdinalIgnoreCase)) |
| 40 | + { |
| 41 | + return CacheScope.Private; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return null; |
| 46 | + } |
| 47 | + |
| 48 | + public override void Write(Utf8JsonWriter writer, CacheScope? value, JsonSerializerOptions options) |
| 49 | + { |
| 50 | + if (value is null) |
| 51 | + { |
| 52 | + writer.WriteNullValue(); |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + writer.WriteStringValue(value switch |
| 57 | + { |
| 58 | + CacheScope.Public => "public", |
| 59 | + CacheScope.Private => "private", |
| 60 | + _ => throw new JsonException($"Unsupported {nameof(CacheScope)} value: {value}."), |
| 61 | + }); |
| 62 | + } |
| 63 | +} |
0 commit comments