# API reference

Two equivalent surfaces cover the same domain: a **REST API** and an **MCP
server**. This page is a map — the interactive, always-current reference is the
generated OpenAPI at <https://futex.rodmena.co.uk/docs>, and the agent-oriented
guide is <https://futex.rodmena.co.uk/claude>.

## Authentication

Every `/v1/*` call and the MCP endpoint takes a bearer token:

```
Authorization: Bearer futex_sk_...
```

Keys are tenant + principal scoped. An invalid key is `401`; the authorization
oracle being unavailable is `503` (fail-closed). Errors use a consistent envelope:
`{ "error": { "code", "message", "details", "request_id" } }`.

## REST endpoints

### Public / operational
| Method | Path | Purpose |
|--------|------|---------|
| GET | `/` | Landing page |
| GET | `/claude` | Agent setup guide |
| GET/HEAD | `/llms.txt` | Plain-text agent reference |
| GET/HEAD | `/guides/{webhooks,api-reference,provisioning,state-machine}.md` | These docs, served as markdown |
| GET | `/healthz`, `/ping` | Liveness (also `HEAD /health`) |
| GET | `/readyz` | Readiness — checks DB + Redis |
| GET | `/metrics` | Prometheus metrics. nginx answers it only to vm-2 itself, where Prometheus runs; anyone else gets `403` |
| — | `/docs`, `/openapi.json` | Interactive OpenAPI |

### Tenants, members, keys
| Method | Path | Purpose |
|--------|------|---------|
| POST | `/v1/tenants` | Create a tenant (platform key) |
| GET/POST | `/v1/tenants/{id}/members` | List / add members |
| POST/GET | `/v1/tenants/{id}/api-keys` | Issue / list keys |
| DELETE | `/v1/tenants/{id}/api-keys/{key_id}` | Revoke a key |
| GET | `/v1/platform/tenants/{id}/decisions` | Decision **status only**, across a tenant (platform key) |
| GET | `/v1/platform/tenants/{id}/decisions/{decision_id}` | One decision's status (platform key) |
| POST | `/v1/platform/provisioners` | Issue a provisioning key (platform key) |
| PUT | `/v1/platform/provisioners/{principal_id}/roles` | Set the extra roles a provisioning key may grant: `{"grantable_roles": [...]}` from `attesting_operator`, `auditor`, `delegated_actor` (platform key) |
| PUT | `/v1/platform/tenants/{id}/owner` | Give a tenant to a provisioner, or take it back (platform key) |
| POST/GET | `/v1/provisioning/tenants` | Create / list the provisioner's own tenants (provisioning key) |
| DELETE | `/v1/provisioning/tenants/{id}` | Close a tenant and revoke its keys (provisioning key) |
| POST/GET | `/v1/provisioning/tenants/{id}/members` · `/api-keys` | Members and keys in an owned tenant (provisioning key) |
| DELETE | `/v1/provisioning/tenants/{id}/api-keys/{key_id}` | Revoke a key in an owned tenant (provisioning key) |

Provisioning keys are described in [provisioning.md](provisioning.md).

