Build, Deploy and Troubleshoot A2A

A working agent, a client that drives it through a full task, the deployment decisions that matter and a table of symptoms with their causes.

BeginnerIntermediateExpert · 15 min read · Last updated:

In short

An A2A server is a web service with three parts: a published Agent Card, an executor that turns messages into task states and artifacts, and a task store that remembers them. Most failures come from the executor not following the task lifecycle, from task state that is private to one copy of the service, or from a client and server speaking different protocol versions.

What you will learn: how to design the contract, write and run a server, drive it from a client, stream progress, deploy more than one copy and read error symptoms.
Prerequisites: What Is A2A? Agent Cards, Tasks and Messages for the objects and states, and basic Python.

Versions used

Written for protocol version 1.0 and run in November 2026 with Python package a2a-sdk 1.3.1. The behavior described under troubleshooting is what that release did; other SDKs and later releases may differ.

Beginner Design before code

Should this be an A2A agent?

A2A earns its keep when the other side is a separate system that takes time, may need to ask questions and keeps its inner workings to itself. If you only need to fetch a record or run a calculation, an ordinary API or an MCP tool is smaller and easier to test. See MCP vs A2A vs REST for the comparison.

QuestionPoints toward A2APoints away
Who owns it?Another team or companyThe same codebase
How long does work take?Seconds to daysMilliseconds
Can it need more information?Yes, part way throughAll inputs are known up front
Is the method private?The caller should not care howThe caller controls each step

Write the contract first

Before any code, write one page that a caller could build against. The Agent Card carries the machine-readable part; the rest belongs in your documentation.

DecideExample for an invoice checker
SkillCompare an invoice amount with its purchase order
Required inputOrder number, amount, currency
Questions it may askWhich currency?
OutputA data artifact named match-report with order, currency and difference
Reasons to rejectNo known purchase order
What it will never doApprove or pay the invoice
Time limit and retentionHow long a task may stay open, and how long results are kept

The path of one request

Clientreads the card
Request handlerchecks the protocol
Executoryour logic
Task storeremembers state
The SDK supplies the handler. You write the executor and choose the store.
Intermediate Build and call it

The server

Install the SDK with its web server support, plus a server to run it:

pip install "a2a-sdk[http-server]" uvicorn httpx2

The httpx2 package serves the in-memory test client that the scripts use; without it, newer releases of Starlette print a deprecation warning. The outputs on these pages are standard output only. Log messages and warnings may also appear on the error stream.

Save the following as agent.py. There is no model in it, so you can see the protocol behavior without cost or randomness. In a real agent, the lines that pick out the order, currency and amount are where a model and its tools would work, followed by the same checks in code.

"""A small A2A agent: checks an invoice and asks for a missing currency."""
from a2a.auth.user import UnauthenticatedUser, User
from a2a.helpers.proto_helpers import (new_data_part, new_task_from_user_message,
                                       new_text_part)
from a2a.server.agent_execution import AgentExecutor
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.routes.common import DefaultServerCallContextBuilder
from a2a.server.tasks import InMemoryTaskStore, TaskUpdater
from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill
from starlette.applications import Starlette

ORDERS = {"PO-7731": 1200.0}
CARD = AgentCard(
    name="Invoice Checker", version="1.0.0",
    description="Checks a supplier invoice against its purchase order.",
    supported_interfaces=[AgentInterface(
        url="http://127.0.0.1:9000/a2a", protocol_binding="JSONRPC",
        protocol_version="1.0")],
    capabilities=AgentCapabilities(streaming=True),
    default_input_modes=["text/plain"],
    default_output_modes=["application/json"],
    skills=[AgentSkill(id="match", name="Match an invoice", tags=["finance"],
                       description="Compare an amount with a purchase order.")])


