Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,10 @@ public static void closeChannel() {
Thread.currentThread().interrupt();
}
}

@Override
public void testAgentCardHeaders() {
// Skip - gRPC doesn't use HTTP caching headers for Agent Card
// The A2A spec section 8.6 caching requirements apply only to HTTP endpoints
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ public class A2AServerRoutes {
@Inject
JSONRPCHandler jsonRpcHandler;

@Inject
io.a2a.server.AgentCardCacheMetadata cacheMetadata;

// Hook so testing can wait until the MultiSseSupport is subscribed.
// Without this we get intermittent failures
private static volatile Runnable streamingMultiSseSupportSubscribedRunnable;
Expand Down Expand Up @@ -322,6 +325,13 @@ public void invokeJSONRPCHandler(@Body String body, RoutingContext rc) {
* <p>Returns the agent's capabilities and metadata in JSON format according to the
* A2A protocol specification. This endpoint is publicly accessible (no authentication).
*
* <p>Includes HTTP caching headers per A2A specification section 8.6:
* <ul>
* <li>{@code Cache-Control} - with max-age directive</li>
* <li>{@code ETag} - content hash for validation</li>
* <li>{@code Last-Modified} - timestamp when agent card was initialized</li>
* </ul>
*
* <p><b>Request:</b>
* <pre>{@code
* GET /.well-known/agent-card.json
Expand All @@ -331,6 +341,9 @@ public void invokeJSONRPCHandler(@Body String body, RoutingContext rc) {
* <pre>{@code
* HTTP/1.1 200 OK
* Content-Type: application/json
* Cache-Control: public, max-age=3600
* ETag: "a1b2c3d4..."
* Last-Modified: Mon, 17 Mar 2025 10:00:00 GMT
*
* {
* "name": "My Agent",
Expand All @@ -343,12 +356,15 @@ public void invokeJSONRPCHandler(@Body String body, RoutingContext rc) {
* }
* }</pre>
*
* @param rc the Vert.x routing context
* @return the agent card as a JSON string
* @throws JsonProcessingException if serialization fails
* @see JSONRPCHandler#getAgentCard()
*/
@Route(path = "/.well-known/agent-card.json", methods = Route.HttpMethod.GET, produces = APPLICATION_JSON)
public String getAgentCard() throws JsonProcessingException {
public String getAgentCard(RoutingContext rc) throws JsonProcessingException {
// Add caching headers per A2A specification section 8.6
cacheMetadata.getHttpHeadersMap().forEach((k, v) -> rc.response().putHeader(k, v));
return JsonUtil.toJson(jsonRpcHandler.getAgentCard());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,10 +380,14 @@ public void cancelTask(@Body String body, RoutingContext rc) {
*/
private void sendResponse(RoutingContext rc, @Nullable HTTPRestResponse response) {
if (response != null) {
rc.response()
var httpResponse = rc.response()
.setStatusCode(response.getStatusCode())
.putHeader(CONTENT_TYPE, response.getContentType())
.end(response.getBody());
.putHeader(CONTENT_TYPE, response.getContentType());

// Add any additional headers from the response
response.getHeaders().forEach(httpResponse::putHeader);

httpResponse.end(response.getBody());
} else {
rc.response().end();
}
Expand Down
190 changes: 190 additions & 0 deletions server-common/src/main/java/io/a2a/server/AgentCardCacheMetadata.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
package io.a2a.server;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;
import java.util.function.Consumer;

import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;

import org.jspecify.annotations.Nullable;

import io.a2a.jsonrpc.common.json.JsonProcessingException;
import io.a2a.jsonrpc.common.json.JsonUtil;
import io.a2a.server.config.A2AConfigProvider;
import io.a2a.spec.AgentCard;

/**
* Provides HTTP caching metadata for Agent Card responses.
*
* <p>This bean computes and caches HTTP caching headers (Cache-Control, ETag, Last-Modified)
* for the Agent Card endpoint as specified in the A2A protocol specification section 8.6.
*
* <p>The metadata is computed once at initialization:
* <ul>
* <li><b>Cache-Control:</b> Configured via {@code a2a.agent-card.cache.max-age} (default: 3600 seconds)</li>
* <li><b>ETag:</b> MD5 hash of the serialized Agent Card JSON</li>
* <li><b>Last-Modified:</b> Timestamp when the bean was initialized (RFC 1123 format)</li>
* </ul>
*
* <p>Since the Agent Card is {@code @ApplicationScoped}, these values remain stable
* throughout the application lifecycle unless the application is restarted.
*
* @see <a href="https://github.com/a2aproject/A2A/blob/main/docs/specification.md#86-caching">A2A Specification - Agent Card Caching</a>
*/
@ApplicationScoped
public class AgentCardCacheMetadata {

private static final String CONFIG_KEY_MAX_AGE = "a2a.agent-card.cache.max-age";
private static final String DEFAULT_MAX_AGE = "3600"; // 1 hour
private static final DateTimeFormatter RFC_1123_FORMATTER = DateTimeFormatter.RFC_1123_DATE_TIME;

@Inject
@PublicAgentCard
Instance<AgentCard> agentCardInstance;

@Inject
Instance<A2AConfigProvider> configInstance;

private @Nullable AgentCard agentCard;
private @Nullable A2AConfigProvider config;

@SuppressWarnings("NullAway") // Initialized in @PostConstruct when agentCard is available
private String etag;
@SuppressWarnings("NullAway") // Initialized in @PostConstruct when agentCard is available
private String lastModified;
@SuppressWarnings("NullAway") // Initialized in @PostConstruct when agentCard is available
private String cacheControl;

/**
* Package-private no-arg constructor for CDI.
*/
AgentCardCacheMetadata() {
// For CDI
}

/**
* Public constructor for testing purposes.
*
* @param agentCard the agent card
* @param config the configuration provider
*/
public AgentCardCacheMetadata(AgentCard agentCard, A2AConfigProvider config) {
this.agentCard = agentCard;
this.config = config;
init();
}

@PostConstruct
@SuppressWarnings("NullAway") // agentCard and config are guaranteed non-null in both paths
void init() {
// Handle two initialization paths:
// 1. CDI injection: get beans from Instance if available
// 2. Direct constructor: agentCard and config already set

if (agentCard == null && agentCardInstance != null) {
// CDI path - only initialize if AgentCard bean is available
if (agentCardInstance.isUnsatisfied() || configInstance.isUnsatisfied()) {
return;
}
this.agentCard = agentCardInstance.get();
this.config = configInstance.get();
}

// At this point, agentCard and config should be set (either via CDI or constructor)
if (agentCard == null || config == null) {
return;
}

// Calculate ETag from the serialized JSON representation
this.etag = calculateETag(agentCard);

// Set Last-Modified to the initialization time
this.lastModified = RFC_1123_FORMATTER.format(Instant.now().atZone(ZoneOffset.UTC));

// Configure Cache-Control with max-age directive
String maxAge = config.getOptionalValue(CONFIG_KEY_MAX_AGE).orElse(DEFAULT_MAX_AGE);
this.cacheControl = "public, max-age=" + maxAge;
}

/**
* Returns the ETag header value for the Agent Card.
*
* <p>The ETag is an MD5 hash of the serialized Agent Card JSON, quoted per HTTP specification.
*
* @return the ETag header value (e.g., {@code "a1b2c3d4..."})
*/
public String getETag() {
return etag;
}

/**
* Returns the Last-Modified header value for the Agent Card.
*
* <p>The timestamp represents when the bean was initialized, in RFC 1123 format.
*
* @return the Last-Modified header value (e.g., {@code "Mon, 17 Mar 2025 10:00:00 GMT"})
*/
public String getLastModified() {
return lastModified;
}

/**
* Returns the Cache-Control header value for the Agent Card.
*
* <p>The value includes {@code public} and a {@code max-age} directive configured
* via {@code a2a.agent-card.cache.max-age} (default: 3600 seconds).
*
* @return the Cache-Control header value (e.g., {@code "public, max-age=3600"})
*/
public String getCacheControl() {
return cacheControl;
}

/**
* Calculates an MD5 hash of the Agent Card JSON for use as an ETag.
*
* @param card the agent card to hash
* @return the hex-encoded MD5 hash, quoted per HTTP specification
*/
private String calculateETag(AgentCard card) {
try {
String json = JsonUtil.toJson(card);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(json.getBytes(StandardCharsets.UTF_8));
return "\"" + HexFormat.of().formatHex(hash) + "\"";
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 algorithm not available", e);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Failed to serialize Agent Card for ETag calculation", e);
}
}

/**
* Populates a map with header names and header values stored in this instance.
*
* @return a map of the headers
*/
public Map<String, String> getHttpHeadersMap() {
Map<String, String> headers = new HashMap<>();
if (cacheControl != null) {
headers.put("Cache-Control", cacheControl);
}
if (lastModified != null) {
headers.put("Last-Modified", lastModified);
}
if (etag != null) {
headers.put("ETag", etag);
}
return headers;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,48 @@ public void testGetExtendedAgentCard() throws A2AClientException {
assertTrue(agentCard.skills().isEmpty());
}

/**
* Tests that the Agent Card endpoint returns HTTP caching headers.
*
* <p>Per A2A specification section 8.6, Agent Card HTTP endpoints SHOULD include:
* <ul>
* <li>Cache-Control header with max-age directive (CARD-CACHE-001)</li>
* <li>ETag header for conditional request support (CARD-CACHE-002)</li>
* <li>Last-Modified header (CARD-CACHE-003, MAY requirement)</li>
* </ul>
*
* @throws Exception if HTTP request fails
*/
@Test
public void testAgentCardHeaders() throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + serverPort + "/.well-known/agent-card.json"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

assertEquals(200, response.statusCode());

// Verify Cache-Control header with max-age directive (CARD-CACHE-001)
Optional<String> cacheControl = response.headers().firstValue("Cache-Control");
assertTrue(cacheControl.isPresent(), "Cache-Control header should be present");
assertTrue(cacheControl.get().contains("max-age"),
"Cache-Control should contain max-age directive, got: " + cacheControl.get());

// Verify ETag header (CARD-CACHE-002)
Optional<String> etag = response.headers().firstValue("ETag");
assertTrue(etag.isPresent(), "ETag header should be present");
assertTrue(etag.get().startsWith("\"") && etag.get().endsWith("\""),
"ETag should be quoted per HTTP specification, got: " + etag.get());

// Verify Last-Modified header in RFC 1123 format (CARD-CACHE-003)
Optional<String> lastModified = response.headers().firstValue("Last-Modified");
assertTrue(lastModified.isPresent(), "Last-Modified header should be present");
assertTrue(lastModified.get().contains("GMT"),
"Last-Modified should be in RFC 1123 format (containing GMT), got: " + lastModified.get());
}

@Test
public void testSendMessageStreamNewMessageSuccess() throws Exception {
testSendStreamingMessage(false);
Expand Down
Loading
Loading