Integrations

Protect an MCP server with Better Auth

Add OAuth authorization to an HTTP MCP server with Nuxt Better Auth.

Let people connect an MCP client to your Nuxt app, sign in with their existing account, and choose what the client can access.

This guide adds an authenticated HTTP MCP endpoint at /mcp. Better Auth handles authorization. Your MCP server handles tools, resources, and prompts. You can use this setup with different MCP implementations; the example uses the official TypeScript SDK.

Before you start

You need a Nuxt app with Nuxt Better Auth installed, a working login page, and a database-backed auth setup. OAuth clients, consent, authorization codes, and signing keys need persistent storage.

The example uses Nuxt 4 with Nitro v2, the default /api/auth auth path, and app.baseURL: '/'. It targets the MCP 2026-07-28 protocol. On Nuxt with Nitro v3, use the equivalent server imports and Web Request adapter for that runtime.

This guide covers remote HTTP MCP servers. A local MCP server connected over standard input and output uses a different transport and does not use this HTTP authorization flow.

1. Install the packages

Install the Better Auth plugins and an MCP server implementation:

pnpm add better-auth@1.7.14 @better-auth/mcp@1.7.14 @better-auth/cimd@1.7.14 @better-auth/oauth-provider@1.7.14 @modelcontextprotocol/server@2.4.0 zod

These versions provide the APIs used below. Keep the Better Auth packages on matching versions. If you use NuxtHub schema generation, update its CLI too:

pnpm add -D auth@1.7.14

Set your app's public URL. Use your HTTPS origin in production:

.env
NUXT_PUBLIC_SITE_URL=http://localhost:3000

Keep your existing auth secret. Adding MCP does not require a new one.

2. Configure Better Auth

Add the plugins to your existing configuration. Preserve your database adapter, sign-in methods, and other plugins.

server/auth.config.ts
import { cimd } from '@better-auth/cimd'
import { fetchClientMetadataResource } from '@better-auth/cimd/node'
import { mcp } from '@better-auth/mcp'
import { defineServerAuth } from '@nuxtjs/better-auth/config'
import { jwt } from 'better-auth/plugins'
import { z } from 'zod'

export default defineServerAuth(({ runtimeConfig }) => {
    const config = z.object({
        public: z.object({ siteUrl: z.url() }),
    }).parse(runtimeConfig)
    const resource = new URL('/mcp', config.public.siteUrl).href

    return {
        plugins: [
            jwt(),
            mcp({
                loginPage: '/login',
                consentPage: '/consent',
                resource,
                scopes: ['openid', 'profile', 'mcp:tools'],
                resources: [{
                    identifier: resource,
                    allowedScopes: ['openid', 'profile', 'mcp:tools'],
                }],
            }),
            cimd({
                fetchClientMetadataResource,
                metadataProfile: 'mcp-2026-07-28',
            }),
        ],
    }
})

jwt() supplies the signing keys. mcp() issues access tokens bound to your /mcp URL. cimd() lets compatible clients identify themselves with a Client ID Metadata Document.

The metadata fetcher above is for Node.js deployments. For Cloudflare Workers or another runtime, supply the CIMD transport required by Better Auth.

mcp() includes the OAuth provider. Register it once; a separate oauthProvider() plugin would duplicate the provider.

Apply the database schema changes before continuing. With NuxtHub, restart the app to regenerate the schema and follow the schema migration workflow. With a custom adapter, use your existing Better Auth migration workflow.

Support clients that use dynamic registration

Some clients still require Dynamic Client Registration instead of Client ID Metadata Documents. To support those clients, add these options to mcp():

allowDynamicClientRegistration: true,
allowUnauthenticatedClientRegistration: true,
clientRegistrationDefaultApplicationType: 'infer',

This exposes public client registration. Enable it for the clients you intend to support. The infer setting handles clients that omit their application type when registering native or loopback callbacks.

Register the OAuth provider's client companion:

app/auth.config.ts
import { oauthProviderClient } from '@better-auth/oauth-provider/client'
import { defineClientAuth } from '@nuxtjs/better-auth/config'

export default defineClientAuth({
    plugins: [oauthProviderClient()],
})

When Better Auth sends someone to /login, it includes a signed OAuth query. The companion plugin carries that query into sign-in requests so Better Auth can resume authorization.

Keep the query on the login page. During this flow, let Better Auth's redirect response choose the next page. A fixed redirect to your dashboard interrupts authorization.

For example, the email sign-in handler in your existing login page can call the client directly:

const client = useAuthClient()

async function signIn(email: string, password: string) {
    if (!client)
        return
    const result = await client.signIn.email({ email, password })
    if (result.error)
        throw new Error(result.error.message)
}

Show the request before accepting it

Create an endpoint that verifies the signed query and returns the client and requested access. The signature check must run on the server.

