# Agent API & Protocols

Call your deployed agent over the thread API, Agents API, SSE streams, MCP, ACP, or A2A, backed by one durable session store and one fail-closed client token.

Your product's agent is part of your product. Whether the caller is your own
backend, a browser UI, a code editor, or a customer's agent, every app built on
the Agent SDK serves the same six protocol faces over one durable session store
on Ferrite's storage planes. Conversations survive process restarts and app
redeploys, and every face reads and writes the same underlying agent instances.

## Choose a face

Pick the protocol your client already speaks. Every face authenticates with the
deployment's client token, except the SSE stream face (which uses a short-lived
minted token) and the A2A agent card (which is public).

| Face | Where | Authenticates with | Use it when |
| --- | --- | --- | --- |
| Thread API | `/api/agent`, `/api/threads/…` | the client token | your backend or console runs turns against the default agent and reads the transcript |
| Agents API | `/api/agents/{agent}/instances/…` | the client token | you address a named agent, or control instance creation and incarnation |
| Stream | `GET /api/stream/…` | a minted `?token=`, valid for ten minutes | a browser follows a run as it happens |
| MCP | `POST /mcp` | the client token | an MCP client at revision `2026-07-28` calls each agent as a tool |
| ACP | `POST /acp` | the client token | an editor speaking ACP v1 opens sessions with an agent |
| A2A | `GET /.well-known/agent-card.json`, `POST /a2a` | none for the card; the client token for `/a2a` | another agent discovers the deployment and sends it tasks |

## Authentication

All authenticated faces check a single client token stored in the
`agents-client-token` secret. Callers can pass it in one of three places:

- `Authorization: Bearer <token>`
- `x-ferrite-agents-authorization: Bearer <token>`
- `client_token` in a JSON request body

The platform gateway treats both headers as ordinary application headers and
forwards only the header names listed in each route's `forward_headers`. The
reference Agents app lists both `x-ferrite-agents-authorization` and
`authorization` on its authenticated routes so standard Bearer clients work
directly. If you place a proxy in front of the app that uses `Authorization`
for its own credential, remove `authorization` from those `forward_headers`
lists and send `x-ferrite-agents-authorization` instead.

The surface fails closed. With no `agents-client-token` configured, every
authenticated route answers `503 client token is not configured`; a wrong token
answers `401`.

One client token covers the entire deployment, and every caller holding it has
equal authority over every agent and every instance. The faces carry no
per-user identity. If your agent serves multiple end users, sign them in inside
your own application with the `auth` package (see
[Authentication](/developers/authentication/)) and call the agent faces from
your backend with the client token. Never send the client token to a browser;
mint a short-lived stream token for browser clients instead.

Every face returns errors in one JSON envelope:

```json
{ "error": { "type": "agent_instance_not_found", "code": "agent_instance_not_found", "message": "…", "details": "…" } }
```

`type` identifies the error kind (such as `agent_instance_not_found` or
`submission_conflict`), and `code` repeats it for clients that read that field.
`details` is always a string (empty when there is nothing to add). `meta`, when
present, holds structured fields such as the conflicting `submissionId`. `dev`
carries extra diagnostics only when the app runs in development mode.

## Thread API

The Thread API gives your backend or console a thread-shaped view over the
default agent. Each instance is a thread, and each turn is a submission that
runs to completion and answers in the same HTTP reply.

By default, the default agent is the alphabetically first registered name. You
can override it with `AppConfig.default_agent`, which also sets the default for
ACP and A2A. Registering a second agent under an existing name replaces the
first without raising an error.

Create a thread, run one turn, and read the event transcript:

```bash
AGENTS=https://agents.example.com
TOKEN="x-ferrite-agents-authorization: Bearer $AGENTS_CLIENT_TOKEN"

curl -s -X POST "$AGENTS/api/threads" -H "$TOKEN" -H 'content-type: application/json' \
  -d '{"thread_id":"t1","title":"first"}'

curl -s -X POST "$AGENTS/api/threads/t1/turn" -H "$TOKEN" -H 'content-type: application/json' \
  -d '{"message":"Count the words in: the quick brown fox"}'

curl -s "$AGENTS/api/threads/t1/events?from=0" -H "$TOKEN"
```

A completed turn returns the submission outcome and summed token usage:

```json
{ "thread": "t1", "agent": "assistant", "submission_id": "ingress_…", "status": "completed", "stop": "completed", "runtime": "agent-sdk", "steps": 1, "answer": "4", "usage": { "input": 812, "output": 9, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 821, "cost": { … }, "billing": "platform-credit", "costMicros": … }, "data": null, "error": null }
```

