# Mailagents Test API foundation

Version 0.3.0 · October 13, 2026 · [OpenAPI](/openapi.json) · [Capabilities](/v1/capabilities)

This development release persists identities, key metadata, inbox metadata, drafts, messages, threads and policies in Supabase. Database readiness does not establish email delivery: SES/DNS provisioning, mandatory provider screening, payments, AI, external event delivery, and production SDK/CLI/MCP remain separate integration gates. The console and A2A demo still use demonstration data.

The public deployment remains Test with `MAILAGENTS_API_ENABLED=false` and signup disabled. All agent API operations, including existing-key access to inboxes, messages, drafts and policies, return `503 api_disabled` before contacting the database. Public capabilities and OPTIONS discovery remain available; capabilities reports `api_enabled: false` and no available operations. The website and deterministic demos do not send email. Billing is not implemented, so paid access is not available either; this deployment lock is not a payment entitlement check. Keep it closed until billing and release gates are implemented. Vercel defaults to a closed API when this flag is absent or invalid.

## SDK and CLI setup

The homepage examples use development builds from source; SDK packages and CLI binaries are not published yet. Build `packages/sdk-typescript` and install or link that local package into your server application as `@mailagents/sdk`. Install Python from `packages/sdk-python` (import `mailagents`), or build the native CLI from `crates/mailagents-cli`. The repository's `docs/clients/README.md` contains the build commands.

Run SDK examples server-side. Inject `MAILAGENTS_API_KEY` into the runtime; do not put it in browser code. `new Mailagents()` and Python `Mailagents()` read this variable automatically. The URL defaults to `https://api.mailagents.dev`; set `MAILAGENTS_BASE_URL` for an authorized Test deployment. Explicit constructor URL/key options override environment variables. Loading a saved profile uses its stored credential and still checks that its origin matches the configured URL.

Before creating an inbox, generate one random UUID and persist it with the request body in your application's job record. Set `MAILAGENTS_IDEMPOTENCY_KEY` to that saved value for these examples. Reuse the same value and input after a timeout, retry or process restart; use a new value only for a new operation. SDK mutations require the key explicitly and never generate a replacement on retry. The CLI requires `--idempotency-key`; JSON output is already the default. The cURL and CLI examples use POSIX shell syntax.

The public API remains disabled in this preview. A shorter example does not enable account creation or email delivery; the playground only simulates these actions locally.

## Operator setup

1. Select an isolated Supabase development project. Apply the versioned files in `supabase/migrations/` in order using your normal migration workflow. Each is transactional and intended to run once. The foundation migration creates the API; `202610130002_worker_status.sql` adds the server-only Trigger.dev diagnostic; `202610130003_key_lifecycle.sql` adds issuance, management and rotation; `202610130004_mail_core.sql` adds the mail API. Provider/worker migrations are separate from the public API readiness probe.
2. Copy `.env.example` to `.env.local`. Set `SUPABASE_URL` and a server-only `SUPABASE_SECRET_KEY`. A legacy `SUPABASE_SERVICE_ROLE_KEY` also works. Do not use a publishable/anon key or a `NEXT_PUBLIC_` variable.
3. Keep `MAILAGENTS_ENVIRONMENT=test`. For isolated operator testing only, explicitly set `MAILAGENTS_API_ENABLED=true` and enable `MAILAGENTS_SIGNUP_ENABLED=true` when registration is needed after migration. Keep both flags false on the public deployment. SQL caps Test registrations at 30/hour and 100 total; only an operator can change those limits.
4. Leave `MAILAGENTS_EMAIL_DOMAIN` empty until a separate agent email domain is selected. Empty produces `address: null`; a configured value reserves an address without verifying DNS. The brand domain and its subdomains are rejected.
5. Run `pnpm dev` and check `GET /v1/health`. Success verifies the foundation, key lifecycle and mail core RPC versions (001/003/004). Errors identify the unavailable/incompatible migration without database details. `capabilities` separates `database_configured`, `database_ready`, code `implemented`, currently `available` and `unavailable`; its `readiness` object reports each probe separately. Missing key/mail SQL does not hide the available foundation. These checks do not establish email or payment readiness. There is no fallback to in-memory identities.

The private schema has RLS enabled. Only `service_role` can execute the exposed RPC; browser roles cannot call it or read tables. Human Supabase Auth is not connected in this release.

## Agent registration

Generate **32 cryptographically random bytes**, encode as 64 hexadecimal characters, and save in the runtime's secret store **before the first request**. Persist a random `Idempotency-Key` and the body too. They must survive a timeout or restart.

```http
POST /v1/agents/register
Content-Type: application/json
Authorization: Bootstrap <64 hexadecimal characters from your secret store>
Idempotency-Key: <persisted UUID>

{"agent_name":"Support agent","workspace_name":"Default","local_part":"support"}
```

