Clerk
The Clerk plugin provides authentication for your MCP server using Clerk's OAuth system.
Installation
Install the Clerk plugin:
Clerk Setup
Before integrating the plugin, configure your Clerk application:
- Navigate to your Clerk Dashboard
- Create a new application (or use an existing one)
- Go to Configure and access to API Keys to get the following values:
- Secret Key (
sk_...) - Frontend API URL (
your-app.clerk.accounts.dev)
- Secret Key (
- Click on Development, enter to OAuth Applications and enable Dynamic Client Registration
Environment Variables
Create a .env file in the root of your project and configure the following environment variables:
For production, the BASE_URL should be replaced with your deployed server URL.
Set up the Provider
Create a middleware.ts file in your xmcp app's src directory and import the provider from the package:
Configuration Options
secretKey: Clerk Secret KeyclerkDomain: Clerk Frontend domainbaseURL: Base URL of your MCP serverscopes: (Optional) OAuth scopes to request (default:['profile', 'email'])docsURL: (Optional) URL to your MCP server's API documentation
Get a user session
Access the authenticated user in your xmcp tools using getSession:
Example: Greet the user with their Clerk identity
Get user details
Access the authenticated user in your xmcp tools using getUser:
Example: Get user details
Access the client
The getClient() function gives you access to the full Clerk Backend SDK, allowing you to leverage all Clerk features in your MCP tools.
Example: Retrieve an Organization
Troubleshooting
Missing Configuration Errors
If you see "[Clerk] Missing required config: ..." at startup:
- Ensure all required environment variables are set (
CLERK_SECRET_KEY,CLERK_DOMAIN,BASE_URL) - Check your
.envfile is being loaded correctly
Session or Client Not Initialized
If getSession(), getUser(), or getClient() throws "... not initialized":
- Ensure
clerkProvideris exported as default frommiddleware.ts - Ensure the tool is called on a route under
/mcp/* - Don't call these functions at module load time only inside tool handlers
Token Expired Errors
Access tokens are short-lived. If you see token_expired errors:
- MCP clients should automatically refresh tokens
- Users can disconnect and reconnect to get fresh tokens
Invalid Token Errors
If tokens are consistently invalid:
- Verify your
CLERK_SECRET_KEYmatches your Clerk application - Verify your
CLERK_DOMAINmatches your Clerk Frontend API URL - Check that you're using the correct environment (development vs production)
Authentication Service Misconfigured
If you see a 500 error with "Authentication service misconfigured":
- Your
CLERK_SECRET_KEYis invalid or doesn't match your Clerk application - Double-check you're using the correct key for your environment (development vs production)