Better Auth

Add secure authentication to your MCP server using Better Auth and PostgreSQL

Overview

The Better Auth plugin provides comprehensive authentication for your xmcp server using Better Auth, supporting email/password authentication, OAuth providers, and session management.

Currently supports PostgreSQL as the database provider.

Installation

Install the Better Auth plugin and PostgreSQL dependencies:

Database Setup

Better Auth requires a PostgreSQL database with specific tables for user management, sessions, and OAuth applications.

We recommend Neon for easy PostgreSQL setup, especially with Vercel's storage integration.

Run the following SQL script to create the necessary tables:

Schema generation through Better Auth's CLI is not currently supported. You must run this SQL manually.

Environment Variables

Configure the following environment variables in your .env file:

Generate a strong, random secret for BETTER_AUTH_SECRET. This is used to sign JWT tokens and must be kept secure.

Configuration

Create a middleware.ts file in your xmcp app root directory:

src/middleware.ts

Configuration Options

  • database - PostgreSQL Pool instance for database connections
  • baseURL - Base URL of your app for generating OAuth callback URLs
  • secret - Secret key for signing JWT tokens
  • providers - Authentication provider configuration

Authentication Providers

Email and Password

Enable email/password authentication:

Google OAuth

To enable Google OAuth:

  1. Visit the Google Cloud Console
  2. Create or select a project
  3. Enable the Google+ API
  4. Create OAuth 2.0 credentials
  5. Set authorized redirect URI:
    • Development: http://localhost:3001/auth/callback/google
    • Production: https://yourdomain.com/auth/callback/google

Multiple Providers

You can enable multiple authentication methods simultaneously:

Usage in Tools

Access the authenticated user session in your xmcp tools using getBetterAuthSession:

src/tools/get-user-profile.ts

getBetterAuthSession will throw an error if called outside of a betterAuthProvider middleware context.

Login Page

The authentication UI is automatically generated and available at:

This page handles both sign-in and sign-up functionality based on your provider configuration.

Next Steps

After authentication is configured, users will be prompted to authenticate when establishing a connection to your MCP server.

On this page

One framework to rule them all

    Better Auth | xmcp Documentation