|
| 1 | +using System.Text.Json; |
| 2 | +using System.Text.Json.Nodes; |
| 3 | + |
| 4 | +namespace A2A_Agent_Framework; |
| 5 | + |
| 6 | +public class JsonRpcMiddleware |
| 7 | +{ |
| 8 | + private readonly RequestDelegate _next; |
| 9 | + |
| 10 | + public JsonRpcMiddleware(RequestDelegate next) |
| 11 | + { |
| 12 | + _next = next; |
| 13 | + } |
| 14 | + |
| 15 | + public async Task InvokeAsync(HttpContext context) |
| 16 | + { |
| 17 | + // Check if it's a POST request and looks like it might be JSON-RPC |
| 18 | + if (context.Request.Method == HttpMethods.Post && |
| 19 | + context.Request.ContentType?.Contains("application/json") == true) |
| 20 | + { |
| 21 | + context.Request.EnableBuffering(); |
| 22 | + |
| 23 | + // Read the body |
| 24 | + using var reader = new StreamReader(context.Request.Body, leaveOpen: true); |
| 25 | + var body = await reader.ReadToEndAsync(); |
| 26 | + context.Request.Body.Position = 0; |
| 27 | + |
| 28 | + JsonNode? root = null; |
| 29 | + try |
| 30 | + { |
| 31 | + root = JsonNode.Parse(body); |
| 32 | + } |
| 33 | + catch |
| 34 | + { |
| 35 | + // Not valid JSON, ignore |
| 36 | + } |
| 37 | + |
| 38 | + // Check for JSON-RPC signature |
| 39 | + if (root is JsonObject obj && |
| 40 | + obj.ContainsKey("jsonrpc") && |
| 41 | + obj["jsonrpc"]?.GetValue<string>() == "2.0" && |
| 42 | + obj.ContainsKey("method") && |
| 43 | + obj.ContainsKey("params")) |
| 44 | + { |
| 45 | + var id = obj["id"]; |
| 46 | + var paramsNode = obj["params"]; |
| 47 | + |
| 48 | + // Replace request body with params |
| 49 | + var newBodyBytes = JsonSerializer.SerializeToUtf8Bytes(paramsNode); |
| 50 | + var newBodyStream = new MemoryStream(newBodyBytes); |
| 51 | + context.Request.Body = newBodyStream; |
| 52 | + context.Request.ContentLength = newBodyBytes.Length; |
| 53 | + |
| 54 | + // Capture response |
| 55 | + var originalBodyStream = context.Response.Body; |
| 56 | + using var responseBodyStream = new MemoryStream(); |
| 57 | + context.Response.Body = responseBodyStream; |
| 58 | + |
| 59 | + try |
| 60 | + { |
| 61 | + await _next(context); |
| 62 | + |
| 63 | + // Reset response body stream to read it |
| 64 | + responseBodyStream.Position = 0; |
| 65 | + var responseContent = await new StreamReader(responseBodyStream).ReadToEndAsync(); |
| 66 | + |
| 67 | + // Try to parse the response content as JSON |
| 68 | + JsonNode? resultNode = null; |
| 69 | + |
| 70 | + // Check for SSE format (data: ...) |
| 71 | + if (responseContent.TrimStart().StartsWith("data:")) |
| 72 | + { |
| 73 | + using var stringReader = new StringReader(responseContent); |
| 74 | + string? line; |
| 75 | + while ((line = await stringReader.ReadLineAsync()) != null) |
| 76 | + { |
| 77 | + if (line.StartsWith("data:")) |
| 78 | + { |
| 79 | + var jsonPart = line.Substring(5).Trim(); |
| 80 | + try |
| 81 | + { |
| 82 | + resultNode = JsonNode.Parse(jsonPart); |
| 83 | + if (resultNode != null) break; // Found valid JSON |
| 84 | + } |
| 85 | + catch { } |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + if (resultNode == null) |
| 91 | + { |
| 92 | + try |
| 93 | + { |
| 94 | + if (!string.IsNullOrWhiteSpace(responseContent)) |
| 95 | + { |
| 96 | + resultNode = JsonNode.Parse(responseContent); |
| 97 | + } |
| 98 | + } |
| 99 | + catch { } |
| 100 | + } |
| 101 | + |
| 102 | + // Construct JSON-RPC response |
| 103 | + var rpcResponse = new JsonObject |
| 104 | + { |
| 105 | + ["jsonrpc"] = "2.0", |
| 106 | + ["id"] = id?.DeepClone(), |
| 107 | + }; |
| 108 | + |
| 109 | + if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 300) |
| 110 | + { |
| 111 | + rpcResponse["result"] = resultNode ?? responseContent; |
| 112 | + } |
| 113 | + else |
| 114 | + { |
| 115 | + rpcResponse["error"] = new JsonObject |
| 116 | + { |
| 117 | + ["code"] = context.Response.StatusCode, |
| 118 | + ["message"] = "Error processing request", |
| 119 | + ["data"] = resultNode ?? responseContent |
| 120 | + }; |
| 121 | + // Reset status code to 200 because JSON-RPC errors are usually 200 OK at HTTP level |
| 122 | + context.Response.StatusCode = 200; |
| 123 | + } |
| 124 | + |
| 125 | + var rpcResponseBytes = JsonSerializer.SerializeToUtf8Bytes(rpcResponse); |
| 126 | + |
| 127 | + // Write back to original stream |
| 128 | + context.Response.Body = originalBodyStream; |
| 129 | + context.Response.ContentLength = rpcResponseBytes.Length; |
| 130 | + context.Response.ContentType = "application/json"; |
| 131 | + await context.Response.Body.WriteAsync(rpcResponseBytes); |
| 132 | + return; |
| 133 | + } |
| 134 | + catch (Exception ex) |
| 135 | + { |
| 136 | + // Handle exceptions |
| 137 | + context.Response.Body = originalBodyStream; |
| 138 | + var errorResponse = new JsonObject |
| 139 | + { |
| 140 | + ["jsonrpc"] = "2.0", |
| 141 | + ["id"] = id?.DeepClone(), |
| 142 | + ["error"] = new JsonObject |
| 143 | + { |
| 144 | + ["code"] = -32603, |
| 145 | + ["message"] = "Internal error", |
| 146 | + ["data"] = ex.Message |
| 147 | + } |
| 148 | + }; |
| 149 | + context.Response.StatusCode = 200; |
| 150 | + context.Response.ContentType = "application/json"; |
| 151 | + await context.Response.WriteAsJsonAsync(errorResponse); |
| 152 | + return; |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + await _next(context); |
| 158 | + } |
| 159 | +} |
0 commit comments