class InvoiceAgent(AgentExecutor):
    async def execute(self, context, event_queue):
        if context.current_task is None:          # first message: open a task
            await event_queue.enqueue_event(
                new_task_from_user_message(context.message))
        task = TaskUpdater(event_queue, context.task_id, context.context_id)
        await task.start_work()
        history = list(context.current_task.history) if context.current_task else []
        said = [p.text for m in history + [context.message] if m.role == 1
                for p in m.parts]
        words = " ".join(said).split()
        order = next((w for w in words if w in ORDERS), None)
        if order is None:
            return await task.reject(task.new_agent_message(
                [new_text_part("No known purchase order was mentioned.")]))
        currency = next((w for w in words if w in {"EUR", "USD"}), None)
        if currency is None:
            return await task.requires_input(task.new_agent_message(
                [new_text_part("Which currency is the invoice in?")]))
        amount = next(float(w) for w in words if w.replace(".", "").isdigit())
        await task.add_artifact(name="match-report", parts=[new_data_part(
            {"order": order, "currency": currency,
             "difference": amount - ORDERS[order]})])
        await task.complete()

    async def cancel(self, context, event_queue):
        await TaskUpdater(event_queue, context.task_id, context.context_id).cancel()


class DemoUser(User):
    def __init__(self, name):
        self.name = name

    @property
    def is_authenticated(self):
        return True

    @property
    def user_name(self):
        return self.name


class DemoIdentity(DefaultServerCallContextBuilder):
    """Trusts a header. A real server validates a token here instead."""

    def build_user(self, request):
        name = request.headers.get("x-demo-user")
        return DemoUser(name) if name else UnauthenticatedUser()


def build_app(identity=None, card=CARD, middleware=None, **handler_options):
    handler = DefaultRequestHandler(
        agent_executor=InvoiceAgent(), task_store=InMemoryTaskStore(),
        agent_card=card, **handler_options)
    return Starlette(middleware=middleware, routes=[
        *create_agent_card_routes(card),
        *create_jsonrpc_routes(handler, "/a2a",
                               context_builder=identity or DemoIdentity())])
PieceIts jobWatch for
CARDAdvertises address, version, features and skillsThe address must be the one clients can reach, not an internal host name
executeRuns for every message to a taskCreate the task first; finish in a clear state
TaskUpdaterPublishes status changes and artifactsOne updater per task and context
requires_inputPauses and asks a questionRead the earlier history when the answer arrives
rejectDeclines work the agent will not doSay why in a message
DemoIdentityTells the SDK who is callingIt trusts a header. Replace it before any real use
This server is not secure

It believes whatever the caller says about their name and does not refuse anonymous callers. The security page adds authentication, ownership checks and callback screening to this same agent.

The client

This script calls the application in memory, using the real request format. It walks a task through a question and an answer, then pokes at the edges. Save it as client_demo.py next to the server.

"""Drive the agent over JSON-RPC, in process, as two different callers."""
from starlette.testclient import TestClient

from agent import build_app


def call(http, method, params, user="ana", version="1.0"):
    headers = {"x-demo-user": user, "A2A-Version": version}
    body = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
    return http.post("/a2a", json=body, headers=headers).json()


def message(number, text, task_id=None):
    data = {"messageId": f"m-{number}", "role": "ROLE_USER",
            "parts": [{"text": text}]}
    if task_id:
        data["taskId"] = task_id
    return {"message": data}


def state(task):
    return task["status"]["state"].replace("TASK_STATE_", "")


def failure(reply):
    text = reply["error"]["message"]
    for word in text.split():
        if word.count("-") == 4:                   # hide random task ids
            text = text.replace(word, "<task-id>")
    return f"error {reply['error']['code']}: {text}"


def demo():
    with TestClient(build_app()) as http:
        card = http.get("/.well-known/agent-card.json").json()
        print("card:", card["name"], "| skills:", [s["id"] for s in card["skills"]])

        first = call(http, "SendMessage",
                     message(1, "Check 1320 against PO-7731"))["result"]["task"]
        print("1:", state(first), "-", first["status"]["message"]["parts"][0]["text"])

        second = call(http, "SendMessage",
                      message(2, "EUR", first["id"]))["result"]["task"]
        print("2:", state(second), "-", second["artifacts"][0]["parts"][0]["data"])

        again = call(http, "SendMessage", message(3, "USD", first["id"]))
        print("message to a finished task ->", failure(again))

        other = call(http, "GetTask", {"id": first["id"]}, user="ben")
        print("another user reads it     ->", failure(other))

        cancel = call(http, "CancelTask", {"id": first["id"]})
        print("cancel a finished task    ->", failure(cancel))

        old = call(http, "GetTask", {"id": first["id"]}, version="0.1")
        print("unsupported version       ->", failure(old))

        bad = call(http, "SendMessage",
                   message(4, "Check 50 against PO-1"))["result"]["task"]
        print("unknown order             ->", state(bad))


