Skip to content
Back to search

selfhosted-supabase-mcp

An MCP Server for your Self Hosted Supabase

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/henkdz--selfhosted-supabase-mcp/badge.svg)](/listings/henkdz--selfhosted-supabase-mcp)

HTML

<a href="/listings/henkdz--selfhosted-supabase-mcp"><img src="/api/listings/henkdz--selfhosted-supabase-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Installing via Smithery

To install Self-Hosted Supabase MCP Server for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@HenkDz/selfhosted-supabase-mcp):

npx -y @smithery/cli install @HenkDz/selfhosted-supabase-mcp --client claude

Prerequisites

* [Bun](https://bun.sh/) v1.1 or later (replaces Node.js/npm — used for runtime and builds) * Access to your self-hosted Supabase instance (URL, keys, and optionally a direct PostgreSQL connection string).

Steps

1. **Clone the repository:** ```bash git clone <repository-url> cd selfhosted-supabase-mcp ``` 2. **Install dependencies:** ```bash bun install ``` 3. **Build the project:** ```bash bun run build ``` This compiles the TypeScript source to JavaScript in the `dist` directory.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 619 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Self-Hosted Supabase MCP Server
  2. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  3. [![smithery badge](https://smithery.ai/badge/@HenkDz/selfhosted-supabase-mcp)](https://smithery.ai/server/@HenkDz/selfhosted-supabase-mcp)
  4. ## Overview
  5. This project provides a [Model Context Protocol (MCP)](https://github.com/modelcontextprotocol/specification) server designed specifically for interacting with **self-hosted Supabase instances**. It bridges the gap between MCP clients (like IDE extensions) and your local or privately hosted Supabase projects, enabling database introspection, management, and interaction directly from your development environment.
  6. This server was built from scratch, drawing lessons from adapting the official Supabase cloud MCP server, to provide a minimal, focused implementation tailored for the self-hosted use case.
  7. ## Purpose
  8. The primary goal of this server is to enable developers using self-hosted Supabase installations to leverage MCP-based tools for tasks such as:
  9. * Querying database schemas and data.
  10. * Managing database migrations.
  11. * Inspecting database statistics and connections.
  12. * Managing authentication users.
  13. * Interacting with Supabase Storage.
  14. * Generating type definitions.
  15. It avoids the complexities of the official cloud server related to multi-project management and cloud-specific APIs, offering a streamlined experience for single-project, self-hosted environments.
  16. ## Features (Implemented Tools)
  17. Tools are categorized by privilege level:
  18. - **Regular** tools are accessible by any authenticated Supabase JWT (`authenticated` or `service_role` role).
  19. - **Privileged** tools require a `service_role` JWT (HTTP mode) or direct database/service-key access (stdio mode).
  20. ### Schema & Migrations
  21. | Tool | Description | Privilege |
  22. |------|-------------|-----------|
  23. | `list_tables` | Lists tables in the database schemas | Regular |
  24. | `list_extensions` | Lists installed PostgreSQL extensions | Regular |
  25. | `list_available_extensions` | Lists all available (installable) extensions | Regular |
  26. | `list_migrations` | Lists applied migrations from `supabase_migrations.schema_migrations` | Regular |
  27. | `apply_migration` | Applies a SQL migration and records it in `supabase_migrations.schema_migrations` | **Privileged** |
  28. | `list_table_columns` | Lists columns for a specific table | Regular |
  29. | `list_indexes` | Lists indexes for a specific table | Regular |
  30. | `list_constraints` | Lists constraints for a specific table | Regular |
  31. | `list_foreign_keys` | Lists foreign keys for a specific table | Regular |
  32. | `list_triggers` | Lists triggers for a specific table | Regular |
  33. | `list_database_functions` | Lists user-defined database functions | Regular |
  34. | `get_function_definition` | Gets the source definition of a function | Regular |
  35. | `get_trigger_definition` | Gets the source definition of a trigger | Regular |
  36. ### Database Operations & Stats
  37. | Tool | Description | Privilege |
  38. |------|-------------|-----------|
  39. | `execute_sql` | Executes an arbitrary SQL query | **Privileged** |
  40. | `explain_query` | Runs `EXPLAIN ANALYZE` on a query | **Privileged** |
  41. | `get_database_connections` | Shows active connections (`pg_stat_activity`) | Regular |
  42. | `get_database_stats` | Retrieves database statistics (`pg_stat_*`) | Regular |
  43. | `get_index_stats` | Shows index usage statistics | Regular |
  44. | `get_vector_index_stats` | Shows pgvector index statistics | Regular |
  45. ### Security & RLS
  46. | Tool | Description | Privilege |
  47. |------|-------------|-----------|
  48. | `list_rls_policies` | Lists Row-Level Security policies for a table | Regular |
  49. | `get_rls_status` | Shows RLS enabled/disabled status for tables | Regular |
  50. | `get_advisors` | Retrieves security and performance advisory notices | Regular |
  51. ### Project Configuration
  52. | Tool | Description | Privilege |
  53. |------|-------------|-----------|
  54. | `get_project_url` | Returns the configured Supabase URL | Regular |
  55. | `verify_jwt_secret` | Checks if the JWT secret is configured | Regular |
  56. ### Development & Extension Tools
  57. | Tool | Description | Privilege |
  58. |------|-------------|-----------|
  59. | `generate_typescript_types` | Generates TypeScript types from the database schema | Regular |
  60. | `rebuild_hooks` | Restarts the `pg_net` worker (if used) | **Privileged** |
  61. | `get_logs` | Retrieves recent log entries (analytics stack or CSV fallback) | Regular |
  62. ### Auth User Management
  63. | Tool | Description | Privilege |
  64. |------|-------------|-----------|
  65. | `list_auth_users` | Lists users from `auth.users` | Regular |
  66. | `get_auth_user` | Retrieves details for a specific user | Regular |
  67. | `create_auth_user` | Creates a new user in `auth.users` (password bcrypt-hashed via pgcrypto) | **Privileged** |
  68. | `update_auth_user` | Updates user details (password bcrypt-hashed if changed) | **Privileged** |
  69. | `delete_auth_user` | Deletes a user from `auth.users` | **Privileged** |
  70. ### Storage
  71. | Tool | Description | Privilege |
  72. |------|-------------|-----------|
  73. | `list_storage_buckets` | Lists all storage buckets | Regular |
  74. | `list_storage_objects` | Lists objects within a specific bucket | Regular |
  75. | `get_storage_config` | Retrieves storage bucket configuration | Regular |
  76. | `update_storage_config` | Updates storage bucket settings | **Privileged** |
  77. ### Realtime Inspection
  78. | Tool | Description | Privilege |
  79. |------|-------------|-----------|
  80. | `list_realtime_publications` | Lists PostgreSQL publications (e.g. `supabase_realtime`) | Regular |
  81. ### Extension-Specific Tools
  82. | Tool | Description | Privilege |
  83. |------|-------------|-----------|
  84. | `list_cron_jobs` | Lists scheduled jobs (requires `pg_cron` extension) | Regular |
  85. | `get_cron_job_history` | Shows recent execution history for a cron job | Regular |
  86. | `list_vector_indexes` | Lists pgvector indexes (requires `pgvector` extension) | Regular |
  87. ### Edge Functions
  88. | Tool | Description | Privilege |
  89. |------|-------------|-----------|
  90. | `list_edge_functions` | Lists deployed Edge Functions | Regular |
  91. | `get_edge_function_details` | Gets details and metadata for an Edge Function | Regular |
  92. | `list_edge_function_logs` | Retrieves recent logs for an Edge Function | Regular |
  93. ---
  94. ### About `supabase_migrations.schema_migrations`
  95. The `list_migrations` and `apply_migration` tools rely on the `supabase_migrations.schema_migrations` table. This table is **created and managed by the Supabase CLI** — it is not part of the MCP server itself.
  96. **How the table is created:**
  97. The table is automatically created when you initialise or run migrations using the Supabase CLI:
  98. ```bash
  99. supabase db push # pushes local migrations to a remote database
  100. supabase migration up # applies pending local migration files
  101. ```
  102. If you have never run the Supabase CLI against your database, the table will not exist and `list_migrations` will return an error. You can create it manually with:
  103. ```sql
  104. CREATE SCHEMA IF NOT EXISTS supabase_migrations;
  105. CREATE TABLE IF NOT EXISTS supabase_migrations.schema_migrations (
  106. version text NOT NULL PRIMARY KEY,
  107. name text NOT NULL DEFAULT '',
  108. inserted_at timestamptz NOT NULL DEFAULT now()
  109. );
  110. ```
  111. **Schema difference vs. official Supabase:**
  112. The Supabase cloud platform tracks additional columns (e.g. `statements`, `dirty`). This MCP server uses the minimal schema (version + name + inserted_at) that is compatible with the Supabase CLI's local-development workflow. If your existing table has extra columns they are simply ignored.
  113. ## Setup and Installation
  114. ### Installing via Smithery
  115. To install Self-Hosted Supabase MCP Server for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@HenkDz/selfhosted-supabase-mcp):
  116. ```bash
  117. npx -y @smithery/cli install @HenkDz/selfhosted-supabase-mcp --client claude
  118. ```
  119. ### Prerequisites
  120. * [Bun](https://bun.sh/) v1.1 or later (replaces Node.js/npm — used for runtime and builds)
  121. * Access to your self-hosted Supabase instance (URL, keys, and optionally a direct PostgreSQL connection string).
  122. ### Steps
  123. 1. **Clone the repository:**
  124. ```bash
  125. git clone <repository-url>
  126. cd selfhosted-supabase-mcp
  127. ```
  128. 2. **Install dependencies:**
  129. ```bash
  130. bun install
  131. ```
  132. 3. **Build the project:**
  133. ```bash
  134. bun run build
  135. ```
  136. This compiles the TypeScript source to JavaScript in the `dist` directory.
  137. ## Configuration
  138. The server requires configuration details for your Supabase instance. These can be provided via command-line arguments or environment variables. CLI arguments take precedence.
  139. **Required:**
  140. * `--url <url>` or `SUPABASE_URL=<url>`: The main HTTP URL of your Supabase project (e.g., `http://localhost:8000`).
  141. * `--anon-key <key>` or `SUPABASE_ANON_KEY=<key>`: Your Supabase project's anonymous key.
  142. **Optional (but Recommended/Required for certain tools):**
  143. * `--service-key <key>` or `SUPABASE_SERVICE_ROLE_KEY=<key>`: Your Supabase project's service role key. Required for privileged tools and for auto-creating the `execute_sql` helper function on startup.
  144. * `--db-url <url>` or `DATABASE_URL=<url>`: The direct PostgreSQL connection string for your Supabase database (e.g., `postgresql://postgres:password@localhost:5432/postgres`). Required for tools needing direct database access (`apply_migration`, Auth tools, Storage tools, `pg_catalog` queries).
  145. * `--jwt-secret <secret>` or `SUPABASE_AUTH_JWT_SECRET=<secret>`: Your Supabase project's JWT secret. Required when using `--transport http` and needed by the `verify_jwt_secret` tool.
  146. * `--tools-config <path>`: Path to a JSON file specifying which tools to enable (whitelist). If omitted, all tools are enabled. Format: `{"enabledTools": ["tool_name_1", "tool_name_2"]}`.
  147. **HTTP transport options (when using `--transport http`):**
  148. * `--port <number>`: HTTP server port (default: `3000`).
  149. * `--host <string>`: HTTP server host (default: `127.0.0.1`).
  150. * `--cors-origins <origins>`: Comma-separated list of allowed CORS origins. Defaults to localhost only.
  151. * `--rate-limit-window <ms>`: Rate limit window in milliseconds (default: `60000`).
  152. * `--rate-limit-max <count>`: Max requests per rate limit window (default: `100`).
  153. * `--request-timeout <ms>`: Request timeout in milliseconds (default: `30000`).
  154. ### Important Notes:
  155. * **`execute_sql` Helper Function:** Many tools rely on a `public.execute_sql` function within your Supabase database for SQL execution via RPC. The server attempts to check for this function on startup. If it's missing *and* a `service-key` *and* `db-url` are provided, it will attempt to create the function automatically. If creation fails or keys aren't provided, tools relying solely on RPC may fail.
  156. * **Direct Database Access:** Tools interacting directly with privileged schemas (`auth`, `storage`) or system catalogs (`pg_catalog`) generally require `DATABASE_URL` to be configured.
  157. * **Coolify / reverse-proxy deployments:**
  158. * The `DATABASE_URL` must use the internal hostname reachable from wherever the MCP server process runs, not the public-facing domain.
  159. * An `ECONNRESET` error during startup means the `DATABASE_URL` cannot be reached from the server's network context.
  160. * The server will still start successfully and all tools that don't require a direct DB connection will continue to work normally.
  161. ## Security
  162. ### HTTP transport (recommended for remote access)
  163. When running with `--transport http`, the server enforces:
  164. - **JWT authentication** on all `/mcp` endpoints using your `SUPABASE_AUTH_JWT_SECRET`.
  165. - **Privilege-based access control (RBAC)** — the `role` claim in the JWT determines which tools are accessible:
  166. - `service_role`: Full access (all tools including privileged ones).
  167. - `authenticated`: Regular tools only.
  168. - `anon`: No tool access.
  169. - **Rate limiting** — configurable request rate limit per IP address.
  170. - **CORS** — configurable allow-list of origins (defaults to localhost only).
  171. - **Security headers** — `X-Content-Type-Options`, `X-Frame-Options`, `Strict-Transport-Security`, etc.
  172. - **Request timeouts** — configurable timeout to prevent resource exhaustion.
  173. ### Stdio transport (local development)
  174. Stdio mode has **no authentication** — all tools (including privileged ones) are accessible. It is intended for trusted local clients only (e.g., an IDE extension running on your local machine). A warning is printed on startup when this mode is used.
  175. ### Password handling for auth user tools
  176. `create_auth_user` and `update_auth_user` accept a plain-text password from the MCP client, then immediately hash it with **bcrypt** (via PostgreSQL's `pgcrypto` extension: `crypt($password, gen_salt('bf'))`) before storing it in `auth.users`. The plain-text password is never stored. Passwords are passed as query parameters (not string-interpolated into SQL), preventing SQL injection.
  177. > **Note:** The password travels over the MCP transport in plain text between the MCP client and server. This is inherent to the MCP protocol interface and unavoidable at this layer. Use the HTTP transport with TLS termination (e.g., behind Kong/nginx) for network protection.
  178. ### SQL execution security
  179. All database operations in the MCP server use parameterized queries (`$1`, `$2`, ...) to prevent SQL injection. The `execute_sql` tool is an intentional exception — it executes arbitrary SQL by design (it is the tool's purpose). This tool is restricted to `service_role` privilege level to limit exposure.
  180. ## Usage
  181. ### Stdio mode (local MCP clients)
  182. Run the server using Bun, providing the necessary configuration:
  183. ```bash
  184. # Using CLI arguments (stdio mode — default)
  185. bun run dist/index.js --url http://localhost:8000 --anon-key <your-anon-key> \
  186. --db-url postgresql://postgres:password@localhost:5432/postgres \
  187. --service-key <your-service-key>
  188. # Example with tool whitelisting via config file
  189. bun run dist/index.js --url http://localhost:8000 --anon-key <your-anon-key> \
  190. --tools-config ./mcp-tools.json
  191. # Or configure using environment variables and run:
  192. # export SUPABASE_URL=http://localhost:8000
  193. # export SUPABASE_ANON_KEY=<your-anon-key>
  194. # export DATABASE_URL=postgresql://postgres:password@localhost:5432/postgres
  195. # export SUPABASE_SERVICE_ROLE_KEY=<your-service-key>
  196. bun run dist/index.js
  197. ```
  198. ### HTTP mode (Docker / remote access)
  199. ```bash
  200. bun run dist/index.js \
  201. --transport http \
  202. --port 3100 \
  203. --host 0.0.0.0 \
  204. --url http://kong:8000 \
  205. --anon-key <your-anon-key> \
  206. --service-key <your-service-key> \
  207. --jwt-secret <your-jwt-secret> \
  208. --db-url postgresql://postgres:password@db:5432/postgres
  209. ```
  210. HTTP mode requires `--jwt-secret`. All `/mcp` requests must include a valid Supabase JWT in the `Authorization: Bearer <token>` header.
  211. The server communicates via stdio (default) or HTTP (Streamable HTTP Transport) and is designed to be invoked by an MCP client application (e.g., an IDE extension like Cursor). The client will connect to the server's stdio stream or HTTP endpoint to list and call the available tools.
  212. ## Client Configuration Examples
  213. Below are examples of how to configure popular MCP clients to use this self-hosted server.
  214. **Important:**
  215. * Replace placeholders like `<your-supabase-url>`, `<your-anon-key>`, `<your-db-url>`, `<path-to-dist/index.js>` etc., with your actual values.
  216. * Ensure the path to the compiled server file (`dist/index.js`) is correct for your system.
  217. * Be cautious about storing sensitive keys directly in configuration files, especially if committed to version control. Consider using environment variables or more secure methods where supported by the client.
  218. ### Cursor
  219. 1. Create or open the file `.cursor/mcp.json` in your project root.
  220. 2. Add the following configuration:
  221. ```json
  222. {
  223. "mcpServers": {
  224. "selfhosted-supabase": {
  225. "command": "bun",
  226. "args": [
  227. "run",
  228. "<path-to-dist/index.js>", // e.g., "/home/user/selfhosted-supabase-mcp/dist/index.js"
  229. "--url",
  230. "<your-supabase-url>", // e.g., "http://localhost:8000"
  231. "--anon-key",
  232. "<your-anon-key>",
  233. // Optional - Add these if needed by the tools you use
  234. "--service-key",
  235. "<your-service-key>",
  236. "--db-url",
  237. "<your-db-url>", // e.g., "postgresql://postgres:password@host:port/postgres"
  238. "--jwt-secret",
  239. "<your-jwt-secret>",
  240. // Optional - Whitelist specific tools
  241. "--tools-config",
  242. "<path-to-your-mcp-tools.json>" // e.g., "./mcp-tools.json"
  243. ]
  244. }
  245. }
  246. }
  247. ```
  248. ### Visual Studio Code (Copilot)
  249. VS Code Copilot allows using environment variables populated via prompted inputs, which is more secure for keys.
  250. 1. Create or open the file `.vscode/mcp.json` in your project root.
  251. 2. Add the following configuration:
  252. ```json
  253. {
  254. "inputs": [
  255. { "type": "promptString", "id": "sh-supabase-url", "description": "Self-Hosted Supabase URL", "default": "http://localhost:8000" },
  256. { "type": "promptString", "id": "sh-supabase-anon-key", "description": "Self-Hosted Supabase Anon Key", "password": true },
  257. { "type": "promptString", "id": "sh-supabase-service-key", "description": "Self-Hosted Supabase Service Key (Optional)", "password": true, "required": false },
  258. { "type": "promptString", "id": "sh-supabase-db-url", "description": "Self-Hosted Supabase DB URL (Optional)", "password": true, "required": false },
  259. { "type": "promptString", "id": "sh-supabase-jwt-secret", "description": "Self-Hosted Supabase JWT Secret (Optional)", "password": true, "required": false },
  260. { "type": "promptString", "id": "sh-supabase-server-path", "description": "Path to self-hosted-supabase-mcp/dist/index.js" },
  261. { "type": "promptString", "id": "sh-supabase-tools-config", "description": "Path to tools config JSON (Optional, e.g., ./mcp-tools.json)", "required": false }
  262. ],
  263. "servers": {
  264. "selfhosted-supabase": {
  265. "command": "bun",
  266. "args": [
  267. "run",
  268. "${input:sh-supabase-server-path}",
  269. "--tools-config", "${input:sh-supabase-tools-config}"
  270. ],
  271. "env": {
  272. "SUPABASE_URL": "${input:sh-supabase-url}",
  273. "SUPABASE_ANON_KEY": "${input:sh-supabase-anon-key}",
  274. "SUPABASE_SERVICE_ROLE_KEY": "${input:sh-supabase-service-key}",
  275. "DATABASE_URL": "${input:sh-supabase-db-url}",
  276. "SUPABASE_AUTH_JWT_SECRET": "${input:sh-supabase-jwt-secret}"
  277. }
  278. }
  279. }
  280. }
  281. ```
  282. 3. When you use Copilot Chat in Agent mode (@workspace), it should detect the server. You will be prompted to enter the details (URL, keys, path) when the server is first invoked.
  283. ### Other Clients (Windsurf, Cline, Claude)
  284. Adapt the configuration structure shown for Cursor or the official Supabase documentation, replacing the `command` and `args` with the `bun run` command and the arguments for this server, similar to the Cursor example:
  285. ```json
  286. {
  287. "mcpServers": {
  288. "selfhosted-supabase": {
  289. "command": "bun",
  290. "args": [
  291. "run",
  292. "<path-to-dist/index.js>",
  293. "--url", "<your-supabase-url>",
  294. "--anon-key", "<your-anon-key>",
  295. "--service-key", "<your-service-key>",
  296. "--db-url", "<your-db-url>",
  297. "--jwt-secret", "<your-jwt-secret>",
  298. "--tools-config", "<path-to-your-mcp-tools.json>"
  299. ]
  300. }
  301. }
  302. }
  303. ```
  304. Consult the specific documentation for each client on where to place the `mcp.json` or equivalent configuration file.
  305. ## Docker Integration with Self-Hosted Supabase
  306. This MCP server can be integrated directly into a self-hosted Supabase Docker Compose stack, making it available alongside other Supabase services via the Kong API gateway.
  307. ### Architecture Overview
  308. When integrated with Docker:
  309. - The MCP server runs in HTTP transport mode (not stdio)
  310. - It's exposed through Kong at `/mcp/v1/*`
  311. - JWT authentication is handled by the MCP server itself
  312. - The server has direct access to the database and all Supabase keys
  313. ### Setup Steps
  314. #### 1. Add the MCP Server as a Git Submodule
  315. From your Supabase Docker directory:
  316. ```bash
  317. git submodule add https://github.com/HenkDz/selfhosted-supabase-mcp.git selfhosted-supabase-mcp
  318. ```
  319. #### 2. Create the Dockerfile
  320. Create `volumes/mcp/Dockerfile`:
  321. ```dockerfile
  322. # Dockerfile for selfhosted-supabase-mcp HTTP mode
  323. # Multi-stage build using Bun runtime for self-hosted Supabase
  324. FROM oven/bun:1.1-alpine AS builder
  325. WORKDIR /app
  326. # Copy package files from submodule
  327. COPY selfhosted-supabase-mcp/package.json selfhosted-supabase-mcp/bun.lock* ./
  328. # Install dependencies
  329. RUN bun install --frozen-lockfile || bun install
  330. # Copy source code
  331. COPY selfhosted-supabase-mcp/src ./src
  332. COPY selfhosted-supabase-mcp/tsconfig.json ./
  333. # Build the application
  334. RUN bun build src/index.ts --outdir dist --target bun
  335. # Production stage
  336. FROM oven/bun:1.1-alpine AS runner
  337. WORKDIR /app
  338. # Create non-root user for security
  339. RUN addgroup --system --gid 1001 mcp && \
  340. adduser --system --uid 1001 --ingroup mcp mcp
  341. # Copy built application from builder
  342. COPY --from=builder /app/dist ./dist
  343. COPY --from=builder /app/node_modules ./node_modules
  344. COPY --from=builder /app/package.json ./
  345. # Set ownership
  346. RUN chown -R mcp:mcp /app
  347. USER mcp
  348. # Default environment variables
  349. ENV NODE_ENV=production
  350. # Health check
  351. HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  352. CMD wget --no-verbose --tries=1 --spider http://localhost:3100/health || exit 1
  353. # Expose HTTP port
  354. EXPOSE 3100
  355. # Start the MCP server in HTTP mode
  356. CMD ["bun", "run", "dist/index.js"]
  357. ```
  358. #### 3. Add the MCP Service to docker-compose.yml
  359. Add this service definition to your `docker-compose.yml`:
  360. ```yaml
  361. ## MCP Server - Model Context Protocol for AI integrations
  362. ## DISABLED BY DEFAULT - Add 'mcp' to COMPOSE_PROFILES to enable
  363. mcp:
  364. container_name: ${COMPOSE_PROJECT_NAME:-supabase}-mcp
  365. profiles:
  366. - mcp
  367. build:
  368. context: .
  369. dockerfile: ./volumes/mcp/Dockerfile
  370. restart: unless-stopped
  371. healthcheck:
  372. test:
  373. [
  374. "CMD",
  375. "wget",
  376. "--no-verbose",
  377. "--tries=1",
  378. "--spider",
  379. "http://localhost:3100/health"
  380. ]
  381. timeout: 5s
  382. interval: 10s
  383. retries: 3
  384. depends_on:
  385. db:
  386. condition: service_healthy
  387. rest:
  388. condition: service_started
  389. environment:
  390. SUPABASE_URL: http://kong:8000
  391. SUPABASE_ANON_KEY: ${ANON_KEY}
  392. SUPABASE_SERVICE_ROLE_KEY: ${SERVICE_ROLE_KEY}
  393. SUPABASE_AUTH_JWT_SECRET: ${JWT_SECRET}
  394. DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}
  395. command:
  396. [
  397. "bun",
  398. "run",
  399. "dist/index.js",
  400. "--transport", "http",
  401. "--port", "3100",
  402. "--host", "0.0.0.0",
  403. "--url", "http://kong:8000",
  404. "--anon-key", "${ANON_KEY}",
  405. "--service-key", "${SERVICE_ROLE_KEY}",
  406. "--jwt-secret", "${JWT_SECRET}",
  407. "--db-url", "postgresql://postgres:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
  408. ]
  409. ```
  410. #### 4. Add Kong API Gateway Routes
  411. Add the MCP routes to `volumes/api/kong.yml` in the `services` section:
  412. ```yaml
  413. ## MCP Server routes - Model Context Protocol for AI integrations
  414. ## Authentication is handled by the MCP server itself (JWT validation)
  415. - name: mcp-v1
  416. _comment: 'MCP Server: /mcp/v1/* -> http://mcp:3100/*'
  417. url: http://mcp:3100/
  418. routes:
  419. - name: mcp-v1-all
  420. strip_path: true
  421. paths:
  422. - /mcp/v1/
  423. plugins:
  424. - name: cors
  425. config:
  426. origins:
  427. - "$SITE_URL_PATTERN"
  428. - "http://localhost:3000"
  429. - "http://127.0.0.1:3000"
  430. methods:
  431. - GET
  432. - POST
  433. - DELETE
  434. - OPTIONS
  435. headers:
  436. - Accept
  437. - Authorization
  438. - Content-Type
  439. - X-Client-Info
  440. - apikey
  441. - Mcp-Session-Id
  442. exposed_headers:
  443. - Mcp-Session-Id
  444. credentials: true
  445. max_age: 3600
  446. ```
  447. #### 5. Enable the MCP Service
  448. The MCP service uses Docker Compose profiles, so it's disabled by default. To enable it:
  449. **Option A: Set in `.env` file:**
  450. ```bash
  451. COMPOSE_PROFILES=mcp
  452. ```
  453. **Option B: Enable at runtime:**
  454. ```bash
  455. docker compose --profile mcp up -d
  456. ```
  457. ### Accessing the MCP Server
  458. Once running, the MCP server is available at:
  459. - **Internal (from other containers):** `http://mcp:3100`
  460. - **External (via Kong):** `http://localhost:8000/mcp/v1/`
  461. ### Authentication
  462. When running in HTTP mode, the MCP server validates JWTs using the configured `JWT_SECRET`. Clients must include a valid Supabase JWT in the `Authorization` header:
  463. ```
  464. Authorization: Bearer <supabase-jwt>
  465. ```
  466. The JWT's `role` claim determines access:
  467. - `service_role`: Full access to all tools (regular + privileged)
  468. - `authenticated`: Access to regular tools only
  469. - `anon`: No tool access
  470. ### Health Check
  471. The MCP server exposes a health endpoint:
  472. ```bash
  473. curl http://localhost:8000/mcp/v1/health
  474. ```
  475. ### Security Considerations
  476. When deploying via Docker:
  477. 1. The MCP server runs as a non-root user (`mcp:mcp`)
  478. 2. JWT authentication is enforced for all tool calls
  479. 3. Privileged tools (like `execute_sql`) require `service_role` JWT
  480. 4. CORS is configured via Kong - adjust origins for your deployment
  481. ## Development
  482. * **Language:** TypeScript
  483. * **Build:** `bun build` (via `bun run build`)
  484. * **Runtime:** [Bun](https://bun.sh/) v1.1+
  485. * **Test runner:** `bun test`
  486. * **Dependencies:** Managed via `bun` (`bun.lock`)
  487. * **Core Libraries:** `@supabase/supabase-js`, `pg` (node-postgres), `zod` (validation), `commander` (CLI args), `@modelcontextprotocol/sdk` (MCP server framework), `express`, `jsonwebtoken`.
  488. ## License
  489. This project is licensed under the MIT License. See the LICENSE file for details.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.