> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
> Use this file to discover all available pages before exploring further.

# A2A Quickstart

> Serve a Swarms agent over the A2A protocol, call it from Python or curl, and hand tasks off to remote agents

[A2A](https://a2a-protocol.org) (Agent2Agent) lets agents built on different frameworks call each other over HTTP. This guide serves a Swarms agent as an A2A agent with `A2AServer`, then calls it with `A2AClient`, with `curl`, and as a handoff target from another agent.

Reference: [A2AServer and A2AClient](https://docs.swarms.world/api/a2a.md).

## Install

```bash theme={null}
pip install -U swarms
export OPENAI_API_KEY="sk-..."
```

`A2AServer` and `A2AClient` need nothing else.

## 1. Serve an agent

Save this as `server.py` and run it. It serves the agent on port 8000 and accepts one API key.

```python theme={null}
from swarms import A2AServer, Agent

researcher = Agent(
    agent_name="Researcher",
    agent_description="Answers research questions in a short paragraph.",
    system_prompt="Answer the question in one short, factual paragraph.",
    model_name="gpt-5.4-mini",
    max_loops=1,
    output_type="final",  # Reply with the answer only, not the agent's history
    print_on=False,
)

if __name__ == "__main__":
    server = A2AServer(
        researcher,
        api_keys=["demo-key"],
        host="127.0.0.1",
        port=8000,
    )
    server.run()  # Blocks until Ctrl+C
```

The agent's `agent_description` becomes the description other agents see, so make it say what the agent is good at.

`output_type="final"` matters for a served agent. One agent answers every request and keeps its conversation between them, and the default `output_type` returns that history. Without it, the second caller's reply would start with the first caller's question and answer. See [Keep callers apart](#8-keep-callers-apart) to stop requests sharing context at all.

> [!NOTE]
>
> `A2AServer` refuses to start without auth. Pass `api_keys`, `api_key_env`, `auth` or `token_verifier`, or `allow_anonymous=True` for a local experiment.

## 2. Look at the agent card

The card is public, so any client can find out what the agent does before calling it:

```bash theme={null}
curl -s http://127.0.0.1:8000/.well-known/agent-card.json
```

```json theme={null}
{
  "name": "researcher",
  "description": "Answers research questions in a short paragraph.",
  "version": "1.0.0",
  "capabilities": {},
  "defaultInputModes": ["text/plain"],
  "defaultOutputModes": ["text/plain"],
  "supportedInterfaces": [
    {"url": "http://127.0.0.1:8000/a2a", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"}
  ],
  "skills": [
    {"id": "researcher", "name": "researcher", "description": "Answers research questions in a short paragraph.", "tags": ["Agent"]}
  ]
}
```

The card's `name` is a snake\_case form of the agent's name. Pass `name="Researcher"` to `A2AServer` to show a different one.

## 3. Call it from Python

In a second terminal:

```python theme={null}
from swarms import A2AClient

remote = A2AClient("http://127.0.0.1:8000", api_key="demo-key")

print(f"Connected to {remote.agent_name}: {remote.agent_description}")
print(f"JSON-RPC endpoint: {remote.url}")

print(remote.run("What is the A2A protocol used for?"))
```

`A2AClient` reads the card when it is built, so the server must already be running. `run()` sends one `SendMessage` request and returns the reply as a string.

## 4. Call it from any language

The endpoint is plain JSON-RPC, so anything that can send HTTP can call it. Every request needs the `A2A-Version: 1.0` header and the key, either as `x-api-key` or as `Authorization: Bearer`:

```bash theme={null}
curl -s http://127.0.0.1:8000/a2a \
  -H "Content-Type: application/json" \
  -H "A2A-Version: 1.0" \
  -H "Authorization: Bearer demo-key" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "SendMessage",
    "params": {
      "message": {
        "role": "ROLE_USER",
        "messageId": "msg-1",
        "parts": [{"text": "What is the A2A protocol used for?"}]
      }
    }
  }'
```

The answer is in `result.message.parts[0].text`:

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "message": {
      "role": "ROLE_AGENT",
      "messageId": "c28ce2e6-c315-43a4-b625-38b2b8cfcfd3",
      "parts": [{"text": "The A2A protocol lets AI agents discover each other and exchange tasks..."}]
    }
  }
}
```

## 5. Server and client in one script

`A2AServer` is a context manager: the `with` block starts the server in a background thread and stops it on exit. That makes a self-contained script, or a test:

```python theme={null}
import socket

from swarms import A2AClient, A2AServer, Agent


def free_port() -> int:
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


poet = Agent(
    agent_name="Poet",
    agent_description="Writes a two-line poem about the topic it is given.",
    system_prompt="Write exactly two short lines of poetry about the topic. Nothing else.",
    model_name="gpt-5.4-mini",
    max_loops=1,
    print_on=False,
)

if __name__ == "__main__":
    port = free_port()

    with A2AServer(poet, api_keys=["demo-key"], port=port, show_banner=False):
        remote = A2AClient(f"http://127.0.0.1:{port}", api_key="demo-key")
        print(f"Calling {remote.agent_name} at {remote.url}")
        print(remote.run("Write a poem about lighthouses."))
```

## 6. Hand tasks off to a remote agent

An `A2AClient` has an `agent_name`, an `agent_description` and a `run()` method, so it can go in an agent's `handoffs` next to local agents. With the server from step 1 running:

```python theme={null}
from swarms import A2AClient, Agent

remote_researcher = A2AClient("http://127.0.0.1:8000", api_key="demo-key")

coordinator = Agent(
    agent_name="Coordinator",
    system_prompt=(
        "Hand research questions off to the researcher, "
        "then summarise its answer in two sentences."
    ),
    model_name="gpt-5.4-mini",
    handoffs=[remote_researcher],
    max_loops=2,
)

print(coordinator.run("Find out what the A2A protocol is used for."))
```

The coordinator sees `researcher` and its description in its handoff prompt, calls `handoff_task`, and the request goes over A2A. To give the remote agent a different local name, pass `agent_name=` and `agent_description=` to `A2AClient`.

## 7. Serve a whole swarm

The target can be any structure with `run(task)`. Give it `output_type="final"` so the reply is the final answer rather than the whole conversation:

```python theme={null}
from swarms import A2AServer, Agent, SequentialWorkflow

writing_team = SequentialWorkflow(
    name="Writing-Team",
    description="Drafts a short text, then edits it.",
    agents=[
        Agent(agent_name="Drafter", system_prompt="Write a first draft.", model_name="gpt-5.4-mini", max_loops=1, print_on=False),
        Agent(agent_name="Editor", system_prompt="Tighten the draft and return only the final text.", model_name="gpt-5.4-mini", max_loops=1, print_on=False),
    ],
    output_type="final",
)

if __name__ == "__main__":
    A2AServer(writing_team, api_keys=["demo-key"], port=8001).run()
```

Callers see one agent named `writing_team` with the workflow's description. They don't need to know a team is behind it.

## 8. Keep callers apart

The server runs one target instance for every request, from every caller. An `Agent` remembers each task it was given, so later requests see earlier ones, and requests that arrive together run on separate threads against the same agent. When callers must not share context, serve a function that builds a fresh agent for each request:

```python theme={null}
from swarms import A2AServer, Agent


def research(task: str) -> str:
    """Answers research questions in a short paragraph."""
    agent = Agent(
        agent_name="Researcher",
        system_prompt="Answer the question in one short, factual paragraph.",
        model_name="gpt-5.4-mini",
        max_loops=1,
        output_type="final",
        print_on=False,
    )
    return agent.run(task)


if __name__ == "__main__":
    A2AServer(research, api_keys=["demo-key"], port=8002).run()
```

The card is named after the function, `research`, and its description is the first line of the docstring.

## 9. Keys from the environment

Keep keys out of code with `api_key_env`. It reads a comma-separated list, so you can rotate keys without downtime:

```bash theme={null}
export A2A_KEYS="key-for-team-a,key-for-team-b"
```

```python theme={null}
server = A2AServer(researcher, api_key_env="A2A_KEYS", host="0.0.0.0", port=8000)
```

`host="0.0.0.0"` listens on every interface, for a server other machines call. Run it behind HTTPS in production. For tokens checked against your own identity provider, see [Auth](https://docs.swarms.world/api/mcp-deployer.md#auth-in-order-of-precedence) on the MCPDeployer page; `A2AServer` takes the same options.

## 10. Handle errors

```python theme={null}
import httpx

from swarms import A2AClient

try:
    remote = A2AClient("http://127.0.0.1:8000", api_key="demo-key", timeout=120.0)
    print(remote.run("Summarise the A2A specification."))
except httpx.HTTPStatusError as error:
    print("HTTP error, for example a wrong key:", error.response.status_code)
except httpx.HTTPError as error:
    print("Could not reach the agent:", error)
except RuntimeError as error:
    print("The agent returned an error:", error)
```

| You see | Cause |
| - | - |
| `httpx.ConnectError` when building the client | The server isn't running at that URL |
| `httpx.HTTPStatusError` with status `401` | Missing or wrong key |
| `ValueError: ... no JSONRPC 1.0 interface` | The remote agent doesn't speak A2A 1.0 over JSON-RPC |
| `RuntimeError: A2A error {'code': -32603, 'message': 'TimeoutError()'}` | The agent ran longer than the server's `timeout` |
| `RuntimeError: A2A error {'code': -32603, ...}` | The agent raised on the server |

## 11. MCP on the same port

`A2AServer` extends [`MCPDeployer`](https://docs.swarms.world/api/mcp-deployer), so the same process also serves the agent as an MCP tool at `/mcp`, with a public health check at `/health`. One deployment reaches both A2A agents and MCP clients such as Claude Desktop or another Swarms agent with `mcp_url`.

```bash theme={null}
curl -s http://127.0.0.1:8000/health
# {"status":"ok","name":"researcher","tool":"researcher","tools":["researcher"],"transport":"streamable-http"}
```

## Next steps

* [A2AServer and A2AClient reference](https://docs.swarms.world/api/a2a.md)
* [MCPDeployer](https://docs.swarms.world/api/mcp-deployer.md): auth, timeouts and serving several agents
* [Agent handoffs](https://docs.swarms.world/api/agent.md#agent-handoffs-and-task-delegation)
* [Runnable scripts](https://github.com/kyegomez/swarms/tree/master/examples/a2a)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.