A PRACTICAL GUIDE TO AGENT-TO-AGENT COMMUNICATION
The landscape of artificial intelligence has evolved dramatically from single, monolithic models to sophisticated ecosystems of specialized agents working in concert. While individual language models have become remarkably capable, the real power emerges when multiple agents collaborate, each bringing unique expertise to solve complex problems. However, this collaboration requires a standardized way for agents to communicate, negotiate, and coordinate their efforts. This is precisely where Google's Agent-to-Agent protocol, commonly known as A2A, enters the picture.
Imagine a software development team where each member has deep expertise in a specific domain. The frontend specialist, backend architect, database administrator, and DevOps engineer must communicate effectively to build a cohesive system. Similarly, in an agentic AI system, we need research agents, writing agents, fact-checking agents, and coordination agents to work together seamlessly. Without a common language and protocol, this coordination becomes chaotic and unreliable.
Google's A2A protocol, launched with contributions from over fifty technology partners, provides exactly this common language. It establishes a standardized framework for how agents discover each other, advertise their capabilities, negotiate tasks, exchange information, and coordinate their activities. Think of it as a combination of HTTP for message transport, JSON-RPC for remote procedure calls, and a service discovery mechanism all rolled into one, but specifically designed for the unique requirements of AI agents.
UNDERSTANDING THE A2A PROTOCOL FUNDAMENTALS
The A2A protocol is built on several core principles that distinguish it from traditional inter-process communication mechanisms. At its heart, A2A recognizes that AI agents are not just passive services waiting for requests, but active entities with goals, capabilities, constraints, and the ability to reason about their interactions.
The protocol is designed around key architectural principles that make it practical for enterprise deployment. First is agent independence, which means agents can collaborate in their natural modalities without needing to share internal logic, memory, tools, or context. Each agent remains autonomous while participating in larger collaborative workflows. Second, the protocol builds upon existing web standards like HTTP, Server-Sent Events for streaming, and JSON-RPC 2.0 for remote procedure calls. This means developers can leverage familiar tools and libraries rather than learning entirely new technologies. Third, security is built in from the ground up, supporting enterprise-grade authentication and authorization including OAuth and API keys. Fourth, the protocol handles flexible timelines, supporting tasks ranging from instant queries to multi-day workflows without requiring different communication patterns. Finally, A2A is content type agnostic, supporting various modalities including text, images, videos, audio, PDFs, and structured data.
The protocol defines several fundamental components that work together to enable agent collaboration. The A2A Client, also called the client agent, is an application, service, or AI agent that requests actions or information from a remote agent. The A2A Server, also called the remote agent, is an AI agent that exposes an HTTP endpoint, receives requests, processes tasks, and returns results. The Agent Card is a JSON metadata document that agents use to advertise their capabilities, identity, service endpoint, version, supported A2A capabilities, and authentication requirements. This allows client agents to discover and identify suitable remote agents. Tasks represent stateful, traceable units of work executed by an agent to achieve specific outcomes and generate artifacts. Messages are the basic units for exchanging information between users and agents, supporting multiple content types.
Communication in A2A occurs over HTTP and HTTPS, with JSON-RPC 2.0 serving as the payload format for all requests and responses. This choice leverages JSON-RPC's stateless, lightweight, and transport-agnostic nature, providing a standardized way for applications to invoke methods or procedures on remote systems. The Content-Type header for JSON-RPC payloads is set to application/json.
Let's examine the structure of an Agent Card to understand how agents advertise their capabilities. An Agent Card is typically made available at a well-known URI, specifically at the path /.well-known/agent.json on the agent's domain. This follows the RFC 8615 standard for well-known URIs, making agent discovery straightforward and predictable.
Here is what a real Agent Card looks like in practice:
{
"protocolVersion": "0.2.5",
"name": "WeatherBot",
"description": "Provides accurate weather forecasts and historical data for any location.",
"url": "https://weather.example.com/a2a/api",
"provider": {
"name": "Example Weather Services Inc.",
"url": "https://example.com/weather"
},
"version": "1.0.0",
"documentationUrl": "https://weather.example.com/a2a/docs",
"capabilities": {
"streaming": true,
"pushNotifications": false,
"stateTransitionHistory": true
},
"securitySchemes": {
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
},
"security": [
{
"bearerAuth": []
}
],
"defaultInputModes": [
"text/plain",
"application/json"
],
"defaultOutputModes": [
"text/plain",
"application/json"
],
"skills": [
{
"id": "getCurrentWeather",
"name": "Get Current Weather",
"description": "Retrieves real-time weather conditions for a specified location.",
"tags": ["weather", "current", "real-time"],
"examples": [
"What's the weather like in London?",
"Current temperature in New York City"
],
"inputModes": ["text/plain"],
"outputModes": ["application/json"]
},
{
"id": "getForecast",
"name": "Get Weather Forecast",
"description": "Provides a weather forecast for a specified location and period.",
"tags": ["weather", "forecast", "future"],
"examples": [
"5-day forecast for Paris",
"Will it rain in Berlin tomorrow?"
],
"inputModes": ["text/plain"],
"outputModes": ["application/json"]
}
]
}
In this example, the WeatherBot agent clearly identifies itself with a human-readable name and description. The protocolVersion field indicates this agent supports version 0.2.5 of the A2A protocol. The url field specifies the base endpoint for the agent's A2A service. The capabilities section indicates that this agent supports streaming responses and maintains state transition history, but does not support push notifications. The securitySchemes and security fields define that clients must authenticate using a bearer token in JWT format. The skills array is particularly important, as it lists the specific capabilities this agent offers. Each skill has a unique identifier, descriptive name, detailed description, relevant tags, example queries that would trigger this skill, and the input and output MIME types it supports.
When a client agent wants to interact with this weather agent, it first retrieves the Agent Card from the well-known URI. The client can then examine the available skills, determine which one matches its needs, check the authentication requirements, and prepare an appropriately formatted request.
TASK LIFECYCLE AND STATE MANAGEMENT
One of the most sophisticated aspects of the A2A protocol is its task management system. Tasks are the fundamental unit of work in A2A, and they progress through a well-defined lifecycle with various states indicating their current stage.
When a client agent sends a request to a remote agent, the remote agent may determine that fulfilling the request requires completing a task. Each task is assigned a unique task identifier that the client can use for future messages related to that task. The task then progresses through various states as the agent works on it.
The submitted state indicates the task has been initiated and sent to the remote agent. The working state means the remote agent is actively processing the task. The input-required state signals that the task requires additional information or action from the client agent to proceed. This is particularly important for interactive workflows where the agent needs clarification or additional context. The completed state indicates the task has been successfully finished. The canceled state means the task was terminated before completion, usually by request from the client. The failed state indicates the task encountered an error and could not be completed successfully. The unknown state is used when the current state of the task is not known. The rejected state means the task was declined by the agent, perhaps because it lacks the necessary capabilities or resources. The auth-required state indicates the task requires authentication to proceed.
For long-running tasks, clients can periodically poll for status updates until the task reaches a terminal state like completed, failed, or canceled. The protocol also supports streaming responses using Server-Sent Events, allowing the remote agent to push updates to the client as the task progresses without requiring polling.
The JSON-RPC methods that agents use to interact with tasks include message/send for sending initial requests and continuing conversations. When a client sends a message, if a task is initiated, it will have a taskId which the client can use for future messages related to that task. The tasks/get method allows clients to retrieve the current state and details of a specific task. The tasks/send and tasks/sendSubscribe methods are used to start or continue work on tasks, with the subscribe variant enabling streaming responses.
DESIGNING OUR MULTI-AGENT SYSTEM ARCHITECTURE
Now that we understand the A2A protocol fundamentals, let's design a practical multi-agent system that demonstrates these concepts in action. Our system will tackle a common real-world scenario: automated research and report generation. This task naturally decomposes into several specialized subtasks, making it perfect for a multi-agent approach.
Our system will consist of three specialized agents, each with distinct capabilities and responsibilities. The Research Agent specializes in gathering information from various sources, including web search, document analysis, and knowledge synthesis. The Writing Agent takes structured information and transforms it into coherent, well-written prose following specific style guidelines. The Coordinator Agent acts as the orchestrator, receiving high-level user requests, decomposing them into subtasks, and managing the workflow across other agents.
These agents will communicate exclusively through A2A protocol messages, demonstrating agent discovery via Agent Cards, task negotiation and lifecycle management, information exchange through messages, and result aggregation. The beauty of this architecture is that each agent can be implemented independently, potentially using different underlying language models optimized for their specific tasks, yet they all interoperate seamlessly through the standardized protocol.
For our implementation, we will use Python as the primary programming language due to its rich ecosystem of AI and machine learning libraries. We will leverage the official A2A Python SDK developed by the a2aproject organization on GitHub. This SDK provides compliance with the A2A Protocol, extensibility to support various communication protocols and database backends, asynchronous design for high performance, and optional integrations for HTTP servers using FastAPI or Starlette, gRPC, OpenTelemetry for tracing, and SQL databases including PostgreSQL, MySQL, and SQLite.
For local LLM inference with GPU support, we will use llama-cpp-python, which provides excellent support for both Apple Metal Performance Shaders on macOS and NVIDIA CUDA on systems with NVIDIA GPUs. This ensures our system can run efficiently on a wide range of hardware configurations without requiring cloud API access.
The system architecture follows a clean separation of concerns. Each agent is implemented as an independent A2A server with its own HTTP endpoint, Agent Card describing its capabilities, AgentExecutor implementing its core logic, and LLM instance for reasoning and generation. A central discovery mechanism allows agents to find each other through well-known URIs or a registry. The A2A SDK handles all the protocol details including JSON-RPC message formatting, HTTP transport, streaming via Server-Sent Events, and task state management.
SETTING UP THE DEVELOPMENT ENVIRONMENT
Before we start implementing our agents, we need to set up the development environment with all necessary dependencies. We will use uv, a fast Python package installer and manager, to streamline the setup process.
First, install uv if you do not already have it:
curl -LsSf https://astral.sh/uv/install.sh | sh
Create a project directory and set up a virtual environment:
mkdir a2a_multi_agent_research
cd a2a_multi_agent_research
uv venv
source .venv/bin/activate
On Windows, you would use .venv\Scripts\activate instead.
Now install the required packages:
uv pip install a2a-sdk uvicorn llama-cpp-python httpx
The a2a-sdk package provides the core A2A protocol implementation. The uvicorn package is an ASGI server for running our agent HTTP endpoints. The llama-cpp-python package enables local LLM inference with GPU acceleration. The httpx package provides async HTTP client capabilities for agent-to-agent communication.
If you have an NVIDIA GPU and want to use CUDA acceleration, you need to install llama-cpp-python with CUDA support:
CMAKE_ARGS="-DLLAMA_CUDA=on" uv pip install llama-cpp-python --force-reinstall --no-cache-dir
For Apple Silicon Macs with Metal Performance Shaders support:
CMAKE_ARGS="-DLLAMA_METAL=on" uv pip install llama-cpp-python --force-reinstall --no-cache-dir
You will also need a local LLM model in GGUF format. For this tutorial, I recommend downloading a quantized Mistral or Llama model from HuggingFace. For example, you could download Mistral-7B-Instruct in GGUF format from TheBloke's repository. Create a models directory in your project and place the downloaded model file there:
mkdir models
# Download your chosen model to models/model.gguf
With the environment set up, we are ready to start implementing our agents.
IMPLEMENTING THE RESEARCH AGENT
Let's begin by implementing the Research Agent, which will be responsible for gathering and synthesizing information. This agent will expose its capabilities through an Agent Card and implement the AgentExecutor interface to process incoming requests.
Create a file named research_agent.py:
import uvicorn
import asyncio
from llama_cpp import Llama
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.app import A2AStarletteApplication
from a2a.types import AgentCard, AgentCapabilities, AgentSkill, Message, TextPart, Role
class ResearchAgentExecutor(AgentExecutor):
"""
Executes research tasks using a local LLM.
Gathers and synthesizes information based on user queries.
"""
def __init__(self, model_path: str):
"""
Initialize the research agent executor with a local LLM.
Args:
model_path: Path to the GGUF format model file
"""
self.llm = self._initialize_llm(model_path)
def _initialize_llm(self, model_path: str) -> Llama:
"""
Initialize the local LLM with GPU acceleration if available.
Args:
model_path: Path to the GGUF format model file
Returns:
Initialized Llama instance
"""
try:
import torch
# Detect available GPU acceleration
n_gpu_layers = 0
if torch.cuda.is_available():
# NVIDIA CUDA available
n_gpu_layers = -1 # Offload all layers to GPU
print("Research Agent: Using NVIDIA CUDA acceleration")
elif torch.backends.mps.is_available():
# Apple Metal Performance Shaders available
n_gpu_layers = 1
print("Research Agent: Using Apple Metal acceleration")
else:
print("Research Agent: Using CPU inference")
except ImportError:
n_gpu_layers = 0
print("Research Agent: PyTorch not found, using CPU")
# Initialize llama.cpp with appropriate settings
llm = Llama(
model_path=model_path,
n_gpu_layers=n_gpu_layers,
n_ctx=4096, # Context window size
n_batch=512, # Batch size for prompt processing
verbose=False
)
print("Research Agent: LLM initialized successfully")
return llm
def _generate_response(self, prompt: str, max_tokens: int = 1024) -> str:
"""
Generate text using the local LLM.
Args:
prompt: Input prompt for the LLM
max_tokens: Maximum number of tokens to generate
Returns:
Generated text response
"""
try:
response = self.llm(
prompt,
max_tokens=max_tokens,
temperature=0.7,
top_p=0.9,
stop=["</s>", "Human:", "User:"],
echo=False
)
return response['choices'][0]['text'].strip()
except Exception as e:
return f"Error generating response: {e}"
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
"""
Execute a research task based on the incoming request.
Args:
context: The request context containing the message and task info
event_queue: Queue for sending back messages and status updates
"""
# Extract the user's research query from the message
user_query = ""
if context.request.message and context.request.message.parts:
for part in context.request.message.parts:
if isinstance(part, TextPart):
user_query += part.text + " "
user_query = user_query.strip()
print(f"\nResearch Agent: Received research query: {user_query}")
# Update task status to working
await event_queue.task_status_update(status="working")
# Construct a research-focused prompt for the LLM
research_prompt = f"""You are a research assistant with expertise in gathering and synthesizing information. Provide comprehensive, well-structured research on the following topic.
Research Query: {user_query}
Please provide:
1. Key facts and important concepts
2. Relevant background information
3. Current understanding and recent developments
4. Important considerations and nuances
Research Summary:"""
# Generate research findings using the LLM
research_result = self._generate_response(research_prompt, max_tokens=1024)
print(f"Research Agent: Generated {len(research_result)} characters of research")
# Send the research findings back as a message
response_message = Message(
kind="message",
role=Role.AGENT,
parts=[TextPart(text=research_result)]
)
await event_queue.message(response_message)
# Mark the task as completed
await event_queue.task_status_update(status="completed")
async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
"""
Handle cancellation of a research task.
Args:
context: The request context
event_queue: Queue for sending status updates
"""
print(f"Research Agent: Received cancel request for task {context.request.task_id}")
# In a real implementation, you would stop any ongoing LLM generation
# For this example, we simply acknowledge the cancellation
await event_queue.task_status_update(status="canceled")
def build_research_agent_card(host: str, port: int) -> AgentCard:
"""
Build the Agent Card for the Research Agent.
This advertises the agent's capabilities to potential clients.
Args:
host: The hostname where the agent is running
port: The port number where the agent is listening
Returns:
AgentCard describing the Research Agent
"""
return AgentCard(
protocolVersion="0.2.5",
name="ResearchAgent",
description="Specialized agent for information gathering and research synthesis. Uses local LLM to provide comprehensive research on various topics.",
url=f"http://{host}:{port}",
version="1.0.0",
capabilities=AgentCapabilities(streaming=True),
skills=[
AgentSkill(
id="research",
name="Research",
description="Conducts comprehensive research on a given topic, gathering facts, concepts, and relevant information.",
tags=["research", "information-gathering", "synthesis"],
examples=[
"Research the benefits of multi-agent AI systems",
"Gather information about renewable energy technologies",
"Provide background on quantum computing"
]
),
AgentSkill(
id="fact-gathering",
name="Fact Gathering",
description="Collects specific facts and data points about a topic.",
tags=["facts", "data", "information"],
examples=[
"What are the key facts about climate change?",
"Gather statistics on global internet usage"
]
)
]
)
async def main():
"""
Main entry point for the Research Agent.
Initializes the agent and starts the HTTP server.
"""
# Configuration
host = "127.0.0.1"
port = 8001
model_path = "models/model.gguf" # Update this to your model path
print("="*60)
print("RESEARCH AGENT - A2A PROTOCOL")
print("="*60)
print()
# Build the Agent Card
agent_card = build_research_agent_card(host, port)
# Initialize the executor with the LLM
executor = ResearchAgentExecutor(model_path)
# Build the A2A application
app = A2AStarletteApplication(
agent_card=agent_card,
agent_executor=executor
)
# Start the server
print(f"Starting Research Agent on {host}:{port}")
print(f"Agent Card available at: http://{host}:{port}/.well-known/agent.json")
print()
config = uvicorn.Config(
app.build(),
host=host,
port=port,
log_level="info"
)
server = uvicorn.Server(config)
await server.serve()
if __name__ == "__main__":
asyncio.run(main())
This Research Agent implementation demonstrates several key A2A concepts. The AgentExecutor class is the core of the agent, implementing the execute method that processes incoming requests and the cancel method that handles task cancellation. The agent initializes a local LLM with automatic GPU detection, supporting both CUDA and Metal acceleration. The Agent Card clearly describes the agent's capabilities through the skills array, making it discoverable by other agents. The agent communicates task progress through the EventQueue's task_status_update method, keeping clients informed about the task lifecycle. Messages are sent back through the EventQueue using the message method, which the A2A SDK manages to ensure proper protocol compliance.
When you run this agent, it starts an HTTP server on port 8001 and automatically exposes its Agent Card at the well-known URI. Other agents can discover this agent by fetching the Agent Card and examining its capabilities.
IMPLEMENTING THE WRITING AGENT
Next, let's implement the Writing Agent, which transforms research findings into polished, well-written content. This agent will demonstrate how A2A agents can build upon the work of other agents.
Create a file named writing_agent.py:
import uvicorn
import asyncio
from llama_cpp import Llama
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.app import A2AStarletteApplication
from a2a.types import AgentCard, AgentCapabilities, AgentSkill, Message, TextPart, Role
class WritingAgentExecutor(AgentExecutor):
"""
Executes writing tasks using a local LLM.
Transforms information into well-structured, polished content.
"""
def __init__(self, model_path: str):
"""
Initialize the writing agent executor with a local LLM.
Args:
model_path: Path to the GGUF format model file
"""
self.llm = self._initialize_llm(model_path)
def _initialize_llm(self, model_path: str) -> Llama:
"""
Initialize the local LLM with GPU acceleration if available.
Args:
model_path: Path to the GGUF format model file
Returns:
Initialized Llama instance
"""
try:
import torch
n_gpu_layers = 0
if torch.cuda.is_available():
n_gpu_layers = -1
print("Writing Agent: Using NVIDIA CUDA acceleration")
elif torch.backends.mps.is_available():
n_gpu_layers = 1
print("Writing Agent: Using Apple Metal acceleration")
else:
print("Writing Agent: Using CPU inference")
except ImportError:
n_gpu_layers = 0
print("Writing Agent: PyTorch not found, using CPU")
llm = Llama(
model_path=model_path,
n_gpu_layers=n_gpu_layers,
n_ctx=4096,
n_batch=512,
verbose=False
)
print("Writing Agent: LLM initialized successfully")
return llm
def _generate_response(self, prompt: str, max_tokens: int = 1024) -> str:
"""
Generate text using the local LLM.
Args:
prompt: Input prompt for the LLM
max_tokens: Maximum number of tokens to generate
Returns:
Generated text response
"""
try:
response = self.llm(
prompt,
max_tokens=max_tokens,
temperature=0.7,
top_p=0.9,
stop=["</s>", "Human:", "User:"],
echo=False
)
return response['choices'][0]['text'].strip()
except Exception as e:
return f"Error generating response: {e}"
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
"""
Execute a writing task based on the incoming request.
Args:
context: The request context containing the message and task info
event_queue: Queue for sending back messages and status updates
"""
# Extract the user's writing request from the message
user_request = ""
if context.request.message and context.request.message.parts:
for part in context.request.message.parts:
if isinstance(part, TextPart):
user_request += part.text + " "
user_request = user_request.strip()
print(f"\nWriting Agent: Received writing request: {user_request}")
# Update task status to working
await event_queue.task_status_update(status="working")
# Construct a writing-focused prompt for the LLM
writing_prompt = f"""You are a professional writer and content creator. Your task is to create well-structured, engaging, and polished content.
Writing Task: {user_request}
Please create clear, well-organized content that:
- Has a logical structure with clear flow
- Uses professional yet accessible language
- Includes relevant details and examples
- Maintains reader engagement throughout
Written Content:"""
# Generate written content using the LLM
written_content = self._generate_response(writing_prompt, max_tokens=1536)
print(f"Writing Agent: Generated {len(written_content)} characters of content")
# Send the written content back as a message
response_message = Message(
kind="message",
role=Role.AGENT,
parts=[TextPart(text=written_content)]
)
await event_queue.message(response_message)
# Mark the task as completed
await event_queue.task_status_update(status="completed")
async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
"""
Handle cancellation of a writing task.
Args:
context: The request context
event_queue: Queue for sending status updates
"""
print(f"Writing Agent: Received cancel request for task {context.request.task_id}")
await event_queue.task_status_update(status="canceled")
def build_writing_agent_card(host: str, port: int) -> AgentCard:
"""
Build the Agent Card for the Writing Agent.
Args:
host: The hostname where the agent is running
port: The port number where the agent is listening
Returns:
AgentCard describing the Writing Agent
"""
return AgentCard(
protocolVersion="0.2.5",
name="WritingAgent",
description="Specialized agent for content creation and writing. Transforms information into polished, well-structured prose.",
url=f"http://{host}:{port}",
version="1.0.0",
capabilities=AgentCapabilities(streaming=True),
skills=[
AgentSkill(
id="content-writing",
name="Content Writing",
description="Creates well-structured, engaging content on various topics.",
tags=["writing", "content-creation", "prose"],
examples=[
"Write an article about renewable energy",
"Create a report on market trends",
"Draft a blog post about AI advancements"
]
),
AgentSkill(
id="text-formatting",
name="Text Formatting",
description="Formats and structures text for readability and impact.",
tags=["formatting", "structure", "editing"],
examples=[
"Format this research into a readable article",
"Structure these findings into a report"
]
)
]
)
async def main():
"""
Main entry point for the Writing Agent.
"""
# Configuration
host = "127.0.0.1"
port = 8002
model_path = "models/model.gguf" # Update this to your model path
print("="*60)
print("WRITING AGENT - A2A PROTOCOL")
print("="*60)
print()
# Build the Agent Card
agent_card = build_writing_agent_card(host, port)
# Initialize the executor with the LLM
executor = WritingAgentExecutor(model_path)
# Build the A2A application
app = A2AStarletteApplication(
agent_card=agent_card,
agent_executor=executor
)
# Start the server
print(f"Starting Writing Agent on {host}:{port}")
print(f"Agent Card available at: http://{host}:{port}/.well-known/agent.json")
print()
config = uvicorn.Config(
app.build(),
host=host,
port=port,
log_level="info"
)
server = uvicorn.Server(config)
await server.serve()
if __name__ == "__main__":
asyncio.run(main())
The Writing Agent follows the same structural pattern as the Research Agent but specializes in content creation. It exposes different skills in its Agent Card, specifically content-writing and text-formatting. The LLM prompt is tailored for writing tasks, emphasizing structure, clarity, and engagement. The agent runs on a different port, allowing both agents to operate simultaneously on the same machine.
IMPLEMENTING THE COORDINATOR AGENT
Now we implement the most sophisticated component: the Coordinator Agent. This agent acts as both an A2A server to receive user requests and an A2A client to communicate with the Research and Writing agents. It demonstrates the full power of multi-agent collaboration.
Create a file named coordinator_agent.py:
import uvicorn
import asyncio
import httpx
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.app import A2AStarletteApplication
from a2a.types import AgentCard, AgentCapabilities, AgentSkill, Message, TextPart, Role
from a2a.client.client import A2AClient
class CoordinatorAgentExecutor(AgentExecutor):
"""
Coordinates multi-agent workflows by orchestrating tasks across
specialized agents (Research and Writing agents).
"""
def __init__(self, research_agent_url: str, writing_agent_url: str):
"""
Initialize the coordinator with URLs of the agents it will coordinate.
Args:
research_agent_url: Base URL of the Research Agent
writing_agent_url: Base URL of the Writing Agent
"""
self.research_agent_url = research_agent_url
self.writing_agent_url = writing_agent_url
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
"""
Execute a coordinated multi-agent workflow.
This method:
1. Receives a high-level request from the user
2. Delegates research to the Research Agent
3. Passes research results to the Writing Agent
4. Returns the final written content to the user
Args:
context: The request context containing the user's message
event_queue: Queue for sending back messages and status updates
"""
# Extract the user's request
user_request = ""
if context.request.message and context.request.message.parts:
for part in context.request.message.parts:
if isinstance(part, TextPart):
user_request += part.text + " "
user_request = user_request.strip()
print(f"\nCoordinator: Received request: {user_request}")
# Update task status to working
await event_queue.task_status_update(status="working")
# Send progress update to user
progress_message = Message(
kind="message",
role=Role.AGENT,
parts=[TextPart(text="Starting multi-agent workflow. First, I'll gather research...")]
)
await event_queue.message(progress_message)
# Step 1: Delegate to Research Agent
research_result = await self._get_research(user_request)
if research_result.startswith("Error"):
# Research failed, report error and complete task
error_message = Message(
kind="message",
role=Role.AGENT,
parts=[TextPart(text=f"Research phase failed: {research_result}")]
)
await event_queue.message(error_message)
await event_queue.task_status_update(status="failed")
return
print(f"Coordinator: Research completed, {len(research_result)} characters received")
# Send progress update
progress_message = Message(
kind="message",
role=Role.AGENT,
parts=[TextPart(text="Research complete. Now creating polished content...")]
)
await event_queue.message(progress_message)
# Step 2: Delegate to Writing Agent with research results
writing_request = f"Based on the following research, create a comprehensive, well-structured article:\n\n{research_result}"
written_content = await self._get_written_content(writing_request)
if written_content.startswith("Error"):
# Writing failed, report error and complete task
error_message = Message(
kind="message",
role=Role.AGENT,
parts=[TextPart(text=f"Writing phase failed: {written_content}")]
)
await event_queue.message(error_message)
await event_queue.task_status_update(status="failed")
return
print(f"Coordinator: Writing completed, {len(written_content)} characters received")
# Step 3: Return final result to user
final_message = Message(
kind="message",
role=Role.AGENT,
parts=[TextPart(text=f"Multi-agent workflow complete! Here is the final result:\n\n{written_content}")]
)
await event_queue.message(final_message)
# Mark task as completed
await event_queue.task_status_update(status="completed")
async def _get_research(self, query: str) -> str:
"""
Communicate with the Research Agent to gather information.
Args:
query: The research query to send to the Research Agent
Returns:
Research results as a string, or error message
"""
print(f"Coordinator: Requesting research from {self.research_agent_url}")
async with httpx.AsyncClient(timeout=60.0) as http_client:
try:
# Discover the Research Agent via its Agent Card
research_client = await A2AClient.get_client_from_agent_card_url(
http_client=http_client,
agent_card_url=f"{self.research_agent_url}/.well-known/agent.json"
)
print("Coordinator: Successfully discovered Research Agent")
# Create a message to send to the Research Agent
research_message = Message(
kind="message",
role=Role.USER,
parts=[TextPart(text=query)]
)
# Send the message and collect the response
research_result = ""
async for event in research_client.send_message(message=research_message):
if isinstance(event, Message):
for part in event.parts:
if isinstance(part, TextPart):
research_result += part.text
# Task status updates are handled automatically by the SDK
return research_result
except httpx.ConnectError as e:
error_msg = f"Error: Could not connect to Research Agent at {self.research_agent_url}. Is it running?"
print(f"Coordinator: {error_msg}")
return error_msg
except Exception as e:
error_msg = f"Error during research: {str(e)}"
print(f"Coordinator: {error_msg}")
return error_msg
async def _get_written_content(self, writing_request: str) -> str:
"""
Communicate with the Writing Agent to create polished content.
Args:
writing_request: The writing request to send to the Writing Agent
Returns:
Written content as a string, or error message
"""
print(f"Coordinator: Requesting writing from {self.writing_agent_url}")
async with httpx.AsyncClient(timeout=60.0) as http_client:
try:
# Discover the Writing Agent via its Agent Card
writing_client = await A2AClient.get_client_from_agent_card_url(
http_client=http_client,
agent_card_url=f"{self.writing_agent_url}/.well-known/agent.json"
)
print("Coordinator: Successfully discovered Writing Agent")
# Create a message to send to the Writing Agent
writing_message = Message(
kind="message",
role=Role.USER,
parts=[TextPart(text=writing_request)]
)
# Send the message and collect the response
written_content = ""
async for event in writing_client.send_message(message=writing_message):
if isinstance(event, Message):
for part in event.parts:
if isinstance(part, TextPart):
written_content += part.text
# Task status updates are handled automatically by the SDK
return written_content
except httpx.ConnectError as e:
error_msg = f"Error: Could not connect to Writing Agent at {self.writing_agent_url}. Is it running?"
print(f"Coordinator: {error_msg}")
return error_msg
except Exception as e:
error_msg = f"Error during writing: {str(e)}"
print(f"Coordinator: {error_msg}")
return error_msg
async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
"""
Handle cancellation of a coordination task.
Args:
context: The request context
event_queue: Queue for sending status updates
"""
print(f"Coordinator: Received cancel request for task {context.request.task_id}")
# In a production system, you would also cancel any ongoing subtasks
# with the Research and Writing agents
await event_queue.task_status_update(status="canceled")
def build_coordinator_agent_card(host: str, port: int) -> AgentCard:
"""
Build the Agent Card for the Coordinator Agent.
Args:
host: The hostname where the agent is running
port: The port number where the agent is listening
Returns:
AgentCard describing the Coordinator Agent
"""
return AgentCard(
protocolVersion="0.2.5",
name="CoordinatorAgent",
description="Orchestrates multi-agent workflows by coordinating Research and Writing agents to produce comprehensive reports.",
url=f"http://{host}:{port}",
version="1.0.0",
capabilities=AgentCapabilities(streaming=True),
skills=[
AgentSkill(
id="create-report",
name="Create Report",
description="Creates comprehensive reports by coordinating research and writing tasks across multiple specialized agents.",
tags=["coordination", "orchestration", "multi-agent", "report-generation"],
examples=[
"Create a comprehensive report about renewable energy",
"Generate an article on the benefits of multi-agent systems",
"Produce a detailed analysis of quantum computing"
]
)
]
)
async def main():
"""
Main entry point for the Coordinator Agent.
"""
# Configuration
host = "127.0.0.1"
port = 8000
research_agent_url = "http://127.0.0.1:8001"
writing_agent_url = "http://127.0.0.1:8002"
print("="*60)
print("COORDINATOR AGENT - A2A PROTOCOL")
print("="*60)
print()
# Build the Agent Card
agent_card = build_coordinator_agent_card(host, port)
# Initialize the executor
executor = CoordinatorAgentExecutor(research_agent_url, writing_agent_url)
# Build the A2A application
app = A2AStarletteApplication(
agent_card=agent_card,
agent_executor=executor
)
# Start the server
print(f"Starting Coordinator Agent on {host}:{port}")
print(f"Agent Card available at: http://{host}:{port}/.well-known/agent.json")
print(f"Coordinating with:")
print(f" - Research Agent: {research_agent_url}")
print(f" - Writing Agent: {writing_agent_url}")
print()
config = uvicorn.Config(
app.build(),
host=host,
port=port,
log_level="info"
)
server = uvicorn.Server(config)
await server.serve()
if __name__ == "__main__":
asyncio.run(main())
The Coordinator Agent demonstrates the full power of the A2A protocol. It acts as both a server, exposing its own capabilities through an Agent Card, and as a client, discovering and communicating with other agents. The agent uses the A2AClient class to discover other agents via their Agent Cards at well-known URIs. It sends messages to remote agents and processes streaming responses. The coordinator implements a sequential workflow where research results feed into the writing task. Progress updates keep the user informed throughout the multi-step process. Error handling ensures graceful degradation if any agent is unavailable or fails.
CREATING A CLIENT TO TEST THE SYSTEM
Now let's create a simple client application that sends requests to the Coordinator Agent and displays the results. This demonstrates how external applications can interact with A2A agents.
Create a file named client.py:
import asyncio
import httpx
from a2a.client.client import A2AClient
from a2a.types import Message, TextPart, Role
async def send_request_to_coordinator(coordinator_url: str, user_request: str):
"""
Send a request to the Coordinator Agent and display the results.
Args:
coordinator_url: Base URL of the Coordinator Agent
user_request: The user's request to process
"""
print("="*60)
print("A2A CLIENT - SENDING REQUEST TO COORDINATOR")
print("="*60)
print()
print(f"Request: {user_request}")
print()
async with httpx.AsyncClient(timeout=120.0) as http_client:
try:
# Discover the Coordinator Agent via its Agent Card
print(f"Discovering Coordinator Agent at {coordinator_url}...")
coordinator_client = await A2AClient.get_client_from_agent_card_url(
http_client=http_client,
agent_card_url=f"{coordinator_url}/.well-known/agent.json"
)
print("Successfully discovered Coordinator Agent")
print()
# Create a message to send
user_message = Message(
kind="message",
role=Role.USER,
parts=[TextPart(text=user_request)]
)
# Send the message and stream the response
print("Sending request and streaming response...")
print("-"*60)
async for event in coordinator_client.send_message(message=user_message):
if isinstance(event, Message):
# Display message content
for part in event.parts:
if isinstance(part, TextPart):
print(f"\n{part.text}")
print("-"*60)
print("\nRequest completed successfully!")
except httpx.ConnectError as e:
print(f"Error: Could not connect to Coordinator Agent at {coordinator_url}")
print("Make sure the Coordinator Agent is running.")
print(f"Details: {e}")
except Exception as e:
print(f"Error during communication: {e}")
async def main():
"""
Main entry point for the client application.
"""
# Configuration
coordinator_url = "http://127.0.0.1:8000"
# Example request
user_request = "Create a comprehensive report about the benefits and challenges of multi-agent AI systems"
# Send the request
await send_request_to_coordinator(coordinator_url, user_request)
if __name__ == "__main__":
asyncio.run(main())
This client demonstrates how external applications interact with A2A agents. It discovers the Coordinator Agent using the well-known Agent Card URI. It sends a message using the A2A protocol. It streams the response, displaying message content as it arrives. The client handles connection errors gracefully, providing helpful feedback.
RUNNING THE COMPLETE MULTI-AGENT SYSTEM
Now that we have implemented all components, let's run the complete system and observe how the agents collaborate through the A2A protocol.
You will need four terminal windows to run this example. Make sure you have activated your virtual environment in each terminal and are in the project directory.
Terminal 1: Start the Research Agent
python research_agent.py
You should see output indicating the Research Agent has started and is listening on port 8001. The agent will display its Agent Card URL.
Terminal 2: Start the Writing Agent
python writing_agent.py
You should see output indicating the Writing Agent has started and is listening on port 8002.
Terminal 3: Start the Coordinator Agent
python coordinator_agent.py
You should see output indicating the Coordinator Agent has started on port 8000 and has identified the URLs of the Research and Writing agents it will coordinate.
Terminal 4: Run the Client
python client.py
You should now see the complete multi-agent workflow in action. The client discovers the Coordinator Agent and sends the request. The Coordinator receives the request and updates its task status to working. The Coordinator discovers the Research Agent via its Agent Card. The Coordinator sends a research request to the Research Agent. The Research Agent processes the request using its local LLM and returns results. The Coordinator receives the research results. The Coordinator discovers the Writing Agent via its Agent Card. The Coordinator sends a writing request with the research results to the Writing Agent. The Writing Agent creates polished content based on the research. The Coordinator receives the written content. The Coordinator sends the final result back to the client. The client displays the complete response.
Throughout this process, you will see detailed logging in each terminal showing the A2A protocol messages being exchanged, task status updates, and the flow of information between agents.
UNDERSTANDING THE A2A MESSAGE FLOW
Let's examine what actually happens under the hood when the client sends a request. Understanding this message flow helps you appreciate how the A2A protocol orchestrates complex multi-agent interactions.
When the client calls send_message on the A2AClient, the client first performs an HTTP GET request to the Coordinator's well-known URI to retrieve its Agent Card. The client examines the Agent Card to understand the Coordinator's capabilities, endpoint URL, and authentication requirements. The client constructs a JSON-RPC 2.0 request with the method message/send and the user's message as a parameter. The client sends this as an HTTP POST request to the Coordinator's API URL. The Coordinator's A2A server receives the request and validates it against the protocol specification. The server creates a new Task with a unique task ID and sets its status to submitted. The server invokes the CoordinatorAgentExecutor's execute method, passing the request context and an event queue. The executor updates the task status to working and sends this update through the event queue. The A2A server converts the status update to a JSON-RPC notification and sends it to the client via Server-Sent Events.
The Coordinator now acts as a client to the Research Agent. It performs an HTTP GET to retrieve the Research Agent's Agent Card. It constructs a JSON-RPC request with the research query. It sends the request to the Research Agent's API URL. The Research Agent receives the request, creates a task, and invokes its executor. The Research Agent's executor uses the local LLM to generate research findings. The Research Agent sends the results back as a Message through its event queue. The A2A server converts this to a JSON-RPC response and sends it back to the Coordinator. The Coordinator receives the research results.
The Coordinator now acts as a client to the Writing Agent. It retrieves the Writing Agent's Agent Card. It constructs a JSON-RPC request with the writing task, including the research results. It sends the request to the Writing Agent's API URL. The Writing Agent receives the request, creates a task, and invokes its executor. The Writing Agent's executor uses the local LLM to create polished content. The Writing Agent sends the written content back as a Message. The Coordinator receives the written content.
Finally, the Coordinator sends the final result to the original client. It creates a Message containing the written content. It sends this through its event queue. The A2A server converts this to a JSON-RPC notification and sends it to the client via Server-Sent Events. The client receives and displays the final result. The Coordinator updates the task status to completed. The client receives the completion notification.
Throughout this entire flow, all communication follows the A2A protocol specification. Messages are formatted as JSON-RPC 2.0 requests and responses. Task lifecycle states are properly managed and communicated. Agent discovery happens through standardized Agent Cards. Authentication and security are handled at the HTTP layer. The protocol abstracts away all these details, allowing developers to focus on agent logic rather than communication mechanics.
ADVANCED A2A FEATURES AND PATTERNS
The example we have built demonstrates the core A2A protocol, but there are several advanced patterns and features worth exploring for production systems.
One important pattern is streaming responses for long-running tasks. The A2A protocol supports Server-Sent Events, which allows agents to stream partial results back to clients as they become available. This is particularly valuable for tasks that take significant time to complete, as it provides immediate feedback and allows for progressive rendering of results. To implement streaming, agents can send multiple Message events through the event queue before sending the final completion status. Each message appears to the client as it is sent, creating a real-time communication channel.
Another valuable pattern is task cancellation and cleanup. The AgentExecutor interface includes a cancel method that is invoked when a client requests task cancellation. In a production system, this method should implement proper cleanup logic, stopping any ongoing LLM generation, releasing resources, and notifying any downstream agents of the cancellation. The A2A protocol ensures that cancellation requests are properly propagated through the task lifecycle.
Error handling and recovery is crucial in production systems. The A2A protocol includes comprehensive error reporting through JSON-RPC error responses. When an agent encounters an error, it should set the task status to failed and include detailed error information in the response. Clients can then decide whether to retry the request, fall back to alternative agents, or report the error to users. Implementing retry logic with exponential backoff is a common pattern for handling transient failures.
Agent discovery and registration can be made more sophisticated by implementing a service registry pattern. Instead of hardcoding agent URLs, you can create a central registry service where agents register themselves at startup and periodically send heartbeat signals. Clients can query the registry to discover available agents with specific capabilities. This enables dynamic agent populations where new agents can join the system at runtime and failed agents can be detected and removed. The registry itself can be implemented as an A2A agent, making it part of the ecosystem rather than a separate infrastructure component.
Load balancing becomes important when multiple agents offer the same capabilities. The A2A protocol's skill-based discovery makes this straightforward. A registry or router agent can maintain a list of all agents offering a particular skill and distribute requests among them based on current load, response time, or other metrics. This allows the system to scale horizontally by adding more instances of popular agent types.
Security and authentication are essential for multi-agent systems that span trust boundaries. The A2A protocol supports various authentication schemes through the securitySchemes field in the Agent Card. Common patterns include bearer tokens where each agent is issued a JWT token that it includes in requests to other agents, API keys for simpler authentication scenarios, OAuth 2.0 for delegated authorization, and mutual TLS for high-security environments. The protocol handles authentication at the HTTP layer, keeping it separate from the JSON-RPC payload and making it compatible with standard web security practices.
Conversation context and memory enable more sophisticated agent interactions. While our example processes each request independently, production systems often need to maintain context across multiple turns. The A2A protocol supports this through the conversation context in messages. Agents can store conversation state in a database or memory store, keyed by conversation ID, and retrieve it when processing subsequent messages in the same conversation. This enables multi-turn dialogues where agents remember previous exchanges and build upon them.
PERFORMANCE CONSIDERATIONS AND OPTIMIZATION
Running multiple LLM instances simultaneously requires careful resource management, especially when using GPU acceleration. Each agent in our example loads its own model, which can quickly exhaust GPU memory. For production deployments, consider these optimization strategies.
Model sharing allows multiple agents to share a single LLM instance, reducing memory footprint significantly. This requires running a model server that agents communicate with via an API. The llama.cpp project includes a server mode that exposes an OpenAI-compatible API. You can run one llama.cpp server instance and configure all your agents to use it as their LLM backend instead of loading models directly. This dramatically reduces memory usage and allows you to run more agents on the same hardware.
Quantization reduces model size and memory requirements at the cost of some accuracy. The GGUF format supports various quantization levels from 2-bit to 8-bit. For many agent tasks, 4-bit or 5-bit quantization provides an excellent balance between quality and resource usage. Experiment with different quantization levels to find the sweet spot for your use case. Generally, research and writing tasks can tolerate more aggressive quantization than tasks requiring precise reasoning or calculation.
Batching can improve throughput when multiple agents have pending requests. Instead of processing each agent's prompt individually, batch them together and process them in parallel. This is particularly effective on GPUs where parallel processing capabilities are underutilized by single requests. However, batching introduces latency as requests wait for a batch to fill, so it works best for high-throughput scenarios rather than interactive applications.
Agent specialization through fine-tuning can improve both quality and efficiency. Rather than using a general-purpose model for all agents, fine-tune smaller, specialized models for each agent type. A research agent might use a model fine-tuned on question-answering and information retrieval tasks, while a writing agent uses one optimized for content generation and style adaptation. Smaller specialized models often outperform larger general models on specific tasks while using fewer resources.
Caching and memoization can eliminate redundant LLM calls. If multiple agents ask similar questions or process similar inputs, cache the results and reuse them. This is particularly effective for capability queries, common research topics, and frequently requested information. Implement a shared cache that all agents can access, with appropriate cache invalidation policies to ensure freshness.
Asynchronous processing is built into the A2A SDK through its use of Python's asyncio. This allows agents to handle multiple concurrent requests without blocking. When an agent is waiting for an LLM response, it can process other requests or perform other work. Make sure your agent implementations properly leverage async/await to maximize concurrency.
MONITORING AND DEBUGGING MULTI-AGENT SYSTEMS
Understanding what is happening inside a multi-agent system can be challenging since interactions are distributed and asynchronous. Implementing comprehensive monitoring and debugging capabilities is essential for development and production operation.
Message logging provides visibility into all agent communications. The A2A SDK can be configured to log all JSON-RPC messages, allowing you to see exactly what data is being exchanged between agents. Implement structured logging that captures message IDs, task IDs, timestamps, sender and recipient information, and message content. Store these logs in a searchable format like JSON Lines or send them to a log aggregation service like Elasticsearch. This makes it easy to trace complete workflows from start to finish and debug issues.
Performance metrics help identify bottlenecks and optimization opportunities. Track metrics like message processing latency measuring the time from receiving a request to sending the first response, LLM inference time tracking how long model generation takes, task completion time measuring end-to-end task duration, queue depths monitoring how many pending requests each agent has, and agent utilization rates calculating the percentage of time agents spend actively processing versus idle. Export these metrics to a monitoring system like Prometheus and create dashboards in Grafana to visualize system behavior.
Distributed tracing provides end-to-end visibility into multi-agent workflows. The A2A SDK supports OpenTelemetry integration, which allows you to trace requests as they flow through multiple agents. Each agent creates spans representing its work, and these spans are linked together to form a complete trace. Tracing tools like Jaeger or Zipkin can then visualize these traces, showing you exactly how long each step took and where bottlenecks occur.
Health checks and heartbeats ensure agents remain responsive. Implement a health endpoint on each agent that returns its current status, including whether the LLM is loaded and ready, how many active tasks it is processing, current queue depth, and resource usage like memory and CPU. A monitoring service can periodically check these endpoints and alert operators to problems. The A2A protocol itself does not define health check mechanisms, but you can add them as additional HTTP endpoints on your agent servers.
Visualization tools can make complex agent interactions comprehensible. Build a web dashboard that displays active agents and their capabilities, current tasks and their states, message flows between agents, and performance metrics in real-time. Sequence diagrams showing message exchanges help developers understand and debug complex workflows. Tools like Mermaid can generate these diagrams programmatically from log data.
EXTENDING THE SYSTEM WITH ADDITIONAL AGENTS
The multi-agent system we have built provides a solid foundation that can be extended in numerous directions. Here are some practical extensions that demonstrate the flexibility of the A2A protocol.
Adding a Verification Agent would enhance the quality of generated content. This agent would receive the written content from the Writing Agent and perform fact-checking, consistency verification, quality assessment, and source validation. It would expose skills like fact-check and quality-assurance in its Agent Card. The Coordinator would add a third step to its workflow, sending the written content to the Verification Agent before returning the final result. This demonstrates how easily new agents can be inserted into existing workflows.
Implementing a Translation Agent would enable multilingual content generation. This agent would expose skills for translating content between various languages. The Coordinator could offer a new skill that generates reports in multiple languages by coordinating the Research, Writing, and Translation agents. The Translation Agent could use a specialized translation model or call external translation APIs, demonstrating how A2A agents can wrap existing services.
Creating a Data Analysis Agent would enable agents to work with structured data. This agent would expose skills for analyzing datasets, generating visualizations, computing statistics, and identifying trends. It could integrate with libraries like pandas and matplotlib. The Research Agent could delegate quantitative research tasks to the Data Analysis Agent, demonstrating agent-to-agent delegation beyond just the Coordinator.
Building a Planning Agent would enable more sophisticated task decomposition. Instead of the Coordinator using simple rules or LLM prompts to break down tasks, it could delegate to a specialized Planning Agent that uses advanced planning algorithms. The Planning Agent would receive a high-level goal and return a detailed execution plan with dependencies, resource requirements, and time estimates. This demonstrates how agents can provide meta-level services to other agents.
Implementing a Memory Agent would enable persistent knowledge across sessions. This agent would maintain a knowledge graph or vector database of information gathered in previous interactions. Other agents could query the Memory Agent to retrieve relevant context before processing new requests. This demonstrates how agents can provide shared services that enhance the capabilities of the entire system.
INTEGRATING WITH EXTERNAL TOOLS AND SERVICES
While our example agents use local LLMs for all processing, production agents often need to integrate with external tools and services. The A2A protocol makes this straightforward since agents encapsulate their implementation details.
The Research Agent could integrate with real web search APIs like Google Custom Search, Bing Web Search, or DuckDuckGo. Instead of relying solely on the LLM's training data, it would perform actual web searches and synthesize the results. The agent's implementation would change, but its Agent Card and A2A interface would remain the same. Other agents would not need to know or care that the Research Agent is now using external APIs.
Database integration allows agents to work with persistent data. An agent could connect to PostgreSQL, MongoDB, or other databases to retrieve information, store results, or maintain state. The A2A protocol's task model maps naturally to database transactions, with task IDs serving as transaction identifiers.
API wrapping enables agents to expose existing services through the A2A protocol. If you have a legacy API or third-party service, you can create an A2A agent that wraps it, translating between the A2A protocol and the service's native API. This allows the service to participate in multi-agent workflows without modification.
Tool use frameworks like LangChain or the Model Context Protocol can be integrated within individual agents. An agent's AgentExecutor can use LangChain to orchestrate complex tool use internally while exposing a simple A2A interface externally. This demonstrates how A2A complements rather than replaces existing agent frameworks.
COMPARISON WITH OTHER AGENT PROTOCOLS
Understanding how the A2A protocol relates to other agent communication standards helps you choose the right tool for your use case.
The Model Context Protocol from Anthropic focuses on how AI models and agents interact with tools and resources. MCP standardizes the interface between models and tools like file systems, databases, and APIs. A2A standardizes how independent agents communicate with each other as peers. These protocols are complementary. An agentic application might use A2A for inter-agent communication while each agent internally uses MCP to interact with its specific tools and resources.
FIPA, the Foundation for Intelligent Physical Agents, is an IEEE standard that has been around since the 1990s. It defines a comprehensive agent communication language based on speech act theory. FIPA is more formal and complex than A2A, with extensive specifications for agent lifecycle management, directory services, and interaction protocols. A2A takes a more pragmatic approach, building on familiar web standards and focusing on practical interoperability. FIPA is better suited for academic research and formal multi-agent systems, while A2A targets practical enterprise deployments.
OpenAI's Swarm framework is a lightweight Python library for building multi-agent systems. Swarm focuses on handoffs and routines between agents within a single application. It is not a protocol but rather a programming framework. A2A is a protocol that enables agents from different developers, frameworks, and organizations to interoperate. You could implement Swarm-style agent coordination using the A2A protocol, but A2A also supports much broader scenarios.
AutoGen from Microsoft Research enables multi-agent conversations with support for both LLM-based and human agents. Like Swarm, AutoGen is primarily a framework rather than a protocol. It provides patterns for agent collaboration within a single application. A2A could be used to connect AutoGen-based agent systems with agents built using other frameworks, providing a standardization layer above the framework level.
LangGraph from LangChain provides stateful, graph-based agent workflows. It excels at defining complex agent interaction patterns within an application. A2A could be used to expose LangGraph workflows as agents that other systems can interact with, or to allow LangGraph-based agents to communicate with agents built using other tools.
PRODUCTION DEPLOYMENT CONSIDERATIONS
Moving from a development prototype to a production multi-agent system requires addressing several operational concerns.
Containerization makes deployment consistent and reproducible. Package each agent as a Docker container with its dependencies, model files, and configuration. Use Docker Compose or Kubernetes to orchestrate multiple agent containers. This ensures agents can be deployed consistently across development, staging, and production environments.
Service discovery in production environments typically uses tools like Consul, etcd, or Kubernetes DNS. Instead of hardcoding agent URLs, agents register themselves with the service discovery system at startup. Clients query the service discovery system to find available agents with specific capabilities. This enables dynamic scaling where new agent instances can be added without reconfiguring existing agents.
Load balancing distributes requests across multiple instances of the same agent type. Use a reverse proxy like nginx or a cloud load balancer to distribute incoming requests. The A2A protocol's stateless design makes this straightforward since any instance of an agent can handle any request for its capabilities.
Monitoring and observability are critical for production systems. Implement comprehensive logging, metrics collection, and distributed tracing as discussed earlier. Set up alerts for error rates, latency spikes, and resource exhaustion. Use tools like Prometheus, Grafana, and Jaeger to monitor system health.
Security hardening protects production systems from attacks. Implement authentication and authorization for all agent endpoints. Use TLS for all communication. Validate and sanitize all inputs. Implement rate limiting to prevent abuse. Run agents with minimal privileges. Regularly update dependencies to patch security vulnerabilities.
Disaster recovery ensures business continuity. Implement backup and restore procedures for any persistent state. Design agents to be stateless where possible, storing state in external databases that can be backed up. Test failover procedures regularly. Implement circuit breakers to prevent cascading failures when agents become unavailable.
CONCLUSION AND FUTURE DIRECTIONS
We have built a complete multi-agent system using Google's A2A protocol, demonstrating how standardized agent communication enables sophisticated collaborative AI systems. The protocol's design principles of agent independence, web standards compatibility, enterprise-grade security, flexible timelines, and content type agnosticism make it practical for real-world deployments.
The key insights from this implementation are that standardization enables interoperability, allowing agents from different developers to work together seamlessly. Capability-based discovery provides flexibility, letting systems adapt to changing agent populations and requirements. Asynchronous message passing enables scalability, allowing agents to process multiple requests concurrently. Task lifecycle management provides visibility, keeping clients informed about long-running operations. Building on web standards reduces complexity, allowing developers to leverage familiar tools and libraries.
The A2A protocol represents an important step toward a future where AI agents from different organizations, built with different tools, can collaborate to solve complex problems. Just as HTTP enabled the web by providing a common protocol for information exchange, A2A aims to enable an ecosystem of interoperable AI agents.
Future developments in this space will likely include enhanced agent reasoning capabilities, allowing agents to engage in more sophisticated negotiation and planning. Improved learning and adaptation, enabling agents to learn from past interactions and improve over time. Standardized agent marketplaces where developers can publish agents and users can discover and compose them into custom workflows. Integration with blockchain and decentralized systems for trustless agent collaboration. Advanced security and privacy mechanisms for handling sensitive data in multi-agent systems.
The multi-agent system we have built is just the beginning. With the foundation of the A2A protocol, you can create increasingly sophisticated agent ecosystems that tackle complex real-world problems through collaboration and specialization. The future of AI is not monolithic models, but ecosystems of specialized agents working together, and the A2A protocol provides the communication layer that makes this future possible.
About the Author: This comprehensive guide was created to help developers understand and implement multi-agent systems using Google's A2A protocol. The examples demonstrate production-ready patterns while remaining accessible to developers new to agent-based architectures.
Resources: