Skip to content

Commit 83d7f5d

Browse files
authored
feat(server): add caching headers to the agent card endpoint (a2aproject#1272)
## What Spec [8.6.1](https://a2a-protocol.org/latest/specification/#861-server-requirements) asks the card endpoint for a `Cache-Control` header with a `max-age`, and an `ETag` "derived from the Agent Card's `version` field or a hash of the card content". It sent neither, so every client refetched the whole card every time with no way to revalidate - for content the spec itself describes as changing "infrequently relative to the frequency at which clients may fetch it". One serving site, `agent_card_routes.py`. FastAPI re-wraps the same endpoint rather than building its own response, so there is no second variant to keep in step. ## Hash rather than version 8.6.1 allows either, but `card_modifier` can return a different card per request without touching `version`, and a validator that goes stale silently is worse than none. Hashing the card actually being served stays correct under it. There is a test for exactly that. `json.dumps(sort_keys=True)` rather than the RFC 8785 canonicalization this repo already has for signing: an ETag is opaque and is only ever compared against one this server produced, so determinism is the entire requirement, and JCS would add a depth limit and a failure mode for nothing. The signing canonicalizer also strips `signatures`, which would be wrong here - a card whose signatures changed is a different response body. ## Conditional requests `If-None-Match` is honoured with a 304. Emitting a validator and then ignoring the header that uses it would leave clients re-downloading the card anyway, which is the thing 8.6 exists to avoid. Handled per RFC 9110 8.2.2: comparison is weak, so `W/"x"` matches `"x"`, `*` matches, and a list is accepted. ## Cache-Control is opt-in 8.6.1 ties `max-age` to "the agent's expected update frequency", which the SDK cannot know - a card regenerated per deployment and one static for months want very different numbers, and a wrong guess baked into the library is a stale card nobody can explain. It is a parameter with no default. The `ETag` ships either way, so the endpoint satisfies 8.6.1's either/or unconfigured, and revalidation costs one 304. ## Result Clears `CARD-CACHE-001` (`should`) on all three bindings, and takes grpc to zero failures at every level.
1 parent 5751d31 commit 83d7f5d

3 files changed

Lines changed: 233 additions & 2 deletions

File tree

‎.github/actions/spelling/allow.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ Rundgren
139139
SECP
140140
SECP256R1
141141
SFIXED
142+
signings
142143
SLF
143144
socio
144145
sourced

‎src/a2a/server/routes/agent_card_routes.py‎

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import hashlib
2+
import json
3+
14
from collections.abc import Awaitable, Callable
25
from typing import TYPE_CHECKING, Any
36

@@ -28,12 +31,65 @@
2831
from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
2932

3033

34+
def _etag_for(card_dict: dict[str, Any]) -> str:
35+
"""A weak ETag derived from the card being served.
36+
37+
Hashed rather than taken from `version`, because `card_modifier` can
38+
return a different card per request without touching `version`.
39+
40+
`signatures` is excluded and the tag is weak, which is what makes
41+
revalidation work for a card signed per request. The signature covers
42+
the card with `signatures` stripped, so it carries no information the
43+
rest of the card does not -- but with a randomized algorithm such as
44+
ES256 it differs on every signing, and a strong tag over it would change
45+
on every request and never once match. A weak tag claims only semantic
46+
equivalence, which two signings of identical content have.
47+
48+
The cost is that a 304 leaves the client on the signature it already
49+
holds. That signature stays valid, since it covers content that has not
50+
changed.
51+
52+
`sort_keys` rather than RFC 8785 canonicalization: an ETag is opaque and
53+
is only ever compared against one this server produced, so determinism
54+
is the whole requirement, and JCS would add a depth limit and a failure
55+
mode for no gain.
56+
"""
57+
unsigned = {k: v for k, v in card_dict.items() if k != 'signatures'}
58+
body = json.dumps(unsigned, sort_keys=True, separators=(',', ':'))
59+
return f'W/"{hashlib.sha256(body.encode("utf-8")).hexdigest()}"'
60+
61+
62+
def _if_none_match_hits(header: str, etag: str) -> bool:
63+
"""Whether an If-None-Match header selects this entity (RFC 9110 8.2.2)."""
64+
candidates = [candidate.strip() for candidate in header.split(',')]
65+
if '*' in candidates:
66+
return True
67+
# If-None-Match uses the weak comparison function, so W/"x" and "x" are
68+
# the same entity on both sides of the comparison.
69+
return any(
70+
candidate.removeprefix('W/') == etag.removeprefix('W/')
71+
for candidate in candidates
72+
)
73+
74+
3175
def create_agent_card_routes(
3276
agent_card: AgentCard,
3377
card_modifier: Callable[[AgentCard], Awaitable[AgentCard]] | None = None,
3478
card_url: str = AGENT_CARD_WELL_KNOWN_PATH,
79+
cache_control: str | None = None,
3580
) -> list['Route']:
36-
"""Creates the Starlette Route for the A2A protocol agent card endpoint."""
81+
"""Creates the Starlette Route for the A2A protocol agent card endpoint.
82+
83+
Args:
84+
agent_card: The `AgentCard` to serve.
85+
card_modifier: Optional callback to adjust the card per request.
86+
card_url: Path the card is served from.
87+
cache_control: Value for the `Cache-Control` response header, e.g.
88+
``'public, max-age=3600'``. A `max-age` has to suit the agent's
89+
expected update frequency, which only the deployment knows, so
90+
there is no default. The `ETag` is sent either way, and
91+
revalidating against it costs one 304.
92+
"""
3793
if not _package_starlette_installed:
3894
raise ImportError(
3995
'The `starlette` package is required to use `create_agent_card_routes`. '
@@ -45,7 +101,19 @@ async def _get_agent_card(request: Request) -> Response:
45101
card_to_serve = agent_card
46102
if card_modifier:
47103
card_to_serve = await card_modifier(card_to_serve)
48-
return JSONResponse(agent_card_to_dict(card_to_serve))
104+
105+
card_dict = agent_card_to_dict(card_to_serve)
106+
headers = {'ETag': _etag_for(card_dict)}
107+
if cache_control:
108+
headers['Cache-Control'] = cache_control
109+
110+
if_none_match = request.headers.get('if-none-match')
111+
if if_none_match and _if_none_match_hits(
112+
if_none_match, headers['ETag']
113+
):
114+
return Response(status_code=304, headers=headers)
115+
116+
return JSONResponse(card_dict, headers=headers)
49117

50118
return [
51119
Route(

‎tests/server/routes/test_agent_card_routes.py‎

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1+
import copy
2+
13
from unittest.mock import AsyncMock
24

35
import pytest
46

57
from a2a.server.routes.agent_card_routes import create_agent_card_routes
68
from a2a.types.a2a_pb2 import AgentCard
9+
from a2a.utils.signing import create_agent_card_signer
10+
from cryptography.hazmat.primitives import serialization
11+
from cryptography.hazmat.primitives.asymmetric import ec
712
from starlette.applications import Starlette
813
from starlette.testclient import TestClient
914

@@ -69,3 +74,160 @@ def test_agent_card_custom_url(agent_card):
6974
assert client.get('/.well-known/agent-card.json').status_code == 404
7075
# Check that custom returns 200
7176
assert client.get(custom_url).status_code == 200
77+
78+
79+
def card_client(**kwargs) -> TestClient:
80+
return TestClient(
81+
Starlette(routes=create_agent_card_routes(**kwargs)),
82+
# Otherwise httpx resends the ETag it already saw and turns a
83+
# deliberate unconditional GET into a 304.
84+
headers={'cache-control': 'no-cache'},
85+
)
86+
87+
88+
def test_response_carries_a_weak_etag():
89+
response = card_client(agent_card=AgentCard(name='a', version='1')).get(
90+
'/.well-known/agent-card.json'
91+
)
92+
93+
assert response.status_code == 200
94+
assert response.headers['etag'].startswith('W/"')
95+
96+
97+
def test_cache_control_is_sent_only_when_configured():
98+
url = '/.well-known/agent-card.json'
99+
card = AgentCard(name='a', version='1')
100+
101+
assert 'cache-control' not in card_client(agent_card=card).get(url).headers
102+
configured = card_client(
103+
agent_card=card, cache_control='public, max-age=3600'
104+
).get(url)
105+
assert configured.headers['cache-control'] == 'public, max-age=3600'
106+
107+
108+
def test_etag_changes_with_the_card():
109+
url = '/.well-known/agent-card.json'
110+
111+
first = card_client(agent_card=AgentCard(name='a', version='1')).get(url)
112+
second = card_client(agent_card=AgentCard(name='b', version='1')).get(url)
113+
114+
assert first.headers['etag'] != second.headers['etag']
115+
116+
117+
def test_etag_tracks_the_modified_card_not_the_original():
118+
"""card_modifier can vary the body per request, so the hash must follow it."""
119+
url = '/.well-known/agent-card.json'
120+
121+
async def rename(card: AgentCard) -> AgentCard:
122+
return AgentCard(name='modified', version=card.version)
123+
124+
plain = card_client(agent_card=AgentCard(name='a', version='1')).get(url)
125+
modified = card_client(
126+
agent_card=AgentCard(name='a', version='1'), card_modifier=rename
127+
).get(url)
128+
129+
assert plain.headers['etag'] != modified.headers['etag']
130+
131+
132+
@pytest.mark.parametrize(
133+
'make_header',
134+
[
135+
lambda etag: etag,
136+
# Weak comparison, so the strong spelling of the same tag matches.
137+
lambda etag: etag.removeprefix('W/'),
138+
lambda etag: '*',
139+
lambda etag: f'"other", {etag}',
140+
],
141+
ids=['exact', 'strong-spelling', 'star', 'list'],
142+
)
143+
def test_matching_if_none_match_gets_304(make_header):
144+
url = '/.well-known/agent-card.json'
145+
client = card_client(agent_card=AgentCard(name='a', version='1'))
146+
etag = client.get(url).headers['etag']
147+
148+
response = client.get(url, headers={'If-None-Match': make_header(etag)})
149+
150+
assert response.status_code == 304
151+
assert response.content == b''
152+
153+
154+
def test_stale_if_none_match_gets_the_card():
155+
url = '/.well-known/agent-card.json'
156+
client = card_client(agent_card=AgentCard(name='a', version='1'))
157+
158+
response = client.get(url, headers={'If-None-Match': '"stale"'})
159+
160+
assert response.status_code == 200
161+
assert response.json()['name'] == 'a'
162+
163+
164+
def test_a_card_re_signed_per_request_still_revalidates():
165+
"""The card_modifier that re-signs on every request must still get a 304.
166+
167+
ES256 signatures are randomized, so an unchanged card signs differently
168+
every time. Hashing the signature in would produce a tag that changes on
169+
every request and never once matches.
170+
"""
171+
url = '/.well-known/agent-card.json'
172+
private_key = ec.generate_private_key(ec.SECP256R1()).private_bytes(
173+
serialization.Encoding.PEM,
174+
serialization.PrivateFormat.PKCS8,
175+
serialization.NoEncryption(),
176+
)
177+
sign = create_agent_card_signer(
178+
signing_key=private_key,
179+
protected_header={
180+
'alg': 'ES256',
181+
'kid': 'k',
182+
'jku': None,
183+
'typ': 'JOSE',
184+
},
185+
)
186+
187+
async def sign_per_request(card: AgentCard) -> AgentCard:
188+
return sign(copy.deepcopy(card))
189+
190+
client = card_client(
191+
agent_card=AgentCard(name='a', version='1'),
192+
card_modifier=sign_per_request,
193+
)
194+
first = client.get(url)
195+
second = client.get(url)
196+
197+
# Same card, different signature, so the bodies differ byte for byte.
198+
assert first.json()['signatures'] != second.json()['signatures']
199+
assert first.headers['etag'] == second.headers['etag']
200+
assert (
201+
client.get(
202+
url, headers={'If-None-Match': first.headers['etag']}
203+
).status_code
204+
== 304
205+
)
206+
207+
208+
def test_etag_still_changes_when_a_signed_card_changes():
209+
"""Excluding signatures must not blind the tag to real content changes."""
210+
url = '/.well-known/agent-card.json'
211+
sign = create_agent_card_signer(
212+
signing_key='a-secret-long-enough-for-hs256-hmac',
213+
protected_header={
214+
'alg': 'HS256',
215+
'kid': 'k',
216+
'jku': None,
217+
'typ': 'JOSE',
218+
},
219+
)
220+
221+
def signed_client(name: str) -> TestClient:
222+
async def modifier(card: AgentCard) -> AgentCard:
223+
return sign(copy.deepcopy(card))
224+
225+
return card_client(
226+
agent_card=AgentCard(name=name, version='1'),
227+
card_modifier=modifier,
228+
)
229+
230+
first = signed_client('a').get(url)
231+
second = signed_client('b').get(url)
232+
233+
assert first.headers['etag'] != second.headers['etag']

0 commit comments

Comments
 (0)