Customer API Access

Two owner switches for customer API keys and MCP over OAuth: what each registers, which endpoints stay closed, and why switching needs no migration.

Your customers can reach your app from their own code with API keys, and from AI tools over MCP using keys or browser OAuth. Both features are off by default. Browser consent binds one chosen account; keys carry a personal or durable organization grant.

This page is the reference. For step-by-step guides, see MCP Server: connecting clients, adding tools and API keys in your routes.

I want toSection
Turn API keys or MCP onThe Switches
Know how keys are issued, limited and replacedIssuing Keys, Active Key Limit, Replacing Keys
Accept an API key in my own routeAuthorizing Requests
Connect a client to /api/mcpConnecting to MCP with a Key, Browser MCP Authorization
Look up a refusal codeRequest Error Codes
Change the per-credential request limitCredential Request Limits
Set up an OAuth client or understand consentOAuth Discovery and Owner Clients, Account-Bound Consent
Add a business rule to keys and requestsCustomer Policies
Add an MCP toolScoped MCP Tools, Customer Write Tools
Know what a ban or a deleted account does to credentialsBans and Account Deletion
Know how long records are keptCleanup and Retention
Check an integration worksVerify an Integration

The Switches

VariableDefaultRegisters
API_ACCESS_KEYSfalseBetter Auth's API-key plugin
API_ACCESS_MCPfalseBetter Auth's jwt() and mcp() plugins (the OAuth provider for MCP clients)

The default is what an unset variable means, as in production. Local development starts with both on: env.example sets them to true, and pnpm kit:setup copies it into apps/web/.env.

Set the public feature flags through the kit's environment tools locally and as Worker variables in production. They apply when the auth instance is built (apps/web/config/api-access.config.server.ts → config/auth.server.ts), so a change takes effect on the next deploy or restart.

  • Each switch adds only its own plugins. Turning one on never turns the other on.
  • MCP accepts API keys only with both switches on. Browser MCP works with the API-key plugin off.
  • The tables (apikey, jwks, oauth_*) always exist, so switching needs no migration.
API_ACCESS_KEYSAPI_ACCESS_MCPKey issuance/api/mcpOAuth client flow
falsefalseRefused404Absent
truefalseEnabled404Absent
falsetrueRefusedBrowser access tokens onlyEnabled
truetrueEnabledAPI keys or browser access tokensEnabled

Keys-only mode also supports your own routes using authorizeApiKey; the kit does not ship a separate account REST endpoint. Turning issuance off leaves canonical key lists/revocation and Connected Apps management available. Switching back on never clears a key or connection revocation.

Closed Endpoints

The plugins come with many HTTP endpoints. The kit closes all of them (404, like the organization and admin endpoints) except the steps an OAuth client calls: /oauth2/authorize, /oauth2/token, /oauth2/revoke, /jwks and the discovery documents. Key management, client registration, consent and session JWTs are reached only through the kit's server code (auth.api), which authorizes every call. Endpoints a Better Auth upgrade adds in these namespaces are closed too.

Every browser OAuth authorization lands on the consent page (/api-access/consent): a GET never issues a code. Account selection and approval complete through the protected page actions; skip-consent clients are refused.

Issuing Keys

createApiAccessServices({ getAuth, scopes, lockAndCountActiveKeys, maxActiveKeys }).keys.create({ actor, account: 'personal', name, scopes, expiresInDays }) issues a personal key. Users create theirs on Settings → API keys (API Keys), whose create action calls it through apiAccessFor(c).keys.createPersonal(body) (apps/web/lib/api-access.server.ts: the actor from the session, refusals as HTTP errors or a scopes field error).

  • Scopes come from your scope catalogue, apiAccessScopes in config/api-access.config.server.ts: { 'account:read': { personal: true, organization: { apiKey: ['read'] } } }. Each scope is resource:action. A scope outside the catalogue is refused (UNKNOWN_SCOPE), and so is one a personal key may not carry (SCOPE_NOT_ALLOWED).
  • Owner: always the signed-in user. Any owner id in the input is ignored.
  • Session: needs a sign-in from the last few minutes and refuses impersonation (SESSION_NOT_FRESH, IMPERSONATED).
  • Account mode: keys follow ACCOUNT_MODE, as browser grants do (the app binds accountMode: getAccountMode). Organizations-only refuses personal keys and personal-only refuses organization keys (API_KEYS_DISABLED, 404). Existing keys of a disabled kind stop authorizing (INVALID_API_KEY) but stay listed and revocable.
  • Expiry: none by default. expiresInDays takes 1 to 365.
  • Secret: returned once, by create only. The database keeps a hash and the prefix plus the next 6 characters (start) to identify the key.
  • Prefix: every key starts with sk_, like Stripe's. Set your own in config/api-access.config.server.ts (keyPrefix, e.g. acme_sk_: starts with a lowercase letter, then lowercase letters, digits or _, ends with _, at most 17 characters; an invalid prefix fails at startup) so secret scanners such as GitHub push protection can tell your keys apart. Changing it affects new keys only.

Organization Keys