`usage` totals every model call made during the turn. `billing` and
`costMicros` appear only when the AI gateway reported them.

| Method and path | Purpose |
| --- | --- |
| `GET /api/agent` | Return the default agent (`loaded`, `name`, `description`, `initialDataSchema`) and all registered agent names |
| `GET /api/threads` · `POST /api/threads` | List threads; create one (`thread_id`, `title`, optional `initialData`) |
| `GET /api/threads/{id}` · `DELETE /api/threads/{id}` | Read a thread record; delete it durably |
| `POST /api/threads/{id}/turn` | Run one turn with `message` and return the completed answer in the same reply |
| `GET /api/threads/{id}/messages` · `POST /api/threads/{id}/messages` | Read recent messages; submit a message (`message`, optional `resultSchema`, `submissionId`) |
| `GET /api/threads/{id}/events?from=N` | Read the transcript as numbered events (`seq`, `kind`, `payload`, `ts_ms`), plus `next_from` for the next poll and `busy` |
| `GET /api/threads/{id}/submissions/{sid}` | Read one submission's status: `unknown`, `pending`, `running`, `completed`, `failed`, or `aborted` |
| `POST /api/threads/{id}/submissions/{sid}/cancel` | Cancel that specific submission; the cancellation holds even if the submission request has not arrived yet |
| `POST /api/threads/{id}/cancel` · `/abort` | Abort the currently running submission |
| `POST /api/threads/{id}/stream-token` | Mint a short-lived token for the SSE stream face |

List routes, `/messages`, and `/events` accept a `limit` query parameter
(default `100`, maximum `1000`).

### Idempotency

Pass `submissionId` (or `idempotencyKey`) in a message body to make retries
safe. If you omit it on a request arriving through the platform gateway, the
SDK derives the submission id from the ingress envelope's idempotency key as
`ingress_<key>`.

- A retry with the same key and payload while the submission is still in flight
  joins it and returns its outcome.
- A retry with the same key and payload after the submission settles returns
  the recorded outcome without executing the turn again.
- A request reusing the same key with a different payload is refused with
  `submission_conflict` (HTTP `409`).

An instance executes one submission at a time. A second request without a
matching key while the instance is busy is refused with `session_busy`. The
face answers HTTP `500` for `session_busy` even though nothing crashed, so
check `error.type` instead of the status code. Wait until the active submission
settles (poll `/submissions/{sid}`, or poll `/events` until `busy` is `false`)
and resend with the same `submissionId`, or open a separate instance for
parallel conversations.

If a turn outlives the platform's buffered-route deadline, the HTTP call
answers `504`. The submission keeps running on the app, and `/events` holds the
authoritative transcript of what completed.

## Agents and instances

Every registered agent exposes the same operations addressed by name:

- `GET /api/agents`
- `GET /api/agents/{agent}/instances`
- `POST /api/agents/{agent}/instances` (`id`, `initialData`)
- `GET|DELETE /api/agents/{agent}/instances/{id}`
- `GET|POST /api/agents/{agent}/instances/{id}/messages`
- `POST /api/agents/{agent}/instances/{id}/abort`
- `GET /api/agents/{agent}/instances/{id}/submissions/{sid}`
- `POST /api/agents/{agent}/instances/{id}/submissions/{sid}/cancel`
- `POST /api/agents/{agent}/instances/{id}/stream-token`

A message submission accepts `resultSchema` for
[structured results](/developers/agent-sdk/) and `submissionId` for idempotent
retries. By default, posting a message creates the instance if it does not
exist or continues it if it does. Set `"create": true` (with optional
`initialData`) to require creation and fail with `agent_instance_exists`
(`409`) when the instance already exists. Set `"create": false` to continue
only an existing instance. Pass `uid` to pin a specific incarnation, so a call
targeting an instance that was deleted and re-created under the same id answers
`agent_instance_not_found`.

## Streaming

The stream face relays an instance's runtime events over Server-Sent Events
(SSE). On Ferrite, a `stream` route accepts `GET` only, forwards no request
headers, and always answers with a `200` event-stream head. Because headers are
not forwarded on stream routes, subscriptions authenticate with a minted
`?token=` query parameter on one of three `GET` paths:

- `GET /api/stream/{thread}?token=…` sends console frames for browser
  `EventSource` clients.
- `GET /api/stream/threads/{id}?token=…` streams the default agent's instance
  as named SSE events.
- `GET /api/stream/agents/{agent}/instances/{id}?token=…` streams a named
  agent's instance as named SSE events.