if __name__ == "__main__":
    demo()

Output:

card: Invoice Checker | skills: ['match']
1: INPUT_REQUIRED - Which currency is the invoice in?
2: COMPLETED - {'difference': 120.0, 'order': 'PO-7731', 'currency': 'EUR'}
message to a finished task -> error -32004: Task <task-id> is in terminal state: TASK_STATE_COMPLETED
another user reads it     -> error -32001: Task not found
cancel a finished task    -> error -32002: Task cannot be canceled
unsupported version       -> error -32009: A2A version '0.1' is not supported by this handler. Expected version '1.0'.
unknown order             -> REJECTED

Several rules are visible here. A follow-up carries the same taskId. A finished task accepts no more messages and cannot be canceled. Another user is told the task does not exist, which reveals nothing about it. A caller asking for a version the server does not speak is refused rather than guessed at.

Run it as a real service

The same application factory runs under a web server:

uvicorn --factory agent:build_app --host 127.0.0.1 --port 9000

curl http://127.0.0.1:9000/.well-known/agent-card.json

curl -N http://127.0.0.1:9000/a2a \
  -H 'Content-Type: application/json' -H 'A2A-Version: 1.0' -H 'x-demo-user: ana' \
  -d '{"jsonrpc":"2.0","id":1,"method":"SendStreamingMessage","params":{"message":
       {"messageId":"s1","role":"ROLE_USER",
        "parts":[{"text":"Check 1320 EUR against PO-7731"}]}}}'

The streaming call answers with a series of server-sent events. In our run they arrived in this order:

EventContains
taskThe new task, submitted, with your message in its history
statusUpdateWorking
artifactUpdateThe match report
statusUpdateCompleted

Choose how clients follow long work

MethodGood forYou must handle
Wait for the replyWork of a few secondsClient and gateway timeouts
Return at once, then poll GetTaskSimple, firewall-friendly clientsBackoff, so polling does not flood you
Stream, and SubscribeToTask after a dropLive progressProxy buffering and idle timeouts
Push notification to a webhookHours or days; disconnected clientsCallback screening, signatures or tokens, duplicates
Make results independent of the stream

Treat a stream as a convenience. The artifact in the stored task is the record. A client that loses the connection should be able to ask for the task and get everything it needs.

Advanced Run it for others

Task state across several copies

InMemoryTaskStore forgets everything on restart and is invisible to other copies of your service. The next script shows what that does to a follow-up that a load balancer sends elsewhere.

"""Two copies of the agent: what breaks when task state is private to a copy."""
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore
from starlette.applications import Starlette
from starlette.testclient import TestClient

from agent import CARD, DemoIdentity, InvoiceAgent
from client_demo import call, message


def replica(store):
    handler = DefaultRequestHandler(
        agent_executor=InvoiceAgent(), task_store=store, agent_card=CARD)
    return TestClient(Starlette(routes=create_jsonrpc_routes(
        handler, "/a2a", context_builder=DemoIdentity())))


for label, shared in (("separate stores", False), ("one shared store", True)):
    store = InMemoryTaskStore()
    with replica(store) as one, replica(store if shared else InMemoryTaskStore()) as two:
        task = call(one, "SendMessage",
                    message(1, "Check 1320 against PO-7731"))["result"]["task"]
        reply = call(two, "SendMessage", message(2, "EUR", task["id"]))
        if "error" in reply:
            print(f"{label:17}: follow-up on replica two -> {reply['error']['code']}")
        else:
            print(f"{label:17}: follow-up on replica two -> "
                  f"{reply['result']['task']['status']['state']}")

Output:

separate stores  : follow-up on replica two -> -32001
one shared store : follow-up on replica two -> TASK_STATE_COMPLETED

