# Payments AI — agent authentication

How an agent obtains credentials for Payments AI MCP and REST. This file is public. It does not grant access.

## MCP (recommended)

Streamable HTTP endpoint:

`https://mor.payments.ai/api/mcp`

### OAuth 2.1 + PKCE (S256)

Use this unless the host cannot complete a browser redirect. With no browser and no terminal, use the [device authorization grant](#device-authorization-grant-no-browser-no-terminal) instead.

1. Register a client at `POST https://mor.payments.ai/api/v1/oauth/register` (dynamic client registration) or let the MCP host do it from protected-resource metadata.
2. Send the user through `https://mor.payments.ai/api/v1/oauth/authorize` with `response_type=code` and `code_challenge_method=S256` (optional `scope`: if omitted, the consent screen lists every supported scope; if supplied, it lists only the requested scopes).
3. On the dashboard consent screen, the human chooses **read** and **write** tool scopes. If `scope` was supplied, every requested scope is pre-ticked except `transaction:read`; if `scope` was omitted, every supported scope is listed, read scopes are pre-ticked, and write scopes and `transaction:read` are unticked so the human opts in. **Approve** sends `granted_scopes` for the token.
4. Exchange the code at `https://mor.payments.ai/api/v1/oauth/token` (form-encoded, as RFC 6749 requires, or JSON).
5. Call MCP with `Authorization: Bearer <access_token>`. The credential is valid for 90 days: `whoami` reports `credentialExpiresAt`, and from 14 days before expiry `whoami` carries a `credentialExpiryWarning` with the re-approve link (every tool result carries it under `_meta["ai.payments/credentialExpiryWarning"]` plus a closing text block). The link opens https://doc.dev.managed.payments.ai/connect, the top of that page. If you connected with the device grant, renew as described under [Device authorization grant](#device-authorization-grant-no-browser-no-terminal).

A failed `/token` request answers HTTP `400` with the RFC 6749 §5.2 body `{ "error": "...", "error_description": "..." }`, never the API's `Validation failed` body: `invalid_request` (a missing or malformed field; the description names it), `invalid_client`, `invalid_grant` (code unknown, used, expired or PKCE mismatch), `invalid_scope`, `invalid_target` (bad or mismatched `resource`) and `unsupported_grant_type`. For `authorization_code` failures the body also keeps `message`, the full string earlier versions returned alone.

Discovery:

| Document                        | URL                                                                   |
| ------------------------------- | --------------------------------------------------------------------- |
| Authorization server (RFC 8414) | https://mor.payments.ai/.well-known/oauth-authorization-server       |
| Protected resource (RFC 9728)   | https://mor.payments.ai/.well-known/oauth-protected-resource/api/mcp |
| MCP Server Card (SEP-1649)      | https://mor.payments.ai/.well-known/mcp/server-card.json             |
| Legacy MCP card                 | https://mor.payments.ai/.well-known/mcp.json                         |

Host config (OAuth, no token in the file):

```json
{
  "mcpServers": {
    "payments-ai": {
      "url": "https://mor.payments.ai/api/mcp"
    }
  }
}
```

On the first tool call your client opens a browser or prints a sign-in URL; in Claude Code run `/mcp` → Authenticate. The human signs in on the Payments AI dashboard and chooses which MCP tool scopes to grant (grouped as read vs write access).

#### When the connect does not finish

The connection request stays valid for 30 minutes from the moment the connect starts. That is enough time for a first-time human to sign up and verify their email, in the same browser tab or a new one, and then approve.

| What you see                                                                                                                  | Cause                                                                             | What to do                                                                                                                                             |
| ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| The human says the approval page reported that the connection request expired.                                                | More than 30 minutes passed between starting the connect and approving it.        | Tell the human the 30-minute connection window lapsed, then start the connect again. If they already finished signing up, they only sign in this time. |
| Your MCP client reports that it stopped waiting (timed out, no callback received, login cancelled) before the human approved. | Your MCP client's own wait ran out. Payments AI did not reject the authorization. | Tell the human your client timed out, then start the connect again. If they already finished signing up, they only sign in this time.                  |

Never report either case as an authorization failure or a permissions problem.

#### When a stored credential keeps getting 401

Some clients keep an OAuth credential saved without an `issuer` stamp (upstream MCP issue SEP-2352). That stored credential wins over every new authorization, so signing in again changes nothing.

Signature: the client shows Payments AI as connected or holds a stored credential, but every MCP call answers `401`, and running OAuth again does not fix it. The server answers with an ordinary 401 `code` (see the table under User MCP Key); it cannot tell a stale stored credential apart, so recognise the case from the signature.

1. Clear the stored Payments AI credential in your client, then reconnect and approve scopes in the browser again. In Claude Code: `claude mcp remove payments-ai`, then `claude mcp add --transport http payments-ai https://mor.payments.ai/api/mcp`. In other clients, sign out of the server or remove it from the MCP settings, then add it again.
2. If the client offers no way to clear the stored credential, ask the human for a new token from Developer Tools → MCP Tokens and connect with the `Authorization: Bearer` header (User MCP Key below). A bearer token does not use the client's OAuth credential store.
3. Report the case with code `stale_credential_no_issuer`, stage `false_connected_state`, as described under [Report a failed connect](#report-a-failed-connect).

### Device authorization grant (no browser, no terminal)

Use this when nothing on the machine can open a browser or answer a prompt: a headless agent, CI, a container, an SSH session without a TTY. You drive the grant (RFC 8628) with plain HTTP; the human approves on any device that has a browser. The result is the same `pai_mcp_*` credential OAuth issues, valid for 90 days, sent as `Authorization: Bearer`. The authorization server metadata lists the endpoint as `device_authorization_endpoint`.

1. Register a device-only client, once: `POST https://mor.payments.ai/api/v1/oauth/register` with JSON `{"client_name": "<your agent>", "grant_types": ["urn:ietf:params:oauth:grant-type:device_code"]}`. Send no `redirect_uris`: a device-only client has none and cannot use `/authorize`. Keep the returned `client_id`. The human sees `client_name` as an unverified application, as for every client that is not Payments AI's own.
2. Start the authorization: `POST https://mor.payments.ai/api/v1/oauth/device_authorization`, form-encoded, with `client_id`, `resource=https://mor.payments.ai/api/mcp` (the token then works on that MCP URL only) and optionally `scope`. Omit `scope` to let the human pick from every supported scope. The answer is `device_code`, `user_code` (8 letters, written `BCDF-GHJK`), `verification_uri`, `expires_in` (1800 seconds, 30 minutes) and `interval` (5 seconds). There is no `verification_uri_complete`: the human types the code.
3. Tell the human to open `verification_uri` exactly as returned (on Sandbox it carries the deployment), type `user_code`, sign in or sign up, and approve. Scopes start unticked for write access; the human ticks what to grant. They can also press **Deny**. Show `user_code` and `verification_uri`; never show the `device_code`.
4. Poll `POST https://mor.payments.ai/api/v1/oauth/token`, form-encoded, with `grant_type=urn:ietf:params:oauth:grant-type:device_code`, `device_code`, `client_id` and the same `resource`, no faster than `interval`.
5. On success the body is `{ "access_token": "pai_mcp_...", "token_type": "bearer", "expires_in": 7776000, "scope": "..." }`. Store it like any token, send it as `Authorization: Bearer`, then call `whoami`.

Sandbox: use `https://sandbox.mor.payments.ai/api` for the three endpoints and `https://sandbox.mor.payments.ai/api/mcp` as `resource`.

Renewal: the client never ran OAuth, so "re-approve the connection in your AI client" does not apply. When `whoami` carries a `credentialExpiryWarning`, or a call answers `token_expired`, run the device grant again from step 2 (step 1 only if the answer is `invalid_client`) and replace the `Authorization` header with the new token. The warning's re-approve link opens https://doc.dev.managed.payments.ai/connect; the steps for a headless agent are under [Connect without a terminal](https://doc.dev.managed.payments.ai/connect#connect-without-a-terminal).

Poll answers, all HTTP `400` with `{ "error", "error_description" }`:

| `error`                 | Meaning and what to do                                                                                     |
| ----------------------- | ---------------------------------------------------------------------------------------------------------- |
| `authorization_pending` | The human has not decided yet. Keep polling at the current interval.                                       |
| `slow_down`             | You polled faster than the interval. Add 5 seconds to it for this and every later poll, then keep polling. |
| `access_denied`         | The human pressed **Deny**. Stop, tell them, and report `device_consent_denied` (stage `token_exchange`).  |
| `expired_token`         | The 30 minutes passed. Start again at step 2 and report `device_code_expired` (stage `token_exchange`).    |
| `invalid_grant`         | The `device_code` is unknown, already used, or belongs to another client. Start again at step 2.           |
| `invalid_client`        | The client is no longer registered. Register again (step 1).                                               |
| `invalid_target`        | `resource` is not one of this deployment's resources, or differs from the one named at step 2.             |

`device_authorization` itself answers `400` `invalid_scope` for an unsupported `scope` and `invalid_request` for a malformed body. When too many authorizations are waiting (10 per client and requester IP address pair, 20 per IP address, 1000 in total) it answers `429` with `{ "error": "temporarily_unavailable" }` and `Retry-After: 60`: back off for that long and try again later; do not loop.

The approval page accepts 5 code attempts per account every 15 minutes, a correct one included, so a human who mistypes repeatedly has to wait. Fix-It pages for the page's own errors: `/errors/oauth-device-user-code-rejected`, `/errors/oauth-device-request-expired`, `/errors/oauth-device-request-decided`, `/errors/oauth-device-request-forbidden` and `/errors/oauth-invalid-scope`, all under https://doc.dev.managed.payments.ai.

Per client, after the grant: Claude Code, Cursor, Codex, Gemini CLI, Antigravity and VS Code take the token as a header (see the table in [SKILL.md](https://doc.dev.managed.payments.ai/SKILL.md) under "Connect without a terminal"). Claude on the web and Desktop has no shell: use the connector's own browser sign-in (no terminal, 90-day credential); the fallback is a User MCP Key under the connector's Request headers, which lasts at most 7 days, and on Team and Enterprise the Owner sets the headers, so every member then acts as the key owner's account. Grok and ChatGPT run in the browser: use their connector sign-in as described above. The device grant does not apply (no shell) and a header path is not verified; the fallback is https://doc.dev.managed.payments.ai/connect on a device with a browser.

### Report a failed connect

Report every connect failure, at any stage, so Payments AI can see which clients and stages fail. Send one report per failed attempt, after you have told the developer what went wrong. A report never replaces the recovery steps above.

Where: `POST https://mor.payments.ai/api/mcp/connect-diagnostics` (Sandbox: `POST https://sandbox.mor.payments.ai/api/mcp/connect-diagnostics`). A 401 from the MCP endpoint also carries the exact URL as `connectDiagnosticsUrl`. Send `Content-Type: application/json`. No `Authorization` header and no token: the endpoint is public. It always answers `204` with an empty body, whether the report was accepted or dropped, so do not retry and do not read anything into the status.

What: a JSON object with exactly these seven fields. Every field is a closed value; a report cannot carry text.

| Field              | Allowed values                                                                                                                                                                                                                                       |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `client`           | `claude-code`, `claude`, `cursor`, `codex`, `grok`, `chatgpt`, `gemini`, `vscode`, `other`                                                                                                                                                           |
| `stage`            | `discovery`, `authorize`, `callback`, `token_exchange`, `first_tool_call`, `oauth_interactive_unavailable`, `false_connected_state`                                                                                                                  |
| `code`             | `oauth_interactive_unavailable`, `false_connected_state`, `stale_credential_no_issuer`, `device_code_expired`, `device_consent_denied`, `discovery_failed`, `authorize_failed`, `token_exchange_failed`, `first_tool_call_failed`, `unknown_failure` |
| `mcpServerVersion` | Plain semver, at most 32 characters: the `serverInfo.version` from initialize.                                                                                                                                                                       |
| `clientVersion`    | Plain semver, at most 32 characters: your client's own version.                                                                                                                                                                                      |
| `deployment`       | `sandbox` or `live`: the MCP URL you were connecting to.                                                                                                                                                                                             |
| `reportedAt`       | ISO 8601 UTC timestamp, for example `2026-10-12T09:30:00Z`.                                                                                                                                                                                          |

Pick the `stage` where the connect stopped and the closest `code`. Use `unknown_failure` when no other code fits; use `other` as `client` when yours is not listed.

```json
{
  "client": "cursor",
  "stage": "token_exchange",
  "code": "token_exchange_failed",
  "mcpServerVersion": "1.4.0",
  "clientVersion": "2.0.14",
  "deployment": "live",
  "reportedAt": "2026-10-12T09:30:00Z"
}
```

Never include: tokens, API keys, OAuth codes, merchant data, email addresses, error messages, stack traces or any other prose. Unknown fields are dropped, and a body that contains a `pai_mcp_`, `pai_live_` or `pai_test_` credential is discarded whole. Bodies over 2048 bytes are dropped.

### User MCP Key (bearer fallback)

Use only when the host cannot do OAuth.

1. Human signs in at https://mor.payments.ai
2. Developer Tools → MCP Tokens → pick the **Sandbox** or **Live** tab → Generate, choose tool scopes (`pai_mcp_*`, shown once, max TTL 7 days)
3. Use the MCP URL of the tab the token was generated on. A Sandbox token works only with `https://sandbox.mor.payments.ai/api/mcp`; a Live token works only with `https://mor.payments.ai/api/mcp`.
4. Host config (Live token shown):

```json
{
  "mcpServers": {
    "payments-ai": {
      "url": "https://mor.payments.ai/api/mcp",
      "headers": {
        "Authorization": "Bearer pai_mcp_YOUR_TOKEN"
      }
    }
  }
}
```

Never put this token in source, prompts you will commit, or a shared skill file.

Rejected requests return **401** with a JSON body. The `WWW-Authenticate` header keeps the OAuth discovery challenge. Branch on `code`:

```json
{
  "statusCode": 401,
  "error": "Unauthorized",
  "code": "invalid_token",
  "message": "This MCP token is not valid on this Live MCP URL: it is unknown, revoked or malformed. ...",
  "docUrl": "https://doc.dev.managed.payments.ai/errors/invalid-token",
  "connectDiagnosticsUrl": "https://mor.payments.ai/api/mcp/connect-diagnostics",
  "connectPageUrl": "https://doc.dev.managed.payments.ai/connect"
}
```

| Field                   | Value                                                                                                                                                                |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `statusCode`            | Always `401`.                                                                                                                                                        |
| `error`                 | Always `Unauthorized`.                                                                                                                                               |
| `code`                  | One of the codes below.                                                                                                                                              |
| `message`               | Human-readable recovery text for the `code`. Quote it verbatim.                                                                                                      |
| `docUrl`                | The error page for the `code` (`/errors/missing-token`, `/errors/invalid-token`, `/errors/token-expired`); `token_validation_unavailable` links the `/errors` index. |
| `connectDiagnosticsUrl` | Where to send a [connect failure report](#report-a-failed-connect) for this deployment.                                                                              |
| `connectPageUrl`        | The public connect page: server status, one way to connect and the `whoami` check. Hand it to the human.                                                             |

| `code`                         | Meaning and recovery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `missing_token`                | No `Authorization: Bearer` header. Add it, or use OAuth.                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `invalid_token`                | Unknown, revoked or malformed token (a revoked key, or a placeholder such as `pai_mcp_YOUR_TOKEN`, lands here). Ask the human for their real token, or a new one from the matching tab.                                                                                                                                                                                                                                                                                                                         |
| `token_expired`                | Message starts `MCP Session Expired. Re-approve the connection in your AI client, or generate a new token in Developer Tools → MCP Tokens if you connected with a token.` and ends `How to reconnect: <connect page URL>`. OAuth connection: tell the human to re-approve it (the connect page shows how). Device-grant connection (no terminal): run the device grant again and replace the `Authorization` header; there is nothing to re-approve in the client. Pasted token: ask the human for a new token. |
| `token_validation_unavailable` | The token could not be checked right now. Retry later; do not ask for a new token.                                                                                                                                                                                                                                                                                                                                                                                                                              |

## Scopes

| Scope              | Tools                                                                |
| ------------------ | -------------------------------------------------------------------- |
| `docs:read`        | `search_payments_ai_docs`                                            |
| `merchant:create`  | `create_merchant_account`                                            |
| `merchant:read`    | `get_my_merchant`, `get_merchant_activation_status`                  |
| `merchant:go_live` | `go_live`                                                            |
| `product:create`   | `create_product`, image upload/confirm                               |
| `product:read`     | `list_products`                                                      |
| `checkout:read`    | `get_checkout_customization`                                         |
| `checkout:write`   | `update_checkout_customization`, `set_checkout_logo`, `create_order` |
| `transaction:read` | `list_transactions`, `get_transaction`                               |

`whoami` needs no scope: every valid token can call it.

Checkout branding tools need `checkout:read` / `checkout:write`. If you see "Insufficient scope", the human must mint a new token or re-consent with those scopes.

`transaction:read` exposes customer emails and names, so it is never granted by default, by a token minted without a scope list, or by a token whose `scopes` is `null`. Request it by name in the authorize `scope`; the consent screen shows it unticked, so the human must tick it to grant it. Or ask the human to tick it when minting a token.

## Merchant Public API (REST)

Not MCP. Sandbox base: `https://sandbox.mor.payments.ai/api`

```
Authorization: Bearer pai_test_<64 hex>
```

Live keys use `pai_live_*` against the live API host. Do not send live keys to the docs Try It panel.

Platforms create sub-merchants with `POST /v1/public-api/merchants` using their own Merchant API Key (`pai_test_*` / `pai_live_*`); the parent is derived from the key. Assign parent-team users to a sub-merchant with `POST /v1/public-api/merchants/{merchantId}/members`. Key lifecycle for your merchant or sub-merchants: `/v1/public-api/merchants/{merchantId}/api-keys`. Single-merchant flows can also create via dashboard or MCP (`create_merchant_account`). Catalog routes are `/v1/public-api/merchants/{merchantId}/…`.

## What this server will not do

No payout, refund, key revoke, or webhook-secret tools over MCP. Do not invent them. For a refund, send the merchant to the transaction's Transaction Details page (`transactionDetailsUrl` from `list_transactions` or `get_transaction`).

## Stuck

- MCP setup: https://doc.dev.managed.payments.ai/mcp
- Skill: https://doc.dev.managed.payments.ai/SKILL.md
- Support: merchants@payments.ai
