Better Auth
Let a Better Auth server issue the tokens; verify them with okmcp/oauth.
Better Auth's mcp() plugin acts as the OAuth 2.1 authorization server. It handles login, consent, PKCE, Client ID Metadata Documents, and discovery metadata. okmcp is the resource server: it checks tokens but does not issue them.
Configure both servers with the same issuer, resource URL, and key set.
#The Better Auth side
import { betterAuth } from "better-auth";
import { jwt } from "better-auth/plugins";
import { mcp } from "@better-auth/mcp";
export const auth = betterAuth({
baseURL: "https://auth.example.com", // + basePath (`/api/auth` by default) = the issuer
plugins: [
jwt(), // signs the access tokens; EdDSA/Ed25519 by default
mcp({
loginPage: "/sign-in",
consentPage: "/consent",
resource: "https://api.example.com/mcp", // the audience for access tokens
scopes: ["openid", "profile", "mcp:read", "mcp:write"],
}),
],
});The values okmcp needs are:
| Better Auth | Value |
|---|---|
| Access token | An RFC 9068 JWT, typ: at+jwt, with a kid |
iss | jwt.issuer, or the resolved base URL — base path included: https://auth.example.com/api/auth |
aud | resource; when openid is granted, a list that also includes the UserInfo endpoint |
scope | Space-separated; the verifier converts it to AuthIdentity.scopes |
| Key set | {issuer}/jwks |
| Introspection (RFC 7662) | {issuer}/oauth2/introspect, client-authenticated |
| Protected-resource document | /.well-known/oauth-protected-resource and /.well-known/oauth-protected-resource/mcp on the Better Auth origin |
#The okmcp side
Use jwtValidator() to verify tokens locally with Better Auth's public keys. It uses WebCrypto and does not need jose:
import { defineMcpHandler } from "okmcp";
import { jwtValidator } from "okmcp/oauth";
const ISSUER = "https://auth.example.com/api/auth"; // Better Auth's base URL, base path included
const RESOURCE = "https://api.example.com/mcp"; // identical to `mcp({ resource })`
export default defineMcpHandler({
name: "my-server",
version: "1.0.0",
auth: {
schemes: ["bearer"],
validate: jwtValidator({
issuer: ISSUER,
audience: RESOURCE,
jwksUri: `${ISSUER}/jwks`,
requireType: true, // require Better Auth's `typ: at+jwt` header
}),
resourceMetadataUrl: "https://auth.example.com/.well-known/oauth-protected-resource/mcp",
scopes: ["mcp:read"],
},
tools: [
{
name: "delete_file",
scopes: ["mcp:write"], // returns 403 if this scope is missing
// ...
},
],
});iss and aud must match exactly. Copy them from the Better Auth config: a different trailing slash or missing base path causes 401 responses. If you set jwt.issuer, use that value for issuer here.
Handlers can read all verified claims from event.context.mcp.auth.claims, including sub, client_id, azp, jti, sid, and any resource customClaims.
#The metadata document
After a 401, an MCP client follows the challenge's resource_metadata URL to find the authorization server. Better Auth already serves this document. If Better Auth and /mcp run on the same origin, point resourceMetadataUrl to that document. You do not need another metadata route.
If they run on different origins, you can still point to Better Auth's document. The client checks that its resource matches the MCP endpoint. You can also serve the document on the MCP origin, as RFC 9728 expects:
import { protectedResourceMetadata } from "okmcp/oauth";
export default protectedResourceMetadata({
resource: "https://api.example.com/mcp",
authorizationServers: ["https://auth.example.com/api/auth"],
scopesSupported: ["mcp:read", "mcp:write"],
});#Checking for sign-out
Better Auth links each token to a session through sid. Its introspection endpoint reports the token as inactive when the session ends, whether through sign-out, admin revocation, or back-channel logout.
Local verification cannot detect these changes. It accepts a token until exp (one hour by default). Use introspection if MCP access needs to end sooner:
import { introspectionValidator } from "okmcp/oauth";
validate: introspectionValidator({
endpoint: `${ISSUER}/oauth2/introspect`,
issuer: ISSUER,
audience: RESOURCE,
clientId: process.env.MCP_RS_CLIENT_ID!,
clientSecret: process.env.MCP_RS_CLIENT_SECRET!,
cacheTtlMs: 30_000, // how long a sign-out can go unnoticed
}),Use credentials for a client registered with Better Auth and linked to the resource. Registration with resources creates this link as an oauthClientResource row. Other clients receive { "active": false }, so they cannot inspect tokens for your resource.
This also works if Better Auth issues opaque tokens. Set cacheTtlMs: 0 if every request must check for sign-out; the example above may accept a token for up to 30 seconds after its session ends.
#DPoP
Better Auth advertises DPoP support through dpop_signing_alg_values_supported. Clients using DPoP receive a token tied to a key and send it with Authorization: DPoP … and a proof.
Wrap the token verifier in dpopValidator() and enable the scheme, and those clients are served too:
import { dpopValidator, jwtValidator } from "okmcp/oauth";
auth: {
schemes: ["bearer", "dpop"],
validate: dpopValidator({
validate: jwtValidator({ issuer: ISSUER, audience: RESOURCE, jwksUri: `${ISSUER}/jwks`, requireType: true }),
resource: RESOURCE, // the proof's `htu`; identical to `mcp({ resource })`
// replay: yourSharedStore, // several instances behind one URL need one
}),
}The proof is verified against Better Auth's cnf.jkt binding (see sender-constrained tokens); Better Auth's default dpop.signingAlgorithms are all in okmcp's table. Clients using ordinary bearer tokens are unaffected, and a DPoP token sent as a bearer token is still refused by the transport. With this in place you can turn on dpopBoundAccessTokensRequired for the resource, which makes every client bind its token. Better Auth keeps its DPoP replay store in its database; okmcp's default is per process and evicts live entries at its cap, so give replay a shared store (one atomic add) when you run more than one instance or want the replay window airtight.
#Try it on the playground
The playground is a Better Auth server. pnpm play starts one Nitro process that is both sides of this page: Better Auth's mcp() plugin at http://localhost:6274/api/auth (in-memory database, one seeded account — the console prints the credentials) and the okmcp endpoints at /mcp, /mcp/modern and /mcp/legacy, whose jwtValidator() fetches /api/auth/jwks over loopback exactly as it would from another host.
pnpm play
open http://localhost:6274/.well-known/oauth-protected-resource/mcpAuth is optional there: connect any MCP client to http://localhost:6274/mcp with no token and every unscoped tool works. Call secret (scope secret:read) or read auth://me (scope profile) and the answer is 401 with resource_metadata and the scope — a client that follows it registers itself (dynamic registration is open), lands on the playground's login page, then its consent page, and comes back with a token that makes both calls succeed. auth://me shows what the token said.
The playground's own browser UI is such a client. Call secret there and the refusal offers Sign in for secret:read; the header has Sign in too. Either runs the whole flow — discovery, registration, PKCE — and comes back to the same item with the token set. The hosted playground works the same way.
A client registering a loopback redirect URI (http://localhost:…, http://127.0.0.1:…) must send application_type: "native", as 2026-07-28 requires: Better Auth follows OIDC registration, where an omitted type means "web", which only takes https on a public host.
Hosts that only run OAuth when the first request is a 401 get that from http://localhost:6274/mcp?auth: the same server with optional off, so anonymous callers are refused up front. A token is good on both URLs.
The embedded server keeps its data in memory unless DATABASE_URL (or POSTGRES_URL) names a Postgres database — the Vercel Neon integration sets it. A serverless deployment needs one: each step of one sign-in may reach a different instance, and every instance must see the same clients, sessions, codes and signing key. The schema is created on first start.
To point the playground at another authorization server instead of its own:
| Variable | Effect |
|---|---|
MCP_PLAYGROUND_BETTER_AUTH_URL=http://localhost:3000/api/auth | Verify against an external Better Auth (its mcp({ resource }) must be http://localhost:6274/mcp); its RFC 9728 document is advertised |
MCP_PLAYGROUND_CLIENT_ID / MCP_PLAYGROUND_CLIENT_SECRET | Use introspection instead of the key set (a client registered as a resource server) |
MCP_PLAYGROUND_JWKS_URI + MCP_PLAYGROUND_AUTHORIZATION_SERVER, or MCP_PLAYGROUND_INTROSPECTION_ENDPOINT | Any other issuer; add MCP_PLAYGROUND_RESOURCE_METADATA for a document published elsewhere |
MCP_PLAYGROUND_TOKEN (+ MCP_PLAYGROUND_SCOPES, default secret:read) | A shared secret accepted besides the OAuth tokens — the quickest way to see a scoped call succeed from curl |
MCP_STATE_SECRET | The secret Better Auth signs with (shared with the MRTR demo); a development fallback is used, with a warning, when unset |
MCP_PLAYGROUND_ORIGIN | The public origin, when it is neither http://localhost:6274 nor the one Vercel reports |
The embedded server keeps running in every mode; only what /mcp trusts changes.