Google A2A (Agent2Agent) Protocol Tutorial: Build Discovering Agents in Python
Learn how to build discovering AI agents using Google's A2A protocol, Agent Cards, JSON-RPC 2.0, and Python. Connect LangGraph to Google ADK.
The rapid explosion of agent frameworks has created an unintended engineering crisis: vendor silos. While teams build capable autonomous workers using LangGraph, Google ADK, CrewAI, or AutoGen, these agents remain trapped inside their proprietary runtimes, unable to discover or delegate tasks to external agents across network boundaries.
Breaking down these isolated silos requires an open, vendor-neutral wire standard for inter-agent communication. In our architectural exploration of AI agent memory systems, we discussed how agents maintain local state and episodic context.
This tutorial shows you how to implement the Google A2A protocol specification in Python. You will learn how to enable decentralized agents to discover capabilities via Agent Cards (agent.json), coordinate tasks over JSON-RPC 2.0, and bridge disparate runtimes like LangGraph and Google ADK.
Key Takeaways
- The Google A2A protocol provides an open, transport-agnostic standard for inter-agent discovery, capability negotiation, and asynchronous task execution.
- Agent discovery centers on Agent Cards (
.well-known/agent.json), which declare identity, security requirements, and modular skill interfaces over standard HTTPS.- Task execution uses JSON-RPC 2.0 over HTTP with Server-Sent Events (SSE) for streaming incremental thoughts, progress updates, and task artifacts.
- A2A enforces 100% opaque agent boundaries: agents collaborate securely without exposing internal system prompts, proprietary memory, or model weights.
- Using the Python
a2a-sdk, developers can expose Google ADK specialists and invoke them dynamically from LangGraph orchestrator graphs.
Figure 1: Google A2A discovery and execution lifecycle: client agents fetch Agent Cards over HTTPS, initiate tasks with JSON-RPC 2.0, and consume real-time SSE artifacts.
The Multi-Agent Silo Problem: Why We Need an Open Agent-to-Agent Protocol
Early multi-agent architectures operated under the assumption of a shared runtime. Developers built multi-agent systems where supervisor agents and workers resided in the same Python process, sharing in-memory dictionaries and shared message queues.
The Fragmentation of Proprietary Agent Runtimes
In real-world enterprise architectures, monolithic multi-agent systems quickly break down. A financial risk team might build a specialized audit agent using Google ADK and Gemini, while an engineering squad orchestrates developer tooling with LangGraph and Claude.
Without a common inter-agent protocol, connecting these agents requires writing fragile, custom point-to-point REST adapters for every pair of workers. Each team must reinvent authentication schemes, polling loops, error formats, and task serialization routines, creating an unmaintainable web of proprietary glue code.
How Google A2A Enables Decentralized Agent Federation
The Google A2A protocol solves runtime fragmentation by standardizing the boundary between independent agents. Inspired by classic web principles, A2A defines a lightweight communication protocol layered over standard HTTP, JSON-RPC 2.0, and Server-Sent Events.
Instead of sharing runtime code, agents communicate across clean network contracts. An agent publishes what it can do through a public Agent Card, accepts structured task payloads from remote callers, and streams back verifiable artifacts upon completion.
Crucially, A2A preserves complete operational privacy. The invoking agent never sees the worker’s internal reasoning chains, prompt templates, or proprietary databases, ensuring enterprise security across organizational perimeters.
Anatomy of an Agent Card: The /.well-known/agent.json Standard
At the core of the A2A discovery mechanism is the Agent Card. Analogous to robots.txt for web crawlers or .well-known/openid-configuration for OAuth2, an Agent Card is a machine-readable JSON document hosted at /.well-known/agent.json.
Metadata Fields: Name, Version, and Provider Authentication
An Agent Card defines identity, endpoint routing, and security guardrails. Below is a production-compliant agent.json manifest for an autonomous foreign exchange specialist:
{
"name": "GlobalForexAgent",
"version": "1.0.0",
"description": "An autonomous financial agent providing real-time currency conversions and macro forecasting.",
"provider": {
"organization": "Enterprise Financial AI Systems",
"contact": "support@example.com"
},
"url": "https://forex-agent.example.com/a2a",
"documentationUrl": "https://forex-agent.example.com/docs",
"capabilities": {
"streaming": true,
"pushNotifications": false
},
"authentication": {
"type": "bearer"
},
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"skills": [
{
"id": "convert_currency",
"name": "Convert Currency",
"description": "Calculates live currency conversion rates between global fiat currencies.",
"tags": ["finance", "forex", "rates"],
"inputModes": ["text"],
"outputModes": ["text"]
}
]
}
Declaring Modular Skills and I/O Modes
The skills array declares the discrete operational capabilities the remote agent exposes to callers. Each skill defines:
id: A stable, machine-readable identifier used during task invocation.description: A natural language explanation that caller agents use for semantic routing decisions.inputModesandoutputModes: Specifies supported data formats (such astext,audio, or structured JSON objects).
By inspecting this card, a client orchestrator can dynamically decide whether the remote agent possesses the requisite competence to solve a user request.
Under the Hood: The A2A Task Lifecycle and SSE Artifact Streaming
Communication in A2A follows a structured task execution lifecycle. The protocol models long-running units of work as stateful Task entities governed by JSON-RPC 2.0 semantics.
Discovery Handshake: Fetching Remote Agent Cards
Before delegating work, the client agent performs an HTTP GET request to https://remote-agent.example.com/.well-known/agent.json. The client parses the JSON response, validates security requirements (such as Bearer token headers), and caches the agent’s published skills.
Because Agent Cards are static or long-lived documents, client agents can cache cards locally with HTTP ETag headers, keeping discovery latency under 10ms on subsequent task executions.
Task Delegation via JSON-RPC 2.0 Payloads
Once discovery completes, the caller initiates work by dispatching a JSON-RPC 2.0 POST request to the agent’s base endpoint:
{
"jsonrpc": "2.0",
"method": "tasks/create",
"params": {
"skill_id": "convert_currency",
"message": {
"role": "user",
"content": {
"text": "Convert 5000 USD to JPY using current market rates."
}
}
},
"id": "task_req_4281"
}
The remote server acknowledges the request by returning a unique task_id and initializing an execution context.
Streaming Real-Time Thought Traces and Artifacts via SSE
For long-running tasks, A2A leverages Server-Sent Events (SSE) over standard HTTP connections. The server emits typed lifecycle events, allowing caller agents to track progress in real-time:
event: task_status
data: {"task_id": "task_77", "state": "WORKING", "progress": 0.5}
event: task_artifact
data: {"task_id": "task_77", "state": "COMPLETED", "artifact": {"parts": [{"text": "5000 USD = 772,500 JPY at 154.50 JPY/USD."}]}}
This streaming design prevents gateway timeouts while giving users visibility into intermediate sub-agent thought cycles.
Step-by-Step Python Implementation: Building an A2A Server
Building a compliant A2A server in Python requires creating an asynchronous service that serves both static discovery endpoints and stateful task execution routes. The official a2a-sdk wraps standard ASGI frameworks like FastAPI and Starlette, mounting standard handlers for JSON-RPC 2.0 dispatch and Server-Sent Event streaming.
At the center of your server architecture is the AgentExecutor interface. When incoming tasks arrive from remote caller agents, the server maps the JSON-RPC request to a task object, establishes an execution context, and passes both to your executor. This design cleanly decouples network wire serialization from your agent’s underlying business logic or model inference calls.
By deploying your A2A server with high-throughput ASGI workers via Uvicorn, your agent can handle multiple concurrent peer delegations while maintaining strict isolation across incoming task contexts.
Installing Dependencies
Install the official A2A Python SDK and ASGI server packages:
pip install a2a-sdk uvicorn pydantic python-dotenv
Implementing the Custom AgentExecutor Business Logic
Create a file named server.py. The AgentExecutor handles incoming tasks, executes business reasoning, and returns completed task artifacts:
import uvicorn
from a2a.server import A2AServer, AgentExecutor, TaskContext
from a2a.types import Task, TaskState
class ForexAgentExecutor(AgentExecutor):
"""Executes currency conversion tasks conforming to A2A v1.0 specifications."""
async def execute(self, context: TaskContext, task: Task) -> None:
# Extract prompt text from incoming task payload
user_text = task.message.get("content", {}).get("text", "")
print(f"[A2A Server] Received incoming task: '{user_text}'")
# Business logic execution (mock rates for deterministic demonstration)
conversion_rate = 154.50
amount_usd = 5000.0
amount_jpy = amount_usd * conversion_rate
result_message = (
f"Forex Specialist Evaluation: {amount_usd:,.2f} USD equals "
f"{amount_jpy:,.2f} JPY based on live rate ({conversion_rate} JPY/USD)."
)
# Transition task state and attach output artifacts
task.state = TaskState.COMPLETED
task.artifacts = [
{
"parts": [
{"type": "text", "text": result_message}
]
}
]
# Commit updated state back to client stream
await context.update_task(task)
print("[A2A Server] Task execution completed and artifacts committed.")
Mounting and Booting the ASGI Server with Uvicorn
Configure the A2AServer with your agent.json manifest path and launch the service:
# Initialize A2A server application
app = A2AServer(
agent_card_path="agent.json",
executor=ForexAgentExecutor()
)
if __name__ == "__main__":
print("Launching A2A Foreign Exchange Specialist on port 8080...")
# Mount ASGI app on standard port
uvicorn.run(app.asgi_app, host="0.0.0.0", port=8080)
Launch the server from your terminal:
python server.py
Verify that the Agent Card is properly hosted at the standard .well-known path:
curl -s http://localhost:8080/.well-known/agent.json | grep "GlobalForexAgent"
Consuming Remote Agents: Implementing the Python A2AClient
Once an A2A service is deployed across your private cloud or public infrastructure, client applications interact with it using the A2AClient interface. Rather than hardcoding tool URLs or rigid parameter payloads, the client implements dynamic capability discovery, verifying supported skills before dispatching execution requests.
Under the hood, A2AClient performs automated schema negotiation. It fetches the remote Agent Card, evaluates declared input modes (such as text or structured parameters), and builds compliant JSON-RPC 2.0 requests. If an endpoint requires Bearer authentication, the client injects authorization headers into all subsequent task handshakes.
Furthermore, A2AClient abstracts asynchronous response streaming. When executing long-running tasks, the client consumes incoming Server-Sent Events, updating internal task state representations and yielding completed output artifacts without requiring manual polling loops.
Dynamic Capability Discovery via get_agent_card()
Create a file named client.py demonstrating dynamic discovery and execution:
import asyncio
from a2a.client import A2AClient
async def main():
target_agent_url = "http://localhost:8080"
client = A2AClient(base_url=target_agent_url)
# 1. Discover remote agent capabilities
print(f"Connecting to remote agent at {target_agent_url}...")
agent_card = await client.get_agent_card()
print("\n--- Discovered Agent Metadata ---")
print(f"Agent Name: {agent_card['name']}")
print(f"Version: {agent_card['version']}")
print(f"Organization: {agent_card['provider']['organization']}")
print(f"Available Skill: {agent_card['skills'][0]['name']} ({agent_card['skills'][0]['id']})")
print(f"Skill Description: {agent_card['skills'][0]['description']}")
# 2. Dispatch task to the remote specialist
print("\nDispatching conversion task...")
response = await client.send_task(
skill_id="convert_currency",
message="Convert 5000 USD to JPY"
)
# 3. Inspect response artifacts
print("\n--- Task Result from Remote Agent ---")
artifact_text = response["artifacts"][0]["parts"][0]["text"]
print(f"Response: {artifact_text}")
if __name__ == "__main__":
asyncio.run(main())
Execute the client script:
python client.py
The output confirms that the client dynamically discovered the agent’s published skills, dispatched the conversion request over JSON-RPC, and parsed the resulting artifact without direct code imports.
Figure 2: Cross-framework interoperability topology: a LangGraph orchestrator graph delegates specialized financial calculations to a remote Google ADK worker over A2A.
Cross-Framework Interoperability: Connecting LangGraph to Google ADK via A2A
The true value of A2A lies in connecting heterogeneous agent runtimes. In this section, we build a bridge connecting a LangGraph orchestrator to a remote Google Agent Development Kit (ADK) specialist, as shown in Figure 2.
Exposing a Google ADK Specialist Agent with to_a2a()
Google’s Agent Development Kit provides native helpers to turn internal LlmAgent definitions into A2A services using to_a2a():
# adk_specialist.py
from adk import LlmAgent
from a2a.integration.adk import to_a2a
import uvicorn
# Define specialist agent using Google ADK
adk_worker = LlmAgent(
name="FinancialAnalysisSpecialist",
model="gemini-2.5-pro",
system_instruction="You are a senior hedge fund analyst specializing in FX conversions and macro liquidity."
)
# to_a2a automatically constructs the agent.json card and mounts ASGI routes
adk_server_app = to_a2a(adk_worker)
if __name__ == "__main__":
uvicorn.run(adk_server_app, host="0.0.0.0", port=8081)
Building a LangGraph Dispatch Node with A2AClient
Inside your LangGraph orchestrator application, define a node that calls the remote ADK specialist whenever a financial conversion query is identified:
# langgraph_orchestrator.py
from typing import TypedDict, List
from langchain_core.messages import HumanMessage, BaseMessage
from langgraph.graph import StateGraph, START, END
from a2a.client import A2AClient
class OrchestratorState(TypedDict):
messages: List[BaseMessage]
specialist_result: str
# Initialize A2A client targeting the Google ADK worker on port 8081
a2a_remote_client = A2AClient(base_url="http://localhost:8081")
async def a2a_dispatch_node(state: OrchestratorState):
"""LangGraph node delegating work to remote Google ADK worker via A2A."""
latest_query = state["messages"][-1].content
print(f"[LangGraph Node] Delegating query to ADK worker: '{latest_query}'")
try:
# Dispatch task to remote ADK agent over open A2A wire protocol
task_response = await a2a_remote_client.send_task(
skill_id="convert_currency",
message=str(latest_query)
)
result_text = task_response["artifacts"][0]["parts"][0]["text"]
return {"specialist_result": result_text}
except Exception as exc:
print(f"[A2A Error] Delegation failed: {exc}")
return {"specialist_result": "Error communicating with remote specialist."}
# Build LangGraph workflow
workflow = StateGraph(OrchestratorState)
workflow.add_node("delegate_to_adk", a2a_dispatch_node)
workflow.add_edge(START, "delegate_to_adk")
workflow.add_edge("delegate_to_adk", END)
orchestrator_app = workflow.compile()
This clean separation allows your team to compose complex distributed systems without coupling framework codebases. For additional structural patterns on composing multi-agent systems, review our complete guide on multi-agent systems.
Production Troubleshooting Runbook for A2A Protocols
Operating distributed agents across networks introduces distinct failure modes. Use this diagnostic guide to resolve the four most prevalent A2A integration errors.
Resolving HTTP 404 on /.well-known/agent.json Endpoints
If callers fail with ClientError: 404 Not Found on /.well-known/agent.json, verify that reverse proxies (such as Nginx or Cloudflare) are not blocking dot-prefixed paths.
Nginx often contains default rules blocking hidden directories:
# INCORRECT (Blocks .well-known):
location ~ /\. { deny all; }
# CORRECT (Permits standard discovery endpoints):
location ^~ /.well-known/ {
allow all;
proxy_pass http://localhost:8080;
}
Confirm accessibility using curl:
curl -I http://localhost:8080/.well-known/agent.json
Fixing JSON-RPC 2.0 Parse Errors and Schema Validation Mismatches
If the server logs JSON-RPC error: -32700 Parse error or -32600 Invalid Request, inspect the request body formatting.
Common mistakes include omitting "jsonrpc": "2.0" from top-level payloads or nesting the message object incorrectly inside params. Use strict Pydantic schemas on both ends to catch serialization bugs prior to network egress.
Handling SSE Streaming Connection Drops and Timeout Retries
Long-running agent reasoning loops can exceed standard HTTP proxy timeouts (typically 60 seconds). When this occurs, intermediary proxies terminate the SSE connection before the agent emits the final COMPLETED event.
Configure explicit keep-alive heartbeat pings in your ASGI configuration:
# Configure 15-second heartbeat in A2AServer
app = A2AServer(
agent_card_path="agent.json",
executor=ForexAgentExecutor(),
heartbeat_interval_seconds=15
)
Diagnosing Missing Skill ID and Unsupported Input Mode Exceptions
If a client receives JSON-RPC error: -32601 Method not found or SkillNotFoundException, compare the skill_id passed in send_task() against the exact strings listed in the remote agent.json manifest.
Always verify that the caller’s payload format matches the declared defaultInputModes (such as supplying plain text versus base64 audio). For a review of production agent tool interfaces, see our practical guide to AI agent code patterns.
Frequently Asked Questions About the Google A2A Protocol
What is the Google A2A (Agent2Agent) protocol?
Google A2A is an open communication standard that allows autonomous AI agents to discover one another, negotiate capabilities, and delegate complex tasks across organizational and framework boundaries. It utilizes HTTP, JSON-RPC 2.0, and Server-Sent Events to maintain transparent, decoupled interoperability between disparate runtimes.
What is an Agent Card (.well-known/agent.json) in A2A?
An Agent Card is a machine-readable JSON document hosted at /.well-known/agent.json that publishes an agent’s identity, version, base URL, authentication schemes, and list of supported skills. Caller agents inspect this card to discover remote capabilities before dispatching task requests.
How does the A2A task lifecycle work with JSON-RPC 2.0 and SSE?
Callers initiate a task by dispatching a JSON-RPC 2.0 request containing the target skill ID and user message. The server executes the task asynchronously, using Server-Sent Events to stream progress status updates and final output artifacts back to the caller in real-time.
How is A2A different from Anthropic’s Model Context Protocol (MCP)?
Anthropic’s Model Context Protocol (MCP) is designed for Agent-to-Tool and Agent-to-Database connectivity, providing structured access to local and remote resources. Google A2A is designed for Agent-to-Agent collaboration, standardizing discovery, multi-turn task negotiation, and opaque inter-agent delegation.
How do you connect a LangGraph agent to a remote Google ADK agent using A2A?
You expose the Google ADK agent as an A2A service using to_a2a() and run it on an ASGI port. Within LangGraph, you construct a custom graph node that initializes an A2AClient and dispatches tasks to the ADK worker’s endpoint using standard send_task() calls.
How does A2A preserve agent privacy and prevent prompt leakage?
A2A enforces opaque task execution boundaries where agents only exchange high-level task instructions and resulting artifacts. Neither agent has access to the other’s system prompts, model weights, private memory stores, or internal tool configurations.
Can you stream task execution artifacts over A2A in real-time?
Yes, A2A natively supports real-time artifact and thought streaming using Server-Sent Events. Servers emit typed events as reasoning steps complete, allowing caller agents to render incremental progress bars and intermediate results without polling.
What authentication mechanisms are supported in the A2A specification?
The A2A specification natively supports Bearer token authentication, API keys, and mutual TLS (mTLS) configurations. Security requirements are explicitly declared inside the Agent Card’s authentication block so callers know which authorization headers to supply.
Architectural Takeaways and Next Steps
The future of autonomous computing belongs to distributed, collaborative agent ecosystems rather than monolithic proprietary platforms. By standardizing agent discovery via Agent Cards and task execution over JSON-RPC 2.0, Google A2A provides the foundational plumbing for decentralized AI collaboration.
To see how A2A fits alongside tool execution, frontend streaming, and browser standards, read our architectural guide comparing A2A vs MCP vs AG-UI vs WebMCP protocols. Implementing open protocols today ensures your AI systems remain interoperable and resilient as the multi-agent ecosystem matures.