Skip to content
A2A 1.0: Sign and Verify Agent Cards Before Delegating — ContentBuffer guide

A2A 1.0: Sign and Verify Agent Cards Before Delegating

K
Kodetra Technologies··11 min read Intermediate

Summary

Publish a JWS-signed A2A v1.0 Agent Card in Python and refuse any card you cannot verify.

On August 17, Google's Agent2Agent protocol moved out of the Linux Foundation's general portfolio and became a hosted project of the Agentic AI Foundation, the same body that stewards MCP. The foundation has gone from under 40 member organizations at its December 2025 launch to more than 250, with Google, Microsoft, Amazon, Anthropic, OpenAI, Bloomberg, Shopify and Block on the list. A2A and MCP now sit under one roof: MCP is how an agent reaches tools, A2A is how an agent reaches another agent.

That governance news is the headline. The part that actually changes your code is quieter. A2A hit v1.0, and the Agent Card — the JSON business card every agent publishes so other agents can find it — was restructured with several breaking changes. v1.0 also added the thing people had been asking for since 2025: cryptographically signed Agent Cards, using JWS over RFC 8785 canonical JSON.

This matters because an Agent Card is an instruction to send work somewhere. If an attacker can edit the url field on a card your orchestrator fetches, they redirect your invoice-settlement traffic to their endpoint and you never see a stack trace. Signing the card closes that hole. This guide walks the whole loop in Python: build a v1.0 card, canonicalize it correctly, sign it, serve it, and write a client that refuses to delegate to any card it cannot verify. Every snippet below was run against a2a-sdk 1.1.2.


What actually changed in the Agent Card

If you built against v0.3, four things will bite you. The card no longer has a top-level url, and preferredTransport plus additionalInterfaces collapsed into a single ordered supportedInterfaces[] array where each entry carries its own protocolVersion. Protocol version is now per-interface, not per-card.

v0.3.0v1.0Why
url (top level)supportedInterfaces[0].urlOne agent, several bindings, ordered by preference
preferredTransportsupportedInterfaces[].protocolBindingPreference is now array order
additionalInterfacesmerged into supportedInterfaces[]One list instead of two
protocolVersion (card)supportedInterfaces[].protocolVersionLets one card serve 0.3 and 1.0 endpoints
supportsAuthenticatedExtendedCardcapabilities.extendedAgentCardCapabilities grouped together
no signaturessignatures[]JWS + RFC 8785 canonicalization

Two more v1.0-wide changes will show up the moment you send a message rather than just read a card. Enum values moved to SCREAMING_SNAKE_CASE — "completed" is now "TASK_STATE_COMPLETED", "user" is now "ROLE_USER". And the kind discriminator is gone everywhere; a Part is now discriminated by which member is present (text, raw, url, or data), so if part.kind == "text" becomes if "text" in part.


Prerequisites

  • Python 3.10 or newer
  • pip install a2a-sdk rfc8785 cryptography — the examples below were run on a2a-sdk 1.1.2, pydantic 2.13.4
  • Rough familiarity with JWS (RFC 7515). You do not need to have implemented one before
  • No API keys, no model calls. This is all protocol and crypto, so it runs offline

One surprise before you start: in the 1.x SDK, a2a.types objects are protobuf messages, not Pydantic models. v1.0 promoted a2a.proto to the normative source of truth for the data model, and the Python types followed. If you reach for .model_dump() you will get an AttributeError. You want google.protobuf.json_format.MessageToDict.


Step 1: Build a v1.0 Agent Card

Start with a realistic agent rather than a hello-world echo, because the security argument only lands when there is money on the other end of the delegation. Here is an accounts-payable agent that settles supplier invoices.

from a2a.types import (
    AgentCard, AgentSkill, AgentCapabilities, AgentInterface, AgentCardSignature,
)

