Skip to content

Commit 8da806e

Browse files
committed
feat: automatic project detection and enhanced authentication
- Add automatic Supabase project detection from working directory - Scan .env, .env.local, .supabase/config.toml, .supabase/.env files - Support framework-specific variables (Next.js, React, Vite) - Priority-based configuration resolution system - Extract project credentials and auto-switch context - Enhance personal access token detection - Auto-detect from ~/.supabase/access-token (CLI integration) - Support multiple token file formats and locations - Seamless integration with `supabase login` workflow - Smart fallback chain for token resolution - Implement dual authentication modes - personal-token: Management API with personal access tokens - project-keys: Project-specific anon/service keys when available - Automatic mode switching based on available credentials - Update platform integration - Enhanced API platform to use project context - Project-specific URL and key resolution - Improved fallback handling for missing credentials - Add comprehensive test suite - Unit tests for project context detection - Enhanced authentication flow testing - Config file parsing and validation tests - Update documentation and examples - README with automatic detection features - CHANGELOG with detailed feature descriptions - Enhanced Claude CLI integration guide
1 parent 5d9ca75 commit 8da806e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+4559
-735
lines changed

.vscode/settings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
"[json]": {
66
"editor.defaultFormatter": "biomejs.biome"
77
}
8-
}
8+
}

AGENTS.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Repository Guidelines
2+
3+
## Project Structure & Module Organization
4+
The pnpm workspace centers on `packages/mcp-server-supabase` (production MCP server) and `packages/mcp-utils` (shared schemas, validation, and helpers). An experimental `mcp-server-postgrest` lives alongside them for targeted pilots. Runtime code stays under each package’s `src/`; Vitest fixtures sit in sibling `test/` folders. Top-level `docs/` holds integration guides, `scripts/` provides registry and release automation, and `supabase/` contains migrations plus seed data consumed by integration suites.
5+
6+
## Build, Test, and Development Commands
7+
- `pnpm install` — install workspace dependencies.
8+
- `pnpm build` — run `tsup` builds for utils and the Supabase server.
9+
- `pnpm --filter @supabase/mcp-server-supabase dev` — watch-and-rebuild while coding.
10+
- `pnpm test` — execute all Vitest projects in parallel.
11+
- `pnpm test:coverage` — collect coverage for the Supabase server.
12+
- `pnpm format` / `pnpm format:check` — apply or verify Biome formatting.
13+
14+
## Coding Style & Naming Conventions
15+
Code is TypeScript-first, strict ESM, and two-space indented. Favor named exports; map filesystem names to camelCase exports (see `src/tools`). Generated OpenAPI artifacts belong under `src/management-api/`. Biome is the source of truth for formatting, linting, and import order—run it before committing. `tsup.config.ts` already targets both ESM and CJS outputs; keep new entrypoints consistent with existing build targets.
16+
17+
## Testing Guidelines
18+
Vitest drives unit, integration, and e2e suites configured in `vitest.workspace.ts`. Use package-scoped scripts (`pnpm test:unit`, `test:integration`, `test:e2e`) for faster iteration. Integration flows expect the seeded Supabase instance; refresh with `supabase db reset` when fixtures drift. Place new tests beside the modules they cover, naming files `*.test.ts`, and assert on concrete Supabase responses where possible instead of broad snapshots.
19+
20+
## Commit & Pull Request Guidelines
21+
Follow Conventional Commits (`feat:`, `fix:`, `chore:`) and collapse WIP history before raising a PR. Reference Supabase issues or MCP registry tickets when applicable. PR descriptions should outline behaviour changes, highlight tooling updates, and mention any Supabase config required for reviewers. Confirm `pnpm build`, `pnpm test`, and `pnpm format:check` pass locally, and attach CLI output for non-obvious failures or regressions.
22+
23+
## Security & Configuration Tips
24+
Store `SUPABASE_ACCESS_TOKEN` outside the repo (environment managers or MCP client secrets). Prefer `--read-only` and `--project-ref` flags when sharing demos, and scrub captured payloads before committing fixtures or docs.

README.md

Lines changed: 307 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,293 @@ Make sure Node.js is available in your system `PATH` environment variable. If yo
126126

127127
3. Restart your MCP client.
128128

129-
### 3. Follow our security best practices
129+
### 3. Automatic Project Detection (New)
130+
131+
The MCP server now supports automatic detection of your Supabase project configuration from your current working directory. This feature simplifies setup by automatically detecting project credentials and configuration.
132+
133+
#### How it works
134+
135+
When you start the MCP server, it will automatically scan your current working directory for Supabase configuration in the following priority order:
136+
137+
1. **`.env` file** - Checks for `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`
138+
2. **`.env.local` file** - Overrides `.env` values if present
139+
3. **`.supabase/config.toml`** - Supabase CLI configuration file
140+
4. **`.supabase/.env`** - Additional environment configuration
141+
142+
The server also supports framework-specific environment variable naming:
143+
- Next.js: `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`
144+
- Vite: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`
145+
- React: `REACT_APP_SUPABASE_URL`, `REACT_APP_SUPABASE_ANON_KEY`
146+
147+
#### Enhanced Token Detection
148+
149+
The server will automatically detect your personal access token from:
150+
151+
1. **Environment variable**: `SUPABASE_ACCESS_TOKEN`
152+
2. **Supabase CLI directory**: `~/.supabase/access-token` (automatically created by `supabase login`)
153+
3. **Alternative token files**: `~/.supabase/token`, `~/.supabase/config.toml`, etc.
154+
155+
#### Usage
156+
157+
With automatic detection, you can simply run:
158+
159+
```shell
160+
npx -y @supabase/mcp-server-supabase@latest
161+
```
162+
163+
The server will automatically:
164+
- Detect your personal access token from `~/.supabase/access-token`
165+
- Extract project credentials from your working directory
166+
- Switch to the detected project context
167+
- Use project-specific API keys when available
168+
169+
#### Benefits
170+
171+
- **Zero configuration** for projects with proper `.env` setup
172+
- **Framework agnostic** - works with Next.js, React, Vite, and others
173+
- **Secure** - Uses project-specific keys when available, falls back to personal tokens
174+
- **CLI integration** - Works seamlessly with `supabase login` and existing workflows
175+
176+
### 4. Follow our security best practices
130177

131178
Before running the MCP server, we recommend you read our [security best practices](#security-risks) to understand the risks of connecting an LLM to your Supabase projects and how to mitigate them.
132179

180+
## Claude CLI Configuration
181+
182+
If you're using this MCP server with Claude CLI specifically, we **strongly recommend using the wrapper script approach** for reliable authentication.
183+
184+
### Recommended Setup (Wrapper Script Method)
185+
186+
This is the most reliable method for Claude CLI integration:
187+
188+
#### 1. Download the Authentication Wrapper Script
189+
190+
Download our pre-configured wrapper script:
191+
192+
```bash
193+
curl -o supabase-mcp-wrapper.sh https://raw.githubusercontent.com/supabase/supabase-mcp/main/scripts/claude-cli-wrapper.sh
194+
chmod +x supabase-mcp-wrapper.sh
195+
```
196+
197+
#### 2. Configure Your Credentials
198+
199+
Edit the wrapper script and replace the placeholder values:
200+
201+
```bash
202+
# Edit the script with your preferred editor
203+
nano supabase-mcp-wrapper.sh
204+
```
205+
206+
Replace these lines:
207+
```bash
208+
export SUPABASE_ACCESS_TOKEN="YOUR_TOKEN_HERE"
209+
PROJECT_REF="YOUR_PROJECT_REF_HERE"
210+
```
211+
212+
With your actual values:
213+
```bash
214+
export SUPABASE_ACCESS_TOKEN="sbp_your_actual_token_here"
215+
PROJECT_REF="your_actual_project_ref_here"
216+
```
217+
218+
- **Personal Access Token**: Get from [Supabase Token Settings](https://supabase.com/dashboard/account/tokens)
219+
- **Project Reference**: Get from [Project Settings](https://supabase.com/dashboard/project/_/settings/general)
220+
221+
#### 3. Add to Claude CLI
222+
223+
```bash
224+
claude mcp add supabase /path/to/supabase-mcp-wrapper.sh
225+
```
226+
227+
#### 4. Connect in Claude CLI
228+
229+
Use the `/mcp` command in Claude CLI to connect to the Supabase MCP.
230+
231+
### Why Use the Wrapper Script?
232+
233+
The wrapper script solves common Claude CLI authentication issues:
234+
235+
- **Reliable Token Passing**: Bypasses environment variable issues in Claude CLI
236+
- **Built-in Validation**: Checks token format and configuration before starting
237+
- **Error Recovery**: Provides clear error messages for misconfiguration
238+
- **Cross-Platform**: Works on macOS, Linux, and Windows (with bash)
239+
240+
### Alternative Method (Environment Variables)
241+
242+
If you prefer using environment variables directly:
243+
244+
1. **Set Environment Variable**:
245+
```bash
246+
export SUPABASE_ACCESS_TOKEN="sbp_your_token_here"
247+
```
248+
249+
2. **Add to Claude CLI**:
250+
```bash
251+
claude mcp add supabase npx @supabase/mcp-server-supabase --project-ref=your_project_ref
252+
```
253+
254+
**Note**: This method may experience authentication issues due to how Claude CLI handles environment variables. If you encounter problems, switch to the wrapper script method.
255+
256+
### Troubleshooting Claude CLI Issues
257+
258+
If you experience authentication errors:
259+
260+
#### "Unauthorized. Please provide a valid access token" Error
261+
262+
This is the most common issue. Follow these steps:
263+
264+
1. **Verify Token Format**: Ensure your token starts with `sbp_`:
265+
```bash
266+
echo $SUPABASE_ACCESS_TOKEN | grep "^sbp_"
267+
```
268+
269+
2. **Use Wrapper Script**: If using environment variables isn't working, switch to the wrapper script method (recommended).
270+
271+
3. **Check Token Validity**: Generate a new token at [Supabase Token Settings](https://supabase.com/dashboard/account/tokens).
272+
273+
4. **Restart Claude CLI**: After making changes, restart Claude CLI completely.
274+
275+
#### "Failed to reconnect to supabase" Error
276+
277+
1. **Check MCP Status**:
278+
```bash
279+
claude mcp list
280+
```
281+
282+
2. **Remove and Re-add**:
283+
```bash
284+
claude mcp remove supabase
285+
claude mcp add supabase /path/to/supabase-mcp-wrapper.sh
286+
```
287+
288+
3. **Verify Script Permissions**:
289+
```bash
290+
chmod +x /path/to/supabase-mcp-wrapper.sh
291+
```
292+
293+
#### Common Token Issues
294+
295+
**Wrong Token Type**: The most common mistake is using the wrong type of Supabase token:
296+
297+
-**API Keys** (`sb_publishable_...` or `sb_secret_...`) - These are for client applications
298+
-**Environment Variables** (`SUPABASE_ACCESS_TOKEN=sbp_...`) - Don't put the variable name in config files
299+
-**Personal Access Token** (`sbp_...`) - Required for Management API operations
300+
301+
**File Configuration Issues**:
302+
303+
1. **Check `~/.supabase/access-token`** should contain only the token:
304+
```bash
305+
# Correct - just the token
306+
sbp_your_actual_token_here
307+
308+
# Wrong - contains variable syntax
309+
SUPABASE_ACCESS_TOKEN=sbp_your_actual_token_here
310+
```
311+
312+
2. **Verify Environment Variables**:
313+
```bash
314+
echo $SUPABASE_ACCESS_TOKEN
315+
# Should output your sbp_ token, not empty or undefined
316+
```
317+
318+
#### Environment Setup Issues
319+
320+
**PATH Problems**: If the wrapper script can't find `npx`:
321+
```bash
322+
# Add to your shell profile (~/.zshrc, ~/.bashrc)
323+
export PATH="/usr/local/bin:$HOME/.nvm/versions/node/$(node -v)/bin:$PATH"
324+
```
325+
326+
**Node.js Version**: Ensure you have Node.js 18+ installed:
327+
```bash
328+
node --version # Should be v18.0.0 or higher
329+
```
330+
331+
#### Testing Your Configuration
332+
333+
Test the wrapper script directly to isolate issues:
334+
335+
```bash
336+
# Test tool listing (should return JSON with available tools)
337+
echo '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}' | ./supabase-mcp-wrapper.sh
338+
339+
# Test with authentication (should work without "Unauthorized" errors)
340+
echo '{"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "get_project_url"}, "id": 2}' | ./supabase-mcp-wrapper.sh
341+
```
342+
343+
**If wrapper script works but Claude CLI fails:**
344+
- Check Claude CLI version: `claude --version`
345+
- Clear Claude CLI cache: `claude mcp list` then restart Claude CLI
346+
- Verify MCP configuration: `claude mcp list` should show your supabase entry
347+
348+
**If wrapper script fails:**
349+
- Check script permissions: `chmod +x /path/to/wrapper/script.sh`
350+
- Verify token and project ref are set correctly in the script
351+
- Test npx availability: `npx @supabase/mcp-server-supabase --help`
352+
353+
### Advanced Claude CLI Features
354+
355+
The Supabase MCP server includes several advanced features specifically designed for Claude CLI integration:
356+
357+
#### Token Configuration Options
358+
359+
The server supports multiple token sources with Claude CLI-optimized priority:
360+
361+
1. **Automatic Detection (New & Recommended)**:
362+
```bash
363+
# Simply login with Supabase CLI
364+
supabase login
365+
# Token is automatically stored in ~/.supabase/access-token
366+
```
367+
368+
2. **Environment Variables**:
369+
```bash
370+
export SUPABASE_ACCESS_TOKEN="sbp_your_token_here"
371+
```
372+
373+
3. **Config File Support**:
374+
Create a `~/.supabase/access-token` file containing just your token:
375+
```
376+
sbp_your_token_here
377+
```
378+
379+
The server will automatically detect and use tokens from the Supabase CLI directory, with fallback support for multiple token file formats.
380+
381+
**Claude CLI Note**: The automatic detection method works seamlessly with `supabase login` and is the recommended approach.
382+
383+
#### Runtime Mode Management
384+
385+
**Toggle Read-Only Mode**: Use the `toggle_read_only_mode` tool to switch between safe read-only operations and full database write access:
386+
387+
- **Read-Only Mode** 🔒: Safe for production, prevents accidental data modifications
388+
- **Write Mode** 🔓: Allows full database access, requires confirmation in Claude CLI
389+
390+
**Status Monitoring**: Use `get_runtime_mode_status` to check current mode and security settings.
391+
392+
#### Automatic Project Context Detection (New)
393+
394+
**Smart Project Detection**: The MCP server now automatically detects your current project from your working directory:
395+
396+
1. **Automatic Switching**: When started from a project directory, the server automatically switches to that project
397+
2. **Framework Support**: Works with Next.js, React, Vite, and other frameworks
398+
3. **Priority System**: Uses `.env.local` > `.env` > `.supabase/config.toml` configuration priority
399+
4. **Seamless Integration**: No manual project switching required for local development
400+
401+
**Manual Project Switching**: If you have multiple Supabase projects, use the `switch_project` tool for interactive project selection:
402+
403+
1. Call `switch_project` without parameters to see available projects
404+
2. Claude CLI users get a formatted project list with status indicators
405+
3. Select project by ID or name: `switch_project` with `project_identifier`
406+
407+
**Project Status**: Use `get_current_project` to see details about your currently active project.
408+
409+
#### Claude CLI-Specific Features
410+
411+
- **Interactive Confirmations**: All potentially destructive operations require explicit confirmation
412+
- **Status Indicators**: Clear visual feedback (🔒 read-only, 🔓 write mode, 🎯 current project)
413+
- **Contextual Guidance**: Step-by-step instructions tailored for Claude CLI workflows
414+
- **Security Warnings**: Automatic alerts for high-risk operations
415+
133416
### Project scoped mode
134417

135418
Without project scoping, the MCP server will have access to all organizations and projects in your Supabase account. We recommend you restrict the server to a specific project by setting the `--project-ref` flag on the CLI command:
@@ -171,9 +454,9 @@ You can enable or disable specific tool groups by passing the `--features` flag
171454
npx -y @supabase/mcp-server-supabase@latest --features=database,docs
172455
```
173456

