/notes / 18 Nov 2026

Let's Build It: A Hands-On Agent-to-Agent Walkthrough

Part 9, the finale of AI From Zero to Agents. We build three small agents (a trip planner, a currency agent and a weather agent) that find each other through A2A Agent Cards and work together over the A2A protocol, and read the real messages they exchange.

· 11 min read

Series · AI From Zero to AgentsPart 9 of 9
  1. 1 AI for Newbies: The 10-Minute Guide That Finally Makes It Click
  2. 2 ChatGPT Isn't Magic, It's Autocomplete on Steroids
  3. 3 Not All AI Is the Same Brain: Meet the Model Family
  4. 4 ChatGPT vs Claude vs Gemini vs Grok vs Llama vs Perplexity: Which AI Should You Actually Use?
  5. 5 Free, Open and on Your Laptop: Open-Source Models and the Secret Currency Called Tokens
  6. 6 From Chatbot to Coworker: What Agentic AI Is and How to Build Your First Agent
  7. 7 Stop Prompting, Start Automating: AI Workflows That Save You Hours Every Week
  8. 8 The USB-C Moment for AI: MCP vs A2A vs ACP, and How Agents Talk to Each Other
  9. 9 Let's Build It: A Hands-On Agent-to-Agent Walkthrough
Two glowing geometric orbs on a workbench connected by a bridge of light carrying envelope-shaped pulses, with a builder's hands adjusting the bridge

Eight parts ago we started with "what is AI?". Today we build a small team of agents that find each other and work together, using the same open standard the big players have signed up to.

If you've never written a line of code, don't panic. You can read this one like a story. I'll explain each step as we go, and you'll see exactly what the agents say to each other. If you do code, everything here runs as it is, with nothing but Python installed.

What we're building

Imagine a family planning a holiday: "Dubai in December, budget 2,000 AED a day. What's that in euros, and what weather should we pack for?"

No single agent knows all of that, so we build a small team.

Three agents: a Trip Planner orchestrator in the middle receives the family's question, discovers a Currency Agent and a Dubai Weather Agent by reading their Agent Cards, delegates one task to each over A2A, and combines their answers into one plan
Our team: one orchestrator, two specialists, one protocol

The Trip Planner is the one the family talks to. It splits the question up and hands the pieces out. A Currency Agent converts money, and a Dubai Weather Agent knows what the weather is typically like in each month. In real life those two specialists could be built by different companies, on different platforms, in different countries, and the Trip Planner wouldn't need to care. That's the whole promise of A2A.

Step 1: each specialist publishes an Agent Card

You'll remember the "business card" from Part 8. Every A2A agent publishes one at a standard address, /.well-known/agent-card.json. This is the Currency Agent's card, exactly as it was served when I ran the demo:

{
  "name": "Currency Agent",
  "description": "Converts amounts between currencies.",
  "version": "1.0.0",
  "supportedInterfaces": [
    { "url": "http://localhost:9001/", "protocolBinding": "JSONRPC", "protocolVersion": "1.0" }
  ],
  "capabilities": { "streaming": false, "pushNotifications": false },
  "defaultInputModes": ["text/plain"],
  "defaultOutputModes": ["text/plain"],
  "skills": [{
    "id": "convert",
    "name": "Convert currency",
    "description": "Convert an amount from one currency to another.",
    "tags": ["currency", "fx", "money"],
    "examples": ["2000 AED to EUR"]
  }]
}

Strip away the brackets and it's saying something quite human: "I'm the Currency Agent. You can reach me at this address using JSON-RPC and version 1.0 of A2A. I convert currencies, and here's the sort of thing you can ask me."

Step 2: the Trip Planner works out who can help

The Trip Planner reads each card and matches the skill tags against what it needs, which here is "currency" and "weather":

def discover():
    cards = []
    for base in KNOWN_AGENTS:
        card = http(f"{base}/.well-known/agent-card.json")   # read the business card
        cards.append(card)
    return cards

def pick(cards, need):                                     # e.g. need = "currency"
    return next(c for c in cards if any(need in s["tags"] for s in c["skills"]))

In a real company, KNOWN_AGENTS would be a directory of approved agents rather than a list typed into the code.

Step 3: hand over a task with SendMessage

Now the Trip Planner asks for help using the A2A method SendMessage. This is the actual request that went over the wire:

{
  "jsonrpc": "2.0",
  "id": "320f16ea-3394-4b1c-b234-9650c9c0854d",
  "method": "SendMessage",
  "params": {
    "message": {
      "messageId": "03868ba2-2a7a-44bb-8392-a41da7ef42cf",
      "contextId": "ca458d37-64d9-4da1-8937-ac5552fdaa45",
      "role": "ROLE_USER",
      "parts": [{ "text": "Convert 2000 AED to EUR" }]
    }
  }
}

A few things are worth a second look. The parts list is there because a message can carry text, files or structured data; this one is just a line of text. The contextId is a conversation ID, and the planner sends the same one to both specialists, so you can trace the whole trip from start to finish later. And ROLE_USER simply marks this as coming from the side that's asking for help.

Step 4: follow the task and collect the result

The specialist replies with a task. It carries a status and, once the work is finished, an artifact holding the answer:

{
  "id": "8e775d89-46b3-4bd1-bec5-7921bb97d1ae",
  "contextId": "ca458d37-64d9-4da1-8937-ac5552fdaa45",
  "status": { "state": "TASK_STATE_COMPLETED", "timestamp": "2026-10-21T06:22:41+00:00" },
  "artifacts": [{
    "artifactId": "824130a5-704e-4257-824a-e7a5a331e18e",
    "name": "conversion",
    "parts": [{ "text": "2,000 AED ≈ 469 EUR (demo rates)" }]
  }]
}

If A2A has a heart, it's that state field. A task can be SUBMITTED, WORKING, COMPLETED, FAILED, CANCELED or REJECTED. It can also pause as INPUT_REQUIRED or AUTH_REQUIRED when the specialist needs something from you before it can carry on.

The A2A task lifecycle: a task is submitted, moves to working, and ends as completed, failed, canceled or rejected; it can pause in input required or auth required and resume to working once the missing information arrives
The A2A task lifecycle. Long-running work and back-and-forth questions are built in.

Step 5: run it

Here's the real run, start to finish:

A terminal window showing the trip planner run: it discovers the Currency Agent and the Dubai Weather Agent with their skill tags, receives a completed conversion of 2,000 AED to about 469 EUR and a completed weather answer of typically 26°C by day and 16°C at night in December, gets an input-required response to a vague request, and prints the combined plan
The real output of the demo, run on 21 October 2026

Look at the edge case near the end. I had the Trip Planner send a deliberately vague request ("How much is that in euros?"), and the Currency Agent didn't guess. It came back with TASK_STATE_INPUT_REQUIRED and a question. That's what you'd want from a good colleague, and it's Part 2's lesson about hallucination built straight into the protocol: when in doubt, ask.

So where's the AI?

You may have spotted that the specialists' "brains" here are a few simple rules. I did that on purpose, so the demo runs without an API key and the protocol stays easy to see. In a real system each brain would be an LLM with its own tools:

Inside a production agent: the A2A layer on the outside receives tasks and returns artifacts; inside, an LLM plans the work and calls tools through MCP servers such as a live exchange-rate API, a weather service or a database; guardrails and logging wrap everything
A2A on the outside, an LLM plus MCP tools on the inside

That picture is really the whole series in one frame. Inside each agent sits an LLM like the ones in Part 2, picked at the right size (Part 3), from whichever vendor suits you (Part 4), open or closed (Part 5). It runs the agent loop from Part 6, usually inside a governed workflow like the ones in Part 7, and it uses MCP to reach its tools and A2A to work with its colleagues (Part 8).

Before you do this for real

This demo is tiny on purpose. If you're going to let agents talk to each other in production, here's what I'd add:

AreaWhat to addWhy
SDKsUse the official A2A SDKs (Python, JavaScript, Java, Go, .NET, Rust)Full spec support, fewer bugs
TransportHTTPS everywhereThe spec requires secure URLs in production
IdentityAuthentication on every agent (securitySchemes in the card)Only approved agents may call yours
TrustSigned Agent Cards and an approved-agents registryStop impostor agents
Long tasksStreaming updates and push notificationsReal work takes minutes, not milliseconds
GuardrailsLimits on spend, steps and data shared; human approval for actionsPart 6's rules still apply
ObservabilityLog every task and its contextIdTrace any answer back to who did what

That's a wrap

When we started, "AI" was mostly a word people nodded along to in meetings. If you've stuck with me through all nine parts, you now know what's going on inside it, how to choose and run a model, how agents and workflows actually work, and you've watched agents cooperate over an open standard. That's more than a lot of people who talk about AI for a living.

If I could leave you with one piece of advice, it would be to start small and make it real. Pick one workflow from Part 7, or one agent from the Part 6 canvas, and get it working this month. The people I see getting ahead with AI aren't the ones who've read the most about it. They're the ones who built one useful thing, then built another.