In production, use a durable store. The Python SDK includes a database-backed task store, installed through extras such as a2a-sdk[postgresql]; we did not run it for this page. A shared store solves lookups, but live event queues are still held inside each process. Route one task's follow-ups and subscriptions to the same copy, or test streaming across copies before you rely on it.

A deployment shape

Client agentsother teams and partners
GatewayTLS, identity, rate and size limits, logging
Agent service, two or more copiesrequest handler and executor; per-task authorization
Shared task store and work queuestate that survives restarts
Models, tools and business systemsreached with the agent's own narrow credentials
  • The Agent Card gives the public HTTPS address, and it matches what the gateway serves.
  • Authentication happens before any protocol method runs; every task lookup checks ownership.
  • The proxy does not buffer event streams, and idle timeouts are longer than your longest quiet period.
  • Request size, parts per message and file sizes are limited.
  • Each task has a deadline, a budget for model calls and a way to be canceled.
  • Work that changes anything is safe to retry, because clients will retry.
  • Health checks cover the task store and key dependencies, not only the web process.
  • Shutdown stops accepting work, then lets running tasks finish or records them as interrupted.
Containers

The agent packages like any Python web service: pin dependencies, run as a non-root user, keep secrets out of the image and set resource limits. See Docker and Kubernetes for Agents.

Here is a starting point. We did not build or run this image.

FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .          # pin a2a-sdk[http-server] and uvicorn
RUN pip install --no-cache-dir -r requirements.txt
COPY agent.py .
RUN useradd --system agent
USER agent
EXPOSE 9000
CMD ["uvicorn", "--factory", "agent:build_app", "--host", "0.0.0.0", "--port", "9000"]

Change without breaking callers

  • Add optional fields and new skills freely; removing or renaming a skill is a breaking change.
  • Change the card's own version when behavior changes, and publish notes.
  • When you must support two protocol versions, advertise each interface in the card and test both.
  • Keep a small set of recorded requests and expected states, and replay them before each release.
  • Refresh cached cards. The SDK served an ETag header with the card, which lets clients check cheaply for change.

Know what it is doing

MeasureTells you
Tasks by final state, per skill and callerWhether work succeeds, and for whom it does not
Share of tasks that pause for inputWhether your contract asks for the right inputs up front
Age of the oldest active taskStuck work
Time to first update and to final stateWhat callers experience
Model and tool cost per taskWhether limits are working

Carry one trace identifier from the caller through your tool calls. Agent Tracing and OpenTelemetry explains how, and Safe Logging, Sampling and Retention what to leave out.

Troubleshooting

Rather than guess, we caused each failure on purpose and recorded what the caller saw.

"""Reproduce the failures you are most likely to meet, then read the symptom."""
import logging

from a2a.helpers.proto_helpers import new_task_from_user_message
from a2a.server.agent_execution import AgentExecutor
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore, TaskUpdater
from starlette.applications import Starlette
from starlette.testclient import TestClient

from agent import CARD, DemoIdentity
from client_demo import message

logging.disable(logging.CRITICAL)          # keep the output to the symptoms


class Base(AgentExecutor):
    async def cancel(self, context, event_queue):
        pass


class Silent(Base):
    async def execute(self, context, event_queue):
        pass


class UpdateBeforeTask(Base):
    async def execute(self, context, event_queue):
        await TaskUpdater(event_queue, context.task_id, context.context_id).complete()


class NeverFinishes(Base):
    async def execute(self, context, event_queue):
        await event_queue.enqueue_event(new_task_from_user_message(context.message))
        await TaskUpdater(event_queue, context.task_id, context.context_id).start_work()


class Crashes(Base):
    async def execute(self, context, event_queue):
        await event_queue.enqueue_event(new_task_from_user_message(context.message))
        raise RuntimeError("login failed for db_user at 10.0.0.12")


class FailsSafely(Crashes):
    async def execute(self, context, event_queue):
        task = TaskUpdater(event_queue, context.task_id, context.context_id)
        try:
            await super().execute(context, event_queue)
        except Exception:
            # log the details privately here, then say only what the caller needs
            await task.failed()