keys.create({ actor, account: 'organization', organizationId, name, scopes, expiresInDays }) issues a key the organization owns. Members use /settings/organization-api-keys (API Keys); apiAccessFor(c) binds the verified session and active membership for every action.

  • Owner: the actor's active organization (actor.membership, resolved by the app from the database). organizationId is the organization the form was rendered for: a different one means the user switched in another tab (409 ORGANIZATION_CHANGED). No active organization: 404 NO_ACTIVE_ORGANIZATION.
  • Permission: the member needs apiKey: create from your roles (owners and admins by default). Without it: 403 PERMISSION_DENIED. Better Auth's API-key plugin checks the same statement against the member row again when it inserts.
  • Scopes: each needs an organization statement in the catalogue, and the member must hold every action in it: { 'members:write': { personal: false, organization: { member: ['update'] } } }. A scope without one (or with an empty one), or beyond the member's roles, is refused (403 SCOPE_NOT_ALLOWED). So a member can never hand a key more than they hold today.
  • Durable: after issuing, the key is the organization's grant. It keeps its scopes when the member who made it is demoted or leaves; revoke it to end it.
  • Session: the same fresh, non-impersonated sign-in as personal keys.
  • Roles: the ceiling reads the roles in your rbac.config.ts. Roles created at runtime (Better Auth dynamic access control, off in the kit) can't issue organization keys.

keys.listOrganization({ actor, organizationId, url }) needs apiKey: read; keys.revokeOrganization({ actor, organizationId, keyId }) needs apiKey: delete. Both check the actor's active membership and the form's organization separately. They read and write the database directly, filtered by owner and key config, instead of calling plugin endpoints, so they work with API_ACCESS_KEYS off. Revocation is idempotent, needs no recent sign-in and reveals nothing about unknown or other accounts' key IDs. Read permission never grants creation, revocation or access to a stored secret.