Only `agent_name` is required. Omit `workspace_name` and `local_part` to create the `Default` workspace and an `agent` inbox automatically, with no separate workspace setup. The first response is `201`, with `data.organization`, `workspace`, `agent`, `api_key`, `inbox`, and `credential.secret`. Save the API key securely without logging it or passing it into model context. Subsequent requests use `Authorization: Bearer <API key>`.

If the response is lost, retry with the same bootstrap secret, key and body. For 24 hours this returns `200`, `replayed: true`, and the same resources/credential. The server stores only secret hashes and rechecks access before deriving the credential. An idempotency key alone cannot recover it. Revocation, expiry, suspension and narrowed access prevent recovery. After 24 hours, use the saved API key; credential-free recovery is unavailable.

The initial key expires after 30 days and grants identity/inbox metadata access, self-revocation and `keys:manage`. It grants no financial authority. Migration 003 upgrades only active initial keys proven by registration records with their original scopes intact and unrestricted inbox access. Narrowed, expired, revoked or unproven keys receive no additional authority. Rotation of a valid bootstrap key now renews its 30-day lifetime without adding scopes. Expired bootstrap recovery is restricted to a separately authenticated, verified workspace owner; owner onboarding/UI is not connected yet. Revoked keys cannot be recovered.

After migration 004, **new registrations** additionally receive `messages:read`, `messages:send`, `drafts:write`, `drafts:approve`, `policies:read` and `policies:write`. Existing keys do not gain these mail scopes through migration, recovery or rotation. Consult `capabilities.api_key_scopes` and your current credential before delegating.

## Operations

| Method | Path | Permission |
|---|---|---|
| GET | `/v1/capabilities` | Public; includes read-only database availability probes |
| GET | `/v1/health` | Public; database readiness only |
| POST | `/v1/agents/register` | Bootstrap proof, registration enabled |
| GET | `/v1/me` | `identity:read` |
| GET | `/v1/inboxes?limit=20&after=<next_cursor>` | `inboxes:read` |
| POST | `/v1/inboxes` | `inboxes:write`, workspace-wide grant |
| GET | `/v1/inboxes/{id}` | `inboxes:read`, accessible inbox |
| POST | `/v1/inboxes/{id}/archive` | `inboxes:write`, accessible inbox |
| DELETE | `/v1/api-keys/current` | `keys:revoke` |
| GET | `/v1/api-keys/current` | Any active credential; metadata only |
| GET | `/v1/api-keys?limit=20&after=<next_cursor>` | `keys:manage`; covered grants in the same agent |
| POST | `/v1/api-keys` | `keys:manage`; delegate equal or narrower access |
| DELETE | `/v1/api-keys/{id}` | `keys:manage`; target grant covered by caller |
| POST | `/v1/api-keys/current/rotate` | `keys:revoke`; prepare replacement |
| POST | `/v1/api-keys/current/confirm-rotation` | `keys:revoke`; authenticate with replacement |

Create an inbox with JSON `{"local_part":"billing"}` and an `Idempotency-Key`. `display_name` is optional and defaults to `local_part`; an explicit name is trimmed and must be nonblank, at most 80 characters, without control characters. Null and other non-string names are rejected. Archive with `{}` and an `Idempotency-Key`. Bodies are JSON objects up to 8 KiB. Unknown fields, invalid local parts and duplicate/unknown query parameters are rejected. Page size is 1–100; treat cursors as opaque. Pagination is not a snapshot during concurrent writes.

Inboxes start in `provisioning` and cannot send or receive. Free permits at most three non-archived inboxes across the organization, including provisioning inboxes and other workspaces. Archive frees capacity but permanently reserves the address; it is not deletion. Inbox-scoped credentials cannot expand their grant by creating inboxes. Out-of-scope resources return 404. Plan upgrades are unavailable in this release.

Retries return the original create/archive result with `Idempotency-Replayed: true`; GET returns current state. Inbox defaults are resolved before hashing: omitting `display_name` and explicitly sending the same value as `local_part` identify the same payload. Different normalized input with the same key produces 409. Idempotency is scoped to the agent and operation, including across replacement credentials. Authorization is checked on every replay. Retrying self-revocation returns 401 because the key is already invalid.

## Delegating credentials

Generate and persist a **fresh** 32-byte random `Key-Bootstrap` (64 hex characters), an `Idempotency-Key` and the exact request before issuance. Send `POST /v1/api-keys` with your Bearer credential and both headers. The JSON body requires all four fields:

