---
name: a2a-protocol
description: >-
  Builds Agent-to-Agent (A2A) servers and clients following Google's open
  protocol for agent interoperability. Use when the user wants to create
  an A2A-compliant agent, build an Agent Card, implement task management,
  connect agents across frameworks, set up agent discovery, handle streaming
  responses, implement push notifications, or orchestrate multi-agent
  workflows. Trigger words: a2a, agent to agent, agent2agent, a2a protocol,
  a2a server, a2a client, agent card, agent interoperability, agent
  collaboration, multi-agent, agent discovery, a2a sdk, a2a task.
license: Apache-2.0
compatibility: "Python 3.10+ (a2a-sdk) or Node.js 18+ (@a2a-js/sdk). Go and Java SDKs also available."
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: development
  tags: ["a2a", "agents", "interoperability", "protocol"]
---

# A2A Protocol

## Overview

Implements the Agent2Agent (A2A) open protocol for communication between AI agents built on different frameworks. A2A enables agents to discover each other via Agent Cards, negotiate interaction modalities, manage collaborative tasks, and exchange data — all without exposing internal state, memory, or tools. Supports JSON-RPC 2.0 over HTTP(S), streaming via SSE, gRPC, and async push notifications.

## Instructions

### 1. Core Concepts

**Architecture:**
- **A2A Client**: Initiates requests to an A2A Server (on behalf of a user or another agent)
- **A2A Server (Remote Agent)**: Exposes an A2A-compliant endpoint, processes tasks
- **Agent Card**: JSON metadata describing agent identity, capabilities, skills, endpoint, auth
- **Task**: Unit of work with lifecycle (submitted → working → completed/failed/canceled)
- **Message**: Communication turn (role: "user" or "agent") containing one or more Parts
- **Part**: Content unit — text, file reference, or structured data (JSON)
- **Artifact**: Output generated by the agent (documents, images, structured data)
- **Context**: Optional grouping of related tasks and messages

**Protocol layers:**
1. **Data Model**: Task, Message, AgentCard, Part, Artifact (defined in protobuf)
2. **Operations**: SendMessage, StreamMessage, GetTask, ListTasks, CancelTask, GetAgentCard
3. **Bindings**: JSON-RPC, gRPC, HTTP+JSON/REST

### 2. Python SDK Setup

```bash
# Core SDK
pip install a2a-sdk

# With HTTP server (FastAPI/Starlette)
pip install "a2a-sdk[http-server]"

# With gRPC support
pip install "a2a-sdk[grpc]"

# With all extras
pip install "a2a-sdk[all]"
```

### 3. Building an A2A Server (Python)

**Agent Card definition:**
```python
from a2a.types import AgentCard, AgentSkill, AgentCapabilities

agent_card = AgentCard(
    name="Research Assistant",
    description="Searches the web, summarizes documents, and answers questions with citations.",
    url="https://research-agent.example.com",
    version="1.0.0",
    capabilities=AgentCapabilities(
        streaming=True,
        pushNotifications=True,
        stateTransitionHistory=True,
    ),
    skills=[
        AgentSkill(
            id="web-search",
            name="Web Search",
            description="Search the web for current information on any topic",
            tags=["search", "research", "web"],
            examples=["Find the latest news about AI regulation"],
        ),
        AgentSkill(
            id="summarize",
            name="Document Summarization",
            description="Summarize long documents into key points",
            tags=["summary", "documents", "analysis"],
            examples=["Summarize this research paper"],
        ),
    ],
    defaultInputModes=["text/plain"],
    defaultOutputModes=["text/plain", "application/json"],
)
```