Thank you for reading this far. If the series helped you, pass it on to someone who's still nodding along in meetings, and do tell me what you end up building. I read every message, and I'd love to hear about it.

The full code

Two files, Python standard library only. Save them, run python a2a_agents.py in one terminal and python trip_planner.py in another (add --wire if you want to see every JSON message). It's a teaching implementation of the A2A 1.0 JSON-RPC binding, so please don't put it into production as it is.

a2a_agents.py: the two specialists

"""Two tiny A2A agents for learning: a Currency agent and a Weather agent.

Deliberately dependency-free (Python standard library only) so every byte on the wire is visible.
It follows the A2A 1.0 JSON-RPC binding: an Agent Card at /.well-known/agent-card.json and a
SendMessage method that returns a Task. For real projects use the official A2A SDKs.

The "brains" here are simple rules so the demo runs without an API key; in a real agent this is
where you would call an LLM (with its own MCP tools).

Run:  python a2a_agents.py            (starts both agents on ports 9001 and 9002)
"""
import json, re, threading, uuid
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

AED_PER_USD = 3.6725  # the UAE dirham is pegged to the US dollar at this rate
DEMO_RATES_TO_USD = {"USD": 1.0, "AED": 1 / AED_PER_USD, "EUR": 1.16, "GBP": 1.34, "INR": 0.0114}  # illustrative

DUBAI_CLIMATE = {  # typical daily high / low in °C (long-term averages, rounded)
    "january": (24, 15), "february": (25, 16), "march": (28, 18), "april": (33, 22),
    "may": (38, 26), "june": (40, 28), "july": (41, 30), "august": (41, 30),
    "september": (39, 28), "october": (35, 24), "november": (30, 20), "december": (26, 16),
}