- `name`: 1–80 characters after trimming, without control characters.
- `scopes`: nonempty, unique values from `capabilities.api_key_scopes`, all held by the issuing key.
- `inbox_ids`: `null` for workspace access, `[]` for no inbox access, or up to 100 distinct accessible inbox UUIDs. A restricted key cannot delegate `null` or inboxes outside its own grant.
- `expires_at`: a real UTC timestamp such as `2026-10-14T12:00:00.000Z`, strictly in the future and no later than the issuer's expiry. Choose a date valid for your current key. UTC `Z` and seconds are required; fractional seconds may contain 1–3 digits. Offsets, impossible dates, `24:00`, leap seconds and non-finite dates are rejected.

Success is `201` with `data.api_key` metadata and `data.credential.secret`. Save the credential securely. On timeout, repeat the original request with the same bootstrap, idempotency identity and authorized Bearer key within 24 hours; this reconstructs the same credential and sets `Idempotency-Replayed: true`. The database stores only hashes. Different payload or bootstrap with the same operation identity returns `idempotency_conflict` (409). Reusing the bootstrap for a different issuance also conflicts. Caller authorization and target validity are checked before disclosure; expiration, revocation or lost authority cannot be bypassed through replay. After 24 hours recovery returns `key_recovery_expired` (410); the issued key's own expiry is unchanged.

GET and list return only metadata, including status, timestamps, issuer and rotation IDs. They never return credentials, bootstrap material or credential hashes. Management is limited to the same agent, organization and workspace, and to target scopes/inbox access/expiry fully covered by the caller. A key with `keys:manage` cannot list or revoke a stronger sibling. Revoked and expired metadata remain visible within that grant. All GET paths support HEAD with the same status/headers and no body.

The Test safety limit is 20 active keys per agent, including unconfirmed replacements. Expired and revoked keys do not count. Idempotent retries never consume another slot. Revoke a covered key with `DELETE /v1/api-keys/{id}`; retries with a still-valid management key return 200 without duplicate audit events. Revoking an issuer does not revoke its already-issued independent delegates; revoke those separately by ID.

## Rotation and timeout recovery

1. Persist a fresh bootstrap and idempotency identity. Call `POST /v1/api-keys/current/rotate` with `{}`, the old Bearer key, `Key-Bootstrap` and `Idempotency-Key`.
2. The response is `201` with the replacement metadata and credential. The old key remains usable. The replacement has exactly the same scopes and inbox grant. Bootstrap-key rotation renews expiry to 30 days; delegated-key rotation retains its **absolute expiry**. Save it and verify access with `GET /v1/api-keys/current`.
3. Call `POST /v1/api-keys/current/confirm-rotation` with `{}` and the **replacement** Bearer key. No bootstrap or idempotency header is required. The transaction marks the replacement confirmed and revokes the old key; the response contains `api_key` and `revoked_key_id`.
4. If preparation times out, recover by retrying step 1 unchanged within 24 hours. If confirmation times out, retry step 3 with the replacement; it remains idempotent while that credential is valid. The old key may already be revoked.

Only one pending replacement is allowed per source. Before 24 hours, a different prepare request returns `rotation_pending` (409). An unconfirmed replacement can read/use its authorized resources but cannot issue more keys or begin another rotation. Revoking the source before confirmation also revokes the pending replacement. Narrowing or expiring the source blocks the pending key and confirmation.

After 24 hours, the original preparation retry returns 410. A **new** prepare request using the still-valid source can atomically revoke the abandoned unconfirmed replacement and issue another, with an `api_key.rotation_expired` audit event. The invalidated replacement cannot be confirmed. Confirmation and abandonment recovery share the organization lock: if confirmation already succeeded, the revoked source cannot cancel the confirmed key. An authorized management key can also revoke a pending replacement by ID before starting over.

Confirmed replacements may rotate again. Rotation does **not** renew the 30-day Test access period, and delegation cannot extend it. Renewal beyond the original authorization period requires a separate operator/identity recovery contract and is unavailable in this release.

## Mail API integration

These paths are relative to `/v1/inboxes/{inbox_id}` and always authorize the inbox before accessing data or replaying an operation:

| Method | Path | Permission |
|---|---|---|
| GET / POST | `/messages` | `messages:read` / `messages:send` |
| GET | `/messages/{id}` | `messages:read` |
| POST | `/messages/{id}/reply` | `messages:send` |
| GET / POST | `/drafts` | `messages:read` / `drafts:write` |
| GET / PUT | `/drafts/{id}` | `messages:read` / `drafts:write` |
| POST | `/drafts/{id}/approve` | `drafts:approve` |
| POST | `/drafts/{id}/send` | `messages:send` |
| GET | `/threads` and `/threads/{id}` | `messages:read` |
| GET / PUT | `/policy` | `policies:read` / `policies:write` with workspace-wide grant |
| POST | `/policy/simulate` | `policies:read`; no persistent mutation |

