| 1 | using System.Text.Json; |
| 2 | using System.Text.Json.Serialization; |
| 3 | |
| 4 | namespace AgentClientProtocol; |
| 5 | |
| 6 | [JsonConverter(typeof(McpServerJsonConverter))] |
| 7 | public abstract record McpServer |
| 8 | { |
| 9 | [JsonPropertyName("name")] |
| 10 | public required string Name { get; init; } |
| 11 | |
| 12 | [JsonPropertyName("type")] |
| 13 | public abstract string Type { get; } |
| 14 | } |
| 15 | |
| 16 | public record HttpMcpServer : McpServer |
| 17 | { |
| 18 | [JsonPropertyName("type")] |
| 19 | public override string Type => "http"; |
| 20 | |
| 21 | [JsonPropertyName("url")] |
| 22 | public required string Url { get; init; } |
| 23 | |
| 24 | [JsonPropertyName("headers")] |
| 25 | public required HttpHeader[] Headers { get; init; } |
| 26 | } |
| 27 | |
| 28 | public record SseMcpServer : McpServer |
| 29 | { |
| 30 | [JsonPropertyName("type")] |
| 31 | public override string Type => "sse"; |
| 32 | |
| 33 | [JsonPropertyName("url")] |
| 34 | public required string Url { get; init; } |
| 35 | |
| 36 | [JsonPropertyName("headers")] |
| 37 | public required HttpHeader[] Headers { get; init; } |
| 38 | } |
| 39 | |
| 40 | public record StdioMcpServer : McpServer |
| 41 | { |
| 42 | [JsonPropertyName("type")] |
| 43 | public override string Type => "stdio"; |
| 44 | |
| 45 | [JsonPropertyName("command")] |
| 46 | public required string Command { get; init; } |
| 47 | |
| 48 | [JsonPropertyName("args")] |
| 49 | public required string[] Args { get; init; } |
| 50 | |
| 51 | [JsonPropertyName("env")] |
| 52 | public required EnvVariable[] Env { get; init; } |
| 53 | } |
| 54 | |
| 55 | public class McpServerJsonConverter : JsonConverter<McpServer> |
| 56 | { |
| 57 | public override McpServer? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 58 | { |
| 59 | using var doc = JsonDocument.ParseValue(ref reader); |
| 60 | var root = doc.RootElement; |
| 61 | |
| 62 | if (!root.TryGetProperty("type", out var typeProperty)) |
| 63 | { |
| 64 | throw new JsonException("Missing 'type' property in McpServer"); |
| 65 | } |
| 66 | |
| 67 | var type = typeProperty.GetString(); |
| 68 | return type switch |
| 69 | { |
| 70 | "http" => root.Deserialize<HttpMcpServer>(options), |
| 71 | "sse" => root.Deserialize<SseMcpServer>(options), |
| 72 | "stdio" => root.Deserialize<StdioMcpServer>(options), |
| 73 | _ => throw new JsonException($"Unknown McpServer type: {type}") |
| 74 | }; |
| 75 | } |
| 76 | |
| 77 | public override void Write(Utf8JsonWriter writer, McpServer value, JsonSerializerOptions options) |
| 78 | { |
| 79 | JsonSerializer.Serialize(writer, value, value.GetType(), options); |
| 80 | } |
| 81 | } |