Build and authenticate an MCP server with Clerk
Example repository
Build an MCP server that lets clients access your application's data with Clerk OAuth. Clerk handles sign-in and consent; your server verifies and authorizes tool calls. Complete your framework's Clerk quickstart first, and use Node.js 22.18 or later.
Configure Clerk for your MCP server
Pick the Clerk application and instance your MCP server will use. For local development, use http://localhost:3000/mcp on a development instance. For a hosted server, use its full HTTPS endpoint, such as https://mcp.example.com/mcp.
Use the same URL in Clerk setup, client configuration, metadata, and token audience checks. These examples serve /mcp without a query or trailing slash.
- In the Clerk Dashboard, open Agents → MCP servers and select Add MCP server, or Get started if this is your first server.
- Enter the full endpoint in MCP URL and select Add server.
- If the server's page shows Copy prompt, use it with your coding agent. Otherwise, continue below.
Connect your agent to Clerk's MCP server. Use this path for a hosted HTTPS endpoint; add local development URLs through the Dashboard.
- Use
list_applicationsorget_applicationto identify your target application and instance. - Call
configure_mcp_serverwithapplication_id,instance(development,production, or an instance ID), andresource_url. Passdry_run: trueto preview without saving. - Review the changes and blockers, then call it again with the same inputs and without
dry_runto save. - Use the returned
setup_promptor the implementation below.
To replace a saved URL, also pass replace_resource_url with the old URL.
OAuth settings
When you add your first MCP server, Clerk turns on audience claims (aud). The Dashboard turns on Client ID Metadata Documents (CIMD) support if you select Allow public clients to connect; configure_mcp_server turns it on for the first server. Existing client restrictions and the instance-wide Proof Key for Code Exchange (PKCE) setting stay unchanged.
If your instance already has MCP servers, in the Clerk Dashboard, navigate to the OAuth applications page and select the Settings tab. Turn on Include Audience if it's off. If a client's token has no aud claim or a different audience, reauthorize the client with the full MCP server URL as its resource to get a token for this server.
This example requires only profile. Set default scopes if your client doesn't request scopes.
Install dependencies
npm install @clerk/mcp-tools @clerk/nextjs mcp-handler @modelcontextprotocol/server zodpnpm add @clerk/mcp-tools @clerk/nextjs mcp-handler @modelcontextprotocol/server zodyarn add @clerk/mcp-tools @clerk/nextjs mcp-handler @modelcontextprotocol/server zodbun add @clerk/mcp-tools @clerk/nextjs mcp-handler @modelcontextprotocol/server zodThe quickstart already added @clerk/nextjs. Install it again to update it to 7.9.5 or later. The token verification below needs that version, because earlier versions let opaque access tokens, and JWT access tokens without an aud claim, pass the audience check. This guide requires @clerk/mcp-tools 1.0.0 or later and @modelcontextprotocol/server 2.3.0 or later.
For Hono, @clerk/mcp-tools/hono has the same mcpAuth() and protectedResourceMetadataHandler(). See the @clerk/mcp-tools/hono README.
If you're upgrading an existing server from @clerk/mcp-tools 0.9, see Upgrade to @clerk/mcp-tools 1.0.
Create your MCP server
The MCP route and its metadata route share options, so create lib/mcp.ts to hold them. Set resourceUrl to the exact endpoint your clients use. It's read from the MCP_RESOURCE_URL environment variable, so each environment can set its own URL. In a project with a src/ directory, put this file in src/lib/ and the route files below in src/app/ instead.
import type { McpAuthOptions } from '@clerk/mcp-tools/next'
const resourceUrl = process.env.MCP_RESOURCE_URL
if (!resourceUrl) throw new Error('MCP_RESOURCE_URL is not set')
export const mcpAuthOptions = {
resourceUrl,
requiredScopes: ['profile'],
} satisfies McpAuthOptionsAdd the variable to your .env file with the localhost value for local development:
MCP_RESOURCE_URL=http://localhost:3000/mcpWhen you deploy, set MCP_RESOURCE_URL to your HTTPS endpoint, such as https://mcp.example.com/mcp. lib/mcp.ts throws if it's unset instead of falling back to localhost.
Then create app/mcp/route.ts. Import withClerkMcpAuth() from @clerk/mcp-tools/next, not mcp-handler. It takes options instead of a verifier function.
withClerkMcpAuth() accepts only issued by your instance. It checks the token's signature and expiry, and that its aud claim includes resourceUrl. It rejects tokens without an audience or without every scope in requiredScopes. A rejected request gets a WWW-Authenticate challenge that points clients to the protected resource metadata route below. On a 401, the challenge also names requiredScopes as the scopes to request. withClerkMcpAuth() verifies tokens with clerkClient from @clerk/nextjs/server, which reads the CLERK_SECRET_KEY and NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY the quickstart added to your environment.
Tools read the verified token from ctx.http?.authInfo. It holds the token's clientId, scopes, and the user ID in extra.userId. isClerkAuthInfo() narrows its type, so extra.userId is typed as a string. withClerkMcpAuth() also marks the result as verified by Clerk, which the create_browser_session tool requires.
import { isClerkAuthInfo, withClerkMcpAuth } from '@clerk/mcp-tools/next'
import { createMcpHandler } from 'mcp-handler'
import { mcpAuthOptions } from '@/lib/mcp'
const handler = createMcpHandler((server) => {
server.registerTool(
'whoami',
{ description: 'Gets the ID of the Clerk user who authorized this request' },
async (ctx) => {
const authInfo = ctx.http?.authInfo
if (!isClerkAuthInfo(authInfo)) {
return { content: [{ type: 'text', text: 'Not signed in with Clerk.' }], isError: true }
}
// `authInfo.token` is the bearer token, so return only the user ID that `withClerkMcpAuth()` puts in `extra`
return { content: [{ type: 'text', text: authInfo.extra.userId }] }
},
)
})
const authHandler = withClerkMcpAuth(handler, mcpAuthOptions)
export { authHandler as GET, authHandler as POST, authHandler as DELETE }Return only the fields the granted scopes allow. Add your application's permission checks before accessing other protected data. To ask for more scopes only when a tool needs them, see Request more scopes with step-up authorization.
Your server is discoverable by default. A client without a token can connect and list whoami, with its name, description, and input schema, but a call to it gets the 401 challenge that starts sign-in. To require a token for every request, add discoverable: false to mcpAuthOptions. To let clients call some tools before they sign in, see Allow public access to your MCP server before sign-in.
Expose public OAuth metadata
Create the protected resource metadata route with the same mcpAuthOptions. Its resource then matches the resourceUrl that withClerkMcpAuth() checks, and its scopes_supported lists the requiredScopes.
import { metadataCorsHandler, protectedResourceMetadataHandler } from '@clerk/mcp-tools/next'
import { mcpAuthOptions } from '@/lib/mcp'
const handler = protectedResourceMetadataHandler(mcpAuthOptions)
const corsHandler = metadataCorsHandler()
export { handler as GET, corsHandler as OPTIONS }Clients that follow RFC 9728 find Clerk's authorization server from the authorization_servers in this metadata. To also support older clients that look for /.well-known/oauth-authorization-server on your server's origin, add a route that relays Clerk's authorization server metadata:
import { authorizationServerMetadataHandler, metadataCorsHandler } from '@clerk/mcp-tools/next'
const handler = authorizationServerMetadataHandler()
const corsHandler = metadataCorsHandler()
export { handler as GET, corsHandler as OPTIONS }Keep the .well-known routes public and withClerkMcpAuth() on /mcp. The MCP route doesn't need clerkMiddleware() or <ClerkProvider>, because withClerkMcpAuth() verifies the bearer token itself. If your app uses clerkMiddleware() for its other pages, leave these routes out of auth.protect(): /mcp, /.well-known/oauth-protected-resource/mcp, and /.well-known/oauth-authorization-server if you added it. MCP clients then get the challenge and metadata from these handlers instead of a sign-in redirect. Start your app with npm run dev; for a production build, run npm run build followed by npm run start.
Neither withClerkMcpAuth() nor mcp-handler sets CORS headers on /mcp. Browser-based MCP clients, such as MCP Inspector, can't read the 401 challenge without them. To support those clients, add the CORS headers and preflight handler from the @clerk/mcp-tools/next README to app/mcp/route.ts. The recipe allows the 2026-07-28 transport headers, including Mcp-Method and Mcp-Name.
Verify authentication and authorization
Start your server, then connect an MCP client. Sign in, approve access, and call whoami, which returns your Clerk user ID.
For a hosted server, the Clerk Dashboard runs checks automatically and tells you if your MCP server isn't configured correctly. Fix any reported issues, then select Re-test connection.
For localhost, use a client on the same machine. Dashboard checks and cloud connectors require a hosted HTTPS endpoint.
How verification fails
A token Clerk rejects gets the 401 or 403 challenge described above, but not every failure is a rejection.
If Clerk can't verify an opaque access token at all, such as during an outage, when Clerk rate-limits your server, or with an invalid , withClerkMcpAuth() answers with a JSON {"error":"server_error"} and no challenge, so clients keep their tokens. The status is the 429 or 5xx that Clerk reported, or 500. It logs the McpAuthError with console.error instead of throwing it, so Next.js's onRequestError doesn't see it.
A JWT access token gets the same server error when Clerk can't load its signing keys. With current @clerk/backend releases, 3.31.3 and earlier, that happens only when Clerk answers the signing keys request with an error status and a JSON body. Those releases treat any other signing key failure as an invalid signature, so the client gets the 401 challenge instead. Other failures include an invalid Secret Key, a network error, or an error page that isn't JSON.
Verify tokens yourself
withClerkMcpAuth() and mcpAuth() verify tokens for you, and the tools in @clerk/mcp-tools/tools, create_browser_session and submit_feedback, trust only the auth info they produce. If you verify tokens in your own code instead, call authenticateRequest() with acceptsToken: 'oauth_token' and your resourceUrl as the audience, then convert the request state with toClerkAuthInfo(). Without the audience check, any OAuth access token your instance issued passes, whichever OAuth application it was issued to. auth({ acceptsToken: 'oauth_token' }) alone doesn't check the audience.
The following example verifies the bearer token of a request to /mcp:
import { toClerkAuthInfo } from '@clerk/mcp-tools/next'
import { clerkClient } from '@clerk/nextjs/server'
import { mcpAuthOptions } from '@/lib/mcp'
export async function verifyToken(req: Request) {
const clerk = await clerkClient()
const requestState = await clerk.authenticateRequest(req, {
acceptsToken: 'oauth_token',
audience: mcpAuthOptions.resourceUrl,
})
if (!requestState.isAuthenticated) return undefined
return toClerkAuthInfo(requestState.toAuth(), requestState.token)
}The MCP SDK's step-up challenge reads resourceMetadataUrl from the auth info. Add it to the object that toClerkAuthInfo() returned with Object.assign(authInfo, { resourceMetadataUrl }). Set resourceMetadataUrl to the full URL of your protected resource metadata route, such as http://localhost:3000/.well-known/oauth-protected-resource/mcp. Don't copy the object, such as with { ...authInfo, resourceMetadataUrl }. A copy fails isClerkAuthInfo(), so create_browser_session refuses every call with the not_authenticated error code, and submit_feedback stops attaching the user and client IDs to reports.
Feedback
Last updated on