174-
Available groups are: [`account`](#account), [`docs`](#knowledge-base), [`database`](#database), [`debugging`](#debugging), [`development`](#development), [`functions`](#edge-functions), [`storage`](#storage), and [`branching`](#branching-experimental-requires-a-paid-plan).
457+
Available groups are: [`account`](#account), [`docs`](#knowledge-base), [`database`](#database), [`debugging`](#debugging), [`development`](#development), [`functions`](#edge-functions), [`storage`](#storage), [`branching`](#branching-experimental-requires-a-paid-plan), and [`runtime`](#runtime-claude-cli-optimized).
175458

176-
If this flag is not passed, the default feature groups are: `account`, `database`, `debugging`, `development`, `docs`, `functions`, and `branching`.
459+
If this flag is not passed, the default feature groups are: `account`, `database`, `debugging`, `development`, `docs`, `functions`, `branching`, and `runtime`.
177460

178461
## Tools
179462

@@ -255,6 +538,27 @@ Disabled by default to reduce tool count. Use `storage` to target this group of
255538
- `get_storage_config`: Gets the storage config for a Supabase project.
256539
- `update_storage_config`: Updates the storage config for a Supabase project (requires a paid plan).
257540

541+
#### Runtime (Claude CLI Optimized)
542+
543+
Enabled by default for enhanced Claude CLI integration. Use `runtime` to target this group of tools with the [`--features`](#feature-groups) option.
544+
545+
**Mode Management:**
546+
- `toggle_read_only_mode`: Toggle between read-only and write modes with Claude CLI-specific confirmations
547+
- `get_runtime_mode_status`: Get current mode status with security information and Claude CLI guidance
548+
- `set_read_only_mode`: Explicitly set read-only or write mode
549+
- `validate_mode_change`: Check mode change requirements and confirmations needed
550+
551+
**Project Management:**
552+
- `switch_project`: Interactive project switching with Claude CLI-formatted project lists
553+
- `get_current_project`: Get details about the currently selected project
554+
- `list_projects`: List all available projects with Claude CLI-optimized display
555+
556+
**Claude CLI Features:**
557+
- Interactive confirmations for destructive operations
558+
- Visual status indicators (🔒 read-only, 🔓 write, 🎯 current project)
559+
- Context-aware error messages and guidance
560+
- Security warnings and recommendations
561+
258562
## Security risks
259563

260564
Connecting any data source to an LLM carries inherent risks, especially when it stores sensitive data. Supabase is no exception, so it's important to discuss what risks you should be aware of and extra precautions you can take to lower them.

0 commit comments

Comments
 (0)