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.
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.
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.
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.
| Question | Points toward A2A | Points away |
|---|---|---|
| Who owns it? | Another team or company | The same codebase |
| How long does work take? | Seconds to days | Milliseconds |
| Can it need more information? | Yes, part way through | All inputs are known up front |
| Is the method private? | The caller should not care how | The 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.
| Decide | Example for an invoice checker |
|---|---|
| Skill | Compare an invoice amount with its purchase order |
| Required input | Order number, amount, currency |
| Questions it may ask | Which currency? |
| Output | A data artifact named match-report with order, currency and difference |
| Reasons to reject | No known purchase order |
| What it will never do | Approve or pay the invoice |
| Time limit and retention | How long a task may stay open, and how long results are kept |
The path of one request
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())])
| Piece | Its job | Watch for |
|---|---|---|
CARD | Advertises address, version, features and skills | The address must be the one clients can reach, not an internal host name |
execute | Runs for every message to a task | Create the task first; finish in a clear state |
TaskUpdater | Publishes status changes and artifacts | One updater per task and context |
requires_input | Pauses and asks a question | Read the earlier history when the answer arrives |
reject | Declines work the agent will not do | Say why in a message |
DemoIdentity | Tells the SDK who is calling | It trusts a header. Replace it before any real use |
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:
| Event | Contains |
|---|---|
task | The new task, submitted, with your message in its history |
statusUpdate | Working |
artifactUpdate | The match report |
statusUpdate | Completed |
Choose how clients follow long work
| Method | Good for | You must handle |
|---|---|---|
| Wait for the reply | Work of a few seconds | Client and gateway timeouts |
Return at once, then poll GetTask | Simple, firewall-friendly clients | Backoff, so polling does not flood you |
Stream, and SubscribeToTask after a drop | Live progress | Proxy buffering and idle timeouts |
| Push notification to a webhook | Hours or days; disconnected clients | Callback screening, signatures or tokens, duplicates |
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.
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
- 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.
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
versionwhen 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
ETagheader with the card, which lets clients check cheaply for change.
Know what it is doing
| Measure | Tells you |
|---|---|
| Tasks by final state, per skill and caller | Whether work succeeds, and for whom it does not |
| Share of tasks that pause for input | Whether your contract asks for the right inputs up front |
| Age of the oldest active task | Stuck work |
| Time to first update and to final state | What callers experience |
| Model and tool cost per task | Whether 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
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.
| Symptom | Likely cause | What to do |
|---|---|---|
| Card returns 404 | Wrong path or card routes not mounted | Serve /.well-known/agent-card.json |
| Card loads, calls fail to connect | The card's address is internal or out of date | Publish the public address |
-32601 | Old or misspelled method name | Use 1.0 names such as SendMessage |
-32602 | A field is missing or an old value is used | Read the field list in the error data; use ROLE_USER |
-32009 | Version header missing or unsupported | Send A2A-Version: 1.0 |
-32001 | Wrong id, expired task, another owner, or another copy's private store | Check identity first, then storage |
-32002 | The task has already ended | Read the task; nothing to cancel |
-32004 | Operation not available, or a message to a finished task | Check card capabilities; start a new task |
-32006 | The executor broke the event order or produced nothing | Enqueue the task first, then updates |
| Task stays working | A path returned without a final or paused state | End every path; add a deadline that fails stale tasks |
| Stream shows nothing, then everything | A proxy is buffering | Turn buffering off for the event stream |
| Same question asked repeatedly | The executor ignores earlier history | Read the history, or keep state per task |
| Duplicate actions | A retried message was processed twice | Deduplicate on message id and make actions idempotent |
A debugging order that saves time
- Fetch the card with the same network path the client uses.
- Send one minimal request with the version header, and keep the full reply.
- Confirm who the server thinks you are.
- Read the task and its history with
GetTask. - Find the matching server trace, and check which copy handled each message.
- Only then look at the model's behavior inside the executor.
Common mistakes
| Mistake | Better |
|---|---|
| Returning results only in a status message | Put deliverables in artifacts |
| Using failed for work you refuse | Use rejected, with the reason |
| Holding state in executor variables | Use the task store and your database |
| Testing only the happy path | Test questions, cancels, retries and wrong owners |
| One broad service account behind the agent | Narrow 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
A2A Security and Interoperability
Authentication, ownership, signed cards and safe callbacks.
MCP vs A2A vs REST
Choose between a tool, an agent and a plain API.
Lab: MCP Server and A2A Agent
Practice with hands-on exercises.