The source code for this demo is available in the apps/nextjs directory of this repository.
Own Your Data and Your Authentication
With @mcpauth/auth, you host the server, you own the data. No separate authorization server. No vendor lock-in.
Required for Modern MCP Clients
Major MCP clients like OpenAI's ChatGPT require OAuth 2.0 for authenticating users and authorizing access to tools and resources. @mcpauth/auth provides the compliant, secure server you need to integrate with these modern clients.
Seamlessly Integrate Your Existing Auth
The biggest challenge with adopting a new authentication system is integrating it with your existing user management. @mcpauth/auth solves this with a single, powerful function: authenticateUser.
This function allows you to plug in any existing authentication logic. Whether your users are authenticated via a session cookie, a bearer token, or an external system, you can validate them and link them to the OAuth flow with just a few lines of code.
For example, if you're using @auth/express for session management, your implementation is as simple as this:
authenticateUser: async(request: Request)=>{// Grab the user's existing session from a cookieconstsession=awaitgetSession(request,authConfig);// Return the user object if they are authenticated, or null if notreturn(session?.userasOAuthUser)??null;},
This flexibility means you can add a compliant MCP OAuth layer to your application without rebuilding your entire authentication stack.
@mcpauth/auth is designed to be adaptable to your existing stack. Here's a summary of our currently supported frameworks and database stores:
Type
Supported
Notes
Framework
Next.js, Express
Adapters provide seamless integration with popular Node.js frameworks.
Database
Prisma, Drizzle
Stores handle all the database interactions for OAuth entities.
These are the basic steps to get started with @mcpauth/auth, regardless of your framework or database.
npm install @mcpauth/auth
2. Configure Environment Variables
Create a .env file at the root of your project and add the following variables.
# The allowed origins for OAuth requests.# Add your development URL and one for MCP InspectorOAUTH_ALLOWED_ORIGIN="http://localhost:3000,http://localhost:6274"# The base URL of your application.BASE_URL="http://localhost:3000" # For Next.js, you might use NEXT_PUBLIC_BASE_URL
# A secret used to sign the state parameter during the OAuth flow.# Generate a secure random string, e.g., `openssl rand -hex 32`INTERNAL_STATE_SECRET=your_internal_state_secret# The private key for signing JWTs.# Generate a secure key, e.g., using `jose newkey -s 256 -t oct`# It should start with "-----BEGIN PRIVATE KEY-----" and end with "-----END PRIVATE KEY-----"OAUTH_PRIVATE_KEY=your_oauth_private_key
Next, you'll need to configure the adapter for your specific framework.
Here's how to set up @mcpauth/auth in an Express application.
1. Create mcpAuth.config.ts
Create a configuration file for the MCP Auth provider.
// src/config/mcpAuth.config.tsimport{McpAuth}from"@mcpauth/auth/adapters/express";// Import your chosen store adapterimport{DrizzleAdapter}from"@mcpauth/auth/stores/drizzle";import{db}from"./db.js";// Assuming you have an auth setup (e.g., @auth/express)import{authConfig}from"./auth.config.js";importtype{OAuthUser}from"@mcpauth/auth";import{Request}from"express";import{getSession}from"@auth/express";exportconstmcpAuthConfig={adapter: DrizzleAdapter(db),// Or PrismaAdapter(db)issuerUrl: process.env.BASE_URL||"http://localhost:3000",issuerPath: "/api/oauth",serverOptions: {accessTokenLifetime: 3600,// 1 hourrefreshTokenLifetime: 1209600,// 14 daysallowBearerTokensInQueryString: true,},authenticateUser: async(request: Request)=>{constsession=awaitgetSession(request,authConfig);return(session?.userasOAuthUser)??null;},signInUrl: (request: Request,callbackUrl: string)=>{// Redirect user to your sign-in pagereturn"/api/auth/signin";},};exportconstmcpAuth=McpAuth(mcpAuthConfig);
2. Set up the OAuth routes
In your main application file (e.g., app.ts or server.ts), use the mcpAuth handler as middleware.
// app.tsimport{mcpAuth}from'./config/mcpAuth.config.js';// ... other app setupapp.use("/api/oauth/",mcpAuth);app.use("/.well-known/*",mcpAuth);// ... other routes and middleware
Here’s how to set up @mcpauth/auth in your Next.js project.
Create a file, for example, at lib/oauth.ts, to initialize the OAuth provider.
// lib/oauth.tsimport{McpAuth}from"@mcpauth/auth/adapters/next";// Import your chosen store adapterimport{DrizzleAdapter}from"@mcpauth/auth/stores/drizzle";import{db}from"./db";// assuming you have a NextAuth setupimport{authasnextAuth}from"./auth";importtype{OAuthUser}from"@mcpauth/auth";import{NextRequest}from"next/server";exportconst{ handlers, auth }=McpAuth({adapter: DrizzleAdapter(db),// Or PrismaAdapter(db)issuerUrl: process.env.NEXT_PUBLIC_BASE_URL||"http://localhost:3000",issuerPath: "/api/oauth",serverOptions: {accessTokenLifetime: 3600,refreshTokenLifetime: 1209600,allowBearerTokensInQueryString: true,},authenticateUser: async(request: NextRequest)=>{constsession=awaitnextAuth();return(session?.userasOAuthUser)??null;},// optional, for customizing the look and feel of the sign-in pagesignInUrl: (request: NextRequest,callbackUrl: string)=>{return"/api/auth/signin";},});
2. Set up the OAuth routes
Create a file at app/api/oauth/[...route]/route.ts to handle OAuth requests.
// app/api/oauth/[...route]/route.tsimport{handlers}from"@/lib/oauth"// Adjust path to your oauth.tsexportconst{GET,POST,OPTIONS}=handlers
3. Configure Next.js rewrites
Add the following to your next.config.js file to serve .well-known endpoints.
Use the auth function from your oauth.ts file to protect your MCP API route.
// app/api/mcp/[...transport]/route.tsimport{createMcpHandler}from"@vercel/mcp-adapter";import{NextRequest,NextResponse}from"next/server";import{authasmcpAuth}from"@/lib/oauth";// Adjust path to your oauth.tsconsthandler=async(req: NextRequest)=>{constsession=awaitmcpAuth(req);if(!session){returnNextResponse.json({error: "unauthorized"},{status: 401,headers: {"Content-Type": "application/json"}});}constmcpHandler=createMcpHandler({// ... your MCP configuration});returnmcpHandler(req);};export{handlerasGET,handlerasPOST};
This library uses adapters to connect to different databases.
@mcpauth/auth provides a DrizzleAdapter.
npm install drizzle-orm pg # or your preferred driver
npm install -D drizzle-kit
// In your oauth.ts or mcpAuth.config.tsimport{DrizzleAdapter}from"@mcpauth/auth/stores/drizzle";import{db}from"./db";// your drizzle instance// ...adapter: DrizzleAdapter(db),// ...
You will need to add the following tables to your Drizzle schema. This example is for Postgres.
// In your oauth.ts or mcpAuth.config.tsimport{PrismaAdapter}from"@mcpauth/auth/stores/prisma";import{db}from"./db";// your prisma client instance// ...adapter: PrismaAdapter(db),// ...
If you are using the PrismaAdapter, you will need to add the following models to your prisma/schema.prisma file: