Skip to main content
Glama
Next.js Supabase MCP Server

Next.js Supabase MCP Server

Next.js + Supabase OAuth 2.1 + Streamable HTTP MCP

Production-tested reference architecture for running a stateless remote MCP (Model Context Protocol) server on Next.js App Router with:

  • Stateless Streamable HTTP MCP (/api/mcp) powered by mcp-handler and @modelcontextprotocol/server.

  • Dual Authentication (Supabase Auth OAuth 2.1 JWTs with client_id verification + constant-time API key fallback).

  • RFC 9728 Protected Resource Metadata (/.well-known/oauth-protected-resource and /.well-known/oauth-protected-resource/api/mcp) + WWW-Authenticate challenge headers so clients like Claude Code and Claude Desktop automatically discover the Supabase OAuth server.

  • Restrictive RLS Isolation (supabase/migrations/0001_oauth_clients_blocked.sql) preventing external OAuth tokens from querying PostgREST tables directly.

  • Serverless Postgres Dead-Socket Recovery (createResilientDb / createAppDb) wrapping drizzle-orm + postgres so suspended serverless instances recover cleanly from hung TCP sockets instead of hitting function timeouts.


Architecture Overview

src/
├── app/
│   ├── .well-known/oauth-protected-resource/
│   │   ├── metadata.ts          # RFC 9728 metadata + CORS helpers
│   │   ├── route.ts             # GET /.well-known/oauth-protected-resource
│   │   └── api/mcp/route.ts     # GET /.well-known/oauth-protected-resource/api/mcp
│   ├── api/mcp/route.ts         # Stateless Streamable HTTP MCP endpoint
│   ├── layout.tsx
│   └── page.tsx
├── lib/
│   ├── auth/
│   │   ├── fetch-timeout.ts     # AbortController timeout wrapper for Auth fetches
│   │   ├── oauth-token.ts       # Bearer/API-key extraction + OAuth JWT claim guard
│   │   └── supabase-oauth.ts    # Supabase `auth.getClaims()` verification
│   ├── db/
│   │   ├── client.ts            # PgBouncer-safe Drizzle pool defaults + createAppDb
│   │   └── resilient-db.ts      # Proxy-based query/transaction deadline & pool reset
│   ├── mcp/
│   │   └── tools.ts             # Example Zod-validated MCP tools (`whoami`, `echo`)
│   └── env.ts
└── ...
supabase/
└── migrations/
    └── 0001_oauth_clients_blocked.sql

Related MCP server: App MCP

Why These Patterns Matter in Production

1. Restrictive RLS for Supabase OAuth 2.1 Clients

Tokens issued by Supabase Auth's OAuth 2.1 server carry role = 'authenticated' and a client_id claim. Without a restrictive policy, any MCP client holding an OAuth token could bypass /api/mcp and call Supabase PostgREST directly with full user permissions.

supabase/migrations/0001_oauth_clients_blocked.sql attaches a RESTRICTIVE policy to every RLS-enabled table in public:

using ((auth.jwt() ->> 'client_id') is null)
with check ((auth.jwt() ->> 'client_id') is null)

Normal browser sessions (client_id is null) and direct server-side Postgres connections (DATABASE_URL) keep working as expected, while OAuth client JWTs are forced through /api/mcp.

2. client_id Enforcement on the MCP Server

oauthIdentityFromClaims() in src/lib/auth/oauth-token.ts explicitly requires role === 'authenticated', a valid UUID sub, and a non-empty client_id. Regular website session cookies/JWTs cannot be replayed as OAuth API credentials.

3. Serverless Postgres Dead-Socket Recovery (createResilientDb)

In serverless runtimes (such as Vercel), function instances can be frozen between invocations. When a TCP socket in the postgres pool dies silently during freeze, an in-flight query can hang until the entire serverless function hits its 300s timeout.

createResilientDb wraps postgres (unsafe and begin) with a hard per-query/transaction deadline (15s by default):

  • If a query stalls past the deadline, it rejects with QueryDeadlineError.

  • The broken pool is discarded once (safe under concurrent stalled queries) and closed gracefully in the background.

  • The next query lazily opens a fresh pool while keeping singleton repository references working transparently.


Quick Start

1. Install dependencies

pnpm install

2. Configure environment variables

cp .env.example .env.local

Update .env.local:

  • NEXT_PUBLIC_SITE_URL: Public origin of your Next.js app (e.g. http://localhost:3000 or https://your-app.com).

  • NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY: Your Supabase project credentials.

  • DATABASE_URL: Supabase transaction pooler connection string (port 6543, ?prepare=false handled in DB_POOL_OPTIONS).

  • MCP_API_KEYS: Comma-separated static API keys for local testing or CI.

3. Enable Supabase OAuth 2.1 & apply the RLS migration

  1. In your Supabase Dashboard, enable the OAuth 2.1 Server (with Dynamic Client Registration if connecting Claude Desktop/Code without pre-registered client IDs) and point the consent redirect URL to your consent route.

  2. Apply supabase/migrations/0001_oauth_clients_blocked.sql to your database.

4. Run locally

pnpm dev

Connecting Clients

Claude Code (HTTP transport)

With static API key:

claude mcp add --transport http local-mcp http://localhost:3000/api/mcp \
  --header "Authorization: Bearer demo_key_replace_me"

With OAuth 2.1 discovery (when deployed over HTTPS with Supabase OAuth enabled):

claude mcp add --transport http my-remote-mcp https://your-app.com/api/mcp

When /api/mcp responds with 401 and WWW-Authenticate: Bearer resource_metadata="https://your-app.com/.well-known/oauth-protected-resource", Claude Code discovers authorization_servers pointing to ${SUPABASE_URL}/auth/v1.

Claude Desktop

Add a remote MCP server pointing to https://your-app.com/api/mcp via custom connectors (OAuth 2.1 dynamic registration).


Verification

Run the full check suite:

pnpm typecheck
pnpm lint
pnpm test
pnpm build

License

MIT

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Exposes your application's resources and tools as an MCP server using Supabase Auth, Postgres, and Row Level Security, allowing authorized users to connect via compatible MCP clients.
      478 npm
      3
      MIT
    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables turning an existing Supabase database and Edge Functions into an MCP server, exposing selected tables with Row Level Security and Edge Functions as tools for use in MCP clients.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables adding a stateless MCP server to a Next.js App Router application, supporting tools, prompts, and resources over Streamable HTTP and the current MCP protocol.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Publishes a stateless MCP endpoint on a Next.js App Router route that speaks Streamable HTTP and runs on any serverless host, exposing example tools (add, get_time, whoami) that clients like Claude Code, Cursor, and MCP Inspector can call. A loopback client forwards per-request context, such as a caller id or a user-supplied API key, in a header so tools can act for that one request without storing anything.
      MIT