Skip to main content
Glama
fastapi-supabase-mcp

fastapi-supabase-mcp

by Ofia

fastapi-supabase-mcp

Turn a FastAPI + Supabase app into an MCP server that Claude (or any MCP client) can connect to — with long-lived API keys, Supabase OAuth 2.1, and per-user data isolation.

Not a framework. A small, complete, working reference you can read in fifteen minutes and copy the three patterns out of.

Claude Desktop ──┐
Claude Code    ──┼── bearer token ──▶  /mcp   ──┐
your own agent ──┘                              ├──▶  the same handlers  ──▶  Supabase
                                                │
browser ──── Supabase JWT ─────────▶  /api  ────┘

Both front doors run the same code. Add a REST route, expose it as a tool in three lines, and the two can never drift apart.


Why this exists

Wiring MCP onto an app that already has users is mostly a set of small, undocumented problems: the session manager that silently never initializes, the DNS-rebinding guard that 421s every request the moment you deploy, the mount path that doubles up, the auth token that expires an hour after your user pasted it.

Each one costs an afternoon. They're all solved here, with the reasons left in the comments rather than stripped out.

Related MCP server: Supabase MCP Server

Quickstart

git clone https://github.com/Ofia/fastapi-supabase-mcp
cd fastapi-supabase-mcp
pip install -r requirements.txt

cp .env.example .env          # add your Supabase URL + service-role key
psql "$DATABASE_URL" -f schema.sql    # or paste schema.sql into the Supabase SQL editor

uvicorn app.main:app --reload

REST API at http://localhost:8000/api, MCP endpoint at http://localhost:8000/mcp.

Connect it to Claude

Mint a key (any Supabase access token works for this call):

curl -X POST localhost:8000/api/mcp-keys \
  -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"label": "my laptop"}'
# => {"key": "mcp_sk_…", ...}   shown once, never retrievable again

Then add the server in your MCP client — URL http://localhost:8000/mcp, that key as the bearer token. Ask it "what projects do I have?" and it will call list_projects against your database, scoped to you.


The three patterns worth stealing

1. MCP tools wrap your REST handlers — they don't reimplement them

Every route handler takes user as an ordinary parameter whose default is a Depends():

# app/routes.py
async def list_projects(user: dict = Depends(verify_jwt)) -> list: ...

FastAPI fills it in for HTTP callers. The MCP layer passes a dict directly:

# app/mcp_server.py
@mcp.tool()
async def list_projects() -> list:
    return await routes.list_projects(user=_auth_user())

One implementation, two front doors. Validation, tenant scoping and error handling are shared by construction, not by discipline.

2. One token verifier, two credential shapes

SupabaseTokenVerifier accepts either a long-lived API key or a Supabase OAuth 2.1 access token on the same Authorization header — because desktop clients paste a key and hosted clients press "Connect", and you need both.

Handing it to FastMCP's token_verifier= also yields the 401 challenge, the WWW-Authenticate header, and the /.well-known/oauth-protected-resource endpoint for free. Hand-rolling those is the usual reason a server fails client compatibility checks.

Keys are stored as sha256 hashes. The plaintext is returned once at generation and is unrecoverable — a dumped database yields hashes, not credentials.

3. Tenant scoping is enforced by a test, not by vigilance

The backend uses the service-role key, which bypasses RLS. The only thing separating one user's rows from another's is an explicit .eq("user_id", …) on every query — exactly the kind of line a tired human omits and a code review skims past.

So it isn't left to humans. tests/test_scoping.py parses the source with ast and fails the build on any Supabase query chain missing its tenant filter:

Un-scoped Supabase queries found:
  routes.py:163 in leaky() -- query without .eq("user_id", ...)

No database, no network, no fixtures — it runs in under a second, which is why it can sit on every commit. There's a second test asserting the guard actually found queries, because a guard that silently matches nothing passes forever.


The gotchas, written down

Every one of these cost real time to find.

Symptom

Cause

Fix

Every MCP request fails with a session error

The streamable-HTTP app's session manager needs its own lifespan run

async with mcp_app.router.lifespan_context(mcp_app) in your lifespan — sdk#1367

Works locally, 421 Misdirected Request once deployed

FastMCP auto-enables DNS-rebinding protection (Host/Origin allowlist) defaulting to localhost-only when no host= is given

TransportSecuritySettings(enable_dns_rebinding_protection=False) — the token verifier is the real gate

Endpoint answers at /mcp/mcp

Mounting the sub-app at /mcp while it also owns an internal path

streamable_http_path="/"

Client 401s in a loop with a valid key

resource_server_url doesn't exactly match the URL the client used, path included

Make MCP_SERVER_URL the single source for both

Key works for an hour, then stops

You handed it a Supabase access token, which expires

Long-lived hashed API keys — app/api_keys.py

Tool result rejected by the client as too large

A select("*") dragging a big JSON column across the wire

Project only the fields the tool needs, at the query level

The last one is worth expanding: in the production app this came from, list returned a full analysis blob per row. A handful of real records produced a 150 KB+ response that blew past the calling client's tool-result limit. List tools want summary projections, not *.

Tests

pytest          # 9 tests, ~1s, no database required
  • test_scoping.py — the AST tenant-scoping guard, plus a check that it isn't blind

  • test_api_keys.py — key generation invariants against a recording fake: plaintext never stored, hash matches the issued key, keys unique, key bound to its requesting user

Layout

app/
  main.py        FastAPI app — mounts the MCP sub-app, runs its lifespan
  mcp_server.py  the MCP server: token verifier, FastMCP config, tools
  routes.py      ordinary REST handlers (projects + tasks) the tools wrap
  api_keys.py    long-lived API key issuance and revocation
  auth.py        Supabase JWT verification against JWKS
  db.py          Supabase client
schema.sql       tables, RLS policies, indexes
tests/

The demo domain is projects-and-tasks on purpose — boring, so the patterns stay visible. Swap it for yours; the four other files don't change.

Provenance

Extracted and generalized from the MCP server I built for Legales, an AI-native legal practice management platform, where it exposes contracts, matters and finance data to external LLM clients in production. The domain logic is gone; the auth model, the wrapping pattern, the scoping guard and the gotchas are exactly what runs there.

License

MIT — see LICENSE.

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

    • F
      license
      Not graded
      quality
      D
      maintenance
      Converts any REST API endpoints into MCP tools, enabling AI clients like Cursor and Claude Desktop to call internal services directly.
      -
    • 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.
      259 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
      B
      maintenance
      Turns existing FastAPI routes (or any OpenAPI spec) into owner-approved MCP tools served from one governed endpoint, keeping tools hidden until an owner reviews a diff and enables them. Agents get incremental discovery via meta-tools, response field projection, per-caller API-key policy, PII redaction, and a JSON-lines audit log.
      37 PyPI
      1
      MIT