# BeatyBook Agent API — authentication

For methods, booking safeguards and retry rules, read the
[agent integration guide](https://beatybook.ru/developers/agent-guide.md).
[Human documentation](https://beatybook.ru/developers/) is available in Russian.

Use the current discovery metadata from the deployment being connected. The
published scopes describe supported capabilities; only the effective scopes in
the token and `get_connection` describe this connection's access. Read current
service, price, availability and booking data through its authorized tools rather
than relying on an earlier conversation or a cached product description.

## Choose an access method

- **Personal agents:** Authorization Code + mandatory PKCE S256, explicit
  owner/admin consent, and rotating refresh tokens. Use CIMD when the deployment
  advertises it, or dynamic client registration (DCR). The person does not give
  the agent their BeatyBook password.
- **Server-side integrations:** an owner/admin creates a project key, then the
  integration uses `client_credentials` with `client_secret_post`.

An authenticated `get_connection` call through an existing personal ChatGPT connection
was verified on TEST. Native step-up → return → proposal → apply and client-managed
refresh in ChatGPT/Dots have not been accepted end to end. Read the
[authorization-server metadata](https://beatybook.ru/.well-known/oauth-authorization-server)
and check that the client supports its flow. An MCP URL alone is not enough.
Codex CLI 0.172.0 completed native registration, browser login/owner consent,
PKCE code exchange and MCP `get_connection` on the test deployment. Its automatic
refresh after access-token expiry was not verified end to end; server refresh
rotation has separate protocol tests. This result does not establish production
compatibility for every client or tool.

## Persistent personal-agent connection

Discover the exact `resource` in
[protected-resource metadata](https://beatybook.ru/.well-known/oauth-protected-resource).
The default is `https://beatybook.ru`, shared by REST and MCP; it is not the REST
base URL or `/mcp`. Use the advertised deployment value unchanged on authorization,
code exchange, and refresh.

### Client ID Metadata Documents (CIMD)

The server supports CIMD and advertises
`client_id_metadata_document_supported: true` in its authorization-server
metadata. Check the current metadata of the deployment being connected before
choosing CIMD. DCR remains available.

With CIMD, do not call `/oauth/register`: use your HTTPS metadata-document URL as
the exact `client_id` in authorization, code exchange and refresh. For example,
serve this document at `https://agent.example/oauth/client.json`:

```json
{
  "client_id": "https://agent.example/oauth/client.json",
  "client_name": "Example appointment assistant",
  "redirect_uris": ["https://agent.example/oauth/callback"],
  "token_endpoint_auth_methods_supported": ["none"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"]
}
```

The URL is an exact identity, not a URL to normalize: it must match the document
`client_id` byte for byte. BeatyBook accepts ASCII HTTPS URLs up to 2048 characters
on port 443, with a non-root path and no userinfo, query, fragment or dot path
segments. Serve HTTP 200 JSON (`application/json` or `application/*+json`);
redirects are not followed. Retrieval is limited to 5 seconds and 64 KiB of
decoded content. All resolved addresses must be public; connections use the
validated addresses, with TLS certificate verification. Referenced logos, JWKS
and other document URLs are not fetched.

The deployment may use an operator-configured outbound proxy. Destination
addresses are still validated and pinned before CONNECT, and TLS verifies the
original metadata hostname. Clients do not configure this transport.

This public-client flow uses `none` and mandatory PKCE S256. A plural
`token_endpoint_auth_methods_supported` containing both `none` and
`private_key_jwt` is accepted even when the legacy singular preference is
`private_key_jwt`: the supported intersection is `none`. A legacy singular
method must also belong to the plural list when both are present. Missing both
fields defaults to `none`. Signed client assertions and client secrets are not
supported for personal agents. Metadata must allow `authorization_code` and
response type `code`; declare `refresh_token` for a persistent connection.
Without it, code exchange returns an access token without a refresh token.
The name is self-declared; callback and consent rules below still apply.

Metadata is checked when starting authorization and again after valid code/PKCE
or refresh credentials have been presented, before consuming them. A malformed
or rejected document returns `invalid_client` without redirecting the person.
A document whose `client_id` no longer matches revokes that client's grants.
A transient retrieval failure returns HTTP 503 without consuming credentials
or revoking existing grants. Protected REST/MCP calls do not fetch metadata.

In ChatGPT's custom MCP setup, select CIMD after refreshing the server discovery
metadata. The missing-CIMD warning should then disappear; ChatGPT's general
warning about custom MCP servers is controlled by ChatGPT and remains. Native
ChatGPT/Dots account linking still needs an end-to-end acceptance test. See the
[OpenAI authentication guide](https://developers.openai.com/plugins/build/auth)
and the [CIMD specification](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-03).

### Dynamic client registration (DCR)

Register a public client:

```text
POST https://beatybook.ru/api/agent/v1/oauth/register
Content-Type: application/json
```

```json
{
  "client_name": "Example appointment assistant",
  "redirect_uris": ["https://agent.example/oauth/callback"],
  "token_endpoint_auth_method": "none",
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"]
}
```

HTTP 201 returns `client_id` and metadata, with no client secret. Registration
also accepts optional `application_type` (`web` by default or `native`) and
`scope`, a supported-scope hint of at most 512 characters validated against the
published scope set. A supplied string must contain known scopes; empty or
unknown scopes return `invalid_scope`, wrong types or excessive length return
`invalid_request`. Omitted/null metadata is accepted and omitted from the
response; a valid string is echoed with unique scopes sorted and separated by
single spaces. Registration scope is informational only: it grants no
access, selects no project and does not replace the required scope on
`/oauth/authorize` or the person's separate permission choices. The visible name is limited to 100 characters; register 1–5 distinct
redirects. Web clients use exact public HTTPS callbacks. Only an explicitly
native client may register HTTP loopback: `http://127.0.0.1:45871/callback` or
`http://[::1]:45871/callback`, with an explicit decimal port 1–65535 and those
literal IP forms. No `localhost`, alternate IP notation, leading-zero ports,
private-network hosts, fragments (even empty `#`), userinfo, or preconfigured
OAuth response parameters (`code`, `state`, `error`, `error_description`, `iss`).
For native loopback only, authorization may change the listener port; scheme,
literal IP, path and query must still match registration. The exact URI chosen
for this attempt is bound to consent and code exchange. Other redirects use
exact matching, without wildcard expansion. Registration is rate
limited and grants **no project access**. The application
name is self-declared and unverified.

Generate a fresh cryptographically random PKCE verifier (43–128 characters from `A–Z`, `a–z`, `0–9`, `-._~`), derive an unpadded BASE64URL SHA-256 challenge, and generate a separate
unpredictable `state`. Keep verifier and state in the integrating client's
protected storage. Open `/api/agent/v1/oauth/authorize` in the person's browser
with URL-encoded parameters:

```text
response_type=code
client_id=<registered_client_id_or_exact_CIMD_URL>
redirect_uri=https://agent.example/oauth/callback
state=<random_state>
resource=https://beatybook.ru
code_challenge=<S256_challenge>
code_challenge_method=S256
scope=services:read availability:read bookings:read
```

All parameters are required; duplicate values are rejected. Request only necessary
scopes. On BeatyBook's private `/connect-agent` page the person signs in, checks
the application and callback origin, selects a project they actually own or
administer, and chooses permissions. Only the three booking read scopes start
selected when requested. `bookings:write` and every owner permission
(`owner:services:read`, `owner:proposals:write`, `owner:calendar:read`,
`owner:changes:propose`, `owner:changes:apply`) start unchecked. Existing connections do not gain new
scopes; request them through fresh interactive consent. A request lasts 5 minutes and is bound to the
first signed-in browser session that opens it. Do not share consent links.

All `owner:*` permissions are available only to delegated personal agents;
machine `client_credentials` keys remain limited to the four booking scopes.
`owner:services:read` reads the catalogue; `owner:proposals:write` remains
price-proposal-only. `owner:calendar:read` reads a bounded calendar without
customer contacts. `owner:changes:propose` plus the matching catalogue/calendar
read scope saves proposals for supported name, duration or visibility fields
and manual free windows, not direct edits. By default a master decides on the private
`/review-agent-change` page with a browser session. With separately selected
`owner:changes:apply`, the agent can instead apply its own immutable proposal
using `apply_owner_proposal` / `POST /owner/proposals/{proposal_id}/apply`.
First clarify missing details in the chat, show exact changes and obtain explicit
agreement. Client confirmation prompts depend on the host's settings; the server
does not verify a chat message as human consent. Browser approve/reject endpoints
remain session/CSRF-only and never accept an agent Bearer token.
Calendar records for busy bookings, payment holds, blocks, external events and
automatic rules are read-only. See the
[owner workflow and exact fields](https://beatybook.ru/developers/agent-guide.md#owner-calendar-and-servicewindow-proposals).

The exact callback selected for this attempt receives `code`, `state`, `iss`; denial returns
`error=access_denied`, `state`, `iss`. Validate original state and expected issuer
before accepting a code. Exchange a single-use code within 5 minutes:

```text
POST https://beatybook.ru/api/agent/v1/oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&client_id=<registered_client_id_or_exact_CIMD_URL>
&code=<authorization_code>
&redirect_uri=https://agent.example/oauth/callback
&code_verifier=<original_verifier>
&resource=https://beatybook.ru
```

Form values must be URL-encoded. Public clients send no client secret and no
Authorization header or signed client assertion. Success returns `access_token`,
`token_type=Bearer`, `expires_in=3600`, effective `scope`, and `refresh_token`
when the client metadata allows refresh.

Refresh at the same endpoint with form-encoded `grant_type=refresh_token`,
`client_id`, `refresh_token`, and the same `resource`. Optional `scope` can only
narrow the previous token's rights. Each successful refresh returns a replacement
refresh token: save it atomically and discard the old one. Serialize refresh
attempts. Reuse of a consumed refresh token revokes the whole connection; do not
blindly retry after a lost refresh response. On `invalid_grant`, stop and restart
interactive authorization. OAuth errors are `{"error":"…","error_description":"…"}`.

The connection and refresh family expire 30 days after consent; refresh never
extends this deadline. Ordinary logout does not revoke a connection. Active grant,
application, project and the consenting person's actual owner/admin role are
checked on subsequent protected calls and refreshes. The owner/admin can revoke
access in project Settings → AI agents («ИИ-агенты»). Revocation blocks the next
REST/MCP call even before access-token expiry; an operation already admitted may
finish.

Revocation targets one `grant_id`, including its refresh families. Repeated
consent can leave several active connections for the same application/project;
revoking one does not revoke the others. To remove all of that application's
existing access to the project, revoke each active connection shown there.

## Browser-only consent and connection management

These routes serve BeatyBook's owner/admin interface. They require a current
DB-backed BeatyBook cookie session, not the external agent's Bearer token.
State-changing requests also require the browser session's CSRF protection.

| Endpoint relative to `/api/agent/v1` | Purpose |
| --- | --- |
| `GET /oauth/consent` | Query `request_id`; bind/read consent request, application origins, requested scopes and eligible projects |
| `POST /oauth/consent` | JSON `{request_id, project_id, scopes, approved}`; one decision, returns `{redirect_url}`; denial can omit project |
| `GET /oauth/connections` | Query `project_id`; list that project's delegated grants and their effective status |
| `POST /oauth/connections/{grant_id}/revoke` | JSON `{project_id}`; revoke a project grant and refresh families |

Project selection and revocation require the person's actual owner/admin role.
Public client registration never authorizes these methods. Do not ask an external
agent to collect or replay the person's cookie or CSRF token.

## Server-side integration key

The studio owner/admin creates a key in Settings → AI agents («ИИ-агенты»). One key
belongs to one project; its secret is shown once. New keys default to
`services:read availability:read bookings:read`; `bookings:write` is enabled
separately. Keep the secret in a secret manager, not a chat, repository or browser
storage.

```text
POST https://beatybook.ru/api/agent/v1/oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&client_id=<client_id>
&client_secret=<client_secret>
&scope=services:read availability:read
```

Form values must be URL-encoded. Omit `scope` to request the key's grants. An
explicit scope must be nonempty, known and entirely granted; otherwise the
server returns `invalid_scope`. Access tokens last 3600 seconds; this flow does
not issue refresh tokens. Request a new access token with the key after expiry.
Revoking the key blocks its next authenticated REST/MCP request.

## Permissions

| Scope | Permission | Access method |
| --- | --- | --- |
| `services:read` | List studio services, prices in rubles and duration in hours | Personal OAuth or server key |
| `availability:read` | List free slots / rental intervals | Personal OAuth or server key |
| `bookings:read` | Read the status of a known booking in the connected project | Personal OAuth or server key |
| `bookings:write` | Create, confirm, reschedule and cancel bookings in that project | Personal OAuth or server key; explicit selection |
| `owner:services:read` | Read the owner catalogue and price-edit eligibility | Personal OAuth; explicit selection |
| `owner:proposals:write` | Save fixed-price proposals and read this connection's proposal status; creating a proposal also needs `owner:services:read` | Personal OAuth; no approval permission |
| `owner:calendar:read` | Read a bounded calendar without customer contacts | Personal OAuth; explicit selection |
| `owner:changes:propose` | Save supported service/manual-window proposals and read their status; creating one also needs the matching owner read scope | Personal OAuth; no approval permission |
| `owner:changes:apply` | Apply this connection's immutable price, service or manual-window proposal; also requires its original read/propose scopes | Personal OAuth; separate explicit selection; no website confirmation |

`bookings:write` includes bookings not created by this connection. It does not
permit editing the catalogue, working schedule, staff, payment credentials or
owner settings. Consent to an agent is separate from the customer's authorization
and SMS verification for a booking.
All five `owner:*` scopes start unchecked and cannot be assigned to server keys.
The read/propose scopes alone cannot apply anything. Only the separately selected
apply scope permits application without website confirmation. Host confirmation
settings still apply; only `status=applied` means an owner change was saved.

## Verify before making changes

```text
GET https://beatybook.ru/api/agent/v1/connection
Authorization: Bearer <access_token>
```

Any valid token can read the connected project name/timezone, effective scopes,
`writes_enabled` and authentication capabilities. This call sends no SMS and
changes no appointment. MCP equivalent: `get_connection` with `{}` arguments.
`writes_enabled: true` does not itself grant the write scope.

## Additional permissions from an MCP conversation

For delegated personal connections, `get_connection.authentication.owner_access_context`
is an opaque signed continuation valid for about 10 minutes. It is not a
credential: keep using the Bearer token, do not print the context in conversation,
and do not interpret or modify it.

When owner access is missing, call the MCP-only
`request_owner_access(operation, access_context, mode)` tool. `operation` is
`service_price`, `service_details` or `manual_windows`; pass the context unchanged.
Always choose `mode` explicitly: `read` for a catalogue/calendar read, `propose`
for a change reviewed on the website, and `apply` only when the person wants
application from chat. If that preference is absent, use `propose` for a requested
change. The omitted mode defaults to `apply` only for backwards compatibility.
Read mode requests no proposal/application rights; propose mode requests no
`owner:changes:apply`. The request also includes current effective rights, but
the person can deselect them during consent. No proposal or project change is created. This helper
adds no REST route or OAuth scope; see the
[exact scope sets and workflow](https://beatybook.ru/developers/agent-guide.md#request-additional-access-before-creating-a-proposal).

The tool can return `isError: true` with `_meta["mcp/www_authenticate"]` containing
a Bearer `insufficient_scope` challenge, `scope`, `resource_metadata` and
`error_description`. Together with per-tool `securitySchemes` and protected-resource
metadata, this lets a compatible host display its native OAuth linking flow.
Tool descriptors also mirror schemes in `_meta.securitySchemes`; the helper's
static OAuth scopes are empty because its exact required set depends on
`operation` and `mode`. Owner tool descriptions are discoverable to delegated connections
before their scopes are granted. Discovery grants no right to execute them.

The owner must explicitly approve the requested rights on BeatyBook's consent
page. After OAuth, retry the same helper arguments to verify the same client,
owner and project. Only `ready` prepares the selected access level; it does not
mean any change was applied. Read mode then reads data; propose mode creates
a proposal with `review_url`; apply mode additionally needs explicit agreement
for that exact proposal before applying it. `consent_incomplete`, `connection_changed`,
`invalid_context` and `access_reduced` stop this attempt without another automatic
OAuth round. Denial stops the upgrade. If the connection still has read/propose
rights, browser review remains an alternative without requesting apply rights;
do not promise a review link before a proposal exists.
Revocation, role loss, machine keys and unrelated business errors are not a
reason for an automatic permission-upgrade loop.

A new grant cannot use proposal IDs created under an older grant. If access was
changed after proposal creation, check the current project and data, create a
fresh proposal, show its exact summary and obtain explicit agreement again.
Do not treat additional-permission consent as approval to replay a change.
ChatGPT/Dots native authorization still needs end-to-end verification with the
intended client and its confirmation settings; the server contract alone does
not establish universal compatibility.

## REST and MCP

- REST base: `https://beatybook.ru/api/agent/v1`.
- MCP: `POST https://beatybook.ru/mcp`, `Authorization: Bearer <access_token>`.
- MCP protocol: `2025-06-18`, stateless JSON-RPC 2.0; initialize, then list/call tools.
- MCP tools: `get_connection`, `search_services`, `get_availability`, `get_booking`,
  `create_booking`, `confirm_booking`, `cancel_booking`, `get_owner_services`,
  `propose_service_price`, `get_owner_proposal`, `get_owner_calendar`,
  `propose_service_change`, `propose_slot_change`, `get_owner_change_proposal`,
  `apply_owner_proposal`, `request_owner_access` (MCP-only access preparation).
  Owner tools require delegated OAuth and their matching scopes. Booking
  rescheduling is exposed through REST only.
- [OpenAPI](https://beatybook.ru/api/agent/v1/openapi.json) includes OAuth and REST schemas.

An anonymous MCP `initialize` returns HTTP 200 with public protocol/server
metadata and `instructions` for clarification and confirmation in the current
chat. Tools advertise read/write, destructive and retry annotations. A new
window without explicit master/service choices returns `clarification_required`
without saving a proposal. `null` / `[]` are explicit user choices, never guesses.
Refresh the MCP tool definitions after an update, and obtain fresh OAuth consent
to add a permission. `ping` is also public and `notifications/initialized` returns 202.
These responses do not grant access. `tools/list` and `tools/call` require a valid
Bearer token, including a call to `get_connection`; missing or invalid access
returns HTTP 401 with a `WWW-Authenticate` resource-metadata challenge. A
`Mcp-Session-Id` returned by initialization does not replace authentication.
Read `result.isError` on tool responses even when HTTP status is 200.

Creating a booking sends an SMS and returns `pending_verification`; no slot is
reserved yet. Confirm with the customer's code. `awaiting_payment` means
prepayment is still pending. Follow the
[booking skill](https://beatybook.ru/.well-known/agent-skills/book-appointment/SKILL.md).
Never set `accept_no_refund=true` without the customer's explicit agreement.

## Discovery

- [MCP server card](https://beatybook.ru/.well-known/mcp/server-card.json)
- [Agent skills index](https://beatybook.ru/.well-known/agent-skills/index.json)
- [Protected resource metadata](https://beatybook.ru/.well-known/oauth-protected-resource)
- [Authorization server metadata](https://beatybook.ru/.well-known/oauth-authorization-server)
- [API catalog](https://beatybook.ru/.well-known/api-catalog)