def send(executor, method="SendMessage", params=None):
    handler = DefaultRequestHandler(
        agent_executor=executor, task_store=InMemoryTaskStore(), agent_card=CARD)
    app = Starlette(routes=create_jsonrpc_routes(
        handler, "/a2a", context_builder=DemoIdentity()))
    with TestClient(app) as http:
        reply = http.post("/a2a", headers={"A2A-Version": "1.0"}, json={
            "jsonrpc": "2.0", "id": 1, "method": method,
            "params": params or message(1, "hello")}).json()
    if "error" in reply:
        return f"{reply['error']['code']} {reply['error']['message']}"
    return reply["result"]["task"]["status"]["state"]


old_role = {"message": {"messageId": "1", "role": "user", "parts": [{"text": "x"}]}}
cases = [
    ("executor sends nothing", send(Silent())),
    ("status update before the task", send(UpdateBeforeTask())),
    ("no final state", send(NeverFinishes())),
    ("unhandled exception", send(Crashes())),
    ("exception turned into failure", send(FailsSafely())),
    ("method name from 0.3", send(Silent(), method="message/send")),
    ("role written the old way", send(Silent(), params=old_role)),
]
for label, symptom in cases:
    print(f"{label:30} -> {symptom}")

Output:

executor sends nothing         -> -32006 Agent execution produced no events
status update before the task  -> -32006 Agent should enqueue Task before TaskStatusUpdateEvent event
no final state                 -> TASK_STATE_WORKING
unhandled exception            -> -32603 login failed for db_user at 10.0.0.12
exception turned into failure  -> TASK_STATE_FAILED
method name from 0.3           -> -32601 Method not found
role written the old way       -> -32602 Validation failed
An error message reached the caller

The unhandled exception returned its own text, including an internal address, as a -32603 error. Catch exceptions in your executor, log the detail privately and fail the task with a safe message.

SymptomLikely causeWhat to do
Card returns 404Wrong path or card routes not mountedServe /.well-known/agent-card.json
Card loads, calls fail to connectThe card's address is internal or out of datePublish the public address
-32601Old or misspelled method nameUse 1.0 names such as SendMessage
-32602A field is missing or an old value is usedRead the field list in the error data; use ROLE_USER
-32009Version header missing or unsupportedSend A2A-Version: 1.0
-32001Wrong id, expired task, another owner, or another copy's private storeCheck identity first, then storage
-32002The task has already endedRead the task; nothing to cancel
-32004Operation not available, or a message to a finished taskCheck card capabilities; start a new task
-32006The executor broke the event order or produced nothingEnqueue the task first, then updates
Task stays workingA path returned without a final or paused stateEnd every path; add a deadline that fails stale tasks
Stream shows nothing, then everythingA proxy is bufferingTurn buffering off for the event stream
Same question asked repeatedlyThe executor ignores earlier historyRead the history, or keep state per task
Duplicate actionsA retried message was processed twiceDeduplicate on message id and make actions idempotent

A debugging order that saves time

  1. Fetch the card with the same network path the client uses.
  2. Send one minimal request with the version header, and keep the full reply.
  3. Confirm who the server thinks you are.
  4. Read the task and its history with GetTask.
  5. Find the matching server trace, and check which copy handled each message.
  6. Only then look at the model's behavior inside the executor.

Common mistakes

MistakeBetter
Returning results only in a status messagePut deliverables in artifacts
Using failed for work you refuseUse rejected, with the reason
Holding state in executor variablesUse the task store and your database
Testing only the happy pathTest questions, cancels, retries and wrong owners
One broad service account behind the agentNarrow credentials, with the caller's authority checked

Questions people ask

Do I need a language model to build an A2A server?

No. The protocol describes how work is requested and tracked. The executor can be ordinary code, a model with tools, or both.

Can I add A2A to an agent I already have?

Usually yes. Write an executor that passes messages to your agent and translates its progress into task states and artifacts. Several frameworks provide adapters, so check yours first.

Should one service offer many skills?

Group skills that share an owner, data and permissions. Split them when they need different access or release at different speeds.

How do I test without a second company's agent?

Drive your server in memory as the scripts here do, then run an independent client or the project's own testing tools against a deployed copy.

References

Next steps