> ## 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.

# A2AServer and A2AClient

> Serve any agent or swarm over the A2A protocol, and call any A2A agent as if it were local

## Overview

[A2A](https://a2a-protocol.org) (Agent2Agent) is an open protocol for agents built by different teams, on different frameworks, to call each other over HTTP. Swarms speaks A2A version 1.0 over its JSON-RPC binding, in both directions:

* **`A2AServer`** serves an `Agent`, any structure with a `run(task)` method, or a plain function, as an A2A agent. It publishes a public agent card and answers `SendMessage` requests.
* **`A2AClient`** reads a remote agent's card and runs tasks on it. It has an `agent_name`, an `agent_description` and a `run(task)` method, so it works anywhere a local agent does, including as a [handoff](#remote-agents-as-handoffs) target.

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

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,
)

# The with block starts the server in the background and stops it on exit.
with A2AServer(poet, api_keys=["demo-key"], port=8000):
    remote = A2AClient("http://127.0.0.1:8000", api_key="demo-key")
    print(remote.run("Write a poem about lighthouses."))
```

For a walkthrough, see the [A2A quickstart](https://docs.swarms.world/examples/a2a-quickstart.md).

## Import

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

Both come with `pip install -U swarms`. The server runs on the `mcp` package's HTTP stack, and the client uses `httpx`; both are core dependencies.

## A2AServer

`A2AServer` is an [`MCPDeployer`](https://docs.swarms.world/api/mcp-deployer) with two extra routes. The same process and port keep serving the target as an MCP tool at `/mcp`, with the health check at `/health`, so one server answers both MCP and A2A clients.

### Constructor

```python theme={null}
A2AServer(
    targets: Any,
    card_path: str = "/.well-known/agent-card.json",
    rpc_path: str = "/a2a",
    protocol_version: str = "1.0",
    agent_version: str = "1.0.0",
    capabilities: Optional[Dict[str, Any]] = None,
    input_modes: Sequence[str] = ("text/plain",),
    output_modes: Sequence[str] = ("text/plain",),
    skills: Optional[List[Dict[str, Any]]] = None,
    **kwargs,
)
```

**targets** `Any | List[Any] | Dict[str, Any]` *required*

What to serve: an `Agent`, any structure with `run(task)`, or a callable that takes the task string. A list or a `{tool name: target}` dict serves several as MCP tools, but A2A answers with the **first** one only. See [How a target becomes a tool](https://docs.swarms.world/api/mcp-deployer.md#how-a-target-becomes-a-tool).

**card\_path** `str` (default: /.well-known/agent-card.json)

Where the agent card is served. It is added to `public_paths`, so it never needs a key. Clients find the card at this path by default.

**rpc\_path** `str` (default: /a2a)

Where the JSON-RPC `SendMessage` endpoint is served. The card advertises its full URL.

**protocol\_version** `str` (default: 1.0)

The A2A version shown on the card and required in every request's `A2A-Version` header.

**agent\_version** `str` (default: 1.0.0)

The version of your agent, shown on the card as `version`.

**capabilities** `Optional[Dict[str, Any]]` (default: None)

The card's `capabilities` object. `None` shows `{}`. The server does not stream or push, so don't advertise either.

**input\_modes** `Sequence[str]` (default: ("text/plain",))

Media types the agent accepts, shown as `defaultInputModes`.

**output\_modes** `Sequence[str]` (default: ("text/plain",))

Media types the agent returns, shown as `defaultOutputModes`.

**skills** `Optional[List[Dict[str, Any]]]` (default: None)

The card's `skills` list. `None` shows one skill built from the first target: its tool name as `id` and `name`, its description, and its class name as the only tag.

\*\***kwargs** `Any`

Every [`MCPDeployer` option](https://docs.swarms.world/api/mcp-deployer#constructor): `name`, `description`, `tool_name`, `host`, `port`, `api_keys`, `api_key_env`, `api_key_header`, `auth`, `token_verifier`, `required_scopes`, `allow_anonymous`, `public_paths`, `timeout`, `verbose`, `show_banner` and the rest. As with `MCPDeployer`, a server with no auth configured raises `ValueError` unless `allow_anonymous=True`.

### What the card says

The card's `name` and `description` come from the deployer:

| Card field | Value |
| - | - |
| `name` | The `name` argument, or else the first tool's name: a snake\_case form of the target's `agent_name` or `name`, so an agent named `Researcher` is served as `researcher` |
| `description` | The `description` argument, or else the target's `agent_description`, `description` or the first line of its docstring |
| `version` | `agent_version` |
| `supportedInterfaces` | One entry: the full URL of `rpc_path`, `"protocolBinding": "JSONRPC"` and `protocol_version` |
| `skills` | `skills`, or one skill built from the first target |

For the `Researcher` agent in the [quickstart](https://docs.swarms.world/examples/a2a-quickstart.md), `GET /.well-known/agent-card.json` returns:

```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 interface URL is built from the request, so it shows the host and port the client used. Behind a proxy that mounts the app under a prefix, the prefix is included.

