How does an instance detect capability drift between a cached A2A agent card and the live peer schema during task dispatch?

**Date of Record:** 2026 December 2 **Scope:** Applies to A2A v1.0 clients that cache remote `AgentCard` documents and dispatch tasks against a peer whose declared `skills`/`capabilities` may have changed since the card was fetched. Does not cover initial discovery of a never-before-seen agent, nor transport-level TLS failures.

Core Distinction

Agent card discovery is not a one-shot bootstrap step; it is a *lease* on a capability contract. The A2A v1.0 `AgentCard` is a snapshot—served at `/.well-known/agent.json`, carrying `skills[]`, `capabilities` (e.g. `streaming`, `pushNotifications`, `stateTransitionHistory`), and an `inputModes`/`outputModes` set. The failure this record isolates is **silent capability drift**: the client holds a card asserting a skill or modality the peer has since dropped or renamed, and the mismatch does not surface as a discovery error but as a *malformed task envelope* deep inside a `tasks/send` round-trip. The client's planner committed tokens and a plan against a contract that no longer exists, and the peer rejects the payload at the `Task` validation layer rather than at negotiation.

The non-obvious invariant: **card freshness and card validity are independent axes.** A card can be perfectly well-formed, correctly signed, and served with a fresh `ETag` while describing a schema the peer's *executor* no longer honors. Discovery success is not negotiation success.

What Was Observed

A three-hop orchestration: an orchestrator agent (O) resolved peer P's card once at session start, cached `skills: ["summarize", "translate"], inputModes: ["text/plain", "application/json"]`, and reused it across 40 dispatched tasks. At task 27, P had been redeployed with `translate` removed and `inputModes` narrowed to `["text/plain"]` only. P's `/.well-known/agent.json` updated correctly—new `ETag`, `translate` absent. But O never re-fetched: its cache had no TTL, only an invalidation hook on *transport* errors, and P answered every request with HTTP 200.

The trace at task 27:

  1. O's planner selected `translate` from its cached skill list and emitted a `Task` with `skillId: "translate"`, `message.parts: [{type: "data", mimeType: "application/json"}]`.
  2. P received the envelope. Because `translate` no longer existed, P's skill router fell through to a default handler that echoed a `TaskStatus: {state: "completed"}` with an empty `artifacts[]` array—no error, no `TaskState.failed`.
  3. O parsed the response, found zero artifacts, and its own downstream reducer interpreted "completed with no output" as a valid empty translation. The error compounded silently across tasks 27–40; the orchestrator produced 14 empty artifacts before a human noticed.

The critical detail: **P did not signal the drift.** A2A v1.0 permits a peer to respond to an unknown `skillId` with a generic failure, but the reference executor's default branch returned success. The client had no signal because the protocol layer was satisfied—the task *ran*, it just ran against nothing. This is the boundary: the failure lives in the gap between "card said this skill exists" and "peer's executor no longer routes it," and neither side is obligated by the wire format to close that gap.

Condition of Validity

The drift is only detectable—and only *dangerous*—under a specific conjunction:

Remove any one condition and the drift either doesn't occur or surfaces immediately. The invariant to enforce is therefore not "always re-fetch" (too costly) but **"a skill invocation must be validated against the response contract, not just the request contract."**

Decision Boundary

The architectural guardrail is a **capability lease with response-shape assertion**, bounding the drift window on two sides:

  1. **Freshness lease.** Cache the card with a `maxAge` (e.g. 300s) and a monotonic `fetchedAt`; on expiry, re-fetch and diff `skills`/`inputModes`/`capabilities`. A diff that removes a skill the current plan depends on must abort the plan *before* dispatch, not after.
  2. **Response-shape assertion.** Every dispatched task carries the expected artifact contract (derived from the card's skill declaration at dispatch time). On response, assert the contract: a `translate` task that returns `completed` with zero artifacts is a **contract violation**, escalated as a drift signal even though the peer reported success. This converts a silent data-loss failure into a loud, bounded one.

The decision boundary: *trust the card for planning, but never trust it for validation.* Planning reads the cached card (cheap, fast). Validation reads the live response shape (authoritative). When they disagree, the response wins and the cache is invalidated.

Operational Effect

With the lease + assertion in place, the same redeploy produces: task 27 dispatched against the stale card → P returns `completed` with empty artifacts → O's assertion fires (`expected ≥1 artifact for skill 'translate'`) → O raises a drift error, invalidates the card, re-fetches, sees `translate` gone, and re-plans to `summarize` or escalates. The blast radius shrinks from 14 silent empty artifacts to exactly one failed-and-recovered task.

The residual cost is one wasted round-trip per drift event and a periodic re-fetch. The invariant that makes this correct: **a capability card is a planning hint, not a runtime guarantee; the only authoritative statement of a peer's capability is its response to a concrete task.** Discovery negotiates intent; dispatch must verify it.

import time
from dataclasses import dataclass, field
from typing import Optional


class CapabilityDriftError(RuntimeError):
    """Raised when a peer's response contradicts the cached AgentCard contract."""
    pass


@dataclass
class AgentCard:
    skills: set[str]
    input_modes: set[str]
    etag: str
    fetched_at: float


@dataclass
class TaskResponse:
    state: str            # "completed" | "failed" | "working"
    artifacts: list = field(default_factory=list)
    reason: Optional[str] = None


class CardLease:
    """Caches an AgentCard with a freshness lease and response-shape assertion."""

    def __init__(self, fetch_fn, max_age_s: float = 300.0):
        self._fetch = fetch_fn          # () -> AgentCard
        self._max_age = max_age_s
        self._card: Optional[AgentCard] = None

    def _fresh(self) -> bool:
        if self._card is None:
            return False
        return (time.monotonic() - self._card.fetched_at) <= self._max_age

    def card(self) -> AgentCard:
        if not self._fresh():
            self._card = self._fetch()
        return self._card

    def invalidate(self) -> None:
        self._card = None

    def dispatch(self, skill: str, response: TaskResponse) -> TaskResponse:
        card = self.card()
        if skill not in card.skills:
            # Planning should have caught this; treat as drift, not a plan bug.
            self.invalidate()
            raise CapabilityDriftError(
                f"skill '{skill}' absent from card at dispatch; cache invalidated"
            )

        # Response-shape assertion: a completed task for a declared skill
        # MUST yield at least one artifact. Empty success == silent drift.
        if response.state == "completed" and not response.artifacts:
            self.invalidate()
            raise CapabilityDriftError(
                f"skill '{skill}' returned completed with 0 artifacts "
                f"(card etag={card.etag}); peer likely dropped capability"
            )

        if response.state == "failed" and response.reason and "skill" in response.reason.lower():
            self.invalidate()
            raise CapabilityDriftError(
                f"peer reported unknown skill '{skill}': {response.reason}"
            )

        return response