Google A2A Protocol Tutorial: Building Interoperable Multi-Agent Systems

# Tutorial Google A2A Protocol: Membangun Sistem Multi-Agent yang Saling Berkomunikasi Dalam era AI yang semakin canggih, satu AI agent saja sering tidak cukup untuk menyelesaikan tugas kompleks. Bay...

By Ruby Abdullah · · tutorial
A2AMulti-AgentGoogleProtocolPython

Google A2A Protocol Tutorial: Building Interoperable Multi-Agent Systems

In the increasingly sophisticated AI era, a single AI agent is often insufficient for solving complex tasks. Imagine you have an agent that excels at research, another that's great at coding, and one more that specializes in data analysis. How do you make them communicate and collaborate? This is the problem solved by Google A2A (Agent-to-Agent) Protocol.

A2A is an open protocol developed by Google to enable AI agents from different vendors and platforms to communicate with each other in a standardized way. If you're already familiar with Model Context Protocol (MCP) that connects agents to tools and data sources, then A2A complements it by connecting agents to other agents.

In this tutorial, we'll learn how to use A2A Protocol to build multi-agent systems that communicate with each other, from basic concepts to complete Python implementation.

What Is Google A2A Protocol?

A2A (Agent-to-Agent) Protocol is an open specification based on JSON-RPC 2.0 that enables AI agents to communicate with each other in a standardized way. The protocol was released by Google in April 2025 and is supported by over 50 technology partners including Salesforce, SAP, MongoDB, and others.

Why Is A2A Needed?