Mint the token from your backend with `POST /api/threads/{id}/stream-token` for
the default agent, or `POST /api/agents/{agent}/instances/{id}/stream-token`
for a named agent. Its wire form is `{expires}.{mac}.{uid}`: an HMAC keyed by
`agents-client-token` over the agent name, instance id, and incarnation `uid`,
valid for ten minutes. Deleting and re-creating the instance invalidates the
token immediately, and opening a stream never creates an instance. A captured
stream URL gives bounded read-only access to one feed and cannot act as a
standing credential.

The SDK also includes a submit-and-stream handler (`POST …/messages` on the
threads and agents paths), which is unavailable on a deployed app because
Ferrite stream routes accept `GET` only, forward no headers, and reject
manifests that ask for anything else. Submit messages through the Thread API or
Agents API, then follow live progress over a `GET` stream or `/events`.

Each SSE frame puts the event kind in the `event` field (or `message` with a
sequence number on the console route) and the JSON envelope in `data`. A frame
with `done` closes the relay, and the gateway sends keep-alive comments while a
run is quiet.

## MCP

`POST /mcp` serves an MCP server at protocol revision `2026-07-28`. It speaks
that revision only. Clients on revision `2025-06-18` or `2025-11-25` cannot
connect because the wire formats are incompatible and no compatibility shim is
provided; call the agent through the Thread API or ACP from those clients. See
[Which clients can connect](/developers/mcp-servers/#which-clients-can-connect)
for the revision each package speaks.

The server exposes one tool per registered agent, named `agent_<name>`, taking
`message` (required), `instanceId`, `initialData` (matching the agent's
initial-data schema), and `resultSchema`. Calling the tool runs a submission,
returns the answer (and any structured output) as the tool result, and records
the instance id and submission id in the result metadata under
`ferrite/instanceId` and `ferrite/submissionId`.

Omitting `instanceId` opens a new instance. When the request carries an
idempotency key, that new instance's id is derived from the key so redeliveries
reach the instance created by the first delivery. The app refuses to start if
two agent names map to the same tool name. Every request must include the
revision's `_meta` fields (`io.modelcontextprotocol/protocolVersion` and
`io.modelcontextprotocol/clientCapabilities`) inside `params`, as revision
`2026-07-28` requires.

## ACP

`POST /acp` exposes an Agent Client Protocol v1 agent over buffered JSON-RPC.
Sessions target the default agent unless `params._meta.agent` names another.
Supported session methods:

- `session/new` creates an instance (reading optional initial data from
  `_meta.initialData`).
- `session/list` lists instances.
- `session/cancel` aborts the running submission.
- `session/load` and `session/resume` reopen an existing instance.
- `session/close` evicts the cached instance from memory.
- `session/delete` deletes the instance durably.

`session/prompt` runs a submission and answers once it settles. The response
puts the reply in `_meta.text`, its id in `_meta.submissionId`, and any error
in `_meta.error`. `/acp` emits no `session/update` notifications; follow the
stream face for live updates. Stop reasons are `end_turn` (completed),
`cancelled` (aborted), and `refusal` (failed). A JSON-RPC batch may contain at
most 16 messages and at most one `session/prompt`.

## A2A

`GET /.well-known/agent-card.json` (also served at `/.well-known/agent.json`)
is public and describes the deployment: its name, its public URL (read from the
`agents-public-url` secret), one skill per registered agent, and `/mcp` and
`/acp` as additional interfaces.

`POST /a2a` supports `message/send` (creates and runs a task), `tasks/get`, and
`tasks/cancel` (cancels a running submission). Every `POST` returns HTTP `200`
with a JSON-RPC body. If a task id is still live, or already bound to another
agent or context, `/a2a` returns JSON-RPC error code `-32602` with
`error.message` joining the SDK error's message and details with `: `. The
methods `message/stream`, `tasks/resubscribe`, and push-notification methods
answer `-32004` (unsupported). Any HTTP method other than `POST` returns `405`.

The SDK also works as an A2A client: `A2aCatalog` converts a peer deployment's
agent card into discoverable tools so one agent can delegate to another through
[dynamic tool discovery](/developers/agent-sdk/).

## Route shape

Endpoint matching is exact or on a path-segment boundary: `/mcp` matches `/mcp`
and `/mcp/…`, while `/mcpfoo` returns `404`. Your manifest controls which faces
are published and which headers reach the app.

Continue with [ferrite-agents App](/developers/agents-app/) for the manifest
routes, forwarded headers, and
[limits to check before you deploy](/developers/agents-app/#limits-to-check-before-you-deploy),
or [Agent Channels](/developers/agent-channels/) to drive conversations from
webhooks and schedules.
