# The agent contract — pairing, auth, endpoints, response shapes

The canonical AgentDB contract, rendered from the same source agents consume: pairing, token rotation, headers, the two endpoints, and response formats.

> HTML version: https://staging.agentdb.com/start/contract — this file (/docs/start/contract.md) is its markdown twin.

Read this first. It points you at the API contract and the runnable scenario,
and states the two JSON-LD rules every request must follow.

## Where to go next

- **API contract:** the contract sections below — pairing, token refresh,
  `CreateAction` / `SearchAction` / `FindAction` / `UpdateAction` /
  `DeleteAction`, the two entry points (`POST /api/action` for tenant data,
  `POST /api/action/admin` for platform admin), and response shapes.
- **Step-by-step quickstarts:** [/start/claude-code](/start/claude-code)
  — pair → create → search → find, per runtime.

Given a pairing token, pair via
`POST https://api.agentdb.com/api/action/admin` with a
`RegisterAction` + object `SoftwareApplication` and a
`PropertyValue { "name": "pairingToken" }` instrument (no JWT required),
then run the create → search → find sequence from
[the quickstarts](/start/claude-code).

## JSON-LD rules (always enforced)

The backend is a Schema.org-conformant JSON-LD store. Two rules matter on every
write:

### 1. Use valid Schema.org types and properties only

- Every payload includes `"@context": "https://schema.org/"` and a valid
  `"@type"`.
- `@type` must be a real Schema.org type, and each property must be a valid
  Schema.org property **for that type** (e.g. a `SoftwareApplication` may carry
  `softwareVersion`, `applicationCategory`, `aggregateRating`; a `Product` may
  carry `offers`, `brand`, etc.).
- Entity data is always wrapped in an action type (`CreateAction`,
  `UpdateAction`, `DeleteAction`, `FindAction`, `SearchAction`, `AddAction`,
  `AppendAction`, `PrependAction`, `DiscoverAction`, `AssessAction`).
- For data that has **no** Schema.org property, use the generic carriers
  Schema.org already provides — `additionalType` (a label/subtype),
  `additionalProperty` (`PropertyValue` `{ name, value }`), `identifier`,
  `description` — rather than inventing a top-level term. There is **no** valid
  Schema.org `error` term: failures are reported in `description`.
- Internal, non-Schema.org metadata (when unavoidable) is namespaced with a
  leading underscore (e.g. `_searchMeta`) so it is never confused with a
  Schema.org property.

### 2. `@id` — server UUID by default, or claim your own IRI

- Every created node (root and nested) gets a server-generated UUIDv7. If you
  **don't** send an `@id` on create, that UUID is the entity's `@id`.
- You **may** send your own `@id` on create — it must be an **absolute IRI**
  (e.g. `https://myshop.example/products/42`). The entity is then addressed
  and serialized by that IRI everywhere; the internal UUID still exists
  underneath. An IRI is unique per container among live entities: re-claiming a
  taken IRI is a conflict (`409`), and once set an entity's IRI cannot be
  changed. A bare relative string (`products/42`) is rejected.
- To give an entity a **stable, custom key without IRI semantics**, set
  **`identifier`** — the user-supplied key, allowed on any `@type` at any
  nesting level. Responses normalize it to `urn:{identifier}`.
- Creates **upsert on `identifier`**, so re-sending the same `identifier` is
  idempotent (it updates the existing node rather than creating a duplicate).
  IRI `@id` creates do NOT upsert — a duplicate claim is an error.
- To **target** an existing entity (find / update / delete / search) you may
  use its `identifier` (plain or `urn:...`), its UUID `@id`, or its IRI `@id`.
  When both `@id` and `identifier` are present, `@id` wins.

#### `@id` vs `identifier` at a glance

| Aspect               | IRI `@id`                        | `identifier`                    |
| -------------------- | -------------------------------- | ------------------------------- |
| Format               | absolute IRI only                | any string                      |
| Uniqueness           | enforced per container (live)    | not enforced                    |
| Duplicate on create  | `409` conflict                   | upsert (updates existing)       |
| Mutability           | immutable once set               | updatable                       |
| Addressing priority  | wins over `identifier`           | fallback when `@id` misses      |

#### Example — publishing with a custom key

```jsonld
{
  "@context": "https://schema.org/",
  "@type": "CreateAction",
  "object": {
    "@type": "SoftwareApplication",
    "identifier": "agentdb-utility:relative-date-parser",
    "name": "relative-date-parser",
    "applicationCategory": "DateTimeParsing",
    "softwareVersion": "1.0.0"
  }
}
```

The response echoes the same node with a generated `@id`
(`"@id": "019b12bf-2cfe-7312-9cfa-941ee068f412"`) and
`"identifier": "urn:agentdb-utility:relative-date-parser"`.

---

## The API contract

The sections below are rendered from the canonical AgentDB contract —
they are not hand-written for this site and cannot drift from it.
The API base URL is `https://api.agentdb.com/api`.

## Agent Bootstrap (First-Time Setup)

An agent cannot self-provision. A **human** registers the agent and configures
its access through the admin portal.

### What the human provides

After setup, the human gives the agent:

- **pairing token** (one-time, short-lived)
- **base URL** of the backend

### Agent pairs (one-time)

Pairing is an action verb on the admin plane — no JWT needed:

```
POST https://api.agentdb.com/api/action/admin
Content-Type: application/json
```

```json
{
  "@context": "https://schema.org/version/28.0",
  "@type": "RegisterAction",
  "object": { "@type": "SoftwareApplication" },
  "instrument": [
    {
      "@type": "PropertyValue",
      "name": "pairingToken",
      "value": "PAIRING_TOKEN"
    }
  ]
}
```

Response (`result` is the token document):

```json
{
  "@context": "https://schema.org/",
  "@type": "RegisterAction",
  "actionStatus": "CompletedActionStatus",
  "object": { "@type": "SoftwareApplication" },
  "result": {
    "@type": "DigitalDocument",
    "name": "Bearer Token",
    "additionalType": "JWT",
    "text": "ACCESS_TOKEN_JWT",
    "additionalProperty": [
      { "@type": "PropertyValue", "name": "tokenType", "value": "Bearer" },
      { "@type": "PropertyValue", "name": "expiresIn", "value": 2592000 },
      { "@type": "PropertyValue", "name": "refreshToken", "value": "OPAQUE" },
      {
        "@type": "PropertyValue",
        "name": "refreshTokenExpiresIn",
        "value": 7776000
      }
    ]
  }
}
```

Store the access token (`result.text`) and the `refreshToken` PropertyValue. The
JWT payload contains `client_id`, `principal_id` (the agent principal), and
`session_id` if you need them — decode the JWT to extract. The pairing token is
single-use; a second call will fail.

### Token rotation

Before the access token expires, rotate — same verb, `refreshToken` instrument:

```
POST https://api.agentdb.com/api/action/admin
Content-Type: application/json
```

```json
{
  "@context": "https://schema.org/version/28.0",
  "@type": "RegisterAction",
  "object": { "@type": "SoftwareApplication" },
  "instrument": [
    {
      "@type": "PropertyValue",
      "name": "refreshToken",
      "value": "CURRENT_OPAQUE_REFRESH_TOKEN"
    }
  ]
}
```

If your session is bound to an OAuth client, also send a
`PropertyValue { "name": "clientId" }` instrument (decode `client_id` from the
JWT received at pairing).

Response returns a fresh token document (new access token in `result.text`, new
`refreshToken` PropertyValue). **Always persist the new refresh token
immediately** — the old one is invalidated on use.

## Authentication Headers

### Data actions (`POST /api/action` — data plane)

```
Authorization: Bearer <access_token>
Content-Type: application/json
```

The JWT contains routing context (principal, scope). No additional headers are
required for the agent's home container. Add `apikey: <root-scoped-api-key>` to
target another container root (e.g. a `Project` root).

> **Do not send top-level `location` or `VirtualLocation`.** The server rejects
> it with 400. Access is membership-based; domains are internal labels only.

### Admin actions (`POST /api/action/admin`)

```
Authorization: Bearer <token>
Content-Type: application/json
```

Admin operations POST to **`/api/action/admin`** — the URL selects the admin
plane; no property of the JSON-LD body does. Public auth actions (`LoginAction`,
`RegisterAction`, `ResetPasswordAction`, and `Person` `LeaveAction`) also POST
to `/api/action/admin` and require no JWT. The container is always resolved from
the credential; a client-sent container header is ignored.

### 2.1 Email OTP sign-in (`LoginAction`)

Use this when you have an **email address** and no token. (If a human gave you a
one-time **pairing token** instead, use §1 — that is a different exchange.) One
JWT comes out of this flow and it authorizes **both** planes: the same
`Authorization: Bearer <jwt>` works for `POST https://api.agentdb.com/api/action` and
`POST https://api.agentdb.com/api/action/admin`.

It is two calls to `POST https://api.agentdb.com/api/action/admin`, both **without** an
`Authorization` header, both sending the same `LoginAction`. What distinguishes
them is the `instrument` slot: **absent** means "send me a code", **present**
means "here is the code".

Both request and response shapes below were captured from a live service on
2026-08-28.

**First — request the code.** No `instrument`:

```json
{
  "@context": "https://schema.org/",
  "@type": "LoginAction",
  "object": {
    "@type": "Person",
    "email": "you@example.com"
  }
}
```

Response — HTTP 200, `ActiveActionStatus` (the action is open, awaiting the
code):

```json
{
  "@context": "https://schema.org/",
  "@type": "LoginAction",
  "actionStatus": "ActiveActionStatus",
  "description": "If this email is registered or eligible, a code has been sent."
}
```

The wording is deliberately non-committal — it does **not** confirm the address
exists, so you cannot use this call to probe for registered accounts. A
six-digit code goes to the mailbox. **Test environments may echo the code back
in `instrument`** so an unattended agent can complete the flow without reading
email:

```json
"instrument": [{ "@type": "PropertyValue", "name": "code", "value": "176146" }]
```

That is exactly the shape you send back when you verify. Never assume it is present —
in a normal environment it is absent and the code must come from the human.

**Then — verify the code.** The same action, repeating the email, now with the
code as a `PropertyValue` named `code` on `instrument`:

```json
{
  "@context": "https://schema.org/",
  "@type": "LoginAction",
  "object": {
    "@type": "Person",
    "email": "you@example.com"
  },
  "instrument": [
    { "@type": "PropertyValue", "name": "code", "value": "176146" }
  ]
}
```

Response — HTTP 200, `CompletedActionStatus`. The signed-in `Person` is on
`agent`; the JWT is on `result` as a `DigitalDocument` with
`additionalType: "JWT"`, and the token string is in **`text`**:

```json
{
  "@context": "https://schema.org/",
  "@type": "LoginAction",
  "actionStatus": "CompletedActionStatus",
  "agent": {
    "@context": "https://schema.org/",
    "@type": "Person",
    "identifier": "user_ef3f0e",
    "email": "you@example.com"
  },
  "result": {
    "@type": "DigitalDocument",
    "name": "Bearer Token",
    "encodingFormat": "text/plain",
    "additionalType": "JWT",
    "text": "<JWT>"
  }
}
```

Read the token from `result.text` and send it as
`Authorization: Bearer <result.text>`. Hold it in memory only. First-time
sign-in also provisions the caller's organizations, so an immediate admin
`SearchAction` on `Organization` will return them.

**Failure modes.** All three keep the `LoginAction` envelope and report
`FailedActionStatus` with an `Error` node on `error`. Branch on `error.name`,
not on the status code — two of the three share HTTP 400:

| `error.name`        | Status  | Meaning                                                                                                                       | What to do                                                                 |
| ------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `InvalidCode`       | **400** | Wrong or expired code. `description`: "Invalid or expired code. Please request a new one."                                    | Ask the human for the correct code. Do **not** retry the same value.       |
| `RateLimitExceeded` | **400** | Too many code **requests** for this address. `description`: "Too many OTP requests. Please wait before trying again."         | Stop requesting. Reuse the code already sent, or wait before asking again. |
| `RateLimited`       | **429** | Too many failed **verify** attempts. `description` names the wait, e.g. "Too many failed attempts. Try again in 900 seconds." | Stop. Wait the stated number of seconds before any further attempt.        |

```json
{
  "@context": "https://schema.org/",
  "@type": "LoginAction",
  "actionStatus": "FailedActionStatus",
  "error": {
    "@type": "Error",
    "name": "InvalidCode",
    "description": "Invalid or expired code. Please request a new one."
  }
}
```

Two traps worth internalizing:

- **Re-requesting a code is itself rate-limited, and fails as a `400`.** A retry
  loop that reacts to `InvalidCode` by requesting a fresh code will hit
  `RateLimitExceeded` within seconds. Request once, then verify.