Before A2A, inter-agent integration was done in an ad-hoc manner. Each vendor had different APIs and communication formats. This created several problems:

  • Vendor lock-in: Agents from one platform couldn't communicate with agents from another platform
  • Integration complexity: Each pair of agents required custom connectors
  • Lack of standards: No standard way to discover agent capabilities
  • Opaque communication: Difficult to monitor and debug inter-agent interactions
  • A2A solves all these problems by providing a standard protocol covering discovery, communication, and task management.

    A2A vs MCP: What's the Difference?

    | Aspect | MCP | A2A |

    |--------|-----|-----|

    | Function | Connects agents to tools/data | Connects agents to agents |

    | Analogy | USB port on a computer | HTTP on the internet |

    | Interaction | Client-server (agent -> tool) | Peer-to-peer (agent <-> agent) |

    | Use case | Database access, APIs, file systems | Multi-agent collaboration |

    Both are complementary: MCP gives agents access to tools and data, while A2A enables agents to collaborate with each other.

    Core Concepts of A2A Protocol

    1. Agent Card

    An Agent Card is a JSON document that describes the identity and capabilities of an agent. Think of it as a "digital business card" that allows other agents to know what a particular agent can do.

    {
    

    "name": "Data Analysis Agent",

    "description": "Agent that analyzes datasets and generates insights",

    "url": "https://data-agent.example.com",

    "version": "1.0.0",

    "capabilities": {

    "streaming": true,

    "pushNotifications": false,

    "stateTransitionHistory": true

    },

    "skills": [

    {

    "id": "analyze-csv",

    "name": "CSV Analysis",

    "description": "Analyzes CSV files and generates statistical summaries",

    "tags": ["data", "analytics", "csv"],

    "examples": [

    "Analyze the Q3 2026 sales dataset",

    "Provide a statistical summary of customer data"

    ]

    },

    {

    "id": "create-chart",

    "name": "Create Chart",

    "description": "Creates chart visualizations from data",

    "tags": ["visualization", "charts"]

    }

    ],

    "defaultInputModes": ["text/plain", "application/json"],

    "defaultOutputModes": ["text/plain", "image/png"]

    }

    2. Task

    A Task is the unit of work in A2A. When one agent asks another agent to do something, it creates a Task. Each task has a lifecycle with state transitions:

    submitted → working → completed
    

    → failed

    → canceled

    → input-required (waiting for additional input)

    3. Message and Part

    Communication between agents is done through Messages that contain one or more Parts. Parts can be text, files, structured data, or even references to other resources.

    4. Artifact

    An Artifact is output produced by an agent while executing a task. Unlike messages which are communications, artifacts are work products (e.g., files, charts, or documents).

    Installation and Setup

    Prerequisites

    • Python 3.10 or later
    • pip or uv package manager

    Installing A2A SDK

    pip install a2a-sdk
    

    Or using uv:

    uv pip install a2a-sdk
    

    Additional Dependencies

    For this tutorial, we also need a few additional packages:

    pip install uvicorn httpx python-dotenv
    

    Project Structure

    Create the following project structure:

    a2a-demo/
    

    ├── .env

    ├── researchagent/

    │ ├── init.py

    │ └── agent.py

    ├── writeragent/

    │ ├── init.py

    │ └── agent.py

    ├── orchestrator.py

    └── requirements.txt

    requirements.txt:
    a2a-sdk>=0.2.0
    

    uvicorn>=0.30.0

    httpx>=0.27.0

    python-dotenv>=1.0.0

    Building Your First A2A Agent

    Let's start by creating a simple agent that can receive and process tasks from other agents.

    Step 1: Define the Agent Card

    # researchagent/agent.py
    

    from a2a.server import A2AServer, TaskHandler, TaskContext

    from a2a.types import (

    AgentCard,

    AgentCapabilities,

    AgentSkill,

    Task,

    TaskState,

    Message,

    TextPart,

    Role,

    )

    import uvicorn

    agentcard = AgentCard(

    name="Research Agent",

    description="Agent that performs research and gathers information about specific topics",

    url="http://localhost:8001",

    version="1.0.0",

    capabilities=AgentCapabilities(

    streaming=False,

    pushNotifications=False,

    stateTransitionHistory=True,

    ),

    skills=[

    AgentSkill(

    id="research-topic",

    name="Research Topic",

    description="Performs in-depth research about a given topic",

    tags=["research", "information", "analysis"],

    examples=[

    "Research AI trends in 2026",

    "Gather information about the latest Python frameworks",

    ],

    )

    ],

    defaultInputModes=["text/plain"],

    defaultOutputModes=["text/plain"],

    )

    Step 2: Implement the Task Handler

    class ResearchTaskHandler(TaskHandler):
    

    async def handletask(self, context: TaskContext) -> None:

    usermessage = context.task.messages[-1]

    query = ""

    for part in usermessage.parts:

    if hasattr(part, "text"):

    query = part.text

    break

    await context.updatestate(TaskState.WORKING)

    researchresult = await self.doresearch(query)

    responsemessage = Message(

    role=Role.AGENT,

    parts=[TextPart(text=researchresult)],

    )

    await context.addmessage(responsemessage)

    await context.complete()

    async def doresearch(self, query: str) -> str:

    # In a real implementation, this could call search APIs,

    # scrape websites, or use an LLM for research

    return (

    f"Research results for '{query}':\n\n"

    f"1. This topic is currently trending among developers\n"

    f"2. There are 15+ related frameworks actively being developed\n"

    f"3. Adoption has increased 40% compared to last year\n"

    f"4. The open-source community is very active with 500+ contributors\n\n"

    f"Recommendation: Focus on practical aspects and implementation "

    f"to get the best value from this topic."

    )

    Step 3: Run the Agent Server

    # Continued in researchagent/agent.py
    
    

    def main():

    handler = ResearchTaskHandler()

    server = A2AServer(

    agentcard=agentcard,

    taskhandler=handler,

    host="0.0.0.0",

    port=8001,

    )

    server.run()

    if name == "main":

    main()

    Run the agent:

    python -m researchagent.agent
    

    The agent is now running at http://localhost:8001 and ready to receive tasks from other agents.

    Step 4: Verify with Agent Card

    Every A2A agent exposes its Agent Card at the /.well-known/agent.json endpoint:

    curl http://localhost:8001/.well-known/agent.json
    

    Output:

    {
    

    "name": "Research Agent",

    "description": "Agent that performs research and gathers information about specific topics",

    "url": "http://localhost:8001",

    "version": "1.0.0",

    "capabilities": {

    "streaming": false,

    "pushNotifications": false,

    "stateTransitionHistory": true

    },

    "skills": [...]

    }

    Building an A2A Client

    Now let's create a second agent that communicates with the Research Agent using the A2A Client.

    Writer Agent That Uses the Research Agent

    # writeragent/agent.py
    

    from a2a.client import A2AClient

    from a2a.server import A2AServer, TaskHandler, TaskContext

    from a2a.types import (

    AgentCard,

    AgentCapabilities,

    AgentSkill,

    Task,

    TaskState,

    TaskSendParams,

    Message,

    TextPart,

    Role,

    )

    writercard = AgentCard(

    name="Writer Agent",

    description="Agent that writes articles based on research results",

    url="http://localhost:8002",

    version="1.0.0",

    capabilities=AgentCapabilities(

    streaming=False,

    pushNotifications=False,

    ),

    skills=[

    AgentSkill(

    id="write-article",

    name="Write Article",

    description="Writes articles based on a given topic. "

    "Automatically performs research first.",

    tags=["writing", "article", "content"],

    examples=["Write an article about AI agents"],

    )

    ],

    defaultInputModes=["text/plain"],

    defaultOutputModes=["text/plain"],

    )

    class WriterTaskHandler(TaskHandler):

    def init(self):

    self.researchclient = A2AClient(url="http://localhost:8001")

    async def handletask(self, context: TaskContext) -> None:

    usermessage = context.task.messages[-1]

    topic = ""

    for part in usermessage.parts:

    if hasattr(part, "text"):

    topic = part.text

    break

    await context.updatestate(TaskState.WORKING)

    # Step 1: Ask Research Agent to conduct research

    researchtask = await self.researchclient.sendtask(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[TextPart(text=f"Research about: {topic}")],

    )

    )

    )

    # Extract research results from response

    researchresult = ""

    if researchtask.messages:

    for part in researchtask.messages[-1].parts:

    if hasattr(part, "text"):

    researchresult = part.text

    # Step 2: Write article based on research results

    article = self.writearticle(topic, researchresult)

    response = Message(

    role=Role.AGENT,

    parts=[TextPart(text=article)],

    )

    await context.addmessage(response)

    await context.complete()

    def writearticle(self, topic: str, research: str) -> str:

    return (

    f"# {topic}\n\n"

    f"## Introduction\n"

    f"This article discusses {topic} based on recent research.\n\n"

    f"## Research Findings\n{research}\n\n"

    f"## Conclusion\n"

    f"Based on the research above, {topic} is a very promising area "

    f"worth exploring further."

    )

    def main():

    handler = WriterTaskHandler()

    server = A2AServer(

    agentcard=writercard,

    taskhandler=handler,

    host="0.0.0.0",

    port=8002,

    )

    server.run()

    if name == "main":

    main()

    Building an Orchestrator

    The Orchestrator is a component that coordinates interactions between agents. It can be an agent itself or a script that manages the multi-agent workflow.

    # orchestrator.py
    

    import asyncio

    from a2a.client import A2AClient

    from a2a.types import (

    TaskSendParams,

    Message,

    TextPart,

    Role,

    TaskState,

    )

    async def discoveragents():

    """Discover agent capabilities through Agent Cards"""

    agents = {}

    researchclient = A2AClient(url="http://localhost:8001")

    card = await researchclient.getagentcard()

    agents["research"] = {

    "client": researchclient,

    "card": card,

    "skills": {s.id: s for s in card.skills},

    }

    print(f"Discovered: {card.name} - {card.description}")

    writerclient = A2AClient(url="http://localhost:8002")

    card = await writerclient.getagentcard()

    agents["writer"] = {

    "client": writerclient,

    "card": card,

    "skills": {s.id: s for s in card.skills},

    }

    print(f"Discovered: {card.name} - {card.description}")

    return agents

    async def runworkflow(topic: str):

    """Run multi-agent workflow to write an article"""

    print(f"\n{'='60}")

    print(f"Starting workflow for topic: {topic}")

    print(f"{'='60}\n")

    # Step 1: Discover agents

    print("[1/3] Discovering agents...")

    agents = await discoveragents()

    # Step 2: Send task to Research Agent

    print(f"\n[2/3] Sending research task to {agents['research']['card'].name}...")

    researchclient = agents["research"]["client"]

    researchtask = await researchclient.sendtask(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[TextPart(text=f"In-depth research about: {topic}")],

    )

    )

    )

    print(f" Task ID: {researchtask.id}")

    print(f" Status: {researchtask.state}")

    if researchtask.messages:

    lastmsg = researchtask.messages[-1]

    for part in lastmsg.parts:

    if hasattr(part, "text"):

    print(f" Research results:\n{part.text[:200]}...")

    # Step 3: Send task to Writer Agent

    print(f"\n[3/3] Sending writing task to {agents['writer']['card'].name}...")

    writerclient = agents["writer"]["client"]

    writertask = await writerclient.sendtask(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[TextPart(text=topic)],

    )

    )

    )

    print(f" Task ID: {writertask.id}")

    print(f" Status: {writertask.state}")

    if writertask.messages:

    lastmsg = writertask.messages[-1]

    for part in lastmsg.parts:

    if hasattr(part, "text"):

    print(f"\n{'='60}")

    print("FINAL ARTICLE:")

    print(f"{'='60}")

    print(part.text)

    return writertask

    if name == "main":

    asyncio.run(runworkflow("The Evolution of AI Agents in 2026"))

    Running the Multi-Agent System

    Open 3 separate terminals:

    Terminal 1 - Run Research Agent:
    python -m researchagent.agent
    

    Output: A2A Server running on http://0.0.0.0:8001

    Terminal 2 - Run Writer Agent:
    python -m writeragent.agent
    

    Output: A2A Server running on http://0.0.0.0:8002

    Terminal 3 - Run Orchestrator:
    python orchestrator.py
    

    Advanced Features

    1. Streaming Responses

    A2A supports streaming for long responses, allowing agents to send results incrementally:

    from a2a.server import TaskHandler, TaskContext
    

    from a2a.types import (

    TaskState,

    Message,

    TextPart,

    Role,

    )

    class StreamingTaskHandler(TaskHandler):

    async def handletask(self, context: TaskContext) -> None:

    await context.updatestate(TaskState.WORKING)

    # Send incremental updates

    sections = [

    "## Part 1: Introduction\nThis is the introduction section...\n\n",

    "## Part 2: Analysis\nHere is the in-depth analysis...\n\n",

    "## Part 3: Conclusion\nFrom the analysis above...\n\n",

    ]

    for i, section in enumerate(sections):

    updatemsg = Message(

    role=Role.AGENT,

    parts=[TextPart(text=section)],

    metadata={"section": i + 1, "total": len(sections)},

    )

    await context.sendstreamingupdate(updatemsg)

    finalmsg = Message(

    role=Role.AGENT,

    parts=[TextPart(text="The complete article has been written.")],

    )

    await context.addmessage(finalmsg)

    await context.complete()

    On the client side, streaming can be consumed like this:

    from a2a.client import A2AClient
    

    from a2a.types import TaskSendParams, Message, TextPart, Role

    async def consumestreaming():

    client = A2AClient(url="http://localhost:8001")

    async for event in client.sendtaskstreaming(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[TextPart(text="Write a long article about AI")],

    )

    )

    ):

    if hasattr(event, "message"):

    for part in event.message.parts:

    if hasattr(part, "text"):

    print(part.text, end="", flush=True)

    elif hasattr(event, "state"):

    print(f"\n[State: {event.state}]")

    2. Multi-Turn Conversations

    A2A supports multi-turn conversations where an agent can request additional information before completing a task:

    from a2a.server import TaskHandler, TaskContext
    

    from a2a.types import (

    TaskState,

    Message,

    TextPart,

    Role,

    )

    class InteractiveTaskHandler(TaskHandler):

    async def handletask(self, context: TaskContext) -> None:

    messages = context.task.messages

    lastmessage = messages[-1]

    query = ""

    for part in lastmessage.parts:

    if hasattr(part, "text"):

    query = part.text

    # If this is the first message, ask for clarification

    if len(messages) == 1:

    clarification = Message(

    role=Role.AGENT,

    parts=[

    TextPart(

    text=(

    f"I will research '{query}'. "

    "Would you like to focus on a specific aspect? "

    "Options: technical, business, or both."

    )

    )

    ],

    )

    await context.addmessage(clarification)

    await context.updatestate(TaskState.INPUTREQUIRED)

    return

    # If this is a response from the user, process based on choice

    focus = query.lower()

    if "technical" in focus:

    result = "Research results with technical focus: ..."

    elif "business" in focus:

    result = "Research results with business focus: ..."

    else:

    result = "Comprehensive research results (technical + business): ..."

    response = Message(

    role=Role.AGENT,

    parts=[TextPart(text=result)],

    )

    await context.addmessage(response)

    await context.complete()

    3. Error Handling

    Proper error handling is crucial in multi-agent systems:

    from a2a.client import A2AClient
    

    from a2a.types import (

    TaskSendParams,

    Message,

    TextPart,

    Role,

    TaskState,

    )

    import httpx

    async def robusttaskexecution(client: A2AClient, message: str):

    """Execute task with comprehensive error handling"""

    try:

    task = await client.sendtask(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[TextPart(text=message)],

    )

    )

    )

    if task.state == TaskState.FAILED:

    errormsg = "Unknown error"

    if task.messages:

    for part in task.messages[-1].parts:

    if hasattr(part, "text"):

    errormsg = part.text

    print(f"Task failed: {errormsg}")

    return None

    return task

    except httpx.ConnectError:

    print("Cannot connect to agent. Make sure the agent is running.")

    return None

    except httpx.TimeoutException:

    print("Timeout while waiting for agent response.")

    return None

    except Exception as e:

    print(f"Unexpected error: {e}")

    return None

    4. Agent Discovery with Registry

    In production systems, you may have many agents. A Registry helps manage and discover the right agent:

    from a2a.client import A2AClient
    

    from a2a.types import AgentCard

    from dataclasses import dataclass

    @dataclass

    class RegisteredAgent:

    url: str

    card: AgentCard

    client: A2AClient

    class AgentRegistry:

    def init(self):

    self.agents: dict[str, RegisteredAgent] = {}

    async def register(self, url: str) -> AgentCard:

    """Register a new agent by URL"""

    client = A2AClient(url=url)

    card = await client.getagentcard()

    self.agents[card.name] = RegisteredAgent(

    url=url, card=card, client=client

    )

    return card

    def findbyskill(self, skilltag: str) -> list[RegisteredAgent]:

    """Find agents by skill tag"""

    results = []

    for agent in self.agents.values():

    for skill in agent.card.skills:

    if skilltag in skill.tags:

    results.append(agent)

    break

    return results

    def findbyname(self, name: str) -> RegisteredAgent | None:

    """Find agent by name"""

    return self.agents.get(name)

    def listall(self) -> list[AgentCard]:

    """List all registered agents"""

    return [a.card for a in self.agents.values()]

    Usage

    async def main():

    registry = AgentRegistry()

    await registry.register("http://localhost:8001")

    await registry.register("http://localhost:8002")

    await registry.register("http://localhost:8003")

    researchagents = registry.findbyskill("research")

    print(f"Found {len(researchagents)} agents with 'research' skill")

    for agent in researchagents:

    print(f" - {agent.card.name}: {agent.card.description}")

    Integrating A2A with LLMs

    In practice, A2A agents typically use LLMs to process tasks. Here's an example integration with Anthropic Claude:

    from a2a.server import TaskHandler, TaskContext
    

    from a2a.types import (

    TaskState,

    Message,

    TextPart,

    Role,

    )

    import anthropic

    import os

    class LLMResearchHandler(TaskHandler):

    def init(self):

    self.llm = anthropic.Anthropic(apikey=os.getenv("ANTHROPICAPIKEY"))

    async def handletask(self, context: TaskContext) -> None:

    lastmessage = context.task.messages[-1]

    query = ""

    for part in lastmessage.parts:

    if hasattr(part, "text"):

    query = part.text

    await context.updatestate(TaskState.WORKING)

    llmresponse = self.llm.messages.create(

    model="claude-sonnet-4-6",

    maxtokens=2048,

    system=(

    "You are a research agent that excels at gathering "

    "and analyzing information. Provide structured and "

    "informative research results."

    ),

    messages=[{"role": "user", "content": query}],

    )

    resulttext = llmresponse.content[0].text

    response = Message(

    role=Role.AGENT,

    parts=[TextPart(text=resulttext)],

    )

    await context.addmessage(response)

    await context.complete()

    Best Practices

    1. Design Informative Agent Cards

    The Agent Card is your agent's public contract. Make sure skill descriptions are accurate and usage examples are clear. Other agents rely on this information to determine whether your agent is suitable for their task.

    # Good - specific and measurable description
    

    AgentSkill(

    id="summarize-pdf",

    name="PDF Summarizer",

    description="Summarizes PDF documents up to 50 pages. Output is a structured summary with key points, max 500 words.",

    tags=["summarization", "pdf", "document"],

    examples=[

    "Summarize the Q3 2026 financial report.pdf",

    "Create an executive summary from this whitepaper",

    ],

    )

    Not ideal - too vague

    AgentSkill(

    id="process",

    name="Process",

    description="Processes documents",

    tags=["document"],

    )

    2. Implement Timeout and Retry

    In distributed systems, failures are normal. Always implement timeout and retry strategies:

    from a2a.client import A2AClient
    

    from a2a.types import TaskSendParams, Message, TextPart, Role

    import asyncio

    async def sendwithretry(

    client: A2AClient,

    message: str,

    maxretries: int = 3,

    timeout: float = 30.0,

    ):

    for attempt in range(maxretries):

    try:

    task = await asyncio.waitfor(

    client.sendtask(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[TextPart(text=message)],

    )

    )

    ),

    timeout=timeout,

    )

    return task

    except asyncio.TimeoutError:

    print(f"Timeout on attempt {attempt + 1}/{maxretries}")

    if attempt == maxretries - 1:

    raise

    await asyncio.sleep(2 attempt)

    except Exception as e:

    print(f"Error on attempt {attempt + 1}: {e}")

    if attempt == maxretries - 1:

    raise

    await asyncio.sleep(2 attempt)

    3. Logging and Observability

    Ensure every inter-agent interaction is well-logged for debugging:

    import logging
    

    from a2a.server import TaskHandler, TaskContext

    from a2a.types import TaskState, Message, TextPart, Role

    logging.basicConfig(level=logging.INFO)

    logger = logging.getLogger("a2a.agent")

    class ObservableTaskHandler(TaskHandler):

    async def handletask(self, context: TaskContext) -> None:

    taskid = context.task.id

    logger.info(f"[{taskid}] Task received - State: {context.task.state}")

    try:

    await context.updatestate(TaskState.WORKING)

    logger.info(f"[{taskid}] Processing started")

    result = await self.process(context)

    response = Message(

    role=Role.AGENT,

    parts=[TextPart(text=result)],

    )

    await context.addmessage(response)

    await context.complete()

    logger.info(f"[{taskid}] Task completed successfully")

    except Exception as e:

    logger.error(f"[{taskid}] Task failed: {e}")

    errormsg = Message(

    role=Role.AGENT,

    parts=[TextPart(text=f"Error: {str(e)}")],

    )

    await context.addmessage(errormsg)

    await context.fail()

    async def process(self, context: TaskContext) -> str:

    return "Processed result"

    4. Security

    Always validate input and implement inter-agent authentication:

    from a2a.server import A2AServer, TaskHandler, TaskContext
    

    from a2a.types import AgentCard, AgentCapabilities

    server = A2AServer(

    agentcard=AgentCard(

    name="Secure Agent",

    description="Agent with authentication",

    url="https://secure-agent.example.com",

    version="1.0.0",

    capabilities=AgentCapabilities(),

    authentication={

    "schemes": ["bearer"],

    "credentials": "API key required",

    },

    skills=[],

    ),

    taskhandler=handler,

    )

    5. Use Artifacts for Structured Output

    For output beyond plain text (files, images, data), use Artifacts:

    from a2a.types import Artifact, FilePart
    

    import base64

    async def handletask(self, context):

    # Generate file (e.g., chart PNG)

    chartbytes = generatechart()

    artifact = Artifact(

    name="sales-chart-q3.png",

    description="Q3 2026 sales chart",

    parts=[

    FilePart(

    file={

    "name": "sales-chart-q3.png",

    "mimeType": "image/png",

    "bytes": base64.b64encode(chartbytes).decode(),

    }

    )

    ],

    )

    await context.addartifact(artifact)

    await context.complete()

    Real-World Use Case: Multi-Agent Data Analysis Pipeline

    Here's a real-world example where 3 agents work together to analyze data:

    # pipeline.py
    

    import asyncio

    from a2a.client import A2AClient

    from a2a.types import TaskSendParams, Message, TextPart, Role

    async def dataanalysispipeline(dataseturl: str):

    # Agent 1: Data Collector - fetches and cleans data

    collector = A2AClient(url="http://localhost:8001")

    # Agent 2: Analyst - analyzes data

    analyst = A2AClient(url="http://localhost:8002")

    # Agent 3: Reporter - creates reports

    reporter = A2AClient(url="http://localhost:8003")

    print("Step 1: Collecting and cleaning data...")

    collecttask = await collector.sendtask(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[TextPart(text=f"Fetch and clean data from: {dataseturl}")],

    )

    )

    )

    cleaneddata = ""

    if collecttask.messages:

    for part in collecttask.messages[-1].parts:

    if hasattr(part, "text"):

    cleaneddata = part.text

    print("Step 2: Analyzing data...")

    analysistask = await analyst.sendtask(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[TextPart(text=f"Analyze the following data:\n{cleaneddata}")],

    )

    )

    )

    analysisresult = ""

    if analysistask.messages:

    for part in analysistask.messages[-1].parts:

    if hasattr(part, "text"):

    analysisresult = part.text

    print("Step 3: Generating report...")

    reporttask = await reporter.sendtask(

    TaskSendParams(

    message=Message(

    role=Role.USER,

    parts=[

    TextPart(

    text=(

    f"Create a report from the following analysis:\n"

    f"{analysisresult}"

    )

    )

    ],

    )

    )

    )

    if reporttask.messages:

    for part in reporttask.messages[-1].parts:

    if hasattr(part, "text"):

    print(f"\nFinal Report:\n{part.text}")

    return reporttask

    if name == "main":

    asyncio.run(

    dataanalysis_pipeline("https://example.com/sales-data-2026.csv")

    )

    Conclusion

    Google A2A Protocol opens a new era in multi-agent AI system development. With an open and structured communication standard, developers can now build systems where specialist agents collaborate to solve complex tasks.

    Key takeaways:

  • A2A complements MCP - use MCP to connect agents to tools, and A2A to connect agents to other agents
  • Agent Card is key - design informative and accurate Agent Cards so other agents can discover and use your agent
  • Error handling is mandatory - in distributed systems, always prepare timeout, retry, and fallback mechanisms
  • Start simple - build 2 communicating agents first before building more complex systems
  • Observability matters - implement good logging to facilitate debugging
  • With A2A, you can build AI agent ecosystems that are modular, reusable, and interoperable. Start experimenting with two simple agents, then increase complexity as your understanding grows.

    Related Articles

    CAMEL-AI Tutorial: Building Multi-Agent Systems with Communicative AI Agents

    Tutorial Lengkap CAMEL-AI: Framework Multi-Agent Communication untuk Membangun Sistem AI Kolaboratif Penulis: Ruby Abdul...

    OpenAI Agents SDK: Building Multi-Agent Systems with Handoffs and Guardrails

    OpenAI Agents SDK: Membangun Sistem Multi-Agent dengan Handoff dan Guardrail Halo temen-temen, kali ini kita bahas OpenA...

    Complete Tutorial: Google Agent Development Kit (ADK) for Building AI Agents with Python

    Tutorial Lengkap Google Agent Development Kit (ADK): Membangun AI Agent dengan Python Google Agent Development Kit (ADK)...

    AutoGen: Microsoft's Multi-Agent Conversation Framework

    AutoGen: Framework Multi-Agent Conversation dari Microsoft AutoGen adalah framework open-source dari Microsoft Research ...