server/api/mcp-consent.get.ts
import { verifyOAuthQueryParams } from '@better-auth/oauth-provider'
import { createError, defineEventHandler, getValidatedQuery, setHeader, toWebRequest } from 'h3'
import { z } from 'zod'

export default defineEventHandler(async (event) => {
    setHeader(event, 'Cache-Control', 'no-store')
    await requireUserSession(event)
    const { oauth_query: query } = await getValidatedQuery(event, z.object({
        oauth_query: z.string().min(1).max(16000),
    }).parse)
    const auth = await ensureServerAuth(event)
    const { secret } = await auth.$context

    if (!await verifyOAuthQueryParams(query, secret))
        throw createError({ statusCode: 400, statusMessage: 'Invalid or expired authorization request' })

    const params = new URLSearchParams(query)
    const clientId = params.get('client_id')
    if (!clientId)
        throw createError({ statusCode: 400, statusMessage: 'Missing client ID' })

    const client = await auth.api.getOAuthClientPublic({
        headers: toWebRequest(event).headers,
        query: { client_id: clientId },
    })

    return {
        clientId,
        clientName: client.client_name ?? clientId,
        scopes: params.get('scope')?.split(' ').filter(Boolean) ?? [],
        claims: params.get('claims'),
    }
})

Render that request on a consent page. Keep Allow and Deny available; neither action runs automatically.

app/pages/consent.vue
<script setup lang="ts">
definePageMeta({ auth: 'user' })

const client = useAuthClient()
const oauthQuery = useRequestURL().search.slice(1)
const { data: request, error: requestError } = await useFetch('/api/mcp-consent', {
    query: { oauth_query: oauthQuery },
})
const pending = shallowRef(false)
const actionError = shallowRef('')

async function respond(accept: boolean) {
    if (!client)
        return
    pending.value = true
    actionError.value = ''
    try {
        const result = await client.oauth2.consent({ accept })
        if (result.error)
            actionError.value = result.error.message ?? 'Could not save your choice.'
    }
    catch {
        actionError.value = 'Could not save your choice. Try again.'
    }
    finally {
        pending.value = false
    }
}
</script>

<template>
    <main>
        <p v-if="requestError">This authorization request is invalid or expired. Reconnect from your MCP client.</p>
        <section v-else-if="request">
            <h1>Allow {{ request.clientName }} to access your account?</h1>
            <p>Client ID: {{ request.clientId }}</p>
            <ul>
                <li v-for="scope in request.scopes" :key="scope">{{ scope }}</li>
            </ul>
            <pre v-if="request.claims">{{ request.claims }}</pre>
            <button :disabled="pending" @click="respond(true)">Allow</button>
            <button :disabled="pending" @click="respond(false)">Deny</button>
            <p v-if="actionError" role="alert">{{ actionError }}</p>
        </section>
    </main>
</template>

Better Auth validates the consent submission and redirects to the client's registered callback. Use that provider-controlled response rather than a redirect_uri read from the page query.

For a product consent page, describe each scope in plain language. For example, mcp:tools means "Run this app's MCP tools as you." Display any requested identity claims alongside those scopes.

4. Make discovery reachable

Nuxt Better Auth mounts its auth handler at /api/auth. MCP clients also need public discovery documents under /.well-known.

Forward those requests to the same auth instance:

server/routes/.well-known/[...path].ts
import { assertMethod, defineEventHandler, toWebRequest } from 'h3'

export default defineEventHandler(async (event) => {
    assertMethod(event, ['GET', 'HEAD'])
    const auth = await ensureServerAuth(event)
    const response = await auth.handler(toWebRequest(event))
    const headers = new Headers(response.headers)
    headers.set('Access-Control-Allow-Origin', '*')

    return new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers,
    })
})

If your app already handles /.well-known routes, merge this forwarding into that routing. Keep discovery public, without a session check or a login redirect.

Check the protected resource document:

curl -i http://localhost:3000/.well-known/oauth-protected-resource/mcp

Expect HTTP 200 and a document containing:

{
    "resource": "http://localhost:3000/mcp",
    "authorization_servers": ["http://localhost:3000/api/auth"]
}

Check authorization server discovery too:

curl -i http://localhost:3000/.well-known/oauth-authorization-server/api/auth

Its issuer must be http://localhost:3000/api/auth. The auth base path is part of the issuer.

The wildcard CORS header above applies to public metadata fetched without credentials. Browser clients need it to read discovery from another origin.

5. Protect the MCP endpoint

Create a tool and wrap the MCP transport with requireMcpAuth():

server/routes/mcp.post.ts
import { requireMcpAuth } from '@better-auth/mcp'
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'
import { defineEventHandler, toWebRequest } from 'h3'
import { z } from 'zod'