Both key lists (keys.list({ actor, url }) for personal keys, keys.listOrganization for an organization's) return a page of 25 keys (active, revoked and expired), newest first, from readListPage. The page's ?keysPage= picks it, and its previous/next links keep the URL's other parameters.

The default account:read catalogue entry permits organization grants from members holding apiKey: read. The picker and server share the full-statement permission check; replace that mapping with your own resource permissions when extending the catalogue.

Active Key Limit

Each personal account and organization defaults to 20 active keys. An organization's issuing members share those slots. Configure apiAccessLimits.maxActiveKeys in config/api-access.config.server.ts; it must be a nonnegative safe integer. Zero refuses new keys. This is trusted server configuration, never a form value or a billing policy.

Disabled and expired keys do not count. Creating a replacement uses another slot until the old key is revoked: at the cap, the settings form asks the user to revoke an unused key before retrying (409 KEY_LIMIT_REACHED).

keys.create opens the Better Auth adapter transaction. The app's lockAndCountActiveKeys binding (db/api-key-issuance.server.ts) locks the owning user or organization row, counts its enabled, unexpired keys, then the plugin inserts on that same transaction. Concurrent requests cannot claim the same final slot. Every caller must supply the binding; a count outside this transaction is insufficient.

Replacing Keys

There is no rotation endpoint: create the new key, switch the integration, then revoke the old one (Replace a Key). Both keys count toward the active-key limit until the old one is revoked.

Connecting to MCP with a Key

With both switches on, create a personal or organization key with account:read (Issuing Keys), then connect to /api/mcp with x-api-key. The endpoint has no browser-session fallback, even when a request carries cookies.

The pinned SDK reference client uses explicit negotiation for the current 2026-07-28 profile:

import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
async function readAccount({ endpoint, key }: { endpoint: string; key: string }) {
const client = new Client(
{ name: 'my-integration', version: '1.0.0' },
{ versionNegotiation: { mode: 'auto' } },
);
try {
await client.connect(new StreamableHTTPClientTransport(new URL(endpoint), {
requestInit: { headers: { 'x-api-key': key } },
}));
const result = await client.callTool({ name: 'account_context', arguments: {} });
return result.structuredContent;
} finally {
await client.close();
}
}

account_context accepts an empty object and returns exactly { id, name, type, scopes }. type is personal or organization; scopes are the key's effective current grant. The account name comes from a named owner-filtered query. Credential IDs, creator IDs, emails and secrets are excluded. Organization keys keep working after their creator leaves, provided the organization and grant remain valid. Revocation or expiry refuses the next authenticated request.

config/mcp-tools.server.ts registers this tool using registerAccountContextTool, binding db/mcp-account.server.ts and translated metadata from api-access.server.json. Additional customer tools use the same scoped registrar (Scoped MCP Tools). Their services still authorize resource IDs and own write transactions and retry safety.

What the endpoint accepts:

  • Transport: JSON over POST with the current profile. Legacy handshakes, batches and subscription streams are refused.
  • Method: any method other than POST answers 405 without credential or database work.
  • Origin: a missing browser Origin is allowed for server clients. A supplied Origin must exactly match the configured site origin, including scheme and port, and is checked before the method.
  • Session: /api/mcp is an exact sessionless path with its own Origin check. Cookie identity and caller-supplied account hints never choose the account.

Its limits. The trusted apiAccessMcpOptions configures the first two, which are named defaults:

LimitValue
Request body64 KiB, enforced by the SDK
Response deadline30 seconds
Response sizeCapped at 1 MiB
  • The outer deadline returns safely even when an in-flight authorization lookup cannot be canceled.
  • Abort guards prevent subsequent tool execution, and cancellation reaches handlers through signal.
  • Already-started domain writes may finish after an aborted response, so clients must not blindly retry arbitrary write tools.

Perimeter checks run before credential lookup. Initialization, discovery and empty registries also authenticate and consume the shared budget. Preflight, listing and callbacks retain the original Request identity, so one HTTP request is charged once despite repeated live checks. Refusals use the codes in Request Error Codes. Scope/policy-denied tools are omitted and direct invocations are refused through MCP. Every response is private/no-store.

Native SDK dispatch remains intact. Protocol errors retain their code/id with a fixed safe message and no raw error data; successful modern wire fields remain unchanged. Better Auth owns key cryptography and OAuth primitives; the official SDK owns MCP transport, schemas and dispatch. The kit supplies account isolation, current authorization, policies and limits.

Code: @kit/api-access/server (apiAccessAuthPlugins, apiAccessSchemaPlugins, createApiAccessServices) and @kit/api-access/mcp (createCustomerMcp, createScopedMcpServer, registerAccountContextTool).

Help Customers Connect

When MCP is enabled, Connected apps includes Connect an app with the configured public server URL, a copy button and short browser sign-in steps. Customers use an MCP-compatible client supported by the app; OAuth clients still require owner provisioning. The panel contains no credentials or account data. Copy failure leaves the URL selectable for manual copying.

With API keys enabled too, the panel links to personal API Keys settings and explains the x-api-key header. API keys are never OAuth Bearer tokens. With MCP off, the panel and URL are absent, while existing connections remain listed and revocable.

Authorizing Requests

A customer route calls the app's authorizeApiKey({ c, requiredScopes }) helper. It checks the IP/global perimeter before key/database work, verifies personal or organization ownership, applies the credential budget and maps safe HTTP refusals (Request Error Codes). The kit ships no account REST endpoint: your handler uses the returned account to authorize its own resources.

import { authorizeApiKey } from '#/lib/api-access.server.ts';
const { keyId, account, scopes } = await authorizeApiKey({
c,
requiredScopes: ['account:read'],
});
// account: { kind: 'personal', id: userId } or
// { kind: 'organization', id: organizationId }, frozen
  • Header: the key goes in x-api-key only. A request that also carries Authorization, or carries a key or api_key/access_token in its URL, is refused.
  • Every request reads live state: the key (hash, enabled, expiry), its owner and your catalogue. A personal owner must exist and not be banned. An organization must exist; its grant does not depend on the creator's current membership or user state. No authority is cached between requests, so revocation or owner deletion fails the next call.
  • Authority: personal scopes are the stored grant intersected with catalogue entries still personal: true. Organization scopes are the stored grant intersected with known catalogue scope names, without consulting the creator. Remove a scope from the catalogue to withdraw it globally. Every required scope must be present; an empty list still verifies the credential and consumes its request budget.
  • One refusal for bad keys: every kind of bad key gets the same INVALID_API_KEY, so callers can't distinguish them.
  • Fails closed: errors reaching auth, canonical configuration, owners or the counter deny the request. Errors never contain the key.
  • The account comes from the key only. Ignore account or user ids in the request, and still check each resource id against account.id in your own service.
  • No sessions: a key never signs anyone in; Better Auth's API-key sessions stay off.
  • One principal per route: a route that takes keys must not also read the browser session (getSession/requireSession): a request can carry a cookie and a key for different users.

Register each credential route's exact path in lib/sessionless-paths.ts before using the helper: otherwise cookie session middleware can reach the database before the route's perimeter check. Keep the one /api/files/ prefix unchanged. Run the wrapper before reading a request body; the route or protocol transport also owns its finite body/work limits.

The package-level createApiAccessServices(deps).authorizeApiKey({ request, requiredScopes }) is the lower-level seam for other frameworks. It requires a consumeCredential binding for authorization (missing binding denies with 503); the app supplies createCredentialRateLimitStore(db). Other framework integrations must provide equivalent perimeter and sessionless routing.

Credential Request Limits

apiAccessLimits.requestsPerMinute defaults to 120 per credential, for both personal and organization keys. It is trusted server configuration, an integer from 0 to 2,147,483,646; zero refuses all credential requests. Separate keys have separate budgets, even in the same account. Defaults and bounds live in packages/api-access/src/limits.service.ts (DEFAULT_MAX_ACTIVE_KEYS, DEFAULT_REQUESTS_PER_MINUTE, CREDENTIAL_WINDOW_SECONDS); the SQL store shares the window constant.

The PostgreSQL rate_limit row is keyed by kit:api-access:api-key:<verified-id> or kit:api-access:connection:<verified-id>. No credential secrets, hashes, request bodies or attacker-supplied counter IDs are stored. Invalid credentials never allocate counter rows. The existing idle-row cleanup covers these rows.

One atomic upsert starts a fixed 60-second window at its first request and shares the budget across Worker instances using the same primary database. It stores the window end in lastRequest, following the kit's auth convention. The limit is authoritative for this fixed window, rather than a sliding minute: a burst around a boundary can span two windows. Rejected attempts saturate the stored count at the limit plus one; larger counts from previous configurations are retained. All instances must use the same configuration. Lowering a cap never lowers an existing count; denials never extend the deadline.

Time comes from PostgreSQL's statement-start timestamp, rounded down to milliseconds, not each Worker's clock. Long row-lock waits may make retry guidance conservative; Retry-After rounds up to whole seconds and stays between 1 and 60.

Verified, live credentials consume budget before required-scope checks and tool execution, including authenticated 403 responses. Repeated/concurrent authorization with the same original Request and credential counts once within the service instance, while cryptography, ownership and scopes are rechecked. Reuse the app's bound service and original request; a new or cloned Request starts a separate request budget. This is request-local counting, not an authority cache. API-key plugin counters stay disabled.

Over quota the helper returns 429, Cache-Control: no-store, Retry-After and { "code": "RATE_LIMITED", "retryAfterSeconds": 1…60 }. Retry with a new HTTP request after that delay. A counter failure denies with 503. The separate IP/global Workers perimeter (Rate Limits) is approximate and follows its existing missing-binding/outage convention; it bounds invalid-key work before any credential lookup during normal operation.

Request Error Codes

HTTP refusals from authorizeApiKey routes and /api/mcp. The body is { "code": … }, private and uncached; errors never contain the credential. Inside MCP, scope- and policy-denied tools are omitted from listings and their calls are refused through MCP instead.

CodeStatusWhen
API_KEY_REQUIRED401authorizeApiKey route: no x-api-key
MIXED_CREDENTIALS400x-api-key together with Authorization, or API-key and OAuth credentials together
CREDENTIALS_IN_URL400A key, api_key or access_token in the URL
INVALID_API_KEY401Unknown, malformed, disabled, revoked or expired key; unsupported key configuration; account kind off in the account mode; banned personal owner; missing owner; the native verifier rejects the key
INVALID_ACCESS_TOKEN401 or 403/api/mcp without x-api-key: missing or rejected browser access token (follows Better Auth's status, with its WWW-Authenticate challenge)
INSUFFICIENT_SCOPE403authorizeApiKey route: a required scope is missing
POLICY_DENIED403authorizeApiKey route: a customer policy denies
PERMISSION_DENIED403/api/mcp: a supplied Origin does not match the site origin
API_KEYS_DISABLED404A key with API_ACCESS_KEYS off; OAuth on /api/mcp stays available
MCP_DISABLED404/api/mcp with API_ACCESS_MCP off
(none)405/api/mcp: any method other than POST
RATE_LIMITED429Over the credential request limit, with Retry-After
AUTHORIZATION_UNAVAILABLE503Auth, configuration, owner, counter or policy failure; missing consumeCredential binding; /api/mcp response deadline

OAuth Discovery and Owner Clients

With API_ACCESS_MCP enabled, Better Auth serves protected-resource metadata at /.well-known/oauth-protected-resource and /.well-known/oauth-protected-resource/api/mcp. Its resource is ${SITE_URL}/api/mcp, and its authorization server is ${SITE_URL}/api/auth. RFC 8414 issuer discovery is available at /.well-known/oauth-authorization-server/api/auth and /api/auth/.well-known/oauth-authorization-server. GET and HEAD use the native plugin documents; no duplicate metadata builder or client registry is maintained. Discovery works with API_ACCESS_KEYS disabled. Turning MCP off closes discovery, OAuth authorization, token, refresh and registration, and the /api/mcp resource, before auth or database work.

This kit supports owner-provisioned public OAuth clients. It disables dynamic registration and installs no CIMD metadata-fetch plugin; URL-shaped client IDs cannot cause remote metadata requests. It does not promise compatibility with named proprietary clients or every optional feature in the current MCP profile. The kit pins Better Auth 1.7.25 (@better-auth/mcp, @better-auth/oauth-provider) and MCP SDK 2.4.0 in pnpm-workspace.yaml; see there for current versions. /api/mcp serves the current 2026-07-28 JSON transport profile with explicit client negotiation (Connecting to MCP with a Key).

Trusted server provisioning can call provisionOwnerMcpClient from @kit/api-access/server, supplying the existing auth instance, the platform admin's session headers, getApiAccessConfig().mcpServer, and { name, applicationType, redirectUris, scopes }. There is no public client-management endpoint or new admin UI. Better Auth's clientPrivileges rejects ordinary users, banned users and impersonation; this reads the platform user.role, never an organization role. Do not expose this helper through an unguarded action. Any new admin page or action still needs the normal requireAdmin check and its configured permission.

Provisioning bounds names to 120 characters, redirects to eight URLs of at most 2,048 characters, and scopes to 32 known entries. Only HTTPS redirects or native HTTP loopback redirects (127.0.0.1 / [::1]) are accepted. Credentials, fragments, wildcards and extra metadata fields are refused; remote JWKS URLs and arbitrary resources are not accepted. The native API stores the client, bound to this MCP resource, with authorization-code/refresh grants, PKCE and consent required, and no client secret. Redirect matching is exact, including native loopback ports. Provisioning failures return stable codes; outages return 503 without backend details.

OAuth HTTP requests pass a focused boundary before Better Auth parses bodies. Closed paths, encoded aliases and anonymous registration return 404 without reading the body. Open OAuth requests share the API-access IP/global perimeter, allow at most 8 KiB of query bytes and 16 KiB of body bytes, and stop stalled body reads after five seconds. Other auth paths retain their existing handling. The native provider still advertises some optional endpoints the kit closes, including introspection; clients must use the supported authorization-code flow.

/api-access/consent shows the client name, requested permissions and accounts the signed-in user can authorize. The first POST binds one account to that signed OAuth request. The next screen shows the selected account and allows the user to narrow its permissions before approving. Cancel returns the native OAuth denial response. Client names render as text, and consent responses are private, uncached and use no-referrer.

Every action verifies the native signed query, session, client, exact redirect, MCP resource and PKCE method. Organization permissions come from the user's current membership roles and the configured scope catalogue. The active organization in another tab does not affect them. Approval rechecks this authority inside the write transaction. Accounts unavailable in the configured account mode cannot be selected; organizations-only users without a grantable account can still see the empty state and cancel.

The additional api_access_connection row binds the user, OAuth client, account and signed flow. It stores no token or duplicate scope grant. Native Better Auth consent and code writes share the application's transaction: selection and continuation commit together; activation, narrowed native consent, code issuance and flow consumption commit together. The native token claim identifies this immutable connection. Browser MCP requests then authorize as described in Browser MCP Authorization.

GET never chooses an account or issues a code. A consumed flow cannot be approved again or changed to another account. Another account or more permissions needs a fresh authorization request and explicit consent. Refresh retains the connection binding; it cannot select a different account. Expired pending flows are cleaned after an additional day, while consumed flow identities remain until owner purge to prevent reuse. User and organization deletion use the existing indexed purge targets, with no cascading foreign keys on connection history.

Connected Apps Settings

/settings/connected-apps lists the signed-in user's completed connections, including revoked history. Each entry shows its client, account, native consent scopes and creation time. Results use 25-entry cursor pages. Pending consent flows, access/refresh tokens and internal flow/session fields are excluded.

The page and revoke action authorize independently from the verified session. Revocation remains available with API keys and MCP disabled, and does not require a fresh sign-in. An owner-filtered conditional update sets one connection's revocation timestamp once; repeated or foreign IDs reveal no existence information. Previously issued tokens and fresh or cached refresh attempts are refused by the live grant checks. Work already authorized may finish.

Fresh consent creates another immutable connection ID, keeping old tokens invalid. Missing client or consent metadata never hides an owned connection. Organization names are shown only while the user still belongs to that organization; otherwise the account is marked unavailable and remains revocable. The generated migration adds a (user_id, id) index for bounded pagination.

Browser MCP Authorization

Browser grants authenticate /api/mcp with an OAuth access token, using native Bearer or DPoP support. Better Auth verifies the signature, issuer, MCP resource audience, expiry and proof binding. The signed connection claim selects the account; URL parameters and browser sessions cannot change it. Mixed API-key and OAuth credentials, and credentials embedded in URLs, are refused.

Every authorization reloads the active connection, current user/account authority, OAuth client and native consent. Granted scopes are intersected with current permissions before listing or running tools. Revocation, missing consent, bans, account deletion and membership loss deny subsequent requests. Customer policies and the existing connection request budget apply alongside these checks. Only verified token claims are reused within one HTTP request, so DPoP proofs are consumed once; live authorization is checked again before execution.

/oauth2/revoke refuses a refresh token issued to another client before Better Auth runs (token not found, 400): oauth-provider 1.7.25 would otherwise clear the named client's refresh tokens for that user when handed an already-rotated token. Token issuance checks current authority and policies before minting. A native after hook also checks every returned token, including Better Auth's cached refresh retry response, before disclosure. Native refresh rotation and its retry window remain unchanged. Policy denials return safe refusals; backing-service failures return retriable 503 responses. Post-token checks cannot undo a completed native rotation, but prevent disclosure and permit the native retry path after recovery.

Customer Policies

Register business rules in apiAccessPolicies in config/api-access.config.server.ts. The registry is empty by default: integrations require no subscription or built-in paywall. Use the existing @kit/policies helpers through the typed integration registry:

import { allow, deny } from '@kit/policies';
import { createApiAccessPolicies, defineApiAccessPolicy } from '@kit/api-access/server';
export const apiAccessPolicies = createApiAccessPolicies().registerPolicy(
defineApiAccessPolicy({
id: 'integrations.business-access',
stages: ['createKey', 'authorize'],
evaluate: async ({ facts }) => {
if (facts.businessAccess === false) {
return deny({ code: 'BUSINESS_ACCESS', message: 'app.integrations.unavailable' });
}
return allow();
},
}),
);

Load your business facts in loadApiAccessPolicyFacts(context) in that config file. Call named queries scoped to the verified context.account.kind and context.account.id; return a plain record of strings, finite numbers, booleans or null. Policies receive the copied, frozen record as context.facts. Do not query databases or call services inside evaluate.

Both the loader and policies receive a frozen account, scopes and resolved numeric limits (maxActiveKeys and requestsPerMinute). Creation adds stage: 'createKey' and actorUserId; credential authorization adds stage: 'authorize', a verified credential and requiredScopes. Organization authorization supplies no creator identity: its grant survives the creator's departure. No request, session, credential secret, auth object or database handle is passed. The context's nested objects and arrays are frozen too; policy changes cannot alter the configured limits or the authorized result.

Creation checks fresh sign-in, the feature switch, account, RBAC and scope ceilings before loading facts. Facts load outside the issuance transaction so app queries do not contend with the single connection. Inside the transaction, the locked active-key cap still runs before policy evaluation and insertion. Facts are a snapshot, not a transactional business quota: enforce strict limits with your own atomic write constraints. Keep policies pure, quick and free of network calls while the lock is held.

Credential requests check cryptography, live ownership, request budget and required scopes before loading facts and running policies. Policies run again on every authorization call, including reuse of the same Request. They can restrict access but cannot bypass these checks or grant broader scopes. Lists and revocation run no business policies, so customers can always revoke their credentials with current management authority.

Every matching policy must allow (ALL). A normal denial returns only 403 POLICY_DENIED; a thrown policy, malformed result, invalid fact record or loader failure returns 503 AUTHORIZATION_UNAVAILABLE. Reasons, metadata and raw errors never reach the client. No loader runs when the registry has no policy for the current stage. Other frameworks supply policies and loadPolicyFacts to createApiAccessServices at the same seam.

Scoped MCP Tools

@kit/api-access/mcp exposes createScopedMcpServer. It builds a native SDK server for one HTTP request and accepts registerTools(registerTool), your scope catalogue, server identity and a trusted authorize({ request, requiredScopes }) binding. Bind authorization to the shared API-access service; never use caller-supplied SDK authInfo as proof. The app binds this through createCustomerMcp at /api/mcp.

Keep definitions in config/mcp-tools.server.ts, with input schemas in a matching *.schema.ts:

import { registerAccountContextTool, type RegisterScopedTool } from '@kit/api-access/mcp';
import { findMcpAccount } from '#/db/mcp-account.server.ts';
export function registerMcpTools({ registerTool, accountContextDescription }: {
registerTool: RegisterScopedTool;
accountContextDescription: string;
}) {
return registerAccountContextTool({
registerTool,
description: accountContextDescription,
findAccount: findMcpAccount,
});
}

The package owns the default account-context schemas (z.object({}) input and the four-field output). Additional tools call the scoped registrar with a nonempty description, a Zod object input schema, known nonempty required scopes and all four boolean annotations. An optional object output schema validates structured output. Names use letters, digits, underscores, dots and hyphens, up to the named SDK limit of 128 characters. Invalid names, duplicate names/scopes, unknown scopes, missing annotations, reserved account fields and schemas that cannot produce JSON Schema fail before authorization or execution. Register synchronously; the registrar closes when your callback returns. Annotations describe behavior to clients; they never grant permission.

Listing uses the shared live account, scope, quota and customer-policy boundary for each tool and disables denied tools through native SDK controls. Every invocation independently authorizes again before its handler runs: a prior listing grants nothing. Create a new server for every HTTP request; listing visibility is a snapshot for that request. The route must authenticate before invoking SDK transport, including initialization and empty registries, which have no per-tool checks to run. The wrapper keeps only the native registrations and a copy of each tool's required scopes; the SDK still owns dispatch, protocol validation and transport.

The trusted authorization binding returns { account, credential, scopes }: account kind/id, verified credential kind/id (api-key or connection) and effective scopes. For API keys, map the shared service's keyId to { kind: 'api-key', id: keyId }. All ids must be verified UUIDs. Handlers receive a frozen copy of these fields plus signal for cancellation. They receive no raw SDK context, request, headers or sessions.

Input objects reject unknown root fields even when the supplied Zod object would normally strip or pass them through. Principal fields (account, accountId, accountKind, organizationId, userId, credential, keyId, connectionId, scopes, requiredScopes) are reserved and cannot be declared as tool inputs. Use resource identifiers such as resourceId or targetUserId; your service still checks each resource against the verified account. Keep input nested-object validation explicit and never merge input into authorization context.

Schema failures return generic validation issues, and thrown handler errors become TOOL_EXECUTION_UNAVAILABLE. Authorization refuses with stable API-access codes. No payload or raw failure metadata is logged. The SDK rejects unknown/disabled tools itself; its unknown-tool protocol message includes the supplied name, so HTTP integration must sanitize protocol errors at the response boundary. Do not replace native SDK list/call dispatch to do that. Resource authorization, write transactions, audit and retry safety belong in each customer service.

Customer Write Tools

Write tools use the same scoped registrar. Put domain writes in a customer service, with strict input validation and ownership checks on every resource query and update. Derive the owner from the handler's verified account.kind and account.id; a valid account context alone does not authorize a supplied resource ID. Scope and policy checks run before the handler, but resource authorization belongs inside its transaction.

The test-only rename example in apps/web/db/__tests__/mcp-mutation.service.ts locks the owned resource, checks its revision, and updates the resource and an operation result in one transaction. Its business identity is rename:<resourceId>:<expectedRevision>, scoped by account kind and ID. An identical retry returns the stored result; a different value for that identity fails. Ownership is checked before returning a stored result, so moving a resource to another owner cannot make an old result accessible. This revision-based design suits this example; choose an identity that matches your own business operation.

The framework never automatically replays writes. A response deadline can happen after a transaction commits: a 503 does not prove that nothing changed. The example stores its result before responding, allowing an explicit identical retry without another write. It checks signal.throwIfAborted() before writing and before returning from the transaction, but cancellation cannot guarantee rollback once a commit has started. Keep network calls outside write transactions; enqueue required follow-up work through the existing transactional outbox.

The example's resource and operation tables are disposable test fixtures, not shipped product tools or migrations. A production operation history needs indexed ownership, a purge target and a retention policy that covers its supported retry window; deleting history too early can permit a replay in other domain designs.

For a scoped custom write, add a scope to apiAccessScopes and map its organization statement to your configured resource permissions. Add those permissions to your RBAC configuration first; a scope name alone grants nothing. Define the input in a matching schema file:

import * as z from 'zod';
const RESOURCE_TITLE_MAX_LENGTH = 120;
export const renameResourceSchema = z.object({
resourceId: z.uuid(),
expectedRevision: z.number().int().nonnegative(),
title: z.string().trim().min(1).max(RESOURCE_TITLE_MAX_LENGTH),
}).strict();

Then register through the existing registerTool argument. This fragment belongs inside your registrar, with renameResourceDescription supplied from a server translation:

registerTool('resource_rename', {
description: renameResourceDescription,
inputSchema: renameResourceSchema,
requiredScopes: ['resources:write'],
annotations: {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: false,
},
}, async (input, { account, credential, signal }) => {
const result = await renameOwnedResource({
account,
resourceId: input.resourceId,
expectedRevision: input.expectedRevision,
title: input.title,
signal,
});
if (result.changed) {
recordSystemAudit({
system: 'customer-mcp',
action: 'resource.renamed',
scope: {
type: account.kind === 'personal' ? 'user' : 'organization',
id: account.id,
},
target: { type: 'resource', id: result.id },
metadata: { credentialId: credential.id },
});
}
return { content: [], structuredContent: { id: result.id, revision: result.revision } };
});

Here renameResourceSchema is a strict object containing resourceId, expectedRevision and title. The named renameOwnedResource service must check resource ownership using the verified account, enforce the expected revision, and commit its own write and retry result before returning. changed is false for an idempotent replay. The transport cannot determine whether your transaction committed; it does not record a mutation event for you.

Import recordSystemAudit from #/lib/audit.server.ts and register the customer action in apps/web/config/audit.config.ts alongside your other actions:

import * as z from 'zod';
import { defineAuditConfig } from '@kit/audit';
export const auditConfig = defineAuditConfig({
scopes: [],
actions: {
'resource.renamed': {
scope: ['user', 'organization'],
severity: 'info',
metadata: z.object({ credentialId: z.uuid() }),
},
},
});

The system actor describes software acting through the verified credential. In particular, an organization key must not be attributed to the member who originally issued it. Use account and credential IDs from the handler context; never include a secret, token, resource title, email or tool payload. Add only the action and scope your service needs; no product mutation tool or action is enabled by this documentation.

Bans and Account Deletion

Credential access follows live account state, before background cleanup runs:

ChangePersonal keyOrganization keyBrowser connection
User bannedRefusedRemains usableRefused for that user, including organization connections
Issuing member leavesUnchangedRemains usableThat user's connection to the organization is refused
User deletedRefusedRemains usable if the organization survivesRefused for that user
Organization deletedUnchangedRefusedConnections to that organization are refused

Organization keys belong to the organization. Browser connections belong to a user and follow current membership. Deleting a user's account also deletes their sole-member organizations, so those organizations' keys stop working too. Unbanning restores authority for otherwise valid credentials; it never clears an explicit key or connection revocation. Already-authorized work may finish.

Use the existing admin ban action, Profile account-deletion flow and Organization deletion flow. They retain their normal permission, ownership and step-up checks. Native server deletion cannot bypass credential authorization: the next request still checks whether its user or organization exists. The kit exposes no public admin deletion endpoint or separate integration deletion service. Cleanup and retention are separate from access revocation.

Cleanup and Retention

Integration records use the existing daily cleanup and owner-purge jobs, including when API-key and MCP runtime plugins are off. Every batch uses the cleanup engine's row, time and lock limits. Live authorization denies deleted or revoked principals before any cleanup runs.

RecordsDaily cleanup rule
Expired keys, access tokens, refresh tokens and client assertionsEligible one day after expiry
Disabled keys and revoked native tokensEligible after 30 days; rotated refresh rows remain until their original expiry
Obsolete native grants/consents and orphan personal or organization keysMetadata older than 30 days, with a missing owner/client/connection or a connection revoked over 30 days ago
Retired JWT signing keysEligible 31 days after expiry, preserving Better Auth's configured 30-day verification grace
Expired pending connection flowsEligible one day after expiry
Consumed connection identities, including revoked connectionsKept until owner purge to prevent reuse of a consumed flow

These are daily-task windows, not guaranteed minimum retention: Better Auth's API-key plugin can eagerly remove expired keys during native key operations. A daily task can run up to a day after eligibility. Active keys with no expiry remain intact while their owner exists. Rotated refresh rows retain native reuse-detection history until expiry; native token or consent cleanup never creates a replacement connection or makes an old token valid again.

Ordinary account deletion saves purge intent in its deletion transaction. Native organization deletion prepares that intent through its existing hook. Native server user deletion prepares it after native authorization and before deleting sessions or sign-in accounts; an enqueue failure preserves those credentials. Prepared purge jobs retry while the owner exists, then drain indexed user/organization targets. User and organization key targets also filter configId, so matching IDs across the two account kinds cannot delete each other's keys.

Native access-token, refresh-token and consent tables retain their relations and indexed owner/client columns without unbounded cascading foreign keys. The generated migration removes those constraints; owner purges and daily obsolete-record cleanup drain the rows instead. Change the schema through the auth generator and its auth-schema.mjs postprocessor, never by editing generated tables.

Set supported kit.api-access-* windows, batch sizes or enabled flags in kitTaskOverrides in config/cleanup.config.server.ts. The JWKS task refuses windows shorter than 31 days. The defaults and task names live in packages/api-access/src/cleanup.ts; shared grace constants live in retention.ts.

Lifecycle Audit Events

The kit registers kit.api_access.key_created, kit.api_access.key_revoked, kit.api_access.connection_granted and kit.api_access.connection_revoked through the existing audit recorder. Replacement is a create event for the new key and a revoke event for the original. Events contain account scope, verified actor and key/connection target IDs, with no metadata or credential material.

Key events use the owning user or organization scope. Connection grant events use the selected account; connection revocation uses the revoking user's scope because Connected Apps is personal management. Impersonation attribution follows the existing audit actor convention. Only an actual revoke transition records an event: unknown, foreign and already-revoked IDs do not create success records.

Events run after the successful write's transaction commits, including when it joins an outer native transaction. Rollbacks record no success. Audit remains best effort with the existing retention and failure behavior; it is not a transactional compliance log. Your custom tools use the explicit post-commit boundary in Customer Write Tools.

Verify an Integration

Use a fresh local test account and an owner-provisioned reference OAuth client. Store real credentials in your client or secret store; examples in this guide use placeholders and never put credentials in URLs.

  1. Enable both switches. Create personal and organization keys with account:read; the default expiry is none. Use the SDK reference client to list tools and call account_context, checking the returned account for each credential.
  2. Complete the browser authorization-code/PKCE flow, selecting a personal account and an organization in separate consent flows. Call account_context with each access token. A grant never follows a later account-switcher change.
  3. Revoke the keys and browser connections from settings. Subsequent key/access requests must fail; refresh must fail too. Already-authorized work may finish.
  4. Exercise all four switch combinations from the table above against the running app. Disabled plugin endpoints must be absent; API-key HTTP management, client registration, native consent mutation and session JWT endpoints stay 404 even when their plugins are enabled.
  5. With both features off, confirm canonical settings still list and revoke credentials. Re-enable both and confirm those credentials remain revoked.

Before accepting an integration change, record your check results and runtime evidence. This local verification is not a production deployment or a compatibility guarantee for named proprietary clients.

Tests

TestCovers
apps/e2e/tests/settings/api-keys.spec.tsPersonal keys in the browser: the secret is shown once, the list shows only your own keys, and revoking asks for confirmation.
apps/e2e/tests/settings/organization-api-keys.spec.tsOrganization keys in the browser: the key is shown once, another manager can revoke it, and a member can neither open the key page nor post its actions.
apps/e2e/tests/settings/mcp.spec.tsThe reference MCP client against the running Worker, with a personal key and an organization key: it works, then is refused after the key is revoked in settings.
apps/e2e/tests/settings/oauth-discovery.spec.tsThe reference client discovers the native OAuth metadata on the running Worker.
apps/web/db/__tests__/mcp-oauth.test.tsThe browser grant on PGlite: authorization with PKCE, the account chosen per flow (two tabs, a second choice, an account the user isn't in), revocation and leaving an organization, GET never granting, and the flows the account choice refuses.
packages/api-access/src/__tests__/authorize.test.tsKey authorization on each request, including bans and deletion: a revoked key, a banned owner and a deleted owner are each refused on the next request.
proveApiAccessCleanup in apps/web/db/__tests__/api-access-cleanup.proof.tsThe real cleanup/outbox jobs on a disposable migrated database: retention, owner isolation and native deletion, including non-expiring keys, malformed references, consumed flows, refresh rotation history, JWT grace, interrupted/repeated purges, equal user/organization IDs and deletion failure/scheduling. No test file calls it: pnpm test:unit does not run it. Call it from a test or a standalone Node driver.
proveApiAccessAudit in apps/web/db/__tests__/api-access-audit.proof.tsThe audit events API access records. No test file calls it either.
packages/api-access/src/__tests__/mcp-mutation.test.tsWrite tools with the real SDK HTTP client, Better Auth and PGlite: personal and organization resource isolation, input/scope/policy refusal, concurrent identical retries, conflicting intent, atomic rollback, safe errors, a deadline before writing and a deadline after commit. PGlite serializes database sessions, so independent PostgreSQL connections are not proven.