### Endpoints

| Method and path | Auth | What it does |
| - | - | - |
| `GET /.well-known/agent-card.json` | None | Returns the agent card |
| `POST /a2a` | Required | Runs the first target on a `SendMessage` request |
| `GET /health` | None | The deployer's health check |
| `POST /mcp` | Required | The same target as an MCP tool |

Auth is the deployer's: a key from `api_keys` or `api_key_env`, sent in the `x-api-key` header (or the header named by `api_key_header`) or as `Authorization: Bearer <key>`; or your own `auth` callable or `token_verifier`. A request without valid credentials gets HTTP `401` with `{"error": "unauthorized"}`. See [Auth, in order of precedence](https://docs.swarms.world/api/mcp-deployer.md#auth-in-order-of-precedence).

### SendMessage

Every request needs the `A2A-Version: 1.0` header. The server reads the text parts of `params.message`, joins them with newlines, and runs the target on that text as the task.

```bash theme={null}
curl -s http://127.0.0.1:8000/a2a \
  -H "Content-Type: application/json" \
  -H "A2A-Version: 1.0" \
  -H "x-api-key: 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 reply is a single agent message, with the target's output as its only text part:

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "message": {
      "role": "ROLE_AGENT",
      "messageId": "c28ce2e6-c315-43a4-b625-38b2b8cfcfd3",
      "parts": [{"text": "A2A (Agent-to-Agent) protocol is a communication standard that lets AI agents..."}]
    }
  }
}
```

The output is whatever the target's `run` returns, turned into text: a string as is, anything else as indented JSON. An `Agent`, a `SequentialWorkflow` and most other structures return their history by default, so serve them with `output_type="final"` to reply with only the final answer.