def now():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def card(name, description, port, skill):
    return {
        "name": name,
        "description": description,
        "version": "1.0.0",
        "supportedInterfaces": [{"url": f"http://localhost:{port}/", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"}],
        "capabilities": {"streaming": False, "pushNotifications": False},
        "defaultInputModes": ["text/plain"],
        "defaultOutputModes": ["text/plain"],
        "skills": [skill],
    }


def task(context_id, state, text, artifact_name=None):
    t = {"id": str(uuid.uuid4()), "contextId": context_id or str(uuid.uuid4()), "status": {"state": state, "timestamp": now()}}
    if artifact_name:
        t["artifacts"] = [{"artifactId": str(uuid.uuid4()), "name": artifact_name, "parts": [{"text": text}]}]
    else:  # no result yet: explain what is missing in the status message
        t["status"]["message"] = {"messageId": str(uuid.uuid4()), "role": "ROLE_AGENT", "parts": [{"text": text}]}
    return t


# ---- the two agents' "brains" -------------------------------------------------------------

def currency_brain(text, context_id):
    m = re.search(r"([\d,.]+)\s*([A-Za-z]{3})\s+(?:to|in)\s+([A-Za-z]{3})", text)
    if not m:
        return task(context_id, "TASK_STATE_INPUT_REQUIRED", "Which amount and currencies? For example: 2000 AED to EUR.")
    amount, src, dst = float(m.group(1).replace(",", "")), m.group(2).upper(), m.group(3).upper()
    if src not in DEMO_RATES_TO_USD or dst not in DEMO_RATES_TO_USD:
        return task(context_id, "TASK_STATE_REJECTED", f"Sorry, I only know {', '.join(DEMO_RATES_TO_USD)}.")
    result = amount * DEMO_RATES_TO_USD[src] / DEMO_RATES_TO_USD[dst]
    return task(context_id, "TASK_STATE_COMPLETED", f"{amount:,.0f} {src} ≈ {result:,.0f} {dst} (demo rates)", "conversion")


def weather_brain(text, context_id):
    month = next((mo for mo in DUBAI_CLIMATE if mo in text.lower()), None)
    if not month:
        return task(context_id, "TASK_STATE_INPUT_REQUIRED", "Which month are you travelling?")
    hi, lo = DUBAI_CLIMATE[month]
    tip = "perfect for outdoor plans" if hi <= 30 else "plan outdoor time for early morning or evening"
    return task(context_id, "TASK_STATE_COMPLETED", f"Dubai in {month.title()}: typically {hi}°C by day, {lo}°C at night; {tip}.", "climate")


AGENTS = {
    9001: (card("Currency Agent", "Converts amounts between currencies.", 9001,
                {"id": "convert", "name": "Convert currency", "description": "Convert an amount from one currency to another.",
                 "tags": ["currency", "fx", "money"], "examples": ["2000 AED to EUR"]}), currency_brain),
    9002: (card("Dubai Weather Agent", "Typical Dubai weather for any month.", 9002,
                {"id": "climate", "name": "Dubai climate", "description": "Typical temperatures in Dubai for a given month.",
                 "tags": ["weather", "climate", "travel", "dubai"], "examples": ["What's Dubai like in December?"]}), weather_brain),
}


def handler_for(port):
    agent_card, brain = AGENTS[port]

    class Handler(BaseHTTPRequestHandler):
        def _send(self, code, body):
            data = json.dumps(body, ensure_ascii=False).encode()
            self.send_response(code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self):  # discovery
            if self.path == "/.well-known/agent-card.json":
                return self._send(200, agent_card)
            self._send(404, {"error": "not found"})

        def do_POST(self):  # JSON-RPC 2.0
            req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
            if req.get("method") != "SendMessage":
                return self._send(200, {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": -32601, "message": "Method not found"}})
            msg = req["params"]["message"]
            text = " ".join(p.get("text", "") for p in msg["parts"])
            self._send(200, {"jsonrpc": "2.0", "id": req["id"], "result": {"task": brain(text, msg.get("contextId"))}})

        def log_message(self, *args):
            pass

    return Handler


if __name__ == "__main__":
    for port in AGENTS:
        threading.Thread(target=ThreadingHTTPServer(("127.0.0.1", port), handler_for(port)).serve_forever, daemon=True).start()
        print(f"{AGENTS[port][0]['name']} listening on http://localhost:{port}")
    threading.Event().wait()

trip_planner.py: the orchestrator

"""The Trip Planner: an orchestrator agent that discovers other agents and delegates to them over A2A.

1. Discover: read each candidate's Agent Card from /.well-known/agent-card.json
2. Choose:   pick the agent whose skill tags match each sub-task
3. Delegate: send a SendMessage JSON-RPC request
4. Track:    check the returned task state (completed, input-required, rejected…)
5. Combine:  merge the artifacts into one answer

Run (with a2a_agents.py running):  python trip_planner.py
"""
import json, sys, urllib.request, uuid

KNOWN_AGENTS = ["http://localhost:9001", "http://localhost:9002"]  # in real life: a registry or directory
VERBOSE = "--wire" in sys.argv


def http(url, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"} if data else {})
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.loads(r.read())


def show(label, obj):
    if VERBOSE:
        print(f"\n--- {label} ---\n{json.dumps(obj, indent=2, ensure_ascii=False)}")


def discover():
    cards = []
    for base in KNOWN_AGENTS:
        c = http(f"{base}/.well-known/agent-card.json")
        show(f"Agent Card from {base}", c)
        print(f"🔎 discovered: {c['name']}  skills={[t for s in c['skills'] for t in s['tags']]}")
        cards.append(c)
    return cards


def pick(cards, need):
    return next(c for c in cards if any(need in s["tags"] for s in c["skills"]))


def delegate(agent, text, context_id):
    url = next(i["url"] for i in agent["supportedInterfaces"] if i["protocolBinding"] == "JSONRPC")
    request = {"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "SendMessage",
               "params": {"message": {"messageId": str(uuid.uuid4()), "contextId": context_id, "role": "ROLE_USER", "parts": [{"text": text}]}}}
    show(f"SendMessage → {agent['name']}", request)
    task = http(url, request)["result"]["task"]
    show(f"Task ← {agent['name']}", task)
    state = task["status"]["state"]
    if state == "TASK_STATE_COMPLETED":
        answer = " ".join(p["text"] for a in task["artifacts"] for p in a["parts"])
    else:
        answer = " ".join(p["text"] for p in task["status"].get("message", {}).get("parts", []))
    print(f"📨 {agent['name']}: {state}  →  {answer}")
    return state, answer


if __name__ == "__main__":
    print("🧭 Trip Planner: “Family trip to Dubai in December, budget 2,000 AED per day. What's that in EUR, and what weather should we pack for?”\n")
    context = str(uuid.uuid4())  # one conversation id shared across the delegated tasks
    cards = discover()
    print()
    fx = delegate(pick(cards, "currency"), "Convert 2000 AED to EUR", context)
    wx = delegate(pick(cards, "weather"), "What's Dubai like in December?", context)
    print("\n🧪 Edge case: a vague request")
    delegate(pick(cards, "currency"), "How much is that in euros?", context)
    print(f"\n✅ Plan: daily budget {fx[1]}. {wx[1]}")

AIA2AAgentic AIAI agentsHands-onPython

More notes