Skip to content

Commit e177b0b

Browse files
committed
feat: Add metadata support to Part types
Add optional metadata field to TextPart, FilePart, and DataPart records to support additional contextual information for message and artifact content parts as specified in the A2A protocol v1.0. Changes: - Add metadata parameter to Part constructors (TextPart, FilePart, DataPart) - Update PartMapper to convert metadata between domain and gRPC proto - Update JsonUtil PartTypeAdapter to serialize/deserialize metadata Signed-off-by: Emmanuel Hugonnet <ehugonne@redhat.com>
1 parent 7c10908 commit e177b0b

11 files changed

Lines changed: 106 additions & 49 deletions

File tree

‎jsonrpc-common/src/main/java/io/a2a/jsonrpc/common/json/JsonUtil.java‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,15 @@
2222
import java.time.OffsetDateTime;
2323
import java.time.format.DateTimeFormatter;
2424
import java.time.format.DateTimeParseException;
25+
import java.util.Map;
2526
import java.util.Set;
2627

2728
import com.google.gson.Gson;
2829
import com.google.gson.GsonBuilder;
2930
import com.google.gson.JsonSyntaxException;
3031
import com.google.gson.ToNumberPolicy;
3132
import com.google.gson.TypeAdapter;
33+
import com.google.gson.reflect.TypeToken;
3234
import com.google.gson.stream.JsonReader;
3335
import com.google.gson.stream.JsonToken;
3436
import com.google.gson.stream.JsonWriter;
@@ -560,14 +562,29 @@ public void write(JsonWriter out, Part<?> value) throws java.io.IOException {
560562
// TextPart: { "text": "value" } - direct string value
561563
out.name(TEXT);
562564
out.value(textPart.text());
565+
// Write metadata if present
566+
if (textPart.metadata() != null && !textPart.metadata().isEmpty()) {
567+
out.name("metadata");
568+
delegateGson.toJson(textPart.metadata(), new TypeToken<Map<String, Object>>(){}.getType(), out);
569+
}
563570
} else if (value instanceof FilePart filePart) {
564571
// FilePart: { "file": {...} }
565572
out.name(FILE);
566573
delegateGson.toJson(filePart.file(), FileContent.class, out);
574+
// Write metadata if present
575+
if (filePart.metadata() != null && !filePart.metadata().isEmpty()) {
576+
out.name("metadata");
577+
delegateGson.toJson(filePart.metadata(), new TypeToken<Map<String, Object>>(){}.getType(), out);
578+
}
567579
} else if (value instanceof DataPart dataPart) {
568580
// DataPart: { "data": <any JSON value> }
569581
out.name(DATA);
570582
delegateGson.toJson(dataPart.data(), Object.class, out);
583+
// Write metadata if present
584+
if (dataPart.metadata() != null && !dataPart.metadata().isEmpty()) {
585+
out.name("metadata");
586+
delegateGson.toJson(dataPart.metadata(), new TypeToken<Map<String, Object>>(){}.getType(), out);
587+
}
571588
} else {
572589
throw new JsonSyntaxException("Unknown Part subclass: " + value.getClass().getName());
573590
}
@@ -591,24 +608,34 @@ Part<?> read(JsonReader in) throws java.io.IOException {
591608

592609
com.google.gson.JsonObject jsonObject = jsonElement.getAsJsonObject();
593610

611+
// Extract metadata if present
612+
Map<String, Object> metadata = null;
613+
if (jsonObject.has("metadata")) {
614+
metadata = delegateGson.fromJson(jsonObject.get("metadata"), new TypeToken<Map<String, Object>>(){}.getType());
615+
}
616+
594617
// Check for member name discriminators (v1.0 protocol)
595618
Set<String> keys = jsonObject.keySet();
596-
if (keys.size() != 1) {
597-
throw new JsonSyntaxException(format("Part object must have exactly one key, which must be one of: %s (found: %s)", VALID_KEYS, keys));
619+
if (keys.size() < 1 || keys.size() > 2) {
620+
throw new JsonSyntaxException(format("Part object must have one content key from %s and optionally 'metadata' (found: %s)", VALID_KEYS, keys));
598621
}
599622

600-
String discriminator = keys.iterator().next();
623+
// Find the discriminator (should be one of TEXT, FILE, DATA)
624+
String discriminator = keys.stream()
625+
.filter(VALID_KEYS::contains)
626+
.findFirst()
627+
.orElseThrow(() -> new JsonSyntaxException(format("Part must have one of: %s (found: %s)", VALID_KEYS, keys)));
601628

602629
return switch (discriminator) {
603-
case TEXT -> new TextPart(jsonObject.get(TEXT).getAsString());
604-
case FILE -> new FilePart(delegateGson.fromJson(jsonObject.get(FILE), FileContent.class));
630+
case TEXT -> new TextPart(jsonObject.get(TEXT).getAsString(), metadata);
631+
case FILE -> new FilePart(delegateGson.fromJson(jsonObject.get(FILE), FileContent.class), metadata);
605632
case DATA -> {
606633
// DataPart supports any JSON value: object, array, primitive, or null
607634
Object data = delegateGson.fromJson(
608635
jsonObject.get(DATA),
609636
Object.class
610637
);
611-
yield new DataPart(data);
638+
yield new DataPart(data, metadata);
612639
}
613640
default ->
614641
throw new JsonSyntaxException(format("Part must have one of: %s (found: %s)", VALID_KEYS, discriminator));

‎jsonrpc-common/src/test/java/io/a2a/jsonrpc/common/json/StreamingEventKindSerializationTest.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ void testMessageSerialization() throws JsonProcessingException {
6262
// Create a Message
6363
Message message = Message.builder()
6464
.role(Message.Role.USER)
65-
.parts(List.of(new TextPart("Hello, agent!")))
65+
.parts(List.of(new TextPart("Hello, agent!", null)))
6666
.taskId("task-789")
6767
.messageId("msg-123")
6868
.contextId("context-456")
@@ -127,7 +127,7 @@ void testTaskArtifactUpdateEventSerialization() throws JsonProcessingException {
127127
Artifact artifact = Artifact.builder()
128128
.artifactId("artifact-xyz")
129129
.name("Test Artifact")
130-
.parts(List.of(new TextPart("Artifact content")))
130+
.parts(List.of(new TextPart("Artifact content", null)))
131131
.build();
132132

133133
TaskArtifactUpdateEvent artifactEvent = TaskArtifactUpdateEvent.builder()

‎jsonrpc-common/src/test/java/io/a2a/jsonrpc/common/json/TaskSerializationTest.java‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,8 @@ void testTaskWithArtifacts() throws JsonProcessingException {
8181
.name("Test Artifact")
8282
.description("Description of artifact")
8383
.parts(List.of(
84-
new TextPart("Hello"),
85-
new TextPart("World")
84+
new TextPart("Hello", null),
85+
new TextPart("World", null)
8686
))
8787
.build();
8888

@@ -115,7 +115,7 @@ void testTaskWithArtifacts() throws JsonProcessingException {
115115
void testTaskWithHistory() throws JsonProcessingException {
116116
Message message = Message.builder()
117117
.role(Message.Role.USER)
118-
.parts(List.of(new TextPart("Test message")))
118+
.parts(List.of(new TextPart("Test message", null)))
119119
.build();
120120

121121
Task task = Task.builder()
@@ -153,17 +153,17 @@ void testTaskWithAllFields() throws JsonProcessingException {
153153
.history(List.of(
154154
Message.builder()
155155
.role(Message.Role.USER)
156-
.parts(List.of(new TextPart("User message")))
156+
.parts(List.of(new TextPart("User message", null)))
157157
.build(),
158158
Message.builder()
159159
.role(Message.Role.AGENT)
160-
.parts(List.of(new TextPart("Agent response")))
160+
.parts(List.of(new TextPart("Agent response", null)))
161161
.build()
162162
))
163163
.artifacts(List.of(
164164
Artifact.builder()
165165
.artifactId("artifact-1")
166-
.parts(List.of(new TextPart("Artifact content")))
166+
.parts(List.of(new TextPart("Artifact content", null)))
167167
.build()
168168
))
169169
.metadata(Map.of("key1", "value1", "key2", 42))
@@ -238,7 +238,7 @@ void testTaskWithNullOptionalFields() throws JsonProcessingException {
238238

239239
@Test
240240
void testTaskWithFilePartBytes() throws JsonProcessingException {
241-
FilePart filePart = new FilePart(new FileWithBytes("application/pdf", "document.pdf", "base64data"));
241+
FilePart filePart = new FilePart(new FileWithBytes("application/pdf", "document.pdf", "base64data"), null);
242242

243243
Artifact artifact = Artifact.builder()
244244
.artifactId("file-artifact")
@@ -276,7 +276,7 @@ void testTaskWithFilePartBytes() throws JsonProcessingException {
276276

277277
@Test
278278
void testTaskWithFilePartUri() throws JsonProcessingException {
279-
FilePart filePart = new FilePart(new FileWithUri("image/png", "photo.png", "https://example.com/photo.png"));
279+
FilePart filePart = new FilePart(new FileWithUri("image/png", "photo.png", "https://example.com/photo.png"), null);
280280

281281
Artifact artifact = Artifact.builder()
282282
.artifactId("uri-artifact")
@@ -311,7 +311,7 @@ void testTaskWithFilePartUri() throws JsonProcessingException {
311311

312312
@Test
313313
void testTaskWithDataPart() throws JsonProcessingException {
314-
DataPart dataPart = new DataPart(Map.of("temperature", 22.5, "humidity", 65));
314+
DataPart dataPart = new DataPart(Map.of("temperature", 22.5, "humidity", 65), null);
315315

316316
Artifact artifact = Artifact.builder()
317317
.artifactId("data-artifact")
@@ -356,16 +356,16 @@ void testTaskRoundTrip() throws JsonProcessingException {
356356
Message.builder()
357357
.role(Message.Role.USER)
358358
.parts(List.of(
359-
new TextPart("Text"),
360-
new FilePart(new FileWithBytes("text/plain", "file.txt", "data")),
361-
new DataPart(Map.of("key", "value"))
359+
new TextPart("Text", null),
360+
new FilePart(new FileWithBytes("text/plain", "file.txt", "data"), null),
361+
new DataPart(Map.of("key", "value"), null)
362362
))
363363
.build()
364364
))
365365
.artifacts(List.of(
366366
Artifact.builder()
367367
.artifactId("artifact-1")
368-
.parts(List.of(new TextPart("Content")))
368+
.parts(List.of(new TextPart("Content", null)))
369369
.build()
370370
))
371371
.metadata(Map.of("meta1", "value1"))
@@ -395,7 +395,7 @@ void testTaskRoundTrip() throws JsonProcessingException {
395395
void testTaskStatusWithMessage() throws JsonProcessingException {
396396
Message statusMessage = Message.builder()
397397
.role(Message.Role.AGENT)
398-
.parts(List.of(new TextPart("Processing complete")))
398+
.parts(List.of(new TextPart("Processing complete", null)))
399399
.build();
400400

401401
Task task = Task.builder()
@@ -682,10 +682,10 @@ void testTaskWithMixedPartTypes() throws JsonProcessingException {
682682
Artifact artifact = Artifact.builder()
683683
.artifactId("mixed-artifact")
684684
.parts(List.of(
685-
new TextPart("Text content"),
686-
new FilePart(new FileWithBytes("application/json", "data.json", "{}")),
687-
new DataPart(Map.of("result", 42)),
688-
new FilePart(new FileWithUri("image/png", "image.png", "https://example.com/img.png"))
685+
new TextPart("Text content", null),
686+
new FilePart(new FileWithBytes("application/json", "data.json", "{}"), null),
687+
new DataPart(Map.of("result", 42), null),
688+
new FilePart(new FileWithUri("image/png", "image.png", "https://example.com/img.png"), null)
689689
))
690690
.build();
691691

‎pom.xml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
<rest-assured.version>5.5.1</rest-assured.version>
7070
<slf4j.version>2.0.17</slf4j.version>
7171
<logback.version>1.5.18</logback.version>
72+
<version.testcontainers>1.21.4</version.testcontainers>
7273
<error-prone.version>2.47.0</error-prone.version>
7374
<nullaway.version>0.13.1</nullaway.version>
7475
<error-prone.flag>-XDaddTypeAnnotationsToSymbol=true</error-prone.flag>
@@ -227,6 +228,13 @@
227228
<scope>import</scope>
228229
</dependency>
229230
<dependency>
231+
                <groupId>org.testcontainers</groupId>
232+
                <artifactId>testcontainers-bom</artifactId>
233+
                <version>${version.testcontainers}</version>
234+
                <type>pom</type>
235+
                <scope>import</scope>
236+
            </dependency>
237+
<dependency>
230238
<groupId>io.quarkus</groupId>
231239
<artifactId>quarkus-bom</artifactId>
232240
<version>${quarkus.platform.version}</version>

‎spec-grpc/src/main/java/io/a2a/grpc/mapper/PartMapper.java‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ default io.a2a.grpc.Part toProto(Part<?> domain) {
4646

4747
if (domain instanceof TextPart textPart) {
4848
builder.setText(textPart.text());
49+
builder.setMetadata(A2ACommonFieldMapper.INSTANCE.metadataToProto(textPart.metadata()));
4950
} else if (domain instanceof FilePart filePart) {
5051
FileContent fileContent = filePart.file();
5152

@@ -68,10 +69,12 @@ default io.a2a.grpc.Part toProto(Part<?> domain) {
6869
builder.setMediaType(fileWithUri.mimeType());
6970
}
7071
}
72+
builder.setMetadata(A2ACommonFieldMapper.INSTANCE.metadataToProto(filePart.metadata()));
7173
} else if (domain instanceof DataPart dataPart) {
7274
// Map data to google.protobuf.Value (supports object, array, primitive, or null)
7375
Value dataValue = A2ACommonFieldMapper.INSTANCE.objectToValue(dataPart.data());
7476
builder.setData(dataValue);
77+
builder.setMetadata(A2ACommonFieldMapper.INSTANCE.metadataToProto(dataPart.metadata()));
7578
}
7679

7780
return builder.build();
@@ -87,24 +90,24 @@ default Part<?> fromProto(io.a2a.grpc.Part proto) {
8790
}
8891

8992
if (proto.hasText()) {
90-
return new TextPart(proto.getText());
93+
return new TextPart(proto.getText(), A2ACommonFieldMapper.INSTANCE.metadataFromProto(proto.getMetadata()));
9194
} else if (proto.hasRaw()) {
9295
// raw bytes → FilePart(FileWithBytes)
9396
String bytes = Base64.getEncoder().encodeToString(proto.getRaw().toByteArray());
9497
String mimeType = proto.getMediaType().isEmpty() ? null : proto.getMediaType();
9598
String name = proto.getFilename().isEmpty() ? null : proto.getFilename();
96-
return new FilePart(new FileWithBytes(mimeType, name, bytes));
99+
return new FilePart(new FileWithBytes(mimeType, name, bytes), A2ACommonFieldMapper.INSTANCE.metadataFromProto(proto.getMetadata()));
97100
} else if (proto.hasUrl()) {
98101
// url → FilePart(FileWithUri)
99102
String uri = proto.getUrl();
100103
String mimeType = proto.getMediaType().isEmpty() ? null : proto.getMediaType();
101104
String name = proto.getFilename().isEmpty() ? null : proto.getFilename();
102-
return new FilePart(new FileWithUri(mimeType, name, uri));
105+
return new FilePart(new FileWithUri(mimeType, name, uri), A2ACommonFieldMapper.INSTANCE.metadataFromProto(proto.getMetadata()));
103106
} else if (proto.hasData()) {
104107
// data (google.protobuf.Value containing any JSON value) → DataPart
105108
Value dataValue = proto.getData();
106109
Object data = A2ACommonFieldMapper.INSTANCE.valueToObject(dataValue);
107-
return new DataPart(data);
110+
return new DataPart(data, A2ACommonFieldMapper.INSTANCE.metadataFromProto(proto.getMetadata()));
108111
}
109112

110113
throw new InvalidRequestError();

‎spec-grpc/src/test/java/io/a2a/grpc/mapper/StreamResponseMapperTest.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ void testConvertMessage_ToProto() {
7272
.messageId("msg-123")
7373
.contextId("context-456")
7474
.role(Message.Role.USER)
75-
.parts(Collections.singletonList(new TextPart("Hello")))
75+
.parts(Collections.singletonList(new TextPart("Hello", null)))
7676
.build();
7777

7878
// Act
@@ -167,7 +167,7 @@ void testConvertTaskArtifactUpdateEvent_ToProto() {
167167
.artifact(Artifact.builder()
168168
.artifactId("artifact-1")
169169
.name("result")
170-
.parts(new TextPart("Result text"))
170+
.parts(new TextPart("Result text", null))
171171
.build())
172172
.build();
173173

@@ -254,7 +254,7 @@ void testConvertStreamResponse_Roundtrip_Message() {
254254
.messageId("msg-123")
255255
.contextId("context-456")
256256
.role(Message.Role.AGENT)
257-
.parts(Collections.singletonList(new TextPart("Response")))
257+
.parts(Collections.singletonList(new TextPart("Response", null)))
258258
.build();
259259

260260
// Act

‎spec-grpc/src/test/java/io/a2a/grpc/utils/ToProtoTest.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class ToProtoTest {
3838

3939
private static final Message SIMPLE_MESSAGE = Message.builder()
4040
.role(Message.Role.USER)
41-
.parts(Collections.singletonList(new TextPart("tell me a joke")))
41+
.parts(Collections.singletonList(new TextPart("tell me a joke", null)))
4242
.contextId("context-1234")
4343
.messageId("message-1234")
4444
.build();
@@ -147,7 +147,7 @@ public void convertTask() {
147147
.artifacts(List.of(Artifact.builder()
148148
.artifactId("11")
149149
.name("artefact")
150-
.parts(new TextPart("text"))
150+
.parts(new TextPart("text", null))
151151
.build()))
152152
.history(List.of(SIMPLE_MESSAGE))
153153
.metadata(Collections.emptyMap())
@@ -189,7 +189,7 @@ public void convertMessage() {
189189
assertEquals(false, result.getParts(0).hasData());
190190
Message message = Message.builder()
191191
.role(Message.Role.AGENT)
192-
.parts(Collections.singletonList(new TextPart("tell me a joke")))
192+
.parts(Collections.singletonList(new TextPart("tell me a joke", null)))
193193
.messageId("message-1234")
194194
.build();
195195
result = ProtoUtils.ToProto.message(message);
@@ -244,7 +244,7 @@ public void convertTaskArtifactUpdateEvent() {
244244
.contextId("session-123")
245245
.artifact(Artifact.builder()
246246
.artifactId("11")
247-
.parts(new TextPart("text"))
247+
.parts(new TextPart("text", null))
248248
.build()).build();
249249
io.a2a.grpc.TaskArtifactUpdateEvent result = ProtoUtils.ToProto.taskArtifactUpdateEvent(task);
250250
assertEquals("task-123", result.getTaskId());

0 commit comments

Comments
 (0)