**Implementing the agent handler:**
```python
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.types import (
    Message,
    Part,
    TextPart,
    Task,
    TaskState,
    TaskStatus,
)
import uuid


class ResearchAgentExecutor(AgentExecutor):
    """Handles incoming A2A requests."""

    async def execute(self, context: RequestContext, event_queue: EventQueue):
        # Extract the user's message
        user_message = context.get_user_message()
        query = user_message.parts[0].text  # Assuming text input

        # Update status to working
        await event_queue.enqueue_event(
            TaskStatus(state=TaskState.working, message=Message(
                role="agent",
                parts=[TextPart(text="Searching for information...")]
            ))
        )

        # Do the actual work (your agent logic here)
        result = await self._research(query)

        # Return the result
        await event_queue.enqueue_event(
            TaskStatus(state=TaskState.completed, message=Message(
                role="agent",
                parts=[TextPart(text=result)]
            ))
        )

    async def cancel(self, context: RequestContext, event_queue: EventQueue):
        await event_queue.enqueue_event(
            TaskStatus(state=TaskState.canceled)
        )

    async def _research(self, query: str) -> str:
        # Your research logic here
        return f"Research results for: {query}"
```

**Starting the server:**
```python
from a2a.server.apps.starlette import A2AStarletteApplication
from a2a.server.request_handler import DefaultRequestHandler
import uvicorn

# Create the handler
agent_executor = ResearchAgentExecutor()
request_handler = DefaultRequestHandler(
    agent_executor=agent_executor,
    task_store=InMemoryTaskStore(),  # Or use SQL-backed store
)

# Create and run the A2A application
app = A2AStarletteApplication(
    agent_card=agent_card,
    http_handler=request_handler,
)

uvicorn.run(app.build(), host="0.0.0.0", port=8000)
```

The Agent Card is automatically served at `/.well-known/agent.json`.

### 4. Building an A2A Client (Python)

```python
from a2a.client import A2AClient
from a2a.types import (
    MessageSendParams,
    SendMessageRequest,
    Message,
    TextPart,
)

# Discover the agent
client = await A2AClient.get_client_from_agent_card_url(
    "https://research-agent.example.com/.well-known/agent.json"
)

# Send a message (synchronous)
request = SendMessageRequest(
    params=MessageSendParams(
        message=Message(
            role="user",
            parts=[TextPart(text="What are the latest developments in quantum computing?")]
        )
    )
)
response = await client.send_message(request)

# Handle response (could be Task or Message)
if hasattr(response, 'status'):
    # It's a Task — check status
    print(f"Task {response.id}: {response.status.state}")
    if response.status.message:
        print(response.status.message.parts[0].text)
else:
    # It's a direct Message
    print(response.parts[0].text)
```

**Streaming response:**
```python
async for event in client.send_message_streaming(request):
    if hasattr(event, 'status'):
        # TaskStatusUpdateEvent
        print(f"Status: {event.status.state}")
        if event.status.message:
            for part in event.status.message.parts:
                if hasattr(part, 'text'):
                    print(part.text, end="", flush=True)
    elif hasattr(event, 'artifact'):
        # TaskArtifactUpdateEvent
        print(f"Artifact: {event.artifact}")
```

### 5. Node.js SDK

```bash
npm install @a2a-js/sdk
```

**A2A Server (Node.js):**
```javascript
import { A2AServer, AgentCard, TaskState } from '@a2a-js/sdk';

const agentCard = {
  name: 'Code Reviewer',
  description: 'Reviews code for bugs, security issues, and best practices',
  url: 'https://code-reviewer.example.com',
  version: '1.0.0',
  capabilities: { streaming: true },
  skills: [{
    id: 'review',
    name: 'Code Review',
    description: 'Analyze code for issues and improvements',
    tags: ['code', 'review', 'security'],
  }],
  defaultInputModes: ['text/plain'],
  defaultOutputModes: ['text/plain'],
};

const server = new A2AServer({
  agentCard,
  async onMessage(context, eventQueue) {
    const userText = context.getUserMessage().parts[0].text;

    await eventQueue.enqueue({
      status: { state: TaskState.WORKING, message: {
        role: 'agent',
        parts: [{ text: 'Reviewing code...' }]
      }}
    });

    const review = await reviewCode(userText);

    await eventQueue.enqueue({
      status: { state: TaskState.COMPLETED, message: {
        role: 'agent',
        parts: [{ text: review }]
      }}
    });
  },
});

server.listen(8000);
```

**A2A Client (Node.js):**
```javascript
import { A2AClient } from '@a2a-js/sdk';

const client = await A2AClient.fromAgentCardUrl(
  'https://code-reviewer.example.com/.well-known/agent.json'
);

const response = await client.sendMessage({
  message: {
    role: 'user',
    parts: [{ text: 'Review this function:\n```js\nfunction add(a,b) { return a + b; }\n```' }],
  },
});
```

### 6. Agent Card

The Agent Card is a JSON document served at `/.well-known/agent.json` that describes your agent:

```json
{
  "name": "Research Assistant",
  "description": "Searches the web and summarizes documents",
  "url": "https://research-agent.example.com",
  "version": "1.0.0",
  "documentationUrl": "https://docs.example.com/research-agent",
  "capabilities": {
    "streaming": true,
    "pushNotifications": true,
    "stateTransitionHistory": true
  },
  "skills": [
    {
      "id": "web-search",
      "name": "Web Search",
      "description": "Search the web for current information",
      "tags": ["search", "research"],
      "examples": ["Find latest news about AI"]
    }
  ],
  "defaultInputModes": ["text/plain", "application/json"],
  "defaultOutputModes": ["text/plain", "application/json"],
  "authentication": {
    "schemes": ["bearer"]
  }
}
```

### 7. Task Lifecycle

```
        ┌──────────┐
        │submitted │
        └────┬─────┘
             │
        ┌────▼─────┐
   ┌────│ working  │────┐
   │    └────┬─────┘    │
   │         │          │
   │    ┌────▼─────┐    │
   │    │input-    │    │
   │    │required  │    │
   │    └────┬─────┘    │
   │         │          │
   │    ┌────▼─────┐    │
   ├───►│completed │    │
   │    └──────────┘    │
   │    ┌──────────┐    │
   ├───►│ failed   │◄───┤
   │    └──────────┘    │
   │    ┌──────────┐    │
   └───►│canceled  │◄───┘
   │    └──────────┘
   │    ┌──────────┐
   └───►│rejected  │
        └──────────┘
```

States:
- **submitted**: Task received, not yet processing
- **working**: Agent is actively processing
- **input-required**: Agent needs more info from the client (human-in-the-loop)
- **completed**: Task finished successfully
- **failed**: Task encountered an error
- **canceled**: Task was canceled by client or agent
- **rejected**: Agent declined the task

### 8. Multi-Agent Orchestration

**Sequential workflow (agent A → agent B → agent C):**
```python
from a2a.client import A2AClient
from a2a.types import Message, TextPart, SendMessageRequest, MessageSendParams

# Discover agents
research_agent = await A2AClient.get_client_from_agent_card_url(
    "https://research-agent.example.com/.well-known/agent.json"
)
writer_agent = await A2AClient.get_client_from_agent_card_url(
    "https://writer-agent.example.com/.well-known/agent.json"
)
reviewer_agent = await A2AClient.get_client_from_agent_card_url(
    "https://reviewer-agent.example.com/.well-known/agent.json"
)

# Step 1: Research
research_result = await research_agent.send_message(SendMessageRequest(
    params=MessageSendParams(message=Message(
        role="user",
        parts=[TextPart(text="Research quantum computing breakthroughs in 2025")]
    ))
))

# Step 2: Write article based on research
article = await writer_agent.send_message(SendMessageRequest(
    params=MessageSendParams(message=Message(
        role="user",
        parts=[TextPart(text=f"Write a blog post based on: {research_result.status.message.parts[0].text}")]
    ))
))

# Step 3: Review the article
review = await reviewer_agent.send_message(SendMessageRequest(
    params=MessageSendParams(message=Message(
        role="user",
        parts=[TextPart(text=f"Review this article: {article.status.message.parts[0].text}")]
    ))
))
```

