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/express express@5 @modelcontextprotocol/sdk corspnpm add @clerk/mcp-tools @clerk/express express@5 @modelcontextprotocol/sdk corsyarn add @clerk/mcp-tools @clerk/express express@5 @modelcontextprotocol/sdk corsbun add @clerk/mcp-tools @clerk/express express@5 @modelcontextprotocol/sdk corsThe quickstart already added @clerk/express. Install it again to update it to 2.1.70 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, Express 5 or later, and @modelcontextprotocol/sdk 1.32.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
Create index.ts. Set resourceUrl in mcpAuthOptions 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. Pass the same mcpAuthOptions to mcpAuth() and protectedResourceMetadataHandler(). The metadata's resource then matches the resourceUrl that mcpAuth() checks, and its scopes_supported lists the requiredScopes.
mcpAuth() 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. mcpAuth() verifies tokens with clerkClient from @clerk/express, which reads the and the quickstart added to your environment.
The MCP route doesn't need clerkMiddleware(). mcpAuth() verifies the token itself, so clerkMiddleware() in front of it only verifies each token twice.
Tool callbacks receive the token's clientId and scopes in authInfo, and the user ID in authInfo.extra.userId. isClerkAuthInfo() narrows its type, so extra.userId is typed as a string. mcpAuth() also marks the result as verified by Clerk, which the create_browser_session tool requires.
streamableHttpHandler() takes the SDK's StreamableHTTPServerTransport and gives each request its own MCP server on it. The server is stateless, so streamableHttpHandler() answers any request that isn't a POST with a 405, Allow: POST, and a JSON-RPC Method not allowed. error. Mount it with app.all() behind mcpAuth(), so every request to /mcp reaches mcpAuth() instead of an Express 404. Mount express.json() before mcpAuth(). mcpAuth() reads the parsed body to tell a request that lists your tools from one that calls them, and throws a Clerk error: for a JSON request without a token when the body isn't parsed.
import {
isClerkAuthInfo,
mcpAuth,
type McpAuthOptions,
protectedResourceMetadataHandler,
streamableHttpHandler,
} from '@clerk/mcp-tools/express'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
import express from 'express'
import cors from 'cors'
const resourceUrl = process.env.MCP_RESOURCE_URL
if (!resourceUrl) throw new Error('MCP_RESOURCE_URL is not set')
const mcpAuthOptions = {
resourceUrl,
requiredScopes: ['profile'],
} satisfies McpAuthOptions
const app = express()
// cors reflects requested preflight headers, including Mcp-Method and Mcp-Name
app.use(cors({ exposedHeaders: ['WWW-Authenticate', 'Mcp-Session-Id'] }))
app.use(express.json())
function createServer() {
const server = new McpServer({ name: 'profile-server', version: '1.0.0' })
// `authInfo.token` is the bearer token, so return only the user ID that `mcpAuth()` puts in `extra`
server.registerTool(
'whoami',
{ description: 'Gets the ID of the Clerk user who authorized this request' },
async ({ authInfo }) => {
if (!isClerkAuthInfo(authInfo)) {
return { content: [{ type: 'text', text: 'Not signed in with Clerk.' }], isError: true }
}
return { content: [{ type: 'text', text: authInfo.extra.userId }] }
},
)
return server
}
app.all(
'/mcp',
mcpAuth(mcpAuthOptions),
streamableHttpHandler(createServer, StreamableHTTPServerTransport),
)
app.all(
'/.well-known/oauth-protected-resource/mcp',
protectedResourceMetadataHandler(mcpAuthOptions),
)
app.listen(3000)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.
Clients that follow RFC 9728 find Clerk's authorization server from the authorization_servers in the protected resource metadata. To also support older clients that look for /.well-known/oauth-authorization-server on your server's origin, import authorizationServerMetadataHandler() from @clerk/mcp-tools/express and mount it before app.listen():
app.all('/.well-known/oauth-authorization-server', authorizationServerMetadataHandler())Keep the metadata routes public and mcpAuth() on /mcp. index.ts uses ES module imports, so in package.json, set "type" to "module". If your app already uses CommonJS, leave "type" as it is and name the file index.mts instead. Add the MCP endpoint 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. index.ts throws if it's unset instead of falling back to localhost. Start the app with node --env-file=.env index.ts (or index.mts) so MCP_RESOURCE_URL and the quickstart's Clerk keys are available before imports.
To type-check this example, install the compiler and declarations with npm install -D typescript @types/node @types/express @types/cors, and enable noEmit.
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 , mcpAuth() 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 and doesn't pass it to your error middleware.
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.
To log the 401 and 403 answers, and the 421 a request gets when resourceUrl is a list of URLs and none of them has the request's origin, read res.locals.mcpAuthFailure in a res.on('finish') listener. The server error doesn't set it.
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 { clerkClient } from '@clerk/express'
import { toClerkAuthInfo } from '@clerk/mcp-tools/express'
export async function verifyToken(token: string) {
const resourceUrl = process.env.MCP_RESOURCE_URL
if (!resourceUrl) throw new Error('MCP_RESOURCE_URL is not set')
const requestState = await clerkClient.authenticateRequest(
new Request(resourceUrl, { headers: { authorization: `Bearer ${token}` } }),
{ acceptsToken: 'oauth_token', audience: 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