### Policies & decisions
| Method | Path | Purpose |
|--------|------|---------|
| POST/GET | `/v1/policies` | Create / list approval policies. The list leaves out retired policies unless you pass `include_retired=true`, and each entry carries its `status` |
| GET/PUT | `/v1/policies/{id}` | Read / update in place (PUT: `hitl:tenant:admin`, unpinned key, body `{definition, expected_version, name?}`) |
| GET | `/v1/policies/{id}/versions[/{n}]` | Immutable version history |
| POST | `/v1/policies/{id}/retire` | Retire a policy. Its creator (`hitl:policy:write`) or a tenant admin may do it. New decisions on it get `409`; decisions already open run to the end |
| POST | `/v1/decisions` | Request a decision (`idempotency_key` in the body is required) |
| GET | `/v1/decisions/{id}` | Fetch status + terminal outcome envelope. Does not return `context` or `proposed_action` |
| POST | `/v1/decisions/{id}/cancel` | Withdraw a pending decision. Revokes every unused approval link already emailed to reviewers (see below) |
| GET | `/v1/decisions/{id}/notifications` | Each email Futex queued for this decision: `kind`, `task_id`, `principal_id`, `state` (pending, sent, suppressed, obsolete or dead), `attempts`, `resend`, `queued_at`, `sent_at` and `mail_track_id` (see [Notification email](#notification-email)). Addresses, message content and links are not returned |
| POST | `/v1/decisions/{id}/notifications/resend` | Email the current reviewer of each open task again, with a new link. Needs `hitl:decision:cancel`. Answers `409` when the decision is closed, no task is open, the policy has notifications off, or the last email is still queued, and `429` with `Retry-After` within 5 minutes of the previous resend. Any earlier one-click link stops working when the new email is sent |
| GET | `/v1/inbox/tasks` | A reviewer's actionable tasks. `decision_id` narrows it to one decision. A `delegated_actor` key adds `on_behalf_of` to list a named person's tasks |
| POST | `/v1/tasks/{id}/actions` | Act on a task (approve, reject, …) |

**Cancel revokes the links reviewers already have.** Every unused approval link
emailed for the decision is revoked in the same transaction. A reviewer who
clicks one afterwards gets a `410` page saying when the decision was withdrawn.
The response reports how many were revoked:

```json
{"id": "dec_…", "status": "cancelled", "revoked_tokens": 1}
```

The optional body `{"reason": "…"}` (up to 1000 characters) is stored in the
`decision.cancelled` audit event together with the key id, the surface (`rest`
or `mcp`) and the request id. The terminal outcome names who withdrew it in
`outcome.terminated_by` (`actor_id`, `via`, `at`). A caller that can no longer
wait for the answer should let the decision expire, because cancelling also
takes the decision away from the reviewer.

### Delegations, webhooks, RunFlow, audit
| Method | Path | Purpose |
|--------|------|---------|
| POST/GET/DELETE | `/v1/delegations` · `/v1/delegations/{id}` | Manage OOO delegation rules |
| POST | `/v1/delegations/{id}/accept` | Delegate accepts a rule |
| POST/GET/DELETE | `/v1/webhooks` · `/v1/webhooks/{id}` | Manage webhook subscriptions |
| GET | `/v1/webhooks/deliveries` | Inspect deliveries. `state` defaults to `dead` |
| POST | `/v1/webhooks/deliveries/{id}/requeue` | Requeue a dead delivery |
| POST | `/v1/webhooks/{id}/enable` | Re-enable a subscription after an auto-disable |

> **Writing a webhook handler?** Read [docs/webhooks.md](webhooks.md) first. Your
> status code decides whether a failed delivery is retried or lost, and the two
> outcomes look identical from your side. `409` and `425` are **not** retried;
> return `503` if you need us to come back.
| POST/GET/DELETE | `/v1/runflow/bindings` · `/v1/runflow/bindings/{id}` | Bind decisions to RunFlow nodes |
| GET | `/v1/audit` | Query the audit trail |

### Action Web (human-facing, token-gated — not for programmatic use)
`GET/POST /a/t/{task}`, `/a/t/{task}/act`, `/a/t/{task}/otp`,
`GET/POST /a/click/{token}`, `GET /a/done`, `/a/expired`.

A refused link is **never a 200** (FTX-134). The page says why, and the status,
the `X-Futex-Refusal` header and the `data-refusal` attribute carry a code:

| code | HTTP | meaning |
|---|---|---|
| `invalid_token` | 403 | malformed, bad signature, wrong scope or binding |
| `expired` | 410 | the link's own expiry or the server-side expiry passed |
| `already_used` | 410 | one-click token already consumed |
| `superseded` | 410 | revoked — a newer email replaced it, or the decision ended |
| `not_actionable` | 409 | the task is already decided / expired / cancelled |
| `justification_required` | 403 | policy needs a written justification; use the review page |
| `session_expired` / `csrf_failed` | 403 | the confirm POST lost its session; reopen the link |

Every refusal writes a log line (`action_web refused … code=… task=…`, never
the token) and, when the token itself verified, an audit event
`one_click.refused` on the task — visible through `GET /v1/audit?entity_id=tsk_…`.

## Action vocabulary

`POST /v1/tasks/{id}/actions` (and the MCP `hitl_act_on_task`) accept:

| Type | Completing? | Notes |
|------|-------------|-------|
| `approve` | yes | Counts toward quorum. |
| `reject` | yes | Requires a reason; terminalizes the stage. |
| `request_changes` | yes | Returns `feedback_for_agent`; terminal or hold per policy. |
| `amend_and_approve` | yes | Approve with `amendments` (JSON pointer to value) on pointers the policy allowlists. Last stage only. The original `context_hash` does not change. The outcome carries `amendments` and `effective_context_hash`. The review page offers it as "Approve with these answers" when the policy allows amendments. |
| `escalate` | no | Advance the escalation path. |
| `delegate_task` | no | Reroute to another member (SoD-checked, depth-capped). |
| `abstain` | no | Recuse; does not count as approval. |
| `request_clearance` | no | Trigger a further-clearance profile. |

## Creating a decision

`POST /v1/decisions` takes a JSON body. These fields are required:

| Field | Type | Notes |
|---|---|---|
| `policy_id` | string | The policy's id, which starts with `pol_`. Get it from `POST /v1/policies` or `GET /v1/policies`. A policy's name is not accepted here. |
| `idempotency_key` | string | Goes in the body. A request that sends it only as an `Idempotency-Key` header gets `422`, because Futex does not read that header. |
| `title` | string | One line the reviewer sees first. |
| `proposed_action` | object | What the reviewer is approving. A string or a list in its place gets `422`. |
| `context` | object | Supporting detail. Send `{}` if you have none. |

`summary` is optional and is shown to the reviewer above the details. For expiry, send `expires_in_hours`
(1 to 8760) or `expires_in_minutes` (1 to 525600), but not both. A value outside those ranges gets `422`
naming the field. Without either, a decision expires after 72 hours.

`GET /v1/decisions/{id}` does not return `context` or `proposed_action`. To confirm a decision is about
the payload you sent, recompute `context_hash` as described below and compare it with the one Futex
returns.

## Reason codes

`reject` and `request_changes` need a `reason_code` and a `reason_text`. When the policy lists
`reason_codes`, the code must be one of them or `OTHER`, and any other code gets `422` listing the
accepted ones. Because `OTHER` is always accepted, a reviewer can reject on a policy with an empty list.
`hitl_list_reason_codes` returns the accepted set, including `OTHER`.

## Retries and idempotency_key

`idempotency_key` is a body field, scoped to your tenant and your key's principal.
Sending the same key again with the **same** request returns the original decision
with 200, in exactly the shape the create returned. Sending it with a **different**
request returns `409` with `error.code = "idempotency_key_reused"` and
`error.details = {decision_id, mismatched_fields}`; the compared fields are
`policy_id`, `title`, `summary` (a missing summary equals the title), `proposed_action`,
`context`, `webhook_url`, `runflow_binding_id`, `on_behalf_of` and `requester`. Expiry inputs are not
compared. Numbers compare exactly: a retry of the same JSON is never a conflict. Derive
the key from the request you are sending, so a changed request carries a new key.

## Verifying what was approved: context_hash

`context_hash` is not opaque and is not ours alone — it is a plain digest of what
the caller supplied, so any caller can recompute it:

```python
canonical = json.dumps(
    {"context": context, "proposed_action": proposed_action, "policy_version": policy_version},
    sort_keys=True,
)
context_hash = "sha256:" + hashlib.sha256(canonical.encode()).hexdigest()
```

`policy_version` comes back on `GET /v1/decisions/{id}`; `context` and
`proposed_action` are what you sent.

**The separators are part of the contract.** That `json.dumps` uses Python's
DEFAULT separators — `", "` and `": "`, with the spaces — not the compact
`(",", ":")` most codebases standardise on, and not another language's default
spacing. Serialise it compactly and you get a different digest for identical
data, silently, and only for decisions you did not raise yourself — which is the
exact case the binding exists for. An adopter hit this within a day of the recipe
being published; pin it with a test that asserts the compact form differs, so a
future tidy-up fails loudly instead of quietly unbinding every foreign approval. Compare it before you act on an approval,
and you are binding the decision to the exact request it approved rather than to
its id. That matters most for a decision id you did not raise in the process
doing the acting.

## Naming the human requester (`requester`)

`on_behalf_of` is display text and binds nothing. When your one service key raises
decisions for many people, send `requester` (the requesting human's principal id)
instead, from a key whose principal holds the `attesting_operator` role
(`hitl:decision:attest_requester`; granted by the Futex operator, not by tenant
admins). Futex then:

- applies `sod_rules.submitter_cannot_act` to the requester as well as to your key:
  they get no task, cannot be delegated or reassigned one, and are refused if they act;
- compares ids case-insensitively and with surrounding spaces trimmed, and stores the
  lower-cased form;
- refuses with `422 requester_is_assignee` (with `details.steps`) when removing the
  requester would leave a step without enough approvers, so a requester can neither
  starve a step nor pick who reviews it;
- returns `403 attestation_not_permitted` if your key lacks the permission, including
  on a retry;
- shows `requester` on `GET /v1/decisions/{id}` and in the outcome envelope, and
  includes it in the idempotency comparison.

## Acting for a signed-in human (`on_behalf_of` on a task action)

A platform that authenticates its own users and wants them to approve from its own
UI can post the action for them: `POST /v1/tasks/{id}/actions` with
`"on_behalf_of": "<the human's principal id>"`. This needs a key whose principal
holds the `delegated_actor` role (`hitl:task:act_on_behalf`), which only the Futex
operator grants. Futex then:

- treats the named human as the actor for every check: they must be the task's
  assignee (or its delegate), and SoD, step-up and reason rules apply to them;
- records them as `actor_principal_id` and records your key's principal as
  `acting_service` on the action, the audit event, the `task.completed` webhook and
  the outcome envelope's `actors`;
- refuses with `403 service_cannot_act_on_own_submission` when the acting key's
  principal raised the decision, so raising and approving always use different keys;
- refuses with `403 act_on_behalf_not_permitted` when your key lacks the permission,
  and with `422 invalid_on_behalf_of` for an empty, non-string, over-254-character or
  self-naming value.

The id is matched exactly against the assignee as written in the policy. Authenticating
the human is your responsibility; Futex trusts the key that names them.

To find the person's tasks, call `GET /v1/inbox/tasks?on_behalf_of=<id>` with the same key,
or subscribe to `task.assigned`, whose `data` carries `decision_id` and `assignee`. Use a
policy with `"notifications": "none"` when people approve only in your screens, and leave
`require_step_up` and `allow_one_click_approve` off, because both mail the assignee.

## If you multiplex your own customers into one Futex tenant

Read this if one Futex tenant serves many of YOUR customers, which is the usual
shape for a platform adopter.

Futex isolates **tenants**, not the customers you put inside one. A decision id
belonging to another of your customers is, to Futex, an id inside your own
tenant, and an unpinned key of yours may read and cancel it. A key with a
`policy_allowlist` reaches only decisions and tasks raised under its pinned
policies, through REST and MCP. Anything else answers `404`, the same answer as
an id that exists nowhere. A pinned key gets `403` on the routes that cover the
whole tenant: webhooks, webhook deliveries, the audit trail and RunFlow
bindings. Use an unpinned key for those. Because webhook subscriptions and audit
reads still cover every decision in the tenant, a pin does not separate your
customers from each other.

Two consequences, both reported from production integrations:

- **Bind before you read the status.** Check that the decision belongs to the
  customer you are acting for — compare `context_hash`, or at minimum a
  `tenant_id`/customer field you put in `context` — and refuse a foreign
  decision as unrelated *before* looking at whether it was approved.
- **A refusal message is part of the authorisation surface.** "decision X is
  rejected, not approved" hands the caller the state of a decision it may have
  guessed rather than raised. Refuse with nothing about the decision in it.

If you want the separation enforced by Futex instead, that is one Futex tenant
per customer of yours, with its own keys and policies.

## Writing a policy definition

`POST /v1/policies` takes `{name, definition}`. **Every control lives at
DEFINITION level. A step carries only its own six fields.** Getting that
backwards is the single most common integration mistake, and until FTX-142 it
was silent — a misnested control was accepted with `200` and discarded.

| Level | Fields |
|-------|--------|
| `definition` | `stages`, `reason_codes`, `require_reason_on_reject`, `require_justification_on_approve`, `sod_rules`, `delegation_allowed`, `max_delegation_depth`, `allow_one_click_approve`, `require_step_up`, `expiration_action`, `on_request_changes`, `default_sla`, `escalation_path`, `notifications`, `clearance`, `amendments` |
| `stages[]` | `name`, `steps` |
| `steps[]` | `name`, `mode`, `assignees`, `n_required`, `sla`, `reject_is_terminal` — **and nothing else** |

Any other key, at any level, is a `422` naming the offending field. That is
deliberate: several definition defaults are more permissive than what an author
who bothers to set them intends (`delegation_allowed` defaults to `true`), so a
silently-ignored control opens a gate rather than closing one.

`allow_one_click_approve: true` combined with `require_step_up: true` or
`require_justification_on_approve: true` is also a `422` (FTX-196). A click
carries no second factor and no text, so Futex would never send the link.

### reject_is_terminal

An `all_of` step ends as rejected on the first reject. An `any_of` or `n_of_m` step normally stays open after a
reject while enough assignees remain to reach the quorum. Set `"reject_is_terminal": true` on the step when one
reject should end the decision as `rejected` and cancel the other assignees' tasks. It takes a boolean and
defaults to `false`.

### require_step_up

`require_step_up: true` binds **every** path that records an action — it is
enforced in the domain layer, not in any one surface.

| Path | Behaviour |
|------|-----------|
| Emailed review page | Sends a code to the assignee, then asks for it. |
| `POST /v1/tasks/{id}/actions` | Two-call handshake, below. |
| One-click token | Never minted for a step-up policy; refused at consume time if an older token still exists. |
| Any future surface | Refused by default until it explicitly reports a verified challenge. |

Over REST:

1. `POST /v1/tasks/{id}/actions` with your action and **no** `otp` field →
   `401`, body `step_up_required`. A six-digit code is mailed to the **task's
   assignee** — never returned to the caller, which is what makes it a second
   factor rather than a formality.
2. Resubmit the same action with `"otp": "<code>"` → the action is recorded.

Codes are single-use, hashed at rest, TTL-bounded (`STEP_UP_OTP_TTL_SECONDS`,
default 600s) and locked out after `OTP_MAX_ATTEMPTS` wrong tries. A wrong or
expired code is `401 step_up_failed`. Nothing is recorded on either refusal.

Before FTX-141 this flag was read only by the emailed review page, so a policy
author could set it on a capital-affecting gate and get no second factor over
the API or via one-click. If you carried a note that step-up was email-only,
it is now out of date.

### notifications

`notifications` chooses the delivery channel for every email a decision on this
policy would send — assignment, reassignment, reminder, escalation.

| Value | Effect |
|---|---|
| `email` (default) | Normal behaviour. |
| `none` | Nothing is mailed. Tasks, audit events, webhooks, expiry and cancellation are unchanged; each queued notification is stored `suppressed` and audited as `notification.suppressed`. |

Use `none` for a test or probe policy, so exercising your approval path cannot
reach a person's inbox. The tasks still exist and still expire, so a probe should
cancel what it creates (`POST /v1/decisions/{id}/cancel`) rather than leave them
to time out. `require_step_up` is not covered: an OTP is mailed when a reviewer
actually acts, which a `none` policy is not expecting anyone to do.

### Notification email

In `GET /v1/decisions/{id}/notifications`, state `sent` means mail-api accepted the
message. `attempts` is the number of failed tries, which is 0 when mail-api accepted the
message first time. `mail_track_id` is mail-api's track id for the message, null for mail
sent before 20 Nov 2026. mail-api's `GET /api/v1/emails/{track_id}/events` shows what
happened after acceptance, including the receiving server's SMTP reply.

### Reminders when a task is not answered

A task whose step has an `sla` (or the definition's `default_sla`) and **no**
`escalation_path` entry left gets a bounded series of default reminders to its
assignee: `DEFAULT_REMINDER_MAX` of them (3), spaced by
`DEFAULT_REMINDER_BACKOFF_HOURS` (1 h, then 4 h). After the last one the task's
SLA deadline is cleared and `escalation.exhausted` is audited; the decision still
expires on its own clock. A configured `escalation_path` is executed exactly as
written and is not capped.

### escalation_path

Each entry is `{after, action, target}`. `action` is one of `remind`, `notify_manager`,
`reassign`, `escalate_up`, `terminal`.

- **Timing.** The first entry fires when the step's `sla` (or `default_sla`) runs out;
  its own `after` is ignored. Every later entry fires `after` the previous hop, so
  `after` is required from the second entry on.
- **Targets are literal principal ids.** An email-shaped id is mailed directly; a bare
  id is mailed at the deployment's local mail domain. Futex has no directory and never
  resolves a role word such as `manager`, `lead` or `role:manager`.
- `reassign` and `notify_manager` need a `target`; `remind` (which always reminds the
  current assignee) and `terminal` take none; `escalate_up` mails `target` if given,
  else the assignee.
- `reassign` obeys `delegation_allowed` and `sod_rules` like a manual delegation.

### sod_rules

`sod_rules` is a free-form dict, so it is validated against the rules the engine
actually implements. Exactly two exist:

| Rule | Enforced where |
|------|----------------|
| `submitter_cannot_act` | assignment (`steps.py`), action time (`actions.py`, `403`), delegation targets (`engine.py`) |
| `mutually_exclusive_principals` | action time, against prior actors |

Anything else is a `422`. There is no `submitter_cannot_approve` — a plausible
name that no code reads. Stored, it would be an inert control that survives any
read-back checking only whether `sod_rules` is present.

### Verify what you stored

`POST /v1/policies` returns the **stored** definition alongside the id, so you
can diff intent against effect without a second request.

To change a policy, `PUT /v1/policies/{id}` with `{definition, expected_version}`
as a tenant admin on an unpinned key. The id stays, so keys pinned to it keep
working; the version goes up by one, a stale `expected_version` is a `409
version_conflict`, every version stays readable at `/v1/policies/{id}/versions/{n}`,
and the change is audited (`policy.updated`, with before/after definition hashes)
and sent as the `policy.updated` webhook. A decision already raised keeps the
definition it was raised under. Creating a new policy and repointing `policy_id`
still works when you want a separate policy.

Two things about that diff, if you automate it:

- The stored definition is a **superset** of what you sent. Every schema field
  is persisted, including ones you omitted, so a field you never set comes back
  at its default. Assert `stored[field] == sent[field]` for your fields, and pin
  the extras you expect exactly — never "ignore extra keys", which is precisely
  the check that misses an inert control.
- Compare **values**, not key presence.

## MCP tools

MCP is served over **Streamable HTTP** at `https://futex.rodmena.co.uk/mcp/`
with per-request bearer auth. Ten tools, scoped to the caller's permissions:

| Tool | Does |
|------|------|
| `hitl_list_policies` | List approval policies available to the caller. |
| `hitl_get_policy` | Fetch one policy's definition. |
| `hitl_list_reason_codes` | Reason codes valid for reject / request_changes. |
| `hitl_request_decision` | Create a decision (non-blocking). |
| `hitl_get_decision` | Poll status + outcome envelope. |
| `hitl_cancel_decision` | Cancel a pending decision. |
| `hitl_submit_context_update` | Attach additional context to a live decision. |
| `hitl_list_inbox` | A reviewer's actionable tasks. |
| `hitl_get_task` | Fetch one task. |
| `hitl_act_on_task` | Approve / reject / request_changes / amend / escalate / delegate / abstain. |

Register it with:

```bash
claude mcp add --transport http --scope user futex-hitl \
  https://futex.rodmena.co.uk/mcp/ \
  --header "Authorization: Bearer <YOUR_FUTEX_API_KEY>"
```

## The one pattern to remember

Request → **poll `hitl_get_decision`** (or receive a webhook) → proceed **only
if** the terminal status is `approved`. Creation never blocks and never means
"approved".