All persistent mail mutations require `Idempotency-Key`; simulation does not. Bodies are JSON objects up to 1 MiB. Message content accepts `to`, `cc`, `bcc`, `subject`, `text`, `html` and exact attachment references `{id,version}`. At least one recipient and a nonblank text or HTML body are required. At most 20 distinct recipients are allowed across To/Cc/Bcc; duplicates are removed in that order. Each body part is at most 256 KiB UTF-8. Client HTML is sanitized before the Free footer and quoted reply text are applied. There is no public upload/download route in this contract.

Create drafts with `POST /drafts` (201). Read the draft to obtain its final preview, `version` and `final_hash`. PUT supplies full replacement content and `expected_version`. Approval requires `{expected_version,expected_hash}`; sending the draft requires `{expected_version}`. Version/content changes invalidate approval. Free branding is part of the final content/hash. A send/reply response of **202 means accepted for screening**, not delivered; mandatory checks and inbox transport readiness still apply.

If an accepted message becomes `held` with `reason_code: approval_required`, read its current preview through `GET /messages/{id}` and have an authenticated workspace owner approve the current version/hash/policy through the private owner RPC. Agent approval endpoints are denied. This does not create a second quota reservation or outbox entry. `delivery_unknown` is never automatically resent; operator/worker recovery remains separate from these public routes.

Lists return metadata and `next_cursor`; use `limit` (1–100) and `after`. Messages also support `q`, `thread_id` and `delivery_status`; draft lists are always restricted to drafts. Thread detail is a paginated message metadata collection. `q` is simple full-text search of readable subject/text, not semantic search. Single-message GET returns authorized content when available. Lists, thread pages and idempotency replay never disclose bodies or Bcc. Eligible outbound detail exposes Bcc only to the creator with sending/draft authority, or a credential with `drafts:approve`.

Policies are workspace-wide even though addressed through an authorized inbox. PUT requires the current `expected_version`, `rules`, `allow_only` for receive/send/reply and `require_approval`. A restricted inbox grant cannot replace a workspace policy. Simulate with `{"action":"send","address":"recipient@example.com"}` to inspect the deterministic policy outcome. Reply must satisfy both Send and Reply rules. Full request and response schemas are in OpenAPI.

## Errors

```json
{
  "error": {
    "code": "quota_exceeded",
    "message": "The organization's inbox capacity is exhausted.",
    "retryable": false,
    "next_action": "Inspect the plan limits. Top-ups and new workspaces do not increase capacity.",
    "request_id": "<server-generated UUID>"
  }
}
```

Responses include `X-Request-Id` and `Cache-Control: private, no-store`. Dependency failures return 503 without upstream details. If a mutation may have committed, retry its original identity rather than creating a replacement. Signup throttling returns 429 with `Retry-After`.

No wallet, AWS, Stripe or AI-provider credentials belong in signup. Supabase secrets stay on the server. Keep bootstrap/API keys outside model context, logs and command-line arguments. Send credentials only to the intended API host over HTTPS outside loopback development.

## Validation

`pnpm test:api` executes the migration on PostgreSQL/PGlite, including rollback and database restart. It does not contact your Supabase project. PGlite has one connection.

Operators can explicitly run `pnpm test:api:hosted` after migrations 003/004 with a configured Test `.env.local` to verify the real Supabase gateway, concurrent idempotent requests, quota races, tenant isolation, delegation, repeated rotations, lost prepare/confirm responses and revocation. The script probes required versions before creating fixtures and never applies migrations. It creates two Test organizations, revokes its API keys afterward, and saves non-secret fixture metadata in `test-results/hosted-<run>.json`. Fixture organizations remain until the operator removes them and count toward the Test registration ceiling. This command is excluded from the default test suite. PGlite covers SQL rollback, both serial orders of abandonment/confirmation and legacy-key migration; it does not demonstrate multiple database sessions. Load/failover and external integrations still require separate acceptance tests; the foundation does not complete the 50 V1 launch checks.

### Additional hardening contracts

Registration has a per-source HMAC quota (3/hour, 5/day) in addition to global limits. Vercel deployments derive it from the trusted platform IP header, grouping IPv6 by /64. Arbitrary forwarded headers are not trusted. This is basic abuse control, not bot-proof identity.

Search uses indexed exact normalized lexemes with AND semantics, including large MIME bodies. Exact domains remain exact; `*.example.com` explicitly covers that domain and its subdomains.

Test mail content expires after 30 days and expired reads expose only redacted metadata. Database cleanup runs hourly; S3 version expiration is asynchronous. See the retention runbook.
