MCP Server Template
Production-ready MCP server template with full authentication infrastructure, extracted from a battle-tested production deployment.
Features
- OAuth 2.0 + PKCE — Full authorization code flow with S256 code challenge
- Auto-authorize — Known emails skip the login form automatically
- Refresh tokens — 7-day refresh tokens with JWT rotation
- Client credentials — Machine-to-machine auth via client_secret_post or client_secret_basic
- Supabase API key validation — Cached key lookups with configurable TTL
- Multi-project scoping —
allowed_projectsper key restricts access across MCP deployments - Organization whitelabeling — CNAME-based branding (custom name, favicon) resolved from Host header
- Usage tracking — Per-key request counts and token usage persisted to Supabase
- Resilient fallback — Configurable behavior when Supabase is unreachable (deny/allow/env)
- Dev/prod table separation —
ENV=devusesapi_keys_dev/usage_devtables - Static file serving — Serve branding assets (favicons, logos) from
/static/ - Health check —
GET /healthreturns{"status": "ok"}
Quick Start
-
Install dependencies
bash pip install -r requirements.txt -
Configure environment
bash cp .env.example .env # Edit .env with your Supabase credentials and PROJECT_ID -
Set up database — Run the SQL migrations in order against your Supabase project:
migrations/000_base_tables.sql # API keys + usage tables migrations/001_organizations.sql # Organizations (optional, for whitelabeling) -
Add your tools — Edit
server.pyand replace theechoexample with your own@mcp.tooldecorated functions. -
Run```bash
# Streamable HTTP (production)
TRANSPORT=http python server.py
# stdio (local development / Claude Desktop)
python server.py
```
Project Structure
| File | Purpose |
|---|---|
server.py |
Entry point + your MCP tools (edit this) |
auth.py |
Auth middleware — OAuth, JWT, API keys, orgs (don't edit) |
tracking.py |
Token/usage tracking via contextvars (don't edit) |
requirements.txt |
Python dependencies |
Dockerfile |
Container deployment |
.env.example |
All configuration variables documented |
migrations/ |
SQL migrations for Supabase tables |
static/ |
Branding assets (favicon, logo) |
Server Instructions (LLM Guidance)
The instructions parameter on FastMCP() is the most important way to control how LLMs use your server. It's returned during the MCP initialization handshake and tells the LLM everything it needs to know — no external skill files or documentation required.```python
mcp = FastMCP(
"my_server",
instructions="""My server does X. Use tool_a for quick checks, tool_b for deep analysis.
Workflow
- tool_a — start here for fast results
- tool_b — use after tool_a when the user wants more detail
Before calling any tool
Always ask the user for: their input data, preferred format, and any constraints.
Presenting results
Lead with the key metric. Show supporting detail after. Never dump raw JSON.
Important
- Never call tool_b without calling tool_a first.
- Reuse results from earlier calls — don't repeat work.
"""
)
**What to include:**
- **Workflow** — which tools to call in what order
- **Prerequisites** — what to collect from the user before calling tools
- **Output rules** — how to format and present results
- **Constraints** — gotchas, ordering requirements, things to avoid
- **Panel/state reuse** — when to reuse previous results vs. making new calls
**What NOT to include:**
- Internal implementation details (model names, scoring methodology)
- API keys or credentials
- Anything you wouldn't want shown to an end user
## Adding Tools
Add tools to `server.py` using the `@mcp.tool` decorator:```python
@mcp.tool(
name="my_tool",
annotations={
"title": "My Tool",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def my_tool(input_text: str, option: str = "default") -> str:
"""Description of what this tool does.
Args:
input_text: The main input.
option: An optional parameter.
Returns:
The tool's output.
"""
# Your logic here
return result
For tools that call LLMs and want token tracking:```python
from tracking import track_tokens
@mcp.tool(name="my_llm_tool")
async def my_llm_tool(prompt: str) -> str:
"""A tool that calls an LLM."""
response = await my_llm_call(prompt)
await track_tokens(response.input_tokens, response.output_tokens)
return response.text
## Authentication Flow
1. Client discovers OAuth metadata at `/.well-known/oauth-authorization-server`
2. Client redirects to `/authorize` with PKCE parameters
3. If `client_id` is a known email, auto-redirects with auth code (no form)
4. Otherwise, user sees login form (email + API key)
5. Client exchanges auth code for tokens at `/token`
6. Access token (JWT, 30min) used as `Bearer` token on `/mcp`
7. Refresh token (JWT, 7 days) used to get new access tokens
## Organization Whitelabeling
To set up whitelabeled instances:
1. Run `migrations/001_organizations.sql`
2. Insert an organization:```sql
INSERT INTO organizations (slug, brand_name, favicon_url, cname_domain)
VALUES ('acme', 'Acme Corp MCP', '/static/acme-favicon.png', 'mcp.acme.com');
```
3. Set up a CNAME record: `mcp.acme.com` → your deployment URL
4. Place `acme-favicon.png` in `static/`
5. API keys with matching `organization_id` will see Acme branding
## Configuration Reference
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `SUPABASE_URL` | Yes | — | Supabase project URL |
| `SUPABASE_KEY` | Yes | — | Supabase anon or service role key |
| `PROJECT_ID` | Yes | — | Unique ID for this MCP project |
| `TRANSPORT` | No | `stdio` | `http` for streamable HTTP, `stdio` for local |
| `PORT` | No | `8000` | HTTP port (when TRANSPORT=http) |
| `ENV` | No | `prod` | `dev` uses `_dev` table variants |
| `JWT_SECRET` | No | auto-generated | Secret for signing JWTs |
| `JWT_EXPIRY` | No | `1800` | Access token expiry in seconds |
| `SUPABASE_FALLBACK` | No | `deny` | `deny`/`allow`/`env` when Supabase unreachable |
| `API_KEYS` | No | — | Comma-separated keys (fallback=env only) |
| `BLOCKED_KEYS` | No | — | Comma-separated blocked keys (fallback=env only) |
## Deployment
### Docker```bash
docker build -t my-mcp .
docker run -p 8000:8000 --env-file .env my-mcp
Railway
- Connect your repo
- Set environment variables in Railway dashboard
- Railway auto-detects the Dockerfile
Endpoints
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/health |
GET | No | Health check |
/.well-known/oauth-authorization-server |
GET | No | OAuth metadata |
/.well-known/oauth-protected-resource |
GET | No | Protected resource metadata |
/authorize |
GET/POST | No | OAuth authorization (login form) |
/token |
POST | No | Token exchange |
/register |
POST | No | Client registration (returns disabled) |
/mcp |
POST/DELETE | Yes | MCP streamable HTTP endpoint |
/ |
POST/DELETE | Yes | Alias for /mcp |
/usage |
GET | admin_key | Usage statistics |
/static/* |
GET | No | Static assets |