const transport = createMcpHandler(() => {
    const server = new McpServer({ name: 'my-nuxt-app', version: '1.0.0' })
    server.registerTool('echo', {
        description: 'Echo a message',
        inputSchema: z.object({ message: z.string() }),
    }, async ({ message }) => ({
        content: [{ type: 'text', text: message }],
    }))
    return server
}, { legacy: 'reject' })

export default defineEventHandler(async (event) => {
    const auth = await ensureServerAuth(event)
    const resource = new URL('/mcp', useRuntimeConfig(event).public.siteUrl).href
    const handler = requireMcpAuth(auth, request => transport.fetch(request), {
        resource,
        requiredScopes: ['mcp:tools'],
    })

    return handler(toWebRequest(event))
})

The wrapper verifies the token's signature, issuer, audience, and expiry. Missing or invalid credentials receive 401 with a WWW-Authenticate discovery challenge. A valid token missing mcp:tools receives 403 with an insufficient_scope challenge.

Keep browser session protection off /mcp. The MCP client authenticates with an access token on every request. A page redirect or a cookie session check would prevent that flow.

When a tool reads or changes application data, use the wrapper's second callback argument to obtain verified token claims. Enforce user and tenant access in the tool. An allowed scope does not grant access to every user's records.

Allow browser clients to call /mcp

The discovery header in step 4 does not configure the MCP endpoint. If a browser client connects from another origin, configure CORS for /mcp too:

  • Allow the browser client's origin and handle its OPTIONS preflight before authentication.
  • Allow POST and the Authorization, Content-Type, MCP-Protocol-Version, Mcp-Method, and Mcp-Name request headers. Allow any Mcp-Param-* headers your tools declare.
  • Expose WWW-Authenticate so the client can read authorization challenges.
  • If you support DPoP, also allow the DPoP request header and expose DPoP-Nonce.

Configure origin validation separately for the MCP transport. An origin allowlist controls which incoming origins you accept; CORS headers control which responses a browser can read.

6. Connect a client

First, check the unauthenticated response:

curl -i -X POST http://localhost:3000/mcp \
    -H 'Content-Type: application/json' \
    -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

Expect 401 and a WWW-Authenticate header containing resource_metadata and the mcp:tools scope. A 302 to /login means browser session protection is intercepting the MCP route.

Add http://localhost:3000/mcp to an MCP client that supports the 2026-07-28 protocol and OAuth authorization. The client must be able to reach your localhost; a hosted client needs a public HTTPS URL instead.

Connect while signed out. Your browser opens the login page, then the consent page. Check the client and requested scopes, choose Allow, and call echo. The result contains the message you supplied.

Repeat the connection with Deny. The client must receive an authorization error and remain unable to call the tool.

Use another MCP implementation

Keep the Better Auth configuration, login and consent pages, and discovery routes. Replace the protocol handler in step 5.

For an implementation that accepts Web Request objects and returns Web Response objects, wrap its handler with requireMcpAuth() the same way. If the implementation already verifies OAuth tokens, configure its verifier with:

  • Issuer: http://localhost:3000/api/auth.
  • Audience: http://localhost:3000/mcp.
  • JWKS: http://localhost:3000/api/auth/jwks.
  • Required scope: mcp:tools.

Use the corresponding HTTPS URLs in production. Compare issuer and audience as exact identifiers, including their paths and trailing slashes.

okmcp's Better Auth example shows this configuration with its own token validator and per-tool scopes. Check its installation instructions and release availability before choosing that implementation.

If the MCP server runs in another process or service, use createMcpProtectedRequestHandler() with explicit issuer, audience, and JWKS settings. Publish protected resource metadata for that server's resource URL.

Choose when access ends

Local JWT verification accepts an otherwise valid token until it expires. Signing out of the Nuxt app does not immediately invalidate that token at the MCP endpoint.

If MCP access must end when the session ends, use Better Auth's authenticated token introspection endpoint and check that the response is active and its audience matches your resource. Any introspection cache adds a delay before revocation takes effect.

Troubleshoot a connection

What you seeWhat to check
Discovery returns 404Forward /.well-known requests to auth.handler. The /api/auth catch-all alone does not receive root discovery requests.
Discovery works in curl but fails in a browserCheck metadata CORS. An MCP origin allowlist does not add response headers.
Sign-in lands on your dashboardPreserve the signed OAuth query and let Better Auth continue the authorization flow.
The client cannot registerCheck CIMD support. Enable DCR explicitly for clients that require it.
A newly issued token gets 401Compare the issuer and resource URL exactly. Include /api/auth in the default issuer.
A token gets 403 insufficient_scopeRequest and approve mcp:tools.
The MCP transport rejects the requestCheck the client's protocol version. This example rejects the 2025 protocol.

Read the Better Auth MCP documentation for provider options and the MCP authorization specification for client requirements.