Class JSONRPCUtils

java.lang.Object
org.a2aproject.sdk.grpc.utils.JSONRPCUtils

public class JSONRPCUtils extends Object
Utilities for converting between JSON-RPC 2.0 messages and Protocol Buffer objects.

This class provides a unified strategy for handling JSON-RPC requests and responses in the A2A SDK by bridging the JSON-RPC transport layer with Protocol Buffer-based internal representations.

Conversion Strategy

The conversion process follows a two-step approach:
  1. JSON → Proto: JSON-RPC messages are parsed using Gson, then converted to Protocol Buffer objects using Google's JsonFormat parser. This ensures consistent handling of field names, types, and nested structures according to the proto3 specification.
  2. Proto → Spec: Protocol Buffer objects are converted to A2A spec objects using ProtoUtils.FromProto converters, which handle type mappings and create immutable spec-compliant Java objects.

Request Processing Flow

 Incoming JSON-RPC Request
   ↓ parseRequestBody(String)
 Validate version, id, method
   ↓ parseMethodRequest()
 Parse params → Proto Builder
   ↓ ProtoUtils.FromProto.*
 Create JSONRPCRequest<?> with spec objects
 

Response Processing Flow

 Incoming JSON-RPC Response
   ↓ parseResponseBody(String, String)
 Validate version, id, check for errors
   ↓ Parse result/error
 Proto Builder → spec objects
   ↓ ProtoUtils.FromProto.*
 Create JSONRPCResponse<?> with result or error
 

Serialization Flow

 Proto MessageOrBuilder
   ↓ JsonFormat.printer()
 Proto JSON string
   ↓ Gson JsonWriter
 Complete JSON-RPC envelope
 

Error Handling

The class provides detailed error messages for common failure scenarios:

Thread Safety

This class is thread-safe. All methods are stateless and use immutable shared resources (Gson instance is thread-safe, proto builders are created per-invocation).

Usage Example


 // Parse incoming JSON-RPC request
 String jsonRequest = """
     {"jsonrpc":"2.0","id":1,"method":"tasks.get","params":{"name":"tasks/task-123"}}
     """;
 JSONRPCRequest<?> request = JSONRPCUtils.parseRequestBody(jsonRequest);

 // Create JSON-RPC request from proto
 org.a2aproject.sdk.grpc.GetTaskRequest protoRequest = ...;
 String json = JSONRPCUtils.toJsonRPCRequest("req-1", "tasks.get", protoRequest);

 // Create JSON-RPC response from proto
 org.a2aproject.sdk.grpc.Task protoTask = ...;
 String response = JSONRPCUtils.toJsonRPCResultResponse("req-1", protoTask);
 
See Also: