Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions examples/auth/supabase_auth/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
SUPABASE_PROJECT_URL=https://your-project.supabase.co
BASE_URL=http://localhost:8000
SUPABASE_ANON_KEY=your-anon-key
AUTH_TYPE=MAGIC_LINK
FASTMCP_LOG_LEVEL=DEBUG
MCP_LOG_LEVEL=DEBUG
HTTPX_LOG_LEVEL=DEBUG
104 changes: 104 additions & 0 deletions examples/auth/supabase_auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@

This walks you through getting a full MCP + Supabase Auth setup, using Email Magic Link as the default login method.

It's been tested on the following MCP Clients:

1. FastMCP Client

## Supabase Setup

### Step 1: Enable OAuth with DCR

In the Supabase Authentication settings, this setting must be turned on:

**Enable the Supabase OAuth Server**

and Dynamic Client Registration (DCR) must also be enabled:

**Allow Dynamic OAuth Apps**

Leave **Site URL** and **Authorization Path** as their default values.

### Step 2: Migrate JWT Keys if needed, and rotate JWT keys

Under **Project Settings / JWT Keys ** if you see:

> Right now your project is using the legacy JWT secret.

You must upgrade to the newer keys, because it will use HS256 (shared secret) which will break the MCP auth handshake. Instead it should use RS256 (asymmetric keys + JWKS).

If you enable the new type of JWT secrets, you must rotate your keys in order to activate it.

### Step 3: Enable Supabase Magic Link auth

Enabled by default, nothing to do here.

### Step 4: Collect settings needed for env vars

1. Supabase URL
2. Anon key

See below.

## Script Setup

### Pull uv deps

```
uv sync
```

### Setup Env Vars

Copy .env.template to .env
Set your env variables accordingly

```
SUPABASE_PROJECT_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
```

You can get these from the Supabase dashboard.

The rest of the env vars can be left as defaults.

## How To Test

First activate the `venv` by running:

```
$ source .venv/bin/activate
```

Then run the following scripts in different terminals.

### Step 1: Start MCP Server

```
uv run fastmcp run hello_supabase.py --transport http --port 8000
```

### Step 2: Start Consent UI Server

```
uv run uvicorn consent_server:app --port 3000
```

### Step 3: Run FastMCP Client

```
python client.py
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Invoke the client via uv so dependencies resolve

After uv sync, the README instructs running python client.py, which uses the system interpreter unless the user manually activates .venv. In a fresh setup this commonly raises ModuleNotFoundError for fastmcp/dotenv; using uv run python client.py is required for the documented workflow to work reliably.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated the readme to tell the user to source .venv/bin/activate

```

### Step 4: Click Allow in browser window

It should open a browser window with Allow / Deny buttons and some debugging information. Hit "Allow".

### Step 5: Verify that it worked

1. You will see error in browser window. I am not sure what's going on here.
2. In the FastMCP client logs, if it worked you should see: `🎉 Tool result: CallToolResult(content=[TextContent(type='text', text='Hello from Supabase-protected MCP server!', annotations=None, meta=None)], structured_content={'result': 'Hello from Supabase-protected MCP server!'}, meta={'fastmcp': {'wrap_result': True}}, data='Hello from Supabase-protected MCP server!', is_error=False)`

## Needs Review

1. Email Auth vs other auth methods as default? (github?)
50 changes: 50 additions & 0 deletions examples/auth/supabase_auth/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# For testing since MCPJam doesn't support DCR ..

import asyncio
import logging
import os
import webbrowser

from dotenv import load_dotenv

from fastmcp import Client

load_dotenv()

os.environ["FASTMCP_LOG_LEVEL"] = os.getenv("FASTMCP_LOG_LEVEL", "DEBUG")
os.environ["MCP_LOG_LEVEL"] = os.getenv("MCP_LOG_LEVEL", "DEBUG")
os.environ["HTTPX_LOG_LEVEL"] = os.getenv("HTTPX_LOG_LEVEL", "DEBUG")

logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)

_original_open = webbrowser.open


def debug_browser_open(url, *args, **kwargs):
print("\n================ BROWSER OPEN ================")
print(url)
print("==============================================\n")
return _original_open(url, *args, **kwargs)


webbrowser.open = debug_browser_open


async def main():
print("🚀 Starting FastMCP OAuth client")

async with Client(
"http://localhost:8000/mcp",
auth="oauth", # 🔥 THIS triggers proper OAuth + DCR
) as client:
print("✅ Connected to MCP server")

result = await client.call_tool("hello_supabase", {})
print("🎉 Tool result:", result)


if __name__ == "__main__":
asyncio.run(main())
218 changes: 218 additions & 0 deletions examples/auth/supabase_auth/consent_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
import os

from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse

load_dotenv()

app = FastAPI()

SUPABASE_URL = os.environ["SUPABASE_PROJECT_URL"]
ANON_KEY = os.environ["SUPABASE_ANON_KEY"]

# "GITHUB_SIGN_IN" (default, correct for OAuth)
# "MAGIC_LINK" (debug only)
AUTH_TYPE = os.environ.get("AUTH_TYPE", "GITHUB_SIGN_IN")


@app.get("/oauth/consent", response_class=HTMLResponse)
async def consent_page(request: Request):
authorization_id = request.query_params.get("authorization_id")

if not authorization_id:
return HTMLResponse("Missing authorization_id", status_code=400)

return HTMLResponse(f"""
<!DOCTYPE html>
<html>
<head>
<title>OAuth Consent</title>
<style>
body {{ font-family: monospace; }}
#debug {{ white-space: pre-wrap; background: #111; color: #0f0; padding: 10px; }}
</style>
</head>
<body>
<h1>Loading...</h1>
<pre id="debug">Starting...</pre>

<script type="module">
import {{ createClient }} from "https://esm.sh/@supabase/supabase-js@2"

const AUTH_TYPE = "{AUTH_TYPE}"

const debugEl = document.getElementById("debug")

function log(...args) {{
console.log(...args)
debugEl.textContent += "\\n" + args.map(a =>
typeof a === "object" ? JSON.stringify(a, null, 2) : a
).join(" ")
}}

log("🚀 Consent page loaded")
log("🔐 AUTH_TYPE:", AUTH_TYPE)
log("🌍 Location:", window.location.href)
log("🌐 Origin:", window.location.origin)
log("🍪 document.cookie:", document.cookie || "(empty)")

const supabase = createClient(
"{SUPABASE_URL}",
"{ANON_KEY}"
)

const authorizationId = "{authorization_id}"

async function run() {{
log("▶️ Starting OAuth consent flow")

try {{
// ---- Session check ----
const sessionRes = await supabase.auth.getSession()
log("📦 getSession():", sessionRes)

const userRes = await supabase.auth.getUser()
log("👤 getUser():", userRes)

const user = userRes.data?.user

if (!user) {{
log("⚠️ NO USER SESSION")

if (AUTH_TYPE === "GITHUB_SIGN_IN") {{
log("🔐 Redirecting to GitHub OAuth login...")

const {{ data, error }} = await supabase.auth.signInWithOAuth({{
provider: "github",
options: {{
redirectTo: window.location.href
}}
}})

log("GitHub login result:", {{ data, error }})
return
}}

if (AUTH_TYPE === "MAGIC_LINK") {{
log("📧 Showing magic link UI")

document.body.innerHTML = `
<h2>No session</h2>
<p>Enter email for magic link</p>

<input id="email" type="email" />
<button id="login">Send</button>

<pre id="debug">${{debugEl.textContent}}</pre>
`

document.getElementById("login").onclick = async () => {{
const email = document.getElementById("email").value
log("📧 Sending magic link:", email)

const res = await supabase.auth.signInWithOtp({{
email,
options: {{
emailRedirectTo: window.location.href
}}
}})

log("Magic link result:", res)
}}

return
}}
}}

log("✅ User authenticated:", user.id)

// ---- Fetch authorization details ----
const authRes =
await supabase.auth.oauth.getAuthorizationDetails(authorizationId)

log("📦 Authorization details:", authRes)

if (authRes.error) {{
log("❌ Authorization error:", authRes.error)

document.body.innerHTML = `
<h2>Error</h2>
<pre>${{JSON.stringify(authRes.error, null, 2)}}</pre>
<pre id="debug">${{debugEl.textContent}}</pre>
`
return
}}

const data = authRes.data

log("✅ Authorization loaded")
log("Client:", data.client.name)
log("Scopes:", data.scope)

// ---- Render UI ----
document.body.innerHTML = `
<h1>Authorize ${{data.client.name}}</h1>
<p>Scopes: ${{data.scope}}</p>

<button id="approve">Approve</button>
<button id="deny">Deny</button>

<pre id="debug">${{debugEl.textContent}}</pre>
`

function logToPage(msg) {{
console.log(msg)
document.getElementById("debug").textContent += "\\n" + msg
}}

document.getElementById("approve").onclick = async () => {{
logToPage("🟢 Approve clicked")

const res =
await supabase.auth.oauth.approveAuthorization(authorizationId)

log("Approve result:", res)

if (res.error) {{
logToPage("❌ " + JSON.stringify(res.error))
return
}}

logToPage("➡️ Redirect → " + res.data.redirect_to)
window.location.href = res.data.redirect_to
}}

document.getElementById("deny").onclick = async () => {{
logToPage("🔴 Deny clicked")

const res =
await supabase.auth.oauth.denyAuthorization(authorizationId)

log("Deny result:", res)

if (res.error) {{
logToPage("❌ " + JSON.stringify(res.error))
return
}}

logToPage("➡️ Redirect → " + res.data.redirect_to)
window.location.href = res.data.redirect_to
}}

}} catch (err) {{
log("🔥 FATAL ERROR:", err)

document.body.innerHTML = `
<h2>Fatal error</h2>
<pre>${{err}}</pre>
<pre id="debug">${{debugEl.textContent}}</pre>
`
}}
}}

run()
</script>
</body>
</html>
""")
Loading
Loading