> [!WARNING]
>
> One target instance answers every request, from every caller. An `Agent` keeps its conversation between calls, so with the default `output_type` the second caller's reply starts with the first caller's question and answer, and every request is answered in the context of the ones before it. Set `output_type="final"`, and when callers must not share context, serve a function that builds a fresh agent per request, as shown in [Keep callers apart](https://docs.swarms.world/examples/a2a-quickstart.md#8-keep-callers-apart).

### Errors

| Code | When |
| - | - |
| HTTP `401` | No credentials, or wrong ones |
| `-32009` | The `A2A-Version` header is missing or isn't `protocol_version`. Message: `A2A-Version must be 1.0` |
| `-32601` | A method other than `SendMessage`, including the A2A 0.3 name `message/send`. Message: `Method not found` |
| `-32602` | The message has no text part. Message: `Message needs a text part` |
| `-32603` | The target raised, or ran longer than the deployer's `timeout`. The message is the exception's repr, for example `TimeoutError()` |

JSON-RPC errors are sent with HTTP status `200`, as `{"jsonrpc": "2.0", "id": ..., "error": {"code": ..., "message": ...}}`.

### Running it

`A2AServer` inherits the deployer's lifecycle:

| Call | What it does |
| - | - |
| `server.run()` | Serves until interrupted. Blocks |
| `server.start()` | Serves in a background thread and returns once the port is open |
| `server.stop()` | Stops a server started with `start()` |
| `with A2AServer(...) as server:` | `start()` on entry and `stop()` on exit |

See [Methods](https://docs.swarms.world/api/mcp-deployer.md#methods) on the MCPDeployer page.

### Limits

* Text in and text out. Non-text parts are ignored, and a message with no text part is an error.
* One reply message per request. There is no streaming, no push notification and no `Task` object, so `GetTask`, `CancelTask` and the other A2A methods return `-32601`.
* The target runs once per message, like an MCP tool call, and there is no A2A context or session: a served `Agent` keeps one memory for all callers. See the warning under [SendMessage](#sendmessage) and [State between calls](https://docs.swarms.world/api/mcp-deployer.md#state-between-calls).
* With several targets, A2A serves the first. Run one `A2AServer` per agent, on its own port, to put several agents on A2A.

## A2AClient

`A2AClient` is a remote A2A agent that you run like a local one.

### Constructor

```python theme={null}
A2AClient(
    url: str,
    api_key: Optional[str] = None,
    transport: Optional[httpx.BaseTransport] = None,
    timeout: float = 300.0,
    headers: Optional[Dict[str, str]] = None,
    card_path: str = "/.well-known/agent-card.json",
    version: str = "1.0",
    agent_name: Optional[str] = None,
    agent_description: Optional[str] = None,
)
```

The constructor fetches the agent card from `url` + `card_path` right away, so the remote server must be running when you build the client.

**url** `str` *required*

The remote agent's base URL, such as `http://127.0.0.1:8000`. A trailing slash is ignored.

**api\_key** `Optional[str]` (default: None)

Sent as `Authorization: Bearer <api_key>` on every request, the card included. `A2AServer` accepts it. Leave it `None` for a server that allows anonymous calls.

**transport** `Optional[httpx.BaseTransport]` (default: None)

The `httpx` transport, for example `httpx.HTTPTransport(retries=3)` to retry failed connections, or `httpx.MockTransport` in tests.

**timeout** `float` (default: 300.0)

Seconds to wait for each request, the card fetch included. A model call on the server can take a while, so keep this generous.

**headers** `Optional[Dict[str, str]]` (default: None)

Extra headers sent on every request, such as `{"x-api-key": "..."}` for a server that reads a different header, or a tracing header. They override the defaults when the names match.

**card\_path** `str` (default: /.well-known/agent-card.json)

Where the card lives under `url`.

**version** `str` (default: 1.0)

The A2A version sent in the `A2A-Version` header. The card must advertise a JSON-RPC interface with this version.

**agent\_name** `Optional[str]` (default: None)

The name to use locally instead of the card's `name`. Useful for handoffs, where the model addresses targets by name.

**agent\_description** `Optional[str]` (default: None)

The description to use locally instead of the card's `description`.

### Attributes

| Attribute | Type | Meaning |
| - | - | - |
| `card` | `dict` | The agent card as the server returned it |
| `agent_name` | `str` | `agent_name`, or else the card's `name` |
| `agent_description` | `str` | `agent_description`, or else the card's `description`, or `""` |
| `url` | `str` | The JSON-RPC endpoint from the card, the first `JSONRPC` interface with a matching version |
| `version` | `str` | The A2A version in use |
| `client` | `httpx.Client` | The HTTP client, with the headers and timeout set |

### run()

Send one task to the remote agent and return its reply.

```python theme={null}
def run(self, task: str) -> str
```

The task goes out as one `SendMessage` request with a single text part. The return value is:

* for a `message` reply, its text parts, joined with newlines;
* for a `task` reply in state `TASK_STATE_COMPLETED`, the text of its artifacts, one per line.

### Errors

| When | Raised |
| - | - |
| The card can't be fetched, at construction | `httpx.HTTPStatusError` for an error status, or `httpx.ConnectError` and other `httpx` errors when the server isn't reachable |
| The card has no `JSONRPC` interface for `version`, at construction | `ValueError`, for example `http://127.0.0.1:8000: no JSONRPC 0.3 interface` |
| The server returns an error status, such as `401` for a wrong key | `httpx.HTTPStatusError` |
| The server returns a JSON-RPC error | `RuntimeError("A2A error {'code': ..., 'message': ...}")` |
| A `task` reply ends in any state but `TASK_STATE_COMPLETED` | `RuntimeError` naming the state and the status message's text |

Servers that speak only A2A 0.3, with the `message/send` method, are not supported.

## Remote agents as handoffs

An agent's `handoffs` take any object with `agent_name`, `agent_description` and `run(task)`, so an `A2AClient` can be a handoff target next to local agents. The model sees the remote agent's name and description from its card in the handoff prompt, and delegates to it through the usual `handoff_task` tool.

```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."))
```

If the remote call fails, the model gets the error as the handoff's result instead of the run crashing. See [Agent Handoffs and Task Delegation](https://docs.swarms.world/api/agent.md#agent-handoffs-and-task-delegation).

## Related

* [A2A quickstart](https://docs.swarms.world/examples/a2a-quickstart.md)
* [MCPDeployer](https://docs.swarms.world/api/mcp-deployer.md), which `A2AServer` extends
* [A2A protocol specification](https://a2a-protocol.org/latest/specification/)
* [Source: a2a\_server.py](https://github.com/kyegomez/swarms/blob/master/swarms/structs/a2a_server.py) and [a2a\_client.py](https://github.com/kyegomez/swarms/blob/master/swarms/structs/a2a_client.py)


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