def build_card(base_url: str) -> AgentCard:
    skill = AgentSkill(
        id="settle_invoice",
        name="Settle Invoice",
        description="Validates an invoice against a PO and schedules payment.",
        tags=["finance", "ap", "invoice"],
        examples=["settle INV-4471 against PO-90210"],
        input_modes=["application/json"],
        output_modes=["application/json"],
    )
    return AgentCard(
        name="Invoice Settlement Agent",
        description="Settles supplier invoices with PO matching.",
        version="1.4.0",
        default_input_modes=["application/json"],
        default_output_modes=["application/json"],
        capabilities=AgentCapabilities(streaming=True, extended_agent_card=True),
        supported_interfaces=[
            AgentInterface(
                url=base_url,
                protocol_binding="JSONRPC",
                protocol_version="1.0",
            )
        ],
        skills=[skill],
    )

Note the field names are snake_case in Python and camelCase on the wire. protobuf handles that translation for you, but it means the JSON you sign is not a naive dump of the Python object.

from google.protobuf.json_format import MessageToDict

def card_to_json(card: AgentCard) -> dict:
    # camelCase JSON, default/zero values omitted -- this is the wire format
    return MessageToDict(card)

Step 2: Canonicalize with RFC 8785, not sort_keys

A signature is over bytes. Two JSON serializers that produce semantically identical documents produce different bytes, and then verification fails for no visible reason. RFC 8785 (the JSON Canonicalization Scheme) pins those bytes down: lexicographic key order by UTF-16 code unit, no insignificant whitespace, ECMAScript number formatting, minimal string escaping.

People reach for json.dumps(doc, sort_keys=True) and assume that is close enough. It is not. Run this:

import json, rfc8785

doc = {"name": "Fakturaflöde", "score": 1.0, "z": 1, "a": 2}
print("json.dumps sort_keys:", json.dumps(doc, sort_keys=True).encode())
print("rfc8785 JCS         :", rfc8785.dumps(doc))

Output:

json.dumps sort_keys: b'{"a": 2, "name": "Fakturafl\\u00f6de", "score": 1.0, "z": 1}'
rfc8785 JCS         : b'{"a":2,"name":"Fakturafl\xc3\xb6de","score":1,"z":1}'

Three divergences in one four-key object: spaces after separators, \u00f6 escaping instead of raw UTF-8, and 1.0 instead of 1. Any one of them breaks a signature. Use the library.


Step 3: Sign the card as a JWS

The signing procedure is a detached-payload JWS. Strip signatures from the card, canonicalize what is left, and sign BASE64URL(protected) || "." || BASE64URL(canonical). The signature goes back onto the card as an AgentCardSignature, which carries the base64url-encoded protected header and the base64url-encoded signature.

import base64
import rfc8785
from cryptography.hazmat.primitives.asymmetric import ec, utils as asym_utils
from cryptography.hazmat.primitives import hashes

