# auth.md

You are an agent. KYBGate (https://kybgate.com) supports **agentic registration**
([auth.md protocol](https://github.com/workos/auth.md)): discover → register → claim (the user
confirms a code) → get an access token → call the API → refresh or revoke. Follow the steps in order.
If the user already gave you an API key (`kg_live_…`), skip to Step 5.

**MCP clients** (Claude, ChatGPT connectors, IDE agents) use standard **OAuth 2.1** instead: see
[MCP and OAuth](#mcp-and-oauth-authorization-code--pkce) below.

## Step 1 — Discover

A `401` from the API points here:

```http
WWW-Authenticate: Bearer realm="kybgate", resource_metadata="https://kybgate.com/.well-known/oauth-protected-resource"
```

- `GET https://kybgate.com/.well-known/oauth-protected-resource`: resource `https://kybgate.com/api/v1/`,
  scopes, authorization server `https://kybgate.com/`.
- `GET https://kybgate.com/.well-known/oauth-authorization-server`: `token_endpoint`
  (`/oauth2/token`), `revocation_endpoint` (`/oauth2/revoke`), and `agent_auth.identity_endpoint`
  (`/agent/identity`), `agent_auth.claim_endpoint` (`/agent/identity/claim`),
  `agent_auth.identity_types_supported` = `anonymous`, `service_auth`.

Open without any credentials: `GET /api/v1/jurisdictions`, `GET /api/v1/openapi.yaml`, `GET /readyz`.

## Step 2 — Pick a method

1. **You know the user's email** → `service_auth`. Best: the code comes back at once.
2. **You don't** → `anonymous`, then ask the user for their email in Step 4.

`identity_assertion` (ID-JAG) is not enabled yet (`issuer_not_enabled`).

KYBGate grants **nothing before the user claims you** (every data call spends registry quota), so
there are no pre-claim scopes and no pre-claim token.

## Step 3 — Register

```http
POST https://kybgate.com/agent/identity
Content-Type: application/json

{ "type": "service_auth", "login_hint": "user@example.com",
  "agent_name": "Your agent's name", "scope": "reports:read graph:read" }
```

- `agent_name` is shown to the user and becomes the key name ("Agent: …"). Use your real name.
- `scope` (space-separated) defaults to `reports:read graph:read`. Ask only for what you need:

| Scope | Lets you |
| --- | --- |
| `reports:read` | search companies, read KYB reports, person appointments, advanced reports and jobs |
| `graph:read` | read the ownership and officer network |
| `advanced:run` | start advanced reports (AI website analysis) and link a company website |

Response: `registration_id`, `claim_token` (**returned once**; keep it in memory only),
`claim_token_expires` (24 h), `post_claim_scopes`, and for `service_auth` a `claim` block:
`user_code` (6 digits), `verification_uri`, `expires_in` (600), `interval` (5).

For `anonymous`: `{ "type": "anonymous", "agent_name": "…" }`; no `claim` block yet.

## Step 4 — Claim ceremony

**4a.** Anonymous only (or to get a fresh code after `expired_token`):

```http
POST https://kybgate.com/agent/identity/claim
Content-Type: application/json

{ "claim_token": "clm_…", "email": "user@example.com" }
```

The email binds the registration: only that Google account can approve you. The response has a
`claim_attempt` block (same fields as `claim`). A new attempt replaces the previous link and code.

**4b.** Tell the user, in one message:

> Open this link, sign in with Google, and enter this code: **123456**
> https://kybgate.com/claim?claim_attempt_token=…

The code goes into the page they land on, not back to you. They see your name and scopes and can
deny you.

**4c.** Poll every `interval` seconds:

```http
POST https://kybgate.com/oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type=urn:workos:agent-auth:grant-type:claim&claim_token=clm_…
```

| Answer (400 `error`) | Meaning |
| --- | --- |
| `authorization_pending` | Not confirmed yet; keep polling |
| `slow_down` | You polled faster than `interval`; add 5 s |
| `expired_token` | The 10-minute code expired; go back to 4a for a new one |
| `access_denied` | The user declined you |
| `invalid_grant` | Unknown or already used `claim_token`; restart at Step 3 |

Success (200):

```json
{ "access_token": "kg_live_…", "token_type": "Bearer", "scope": "reports:read graph:read",
  "identity_assertion": "<service-signed JWT>", "assertion_expires": "…" }
```

The `claim_token` is single-use: the token comes back exactly once.

## Step 5 — Use the access token

```http
GET https://kybgate.com/api/v1/me
Authorization: Bearer kg_live_…
```

`/api/v1/me` shows the user and `auth.key.scopes`. Then, for example,
`GET /api/v1/gb/companies/search?query=tesco` or `GET /api/v1/gb/companies/00445790/report`.
The token is an ordinary KYBGate API key: it does not expire on its own, and the user can see and
revoke it on https://kybgate.com/app/api-keys.

## Step 6 — Refresh and revoke

- **New token:** `POST /oauth2/token` with
  `grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=<identity_assertion>`. You get a
  fresh key; **the previous key is revoked**. If the user revoked your key, this returns
  `invalid_grant`: restart at Step 3.
- **Revoke:** `POST /oauth2/revoke` with `token=kg_live_…` (RFC 7009, always 200).

## Errors on API calls

Every API error is `application/problem+json` with a stable `code`:

| Status | `code` | What to do |
| --- | --- | --- |
| 401 | `unauthenticated` | No credentials: follow this file from Step 1 |
| 401 | `invalid_api_key` | Unknown or revoked key: Step 6 (refresh) once, else restart at Step 3 |
| 403 | `insufficient_scope` | The key lacks the scope named in `WWW-Authenticate`: register again asking for it |
| 403 | `session_required` | Key management and admin pages are for people only |
| 429 | `rate_limited` | 120 requests per minute per key: wait `Retry-After` seconds |

Registration is limited to 20 per hour per IP address. Never ask the user for their Google password
or session cookie. Keep the token secret; don't echo it back to the user.

## MCP and OAuth (authorization code + PKCE)

The MCP server is `https://kybgate.com/mcp` (streamable HTTP, stateless, JSON answers). Without a
token it answers `401` with
`WWW-Authenticate: Bearer resource_metadata="https://kybgate.com/.well-known/oauth-protected-resource/mcp"`.

1. Read the resource metadata, then `/.well-known/oauth-authorization-server`
   (`authorization_endpoint`, `token_endpoint`, `registration_endpoint`, S256 only).
2. Register: `POST /oauth2/register` `{"client_name": "…", "redirect_uris": ["https://…/callback"]}`
   (public client, no secret), or use an https URL serving your Client ID Metadata Document as
   `client_id`.
3. Send the user to `/oauth2/authorize?response_type=code&client_id=…&redirect_uri=…&code_challenge=…&code_challenge_method=S256&scope=reports:read%20graph:read&state=…&resource=https://kybgate.com/mcp`.
   They sign in with Google and approve your app on kybgate.com.
4. `POST /oauth2/token` with `grant_type=authorization_code&code=…&code_verifier=…&redirect_uri=…&client_id=…`.
   The access token is a scoped API key named "MCP: <your client name>"; the user sees and revokes it
   on /app/api-keys. Authorizing again replaces it. It works for `/mcp`, `/a2a` and `/api/v1`.

Tools (`tools/list`): list_jurisdictions, search_companies, get_company_report, get_company_network,
get_person_appointments, start_advanced_report, get_job, create_onboarding, list_onboardings,
get_onboarding, invite_to_onboarding, get_pricing, get_credit_balance, buy_credits. Each maps to one
REST operation: same scopes, credits and errors. Cards: `/.well-known/mcp/server-card.json`
(MCP), `/.well-known/agent-card.json` (A2A, `POST /a2a`).

## Credits and paying

Paid calls spend the user's credits (free plan: 25 a month; prices at https://kybgate.com/pricing or
`GET /api/v1/pricing`). Responses carry `X-Credits-Charged` and `X-Credits-Remaining`. When credits
run out: `402` with `code` `insufficient_credits`, `balance`, `credits_needed` and `buy_url`. Get a
Stripe Checkout link with `POST /api/v1/billing/checkout {"product": "pack_500"}` (MCP:
`buy_credits`) and give it to the user. Never pay on their behalf without asking.

**Agents without an account** may pay per call where pay-per-call is enabled (`GET /api/v1/pricing`
→ `pay_per_call.enabled`): an unauthenticated report, network or person-appointments call answers
`402 payment_required` with `WWW-Authenticate: Payment …` (Machine Payments Protocol, method
`stripe`). Pay with a Shared Payment Token and retry with `Authorization: Payment <credential>`;
the answer has a `Payment-Receipt`. A failed call is refunded.

## Not live yet

- **ID-JAG identity assertions** from agent providers (a trust list is needed first).
- **x402** (stablecoins): not offered; use MPP or credits.
