# AI Gateway REST API

URL: https://www.elchi.io/docs/ai-gateway/reference/rest-api

> Every /api/v3/ai-gateway endpoint of the Elchi controller, with its parameters, answers, status codes, roles and concurrency rules, and an example per group.

Everything the **AI Gateway** page does goes through these endpoints on the Elchi controller, under `/api/v3/ai-gateway`. This page lists each of them. The configuration fields inside the bodies (providers, gateways, consumers, MCP servers, the sensitive-data policy) are described on their own pages; this page links to them.

## Calling the API

**Authentication.** Every request carries a session token: `Authorization: Bearer <token>`. Get one with your Elchi user:

```bash
ELCHI=https://elchi.example.com
TOKEN=$(curl -s -X POST "$ELCHI/auth/login" \
  -H 'Content-Type: application/json' \
  -d '{"username":"admin","password":"..."}' | jq -r .token)
PROJECT=<project-id>
```

Each login starts a new session for that user.

**Project.** Every endpoint is project-scoped. Reads take `?project=<id>`. Writes take `"project"` in the JSON body (deletes take `?project=`). A missing project is `400 project is required`. A project you are not a member of is `403`. Owners pass every project check.

**Roles.**

| Role | Can |
|---|---|
| Any member of the project | Read providers (masked), gateways, consumers, MCP servers, listeners, generated resources, MCP readiness, the sensitive-data policy, usage, the usage summary, provider status |
| **Owner** or **Admin** (and a member) | Everything else: every change, Sync, removal, the provider tools, MCP discovery, edge status and files, the request log, the decision log, the MCP call log |

A member who is not Owner or Admin gets `403 {"message":"only Admin and Owner can manage the AI gateway"}` on those.

**Answers.** Success is `200` with `{"data": …}`. Errors are `{"message": "…"}`:

| Status | When |
|---|---|
| `400` | An unreadable body, or a configuration the gateway would reject. The message names every problem. |
| `403` | Not a member of the project, or not Owner/Admin |
| `404` | No such gateway, consumer, key, MCP server, listener or request. Also `configure the project's AI gateway providers first`: a gateway, consumer or MCP server written before the project has providers. |
| `409` | A concurrent change, a name already used, or something still in use (see [Concurrency](#concurrency)) |
| `502` | A provider, MCP server or ClickHouse could not be read |
| `503` | `AI gateway is disabled: ELCHI_JWT_SECRET is empty`; `clickhouse not configured; …` on the log endpoints; `shield events temporarily busy; retry shortly` when 16 log queries already run on the controller |

### What a write answers

Every change that the edges must get (providers, gateways, consumers, keys, MCP servers, the sensitive-data policy, removal) queues a deploy. Its answer carries the result of that and any configuration warnings:

```json
{
  "data": { "...": "the saved entity" },
  "deploy": { "enqueued": true, "deploy_job": "6752b0…" },
  "warnings": ["gateway chat: …"]
}
```

| `deploy` | Meaning |
|---|---|
| `{"enqueued": true, "deploy_job": "<id>"}` | A deploy job was queued. Follow it under **Administration → Jobs**. |
| `{"enqueued": true, "deduped": true, "message": "…"}` | A deploy for the project was already queued. It reads the store when it runs, so it carries this change too. |
| `{"enqueued": false, "error": "…"}` | The change is saved, but no deploy was queued. Run **Sync**. |

The save succeeds whatever the deploy does. The deploy job records which edges applied the new version.

### Concurrency

Every write to the project's AI gateway configuration claims the configuration's revision and holds a short write lock. Two writers never both land on a stale set: the second gets `409 ai gateway configuration changed since it was loaded; reload it`.

`expected_version` on a named entity (provider document, gateway, consumer, MCP server, sensitive-data policy):

| `expected_version` | Entity exists | Entity does not exist |
|---|---|---|
| `0` (or omitted) | Updated, no version check | Created |
| `N > 0` | Updated only if its version is `N`, else `409` | `404` |

`"create": true` (gateways, consumers, MCP servers) creates only. If the name is already used, the answer is `409 the name is already used: open that one to change it, or choose another name`. The UI's create forms send it.

Listeners use `expected_revision` the same way: `0` = any, otherwise a stale revision is `409`.

## Providers

| Method | Path | Body / query | Answer | Role |
|---|---|---|---|---|
| `GET` | `/providers` | `?project=` | `{providers, limits, capture_recipient, upstreams, effective_upstreams, pricing, version, updated_at, updated_by, warnings?}`. Every set secret reads `***REDACTED***`. `404` when the project has no providers. | member |
| `PUT` | `/providers` | `{project, providers[], limits[], upstreams{}, pricing[], expected_version}` | The saved document (masked) + `deploy` | Owner/Admin |
| `GET` | `/providers/:name/models` | `?project=` | `{"data": ["model-id", …]}`: the provider's own model list, asked with the stored credential | Owner/Admin |
| `POST` | `/providers/:name/check` | `{project}` | `{ok, reachable, status, message, models, latency_ms}`: asks the model list (no tokens spent) | Owner/Admin |
| `POST` | `/providers/:name/try` | `{project, model}` | `{ok, status, message}`: one short answer from that model (spends a few tokens) | Owner/Admin |
| `GET` | `/provider-health` | `?project=` | Per provider: `{provider, status, window_minutes, answers, ok, failures, by_class, last_seen, last_ok, last_failure}` over the last 15 minutes, plus `window_minutes: 15` | member |

`PUT /providers` **replaces** the whole providers document: the providers, the spec-wide limits, the per-provider upstreams and the price table. To keep a stored secret, send back the masked value `***REDACTED***`. It is kept only while the provider's endpoint, type, path and API version stay the same. A sentinel with nothing to keep (a new or renamed provider) is `400`. The first `PUT` of a project also creates its request-log key pair. See [Providers](https://www.elchi.io/docs/ai-gateway/providers) and [Quotas, Limits and Costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs).

`/models` and `/try` work for OpenAI-compatible and Anthropic providers. Other types answer `400` (`… providers publish no model list here; type the model names`). A provider that cannot be reached answers `502`.

```bash
curl -s "$ELCHI/api/v3/ai-gateway/providers?project=$PROJECT" -H "Authorization: Bearer $TOKEN" | jq .data.version

curl -s -X PUT "$ELCHI/api/v3/ai-gateway/providers" -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{
    "project": "'"$PROJECT"'",
    "expected_version": 3,
    "providers": [
      {"name": "openai", "type": "openai", "credentials": {"apiKey": "***REDACTED***"}}
    ],
    "pricing": []
  }'
```

## Gateways

| Method | Path | Body / query | Answer | Role |
|---|---|---|---|---|
| `GET` | `/gateways` | `?project=` | Every gateway | member |
| `GET` | `/gateways/:name` | `?project=` | One gateway, `404` if none | member |
| `PUT` | `/gateways/:name` | `{project, gateway, expected_version, create?}` | The saved gateway + `deploy` | Owner/Admin |
| `DELETE` | `/gateways/:name` | `?project=` | `{message: "deleted"}` + `deploy` | Owner/Admin |

The whole project's configuration is validated with the change applied: hosts unique across gateways, every model's provider configured, and what the listeners serving the gateway need. A gateway's `name` in the body must equal the path's (`400` otherwise; it is filled in when empty). Deleting a gateway that a listener serves is `409 … is served by listener <l>: take it off first`. If a consumer still names it, the set is invalid (`400`). See [Gateways and Models](https://www.elchi.io/docs/ai-gateway/gateways-and-models).

```bash
curl -s -X PUT "$ELCHI/api/v3/ai-gateway/gateways/chat" -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{
    "project": "'"$PROJECT"'",
    "create": true,
    "gateway": {
      "name": "chat",
      "hosts": ["llm.example.com"],
      "requireKey": true,
      "models": [{"model": "gpt-4o-mini", "provider": "openai"}]
    }
  }'
```

## Consumers and keys

| Method | Path | Body / query | Answer | Role |
|---|---|---|---|---|
| `GET` | `/consumers` | `?project=` | Every consumer; keys by `id` and `prefix` only | member |
| `GET` | `/consumers/:name` | `?project=` | One consumer | member |
| `PUT` | `/consumers/:name` | `{project, consumer, expected_version, create?}` | The saved consumer + `deploy` | Owner/Admin |
| `DELETE` | `/consumers/:name` | `?project=` | `{message: "deleted"}` + `deploy`. Every key of the consumer goes with it. | Owner/Admin |
| `POST` | `/consumers/:name/keys` | `{project}` | `{id, prefix, created_at, created_by, key}`: **the only time the key is shown** | Owner/Admin |
| `DELETE` | `/consumers/:name/keys/:key_id` | `?project=` | `{message: "revoked"}` + `deploy` | Owner/Admin |

`consumer` holds the allowlists (`gateways`, `providers`, `models`), `quota`, `disabled` and `mcp` grants. Keys in the body are ignored: they change only through the key endpoints. The store keeps only each key's SHA-256 hash. A revoked or deleted key gets `401 invalid_api_key` on the edges once the deploy has applied. See [Consumers and Keys](https://www.elchi.io/docs/ai-gateway/consumers-and-keys).

```bash
curl -s -X PUT "$ELCHI/api/v3/ai-gateway/consumers/team-a" -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{
    "project": "'"$PROJECT"'", "create": true,
    "consumer": {"name": "team-a", "gateways": ["chat"], "quota": {"requestsPerDay": 1000}}
  }'

curl -s -X POST "$ELCHI/api/v3/ai-gateway/consumers/team-a/keys" -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{"project": "'"$PROJECT"'"}' | jq -r .data.key
# sk-elchi-...   (store it now: it is never shown again)
```

## MCP servers

| Method | Path | Body / query | Answer | Role |
|---|---|---|---|---|
| `GET` | `/mcp-servers` | `?project=` | Every MCP server, credentials masked | member |
| `GET` | `/mcp-servers/:name` | `?project=` | One server | member |
| `PUT` | `/mcp-servers/:name` | `{project, server, url, credential?, expected_version, create?}` | The saved server + `deploy` | Owner/Admin |
| `DELETE` | `/mcp-servers/:name` | `?project=` | `{message: "deleted"}` + `deploy`. `409` while a gateway serves it or a consumer is granted it (`… is used by …: take it off first`). | Owner/Admin |
| `POST` | `/mcp-servers/:name/discover` | `{project, personal_token?}` | The server's tools, asked from the controller. The personal token is used for this one call and never stored. A server that cannot be reached or answers an error is `502` with its message. | Owner/Admin |
| `GET` | `/mcp-readiness` | `?project=` | `{ready, holding[], min_version}`: the client ids whose AI gateway is older than `min_version` (`v0.4.0`). While `holding` is not empty, no listener serves `/mcp`. | member |
| `GET` | `/mcp-calls` | `?project=&from=&to=[&gateway=&consumer=&server=&tool=&class=&limit=&offset=]` | The MCP call log, newest first, and per-tool calls, errors and p95 for the window. `limit` 1–500, default 50. | Owner/Admin |

`server` is what the edges get (`personalToken`, `personalTokenHeader`, `tools`). `url` and `credential` (`{header, prefix, value}`) stay in the control plane and Envoy. A credential sent without a value keeps the stored one, for the same URL only. URL rules: `https://` (or `http://` for a trusted network), no user info, no query or fragment, and not a port of the edge itself. See [MCP Servers](https://www.elchi.io/docs/ai-gateway/mcp/servers).

## Sensitive-data policy

| Method | Path | Body / query | Answer | Role |
|---|---|---|---|---|
| `GET` | `/sensitive` | `?project=` | `{policy, version, types, likelihoods}`. `policy` is `null` when there is none. `types` is the catalog the edges detect. | member |
| `PUT` | `/sensitive` | `{project, policy, expected_version}` | `{policy, version}` + `deploy`. `policy: null` removes it. | Owner/Admin |
| `POST` | `/sensitive/test` | `{project, gateway?, policy?, text}` | Types, likelihoods, reasons and offsets into `text`, never a value. `gateway` applies its override; `policy` tries a draft. The sample is neither logged nor audited. | Owner/Admin |

`expected_version` here is the providers document's `version`: the policy is stored in it. See [Sensitive Data](https://www.elchi.io/docs/ai-gateway/sensitive-data).

## Listeners

| Method | Path | Body / query | Answer | Role |
|---|---|---|---|---|
| `GET` | `/listeners` | `?project=` | `{data: [listeners], leftovers: [{name, version, id}]}`. Leftovers are AI HCMs no listener uses any more. | member |
| `GET` | `/listeners/:name` | `?project=` | One listener | member |
| `POST` | `/listeners` | `{project, name, version, https?: {port, tls_context}, http?: {port, mode}, gateways[], default?}` | `{listener, hcm, redirect_hcm?, tls?, route, version, config, warnings?}`. Creates the listener, its HCM(s), its route and the managed listener with its bootstrap and service. **Does not deploy.** | Owner/Admin |
| `PUT` | `/listeners/:name` | `{project, expected_revision, https?, http?, gateways[], default?}` | The updated listener. Ports, TLS and HTTP mode are published to the clients it runs on, without a restart. Gateways and default change its route. | Owner/Admin |
| `DELETE` | `/listeners/:name` | `?project=&version=` | `{message: "removed"}`. Only while undeployed (`409 the listener is deployed: undeploy it from its clients first`). Its HCMs and route go with it. | Owner/Admin |

Field rules: `name` is lowercase letters, digits and `-` (at most 48), not ending in `-mcp` or `-redirect`. `version` is one of the controller's Envoy versions. At least one of `https` and `http` is required. Ports are 1–65535, never `10088`. `https.tls_context` names a Downstream TLS context you made for that Envoy version. `http.mode` is `serve` (default) or `redirect` (308 to the HTTPS port). `default` must be one of `gateways`. A name already used is `409`. See [Listeners](https://www.elchi.io/docs/ai-gateway/listeners).

```bash
curl -s -X POST "$ELCHI/api/v3/ai-gateway/listeners" -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{
    "project": "'"$PROJECT"'",
    "name": "ai-public",
    "version": "v1.40.2",
    "https": {"port": 443, "tls_context": "llm-example-com"},
    "http": {"port": 80, "mode": "redirect"},
    "gateways": ["chat"],
    "default": "chat"
  }'
```

## Deploy, edges and removal

| Method | Path | Body / query | Answer | Role |
|---|---|---|---|---|
| `POST` | `/sync` | `{project}` | `{data: deploy}`: pushes the project's configuration to its connected edges again | Owner/Admin |
| `GET` | `/status` | `?project=&client_id=` | The edge's gateway service state, applied configuration version, extproc version and logs, plus `desired_version`: what the project's edges should run. An edge reporting another version missed a deploy. | Owner/Admin |
| `GET` | `/files` | `?project=&client_id=` | The edge's conf.d files: path, sha256, mode | Owner/Admin |
| `GET` | `/resources` | `?project=` | Per Envoy version: the defaults the AI gateway needs and what its deploys generated | member |
| `DELETE` | `""` (i.e. `/api/v3/ai-gateway`) | `?project=[&shred=true]` | `{message: "removed", shredded, leftovers_error?}` + `deploy` | Owner/Admin |

`/status` and `/files` send a command to the edge. Without `client_id` they answer `400 client_id is required`. A client that is not a connected client of this project answers `404 client not found in this project (or not connected): <id>`. Answers are never cached by the browser.

**Removal.** `DELETE /api/v3/ai-gateway` is refused with `409` and a `dependents` list while an HCM uses the AI gateway (an AI listener, or an HCM with the AI gateway toggle on). Remove those listeners first. It is also `409` while a deploy or listener change of the project holds the lease for more than two minutes. Otherwise:

- providers, gateways, consumers and every key are deleted;
- every edge gets an empty configuration, so the provider credentials leave the edges (an offline edge gets it when it connects);
- the generated Envoy resources are removed;
- usage history stays.

The request-log key is kept, so captured content stays readable. With `shred=true` every request-log key of the project is destroyed, and captured content can never be read again.

```bash
curl -s -X POST "$ELCHI/api/v3/ai-gateway/sync" -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{"project": "'"$PROJECT"'"}'

curl -s "$ELCHI/api/v3/ai-gateway/status?project=$PROJECT&client_id=<client-id>" \
  -H "Authorization: Bearer $TOKEN" | jq '{desired_version, data}'
```

## Usage, logs and decisions

All of these read ClickHouse (`503` when the controller has none). `from` and `to` are RFC 3339 times. The defaults are the last 24 hours. The window may be at most 90 days, and `from` must be before `to`.

| Method | Path | Query | Answer | Role |
|---|---|---|---|---|
| `GET` | `/usage` | `project, from, to, [gateway, provider, model, consumer], group_by, bucket_seconds` | Request and token totals with cost and unpriced tokens. With `bucket_seconds` (≥ 60) it is a time series. | member |
| `GET` | `/usage/summary` | `project, from, to, [gateway, provider, model, consumer, bucket_seconds, period]` | The window and the one before it (same length): usage, the request log's error rate and latency percentiles, the decision log's denials and sensitive-data findings, a series, and the top 10 by model, provider, consumer and gateway. `period=today\|week\|month` takes a UTC calendar period instead of `from`/`to`. | member |
| `GET` | `/requests` | `project, from, to, [gateway, model, status, consumer, search, limit, offset]` | Request-log metadata, newest first, and `total`. `search` matches a request, trace, response or session id. `limit` default 50, at most 500. | Owner/Admin |
| `GET` | `/requests/:trace_id/:span_id` | `project` | One request. If content was captured, it is decrypted into `content`, or `content_error` explains why it is unreadable (its key was shredded). Each content view is audited. | Owner/Admin |
| `DELETE` | `/requests` | `project`, and at least one of `session_id, request_id, trace_id, gateway, before` (RFC 3339), or `all=true` | `{message: "erased"}`. Erased rows vanish from reads at once. No selector is `400`. | Owner/Admin |
| `GET` | `/decisions` | `project, from, to, [gateway, consumer, result=denied\|flagged, type, phase, sensitive=1, limit, offset]` | The authorization's denials and flagged requests: types and counts, never values. `limit` 1–500, default 50. | Owner/Admin |

`group_by` is one of `gateway`, `provider`, `model`, `instance`, `consumer`, or empty for one total; anything else is `400`. A window with too many parts at the chosen bucket size is `400` (`… use a larger bucket, a narrower window or a filter`). See [Usage and Costs](https://www.elchi.io/docs/ai-gateway/usage-and-costs) and [Request Log](https://www.elchi.io/docs/ai-gateway/request-log).

```bash
curl -s "$ELCHI/api/v3/ai-gateway/usage?project=$PROJECT&group_by=consumer&from=2026-12-01T00:00:00Z&to=2026-12-05T00:00:00Z" \
  -H "Authorization: Bearer $TOKEN" | jq '.data[] | {key, requests, cost}'

curl -s -X DELETE "$ELCHI/api/v3/ai-gateway/requests?project=$PROJECT&session_id=<session-id>" \
  -H "Authorization: Bearer $TOKEN"
```

## Audit

Every change is written to the audit log (**Administration → Audit**) with an action name and never with its body. The action names are `UPDATE_AI_GATEWAY_PROVIDERS`, `PUT_AI_GATEWAY`, `DELETE_AI_GATEWAY`, `PUT_AI_GATEWAY_CONSUMER`, `DELETE_AI_GATEWAY_CONSUMER`, `CREATE_AI_GATEWAY_KEY`, `REVOKE_AI_GATEWAY_KEY`, `PUT_AI_GATEWAY_MCP_SERVER`, `DELETE_AI_GATEWAY_MCP_SERVER`, `UPDATE_AI_GATEWAY_SENSITIVE`, `SYNC_AI_GATEWAY`, `REMOVE_AI_GATEWAY` / `REMOVE_AI_GATEWAY_SHRED`, `ERASE_AI_GATEWAY_REQUESTS`, `VIEW_AI_GATEWAY_REQUEST_CONTENT`, and `create_listener` / `update_listener` / `remove_listener`.