- **A wrong code burns a small budget.** After a handful of failed verifies the
  address is locked for the window named in the `RateLimited` description, and
  requesting a new code does not clear it. Confirm the code with the human
  before sending it.

### 2.2 Report permit — long-lived admin-plane read credential (`Permit`)

The OTP JWT lives 24 hours, so an unattended loop that needs one admin-plane
report a day would otherwise need a human every day. A **report permit** is a
`report_reader` bearer minted once from the owner's JWT: months-long (default
180 days, max 366), revocable, and scoped to **admin-plane report reads only**
(`SearchAction` on a `Dataset` report and the billing usage dashboard). It is
rejected on the data plane and on every admin write.

**Mint** — owner JWT (the organization's owner, a human session), on
`POST https://api.agentdb.com/api/action/admin`:

```json
{
  "@context": "https://schema.org/",
  "@type": "CreateAction",
  "object": {
    "@type": "Permit",
    "name": "nightly ops board",
    "validUntil": "2027-03-01T00:00:00Z"
  }
}
```

The response is a `Permit` whose `identifier` is the permit id and whose
`subjectOf.text` is the bearer — the only time it is shown. Store it with the
same care as a refresh token. Then read reports with
`Authorization: Bearer <permit>` exactly as with the owner JWT.

**Revoke** — `DeleteAction` + `Permit { identifier }`; **list** —
`SearchAction` + `Permit` (no secrets in the listing). A revoked or expired
permit answers `401`; mint a new one at a terminal. Agent tokens and root-scoped
API keys cannot mint permits.

In `@agent-db/client`, `OwnerSession.ensureReadToken()` (module
`@agent-db/client/session`) manages this end to end: it returns a stored, usable
permit without any network call, mints one when a human is at the terminal, and
refuses — without sending a `LoginAction` — when unattended.

## Endpoints Overview

| Endpoint                 | Purpose                                                                                                                                                                                                                                                   |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST /api/action`       | JSON-LD **data plane** (Schema.org entity CRUD, analytics `AssessAction`). Top-level `location` is rejected (400).                                                                                                                                        |
| `POST /api/action/admin` | JSON-LD **admin plane** (organization and agent principals, API keys, `DiscoverAction`, billing, the public auth actions, and agent pairing/token rotation — `RegisterAction` + `SoftwareApplication` with a `pairingToken` / `refreshToken` instrument). |

These two endpoints are the complete surface. Realtime verbs (`SubscribeAction`
— persistent webhook/websocket subscriptions, `ListenAction` — short-lived 24h
event listeners, `ScheduleAction` — recurring/one-time jobs) ride
`POST /api/action` like every other data-plane action.

When the API base URL is `https://api.agentdb.com/api`, data
actions go to `POST https://api.agentdb.com/api/action` and admin actions (including pairing and
token rotation) to `POST https://api.agentdb.com/api/action/admin`.

**Plane rules (the URL is the plane):**

1. `POST https://api.agentdb.com/api/action/admin` → **admin plane** (principal provisioning, API
   keys, `DiscoverAction`, …).
2. `POST https://api.agentdb.com/api/action` → **data plane** (entity CRUD, including container
   roots and their membership).
3. **No property of the JSON-LD body selects a plane.** The legacy top-level
   `additionalType` admin marker is rejected on `/api/action` with 400
   (`ADMIN_MARKER_REMOVED`).
4. **Do not send top-level `location` or `VirtualLocation`** — rejected
   with 400.
5. Public auth actions (`LoginAction`, `RegisterAction`, `ResetPasswordAction`,
   `Person` `LeaveAction`) POST to `/api/action/admin` with no JWT. The
   `LoginAction` email one-time-code exchange is worked end to end in §2.1.

(The legacy `POST /api/data` and `POST /api/admin` endpoints were removed and
return `LEGACY_ACTION_ENDPOINT_REMOVED`.)

**Platform `additionalType` values are URLs.** schema.org defines
`additionalType` as a URL, so every flavour, carrier and role marker AgentDB
defines is an IRI under `https://agentdb.com/ns/` — e.g.
`https://agentdb.com/ns/RegisterMcpConnector`, `https://agentdb.com/ns/Agent`,
`https://agentdb.com/ns/JWT`. Responses always return the IRI form. Requests may
send either the IRI or the bare local name (`"additionalType": "Agent"`), so the
short forms used in the examples below remain valid input. Your own
`additionalType` values (`Product`, `https://schema.org/HowTo`,
`acme:ApproveRefundAction`) are returned exactly as you stored them. When
comparing an `additionalType` in a response, compare against the IRI.

## Response format

**There is no envelope wrapper.** The response body is the JSON-LD document
itself — read it directly. Do not look for the payload under any nested key.

The data plane is **asymmetric**: entity-returning actions answer with the
**bare entity**, while collection and assessment actions answer with an **action
envelope**. Branch on the action you sent, not on a single shape.

| Action                   | Top-level response                                                                         | Where the payload is        |
| ------------------------ | ------------------------------------------------------------------------------------------ | --------------------------- |
| `CreateAction`           | the created entity                                                                         | the body itself             |
| `FindAction` (match)     | the entity                                                                                 | the body itself             |
| `FindAction` (no match)  | `{"message": "No record found"}` with **HTTP 200**                                         | absent — see the note below |
| `UpdateAction`           | the merged entity                                                                          | the body itself             |
| `DeleteAction`           | `{"@type": "DeleteAction", "actionStatus": "CompletedActionStatus", "object": {"@id": …}}` | `object.@id`                |
| `SearchAction`           | `{"@type": "SearchAction", "actionStatus": …, "result": <ItemList>}`                       | `result.itemListElement`    |
| `AssessAction` (Analyze) | `{"@type": "AssessAction", "additionalType": "Analyze", …, "result": <node>}`              | `result`                    |

Entity bodies carry `@id` (server-assigned UUID), `@type`, `@context`,
`identifier` normalized to `urn:<identifier>`, and every property you sent. A
nested single-valued relation (e.g. `publisher`) comes back as a **single
object**, not a one-element array, and each nested node carries its own `@id`
and normalized `identifier`.

> **A `FindAction` miss is not an error.** It returns **HTTP 200** with the body
> `{"message": "No record found"}` — no `@id`, no `actionStatus`, no `error`.
> Test for the presence of `@id` before treating a 200 as a hit; a client that
> assumes 200 means "found" will read `undefined`.

**Errors** on the data plane are a flat object with a single `error` string and
an HTTP 4xx status — **not** an action envelope, so do not look for
`actionStatus` or an `Error` node here:

```json
{ "error": "object[\"@type\"] is required for CreateAction" }
```

Parse `error` for the human-readable message. See §17 for how to classify it —
in particular, a permission denial arrives as a **400**, not a 403.

**Anonymous `SearchAction` is allowed — anonymous `FindAction` is not.** The two
behave differently, so do not generalize from one to the other:

| Action, no `Authorization` header | Result                                                                      |
| --------------------------------- | --------------------------------------------------------------------------- |
| `SearchAction`                    | **200** — normal enveloped result, plus the `contextToken` instrument below |
| `FindAction`                      | **404** — `{ "error": "DIRECTORY_NOT_FOUND: …" }`, no result and no token   |

A 404 here does not mean the entity is absent; it means an unauthenticated
caller cannot address it. Authenticate (§2.1 or §1) and retry, or use
`SearchAction` if you genuinely intend an anonymous public-directory read. See
§17 for the 404 branch.

An anonymous `SearchAction` returns an extra top-level `instrument`:

```json
{
  "@type": "PropertyValue",
  "name": "contextToken",
  "value": "<opaque token>",
  "description": "Anonymous context session token. Present as `Authorization: Bearer <value>` to keep and extend your visit context."
}
```

Present that value as `Authorization: Bearer <value>` on later calls to keep one
visit context. It is **not** a substitute for a real identity: writes and scoped
reads still need a JWT or a pairing-issued token.

## Actions declared on this page (JSON-LD)

```jsonld
[
  {
    "@type": "RegisterAction",
    "name": "Pair an agent",
    "target": {
      "@type": "EntryPoint",
      "urlTemplate": "https://staging-api.agentdb.com/api/action/admin",
      "httpMethod": "POST",
      "contentType": "application/ld+json"
    },
    "object-input": {
      "@type": "PropertyValueSpecification",
      "valueName": "pairingToken",
      "valueRequired": true
    }
  }
]
```