def b64u(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()

def b64u_dec(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

def signing_input(card_json: dict, protected: dict) -> tuple[bytes, str]:
    payload = {k: v for k, v in card_json.items() if k != "signatures"}
    canonical = rfc8785.dumps(payload)          # RFC 8785 JCS bytes
    p = b64u(rfc8785.dumps(protected))
    return f"{p}.{b64u(canonical)}".encode("ascii"), p

def sign_card(card: AgentCard, key, kid: str) -> AgentCard:
    protected = {"alg": "ES256", "kid": kid, "typ": "JOSE"}
    si, p = signing_input(card_to_json(card), protected)
    der = key.sign(si, ec.ECDSA(hashes.SHA256()))
    # JWS wants raw R||S, not the DER that `cryptography` hands back
    r, s = asym_utils.decode_dss_signature(der)
    raw = r.to_bytes(32, "big") + s.to_bytes(32, "big")
    card.signatures.append(AgentCardSignature(protected=p, signature=b64u(raw)))
    return card

The decode_dss_signature line is the one people skip. cryptography returns ECDSA signatures in DER, and JWS ES256 expects a fixed 64-byte concatenation of R and S. Hand the DER blob straight to a JOSE verifier and it rejects a perfectly valid signature.

Signing the card and dumping it gives you this — note the signatures array at the bottom:

{
  "name": "Invoice Settlement Agent",
  "description": "Settles supplier invoices with PO matching.",
  "supportedInterfaces": [
    {
      "url": "https://ap.acme.internal/a2a",
      "protocolBinding": "JSONRPC",
      "protocolVersion": "1.0"
    }
  ],
  "version": "1.4.0",
  "capabilities": { "streaming": true, "extendedAgentCard": true },
  "defaultInputModes": ["application/json"],
  "defaultOutputModes": ["application/json"],
  "skills": [ { "id": "settle_invoice", "name": "Settle Invoice", "...": "..." } ],
  "signatures": [
    {
      "protected": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImFwLTIwMjYtMDgiLCJ0eXAiOiJKT1NFIn0",
      "signature": "zS1n73VrkzRgaQG1-9qegUgTKC74RWgcL9pT4MNKS-jvre_c5m1HAqlhYo-7S9mckCKcw7eA0M8A25HyEDxlDg"
    }
  ]
}

Step 4: Verify before you delegate

Verification is the same three steps in reverse, plus one decision that matters more than the crypto: an unknown kid is a failure, not a pass. If you cannot map the key id in the protected header to a key you already trust, the card is untrusted. Do not fetch the key from a URL the card itself supplies — that defeats the entire exercise.

import json

def verify_card(card_json: dict, jwks: dict) -> bool:
    for sig in card_json.get("signatures", []):
        protected = json.loads(b64u_dec(sig["protected"]))
        pub = jwks.get(protected.get("kid"))
        if pub is None:
            continue                                   # unknown key -> not trusted
        payload = {k: v for k, v in card_json.items() if k != "signatures"}
        si = f'{sig["protected"]}.{b64u(rfc8785.dumps(payload))}'.encode("ascii")
        raw = b64u_dec(sig["signature"])
        der = asym_utils.encode_dss_signature(
            int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big")
        )
        try:
            pub.verify(der, si, ec.ECDSA(hashes.SHA256()))
            return True
        except Exception:
            return False
    return False

Three cases, actual output from running it:

verify(untouched)     -> True
verify(tampered url)  -> False
verify(unknown kid)   -> False

The tampered case flipped one character in supportedInterfaces[0].url to point at https://evil.example.com/a2a. That is precisely the attack signing exists to stop, and it fails closed.


Step 5: Serve and discover at the well-known URI

The standard discovery path in v1.0 is https://{domain}/.well-known/agent-card.json, per RFC 8615. If you are migrating, note it is agent-card.json, not the agent.json that circulated in early 2025 write-ups.

import json, urllib.request

WELL_KNOWN = "/.well-known/agent-card.json"

def fetch_card(origin: str) -> dict:
    req = urllib.request.Request(origin.rstrip("/") + WELL_KNOWN,
                                 headers={"Accept": "application/json"})
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.loads(r.read())

def pick_interface(card: dict, binding: str = "JSONRPC") -> dict:
    for iface in card.get("supportedInterfaces", []):   # ordered by server preference
        if iface.get("protocolBinding") == binding and iface.get("protocolVersion") == "1.0":
            return iface
    raise RuntimeError(f"no {binding} 1.0 interface on card {card.get('name')!r}")

def has_skill(card: dict, skill_id: str) -> bool:
    return any(s.get("id") == skill_id for s in card.get("skills", []))

def resolve(origin: str, jwks: dict, skill_id: str) -> str:
    card = fetch_card(origin)
    if not verify_card(card, jwks):
        raise PermissionError(f"unsigned or untrusted card from {origin}")
    if not has_skill(card, skill_id):
        raise LookupError(f"{card['name']} does not advertise {skill_id}")
    return pick_interface(card)["url"]

Iterating supportedInterfaces in order rather than grabbing index 0 is deliberate. Array order is the server's stated preference, but your client may only speak JSON-RPC while the server prefers gRPC. Scan for the binding you support, in the order the server ranked them.


Worked example: the whole loop, end to end

Serve the signed card from a stdlib HTTP server on localhost and point the resolver at it. This is the version I ran.

import threading, http.server, socketserver
from cryptography.hazmat.primitives.asymmetric import ec

PORT = 8931
key = ec.generate_private_key(ec.SECP256R1())
JWKS = {"ap-2026-08": key.public_key()}          # pinned out of band
CARD = MessageToDict(sign_card(build_card(f"http://127.0.0.1:{PORT}/a2a"), key, "ap-2026-08"))
BODY = json.dumps(CARD).encode()

class H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path != "/.well-known/agent-card.json":
            self.send_error(404); return
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Cache-Control", "max-age=3600")
        self.send_header("ETag", '"1.4.0"')       # derive the ETag from card version
        self.send_header("Content-Length", str(len(BODY)))
        self.end_headers(); self.wfile.write(BODY)
    def log_message(self, *a): pass

socketserver.TCPServer.allow_reuse_address = True
srv = socketserver.TCPServer(("127.0.0.1", PORT), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()

print("endpoint:", resolve(f"http://127.0.0.1:{PORT}", JWKS, "settle_invoice"))

try:
    resolve(f"http://127.0.0.1:{PORT}", {"someone-else": key.public_key()}, "settle_invoice")
except PermissionError as e:
    print("wrong key: refused ->", e)

try:
    resolve(f"http://127.0.0.1:{PORT}", JWKS, "wire_transfer")
except LookupError as e:
    print("missing skill: refused ->", e)

srv.shutdown()

Output:

endpoint: http://127.0.0.1:8931/a2a
wrong key: refused -> unsigned or untrusted card from http://127.0.0.1:8931
missing skill: refused -> Invoice Settlement Agent does not advertise wire_transfer

Three outcomes, three correct behaviors. The card verifies and yields an endpoint; a client holding the wrong trust anchor refuses; and a request for a skill the agent never advertised is refused before a single byte of work is delegated. That last check is cheap and worth having — it turns a runtime error deep inside another org's agent into a local exception with a clear message.


The default-value trap that silently breaks every signature

This one cost me the most time, and it is specific to the protobuf-backed SDK. MessageToDict omits fields at their default value. Turn on always_print_fields_with_no_presence=True — which looks like a harmless verbosity flag — and the JSON grows extra keys. Different keys, different canonical bytes, dead signature.

served_by_the_book   = MessageToDict(card)
served_with_defaults = MessageToDict(card, always_print_fields_with_no_presence=True)

print("keys added by the flag:",
      [k for k in served_with_defaults if k not in served_by_the_book])
print("verify(as signed)        ->", verify_card(served_by_the_book, jwks))
print("verify(defaults printed) ->", verify_card(served_with_defaults, jwks))

Output:

keys added by the flag: ['securitySchemes', 'securityRequirements']
verify(as signed)        -> True
verify(defaults printed) -> False

Two empty collections appeared and the signature died. The rule that keeps you out of this: serialize once, and serve the exact bytes you signed. Do not re-serialize the card per request from the in-memory object; sign it, cache the resulting bytes, and write those bytes to the socket. That also makes your ETag honest.


Other pitfalls worth knowing before you ship

  • DER vs raw signatures. cryptography emits DER, JWS ES256 wants 64 raw bytes. Convert with decode_dss_signature / encode_dss_signature or every cross-language verifier rejects you.
  • Unknown kid must fail. A verifier that treats a missing key as "no signature required" is worse than no verifier, because it gives you a false sense of coverage.
  • Never resolve keys from the card. Trust anchors come from your registry, config, or an x5c chain you already trust — never from a URL the card supplies.
  • Signing the wrong shape. Sign the camelCase wire JSON, not preserving_proto_field_name=True output. The verifier on the other side sees camelCase.
  • Enum strings. Anywhere you hand-build JSON, use ROLE_USER and TASK_STATE_COMPLETED. The old lowercase kebab values are gone in 1.0.
  • The kind field is gone. Discriminate parts by member presence. Old parsers checking part["kind"] raise KeyError on every v1.0 message.
  • Cache with intent. Send Cache-Control and an ETag derived from the card version; clients should use If-None-Match rather than re-pulling the full card. Rotating a key means bumping the version so caches actually expire.

Migrating a v0.3 card

If you already publish a v0.3 card, the shape translation is mechanical. This function moves the endpoint fields into supportedInterfaces and relocates the extended-card flag:

def migrate(old: dict) -> dict:
    new = {k: v for k, v in old.items()
           if k not in {"url", "preferredTransport", "additionalInterfaces",
                        "protocolVersion", "supportsAuthenticatedExtendedCard"}}
    ifaces = []
    if old.get("url"):
        ifaces.append({"url": old["url"],
                       "protocolBinding": old.get("preferredTransport", "JSONRPC"),
                       "protocolVersion": "1.0"})
    for extra in old.get("additionalInterfaces", []):
        ifaces.append({"url": extra["url"],
                       "protocolBinding": extra.get("transport", "JSONRPC"),
                       "protocolVersion": "1.0"})
    new["supportedInterfaces"] = ifaces
    caps = dict(new.get("capabilities", {}))
    if old.get("supportsAuthenticatedExtendedCard"):
        caps["extendedAgentCard"] = True
    new["capabilities"] = caps
    return new

Fed a v0.3 card with a JSON-RPC primary and a gRPC secondary, it emits both as ordered interfaces:

"supportedInterfaces": [
  { "url": "https://ap.acme.internal/a2a",  "protocolBinding": "JSONRPC", "protocolVersion": "1.0" },
  { "url": "https://ap.acme.internal/grpc", "protocolBinding": "GRPC",    "protocolVersion": "1.0" }
],
"capabilities": { "streaming": true, "extendedAgentCard": true }

Because protocolVersion is per-interface now, you can keep a 0.3 endpoint listed alongside a 1.0 one during a rollout and let clients pick. That is the migration path the restructure was designed for.


Quick reference

ThingValue
Discovery path/.well-known/agent-card.json (RFC 8615)
CanonicalizationRFC 8785 JCS — rfc8785.dumps()
Signature formatJWS detached payload (RFC 7515), ES256
Signing inputb64u(protected) + "." + b64u(JCS(card − signatures))
Signature bytesraw R‖S, 64 bytes — not DER
Endpoint fieldsupportedInterfaces[].url
Binding fieldsupportedInterfaces[].protocolBinding
Version fieldsupportedInterfaces[].protocolVersion
Extended card flagcapabilities.extendedAgentCard
Task state enumTASK_STATE_COMPLETED etc.
Role enumROLE_USER, ROLE_AGENT
Part discriminationmember presence: text / raw / url / data
Python serializationMessageToDict (protobuf), not .model_dump()

Next steps

  • Put the verifier in front of every delegation path you already have, then make it fail closed. Log refusals for a week before you enforce, so you learn which of your partners have not signed yet.
  • Move trust anchors out of a dict and into a real registry — the spec explicitly leaves registry APIs unstandardized, so a signed JWKS file in config is a legitimate starting point.
  • Add key rotation: publish two signatures with different kid values during an overlap window, and bump the card version so caches refresh.
  • Wire the resolved endpoint into an actual SendMessage call and watch for the enum and Part changes — that is where the rest of the v1.0 migration surfaces.
  • If you also publish MCP servers, apply the same instinct there. Both protocols now live under the Agentic AI Foundation, and both hand an agent a description of what to trust.

Sources

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,604 newsletter subscribers.

Also get