**Parallel fan-out:**
```python
import asyncio

async def query_agent(client, query):
    response = await client.send_message(SendMessageRequest(
        params=MessageSendParams(message=Message(
            role="user", parts=[TextPart(text=query)]
        ))
    ))
    return response

# Query multiple agents in parallel
results = await asyncio.gather(
    query_agent(agent_a, "Analyze market trends"),
    query_agent(agent_b, "Analyze competitor products"),
    query_agent(agent_c, "Analyze customer feedback"),
)
```

### 9. Push Notifications (Async Tasks)

For long-running tasks, use push notifications:

```python
# Client sets up a webhook to receive updates
request = SendMessageRequest(
    params=MessageSendParams(
        message=Message(role="user", parts=[TextPart(text="Generate a detailed report")]),
        pushNotification={
            "url": "https://my-app.example.com/a2a/webhooks",
            "authentication": {
                "schemes": ["bearer"],
                "credentials": "my-webhook-secret"
            }
        }
    )
)

# Server processes async and POSTs updates to webhook
response = await client.send_message(request)
task_id = response.id  # Track the task

# Later: poll for status if needed
task = await client.get_task(task_id)
```

### 10. A2A vs MCP

A2A and MCP (Model Context Protocol) are complementary:

| | A2A | MCP |
|---|---|---|
| **Purpose** | Agent-to-agent communication | Agent-to-tool communication |
| **Actors** | Agent ↔ Agent | Agent ↔ Tool/Data source |
| **Opacity** | Agents are opaque (no internal state shared) | Tools expose their interface |
| **Tasks** | Stateful, long-running, async | Stateless function calls |
| **Discovery** | Agent Cards | Tool manifests |
| **Use when** | Delegating to another autonomous agent | Calling a specific tool/API |

Use MCP to give your agent tools. Use A2A to let your agent collaborate with other agents.

## Examples

### Example 1: Customer Support Router

**Input:** "Build an A2A server that acts as a customer support router. It receives customer queries and delegates to specialized agents: billing-agent, technical-agent, and sales-agent based on the query content."

**Output:** A2A server with:
- Agent Card listing routing as its primary skill
- Message handler that classifies queries using keyword matching or LLM
- A2A client connections to 3 downstream agents
- Task forwarding with context preservation
- Aggregated response back to the original client
- Fallback to human handoff if no agent can handle the query

### Example 2: Code Pipeline Agents

**Input:** "Create a multi-agent code pipeline: code-writer agent generates code, test-writer agent creates tests, code-reviewer agent reviews both. Each is an independent A2A server. Build an orchestrator that chains them."

**Output:**
- 3 A2A server implementations (code-writer, test-writer, reviewer)
- Each with its own Agent Card, skills, and execution logic
- Orchestrator client that discovers all three agents
- Sequential pipeline: write code → generate tests → review everything
- Streaming updates from each agent back to the user
- Error handling: if reviewer rejects, send feedback back to code-writer for revision

## Guidelines

- Serve the Agent Card at `/.well-known/agent.json` — this is the standard discovery endpoint
- Use descriptive skill definitions — other agents use these to decide whether to delegate to you
- Always handle the `input-required` state for human-in-the-loop scenarios
- Implement proper error handling — return meaningful error messages in the task status
- Use streaming for tasks that take more than a few seconds — clients expect real-time feedback
- Implement task cancellation — long-running tasks must be cancellable
- Use push notifications for tasks that may take minutes or hours
- Keep agents focused — one agent, one capability domain (follows Unix philosophy)
- Validate incoming message content types against your declared `defaultInputModes`
- Use structured data (JSON Parts) for machine-to-machine communication between agents
- Use text Parts for human-readable responses
- Implement authentication on your A2A endpoint — declare the scheme in your Agent Card
- Test with the A2A Inspector: https://github.com/a2aproject/a2a-inspector
- A2A is for agent collaboration; use MCP for tool integration within a single agent
- Pin SDK versions — the protocol is evolving (currently v0.3.0, RC v1.0 in progress)
