Skip to main content
Glama
Next.js Supabase MCP Server

Next.js Supabase MCP Server

README.md
# 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

```text
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
```

---

## 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`:

```sql
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
```bash
pnpm install
```

### 2. Configure environment variables
```bash
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
```bash
pnpm dev
```

---

## Connecting Clients

### Claude Code (HTTP transport)
With static API key:
```bash
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):
```bash
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:
```bash
pnpm typecheck
pnpm lint
pnpm test
pnpm build
```

## License

[MIT](./LICENSE)