├── .github └── workflows │ └── tests.yml ├── .gitignore ├── LICENSE ├── README.md ├── biome.json ├── docs └── production.md ├── package-lock.json ├── package.json ├── packages ├── mcp-server-postgrest │ ├── README.md │ ├── package.json │ ├── src │ │ ├── index.ts │ │ ├── server.test.ts │ │ ├── server.ts │ │ ├── stdio.ts │ │ └── util.ts │ ├── tsconfig.json │ └── tsup.config.ts ├── mcp-server-supabase │ ├── .gitignore │ ├── package.json │ ├── src │ │ ├── content-api │ │ │ ├── graphql.test.ts │ │ │ ├── graphql.ts │ │ │ └── index.ts │ │ ├── edge-function.ts │ │ ├── eszip.test.ts │ │ ├── eszip.ts │ │ ├── index.test.ts │ │ ├── index.ts │ │ ├── logs.ts │ │ ├── management-api │ │ │ ├── index.ts │ │ │ └── types.ts │ │ ├── password.test.ts │ │ ├── password.ts │ │ ├── pg-meta │ │ │ ├── columns.sql │ │ │ ├── extensions.sql │ │ │ ├── index.ts │ │ │ ├── tables.sql │ │ │ └── types.ts │ │ ├── platform │ │ │ ├── api-platform.ts │ │ │ ├── index.ts │ │ │ └── types.ts │ │ ├── pricing.ts │ │ ├── regions.test.ts │ │ ├── regions.ts │ │ ├── server.test.ts │ │ ├── server.ts │ │ ├── tools │ │ │ ├── branching-tools.ts │ │ │ ├── database-operation-tools.ts │ │ │ ├── debugging-tools.ts │ │ │ ├── development-tools.ts │ │ │ ├── docs-tools.ts │ │ │ ├── edge-function-tools.ts │ │ │ ├── project-management-tools.ts │ │ │ └── util.ts │ │ ├── transports │ │ │ └── stdio.ts │ │ ├── types │ │ │ └── sql.d.ts │ │ ├── util.test.ts │ │ └── util.ts │ ├── test │ │ ├── extensions.d.ts │ │ ├── extensions.ts │ │ ├── llm.e2e.ts │ │ ├── mocks.ts │ │ ├── plugins │ │ │ └── text-loader.ts │ │ └── stdio.integration.ts │ ├── tsconfig.json │ ├── tsup.config.ts │ ├── vitest.config.ts │ ├── vitest.setup.ts │ └── vitest.workspace.ts └── mcp-utils │ ├── README.md │ ├── package.json │ ├── src │ ├── index.ts │ ├── server.test.ts │ ├── server.ts │ ├── stream-transport.ts │ ├── types.ts │ ├── util.test.ts │ └── util.ts │ ├── tsconfig.json │ └── tsup.config.ts └── supabase ├── config.toml ├── migrations ├── 20241220232417_todos.sql └── 20250109000000_add_todo_policies.sql └── seed.sql /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: 3 | push: 4 | branches: [main] 5 | pull_request: 6 | branches: [main] 7 | jobs: 8 | test: 9 | timeout-minutes: 60 10 | runs-on: ubuntu-latest 11 | env: 12 | ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: actions/setup-node@v4 16 | with: 17 | node-version: lts/* 18 | cache: 'npm' 19 | - name: Install dependencies 20 | run: npm ci --ignore-scripts 21 | - name: Build libs 22 | run: | 23 | npm run build 24 | npm rebuild # To create bin links 25 | - name: Tests 26 | run: npm run test:coverage 27 | - name: Upload coverage results to Coveralls 28 | uses: coverallsapp/github-action@v2 29 | with: 30 | base-path: ./packages/mcp-server-supabase 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | .branches/ 4 | .temp/ 5 | .DS_Store 6 | .env* 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2025 Supabase 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Supabase MCP Server 2 | 3 | > Connect your Supabase projects to Cursor, Claude, Windsurf, and other AI assistants. 4 | 5 | ![supabase-mcp-demo](https://github.com/user-attachments/assets/3fce101a-b7d4-482f-9182-0be70ed1ad56) 6 | 7 | The [Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) standardizes how Large Language Models (LLMs) talk to external services like Supabase. It connects AI assistants directly with your Supabase project and allows them to perform tasks like managing tables, fetching config, and querying data. See the [full list of tools](#tools). 8 | 9 | ## Prerequisites 10 | 11 | You will need Node.js installed on your machine. You can check this by running: 12 | 13 | ```shell 14 | node -v 15 | ``` 16 | 17 | If you don't have Node.js installed, you can download it from [nodejs.org](https://nodejs.org/). 18 | 19 | ## Setup 20 | 21 | ### 1. Personal access token (PAT) 22 | 23 | First, go to your [Supabase settings](https://supabase.com/dashboard/account/tokens) and create a personal access token. Give it a name that describes its purpose, like "Cursor MCP Server". 24 | 25 | This will be used to authenticate the MCP server with your Supabase account. Make sure to copy the token, as you won't be able to see it again. 26 | 27 | ### 2. Configure MCP client 28 | 29 | Next, configure your MCP client (such as Cursor) to use this server. Most MCP clients store the configuration as JSON in the following format: 30 | 31 | ```json 32 | { 33 | "mcpServers": { 34 | "supabase": { 35 | "command": "npx", 36 | "args": [ 37 | "-y", 38 | "@supabase/mcp-server-supabase@latest", 39 | "--access-token", 40 | "" 41 | ] 42 | } 43 | } 44 | } 45 | ``` 46 | 47 | Replace `` with the token you created in step 1. Alternatively you can omit `--access-token` and instead set the `SUPABASE_ACCESS_TOKEN` environment variable to your personal access token (you will need to restart your MCP client after setting this). This allows you to keep your token out of version control if you plan on committing this configuration to a repository. 48 | 49 | The following additional options are available: 50 | 51 | - `--project-ref`: Used to scope the server to a specific project. See [project scoped mode](#project-scoped-mode). 52 | - `--read-only`: Used to restrict the server to read-only queries. See [read-only mode](#read-only-mode). 53 | 54 | If you are on Windows, you will need to [prefix the command](#windows). If your MCP client doesn't accept JSON, the direct CLI command is: 55 | 56 | ```shell 57 | npx -y @supabase/mcp-server-supabase@latest --access-token= 58 | ``` 59 | 60 | > Note: Do not run this command directly - this is meant to be executed by your MCP client in order to start the server. `npx` automatically downloads the latest version of the MCP server from `npm` and runs it in a single command. 61 | 62 | #### Windows 63 | 64 | On Windows, you will need to prefix the command with `cmd /c`: 65 | 66 | ```json 67 | { 68 | "mcpServers": { 69 | "supabase": { 70 | "command": "cmd", 71 | "args": [ 72 | "/c", 73 | "npx", 74 | "-y", 75 | "@supabase/mcp-server-supabase@latest", 76 | "--access-token", 77 | "" 78 | ] 79 | } 80 | } 81 | } 82 | ``` 83 | 84 | or with `wsl` if you are running Node.js inside WSL: 85 | 86 | ```json 87 | { 88 | "mcpServers": { 89 | "supabase": { 90 | "command": "wsl", 91 | "args": [ 92 | "npx", 93 | "-y", 94 | "@supabase/mcp-server-supabase@latest", 95 | "--access-token", 96 | "" 97 | ] 98 | } 99 | } 100 | } 101 | ``` 102 | 103 | Make sure Node.js is available in your system `PATH` environment variable. If you are running Node.js natively on Windows, you can set this by running the following commands in your terminal. 104 | 105 | 1. Get the path to `npm`: 106 | 107 | ```shell 108 | npm config get prefix 109 | ``` 110 | 111 | 2. Add the directory to your PATH: 112 | 113 | ```shell 114 | setx PATH "%PATH%;" 115 | ``` 116 | 117 | 3. Restart your MCP client. 118 | 119 | ### Project scoped mode 120 | 121 | By default, the MCP server will have access to all organizations and projects in your Supabase account. If you want to restrict the server to a specific project, you can set the `--project-ref` flag on the CLI command: 122 | 123 | ```shell 124 | npx -y @supabase/mcp-server-supabase@latest --access-token= --project-ref= 125 | ``` 126 | 127 | Replace `` with the ID of your project. You can find this under **Project ID** in your Supabase [project settings](https://supabase.com/dashboard/project/_/settings/general). 128 | 129 | After scoping the server to a project, [account-level](#project-management) tools like `list_projects` and `list_organizations` will no longer be available. The server will only have access to the specified project and its resources. 130 | 131 | ### Read-only mode 132 | 133 | If you wish to restrict the Supabase MCP server to read-only queries, set the `--read-only` flag on the CLI command: 134 | 135 | ```shell 136 | npx -y @supabase/mcp-server-supabase@latest --access-token= --read-only 137 | ``` 138 | 139 | This prevents write operations on any of your databases by executing SQL as a read-only Postgres user. Note that this flag only applies to database tools (`execute_sql` and `apply_migration`) and not to other tools like `create_project` or `create_branch`. 140 | 141 | ## Tools 142 | 143 | _**Note:** This server is pre-1.0, so expect some breaking changes between versions. Since LLMs will automatically adapt to the tools available, this shouldn't affect most users._ 144 | 145 | The following Supabase tools are available to the LLM: 146 | 147 | #### Project Management 148 | 149 | _**Note:** these tools will be unavailable if the server is [scoped to a project](#project-scoped-mode)._ 150 | 151 | - `list_projects`: Lists all Supabase projects for the user. 152 | - `get_project`: Gets details for a project. 153 | - `create_project`: Creates a new Supabase project. 154 | - `pause_project`: Pauses a project. 155 | - `restore_project`: Restores a project. 156 | - `list_organizations`: Lists all organizations that the user is a member of. 157 | - `get_organization`: Gets details for an organization. 158 | 159 | #### Database Operations 160 | 161 | - `list_tables`: Lists all tables within the specified schemas. 162 | - `list_extensions`: Lists all extensions in the database. 163 | - `list_migrations`: Lists all migrations in the database. 164 | - `apply_migration`: Applies a SQL migration to the database. SQL passed to this tool will be tracked within the database, so LLMs should use this for DDL operations (schema changes). 165 | - `execute_sql`: Executes raw SQL in the database. LLMs should use this for regular queries that don't change the schema. 166 | - `get_logs`: Gets logs for a Supabase project by service type (api, postgres, edge functions, auth, storage, realtime). LLMs can use this to help with debugging and monitoring service performance. 167 | 168 | #### Edge Function Management 169 | 170 | - `list_edge_functions`: Lists all Edge Functions in a Supabase project. 171 | - `deploy_edge_function`: Deploys a new Edge Function to a Supabase project. LLMs can use this to deploy new functions or update existing ones. 172 | 173 | #### Project Configuration 174 | 175 | - `get_project_url`: Gets the API URL for a project. 176 | - `get_anon_key`: Gets the anonymous API key for a project. 177 | 178 | #### Branching (Experimental, requires a paid plan) 179 | 180 | - `create_branch`: Creates a development branch with migrations from production branch. 181 | - `list_branches`: Lists all development branches. 182 | - `delete_branch`: Deletes a development branch. 183 | - `merge_branch`: Merges migrations and edge functions from a development branch to production. 184 | - `reset_branch`: Resets migrations of a development branch to a prior version. 185 | - `rebase_branch`: Rebases development branch on production to handle migration drift. 186 | 187 | #### Development Tools 188 | 189 | - `search_docs`: Searches the Supabase documentation for up-to-date information. LLMs can use this to find answers to questions or learn how to use specific features. 190 | - `generate_typescript_types`: Generates TypeScript types based on the database schema. LLMs can save this to a file and use it in their code. 191 | 192 | #### Cost Confirmation 193 | 194 | - `get_cost`: Gets the cost of a new project or branch for an organization. 195 | - `confirm_cost`: Confirms the user's understanding of new project or branch costs. This is required to create a new project or branch. 196 | 197 | ## Other MCP servers 198 | 199 | ### `@supabase/mcp-server-postgrest` 200 | 201 | The PostgREST MCP server allows you to connect your own users to your app via REST API. See more details on its [project README](./packages/mcp-server-postgrest). 202 | 203 | ## Resources 204 | 205 | - [**Model Context Protocol**](https://modelcontextprotocol.io/introduction): Learn more about MCP and its capabilities. 206 | - [**From development to production**](/docs/production.md): Learn how to safely promote changes to production environments. 207 | 208 | ## For developers 209 | 210 | This repo uses npm for package management, and the latest LTS version of Node.js. 211 | 212 | Clone the repo and run: 213 | 214 | ``` 215 | npm install --ignore-scripts 216 | ``` 217 | 218 | > [!NOTE] 219 | > On recent versions of MacOS, you may have trouble installing the `libpg-query` transient dependency without the `--ignore-scripts` flag. 220 | 221 | ## License 222 | 223 | This project is licensed under Apache 2.0. See the [LICENSE](./LICENSE) file for details. 224 | -------------------------------------------------------------------------------- /biome.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", 3 | "vcs": { 4 | "enabled": false, 5 | "clientKind": "git", 6 | "useIgnoreFile": false 7 | }, 8 | "files": { 9 | "ignoreUnknown": false, 10 | "ignore": [ 11 | "**/dist", 12 | "packages/mcp-server-supabase/src/management-api/types.ts" 13 | ] 14 | }, 15 | "formatter": { 16 | "enabled": true, 17 | "indentStyle": "space" 18 | }, 19 | "organizeImports": { 20 | "enabled": false 21 | }, 22 | "linter": { 23 | "enabled": false 24 | }, 25 | "javascript": { 26 | "formatter": { 27 | "quoteStyle": "single", 28 | "trailingCommas": "es5", 29 | "bracketSameLine": false, 30 | "arrowParentheses": "always" 31 | } 32 | }, 33 | "json": { 34 | "formatter": { 35 | "trailingCommas": "none" 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /docs/production.md: -------------------------------------------------------------------------------- 1 | ## From development to production 2 | 3 | After releasing your app to the world, we recommend creating a development branch for working on new features and bug fixes. 4 | 5 | Using a development branch, you can safely experiment with schema changes while minimizing the risk of data loss, downtime, or compatibility issues between your app and production database. 6 | 7 | ### Create a development branch 8 | 9 | Simply ask the LLM to "create a development branch", and it will invoke the `create_branch` MCP tool. 10 | 11 | The development branch clones your production branch by applying the same migrations shown by `list_migrations` tool. It does not include any untracked data or schema changes that came directly from users interacting with your app. 12 | 13 | Depending on the size of your migrations, your development branch may take up to a few minutes to setup. You can ask the LLM to check the branch status periodically using the `list_branches` tool. 14 | 15 | ### Create a new migration 16 | 17 | Once your development branch is ready, you can start building new features by invoking the `apply_migration` tool. This tool tracks any schema or data changes as a migration so that it can be replayed on your production branch when you are ready to deploy. 18 | 19 | When creating a migration that inserts static data, it is important to ask the LLM to avoid hardcoding foreign key references. Foreign keys are tied specifically to the data in your development branch so any migration relying on that will fail when applied to the production branch. 20 | 21 | When creating a destructive migration like dropping a column, you must review the generated SQL statements and the current state of your database to confirm that the data loss is expected and acceptable. 22 | 23 | After successfully applying a migration, you can test your database changes by connecting your app to the development branch. The branch project URL and API keys can be fetched using `get_project_url` and `get_anon_key` tools respectively. Save them in your `.env` file to avoid repeating this in the future. 24 | 25 | ### Revert a migration 26 | 27 | If you have discovered any issues during testing and want to revert a migration, simply ask the LLM to reset the last `n` migrations or by specifying a specific version number, like `20250401000000`. You can find the version numbers used for previous migrations by asking the LLM to list migrations (`list_migrations` tool). You will be prompted to invoke the `reset_branch` tool to revert the development branch back to the specified migration version. 28 | 29 | The reset process may take up to a few minutes to complete depending on the size of your migrations. Once it's ready, the branch status will be updated to `FUNCTIONS_DEPLOYED` so that the LLM is aware. All untracked data and schema changes will be cleared by the reset. 30 | 31 | If you want to rollback a migration that has already been applied on the production branch, do not use the `reset_branch` tool. Instead, ask the LLM to create a new migration that reverts changes made in a prior migration. This ensures that your migrations on production branch are always rolling forward without causing compatibility issues with your development branch. 32 | 33 | ### Merge to production 34 | 35 | Now that you are done developing your new feature, it is time to merge it back to the production branch. You can do that by invoking the `merge_branch` tool. 36 | 37 | Merging a development branch is equivalent to applying new migrations incrementally on the production branch. Since these migrations have been tested and verified on your development branch, they are generally safe to execute on your production data. 38 | 39 | If you encounter any errors during the merge, the production branch status will be updated to `MIGRATIONS_FAILED`. You can ask the LLM to lookup the exact error for this branch action using the `get_logs` tool. To fix these errors, you must follow these steps. 40 | 41 | 1. Reset the problematic migration from your development branch. 42 | 2. Apply a new migration with the fix on your development branch. 43 | 3. Merge the development branch to production. 44 | 45 | Only successful migrations are tracked so it is safe to merge the same development branch multiple times. 46 | 47 | ### Delete a development branch 48 | 49 | Finally, after merging all changes to production, you can delete the development branch using the `delete_branch` tool. This helps you save on resources as any active development branch will be billed at $0.01344 per hour. 50 | 51 | ### Rebase a development branch 52 | 53 | Sometimes it is unavoidable to apply a hotfix migration on your production database directly. As a result, your development branch may be behind your production branch in terms of migration versions. 54 | 55 | Similarly, if you are working in a team where each member works on a separate development branch, merging branches in different order could also result in migration drift. 56 | 57 | To fix this problem, you can either recreate your development branch or invoke the `rebase_branch` tool. This tool incrementally applies new migrations from the production branch back on to the development branch. 58 | 59 | ### Conclusion 60 | 61 | To summarise our workflow using development and production branches, we expose 3 core tools for managing migrations. 62 | 63 | 1. `rebase_branch`: This tool brings the development branch in sync with the production branch, covering cases where production is ahead of development. Creating a new development branch runs this tool implicitly. If you use multiple development branches, merging branch A after creating branch B could also result in migration drift. You can run rebase on branch B to recover from drift. 64 | 65 | 2. `merge_branch`: This tool brings production in sync with development, covering cases where development is ahead of production. Running this tool will apply new migrations from development to the production branch. Any failures should be resolved on the development branch before retrying. 66 | 67 | 3. `reset_branch`: This tool is an escape hatch to cover all other cases where migrations are different between production and development. By default it resets the development branch to the latest migration, dropping any untracked tables and data. You can also specify a prior migration version to revert a migration that's already applied on development. A version of 0 will reset the development to a fresh database. 68 | 69 | Mastering this workflow goes a long way to ensure your production app is always ready when you release new features and bug fixes. 70 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "workspaces": ["packages/*"], 3 | "scripts": { 4 | "build": "npm run build --workspace @supabase/mcp-utils --workspace @supabase/mcp-server-supabase", 5 | "test": "npm run test --workspace @supabase/mcp-utils --workspace @supabase/mcp-server-supabase", 6 | "test:coverage": "npm run test:coverage --workspace @supabase/mcp-server-supabase", 7 | "format": "biome check --write .", 8 | "format:check": "biome check ." 9 | }, 10 | "devDependencies": { 11 | "@biomejs/biome": "1.9.4", 12 | "supabase": "^2.1.1" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /packages/mcp-server-postgrest/README.md: -------------------------------------------------------------------------------- 1 | # @supabase/mcp-server-postgrest 2 | 3 | This is an MCP server for [PostgREST](https://postgrest.org). It allows LLMs to perform CRUD operations on your app via REST API. 4 | 5 | This server works with Supabase projects (which run PostgREST) and any standalone PostgREST server. 6 | 7 | ## Tools 8 | 9 | The following tools are available: 10 | 11 | ### `postgrestRequest` 12 | 13 | Performs an HTTP request to a [configured](#usage) PostgREST server. It accepts the following arguments: 14 | 15 | - `method`: The HTTP method to use (eg. `GET`, `POST`, `PATCH`, `DELETE`) 16 | - `path`: The path to query (eg. `/todos?id=eq.1`) 17 | - `body`: The request body (for `POST` and `PATCH` requests) 18 | 19 | It returns the JSON response from the PostgREST server, including selected rows for `GET` requests and updated rows for `POST` and `PATCH` requests. 20 | 21 | ### `sqlToRest` 22 | 23 | Converts a SQL query to the equivalent PostgREST syntax (as method and path). Useful for complex queries that LLMs would otherwise struggle to convert to valid PostgREST syntax. 24 | 25 | Note that PostgREST only supports a subset of SQL, so not all queries will convert. See [`sql-to-rest`](https://github.com/supabase-community/sql-to-rest) for more details. 26 | 27 | It accepts the following arguments: 28 | 29 | - `sql`: The SQL query to convert. 30 | 31 | It returns an object containing `method` and `path` properties for the request. LLMs can then use the `postgrestRequest` tool to execute the request. 32 | 33 | ## Usage 34 | 35 | ### With Claude Desktop 36 | 37 | [Claude Desktop](https://claude.ai/download) is a popular LLM client that supports the Model Context Protocol. You can connect your PostgREST server to Claude Desktop to query your database via natural language commands. 38 | 39 | You can add MCP servers to Claude Desktop via its config file at: 40 | 41 | - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json` 42 | 43 | - Windows:`%APPDATA%\Claude\claude_desktop_config.json` 44 | 45 | To add your Supabase project _(or any PostgREST server)_ to Claude Desktop, add the following configuration to the `mcpServers` object in the config file: 46 | 47 | ```json 48 | { 49 | "mcpServers": { 50 | "todos": { 51 | "command": "npx", 52 | "args": [ 53 | "-y", 54 | "@supabase/mcp-server-postgrest@latest", 55 | "--apiUrl", 56 | "https://your-project-ref.supabase.co/rest/v1", 57 | "--apiKey", 58 | "your-anon-key", 59 | "--schema", 60 | "public" 61 | ] 62 | } 63 | } 64 | } 65 | ``` 66 | 67 | #### Configuration 68 | 69 | - `apiUrl`: The base URL of your PostgREST endpoint 70 | 71 | - `apiKey`: Your API key for authentication _(optional)_ 72 | 73 | - `schema`: The Postgres schema to serve the API from (eg. `public`). Note any non-public schemas must be manually exposed from PostgREST. 74 | 75 | ### Programmatically (custom MCP client) 76 | 77 | If you're building your own MCP client, you can connect to a PostgREST server programmatically using your preferred transport. The [MCP SDK](https://github.com/modelcontextprotocol/typescript-sdk) offers built-in [stdio](https://modelcontextprotocol.io/docs/concepts/transports#standard-input-output-stdio) and [SSE](https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse) transports. We also offer a [`StreamTransport`](../mcp-utils#streamtransport) if you wish to directly connect to MCP servers in-memory or by piping over your own stream-based transport. 78 | 79 | #### Installation 80 | 81 | ```bash 82 | npm i @supabase/mcp-server-postgrest 83 | ``` 84 | 85 | ```bash 86 | yarn add @supabase/mcp-server-postgrest 87 | ``` 88 | 89 | ```bash 90 | pnpm add @supabase/mcp-server-postgrest 91 | ``` 92 | 93 | #### Example 94 | 95 | The following example uses the [`StreamTransport`](../mcp-utils#streamtransport) to connect directly between an MCP client and server. 96 | 97 | ```ts 98 | import { Client } from '@modelcontextprotocol/sdk/client/index.js'; 99 | import { StreamTransport } from '@supabase/mcp-utils'; 100 | import { createPostgrestMcpServer } from '@supabase/mcp-server-postgrest'; 101 | 102 | // Create a stream transport for both client and server 103 | const clientTransport = new StreamTransport(); 104 | const serverTransport = new StreamTransport(); 105 | 106 | // Connect the streams together 107 | clientTransport.readable.pipeTo(serverTransport.writable); 108 | serverTransport.readable.pipeTo(clientTransport.writable); 109 | 110 | const client = new Client( 111 | { 112 | name: 'MyClient', 113 | version: '0.1.0', 114 | }, 115 | { 116 | capabilities: {}, 117 | } 118 | ); 119 | 120 | const supabaseUrl = 'https://your-project-ref.supabase.co'; // http://127.0.0.1:54321 for local 121 | const apiKey = 'your-anon-key'; // or service role, or user JWT 122 | const schema = 'public'; // or any other exposed schema 123 | 124 | const server = createPostgrestMcpServer({ 125 | apiUrl: `${supabaseUrl}/rest/v1`, 126 | apiKey, 127 | schema, 128 | }); 129 | 130 | // Connect the client and server to their respective transports 131 | await server.connect(serverTransport); 132 | await client.connect(clientTransport); 133 | 134 | // Call tools, etc 135 | const output = await client.callTool({ 136 | name: 'postgrestRequest', 137 | arguments: { 138 | method: 'GET', 139 | path: '/todos', 140 | }, 141 | }); 142 | ``` 143 | -------------------------------------------------------------------------------- /packages/mcp-server-postgrest/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@supabase/mcp-server-postgrest", 3 | "version": "0.1.0", 4 | "description": "MCP server for PostgREST", 5 | "license": "Apache-2.0", 6 | "type": "module", 7 | "main": "dist/index.cjs", 8 | "types": "dist/index.d.ts", 9 | "sideEffects": false, 10 | "scripts": { 11 | "build": "tsup --clean", 12 | "prepublishOnly": "npm run build", 13 | "test": "vitest" 14 | }, 15 | "files": ["dist/**/*"], 16 | "bin": { 17 | "mcp-server-postgrest": "./dist/stdio.js" 18 | }, 19 | "exports": { 20 | ".": { 21 | "import": "./dist/index.js", 22 | "types": "./dist/index.d.ts", 23 | "default": "./dist/index.cjs" 24 | } 25 | }, 26 | "dependencies": { 27 | "@modelcontextprotocol/sdk": "^1.11.0", 28 | "@supabase/mcp-utils": "^0.2.1", 29 | "@supabase/sql-to-rest": "^0.1.8", 30 | "zod": "^3.24.1", 31 | "zod-to-json-schema": "^3.24.1" 32 | }, 33 | "devDependencies": { 34 | "@supabase/auth-js": "^2.67.3", 35 | "@total-typescript/tsconfig": "^1.0.4", 36 | "@types/node": "^22.8.6", 37 | "prettier": "^3.3.3", 38 | "tsup": "^8.3.5", 39 | "tsx": "^4.19.2", 40 | "typescript": "^5.6.3", 41 | "vitest": "^2.1.9" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /packages/mcp-server-postgrest/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './server.js'; 2 | -------------------------------------------------------------------------------- /packages/mcp-server-postgrest/src/server.ts: -------------------------------------------------------------------------------- 1 | import { 2 | createMcpServer, 3 | jsonResource, 4 | jsonResourceResponse, 5 | resources, 6 | tool, 7 | } from '@supabase/mcp-utils'; 8 | import { processSql, renderHttp } from '@supabase/sql-to-rest'; 9 | import { z } from 'zod'; 10 | import { version } from '../package.json'; 11 | import { ensureNoTrailingSlash, ensureTrailingSlash } from './util.js'; 12 | 13 | export type PostgrestMcpServerOptions = { 14 | apiUrl: string; 15 | apiKey?: string; 16 | schema: string; 17 | }; 18 | 19 | /** 20 | * Creates an MCP server for interacting with a PostgREST API. 21 | */ 22 | export function createPostgrestMcpServer(options: PostgrestMcpServerOptions) { 23 | const apiUrl = ensureNoTrailingSlash(options.apiUrl); 24 | const apiKey = options.apiKey; 25 | const schema = options.schema; 26 | 27 | function getHeaders( 28 | method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' = 'GET' 29 | ) { 30 | const schemaHeader = 31 | method === 'GET' ? 'accept-profile' : 'content-profile'; 32 | 33 | const headers: HeadersInit = { 34 | 'content-type': 'application/json', 35 | prefer: 'return=representation', 36 | [schemaHeader]: schema, 37 | }; 38 | 39 | if (apiKey) { 40 | headers.apikey = apiKey; 41 | headers.authorization = `Bearer ${apiKey}`; 42 | } 43 | 44 | return headers; 45 | } 46 | 47 | return createMcpServer({ 48 | name: 'supabase/postgrest', 49 | version, 50 | resources: resources('postgrest', [ 51 | jsonResource('/spec', { 52 | name: 'OpenAPI spec', 53 | description: 'OpenAPI spec for the PostgREST API', 54 | async read(uri) { 55 | const response = await fetch(ensureTrailingSlash(apiUrl), { 56 | headers: getHeaders(), 57 | }); 58 | 59 | const result = await response.json(); 60 | return jsonResourceResponse(uri, result); 61 | }, 62 | }), 63 | ]), 64 | tools: { 65 | postgrestRequest: tool({ 66 | description: 'Performs an HTTP request against the PostgREST API', 67 | parameters: z.object({ 68 | method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']), 69 | path: z.string(), 70 | body: z 71 | .union([ 72 | z.record(z.string(), z.unknown()), 73 | z.array(z.record(z.string(), z.unknown())), 74 | ]) 75 | .optional(), 76 | }), 77 | async execute({ method, path, body }) { 78 | const url = new URL(`${apiUrl}${path}`); 79 | 80 | const headers = getHeaders(method); 81 | 82 | if (method !== 'GET') { 83 | headers['content-type'] = 'application/json'; 84 | } 85 | 86 | const response = await fetch(url, { 87 | method, 88 | headers, 89 | body: body ? JSON.stringify(body) : undefined, 90 | }); 91 | 92 | return await response.json(); 93 | }, 94 | }), 95 | sqlToRest: tool({ 96 | description: 97 | 'Converts SQL query to a PostgREST API request (method, path)', 98 | parameters: z.object({ 99 | sql: z.string(), 100 | }), 101 | execute: async ({ sql }) => { 102 | const statement = await processSql(sql); 103 | const request = await renderHttp(statement); 104 | 105 | return { 106 | method: request.method, 107 | path: request.fullPath, 108 | }; 109 | }, 110 | }), 111 | }, 112 | }); 113 | } 114 | -------------------------------------------------------------------------------- /packages/mcp-server-postgrest/src/stdio.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; 4 | import { parseArgs } from 'node:util'; 5 | import { createPostgrestMcpServer } from './server.js'; 6 | 7 | async function main() { 8 | const { 9 | values: { apiUrl, apiKey, schema }, 10 | } = parseArgs({ 11 | options: { 12 | apiUrl: { 13 | type: 'string', 14 | }, 15 | apiKey: { 16 | type: 'string', 17 | }, 18 | schema: { 19 | type: 'string', 20 | }, 21 | }, 22 | }); 23 | 24 | if (!apiUrl) { 25 | console.error('Please provide a base URL with the --apiUrl flag'); 26 | process.exit(1); 27 | } 28 | 29 | if (!schema) { 30 | console.error('Please provide a schema with the --schema flag'); 31 | process.exit(1); 32 | } 33 | 34 | const server = createPostgrestMcpServer({ 35 | apiUrl, 36 | apiKey, 37 | schema, 38 | }); 39 | 40 | const transport = new StdioServerTransport(); 41 | 42 | await server.connect(transport); 43 | } 44 | 45 | main().catch(console.error); 46 | -------------------------------------------------------------------------------- /packages/mcp-server-postgrest/src/util.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Ensures that a URL has a trailing slash. 3 | */ 4 | export function ensureTrailingSlash(url: string) { 5 | return url.endsWith('/') ? url : `${url}/`; 6 | } 7 | 8 | /** 9 | * Ensures that a URL does not have a trailing slash. 10 | */ 11 | export function ensureNoTrailingSlash(url: string) { 12 | return url.endsWith('/') ? url.slice(0, -1) : url; 13 | } 14 | -------------------------------------------------------------------------------- /packages/mcp-server-postgrest/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@total-typescript/tsconfig/bundler/dom/library", 3 | "include": ["src/**/*.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /packages/mcp-server-postgrest/tsup.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'tsup'; 2 | 3 | export default defineConfig([ 4 | { 5 | entry: ['src/index.ts', 'src/stdio.ts'], 6 | format: ['cjs', 'esm'], 7 | outDir: 'dist', 8 | sourcemap: true, 9 | dts: true, 10 | minify: true, 11 | splitting: true, 12 | }, 13 | ]); 14 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/.gitignore: -------------------------------------------------------------------------------- 1 | test/coverage 2 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@supabase/mcp-server-supabase", 3 | "version": "0.4.2", 4 | "description": "MCP server for interacting with Supabase", 5 | "license": "Apache-2.0", 6 | "type": "module", 7 | "main": "dist/index.cjs", 8 | "types": "dist/index.d.ts", 9 | "sideEffects": false, 10 | "scripts": { 11 | "build": "tsup --clean", 12 | "prepublishOnly": "npm run build", 13 | "test": "vitest", 14 | "test:unit": "vitest --project unit", 15 | "test:e2e": "vitest --project e2e", 16 | "test:integration": "vitest --project integration", 17 | "test:coverage": "vitest --coverage", 18 | "generate:management-api-types": "openapi-typescript https://api.supabase.com/api/v1-json -o ./src/management-api/types.ts" 19 | }, 20 | "files": ["dist/**/*"], 21 | "bin": { 22 | "mcp-server-supabase": "./dist/transports/stdio.js" 23 | }, 24 | "exports": { 25 | ".": { 26 | "import": "./dist/index.js", 27 | "types": "./dist/index.d.ts", 28 | "default": "./dist/index.cjs" 29 | }, 30 | "./platform": { 31 | "import": "./dist/platform/index.js", 32 | "types": "./dist/platform/index.d.ts", 33 | "default": "./dist/platform/index.cjs" 34 | } 35 | }, 36 | "dependencies": { 37 | "@deno/eszip": "^0.84.0", 38 | "@modelcontextprotocol/sdk": "^1.11.0", 39 | "@supabase/mcp-utils": "0.2.1", 40 | "common-tags": "^1.8.2", 41 | "graphql": "^16.11.0", 42 | "openapi-fetch": "^0.13.5", 43 | "zod": "^3.24.1" 44 | }, 45 | "devDependencies": { 46 | "@ai-sdk/anthropic": "^1.2.9", 47 | "@electric-sql/pglite": "^0.2.17", 48 | "@total-typescript/tsconfig": "^1.0.4", 49 | "@types/common-tags": "^1.8.4", 50 | "@types/node": "^22.8.6", 51 | "@vitest/coverage-v8": "^2.1.9", 52 | "ai": "^4.3.4", 53 | "date-fns": "^4.1.0", 54 | "dotenv": "^16.5.0", 55 | "msw": "^2.7.3", 56 | "nanoid": "^5.1.5", 57 | "openapi-typescript": "^7.5.0", 58 | "openapi-typescript-helpers": "^0.0.15", 59 | "prettier": "^3.3.3", 60 | "tsup": "^8.3.5", 61 | "tsx": "^4.19.2", 62 | "typescript": "^5.6.3", 63 | "vitest": "^2.1.9" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/content-api/graphql.test.ts: -------------------------------------------------------------------------------- 1 | import { stripIndent } from 'common-tags'; 2 | import { describe, expect, it } from 'vitest'; 3 | import { GraphQLClient } from './graphql.js'; 4 | 5 | describe('graphql client', () => { 6 | it('should load schema', async () => { 7 | const schema = stripIndent` 8 | schema { 9 | query: RootQueryType 10 | } 11 | type RootQueryType { 12 | message: String! 13 | } 14 | `; 15 | 16 | const graphqlClient = new GraphQLClient({ 17 | url: 'dummy-url', 18 | loadSchema: async () => schema, 19 | }); 20 | 21 | const { source } = await graphqlClient.schemaLoaded; 22 | 23 | expect(source).toBe(schema); 24 | }); 25 | 26 | it('should throw error if validation requested but loadSchema not provided', async () => { 27 | const graphqlClient = new GraphQLClient({ 28 | url: 'dummy-url', 29 | }); 30 | 31 | await expect( 32 | graphqlClient.query( 33 | { query: '{ getHelloWorld }' }, 34 | { validateSchema: true } 35 | ) 36 | ).rejects.toThrow('No schema loader provided'); 37 | }); 38 | 39 | it('should throw for invalid query regardless of schema', async () => { 40 | const graphqlClient = new GraphQLClient({ 41 | url: 'dummy-url', 42 | }); 43 | 44 | await expect( 45 | graphqlClient.query({ query: 'invalid graphql query' }) 46 | ).rejects.toThrow( 47 | 'Invalid GraphQL query: Syntax Error: Unexpected Name "invalid"' 48 | ); 49 | }); 50 | 51 | it("should throw error if query doesn't match schema", async () => { 52 | const schema = stripIndent` 53 | schema { 54 | query: RootQueryType 55 | } 56 | type RootQueryType { 57 | message: String! 58 | } 59 | `; 60 | 61 | const graphqlClient = new GraphQLClient({ 62 | url: 'dummy-url', 63 | loadSchema: async () => schema, 64 | }); 65 | 66 | await expect( 67 | graphqlClient.query( 68 | { query: '{ invalidField }' }, 69 | { validateSchema: true } 70 | ) 71 | ).rejects.toThrow( 72 | 'Invalid GraphQL query: Cannot query field "invalidField" on type "RootQueryType"' 73 | ); 74 | }); 75 | 76 | it('bubbles up loadSchema errors', async () => { 77 | const graphqlClient = new GraphQLClient({ 78 | url: 'dummy-url', 79 | loadSchema: async () => { 80 | throw new Error('Failed to load schema'); 81 | }, 82 | }); 83 | 84 | await expect(graphqlClient.schemaLoaded).rejects.toThrow( 85 | 'Failed to load schema' 86 | ); 87 | }); 88 | }); 89 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/content-api/graphql.ts: -------------------------------------------------------------------------------- 1 | import { 2 | buildSchema, 3 | GraphQLError, 4 | GraphQLSchema, 5 | parse, 6 | validate, 7 | type DocumentNode, 8 | } from 'graphql'; 9 | import { z } from 'zod'; 10 | 11 | export const graphqlRequestSchema = z.object({ 12 | query: z.string(), 13 | variables: z.record(z.string(), z.unknown()).optional(), 14 | }); 15 | 16 | export const graphqlResponseSuccessSchema = z.object({ 17 | data: z.record(z.string(), z.unknown()), 18 | errors: z.undefined(), 19 | }); 20 | 21 | export const graphqlErrorSchema = z.object({ 22 | message: z.string(), 23 | locations: z.array( 24 | z.object({ 25 | line: z.number(), 26 | column: z.number(), 27 | }) 28 | ), 29 | }); 30 | 31 | export const graphqlResponseErrorSchema = z.object({ 32 | data: z.undefined(), 33 | errors: z.array(graphqlErrorSchema), 34 | }); 35 | 36 | export const graphqlResponseSchema = z.union([ 37 | graphqlResponseSuccessSchema, 38 | graphqlResponseErrorSchema, 39 | ]); 40 | 41 | export type GraphQLRequest = z.infer; 42 | export type GraphQLResponse = z.infer; 43 | 44 | export type QueryFn = ( 45 | request: GraphQLRequest 46 | ) => Promise>; 47 | 48 | export type QueryOptions = { 49 | validateSchema?: boolean; 50 | }; 51 | 52 | export type GraphQLClientOptions = { 53 | /** 54 | * The URL of the GraphQL endpoint. 55 | */ 56 | url: string; 57 | 58 | /** 59 | * A function that loads the GraphQL schema. 60 | * This will be used for validating future queries. 61 | * 62 | * A `query` function is provided that can be used to 63 | * execute GraphQL queries against the endpoint 64 | * (e.g. if the API itself allows querying the schema). 65 | */ 66 | loadSchema?({ query }: { query: QueryFn }): Promise; 67 | 68 | /** 69 | * Optional headers to include in the request. 70 | */ 71 | headers?: Record; 72 | }; 73 | 74 | export class GraphQLClient { 75 | #url: string; 76 | #headers: Record; 77 | 78 | /** 79 | * A promise that resolves when the schema is loaded via 80 | * the `loadSchema` function. 81 | * 82 | * Resolves to an object containing the raw schema source 83 | * string and the parsed GraphQL schema. 84 | * 85 | * Rejects if no `loadSchema` function was provided to 86 | * the constructor. 87 | */ 88 | schemaLoaded: Promise<{ 89 | /** 90 | * The raw GraphQL schema string. 91 | */ 92 | source: string; 93 | 94 | /** 95 | * The parsed GraphQL schema. 96 | */ 97 | schema: GraphQLSchema; 98 | }>; 99 | 100 | /** 101 | * Creates a new GraphQL client. 102 | */ 103 | constructor(options: GraphQLClientOptions) { 104 | this.#url = options.url; 105 | this.#headers = options.headers ?? {}; 106 | 107 | this.schemaLoaded = 108 | options 109 | .loadSchema?.({ query: this.#query.bind(this) }) 110 | .then((source) => ({ 111 | source, 112 | schema: buildSchema(source), 113 | })) ?? Promise.reject(new Error('No schema loader provided')); 114 | 115 | // Prevent unhandled promise rejections 116 | this.schemaLoaded.catch(() => {}); 117 | } 118 | 119 | /** 120 | * Executes a GraphQL query against the provided URL. 121 | */ 122 | async query( 123 | request: GraphQLRequest, 124 | options: QueryOptions = { validateSchema: true } 125 | ) { 126 | try { 127 | // Check that this is a valid GraphQL query 128 | const documentNode = parse(request.query); 129 | 130 | // Validate the query against the schema if requested 131 | if (options.validateSchema) { 132 | const { schema } = await this.schemaLoaded; 133 | const errors = validate(schema, documentNode); 134 | if (errors.length > 0) { 135 | throw new Error( 136 | `Invalid GraphQL query: ${errors.map((e) => e.message).join(', ')}` 137 | ); 138 | } 139 | } 140 | 141 | return this.#query(request); 142 | } catch (error) { 143 | // Make it obvious that this is a GraphQL error 144 | if (error instanceof GraphQLError) { 145 | throw new Error(`Invalid GraphQL query: ${error.message}`); 146 | } 147 | 148 | throw error; 149 | } 150 | } 151 | 152 | /** 153 | * Executes a GraphQL query against the provided URL. 154 | * 155 | * Does not validate the query against the schema. 156 | */ 157 | async #query(request: GraphQLRequest) { 158 | const { query, variables } = request; 159 | 160 | const response = await fetch(this.#url, { 161 | method: 'POST', 162 | headers: { 163 | ...this.#headers, 164 | 'Content-Type': 'application/json', 165 | Accept: 'application/json', 166 | }, 167 | body: JSON.stringify({ 168 | query, 169 | variables, 170 | }), 171 | }); 172 | 173 | if (!response.ok) { 174 | throw new Error( 175 | `Failed to fetch Supabase Content API GraphQL schema: HTTP status ${response.status}` 176 | ); 177 | } 178 | 179 | const json = await response.json(); 180 | 181 | const { data, error } = graphqlResponseSchema.safeParse(json); 182 | 183 | if (error) { 184 | throw new Error( 185 | `Failed to parse Supabase Content API response: ${error.message}` 186 | ); 187 | } 188 | 189 | if (data.errors) { 190 | throw new Error( 191 | `Supabase Content API GraphQL error: ${data.errors 192 | .map( 193 | (err) => 194 | `${err.message} (line ${err.locations[0]?.line ?? 'unknown'}, column ${err.locations[0]?.column ?? 'unknown'})` 195 | ) 196 | .join(', ')}` 197 | ); 198 | } 199 | 200 | return data.data; 201 | } 202 | } 203 | 204 | /** 205 | * Extracts the fields from a GraphQL query document. 206 | */ 207 | export function getQueryFields(document: DocumentNode) { 208 | return document.definitions 209 | .filter((def) => def.kind === 'OperationDefinition') 210 | .flatMap((def) => { 211 | if (def.kind === 'OperationDefinition' && def.selectionSet) { 212 | return def.selectionSet.selections 213 | .filter((sel) => sel.kind === 'Field') 214 | .map((sel) => { 215 | if (sel.kind === 'Field') { 216 | return sel.name.value; 217 | } 218 | return null; 219 | }) 220 | .filter(Boolean); 221 | } 222 | return []; 223 | }); 224 | } 225 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/content-api/index.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import { GraphQLClient, type GraphQLRequest, type QueryFn } from './graphql.js'; 3 | 4 | const contentApiSchemaResponseSchema = z.object({ 5 | schema: z.string(), 6 | }); 7 | 8 | export type ContentApiClient = { 9 | schema: string; 10 | query: QueryFn; 11 | }; 12 | 13 | export async function createContentApiClient( 14 | url: string, 15 | headers?: Record 16 | ): Promise { 17 | const graphqlClient = new GraphQLClient({ 18 | url, 19 | headers, 20 | // Content API provides schema string via `schema` query 21 | loadSchema: async ({ query }) => { 22 | const response = await query({ query: '{ schema }' }); 23 | const { schema } = contentApiSchemaResponseSchema.parse(response); 24 | return schema; 25 | }, 26 | }); 27 | 28 | const { source } = await graphqlClient.schemaLoaded; 29 | 30 | return { 31 | schema: source, 32 | async query(request: GraphQLRequest) { 33 | return graphqlClient.query(request); 34 | }, 35 | }; 36 | } 37 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/edge-function.ts: -------------------------------------------------------------------------------- 1 | import { codeBlock } from 'common-tags'; 2 | 3 | /** 4 | * Gets the deployment ID for an Edge Function. 5 | */ 6 | export function getDeploymentId( 7 | projectId: string, 8 | functionId: string, 9 | functionVersion: number 10 | ): string { 11 | return `${projectId}_${functionId}_${functionVersion}`; 12 | } 13 | 14 | /** 15 | * Gets the path prefix applied to each file in an Edge Function. 16 | */ 17 | export function getPathPrefix(deploymentId: string) { 18 | return `/tmp/user_fn_${deploymentId}/`; 19 | } 20 | 21 | export const edgeFunctionExample = codeBlock` 22 | import "jsr:@supabase/functions-js/edge-runtime.d.ts"; 23 | 24 | Deno.serve(async (req: Request) => { 25 | const data = { 26 | message: "Hello there!" 27 | }; 28 | 29 | return new Response(JSON.stringify(data), { 30 | headers: { 31 | 'Content-Type': 'application/json', 32 | 'Connection': 'keep-alive' 33 | } 34 | }); 35 | }); 36 | `; 37 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/eszip.test.ts: -------------------------------------------------------------------------------- 1 | import { codeBlock } from 'common-tags'; 2 | import { open, type FileHandle } from 'node:fs/promises'; 3 | import { describe, expect, test } from 'vitest'; 4 | import { bundleFiles, extractFiles } from './eszip.js'; 5 | 6 | describe('eszip', () => { 7 | test('extract files', async () => { 8 | const helloContent = codeBlock` 9 | export function hello(): string { 10 | return 'Hello, world!'; 11 | } 12 | `; 13 | const helloFile = new File([helloContent], 'hello.ts', { 14 | type: 'application/typescript', 15 | }); 16 | 17 | const indexContent = codeBlock` 18 | import { hello } from './hello.ts'; 19 | 20 | Deno.serve(async (req: Request) => { 21 | return new Response(hello(), { headers: { 'Content-Type': 'text/plain' } }) 22 | }); 23 | `; 24 | const indexFile = new File([indexContent], 'index.ts', { 25 | type: 'application/typescript', 26 | }); 27 | 28 | const eszip = await bundleFiles([indexFile, helloFile]); 29 | const extractedFiles = await extractFiles(eszip); 30 | 31 | expect(extractedFiles).toHaveLength(2); 32 | 33 | const extractedIndexFile = extractedFiles.find( 34 | (file) => file.name === 'index.ts' 35 | ); 36 | const extractedHelloFile = extractedFiles.find( 37 | (file) => file.name === 'hello.ts' 38 | ); 39 | 40 | expect(extractedIndexFile).toBeDefined(); 41 | expect(extractedIndexFile!.type).toBe('application/typescript'); 42 | await expect(extractedIndexFile!.text()).resolves.toBe(indexContent); 43 | 44 | expect(extractedHelloFile).toBeDefined(); 45 | expect(extractedHelloFile!.type).toBe('application/typescript'); 46 | await expect(extractedHelloFile!.text()).resolves.toBe(helloContent); 47 | }); 48 | }); 49 | 50 | export class Source implements UnderlyingSource { 51 | type = 'bytes' as const; 52 | autoAllocateChunkSize = 1024; 53 | 54 | path: string | URL; 55 | controller?: ReadableByteStreamController; 56 | file?: FileHandle; 57 | 58 | constructor(path: string | URL) { 59 | this.path = path; 60 | } 61 | 62 | async start(controller: ReadableStreamController) { 63 | if (!('byobRequest' in controller)) { 64 | throw new Error('ReadableStreamController does not support byobRequest'); 65 | } 66 | 67 | this.file = await open(this.path); 68 | this.controller = controller; 69 | } 70 | 71 | async pull() { 72 | if (!this.controller || !this.file) { 73 | throw new Error('ReadableStream has not been started'); 74 | } 75 | 76 | if (!this.controller.byobRequest) { 77 | throw new Error('ReadableStreamController does not support byobRequest'); 78 | } 79 | 80 | const view = this.controller.byobRequest.view as NodeJS.ArrayBufferView; 81 | 82 | if (!view) { 83 | throw new Error('ReadableStreamController does not have a view'); 84 | } 85 | 86 | const { bytesRead } = await this.file.read({ 87 | buffer: view, 88 | offset: view.byteOffset, 89 | length: view.byteLength, 90 | }); 91 | 92 | if (bytesRead === 0) { 93 | await this.file.close(); 94 | this.controller.close(); 95 | } 96 | 97 | this.controller.byobRequest.respond(view.byteLength); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/eszip.ts: -------------------------------------------------------------------------------- 1 | import { build, Parser } from '@deno/eszip'; 2 | import { join, relative } from 'node:path/posix'; 3 | import { fileURLToPath } from 'node:url'; 4 | import { z } from 'zod'; 5 | 6 | const parser = await Parser.createInstance(); 7 | const sourceMapSchema = z.object({ 8 | version: z.number(), 9 | sources: z.array(z.string()), 10 | sourcesContent: z.array(z.string()).optional(), 11 | names: z.array(z.string()), 12 | mappings: z.string(), 13 | }); 14 | 15 | /** 16 | * Extracts source files from an eszip archive. 17 | * 18 | * Optionally removes the given path prefix from file names. 19 | * 20 | * If a file contains a source map, it will return the 21 | * original TypeScript source instead of the transpiled file. 22 | */ 23 | export async function extractFiles( 24 | eszip: Uint8Array, 25 | pathPrefix: string = '/' 26 | ) { 27 | let specifiers: string[] = []; 28 | 29 | if (eszip instanceof ReadableStream) { 30 | const reader = eszip.getReader({ mode: 'byob' }); 31 | specifiers = await parser.parse(reader); 32 | } else { 33 | specifiers = await parser.parseBytes(eszip); 34 | } 35 | 36 | await parser.load(); 37 | 38 | const fileSpecifiers = specifiers.filter((specifier) => 39 | specifier.startsWith('file://') 40 | ); 41 | 42 | const files = await Promise.all( 43 | fileSpecifiers.map(async (specifier) => { 44 | const source: string = await parser.getModuleSource(specifier); 45 | const sourceMapString: string = 46 | await parser.getModuleSourceMap(specifier); 47 | 48 | const filePath = relative( 49 | pathPrefix, 50 | fileURLToPath(specifier, { windows: false }) 51 | ); 52 | 53 | const file = new File([source], filePath, { 54 | type: 'text/plain', 55 | }); 56 | 57 | if (!sourceMapString) { 58 | return file; 59 | } 60 | 61 | const sourceMap = sourceMapSchema.parse(JSON.parse(sourceMapString)); 62 | 63 | const [typeScriptSource] = sourceMap.sourcesContent ?? []; 64 | 65 | if (!typeScriptSource) { 66 | return file; 67 | } 68 | 69 | const sourceFile = new File([typeScriptSource], filePath, { 70 | type: 'application/typescript', 71 | }); 72 | 73 | return sourceFile; 74 | }) 75 | ); 76 | 77 | return files; 78 | } 79 | 80 | /** 81 | * Bundles files into an eszip archive. 82 | * 83 | * Optionally prefixes the file names with a given path. 84 | */ 85 | export async function bundleFiles(files: File[], pathPrefix: string = '/') { 86 | const specifiers = files.map( 87 | (file) => `file://${join(pathPrefix, file.name)}` 88 | ); 89 | const eszip = await build(specifiers, async (specifier: string) => { 90 | const url = new URL(specifier); 91 | const scheme = url.protocol; 92 | 93 | switch (scheme) { 94 | case 'file:': { 95 | const file = files.find( 96 | (file) => `file://${join(pathPrefix, file.name)}` === specifier 97 | ); 98 | 99 | if (!file) { 100 | throw new Error(`File not found: ${specifier}`); 101 | } 102 | 103 | const headers = { 104 | 'content-type': file.type, 105 | }; 106 | 107 | const content = await file.text(); 108 | 109 | return { 110 | kind: 'module', 111 | specifier, 112 | headers, 113 | content, 114 | }; 115 | } 116 | case 'http:': 117 | case 'https:': { 118 | const response = await fetch(specifier); 119 | if (!response.ok) { 120 | throw new Error(`Failed to fetch ${specifier}: ${response.status}`); 121 | } 122 | 123 | // Header keys must be lower case 124 | const headers = Object.fromEntries( 125 | Array.from(response.headers.entries()).map(([key, value]) => [ 126 | key.toLowerCase(), 127 | value, 128 | ]) 129 | ); 130 | 131 | const content = await response.text(); 132 | 133 | return { 134 | kind: 'module', 135 | specifier, 136 | headers, 137 | content, 138 | }; 139 | } 140 | default: { 141 | throw new Error(`Unsupported scheme: ${scheme}`); 142 | } 143 | } 144 | }); 145 | 146 | return eszip; 147 | } 148 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/index.test.ts: -------------------------------------------------------------------------------- 1 | import { Client } from '@modelcontextprotocol/sdk/client/index.js'; 2 | import { StreamTransport } from '@supabase/mcp-utils'; 3 | import { describe, expect, test } from 'vitest'; 4 | import { 5 | ACCESS_TOKEN, 6 | API_URL, 7 | MCP_CLIENT_NAME, 8 | MCP_CLIENT_VERSION, 9 | } from '../test/mocks.js'; 10 | import { createSupabaseMcpServer } from './index.js'; 11 | 12 | type SetupOptions = { 13 | accessToken?: string; 14 | projectId?: string; 15 | readOnly?: boolean; 16 | }; 17 | 18 | async function setup(options: SetupOptions = {}) { 19 | const { accessToken = ACCESS_TOKEN, projectId, readOnly } = options; 20 | const clientTransport = new StreamTransport(); 21 | const serverTransport = new StreamTransport(); 22 | 23 | clientTransport.readable.pipeTo(serverTransport.writable); 24 | serverTransport.readable.pipeTo(clientTransport.writable); 25 | 26 | const client = new Client( 27 | { 28 | name: MCP_CLIENT_NAME, 29 | version: MCP_CLIENT_VERSION, 30 | }, 31 | { 32 | capabilities: {}, 33 | } 34 | ); 35 | 36 | const server = createSupabaseMcpServer({ 37 | platform: { 38 | apiUrl: API_URL, 39 | accessToken, 40 | }, 41 | projectId, 42 | readOnly, 43 | }); 44 | 45 | await server.connect(serverTransport); 46 | await client.connect(clientTransport); 47 | 48 | return { client, clientTransport, server, serverTransport }; 49 | } 50 | 51 | describe('index', () => { 52 | test('index.ts exports a working server', async () => { 53 | const { client } = await setup(); 54 | 55 | const { tools } = await client.listTools(); 56 | 57 | expect(tools.length).toBeGreaterThan(0); 58 | }); 59 | }); 60 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './platform/api-platform.js'; 2 | export type { SupabasePlatform } from './platform/index.js'; 3 | export * from './server.js'; 4 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/logs.ts: -------------------------------------------------------------------------------- 1 | import { stripIndent } from 'common-tags'; 2 | 3 | export function getLogQuery( 4 | service: 5 | | 'api' 6 | | 'branch-action' 7 | | 'postgres' 8 | | 'edge-function' 9 | | 'auth' 10 | | 'storage' 11 | | 'realtime', 12 | limit: number = 100 13 | ) { 14 | switch (service) { 15 | case 'api': 16 | return stripIndent` 17 | select id, identifier, timestamp, event_message, request.method, request.path, response.status_code 18 | from edge_logs 19 | cross join unnest(metadata) as m 20 | cross join unnest(m.request) as request 21 | cross join unnest(m.response) as response 22 | order by timestamp desc 23 | limit ${limit} 24 | `; 25 | case 'branch-action': 26 | return stripIndent` 27 | select workflow_run, workflow_run_logs.timestamp, id, event_message from workflow_run_logs 28 | order by timestamp desc 29 | limit ${limit} 30 | `; 31 | case 'postgres': 32 | return stripIndent` 33 | select identifier, postgres_logs.timestamp, id, event_message, parsed.error_severity from postgres_logs 34 | cross join unnest(metadata) as m 35 | cross join unnest(m.parsed) as parsed 36 | order by timestamp desc 37 | limit ${limit} 38 | `; 39 | case 'edge-function': 40 | return stripIndent` 41 | select id, function_edge_logs.timestamp, event_message, response.status_code, request.method, m.function_id, m.execution_time_ms, m.deployment_id, m.version from function_edge_logs 42 | cross join unnest(metadata) as m 43 | cross join unnest(m.response) as response 44 | cross join unnest(m.request) as request 45 | order by timestamp desc 46 | limit ${limit} 47 | `; 48 | case 'auth': 49 | return stripIndent` 50 | select id, auth_logs.timestamp, event_message, metadata.level, metadata.status, metadata.path, metadata.msg as msg, metadata.error from auth_logs 51 | cross join unnest(metadata) as metadata 52 | order by timestamp desc 53 | limit ${limit} 54 | `; 55 | case 'storage': 56 | return stripIndent` 57 | select id, storage_logs.timestamp, event_message from storage_logs 58 | order by timestamp desc 59 | limit ${limit} 60 | `; 61 | case 'realtime': 62 | return stripIndent` 63 | select id, realtime_logs.timestamp, event_message from realtime_logs 64 | order by timestamp desc 65 | limit ${limit} 66 | `; 67 | default: 68 | throw new Error(`unsupported log service type: ${service}`); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/management-api/index.ts: -------------------------------------------------------------------------------- 1 | import createClient, { 2 | type Client, 3 | type FetchResponse, 4 | type ParseAsResponse, 5 | } from 'openapi-fetch'; 6 | import type { 7 | MediaType, 8 | ResponseObjectMap, 9 | SuccessResponse, 10 | } from 'openapi-typescript-helpers'; 11 | import { z } from 'zod'; 12 | import type { paths } from './types.js'; 13 | 14 | export function createManagementApiClient( 15 | baseUrl: string, 16 | accessToken: string, 17 | headers: Record = {} 18 | ) { 19 | return createClient({ 20 | baseUrl, 21 | headers: { 22 | Authorization: `Bearer ${accessToken}`, 23 | ...headers, 24 | }, 25 | }); 26 | } 27 | 28 | export type ManagementApiClient = Client; 29 | 30 | export type SuccessResponseType< 31 | T extends Record, 32 | Options, 33 | Media extends MediaType, 34 | > = { 35 | data: ParseAsResponse, Media>, Options>; 36 | error?: never; 37 | response: Response; 38 | }; 39 | 40 | const errorSchema = z.object({ 41 | message: z.string(), 42 | }); 43 | 44 | export function assertSuccess< 45 | T extends Record, 46 | Options, 47 | Media extends MediaType, 48 | >( 49 | response: FetchResponse, 50 | fallbackMessage: string 51 | ): asserts response is SuccessResponseType { 52 | if ('error' in response) { 53 | if (response.response.status === 401) { 54 | throw new Error( 55 | 'Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SUPABASE_ACCESS_TOKEN.' 56 | ); 57 | } 58 | 59 | const { data: errorContent } = errorSchema.safeParse(response.error); 60 | 61 | if (errorContent) { 62 | throw new Error(errorContent.message); 63 | } 64 | 65 | throw new Error(fallbackMessage); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/password.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { generatePassword } from './password.js'; 3 | 4 | describe('generatePassword', () => { 5 | it('should generate a password with default options', () => { 6 | const password = generatePassword(); 7 | expect(password.length).toBe(10); 8 | expect(/^[A-Za-z]+$/.test(password)).toBe(true); 9 | }); 10 | 11 | it('should generate a password with custom length', () => { 12 | const password = generatePassword({ length: 16 }); 13 | expect(password.length).toBe(16); 14 | }); 15 | 16 | it('should generate a password with numbers', () => { 17 | const password = generatePassword({ 18 | numbers: true, 19 | uppercase: false, 20 | lowercase: false, 21 | }); 22 | expect(/[0-9]/.test(password)).toBe(true); 23 | }); 24 | 25 | it('should generate a password with symbols', () => { 26 | const password = generatePassword({ symbols: true }); 27 | expect(/[!@#$%^&*()_+~`|}{[\]:;?><,./-=]/.test(password)).toBe(true); 28 | }); 29 | 30 | it('should generate a password with uppercase only', () => { 31 | const password = generatePassword({ uppercase: true, lowercase: false }); 32 | expect(/^[A-Z]+$/.test(password)).toBe(true); 33 | }); 34 | 35 | it('should generate a password with lowercase only', () => { 36 | const password = generatePassword({ uppercase: false, lowercase: true }); 37 | expect(/^[a-z]+$/.test(password)).toBe(true); 38 | }); 39 | 40 | it('should not generate the same password twice', () => { 41 | const password1 = generatePassword(); 42 | const password2 = generatePassword(); 43 | expect(password1).not.toBe(password2); 44 | }); 45 | 46 | it('should throw an error if no character sets are selected', () => { 47 | expect(() => 48 | generatePassword({ 49 | uppercase: false, 50 | lowercase: false, 51 | numbers: false, 52 | symbols: false, 53 | }) 54 | ).toThrow('at least one character set must be selected'); 55 | }); 56 | }); 57 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/password.ts: -------------------------------------------------------------------------------- 1 | const UPPERCASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 2 | const LOWERCASE_CHARS = 'abcdefghijklmnopqrstuvwxyz'; 3 | const NUMBER_CHARS = '0123456789'; 4 | const SYMBOL_CHARS = '!@#$%^&*()_+~`|}{[]:;?><,./-='; 5 | 6 | export type GeneratePasswordOptions = { 7 | length?: number; 8 | numbers?: boolean; 9 | uppercase?: boolean; 10 | lowercase?: boolean; 11 | symbols?: boolean; 12 | }; 13 | 14 | /** 15 | * Generates a cryptographically secure random password. 16 | * 17 | * @returns The generated password 18 | */ 19 | export const generatePassword = ({ 20 | length = 10, 21 | numbers = false, 22 | symbols = false, 23 | uppercase = true, 24 | lowercase = true, 25 | } = {}) => { 26 | // Build the character set based on options 27 | let chars = ''; 28 | if (uppercase) { 29 | chars += UPPERCASE_CHARS; 30 | } 31 | if (lowercase) { 32 | chars += LOWERCASE_CHARS; 33 | } 34 | if (numbers) { 35 | chars += NUMBER_CHARS; 36 | } 37 | if (symbols) { 38 | chars += SYMBOL_CHARS; 39 | } 40 | 41 | if (chars.length === 0) { 42 | throw new Error('at least one character set must be selected'); 43 | } 44 | 45 | const randomValues = new Uint32Array(length); 46 | crypto.getRandomValues(randomValues); 47 | 48 | // Map random values to our character set 49 | let password = ''; 50 | for (let i = 0; i < length; i++) { 51 | const randomIndex = randomValues[i]! % chars.length; 52 | password += chars.charAt(randomIndex); 53 | } 54 | 55 | return password; 56 | }; 57 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/pg-meta/columns.sql: -------------------------------------------------------------------------------- 1 | -- Adapted from information_schema.columns 2 | 3 | SELECT 4 | c.oid :: int8 AS table_id, 5 | nc.nspname AS schema, 6 | c.relname AS table, 7 | (c.oid || '.' || a.attnum) AS id, 8 | a.attnum AS ordinal_position, 9 | a.attname AS name, 10 | CASE 11 | WHEN a.atthasdef THEN pg_get_expr(ad.adbin, ad.adrelid) 12 | ELSE NULL 13 | END AS default_value, 14 | CASE 15 | WHEN t.typtype = 'd' THEN CASE 16 | WHEN bt.typelem <> 0 :: oid 17 | AND bt.typlen = -1 THEN 'ARRAY' 18 | WHEN nbt.nspname = 'pg_catalog' THEN format_type(t.typbasetype, NULL) 19 | ELSE 'USER-DEFINED' 20 | END 21 | ELSE CASE 22 | WHEN t.typelem <> 0 :: oid 23 | AND t.typlen = -1 THEN 'ARRAY' 24 | WHEN nt.nspname = 'pg_catalog' THEN format_type(a.atttypid, NULL) 25 | ELSE 'USER-DEFINED' 26 | END 27 | END AS data_type, 28 | COALESCE(bt.typname, t.typname) AS format, 29 | a.attidentity IN ('a', 'd') AS is_identity, 30 | CASE 31 | a.attidentity 32 | WHEN 'a' THEN 'ALWAYS' 33 | WHEN 'd' THEN 'BY DEFAULT' 34 | ELSE NULL 35 | END AS identity_generation, 36 | a.attgenerated IN ('s') AS is_generated, 37 | NOT ( 38 | a.attnotnull 39 | OR t.typtype = 'd' AND t.typnotnull 40 | ) AS is_nullable, 41 | ( 42 | c.relkind IN ('r', 'p') 43 | OR c.relkind IN ('v', 'f') AND pg_column_is_updatable(c.oid, a.attnum, FALSE) 44 | ) AS is_updatable, 45 | uniques.table_id IS NOT NULL AS is_unique, 46 | check_constraints.definition AS "check", 47 | array_to_json( 48 | array( 49 | SELECT 50 | enumlabel 51 | FROM 52 | pg_catalog.pg_enum enums 53 | WHERE 54 | enums.enumtypid = coalesce(bt.oid, t.oid) 55 | OR enums.enumtypid = coalesce(bt.typelem, t.typelem) 56 | ORDER BY 57 | enums.enumsortorder 58 | ) 59 | ) AS enums, 60 | col_description(c.oid, a.attnum) AS comment 61 | FROM 62 | pg_attribute a 63 | LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid 64 | AND a.attnum = ad.adnum 65 | JOIN ( 66 | pg_class c 67 | JOIN pg_namespace nc ON c.relnamespace = nc.oid 68 | ) ON a.attrelid = c.oid 69 | JOIN ( 70 | pg_type t 71 | JOIN pg_namespace nt ON t.typnamespace = nt.oid 72 | ) ON a.atttypid = t.oid 73 | LEFT JOIN ( 74 | pg_type bt 75 | JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid 76 | ) ON t.typtype = 'd' 77 | AND t.typbasetype = bt.oid 78 | LEFT JOIN ( 79 | SELECT DISTINCT ON (table_id, ordinal_position) 80 | conrelid AS table_id, 81 | conkey[1] AS ordinal_position 82 | FROM pg_catalog.pg_constraint 83 | WHERE contype = 'u' AND cardinality(conkey) = 1 84 | ) AS uniques ON uniques.table_id = c.oid AND uniques.ordinal_position = a.attnum 85 | LEFT JOIN ( 86 | -- We only select the first column check 87 | SELECT DISTINCT ON (table_id, ordinal_position) 88 | conrelid AS table_id, 89 | conkey[1] AS ordinal_position, 90 | substring( 91 | pg_get_constraintdef(pg_constraint.oid, true), 92 | 8, 93 | length(pg_get_constraintdef(pg_constraint.oid, true)) - 8 94 | ) AS "definition" 95 | FROM pg_constraint 96 | WHERE contype = 'c' AND cardinality(conkey) = 1 97 | ORDER BY table_id, ordinal_position, oid asc 98 | ) AS check_constraints ON check_constraints.table_id = c.oid AND check_constraints.ordinal_position = a.attnum 99 | WHERE 100 | NOT pg_is_other_temp_schema(nc.oid) 101 | AND a.attnum > 0 102 | AND NOT a.attisdropped 103 | AND (c.relkind IN ('r', 'v', 'm', 'f', 'p')) 104 | AND ( 105 | pg_has_role(c.relowner, 'USAGE') 106 | OR has_column_privilege( 107 | c.oid, 108 | a.attnum, 109 | 'SELECT, INSERT, UPDATE, REFERENCES' 110 | ) 111 | ) 112 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/pg-meta/extensions.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | e.name, 3 | n.nspname AS schema, 4 | e.default_version, 5 | x.extversion AS installed_version, 6 | e.comment 7 | FROM 8 | pg_available_extensions() e(name, default_version, comment) 9 | LEFT JOIN pg_extension x ON e.name = x.extname 10 | LEFT JOIN pg_namespace n ON x.extnamespace = n.oid 11 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/pg-meta/index.ts: -------------------------------------------------------------------------------- 1 | import { stripIndent } from 'common-tags'; 2 | import columnsSql from './columns.sql'; 3 | import extensionsSql from './extensions.sql'; 4 | import tablesSql from './tables.sql'; 5 | 6 | export const SYSTEM_SCHEMAS = [ 7 | 'information_schema', 8 | 'pg_catalog', 9 | 'pg_toast', 10 | '_timescaledb_internal', 11 | ]; 12 | 13 | /** 14 | * Generates the SQL query to list tables in the database. 15 | */ 16 | export function listTablesSql(schemas: string[] = []) { 17 | let sql = stripIndent` 18 | with 19 | tables as (${tablesSql}), 20 | columns as (${columnsSql}) 21 | select 22 | *, 23 | ${coalesceRowsToArray('columns', 'columns.table_id = tables.id')} 24 | from tables 25 | `; 26 | 27 | sql += '\n'; 28 | 29 | if (schemas.length > 0) { 30 | sql += `where schema in (${schemas.map((s) => `'${s}'`).join(',')})`; 31 | } else { 32 | sql += `where schema not in (${SYSTEM_SCHEMAS.map((s) => `'${s}'`).join(',')})`; 33 | } 34 | 35 | return sql; 36 | } 37 | 38 | /** 39 | * Generates the SQL query to list all extensions in the database. 40 | */ 41 | export function listExtensionsSql() { 42 | return extensionsSql; 43 | } 44 | 45 | /** 46 | * Generates a SQL segment that coalesces rows into an array of JSON objects. 47 | */ 48 | export const coalesceRowsToArray = (source: string, filter: string) => { 49 | return stripIndent` 50 | COALESCE( 51 | ( 52 | SELECT 53 | array_agg(row_to_json(${source})) FILTER (WHERE ${filter}) 54 | FROM 55 | ${source} 56 | ), 57 | '{}' 58 | ) AS ${source} 59 | `; 60 | }; 61 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/pg-meta/tables.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | c.oid :: int8 AS id, 3 | nc.nspname AS schema, 4 | c.relname AS name, 5 | c.relrowsecurity AS rls_enabled, 6 | c.relforcerowsecurity AS rls_forced, 7 | CASE 8 | WHEN c.relreplident = 'd' THEN 'DEFAULT' 9 | WHEN c.relreplident = 'i' THEN 'INDEX' 10 | WHEN c.relreplident = 'f' THEN 'FULL' 11 | ELSE 'NOTHING' 12 | END AS replica_identity, 13 | pg_total_relation_size(format('%I.%I', nc.nspname, c.relname)) :: int8 AS bytes, 14 | pg_size_pretty( 15 | pg_total_relation_size(format('%I.%I', nc.nspname, c.relname)) 16 | ) AS size, 17 | pg_stat_get_live_tuples(c.oid) AS live_rows_estimate, 18 | pg_stat_get_dead_tuples(c.oid) AS dead_rows_estimate, 19 | obj_description(c.oid) AS comment, 20 | coalesce(pk.primary_keys, '[]') as primary_keys, 21 | coalesce( 22 | jsonb_agg(relationships) filter (where relationships is not null), 23 | '[]' 24 | ) as relationships 25 | FROM 26 | pg_namespace nc 27 | JOIN pg_class c ON nc.oid = c.relnamespace 28 | left join ( 29 | select 30 | table_id, 31 | jsonb_agg(_pk.*) as primary_keys 32 | from ( 33 | select 34 | n.nspname as schema, 35 | c.relname as table_name, 36 | a.attname as name, 37 | c.oid :: int8 as table_id 38 | from 39 | pg_index i, 40 | pg_class c, 41 | pg_attribute a, 42 | pg_namespace n 43 | where 44 | i.indrelid = c.oid 45 | and c.relnamespace = n.oid 46 | and a.attrelid = c.oid 47 | and a.attnum = any (i.indkey) 48 | and i.indisprimary 49 | ) as _pk 50 | group by table_id 51 | ) as pk 52 | on pk.table_id = c.oid 53 | left join ( 54 | select 55 | c.oid :: int8 as id, 56 | c.conname as constraint_name, 57 | nsa.nspname as source_schema, 58 | csa.relname as source_table_name, 59 | sa.attname as source_column_name, 60 | nta.nspname as target_table_schema, 61 | cta.relname as target_table_name, 62 | ta.attname as target_column_name 63 | from 64 | pg_constraint c 65 | join ( 66 | pg_attribute sa 67 | join pg_class csa on sa.attrelid = csa.oid 68 | join pg_namespace nsa on csa.relnamespace = nsa.oid 69 | ) on sa.attrelid = c.conrelid and sa.attnum = any (c.conkey) 70 | join ( 71 | pg_attribute ta 72 | join pg_class cta on ta.attrelid = cta.oid 73 | join pg_namespace nta on cta.relnamespace = nta.oid 74 | ) on ta.attrelid = c.confrelid and ta.attnum = any (c.confkey) 75 | where 76 | c.contype = 'f' 77 | ) as relationships 78 | on (relationships.source_schema = nc.nspname and relationships.source_table_name = c.relname) 79 | or (relationships.target_table_schema = nc.nspname and relationships.target_table_name = c.relname) 80 | WHERE 81 | c.relkind IN ('r', 'p') 82 | AND NOT pg_is_other_temp_schema(nc.oid) 83 | AND ( 84 | pg_has_role(c.relowner, 'USAGE') 85 | OR has_table_privilege( 86 | c.oid, 87 | 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER' 88 | ) 89 | OR has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES') 90 | ) 91 | group by 92 | c.oid, 93 | c.relname, 94 | c.relrowsecurity, 95 | c.relforcerowsecurity, 96 | c.relreplident, 97 | nc.nspname, 98 | pk.primary_keys 99 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/pg-meta/types.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | 3 | export const postgresPrimaryKeySchema = z.object({ 4 | schema: z.string(), 5 | table_name: z.string(), 6 | name: z.string(), 7 | table_id: z.number().int(), 8 | }); 9 | 10 | export const postgresRelationshipSchema = z.object({ 11 | id: z.number().int(), 12 | constraint_name: z.string(), 13 | source_schema: z.string(), 14 | source_table_name: z.string(), 15 | source_column_name: z.string(), 16 | target_table_schema: z.string(), 17 | target_table_name: z.string(), 18 | target_column_name: z.string(), 19 | }); 20 | 21 | export const postgresColumnSchema = z.object({ 22 | table_id: z.number().int(), 23 | schema: z.string(), 24 | table: z.string(), 25 | id: z.string().regex(/^(\d+)\.(\d+)$/), 26 | ordinal_position: z.number().int(), 27 | name: z.string(), 28 | default_value: z.any(), 29 | data_type: z.string(), 30 | format: z.string(), 31 | is_identity: z.boolean(), 32 | identity_generation: z.union([ 33 | z.literal('ALWAYS'), 34 | z.literal('BY DEFAULT'), 35 | z.null(), 36 | ]), 37 | is_generated: z.boolean(), 38 | is_nullable: z.boolean(), 39 | is_updatable: z.boolean(), 40 | is_unique: z.boolean(), 41 | enums: z.array(z.string()), 42 | check: z.union([z.string(), z.null()]), 43 | comment: z.union([z.string(), z.null()]), 44 | }); 45 | 46 | export const postgresTableSchema = z.object({ 47 | id: z.number().int(), 48 | schema: z.string(), 49 | name: z.string(), 50 | rls_enabled: z.boolean(), 51 | rls_forced: z.boolean(), 52 | replica_identity: z.union([ 53 | z.literal('DEFAULT'), 54 | z.literal('INDEX'), 55 | z.literal('FULL'), 56 | z.literal('NOTHING'), 57 | ]), 58 | bytes: z.number().int(), 59 | size: z.string(), 60 | live_rows_estimate: z.number().int(), 61 | dead_rows_estimate: z.number().int(), 62 | comment: z.string().nullable(), 63 | columns: z.array(postgresColumnSchema).optional(), 64 | primary_keys: z.array(postgresPrimaryKeySchema), 65 | relationships: z.array(postgresRelationshipSchema), 66 | }); 67 | 68 | export const postgresExtensionSchema = z.object({ 69 | name: z.string(), 70 | schema: z.union([z.string(), z.null()]), 71 | default_version: z.string(), 72 | installed_version: z.union([z.string(), z.null()]), 73 | comment: z.union([z.string(), z.null()]), 74 | }); 75 | 76 | export type PostgresPrimaryKey = z.infer; 77 | export type PostgresRelationship = z.infer; 78 | export type PostgresColumn = z.infer; 79 | export type PostgresTable = z.infer; 80 | export type PostgresExtension = z.infer; 81 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/platform/index.ts: -------------------------------------------------------------------------------- 1 | export * from './types.js'; 2 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/platform/types.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import { AWS_REGION_CODES } from '../regions.js'; 3 | import type { InitData } from '@supabase/mcp-utils'; 4 | 5 | export const organizationSchema = z.object({ 6 | id: z.string(), 7 | name: z.string(), 8 | plan: z.string().optional(), 9 | allowed_release_channels: z.array(z.string()), 10 | opt_in_tags: z.array(z.string()), 11 | }); 12 | 13 | export const projectSchema = z.object({ 14 | id: z.string(), 15 | organization_id: z.string(), 16 | name: z.string(), 17 | status: z.string(), 18 | created_at: z.string(), 19 | region: z.string(), 20 | }); 21 | 22 | export const branchSchema = z.object({ 23 | id: z.string(), 24 | name: z.string(), 25 | project_ref: z.string(), 26 | parent_project_ref: z.string(), 27 | is_default: z.boolean(), 28 | git_branch: z.string().optional(), 29 | pr_number: z.number().optional(), 30 | latest_check_run_id: z.number().optional(), 31 | persistent: z.boolean(), 32 | status: z.enum([ 33 | 'CREATING_PROJECT', 34 | 'RUNNING_MIGRATIONS', 35 | 'MIGRATIONS_PASSED', 36 | 'MIGRATIONS_FAILED', 37 | 'FUNCTIONS_DEPLOYED', 38 | 'FUNCTIONS_FAILED', 39 | ]), 40 | created_at: z.string(), 41 | updated_at: z.string(), 42 | }); 43 | 44 | export const edgeFunctionSchema = z.object({ 45 | id: z.string(), 46 | slug: z.string(), 47 | name: z.string(), 48 | status: z.string(), 49 | version: z.number(), 50 | created_at: z.number().optional(), 51 | updated_at: z.number().optional(), 52 | verify_jwt: z.boolean().optional(), 53 | import_map: z.boolean().optional(), 54 | import_map_path: z.string().optional(), 55 | entrypoint_path: z.string().optional(), 56 | files: z.array( 57 | z.object({ 58 | name: z.string(), 59 | content: z.string(), 60 | }) 61 | ), 62 | }); 63 | 64 | export const createProjectOptionsSchema = z.object({ 65 | name: z.string(), 66 | organization_id: z.string(), 67 | region: z.enum(AWS_REGION_CODES).optional(), 68 | db_pass: z.string().optional(), 69 | }); 70 | 71 | export const createBranchOptionsSchema = z.object({ 72 | name: z.string(), 73 | }); 74 | 75 | export const resetBranchOptionsSchema = z.object({ 76 | migration_version: z.string().optional(), 77 | }); 78 | 79 | export const deployEdgeFunctionOptionsSchema = z.object({ 80 | name: z.string(), 81 | entrypoint_path: z.string(), 82 | import_map_path: z.string().optional(), 83 | files: z.array( 84 | z.object({ 85 | name: z.string(), 86 | content: z.string(), 87 | }) 88 | ), 89 | }); 90 | 91 | export const executeSqlOptionsSchema = z.object({ 92 | query: z.string(), 93 | read_only: z.boolean().optional(), 94 | }); 95 | 96 | export const applyMigrationOptionsSchema = z.object({ 97 | name: z.string(), 98 | query: z.string(), 99 | }); 100 | 101 | export const migrationSchema = z.object({ 102 | version: z.string(), 103 | name: z.string().optional(), 104 | }); 105 | 106 | export const getLogsOptionsSchema = z.object({ 107 | sql: z.string(), 108 | iso_timestamp_start: z.string().optional(), 109 | iso_timestamp_end: z.string().optional(), 110 | }); 111 | 112 | export const generateTypescriptTypesResultSchema = z.object({ 113 | types: z.string(), 114 | }); 115 | 116 | export type Organization = z.infer; 117 | export type Project = z.infer; 118 | export type Branch = z.infer; 119 | export type EdgeFunction = z.infer; 120 | 121 | export type CreateProjectOptions = z.infer; 122 | export type CreateBranchOptions = z.infer; 123 | export type ResetBranchOptions = z.infer; 124 | export type DeployEdgeFunctionOptions = z.infer< 125 | typeof deployEdgeFunctionOptionsSchema 126 | >; 127 | 128 | export type ExecuteSqlOptions = z.infer; 129 | export type ApplyMigrationOptions = z.infer; 130 | export type Migration = z.infer; 131 | export type ListMigrationsResult = z.infer; 132 | 133 | export type GetLogsOptions = z.infer; 134 | export type GenerateTypescriptTypesResult = z.infer< 135 | typeof generateTypescriptTypesResultSchema 136 | >; 137 | 138 | export type SupabasePlatform = { 139 | init?(info: InitData): Promise; 140 | 141 | // Database operations 142 | executeSql(projectId: string, options: ExecuteSqlOptions): Promise; 143 | listMigrations(projectId: string): Promise; 144 | applyMigration( 145 | projectId: string, 146 | options: ApplyMigrationOptions 147 | ): Promise; 148 | 149 | // Project management 150 | listOrganizations(): Promise[]>; 151 | getOrganization(organizationId: string): Promise; 152 | listProjects(): Promise; 153 | getProject(projectId: string): Promise; 154 | createProject(options: CreateProjectOptions): Promise; 155 | pauseProject(projectId: string): Promise; 156 | restoreProject(projectId: string): Promise; 157 | 158 | // Edge functions 159 | listEdgeFunctions(projectId: string): Promise; 160 | getEdgeFunction( 161 | projectId: string, 162 | functionSlug: string 163 | ): Promise; 164 | deployEdgeFunction( 165 | projectId: string, 166 | options: DeployEdgeFunctionOptions 167 | ): Promise>; 168 | 169 | // Debugging 170 | getLogs(projectId: string, options: GetLogsOptions): Promise; 171 | 172 | // Development 173 | getProjectUrl(projectId: string): Promise; 174 | getAnonKey(projectId: string): Promise; 175 | generateTypescriptTypes( 176 | projectId: string 177 | ): Promise; 178 | 179 | // Branching 180 | listBranches(projectId: string): Promise; 181 | createBranch( 182 | projectId: string, 183 | options: CreateBranchOptions 184 | ): Promise; 185 | deleteBranch(branchId: string): Promise; 186 | mergeBranch(branchId: string): Promise; 187 | resetBranch(branchId: string, options: ResetBranchOptions): Promise; 188 | rebaseBranch(branchId: string): Promise; 189 | }; 190 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/pricing.ts: -------------------------------------------------------------------------------- 1 | import type { SupabasePlatform } from './platform/types.js'; 2 | 3 | export const PROJECT_COST_MONTHLY = 10; 4 | export const BRANCH_COST_HOURLY = 0.01344; 5 | 6 | export type ProjectCost = { 7 | type: 'project'; 8 | recurrence: 'monthly'; 9 | amount: number; 10 | }; 11 | 12 | export type BranchCost = { 13 | type: 'branch'; 14 | recurrence: 'hourly'; 15 | amount: number; 16 | }; 17 | 18 | export type Cost = ProjectCost | BranchCost; 19 | 20 | /** 21 | * Gets the cost of the next project in an organization. 22 | */ 23 | export async function getNextProjectCost( 24 | platform: SupabasePlatform, 25 | orgId: string 26 | ): Promise { 27 | const org = await platform.getOrganization(orgId); 28 | const projects = await platform.listProjects(); 29 | 30 | const activeProjects = projects.filter( 31 | (project) => 32 | project.organization_id === orgId && 33 | !['INACTIVE', 'GOING_DOWN', 'REMOVED'].includes(project.status) 34 | ); 35 | 36 | let amount = 0; 37 | 38 | if (org.plan !== 'free') { 39 | // If the organization is on a paid plan, the first project is included 40 | if (activeProjects.length > 0) { 41 | amount = PROJECT_COST_MONTHLY; 42 | } 43 | } 44 | 45 | return { type: 'project', recurrence: 'monthly', amount }; 46 | } 47 | 48 | /** 49 | * Gets the cost for a database branch. 50 | */ 51 | export function getBranchCost(): Cost { 52 | return { type: 'branch', recurrence: 'hourly', amount: BRANCH_COST_HOURLY }; 53 | } 54 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/regions.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { 3 | EARTH_RADIUS, 4 | getClosestAwsRegion, 5 | getCountryCode, 6 | getCountryCoordinates, 7 | getDistance, 8 | TRACE_URL, 9 | } from './regions.js'; 10 | import { http, HttpResponse } from 'msw'; 11 | import { setupServer } from 'msw/node'; 12 | 13 | const COUNTRY_CODE = 'US'; 14 | 15 | describe('getDistance', () => { 16 | it('should return 0 for the same coordinates', () => { 17 | const point = { lat: 50, lng: 50 }; 18 | expect(getDistance(point, point)).toBe(0); 19 | }); 20 | 21 | it('should calculate distance between two points correctly', () => { 22 | // New York City coordinates 23 | const nyc = { lat: 40.7128, lng: -74.006 }; 24 | // Los Angeles coordinates 25 | const la = { lat: 34.0522, lng: -118.2437 }; 26 | 27 | // Approximate distance between NYC and LA is ~3940 km 28 | const distance = getDistance(nyc, la); 29 | expect(distance).toBeCloseTo(3940, -2); // Allow ~100km margin 30 | }); 31 | 32 | it('should handle coordinates at opposite sides of the Earth', () => { 33 | const point1 = { lat: 0, lng: 0 }; 34 | const point2 = { lat: 0, lng: 180 }; 35 | 36 | // Half circumference of Earth 37 | const expectedDistance = Math.PI * EARTH_RADIUS; 38 | expect(getDistance(point1, point2)).toBeCloseTo(expectedDistance, 0); 39 | }); 40 | 41 | it('should handle negative coordinates', () => { 42 | const sydney = { lat: -33.8688, lng: 151.2093 }; 43 | const buenosAires = { lat: -34.6037, lng: -58.3816 }; 44 | 45 | // Approximate distance between Sydney and Buenos Aires is ~11800 km 46 | const distance = getDistance(sydney, buenosAires); 47 | expect(distance).toBeCloseTo(11800, -2); // Allow ~100km margin 48 | }); 49 | 50 | it('should handle coordinates at the equator', () => { 51 | const point1 = { lat: 0, lng: 0 }; 52 | const point2 = { lat: 0, lng: 180 }; 53 | 54 | const expectedDistance = Math.PI * EARTH_RADIUS; // Half circumference 55 | expect(getDistance(point1, point2)).toBeCloseTo(expectedDistance, 0); 56 | }); 57 | 58 | it('should be symmetrical (a to b equals b to a)', () => { 59 | const london = { lat: 51.5074, lng: -0.1278 }; 60 | const tokyo = { lat: 35.6762, lng: 139.6503 }; 61 | 62 | const distanceAtoB = getDistance(london, tokyo); 63 | const distanceBtoA = getDistance(tokyo, london); 64 | 65 | expect(distanceAtoB).toEqual(distanceBtoA); 66 | }); 67 | }); 68 | 69 | describe('getClosestRegion', () => { 70 | it('should find the closest AWS region to a specific location', () => { 71 | const tokyo = { lat: 35.6762, lng: 139.6503 }; 72 | const result = getClosestAwsRegion(tokyo); 73 | expect(result.code).toBe('ap-northeast-1'); // Tokyo region 74 | }); 75 | 76 | it('should find the correct AWS region for European location', () => { 77 | const london = { lat: 51.5074, lng: -0.1278 }; 78 | const result = getClosestAwsRegion(london); 79 | expect(result.code).toBe('eu-west-2'); // London region 80 | }); 81 | 82 | it('should find the correct AWS region for US West Coast location', () => { 83 | const sanFrancisco = { lat: 37.7749, lng: -122.4194 }; 84 | const result = getClosestAwsRegion(sanFrancisco); 85 | expect(result.code).toBe('us-west-1'); // North California region 86 | }); 87 | 88 | it('should find the correct AWS region for Sydney location', () => { 89 | const sydney = { lat: -33.8688, lng: 151.2093 }; 90 | const result = getClosestAwsRegion(sydney); 91 | expect(result.code).toBe('ap-southeast-2'); // Sydney region 92 | }); 93 | 94 | it('should find the correct AWS region for a location in South America', () => { 95 | const saoPaulo = { lat: -23.5505, lng: -46.6333 }; 96 | const result = getClosestAwsRegion(saoPaulo); 97 | expect(result.code).toBe('sa-east-1'); // São Paulo region 98 | }); 99 | }); 100 | 101 | describe('getCountryCode', () => { 102 | const handlers = [ 103 | http.get(TRACE_URL, () => { 104 | return HttpResponse.text( 105 | `fl=123abc\nvisit_scheme=https\nloc=${COUNTRY_CODE}\ntls=TLSv1.3\nhttp=http/2` 106 | ); 107 | }), 108 | ]; 109 | 110 | const server = setupServer(...handlers); 111 | server.listen({ onUnhandledRequest: 'error' }); 112 | 113 | it('should return the correct country code for a given location', async () => { 114 | const code = await getCountryCode(); 115 | expect(code).toEqual(COUNTRY_CODE); 116 | }); 117 | }); 118 | 119 | describe('getCountryCoordinates', () => { 120 | it('should throw an error for an invalid country code', async () => { 121 | const invalidCountryCode = 'INVALID_CODE'; 122 | expect(() => getCountryCoordinates(invalidCountryCode)).toThrowError( 123 | /unknown location code/ 124 | ); 125 | }); 126 | 127 | it('should return coordinates for a valid country code', () => { 128 | const result = getCountryCoordinates('US'); 129 | expect(result).toEqual({ lat: 38, lng: -97 }); 130 | }); 131 | }); 132 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/regions.ts: -------------------------------------------------------------------------------- 1 | import { parseKeyValueList, type UnionToTuple, type ValueOf } from './util.js'; 2 | 3 | export type AwsRegion = { 4 | code: string; 5 | displayName: string; 6 | location: Location; 7 | }; 8 | 9 | export type Location = { 10 | lat: number; 11 | lng: number; 12 | }; 13 | 14 | export const EARTH_RADIUS = 6371; // in kilometers 15 | export const TRACE_URL = 'https://www.cloudflare.com/cdn-cgi/trace'; 16 | 17 | export const COUNTRY_COORDINATES = { 18 | AF: { lat: 33, lng: 65 }, 19 | AX: { lat: 60.116667, lng: 19.9 }, 20 | AL: { lat: 41, lng: 20 }, 21 | DZ: { lat: 28, lng: 3 }, 22 | AS: { lat: -14.3333, lng: -170 }, 23 | AD: { lat: 42.5, lng: 1.6 }, 24 | AO: { lat: -12.5, lng: 18.5 }, 25 | AI: { lat: 18.25, lng: -63.1667 }, 26 | AQ: { lat: -90, lng: 0 }, 27 | AG: { lat: 17.05, lng: -61.8 }, 28 | AR: { lat: -34, lng: -64 }, 29 | AM: { lat: 40, lng: 45 }, 30 | AW: { lat: 12.5, lng: -69.9667 }, 31 | AU: { lat: -27, lng: 133 }, 32 | AT: { lat: 47.3333, lng: 13.3333 }, 33 | AZ: { lat: 40.5, lng: 47.5 }, 34 | BS: { lat: 24.25, lng: -76 }, 35 | BH: { lat: 26, lng: 50.55 }, 36 | BD: { lat: 24, lng: 90 }, 37 | BB: { lat: 13.1667, lng: -59.5333 }, 38 | BY: { lat: 53, lng: 28 }, 39 | BE: { lat: 50.8333, lng: 4 }, 40 | BZ: { lat: 17.25, lng: -88.75 }, 41 | BJ: { lat: 9.5, lng: 2.25 }, 42 | BM: { lat: 32.3333, lng: -64.75 }, 43 | BT: { lat: 27.5, lng: 90.5 }, 44 | BO: { lat: -17, lng: -65 }, 45 | BQ: { lat: 12.183333, lng: -68.233333 }, 46 | BA: { lat: 44, lng: 18 }, 47 | BW: { lat: -22, lng: 24 }, 48 | BV: { lat: -54.4333, lng: 3.4 }, 49 | BR: { lat: -10, lng: -55 }, 50 | IO: { lat: -6, lng: 71.5 }, 51 | BN: { lat: 4.5, lng: 114.6667 }, 52 | BG: { lat: 43, lng: 25 }, 53 | BF: { lat: 13, lng: -2 }, 54 | MM: { lat: 22, lng: 98 }, 55 | BI: { lat: -3.5, lng: 30 }, 56 | KH: { lat: 13, lng: 105 }, 57 | CM: { lat: 6, lng: 12 }, 58 | CA: { lat: 60, lng: -95 }, 59 | CV: { lat: 16, lng: -24 }, 60 | KY: { lat: 19.5, lng: -80.5 }, 61 | CF: { lat: 7, lng: 21 }, 62 | TD: { lat: 15, lng: 19 }, 63 | CL: { lat: -30, lng: -71 }, 64 | CN: { lat: 35, lng: 105 }, 65 | CX: { lat: -10.5, lng: 105.6667 }, 66 | CC: { lat: -12.5, lng: 96.8333 }, 67 | CO: { lat: 4, lng: -72 }, 68 | KM: { lat: -12.1667, lng: 44.25 }, 69 | CD: { lat: 0, lng: 25 }, 70 | CG: { lat: -1, lng: 15 }, 71 | CK: { lat: -21.2333, lng: -159.7667 }, 72 | CR: { lat: 10, lng: -84 }, 73 | CI: { lat: 8, lng: -5 }, 74 | HR: { lat: 45.1667, lng: 15.5 }, 75 | CU: { lat: 21.5, lng: -80 }, 76 | CW: { lat: 12.166667, lng: -68.966667 }, 77 | CY: { lat: 35, lng: 33 }, 78 | CZ: { lat: 49.75, lng: 15.5 }, 79 | DK: { lat: 56, lng: 10 }, 80 | DJ: { lat: 11.5, lng: 43 }, 81 | DM: { lat: 15.4167, lng: -61.3333 }, 82 | DO: { lat: 19, lng: -70.6667 }, 83 | EC: { lat: -2, lng: -77.5 }, 84 | EG: { lat: 27, lng: 30 }, 85 | SV: { lat: 13.8333, lng: -88.9167 }, 86 | GQ: { lat: 2, lng: 10 }, 87 | ER: { lat: 15, lng: 39 }, 88 | EE: { lat: 59, lng: 26 }, 89 | ET: { lat: 8, lng: 38 }, 90 | FK: { lat: -51.75, lng: -59 }, 91 | FO: { lat: 62, lng: -7 }, 92 | FJ: { lat: -18, lng: 175 }, 93 | FI: { lat: 64, lng: 26 }, 94 | FR: { lat: 46, lng: 2 }, 95 | GF: { lat: 4, lng: -53 }, 96 | PF: { lat: -15, lng: -140 }, 97 | TF: { lat: -43, lng: 67 }, 98 | GA: { lat: -1, lng: 11.75 }, 99 | GM: { lat: 13.4667, lng: -16.5667 }, 100 | GE: { lat: 42, lng: 43.5 }, 101 | DE: { lat: 51, lng: 9 }, 102 | GH: { lat: 8, lng: -2 }, 103 | GI: { lat: 36.1833, lng: -5.3667 }, 104 | GR: { lat: 39, lng: 22 }, 105 | GL: { lat: 72, lng: -40 }, 106 | GD: { lat: 12.1167, lng: -61.6667 }, 107 | GP: { lat: 16.25, lng: -61.5833 }, 108 | GU: { lat: 13.4667, lng: 144.7833 }, 109 | GT: { lat: 15.5, lng: -90.25 }, 110 | GG: { lat: 49.5, lng: -2.56 }, 111 | GW: { lat: 12, lng: -15 }, 112 | GN: { lat: 11, lng: -10 }, 113 | GY: { lat: 5, lng: -59 }, 114 | HT: { lat: 19, lng: -72.4167 }, 115 | HM: { lat: -53.1, lng: 72.5167 }, 116 | VA: { lat: 41.9, lng: 12.45 }, 117 | HN: { lat: 15, lng: -86.5 }, 118 | HK: { lat: 22.25, lng: 114.1667 }, 119 | HU: { lat: 47, lng: 20 }, 120 | IS: { lat: 65, lng: -18 }, 121 | IN: { lat: 20, lng: 77 }, 122 | ID: { lat: -5, lng: 120 }, 123 | IR: { lat: 32, lng: 53 }, 124 | IQ: { lat: 33, lng: 44 }, 125 | IE: { lat: 53, lng: -8 }, 126 | IM: { lat: 54.23, lng: -4.55 }, 127 | IL: { lat: 31.5, lng: 34.75 }, 128 | IT: { lat: 42.8333, lng: 12.8333 }, 129 | JM: { lat: 18.25, lng: -77.5 }, 130 | JP: { lat: 36, lng: 138 }, 131 | JE: { lat: 49.21, lng: -2.13 }, 132 | JO: { lat: 31, lng: 36 }, 133 | KZ: { lat: 48, lng: 68 }, 134 | KE: { lat: 1, lng: 38 }, 135 | KI: { lat: 1.4167, lng: 173 }, 136 | KP: { lat: 40, lng: 127 }, 137 | KR: { lat: 37, lng: 127.5 }, 138 | XK: { lat: 42.583333, lng: 21 }, 139 | KW: { lat: 29.3375, lng: 47.6581 }, 140 | KG: { lat: 41, lng: 75 }, 141 | LA: { lat: 18, lng: 105 }, 142 | LV: { lat: 57, lng: 25 }, 143 | LB: { lat: 33.8333, lng: 35.8333 }, 144 | LS: { lat: -29.5, lng: 28.5 }, 145 | LR: { lat: 6.5, lng: -9.5 }, 146 | LY: { lat: 25, lng: 17 }, 147 | LI: { lat: 47.1667, lng: 9.5333 }, 148 | LT: { lat: 56, lng: 24 }, 149 | LU: { lat: 49.75, lng: 6.1667 }, 150 | MO: { lat: 22.1667, lng: 113.55 }, 151 | MK: { lat: 41.8333, lng: 22 }, 152 | MG: { lat: -20, lng: 47 }, 153 | MW: { lat: -13.5, lng: 34 }, 154 | MY: { lat: 2.5, lng: 112.5 }, 155 | MV: { lat: 3.25, lng: 73 }, 156 | ML: { lat: 17, lng: -4 }, 157 | MT: { lat: 35.8333, lng: 14.5833 }, 158 | MH: { lat: 9, lng: 168 }, 159 | MQ: { lat: 14.6667, lng: -61 }, 160 | MR: { lat: 20, lng: -12 }, 161 | MU: { lat: -20.2833, lng: 57.55 }, 162 | YT: { lat: -12.8333, lng: 45.1667 }, 163 | MX: { lat: 23, lng: -102 }, 164 | FM: { lat: 6.9167, lng: 158.25 }, 165 | MD: { lat: 47, lng: 29 }, 166 | MC: { lat: 43.7333, lng: 7.4 }, 167 | MN: { lat: 46, lng: 105 }, 168 | ME: { lat: 42, lng: 19 }, 169 | MS: { lat: 16.75, lng: -62.2 }, 170 | MA: { lat: 32, lng: -5 }, 171 | MZ: { lat: -18.25, lng: 35 }, 172 | NA: { lat: -22, lng: 17 }, 173 | NR: { lat: -0.5333, lng: 166.9167 }, 174 | NP: { lat: 28, lng: 84 }, 175 | AN: { lat: 12.25, lng: -68.75 }, 176 | NL: { lat: 52.5, lng: 5.75 }, 177 | NC: { lat: -21.5, lng: 165.5 }, 178 | NZ: { lat: -41, lng: 174 }, 179 | NI: { lat: 13, lng: -85 }, 180 | NE: { lat: 16, lng: 8 }, 181 | NG: { lat: 10, lng: 8 }, 182 | NU: { lat: -19.0333, lng: -169.8667 }, 183 | NF: { lat: -29.0333, lng: 167.95 }, 184 | MP: { lat: 15.2, lng: 145.75 }, 185 | NO: { lat: 62, lng: 10 }, 186 | OM: { lat: 21, lng: 57 }, 187 | PK: { lat: 30, lng: 70 }, 188 | PW: { lat: 7.5, lng: 134.5 }, 189 | PS: { lat: 32, lng: 35.25 }, 190 | PA: { lat: 9, lng: -80 }, 191 | PG: { lat: -6, lng: 147 }, 192 | PY: { lat: -23, lng: -58 }, 193 | PE: { lat: -10, lng: -76 }, 194 | PH: { lat: 13, lng: 122 }, 195 | PN: { lat: -24.7, lng: -127.4 }, 196 | PL: { lat: 52, lng: 20 }, 197 | PT: { lat: 39.5, lng: -8 }, 198 | PR: { lat: 18.25, lng: -66.5 }, 199 | QA: { lat: 25.5, lng: 51.25 }, 200 | RE: { lat: -21.1, lng: 55.6 }, 201 | RO: { lat: 46, lng: 25 }, 202 | RU: { lat: 60, lng: 100 }, 203 | RW: { lat: -2, lng: 30 }, 204 | BL: { lat: 17.897728, lng: -62.834244 }, 205 | SH: { lat: -15.9333, lng: -5.7 }, 206 | KN: { lat: 17.3333, lng: -62.75 }, 207 | LC: { lat: 13.8833, lng: -61.1333 }, 208 | MF: { lat: 18.075278, lng: -63.06 }, 209 | PM: { lat: 46.8333, lng: -56.3333 }, 210 | VC: { lat: 13.25, lng: -61.2 }, 211 | WS: { lat: -13.5833, lng: -172.3333 }, 212 | SM: { lat: 43.7667, lng: 12.4167 }, 213 | ST: { lat: 1, lng: 7 }, 214 | SA: { lat: 25, lng: 45 }, 215 | SN: { lat: 14, lng: -14 }, 216 | RS: { lat: 44, lng: 21 }, 217 | SC: { lat: -4.5833, lng: 55.6667 }, 218 | SL: { lat: 8.5, lng: -11.5 }, 219 | SG: { lat: 1.3667, lng: 103.8 }, 220 | SX: { lat: 18.033333, lng: -63.05 }, 221 | SK: { lat: 48.6667, lng: 19.5 }, 222 | SI: { lat: 46, lng: 15 }, 223 | SB: { lat: -8, lng: 159 }, 224 | SO: { lat: 10, lng: 49 }, 225 | ZA: { lat: -29, lng: 24 }, 226 | GS: { lat: -54.5, lng: -37 }, 227 | SS: { lat: 8, lng: 30 }, 228 | ES: { lat: 40, lng: -4 }, 229 | LK: { lat: 7, lng: 81 }, 230 | SD: { lat: 15, lng: 30 }, 231 | SR: { lat: 4, lng: -56 }, 232 | SJ: { lat: 78, lng: 20 }, 233 | SZ: { lat: -26.5, lng: 31.5 }, 234 | SE: { lat: 62, lng: 15 }, 235 | CH: { lat: 47, lng: 8 }, 236 | SY: { lat: 35, lng: 38 }, 237 | TW: { lat: 23.5, lng: 121 }, 238 | TJ: { lat: 39, lng: 71 }, 239 | TZ: { lat: -6, lng: 35 }, 240 | TH: { lat: 15, lng: 100 }, 241 | TL: { lat: -8.55, lng: 125.5167 }, 242 | TG: { lat: 8, lng: 1.1667 }, 243 | TK: { lat: -9, lng: -172 }, 244 | TO: { lat: -20, lng: -175 }, 245 | TT: { lat: 11, lng: -61 }, 246 | TN: { lat: 34, lng: 9 }, 247 | TR: { lat: 39, lng: 35 }, 248 | TM: { lat: 40, lng: 60 }, 249 | TC: { lat: 21.75, lng: -71.5833 }, 250 | TV: { lat: -8, lng: 178 }, 251 | UG: { lat: 1, lng: 32 }, 252 | UA: { lat: 49, lng: 32 }, 253 | AE: { lat: 24, lng: 54 }, 254 | GB: { lat: 54, lng: -2 }, 255 | UM: { lat: 19.2833, lng: 166.6 }, 256 | US: { lat: 38, lng: -97 }, 257 | UY: { lat: -33, lng: -56 }, 258 | UZ: { lat: 41, lng: 64 }, 259 | VU: { lat: -16, lng: 167 }, 260 | VE: { lat: 8, lng: -66 }, 261 | VN: { lat: 16, lng: 106 }, 262 | VG: { lat: 18.5, lng: -64.5 }, 263 | VI: { lat: 18.3333, lng: -64.8333 }, 264 | WF: { lat: -13.3, lng: -176.2 }, 265 | EH: { lat: 24.5, lng: -13 }, 266 | YE: { lat: 15, lng: 48 }, 267 | ZM: { lat: -15, lng: 30 }, 268 | ZW: { lat: -20, lng: 30 }, 269 | } as const satisfies Record; 270 | 271 | export const AWS_REGIONS = { 272 | WEST_US: { 273 | code: 'us-west-1', 274 | displayName: 'West US (North California)', 275 | location: { lat: 37.774929, lng: -122.419418 }, 276 | }, 277 | EAST_US: { 278 | code: 'us-east-1', 279 | displayName: 'East US (North Virginia)', 280 | location: { lat: 37.926868, lng: -78.024902 }, 281 | }, 282 | EAST_US_2: { 283 | code: 'us-east-2', 284 | displayName: 'East US (Ohio)', 285 | location: { lat: 39.9612, lng: -82.9988 }, 286 | }, 287 | CENTRAL_CANADA: { 288 | code: 'ca-central-1', 289 | displayName: 'Canada (Central)', 290 | location: { lat: 56.130367, lng: -106.346771 }, 291 | }, 292 | WEST_EU: { 293 | code: 'eu-west-1', 294 | displayName: 'West EU (Ireland)', 295 | location: { lat: 53.3498, lng: -6.2603 }, 296 | }, 297 | WEST_EU_2: { 298 | code: 'eu-west-2', 299 | displayName: 'West Europe (London)', 300 | location: { lat: 51.507351, lng: -0.127758 }, 301 | }, 302 | WEST_EU_3: { 303 | code: 'eu-west-3', 304 | displayName: 'West EU (Paris)', 305 | location: { lat: 2.352222, lng: 48.856613 }, 306 | }, 307 | CENTRAL_EU: { 308 | code: 'eu-central-1', 309 | displayName: 'Central EU (Frankfurt)', 310 | location: { lat: 50.110924, lng: 8.682127 }, 311 | }, 312 | CENTRAL_EU_2: { 313 | code: 'eu-central-2', 314 | displayName: 'Central Europe (Zurich)', 315 | location: { lat: 47.3744489, lng: 8.5410422 }, 316 | }, 317 | NORTH_EU: { 318 | code: 'eu-north-1', 319 | displayName: 'North EU (Stockholm)', 320 | location: { lat: 59.3251172, lng: 18.0710935 }, 321 | }, 322 | SOUTH_ASIA: { 323 | code: 'ap-south-1', 324 | displayName: 'South Asia (Mumbai)', 325 | location: { lat: 18.9733536, lng: 72.8281049 }, 326 | }, 327 | SOUTHEAST_ASIA: { 328 | code: 'ap-southeast-1', 329 | displayName: 'Southeast Asia (Singapore)', 330 | location: { lat: 1.357107, lng: 103.8194992 }, 331 | }, 332 | NORTHEAST_ASIA: { 333 | code: 'ap-northeast-1', 334 | displayName: 'Northeast Asia (Tokyo)', 335 | location: { lat: 35.6895, lng: 139.6917 }, 336 | }, 337 | NORTHEAST_ASIA_2: { 338 | code: 'ap-northeast-2', 339 | displayName: 'Northeast Asia (Seoul)', 340 | location: { lat: 37.5665, lng: 126.978 }, 341 | }, 342 | OCEANIA: { 343 | code: 'ap-southeast-2', 344 | displayName: 'Oceania (Sydney)', 345 | location: { lat: -33.8688, lng: 151.2093 }, 346 | }, 347 | SOUTH_AMERICA: { 348 | code: 'sa-east-1', 349 | displayName: 'South America (São Paulo)', 350 | location: { lat: -1.2043218, lng: -47.1583944 }, 351 | }, 352 | } as const satisfies Record; 353 | 354 | export type RegionCodes = ValueOf['code']; 355 | 356 | export const AWS_REGION_CODES = Object.values(AWS_REGIONS).map( 357 | (region) => region.code 358 | ) as UnionToTuple; 359 | 360 | /** 361 | * Calculates the closest AWS region to a given location. 362 | */ 363 | export function getClosestAwsRegion(location: Location) { 364 | const distances = Object.entries(AWS_REGIONS).map< 365 | [region: string, distance: number] 366 | >(([name, region]) => { 367 | return [name, getDistance(location, region.location)] as const; 368 | }); 369 | 370 | const closestRegion = distances.reduce< 371 | [region: string, distance: number] | undefined 372 | >( 373 | (min, current) => 374 | min === undefined ? current : current[1] < min[1] ? current : min, 375 | undefined 376 | ); 377 | 378 | if (!closestRegion) { 379 | throw new Error('no closest region found'); 380 | } 381 | 382 | const [regionName] = closestRegion; 383 | 384 | return AWS_REGIONS[regionName as keyof typeof AWS_REGIONS]; 385 | } 386 | 387 | /** 388 | * Fetches the user's country code based on their IP address. 389 | */ 390 | export async function getCountryCode() { 391 | const response = await fetch(TRACE_URL); 392 | const data = await response.text(); 393 | const info = parseKeyValueList(data); 394 | const countryCode = info['loc']; 395 | 396 | if (!countryCode) { 397 | throw new Error('location not found'); 398 | } 399 | 400 | return countryCode; 401 | } 402 | 403 | /** 404 | * Gets the approximate coordinates of a country based on its country code. 405 | */ 406 | export function getCountryCoordinates(countryCode: string) { 407 | const location: Location = 408 | COUNTRY_COORDINATES[countryCode as keyof typeof COUNTRY_COORDINATES]; 409 | 410 | if (!location) { 411 | throw new Error(`unknown location code: ${countryCode}`); 412 | } 413 | 414 | return location; 415 | } 416 | 417 | /** 418 | * Calculates the distance between two points on Earth using the Haversine formula. 419 | * 420 | * @returns Distance between the points in kilometers 421 | */ 422 | export function getDistance(a: Location, b: Location): number { 423 | const lat = degreesToRadians(b.lat - a.lat); 424 | const lng = degreesToRadians(b.lng - a.lng); 425 | const a1 = 426 | Math.sin(lat / 2) * Math.sin(lat / 2) + 427 | Math.cos(degreesToRadians(a.lat)) * 428 | Math.cos(degreesToRadians(b.lat)) * 429 | Math.sin(lng / 2) * 430 | Math.sin(lng / 2); 431 | const c = 2 * Math.atan2(Math.sqrt(a1), Math.sqrt(1 - a1)); 432 | return EARTH_RADIUS * c; 433 | } 434 | 435 | /** 436 | * Converts degrees to radians 437 | * 438 | * @returns The angle in radians 439 | */ 440 | export function degreesToRadians(deg: number): number { 441 | return deg * (Math.PI / 180); 442 | } 443 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/server.ts: -------------------------------------------------------------------------------- 1 | import { createMcpServer, type Tool } from '@supabase/mcp-utils'; 2 | import packageJson from '../package.json' with { type: 'json' }; 3 | import { createContentApiClient } from './content-api/index.js'; 4 | import type { SupabasePlatform } from './platform/types.js'; 5 | import { getBranchingTools } from './tools/branching-tools.js'; 6 | import { getDatabaseOperationTools } from './tools/database-operation-tools.js'; 7 | import { getDebuggingTools } from './tools/debugging-tools.js'; 8 | import { getDevelopmentTools } from './tools/development-tools.js'; 9 | import { getDocsTools } from './tools/docs-tools.js'; 10 | import { getEdgeFunctionTools } from './tools/edge-function-tools.js'; 11 | import { getProjectManagementTools } from './tools/project-management-tools.js'; 12 | 13 | const { version } = packageJson; 14 | 15 | export type SupabasePlatformOptions = { 16 | /** 17 | * The access token for the Supabase Management API. 18 | */ 19 | accessToken: string; 20 | 21 | /** 22 | * The API URL for the Supabase Management API. 23 | */ 24 | apiUrl?: string; 25 | }; 26 | 27 | export type SupabaseMcpServerOptions = { 28 | /** 29 | * Platform implementation for Supabase. 30 | */ 31 | platform: SupabasePlatform; 32 | 33 | /** 34 | * The API URL for the Supabase Content API. 35 | */ 36 | contentApiUrl?: string; 37 | 38 | /** 39 | * The project ID to scope the server to. 40 | * 41 | * If undefined, the server will have access 42 | * to all organizations and projects for the user. 43 | */ 44 | projectId?: string; 45 | 46 | /** 47 | * Executes database queries in read-only mode if true. 48 | */ 49 | readOnly?: boolean; 50 | }; 51 | 52 | /** 53 | * Creates an MCP server for interacting with Supabase. 54 | */ 55 | export function createSupabaseMcpServer(options: SupabaseMcpServerOptions) { 56 | const { 57 | platform, 58 | projectId, 59 | readOnly, 60 | contentApiUrl = 'https://supabase.com/docs/api/graphql', 61 | } = options; 62 | 63 | const contentApiClientPromise = createContentApiClient(contentApiUrl); 64 | 65 | const server = createMcpServer({ 66 | name: 'supabase', 67 | version, 68 | async onInitialize(info) { 69 | // Note: in stateless HTTP mode, `onInitialize` will not always be called 70 | // so we cannot rely on it for initialization. It's still useful for telemetry. 71 | await platform.init?.(info); 72 | }, 73 | tools: async () => { 74 | const contentApiClient = await contentApiClientPromise; 75 | const tools: Record = {}; 76 | 77 | // Add account-level tools only if projectId is not provided 78 | if (!projectId) { 79 | Object.assign(tools, getProjectManagementTools({ platform })); 80 | } 81 | 82 | // Add project-level tools 83 | Object.assign( 84 | tools, 85 | getDatabaseOperationTools({ platform, projectId, readOnly }), 86 | getEdgeFunctionTools({ platform, projectId }), 87 | getDebuggingTools({ platform, projectId }), 88 | getDevelopmentTools({ platform, projectId }), 89 | getBranchingTools({ platform, projectId }), 90 | getDocsTools({ contentApiClient }) 91 | ); 92 | 93 | return tools; 94 | }, 95 | }); 96 | 97 | return server; 98 | } 99 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/tools/branching-tools.ts: -------------------------------------------------------------------------------- 1 | import { tool } from '@supabase/mcp-utils'; 2 | import { z } from 'zod'; 3 | import type { SupabasePlatform } from '../platform/types.js'; 4 | import { getBranchCost } from '../pricing.js'; 5 | import { hashObject } from '../util.js'; 6 | import { injectableTool } from './util.js'; 7 | 8 | export type BranchingToolsOptions = { 9 | platform: SupabasePlatform; 10 | projectId?: string; 11 | }; 12 | 13 | export function getBranchingTools({ 14 | platform, 15 | projectId, 16 | }: BranchingToolsOptions) { 17 | const project_id = projectId; 18 | 19 | return { 20 | create_branch: injectableTool({ 21 | description: 22 | 'Creates a development branch on a Supabase project. This will apply all migrations from the main project to a fresh branch database. Note that production data will not carry over. The branch will get its own project_id via the resulting project_ref. Use this ID to execute queries and migrations on the branch.', 23 | parameters: z.object({ 24 | project_id: z.string(), 25 | name: z 26 | .string() 27 | .default('develop') 28 | .describe('Name of the branch to create'), 29 | confirm_cost_id: z 30 | .string({ 31 | required_error: 32 | 'User must confirm understanding of costs before creating a branch.', 33 | }) 34 | .describe('The cost confirmation ID. Call `confirm_cost` first.'), 35 | }), 36 | inject: { project_id }, 37 | execute: async ({ project_id, name, confirm_cost_id }) => { 38 | const cost = getBranchCost(); 39 | const costHash = await hashObject(cost); 40 | if (costHash !== confirm_cost_id) { 41 | throw new Error( 42 | 'Cost confirmation ID does not match the expected cost of creating a branch.' 43 | ); 44 | } 45 | return await platform.createBranch(project_id, { name }); 46 | }, 47 | }), 48 | list_branches: injectableTool({ 49 | description: 50 | 'Lists all development branches of a Supabase project. This will return branch details including status which you can use to check when operations like merge/rebase/reset complete.', 51 | parameters: z.object({ 52 | project_id: z.string(), 53 | }), 54 | inject: { project_id }, 55 | execute: async ({ project_id }) => { 56 | return await platform.listBranches(project_id); 57 | }, 58 | }), 59 | delete_branch: tool({ 60 | description: 'Deletes a development branch.', 61 | parameters: z.object({ 62 | branch_id: z.string(), 63 | }), 64 | execute: async ({ branch_id }) => { 65 | return await platform.deleteBranch(branch_id); 66 | }, 67 | }), 68 | merge_branch: tool({ 69 | description: 70 | 'Merges migrations and edge functions from a development branch to production.', 71 | parameters: z.object({ 72 | branch_id: z.string(), 73 | }), 74 | execute: async ({ branch_id }) => { 75 | return await platform.mergeBranch(branch_id); 76 | }, 77 | }), 78 | reset_branch: tool({ 79 | description: 80 | 'Resets migrations of a development branch. Any untracked data or schema changes will be lost.', 81 | parameters: z.object({ 82 | branch_id: z.string(), 83 | migration_version: z 84 | .string() 85 | .optional() 86 | .describe( 87 | 'Reset your development branch to a specific migration version.' 88 | ), 89 | }), 90 | execute: async ({ branch_id, migration_version }) => { 91 | return await platform.resetBranch(branch_id, { 92 | migration_version, 93 | }); 94 | }, 95 | }), 96 | rebase_branch: tool({ 97 | description: 98 | 'Rebases a development branch on production. This will effectively run any newer migrations from production onto this branch to help handle migration drift.', 99 | parameters: z.object({ 100 | branch_id: z.string(), 101 | }), 102 | execute: async ({ branch_id }) => { 103 | return await platform.rebaseBranch(branch_id); 104 | }, 105 | }), 106 | }; 107 | } 108 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/tools/database-operation-tools.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import { listExtensionsSql, listTablesSql } from '../pg-meta/index.js'; 3 | import { 4 | postgresExtensionSchema, 5 | postgresTableSchema, 6 | } from '../pg-meta/types.js'; 7 | import type { SupabasePlatform } from '../platform/types.js'; 8 | import { injectableTool } from './util.js'; 9 | 10 | export type DatabaseOperationToolsOptions = { 11 | platform: SupabasePlatform; 12 | projectId?: string; 13 | readOnly?: boolean; 14 | }; 15 | 16 | export function getDatabaseOperationTools({ 17 | platform, 18 | projectId, 19 | readOnly, 20 | }: DatabaseOperationToolsOptions) { 21 | const project_id = projectId; 22 | 23 | const databaseOperationTools = { 24 | list_tables: injectableTool({ 25 | description: 'Lists all tables in one or more schemas.', 26 | parameters: z.object({ 27 | project_id: z.string(), 28 | schemas: z 29 | .array(z.string()) 30 | .describe('List of schemas to include. Defaults to all schemas.') 31 | .default(['public']), 32 | }), 33 | inject: { project_id }, 34 | execute: async ({ project_id, schemas }) => { 35 | const query = listTablesSql(schemas); 36 | const data = await platform.executeSql(project_id, { 37 | query, 38 | read_only: readOnly, 39 | }); 40 | const tables = data.map((table) => postgresTableSchema.parse(table)); 41 | return tables; 42 | }, 43 | }), 44 | list_extensions: injectableTool({ 45 | description: 'Lists all extensions in the database.', 46 | parameters: z.object({ 47 | project_id: z.string(), 48 | }), 49 | inject: { project_id }, 50 | execute: async ({ project_id }) => { 51 | const query = listExtensionsSql(); 52 | const data = await platform.executeSql(project_id, { 53 | query, 54 | read_only: readOnly, 55 | }); 56 | const extensions = data.map((extension) => 57 | postgresExtensionSchema.parse(extension) 58 | ); 59 | return extensions; 60 | }, 61 | }), 62 | list_migrations: injectableTool({ 63 | description: 'Lists all migrations in the database.', 64 | parameters: z.object({ 65 | project_id: z.string(), 66 | }), 67 | inject: { project_id }, 68 | execute: async ({ project_id }) => { 69 | return await platform.listMigrations(project_id); 70 | }, 71 | }), 72 | apply_migration: injectableTool({ 73 | description: 74 | 'Applies a migration to the database. Use this when executing DDL operations. Do not hardcode references to generated IDs in data migrations.', 75 | parameters: z.object({ 76 | project_id: z.string(), 77 | name: z.string().describe('The name of the migration in snake_case'), 78 | query: z.string().describe('The SQL query to apply'), 79 | }), 80 | inject: { project_id }, 81 | execute: async ({ project_id, name, query }) => { 82 | if (readOnly) { 83 | throw new Error('Cannot apply migration in read-only mode.'); 84 | } 85 | 86 | return await platform.applyMigration(project_id, { 87 | name, 88 | query, 89 | }); 90 | }, 91 | }), 92 | execute_sql: injectableTool({ 93 | description: 94 | 'Executes raw SQL in the Postgres database. Use `apply_migration` instead for DDL operations.', 95 | parameters: z.object({ 96 | project_id: z.string(), 97 | query: z.string().describe('The SQL query to execute'), 98 | }), 99 | inject: { project_id }, 100 | execute: async ({ query, project_id }) => { 101 | return await platform.executeSql(project_id, { 102 | query, 103 | read_only: readOnly, 104 | }); 105 | }, 106 | }), 107 | }; 108 | 109 | return databaseOperationTools; 110 | } 111 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/tools/debugging-tools.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import { getLogQuery } from '../logs.js'; 3 | import type { SupabasePlatform } from '../platform/types.js'; 4 | import { injectableTool } from './util.js'; 5 | 6 | export type DebuggingToolsOptions = { 7 | platform: SupabasePlatform; 8 | projectId?: string; 9 | }; 10 | 11 | export function getDebuggingTools({ 12 | platform, 13 | projectId, 14 | }: DebuggingToolsOptions) { 15 | const project_id = projectId; 16 | 17 | return { 18 | get_logs: injectableTool({ 19 | description: 20 | 'Gets logs for a Supabase project by service type. Use this to help debug problems with your app. This will only return logs within the last minute. If the logs you are looking for are older than 1 minute, re-run your test to reproduce them.', 21 | parameters: z.object({ 22 | project_id: z.string(), 23 | service: z 24 | .enum([ 25 | 'api', 26 | 'branch-action', 27 | 'postgres', 28 | 'edge-function', 29 | 'auth', 30 | 'storage', 31 | 'realtime', 32 | ]) 33 | .describe('The service to fetch logs for'), 34 | }), 35 | inject: { project_id }, 36 | execute: async ({ project_id, service }) => { 37 | // Omitting start and end time defaults to the last minute. 38 | // But since branch actions are async, we need to wait longer 39 | // for jobs to be scheduled and run to completion. 40 | const startTimestamp = 41 | service === 'branch-action' 42 | ? new Date(Date.now() - 5 * 60 * 1000) 43 | : undefined; 44 | 45 | return platform.getLogs(project_id, { 46 | sql: getLogQuery(service), 47 | iso_timestamp_start: startTimestamp?.toISOString(), 48 | }); 49 | }, 50 | }), 51 | }; 52 | } 53 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/tools/development-tools.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SupabasePlatform } from '../platform/types.js'; 3 | import { injectableTool } from './util.js'; 4 | 5 | export type DevelopmentToolsOptions = { 6 | platform: SupabasePlatform; 7 | projectId?: string; 8 | }; 9 | 10 | export function getDevelopmentTools({ 11 | platform, 12 | projectId, 13 | }: DevelopmentToolsOptions) { 14 | const project_id = projectId; 15 | 16 | return { 17 | get_project_url: injectableTool({ 18 | description: 'Gets the API URL for a project.', 19 | parameters: z.object({ 20 | project_id: z.string(), 21 | }), 22 | inject: { project_id }, 23 | execute: async ({ project_id }) => { 24 | return platform.getProjectUrl(project_id); 25 | }, 26 | }), 27 | get_anon_key: injectableTool({ 28 | description: 'Gets the anonymous API key for a project.', 29 | parameters: z.object({ 30 | project_id: z.string(), 31 | }), 32 | inject: { project_id }, 33 | execute: async ({ project_id }) => { 34 | return platform.getAnonKey(project_id); 35 | }, 36 | }), 37 | generate_typescript_types: injectableTool({ 38 | description: 'Generates TypeScript types for a project.', 39 | parameters: z.object({ 40 | project_id: z.string(), 41 | }), 42 | inject: { project_id }, 43 | execute: async ({ project_id }) => { 44 | return platform.generateTypescriptTypes(project_id); 45 | }, 46 | }), 47 | }; 48 | } 49 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/tools/docs-tools.ts: -------------------------------------------------------------------------------- 1 | import { tool } from '@supabase/mcp-utils'; 2 | import { source } from 'common-tags'; 3 | import { z } from 'zod'; 4 | import { type ContentApiClient } from '../content-api/index.js'; 5 | 6 | export type DocsToolsOptions = { 7 | contentApiClient: ContentApiClient; 8 | }; 9 | 10 | export function getDocsTools({ contentApiClient }: DocsToolsOptions) { 11 | return { 12 | search_docs: tool({ 13 | description: source` 14 | Search the Supabase documentation using GraphQL. Must be a valid GraphQL query. 15 | 16 | You should default to calling this even if you think you already know the answer, since the documentation is always being updated. 17 | 18 | Below is the GraphQL schema for the Supabase docs endpoint: 19 | ${contentApiClient.schema} 20 | `, 21 | parameters: z.object({ 22 | // Intentionally use a verbose param name for the LLM 23 | graphql_query: z.string().describe('GraphQL query string'), 24 | }), 25 | execute: async ({ graphql_query }) => { 26 | return await contentApiClient.query({ query: graphql_query }); 27 | }, 28 | }), 29 | }; 30 | } 31 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/tools/edge-function-tools.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import { edgeFunctionExample } from '../edge-function.js'; 3 | import type { SupabasePlatform } from '../platform/types.js'; 4 | import { injectableTool } from './util.js'; 5 | 6 | export type EdgeFunctionToolsOptions = { 7 | platform: SupabasePlatform; 8 | projectId?: string; 9 | }; 10 | 11 | export function getEdgeFunctionTools({ 12 | platform, 13 | projectId, 14 | }: EdgeFunctionToolsOptions) { 15 | const project_id = projectId; 16 | 17 | return { 18 | list_edge_functions: injectableTool({ 19 | description: 'Lists all Edge Functions in a Supabase project.', 20 | parameters: z.object({ 21 | project_id: z.string(), 22 | }), 23 | inject: { project_id }, 24 | execute: async ({ project_id }) => { 25 | return await platform.listEdgeFunctions(project_id); 26 | }, 27 | }), 28 | deploy_edge_function: injectableTool({ 29 | description: `Deploys an Edge Function to a Supabase project. If the function already exists, this will create a new version. Example:\n\n${edgeFunctionExample}`, 30 | parameters: z.object({ 31 | project_id: z.string(), 32 | name: z.string().describe('The name of the function'), 33 | entrypoint_path: z 34 | .string() 35 | .default('index.ts') 36 | .describe('The entrypoint of the function'), 37 | import_map_path: z 38 | .string() 39 | .describe('The import map for the function.') 40 | .optional(), 41 | files: z 42 | .array( 43 | z.object({ 44 | name: z.string(), 45 | content: z.string(), 46 | }) 47 | ) 48 | .describe( 49 | 'The files to upload. This should include the entrypoint and any relative dependencies.' 50 | ), 51 | }), 52 | inject: { project_id }, 53 | execute: async ({ 54 | project_id, 55 | name, 56 | entrypoint_path, 57 | import_map_path, 58 | files, 59 | }) => { 60 | return await platform.deployEdgeFunction(project_id, { 61 | name, 62 | entrypoint_path, 63 | import_map_path, 64 | files, 65 | }); 66 | }, 67 | }), 68 | }; 69 | } 70 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/tools/project-management-tools.ts: -------------------------------------------------------------------------------- 1 | import { tool } from '@supabase/mcp-utils'; 2 | import { z } from 'zod'; 3 | import type { SupabasePlatform } from '../platform/types.js'; 4 | import { type Cost, getBranchCost, getNextProjectCost } from '../pricing.js'; 5 | import { AWS_REGION_CODES } from '../regions.js'; 6 | import { hashObject } from '../util.js'; 7 | 8 | export type ProjectManagementToolsOptions = { 9 | platform: SupabasePlatform; 10 | }; 11 | 12 | export function getProjectManagementTools({ 13 | platform, 14 | }: ProjectManagementToolsOptions) { 15 | return { 16 | list_organizations: tool({ 17 | description: 'Lists all organizations that the user is a member of.', 18 | parameters: z.object({}), 19 | execute: async () => { 20 | return await platform.listOrganizations(); 21 | }, 22 | }), 23 | get_organization: tool({ 24 | description: 25 | 'Gets details for an organization. Includes subscription plan.', 26 | parameters: z.object({ 27 | id: z.string().describe('The organization ID'), 28 | }), 29 | execute: async ({ id: organizationId }) => { 30 | return await platform.getOrganization(organizationId); 31 | }, 32 | }), 33 | list_projects: tool({ 34 | description: 35 | 'Lists all Supabase projects for the user. Use this to help discover the project ID of the project that the user is working on.', 36 | parameters: z.object({}), 37 | execute: async () => { 38 | return await platform.listProjects(); 39 | }, 40 | }), 41 | get_project: tool({ 42 | description: 'Gets details for a Supabase project.', 43 | parameters: z.object({ 44 | id: z.string().describe('The project ID'), 45 | }), 46 | execute: async ({ id }) => { 47 | return await platform.getProject(id); 48 | }, 49 | }), 50 | get_cost: tool({ 51 | description: 52 | 'Gets the cost of creating a new project or branch. Never assume organization as costs can be different for each.', 53 | parameters: z.object({ 54 | type: z.enum(['project', 'branch']), 55 | organization_id: z 56 | .string() 57 | .describe('The organization ID. Always ask the user.'), 58 | }), 59 | execute: async ({ type, organization_id }) => { 60 | function generateResponse(cost: Cost) { 61 | return `The new ${type} will cost $${cost.amount} ${cost.recurrence}. You must repeat this to the user and confirm their understanding.`; 62 | } 63 | switch (type) { 64 | case 'project': { 65 | const cost = await getNextProjectCost(platform, organization_id); 66 | return generateResponse(cost); 67 | } 68 | case 'branch': { 69 | const cost = getBranchCost(); 70 | return generateResponse(cost); 71 | } 72 | default: 73 | throw new Error(`Unknown cost type: ${type}`); 74 | } 75 | }, 76 | }), 77 | confirm_cost: tool({ 78 | description: 79 | 'Ask the user to confirm their understanding of the cost of creating a new project or branch. Call `get_cost` first. Returns a unique ID for this confirmation which should be passed to `create_project` or `create_branch`.', 80 | parameters: z.object({ 81 | type: z.enum(['project', 'branch']), 82 | recurrence: z.enum(['hourly', 'monthly']), 83 | amount: z.number(), 84 | }), 85 | execute: async (cost) => { 86 | return await hashObject(cost); 87 | }, 88 | }), 89 | create_project: tool({ 90 | description: 91 | 'Creates a new Supabase project. Always ask the user which organization to create the project in. The project can take a few minutes to initialize - use `get_project` to check the status.', 92 | parameters: z.object({ 93 | name: z.string().describe('The name of the project'), 94 | region: z.optional( 95 | z 96 | .enum(AWS_REGION_CODES) 97 | .describe( 98 | 'The region to create the project in. Defaults to the closest region.' 99 | ) 100 | ), 101 | organization_id: z.string(), 102 | confirm_cost_id: z 103 | .string({ 104 | required_error: 105 | 'User must confirm understanding of costs before creating a project.', 106 | }) 107 | .describe('The cost confirmation ID. Call `confirm_cost` first.'), 108 | }), 109 | execute: async ({ name, region, organization_id, confirm_cost_id }) => { 110 | const cost = await getNextProjectCost(platform, organization_id); 111 | const costHash = await hashObject(cost); 112 | if (costHash !== confirm_cost_id) { 113 | throw new Error( 114 | 'Cost confirmation ID does not match the expected cost of creating a project.' 115 | ); 116 | } 117 | 118 | return await platform.createProject({ 119 | name, 120 | region, 121 | organization_id, 122 | }); 123 | }, 124 | }), 125 | pause_project: tool({ 126 | description: 'Pauses a Supabase project.', 127 | parameters: z.object({ 128 | project_id: z.string(), 129 | }), 130 | execute: async ({ project_id }) => { 131 | return await platform.pauseProject(project_id); 132 | }, 133 | }), 134 | restore_project: tool({ 135 | description: 'Restores a Supabase project.', 136 | parameters: z.object({ 137 | project_id: z.string(), 138 | }), 139 | execute: async ({ project_id }) => { 140 | return await platform.restoreProject(project_id); 141 | }, 142 | }), 143 | }; 144 | } 145 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/tools/util.ts: -------------------------------------------------------------------------------- 1 | import { type Tool, tool } from '@supabase/mcp-utils'; 2 | import { z } from 'zod'; 3 | 4 | type RequireKeys = { 5 | [K in keyof Injected]: K extends keyof Params ? Injected[K] : never; 6 | }; 7 | 8 | export type InjectableTool< 9 | Params extends z.ZodObject = z.ZodObject, 10 | Result = unknown, 11 | Injected extends Partial> = {}, 12 | > = Tool & { 13 | /** 14 | * Optionally injects static parameter values into the tool's 15 | * execute function and removes them from the parameter schema. 16 | * 17 | * Useful to scope tools to a specific project at config time 18 | * without redefining the tool. 19 | */ 20 | inject?: Injected & RequireKeys>; 21 | }; 22 | 23 | export function injectableTool< 24 | Params extends z.ZodObject, 25 | Result, 26 | Injected extends Partial>, 27 | >({ 28 | description, 29 | parameters, 30 | inject, 31 | execute, 32 | }: InjectableTool) { 33 | // If all injected parameters are undefined, return the original tool 34 | if (!inject || Object.values(inject).every((value) => value === undefined)) { 35 | return tool({ 36 | description, 37 | parameters, 38 | execute, 39 | }); 40 | } 41 | 42 | // Create a mask used to remove injected parameters from the schema 43 | const mask = Object.fromEntries( 44 | Object.entries(inject) 45 | .filter(([_, value]) => value !== undefined) 46 | .map(([key]) => [key, true as const]) 47 | ); 48 | 49 | type NonNullableKeys = { 50 | [K in keyof Injected]: Injected[K] extends undefined ? never : K; 51 | }[keyof Injected]; 52 | 53 | type CleanParams = z.infer extends any 54 | ? { 55 | [K in keyof z.infer as K extends NonNullableKeys 56 | ? never 57 | : K]: z.infer[K]; 58 | } 59 | : never; 60 | 61 | return tool({ 62 | description, 63 | parameters: parameters.omit(mask), 64 | execute: (args) => execute({ ...args, ...inject }), 65 | }) as Tool, Result>; 66 | } 67 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/transports/stdio.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; 4 | import { parseArgs } from 'node:util'; 5 | import packageJson from '../../package.json' with { type: 'json' }; 6 | import { createSupabaseApiPlatform } from '../platform/api-platform.js'; 7 | import { createSupabaseMcpServer } from '../server.js'; 8 | 9 | const { version } = packageJson; 10 | 11 | async function main() { 12 | const { 13 | values: { 14 | ['access-token']: cliAccessToken, 15 | ['project-ref']: projectId, 16 | ['read-only']: readOnly, 17 | ['api-url']: apiUrl, 18 | ['version']: showVersion, 19 | }, 20 | } = parseArgs({ 21 | options: { 22 | ['access-token']: { 23 | type: 'string', 24 | }, 25 | ['project-ref']: { 26 | type: 'string', 27 | }, 28 | ['read-only']: { 29 | type: 'boolean', 30 | default: false, 31 | }, 32 | ['api-url']: { 33 | type: 'string', 34 | }, 35 | ['version']: { 36 | type: 'boolean', 37 | }, 38 | }, 39 | }); 40 | 41 | if (showVersion) { 42 | console.log(version); 43 | process.exit(0); 44 | } 45 | 46 | // Use access token from CLI argument or environment variable 47 | const accessToken = cliAccessToken ?? process.env.SUPABASE_ACCESS_TOKEN; 48 | 49 | if (!accessToken) { 50 | console.error( 51 | 'Please provide a personal access token (PAT) with the --access-token flag or set the SUPABASE_ACCESS_TOKEN environment variable' 52 | ); 53 | process.exit(1); 54 | } 55 | 56 | const platform = createSupabaseApiPlatform({ 57 | accessToken, 58 | apiUrl, 59 | }); 60 | 61 | const server = createSupabaseMcpServer({ 62 | platform, 63 | projectId, 64 | readOnly, 65 | }); 66 | 67 | const transport = new StdioServerTransport(); 68 | 69 | await server.connect(transport); 70 | } 71 | 72 | main().catch(console.error); 73 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/types/sql.d.ts: -------------------------------------------------------------------------------- 1 | declare module '*.sql' { 2 | const content: string; 3 | export default content; 4 | } 5 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/util.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { hashObject, parseKeyValueList } from './util.js'; 3 | 4 | describe('parseKeyValueList', () => { 5 | it('should parse a simple key-value string', () => { 6 | const input = 'key1=value1\nkey2=value2'; 7 | const result = parseKeyValueList(input); 8 | expect(result).toEqual({ key1: 'value1', key2: 'value2' }); 9 | }); 10 | 11 | it('should handle empty values', () => { 12 | const input = 'key1=\nkey2=value2'; 13 | const result = parseKeyValueList(input); 14 | expect(result).toEqual({ key1: '', key2: 'value2' }); 15 | }); 16 | 17 | it('should handle values with equals sign', () => { 18 | const input = 'key1=value=with=equals\nkey2=simple'; 19 | const result = parseKeyValueList(input); 20 | expect(result).toEqual({ key1: 'value=with=equals', key2: 'simple' }); 21 | }); 22 | 23 | it('should handle empty input', () => { 24 | const input = ''; 25 | const result = parseKeyValueList(input); 26 | expect(result).toEqual({}); 27 | }); 28 | 29 | it('should handle input with only newlines', () => { 30 | const input = '\n\n\n'; 31 | const result = parseKeyValueList(input); 32 | expect(result).toEqual({}); 33 | }); 34 | 35 | it('should parse real-world Cloudflare trace output', () => { 36 | const input = 37 | 'fl=123abc\nvisit_scheme=https\nloc=US\ntls=TLSv1.3\nhttp=http/2'; 38 | const result = parseKeyValueList(input); 39 | expect(result).toEqual({ 40 | fl: '123abc', 41 | visit_scheme: 'https', 42 | loc: 'US', 43 | tls: 'TLSv1.3', 44 | http: 'http/2', 45 | }); 46 | }); 47 | }); 48 | 49 | describe('hashObject', () => { 50 | it('should consistently hash the same object', async () => { 51 | const obj = { a: 1, b: 2, c: 3 }; 52 | 53 | const hash1 = await hashObject(obj); 54 | const hash2 = await hashObject(obj); 55 | 56 | expect(hash1).toBe(hash2); 57 | }); 58 | 59 | it('should produce the same hash regardless of property order', async () => { 60 | const obj1 = { a: 1, b: 2, c: 3 }; 61 | const obj2 = { c: 3, a: 1, b: 2 }; 62 | 63 | const hash1 = await hashObject(obj1); 64 | const hash2 = await hashObject(obj2); 65 | 66 | expect(hash1).toBe(hash2); 67 | }); 68 | 69 | it('should produce different hashes for different objects', async () => { 70 | const obj1 = { a: 1, b: 2 }; 71 | const obj2 = { a: 1, b: 3 }; 72 | 73 | const hash1 = await hashObject(obj1); 74 | const hash2 = await hashObject(obj2); 75 | 76 | expect(hash1).not.toBe(hash2); 77 | }); 78 | 79 | it('should handle nested objects', async () => { 80 | const obj1 = { a: 1, b: { c: 2 } }; 81 | const obj2 = { a: 1, b: { c: 3 } }; 82 | 83 | const hash1 = await hashObject(obj1); 84 | const hash2 = await hashObject(obj2); 85 | 86 | expect(hash1).not.toBe(hash2); 87 | }); 88 | 89 | it('should handle arrays', async () => { 90 | const obj1 = { a: [1, 2, 3] }; 91 | const obj2 = { a: [1, 2, 4] }; 92 | 93 | const hash1 = await hashObject(obj1); 94 | const hash2 = await hashObject(obj2); 95 | 96 | expect(hash1).not.toBe(hash2); 97 | }); 98 | }); 99 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/src/util.ts: -------------------------------------------------------------------------------- 1 | export type ValueOf = T[keyof T]; 2 | 3 | // UnionToIntersection = A & B 4 | export type UnionToIntersection = ( 5 | U extends unknown 6 | ? (arg: U) => 0 7 | : never 8 | ) extends (arg: infer I) => 0 9 | ? I 10 | : never; 11 | 12 | // LastInUnion = B 13 | export type LastInUnion = UnionToIntersection< 14 | U extends unknown ? (x: U) => 0 : never 15 | > extends (x: infer L) => 0 16 | ? L 17 | : never; 18 | 19 | // UnionToTuple = [A, B] 20 | export type UnionToTuple> = [T] extends [never] 21 | ? [] 22 | : [Last, ...UnionToTuple>]; 23 | 24 | /** 25 | * Parses a key-value string into an object. 26 | * 27 | * @returns An object representing the key-value pairs 28 | * 29 | * @example 30 | * const result = parseKeyValueList("key1=value1\nkey2=value2"); 31 | * console.log(result); // { key1: "value1", key2: "value2" } 32 | */ 33 | export function parseKeyValueList(data: string): { [key: string]: string } { 34 | return Object.fromEntries( 35 | data 36 | .split('\n') 37 | .map((item) => item.split(/=(.*)/)) // split only on the first '=' 38 | .filter(([key]) => key) // filter out empty keys 39 | .map(([key, value]) => [key, value ?? '']) // ensure value is not undefined 40 | ); 41 | } 42 | 43 | /** 44 | * Creates a unique hash from a JavaScript object. 45 | * @param obj - The object to hash 46 | * @param length - Optional length to truncate the hash (default: full length) 47 | */ 48 | export async function hashObject( 49 | obj: Record, 50 | length?: number 51 | ): Promise { 52 | // Sort object keys to ensure consistent output regardless of original key order 53 | const str = JSON.stringify(obj, (_, value) => { 54 | if (value && typeof value === 'object' && !Array.isArray(value)) { 55 | return Object.keys(value) 56 | .sort() 57 | .reduce>((result, key) => { 58 | result[key] = value[key]; 59 | return result; 60 | }, {}); 61 | } 62 | return value; 63 | }); 64 | 65 | const buffer = await crypto.subtle.digest( 66 | 'SHA-256', 67 | new TextEncoder().encode(str) 68 | ); 69 | 70 | // Convert to base64 71 | const base64Hash = btoa(String.fromCharCode(...new Uint8Array(buffer))); 72 | return base64Hash.slice(0, length); 73 | } 74 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/test/extensions.d.ts: -------------------------------------------------------------------------------- 1 | import 'vitest'; 2 | 3 | interface CustomMatchers { 4 | /** 5 | * Uses LLM-as-a-judge to evaluate the received string against 6 | * criteria described in natural language. 7 | */ 8 | toMatchCriteria(criteria: string): Promise; 9 | } 10 | 11 | declare module 'vitest' { 12 | interface Assertion extends CustomMatchers {} 13 | interface AsymmetricMatchersContaining extends CustomMatchers {} 14 | } 15 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/test/extensions.ts: -------------------------------------------------------------------------------- 1 | import { anthropic } from '@ai-sdk/anthropic'; 2 | import { generateObject } from 'ai'; 3 | import { codeBlock, stripIndent } from 'common-tags'; 4 | import { expect } from 'vitest'; 5 | import { z } from 'zod'; 6 | 7 | const model = anthropic('claude-3-7-sonnet-20250219'); 8 | 9 | expect.extend({ 10 | async toMatchCriteria(received: string, criteria: string) { 11 | const completionResponse = await generateObject({ 12 | model, 13 | schema: z.object({ 14 | pass: z 15 | .boolean() 16 | .describe("Whether the 'Received' adheres to the test 'Criteria'"), 17 | reason: z 18 | .string() 19 | .describe( 20 | "The reason why 'Received' does or does not adhere to the test 'Criteria'. Keep concise while explaining exactly which part of 'Received' did or did not pass the test 'Criteria'." 21 | ), 22 | }), 23 | messages: [ 24 | { 25 | role: 'system', 26 | content: stripIndent` 27 | You are a test runner. Your job is to evaluate whether 'Received' adheres to the test 'Criteria'. 28 | `, 29 | }, 30 | { 31 | role: 'user', 32 | content: codeBlock` 33 | Received: 34 | ${received} 35 | 36 | Criteria: 37 | ${criteria} 38 | `, 39 | }, 40 | ], 41 | }); 42 | 43 | const { pass, reason } = completionResponse.object; 44 | 45 | return { 46 | message: () => 47 | codeBlock` 48 | ${this.utils.matcherHint('toMatchCriteria', received, criteria, { 49 | comment: `evaluated by LLM '${model.modelId}'`, 50 | isNot: this.isNot, 51 | promise: this.promise, 52 | })} 53 | 54 | ${reason} 55 | `, 56 | pass, 57 | }; 58 | }, 59 | }); 60 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/test/llm.e2e.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import { anthropic } from '@ai-sdk/anthropic'; 4 | import { StreamTransport } from '@supabase/mcp-utils'; 5 | import { 6 | experimental_createMCPClient as createMCPClient, 7 | generateText, 8 | type ToolCallUnion, 9 | type ToolSet, 10 | } from 'ai'; 11 | import { codeBlock } from 'common-tags'; 12 | import { setupServer } from 'msw/node'; 13 | import { beforeEach, describe, expect, test } from 'vitest'; 14 | import { extractFiles } from '../src/eszip.js'; 15 | import { createSupabaseMcpServer } from '../src/index.js'; 16 | import { createSupabaseApiPlatform } from '../src/platform/api-platform.js'; 17 | import { 18 | ACCESS_TOKEN, 19 | API_URL, 20 | createOrganization, 21 | createProject, 22 | MCP_CLIENT_NAME, 23 | mockBranches, 24 | mockManagementApi, 25 | mockOrgs, 26 | mockProjects, 27 | } from './mocks.js'; 28 | 29 | type SetupOptions = { 30 | projectId?: string; 31 | }; 32 | 33 | /** 34 | * Sets up an MCP client and server for testing. 35 | */ 36 | async function setup({ projectId }: SetupOptions = {}) { 37 | const clientTransport = new StreamTransport(); 38 | const serverTransport = new StreamTransport(); 39 | 40 | clientTransport.readable.pipeTo(serverTransport.writable); 41 | serverTransport.readable.pipeTo(clientTransport.writable); 42 | 43 | const platform = createSupabaseApiPlatform({ 44 | apiUrl: API_URL, 45 | accessToken: ACCESS_TOKEN, 46 | }); 47 | 48 | const server = createSupabaseMcpServer({ 49 | platform, 50 | projectId, 51 | }); 52 | 53 | await server.connect(serverTransport); 54 | 55 | const client = await createMCPClient({ 56 | name: MCP_CLIENT_NAME, 57 | transport: clientTransport, 58 | }); 59 | 60 | return { client, clientTransport, server, serverTransport }; 61 | } 62 | 63 | beforeEach(async () => { 64 | mockOrgs.clear(); 65 | mockProjects.clear(); 66 | mockBranches.clear(); 67 | 68 | const server = setupServer(...mockManagementApi); 69 | server.listen({ onUnhandledRequest: 'bypass' }); 70 | }); 71 | 72 | describe('llm tests', () => { 73 | test('identifies correct project before listing tables', async () => { 74 | const { client } = await setup(); 75 | const model = anthropic('claude-3-7-sonnet-20250219'); 76 | 77 | const org = await createOrganization({ 78 | name: 'My Org', 79 | plan: 'free', 80 | allowed_release_channels: ['ga'], 81 | }); 82 | 83 | const todosProject = await createProject({ 84 | name: 'todos-app', 85 | region: 'us-east-1', 86 | organization_id: org.id, 87 | }); 88 | 89 | const inventoryProject = await createProject({ 90 | name: 'inventory-app', 91 | region: 'us-east-1', 92 | organization_id: org.id, 93 | }); 94 | 95 | await todosProject.db.sql`create table todos (id serial, name text)`; 96 | await inventoryProject.db 97 | .sql`create table inventory (id serial, name text)`; 98 | 99 | const toolCalls: ToolCallUnion[] = []; 100 | const tools = await client.tools(); 101 | 102 | const { text } = await generateText({ 103 | model, 104 | tools, 105 | messages: [ 106 | { 107 | role: 'system', 108 | content: 109 | 'You are a coding assistant. The current working directory is /home/user/projects/todos-app.', 110 | }, 111 | { 112 | role: 'user', 113 | content: 'What tables do I have?', 114 | }, 115 | ], 116 | maxSteps: 3, 117 | async onStepFinish({ toolCalls: tools }) { 118 | toolCalls.push(...tools); 119 | }, 120 | }); 121 | 122 | expect(toolCalls).toHaveLength(2); 123 | expect(toolCalls[0]).toEqual( 124 | expect.objectContaining({ toolName: 'list_projects' }) 125 | ); 126 | expect(toolCalls[1]).toEqual( 127 | expect.objectContaining({ toolName: 'list_tables' }) 128 | ); 129 | 130 | await expect(text).toMatchCriteria( 131 | 'Describes a single table in the "todos-app" project called "todos"' 132 | ); 133 | }); 134 | 135 | test('deploys an edge function', async () => { 136 | const { client } = await setup(); 137 | const model = anthropic('claude-3-7-sonnet-20250219'); 138 | 139 | const org = await createOrganization({ 140 | name: 'My Org', 141 | plan: 'free', 142 | allowed_release_channels: ['ga'], 143 | }); 144 | 145 | const project = await createProject({ 146 | name: 'todos-app', 147 | region: 'us-east-1', 148 | organization_id: org.id, 149 | }); 150 | 151 | const toolCalls: ToolCallUnion[] = []; 152 | const tools = await client.tools(); 153 | 154 | const { text } = await generateText({ 155 | model, 156 | tools, 157 | messages: [ 158 | { 159 | role: 'system', 160 | content: 161 | 'You are a coding assistant. The current working directory is /home/user/projects/todos-app.', 162 | }, 163 | { 164 | role: 'user', 165 | content: `Deploy an edge function to project with ref ${project.id} that returns the current time in UTC.`, 166 | }, 167 | ], 168 | maxSteps: 3, 169 | async onStepFinish({ toolCalls: tools }) { 170 | toolCalls.push(...tools); 171 | }, 172 | }); 173 | 174 | expect(toolCalls).toContainEqual( 175 | expect.objectContaining({ toolName: 'deploy_edge_function' }) 176 | ); 177 | 178 | await expect(text).toMatchCriteria( 179 | 'Confirms the successful deployment of an edge function that will return the current time in UTC. It describes steps to test the function.' 180 | ); 181 | }); 182 | 183 | test('modifies an edge function', async () => { 184 | const { client } = await setup(); 185 | const model = anthropic('claude-3-7-sonnet-20250219'); 186 | 187 | const org = await createOrganization({ 188 | name: 'My Org', 189 | plan: 'free', 190 | allowed_release_channels: ['ga'], 191 | }); 192 | 193 | const project = await createProject({ 194 | name: 'todos-app', 195 | region: 'us-east-1', 196 | organization_id: org.id, 197 | }); 198 | 199 | const code = codeBlock` 200 | Deno.serve(async (req: Request) => { 201 | return new Response('Hello world!', { headers: { 'Content-Type': 'text/plain' } }) 202 | }) 203 | `; 204 | 205 | const edgeFunction = await project.deployEdgeFunction( 206 | { 207 | name: 'hello-world', 208 | entrypoint_path: 'index.ts', 209 | }, 210 | [ 211 | new File([code], 'index.ts', { 212 | type: 'application/typescript', 213 | }), 214 | ] 215 | ); 216 | 217 | const toolCalls: ToolCallUnion[] = []; 218 | const tools = await client.tools(); 219 | 220 | const { text } = await generateText({ 221 | model, 222 | tools, 223 | messages: [ 224 | { 225 | role: 'system', 226 | content: 227 | 'You are a coding assistant. The current working directory is /home/user/projects/todos-app.', 228 | }, 229 | { 230 | role: 'user', 231 | content: `Change my edge function (project id ${project.id}) to replace "world" with "Earth".`, 232 | }, 233 | ], 234 | maxSteps: 3, 235 | async onStepFinish({ toolCalls: tools }) { 236 | toolCalls.push(...tools); 237 | }, 238 | }); 239 | 240 | expect(toolCalls).toHaveLength(2); 241 | expect(toolCalls[0]).toEqual( 242 | expect.objectContaining({ toolName: 'list_edge_functions' }) 243 | ); 244 | expect(toolCalls[1]).toEqual( 245 | expect.objectContaining({ toolName: 'deploy_edge_function' }) 246 | ); 247 | 248 | await expect(text).toMatchCriteria( 249 | 'Confirms the successful modification of an Edge Function.' 250 | ); 251 | 252 | const files = await extractFiles( 253 | edgeFunction.eszip!, 254 | edgeFunction.pathPrefix 255 | ); 256 | 257 | expect(files).toHaveLength(1); 258 | expect(files[0].name).toBe('index.ts'); 259 | await expect(files[0].text()).resolves.toEqual(codeBlock` 260 | Deno.serve(async (req: Request) => { 261 | return new Response('Hello Earth!', { headers: { 'Content-Type': 'text/plain' } }) 262 | }) 263 | `); 264 | }); 265 | 266 | test('project scoped server uses less tool calls', async () => { 267 | const org = await createOrganization({ 268 | name: 'My Org', 269 | plan: 'free', 270 | allowed_release_channels: ['ga'], 271 | }); 272 | 273 | const project = await createProject({ 274 | name: 'todos-app', 275 | region: 'us-east-1', 276 | organization_id: org.id, 277 | }); 278 | 279 | await project.db.sql`create table todos (id serial, name text)`; 280 | 281 | const { client } = await setup({ projectId: project.id }); 282 | const model = anthropic('claude-3-7-sonnet-20250219'); 283 | 284 | const toolCalls: ToolCallUnion[] = []; 285 | const tools = await client.tools(); 286 | 287 | const { text } = await generateText({ 288 | model, 289 | tools, 290 | messages: [ 291 | { 292 | role: 'system', 293 | content: 294 | 'You are a coding assistant. The current working directory is /home/user/projects/todos-app.', 295 | }, 296 | { 297 | role: 'user', 298 | content: `What tables do I have?`, 299 | }, 300 | ], 301 | maxSteps: 2, 302 | async onStepFinish({ toolCalls: tools }) { 303 | toolCalls.push(...tools); 304 | }, 305 | }); 306 | 307 | expect(toolCalls).toHaveLength(1); 308 | expect(toolCalls[0]).toEqual( 309 | expect.objectContaining({ toolName: 'list_tables' }) 310 | ); 311 | 312 | await expect(text).toMatchCriteria( 313 | `Describes the a single todos table available in the project.` 314 | ); 315 | }); 316 | }); 317 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/test/plugins/text-loader.ts: -------------------------------------------------------------------------------- 1 | import { readFile } from 'fs/promises'; 2 | import { Plugin } from 'vite'; 3 | 4 | export function textLoaderPlugin(extension: string): Plugin { 5 | return { 6 | name: 'text-loader', 7 | async transform(code, id) { 8 | if (id.endsWith(extension)) { 9 | const textContent = await readFile(id, 'utf8'); 10 | return `export default ${JSON.stringify(textContent)};`; 11 | } 12 | return code; 13 | }, 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/test/stdio.integration.ts: -------------------------------------------------------------------------------- 1 | import { Client } from '@modelcontextprotocol/sdk/client/index.js'; 2 | import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; 3 | import { describe, expect, test } from 'vitest'; 4 | import { ACCESS_TOKEN, MCP_CLIENT_NAME, MCP_CLIENT_VERSION } from './mocks.js'; 5 | import { LoggingMessageNotificationSchema } from '@modelcontextprotocol/sdk/types.js'; 6 | 7 | type SetupOptions = { 8 | accessToken?: string; 9 | projectId?: string; 10 | readOnly?: boolean; 11 | }; 12 | 13 | async function setup(options: SetupOptions = {}) { 14 | const { accessToken = ACCESS_TOKEN, projectId, readOnly } = options; 15 | 16 | const client = new Client( 17 | { 18 | name: MCP_CLIENT_NAME, 19 | version: MCP_CLIENT_VERSION, 20 | }, 21 | { 22 | capabilities: {}, 23 | } 24 | ); 25 | 26 | client.setNotificationHandler(LoggingMessageNotificationSchema, (message) => { 27 | const { level, data } = message.params; 28 | if (level === 'error') { 29 | console.error(data); 30 | } else { 31 | console.log(data); 32 | } 33 | }); 34 | 35 | const command = 'npx'; 36 | const args = ['@supabase/mcp-server-supabase']; 37 | 38 | if (accessToken) { 39 | args.push('--access-token', accessToken); 40 | } 41 | 42 | if (projectId) { 43 | args.push('--project-ref', projectId); 44 | } 45 | 46 | if (readOnly) { 47 | args.push('--read-only'); 48 | } 49 | 50 | const clientTransport = new StdioClientTransport({ 51 | command, 52 | args, 53 | }); 54 | 55 | await client.connect(clientTransport); 56 | 57 | return { client, clientTransport }; 58 | } 59 | 60 | describe('stdio', () => { 61 | test('server connects and lists tools', async () => { 62 | const { client } = await setup(); 63 | 64 | const { tools } = await client.listTools(); 65 | 66 | expect(tools.length).toBeGreaterThan(0); 67 | }); 68 | 69 | test('missing access token fails', async () => { 70 | const setupPromise = setup({ accessToken: null as any }); 71 | 72 | await expect(setupPromise).rejects.toThrow('MCP error -32000'); 73 | }); 74 | }); 75 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@total-typescript/tsconfig/tsc/dom/library", 3 | "include": ["src/**/*.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/tsup.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'tsup'; 2 | 3 | export default defineConfig([ 4 | { 5 | entry: ['src/index.ts', 'src/transports/stdio.ts', 'src/platform/index.ts'], 6 | format: ['cjs', 'esm'], 7 | outDir: 'dist', 8 | sourcemap: true, 9 | dts: true, 10 | minify: true, 11 | splitting: true, 12 | loader: { 13 | '.sql': 'text', 14 | }, 15 | }, 16 | ]); 17 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { configDefaults, defineConfig } from 'vitest/config'; 2 | import { textLoaderPlugin } from './test/plugins/text-loader.js'; 3 | 4 | export default defineConfig({ 5 | plugins: [textLoaderPlugin('.sql')], 6 | test: { 7 | setupFiles: ['./vitest.setup.ts'], 8 | testTimeout: 30_000, // PGlite can take a while to initialize 9 | coverage: { 10 | reporter: ['text', 'lcov'], 11 | reportsDirectory: 'test/coverage', 12 | include: ['src/**/*.{ts,tsx}'], 13 | exclude: [...configDefaults.coverage.exclude!, 'src/transports/stdio.ts'], 14 | }, 15 | }, 16 | }); 17 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/vitest.setup.ts: -------------------------------------------------------------------------------- 1 | import { config } from 'dotenv'; 2 | import { statSync } from 'fs'; 3 | import './test/extensions.js'; 4 | 5 | if (!process.env.CI) { 6 | const envPath = '.env.local'; 7 | statSync(envPath); 8 | config({ path: envPath }); 9 | } 10 | -------------------------------------------------------------------------------- /packages/mcp-server-supabase/vitest.workspace.ts: -------------------------------------------------------------------------------- 1 | import { defineWorkspace } from 'vitest/config'; 2 | 3 | export default defineWorkspace([ 4 | { 5 | extends: './vitest.config.ts', 6 | test: { 7 | name: 'unit', 8 | include: ['src/**/*.{test,spec}.ts'], 9 | }, 10 | }, 11 | { 12 | extends: './vitest.config.ts', 13 | test: { 14 | name: 'e2e', 15 | include: ['test/**/*.e2e.ts'], 16 | testTimeout: 60_000, 17 | }, 18 | }, 19 | { 20 | extends: './vitest.config.ts', 21 | test: { 22 | name: 'integration', 23 | include: ['test/**/*.integration.ts'], 24 | }, 25 | }, 26 | ]); 27 | -------------------------------------------------------------------------------- /packages/mcp-utils/README.md: -------------------------------------------------------------------------------- 1 | # @supabase/mcp-utils 2 | 3 | A collection of utilities for working with the Model Context Protocol (MCP). 4 | 5 | ## Installation 6 | 7 | ```shell 8 | npm i @supabase/mcp-utils 9 | ``` 10 | 11 | ```shell 12 | yarn add @supabase/mcp-utils 13 | ``` 14 | 15 | ```shell 16 | pnpm add @supabase/mcp-utils 17 | ``` 18 | 19 | ## API 20 | 21 | ### `StreamTransport` 22 | 23 | If you're building an MCP client, you'll need to connect to MCP servers programmatically using a [transport](https://modelcontextprotocol.io/docs/concepts/transports). 24 | 25 | In addition to MCP's [built-in](https://modelcontextprotocol.io/docs/concepts/transports#built-in-transport-types) transports, we also offer a `StreamTransport` to connect to clients with servers directly in-memory or over your own stream-based transport: 26 | 27 | ```ts 28 | import { Client } from '@modelcontextprotocol/sdk/client/index.js'; 29 | import { StreamTransport } from '@supabase/mcp-utils'; 30 | import { PostgrestMcpServer } from '@supabase/mcp-server-postgrest'; 31 | 32 | // Create a stream transport for both client and server 33 | const clientTransport = new StreamTransport(); 34 | const serverTransport = new StreamTransport(); 35 | 36 | // Connect the streams together 37 | clientTransport.readable.pipeTo(serverTransport.writable); 38 | serverTransport.readable.pipeTo(clientTransport.writable); 39 | 40 | const client = new Client( 41 | { 42 | name: 'MyClient', 43 | version: '0.1.0', 44 | }, 45 | { 46 | capabilities: {}, 47 | } 48 | ); 49 | 50 | const server = new PostgrestMcpServer({ 51 | apiUrl: API_URL, 52 | schema: 'public', 53 | }); 54 | 55 | // Connect the client and server to their respective transports 56 | await server.connect(serverTransport); 57 | await client.connect(clientTransport); 58 | ``` 59 | 60 | A `StreamTransport` implements a standard duplex stream interface via [`ReadableStream`](https://developer.mozilla.org/docs/Web/API/ReadableStream) and [`WritableStream`](https://developer.mozilla.org/docs/Web/API/WritableStream): 61 | 62 | ```ts 63 | interface StreamTransport { 64 | readable: ReadableStream; 65 | writable: WritableStream; 66 | } 67 | ``` 68 | 69 | You can use `pipeTo` or `pipeThrough` to connect or transform streams. For more information, see the [Web Streams API](https://developer.mozilla.org/docs/Web/API/Streams_API). 70 | 71 | If your using Node.js streams, you can use their [`.toWeb()`](https://nodejs.org/api/stream.html#streamduplextowebstreamduplex) and [`.fromWeb()`](https://nodejs.org/api/stream.html#streamduplexfromwebpair-options) methods to convert to and from web standard streams. 72 | 73 | The full interface for `StreamTransport` is as follows: 74 | 75 | ```ts 76 | import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; 77 | import { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; 78 | 79 | interface DuplexStream { 80 | readable: ReadableStream; 81 | writable: WritableStream; 82 | } 83 | 84 | declare class StreamTransport 85 | implements Transport, DuplexStream 86 | { 87 | ready: Promise; 88 | readable: ReadableStream; 89 | writable: WritableStream; 90 | onclose?: () => void; 91 | onerror?: (error: Error) => void; 92 | onmessage?: (message: JSONRPCMessage) => void; 93 | 94 | constructor(); 95 | start(): Promise; 96 | send(message: JSONRPCMessage): Promise; 97 | close(): Promise; 98 | } 99 | ``` 100 | -------------------------------------------------------------------------------- /packages/mcp-utils/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@supabase/mcp-utils", 3 | "version": "0.2.1", 4 | "description": "MCP utilities", 5 | "license": "Apache-2.0", 6 | "type": "module", 7 | "main": "dist/index.cjs", 8 | "types": "dist/index.d.ts", 9 | "sideEffects": false, 10 | "scripts": { 11 | "build": "tsup --clean", 12 | "test": "vitest", 13 | "test:coverage": "vitest --coverage", 14 | "prepublishOnly": "npm run build" 15 | }, 16 | "files": ["dist/**/*"], 17 | "exports": { 18 | ".": { 19 | "import": "./dist/index.js", 20 | "types": "./dist/index.d.ts", 21 | "default": "./dist/index.cjs" 22 | } 23 | }, 24 | "dependencies": { 25 | "@modelcontextprotocol/sdk": "^1.11.0", 26 | "zod": "^3.24.1", 27 | "zod-to-json-schema": "^3.24.1" 28 | }, 29 | "devDependencies": { 30 | "@total-typescript/tsconfig": "^1.0.4", 31 | "@types/node": "^22.8.6", 32 | "prettier": "^3.3.3", 33 | "tsup": "^8.3.5", 34 | "typescript": "^5.6.3", 35 | "vitest": "^2.1.9" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /packages/mcp-utils/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './server.js'; 2 | export * from './stream-transport.js'; 3 | export * from './types.js'; 4 | -------------------------------------------------------------------------------- /packages/mcp-utils/src/server.test.ts: -------------------------------------------------------------------------------- 1 | import { Client } from '@modelcontextprotocol/sdk/client/index.js'; 2 | import type { Server } from '@modelcontextprotocol/sdk/server/index.js'; 3 | import { 4 | CallToolResultSchema, 5 | type CallToolRequest, 6 | } from '@modelcontextprotocol/sdk/types.js'; 7 | import { describe, expect, test } from 'vitest'; 8 | import { z } from 'zod'; 9 | import { 10 | createMcpServer, 11 | resource, 12 | resources, 13 | resourceTemplate, 14 | tool, 15 | } from './server.js'; 16 | import { StreamTransport } from './stream-transport.js'; 17 | 18 | export const MCP_CLIENT_NAME = 'test-client'; 19 | export const MCP_CLIENT_VERSION = '0.1.0'; 20 | 21 | type SetupOptions = { 22 | server: Server; 23 | }; 24 | 25 | /** 26 | * Sets up an MCP client and server for testing. 27 | */ 28 | async function setup(options: SetupOptions) { 29 | const { server } = options; 30 | const clientTransport = new StreamTransport(); 31 | const serverTransport = new StreamTransport(); 32 | 33 | clientTransport.readable.pipeTo(serverTransport.writable); 34 | serverTransport.readable.pipeTo(clientTransport.writable); 35 | 36 | const client = new Client( 37 | { 38 | name: MCP_CLIENT_NAME, 39 | version: MCP_CLIENT_VERSION, 40 | }, 41 | { 42 | capabilities: {}, 43 | } 44 | ); 45 | 46 | await server.connect(serverTransport); 47 | await client.connect(clientTransport); 48 | 49 | /** 50 | * Calls a tool with the given parameters. 51 | * 52 | * Wrapper around the `client.callTool` method to handle the response and errors. 53 | */ 54 | async function callTool(params: CallToolRequest['params']) { 55 | const output = await client.callTool(params); 56 | const { content } = CallToolResultSchema.parse(output); 57 | const [textContent] = content; 58 | 59 | if (!textContent) { 60 | return undefined; 61 | } 62 | 63 | if (textContent.type !== 'text') { 64 | throw new Error('tool result content is not text'); 65 | } 66 | 67 | if (textContent.text === '') { 68 | throw new Error('tool result content is empty'); 69 | } 70 | 71 | const result = JSON.parse(textContent.text); 72 | 73 | if (output.isError) { 74 | throw new Error(result.error.message); 75 | } 76 | 77 | return result; 78 | } 79 | 80 | return { client, clientTransport, callTool, server, serverTransport }; 81 | } 82 | 83 | describe('tools', () => { 84 | test('parameter set to default value when omitted by caller', async () => { 85 | const server = createMcpServer({ 86 | name: 'test-server', 87 | version: '0.0.0', 88 | tools: { 89 | search: tool({ 90 | description: 'Search text', 91 | parameters: z.object({ 92 | query: z.string(), 93 | caseSensitive: z.boolean().default(false), 94 | }), 95 | execute: async (args) => { 96 | return args; 97 | }, 98 | }), 99 | }, 100 | }); 101 | 102 | const { callTool } = await setup({ server }); 103 | 104 | // Call the tool without the optional parameter 105 | const result = await callTool({ 106 | name: 'search', 107 | arguments: { 108 | query: 'hello', 109 | }, 110 | }); 111 | 112 | expect(result).toEqual({ 113 | query: 'hello', 114 | caseSensitive: false, 115 | }); 116 | }); 117 | }); 118 | 119 | describe('resources helper', () => { 120 | test('should add scheme to resource URIs', () => { 121 | const output = resources('my-scheme', [ 122 | resource('/schemas', { 123 | name: 'schemas', 124 | description: 'Postgres schemas', 125 | read: async () => [], 126 | }), 127 | resourceTemplate('/schemas/{schema}', { 128 | name: 'schema', 129 | description: 'Postgres schema', 130 | read: async () => [], 131 | }), 132 | ]); 133 | 134 | const outputUris = output.map((resource) => 135 | 'uri' in resource ? resource.uri : resource.uriTemplate 136 | ); 137 | 138 | expect(outputUris).toEqual([ 139 | 'my-scheme:///schemas', 140 | 'my-scheme:///schemas/{schema}', 141 | ]); 142 | }); 143 | 144 | test('should not overwrite existing scheme in resource URIs', () => { 145 | const output = resources('my-scheme', [ 146 | resource('/schemas', { 147 | name: 'schemas', 148 | description: 'Postgres schemas', 149 | read: async () => [], 150 | }), 151 | resourceTemplate('/schemas/{schema}', { 152 | name: 'schema', 153 | description: 'Postgres schema', 154 | read: async () => [], 155 | }), 156 | ]); 157 | 158 | const outputUris = output.map((resource) => 159 | 'uri' in resource ? resource.uri : resource.uriTemplate 160 | ); 161 | 162 | expect(outputUris).toEqual([ 163 | 'my-scheme:///schemas', 164 | 'my-scheme:///schemas/{schema}', 165 | ]); 166 | }); 167 | }); 168 | -------------------------------------------------------------------------------- /packages/mcp-utils/src/server.ts: -------------------------------------------------------------------------------- 1 | import { Server } from '@modelcontextprotocol/sdk/server/index.js'; 2 | import { 3 | CallToolRequestSchema, 4 | ListResourcesRequestSchema, 5 | ListResourceTemplatesRequestSchema, 6 | ListToolsRequestSchema, 7 | ReadResourceRequestSchema, 8 | type ClientCapabilities, 9 | type Implementation, 10 | type ListResourcesResult, 11 | type ListResourceTemplatesResult, 12 | type ReadResourceResult, 13 | type ServerCapabilities, 14 | } from '@modelcontextprotocol/sdk/types.js'; 15 | import type { z } from 'zod'; 16 | import zodToJsonSchema from 'zod-to-json-schema'; 17 | import type { 18 | ExpandRecursively, 19 | ExtractNotification, 20 | ExtractParams, 21 | ExtractRequest, 22 | ExtractResult, 23 | } from './types.js'; 24 | import { assertValidUri, compareUris, matchUriTemplate } from './util.js'; 25 | 26 | export type Scheme = string; 27 | 28 | export type Resource = { 29 | uri: Uri; 30 | name: string; 31 | description?: string; 32 | mimeType?: string; 33 | read(uri: `${Scheme}://${Uri}`): Promise; 34 | }; 35 | 36 | export type ResourceTemplate = { 37 | uriTemplate: Uri; 38 | name: string; 39 | description?: string; 40 | mimeType?: string; 41 | read( 42 | uri: `${Scheme}://${Uri}`, 43 | params: { 44 | [Param in ExtractParams]: string; 45 | } 46 | ): Promise; 47 | }; 48 | 49 | export type Tool< 50 | Params extends z.ZodObject = z.ZodObject, 51 | Result = unknown, 52 | > = { 53 | description: string; 54 | parameters: Params; 55 | execute(params: z.infer): Promise; 56 | }; 57 | 58 | /** 59 | * Helper function to define an MCP resource while preserving type information. 60 | */ 61 | export function resource( 62 | uri: Uri, 63 | resource: Omit, 'uri'> 64 | ): Resource { 65 | return { 66 | uri, 67 | ...resource, 68 | }; 69 | } 70 | 71 | /** 72 | * Helper function to define an MCP resource with a URI template while preserving type information. 73 | */ 74 | export function resourceTemplate( 75 | uriTemplate: Uri, 76 | resource: Omit, 'uriTemplate'> 77 | ): ResourceTemplate { 78 | return { 79 | uriTemplate, 80 | ...resource, 81 | }; 82 | } 83 | 84 | /** 85 | * Helper function to define a JSON resource while preserving type information. 86 | */ 87 | export function jsonResource( 88 | uri: Uri, 89 | resource: Omit, 'uri' | 'mimeType'> 90 | ): Resource { 91 | return { 92 | uri, 93 | mimeType: 'application/json' as const, 94 | ...resource, 95 | }; 96 | } 97 | 98 | /** 99 | * Helper function to define a JSON resource with a URI template while preserving type information. 100 | */ 101 | export function jsonResourceTemplate( 102 | uriTemplate: Uri, 103 | resource: Omit, 'uriTemplate' | 'mimeType'> 104 | ): ResourceTemplate { 105 | return { 106 | uriTemplate, 107 | mimeType: 'application/json' as const, 108 | ...resource, 109 | }; 110 | } 111 | 112 | /** 113 | * Helper function to define a list of resources that share a common URI scheme. 114 | */ 115 | export function resources( 116 | scheme: Scheme, 117 | resources: (Resource | ResourceTemplate)[] 118 | ): ( 119 | | Resource<`${Scheme}://${string}`> 120 | | ResourceTemplate<`${Scheme}://${string}`> 121 | )[] { 122 | return resources.map((resource) => { 123 | if ('uri' in resource) { 124 | const url = new URL(resource.uri, `${scheme}://`); 125 | const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`; 126 | 127 | return { 128 | ...resource, 129 | uri, 130 | }; 131 | } 132 | 133 | const url = new URL(resource.uriTemplate, `${scheme}://`); 134 | const uriTemplate = decodeURI( 135 | url.href 136 | ) as `${Scheme}://${typeof resource.uriTemplate}`; 137 | 138 | return { 139 | ...resource, 140 | uriTemplate, 141 | }; 142 | }); 143 | } 144 | 145 | /** 146 | * Helper function to create a JSON resource response. 147 | */ 148 | export function jsonResourceResponse( 149 | uri: Uri, 150 | response: Response 151 | ) { 152 | return { 153 | uri, 154 | mimeType: 'application/json', 155 | text: JSON.stringify(response), 156 | }; 157 | } 158 | 159 | /** 160 | * Helper function to define an MCP tool while preserving type information. 161 | */ 162 | export function tool, Result>( 163 | tool: Tool 164 | ) { 165 | return tool; 166 | } 167 | 168 | export type InitData = { 169 | clientInfo: Implementation; 170 | clientCapabilities: ClientCapabilities; 171 | }; 172 | 173 | export type InitCallback = (initData: InitData) => void | Promise; 174 | export type PropCallback = () => T | Promise; 175 | export type Prop = T | PropCallback; 176 | 177 | export type McpServerOptions = { 178 | /** 179 | * The name of the MCP server. This will be sent to the client as part of 180 | * the initialization process. 181 | */ 182 | name: string; 183 | 184 | /** 185 | * The version of the MCP server. This will be sent to the client as part of 186 | * the initialization process. 187 | */ 188 | version: string; 189 | 190 | /** 191 | * Callback for when initialization has fully completed with the client. 192 | */ 193 | onInitialize?: InitCallback; 194 | 195 | /** 196 | * Resources to be served by the server. These can be defined as a static 197 | * object or as a function that dynamically returns the object synchronously 198 | * or asynchronously. 199 | * 200 | * If defined as a function, the function will be called whenever the client 201 | * asks for the list of resources or reads a resource. This allows for dynamic 202 | * resources that can change after the server has started. 203 | */ 204 | resources?: Prop< 205 | (Resource | ResourceTemplate)[] 206 | >; 207 | 208 | /** 209 | * Tools to be served by the server. These can be defined as a static object 210 | * or as a function that dynamically returns the object synchronously or 211 | * asynchronously. 212 | * 213 | * If defined as a function, the function will be called whenever the client 214 | * asks for the list of tools or invokes a tool. This allows for dynamic tools 215 | * that can change after the server has started. 216 | */ 217 | tools?: Prop>; 218 | }; 219 | 220 | /** 221 | * Creates an MCP server with the given options. 222 | * 223 | * Simplifies the process of creating an MCP server by providing a high-level 224 | * API for defining resources and tools. 225 | */ 226 | export function createMcpServer(options: McpServerOptions) { 227 | const capabilities: ServerCapabilities = {}; 228 | 229 | if (options.resources) { 230 | capabilities.resources = {}; 231 | } 232 | 233 | if (options.tools) { 234 | capabilities.tools = {}; 235 | } 236 | 237 | const server = new Server( 238 | { 239 | name: options.name, 240 | version: options.version, 241 | }, 242 | { 243 | capabilities, 244 | } 245 | ); 246 | 247 | async function getResources() { 248 | if (!options.resources) { 249 | throw new Error('resources not available'); 250 | } 251 | 252 | return typeof options.resources === 'function' 253 | ? await options.resources() 254 | : options.resources; 255 | } 256 | 257 | async function getTools() { 258 | if (!options.tools) { 259 | throw new Error('tools not available'); 260 | } 261 | 262 | return typeof options.tools === 'function' 263 | ? await options.tools() 264 | : options.tools; 265 | } 266 | 267 | server.oninitialized = async () => { 268 | const clientInfo = server.getClientVersion(); 269 | const clientCapabilities = server.getClientCapabilities(); 270 | 271 | if (!clientInfo) { 272 | throw new Error('client info not available after initialization'); 273 | } 274 | 275 | if (!clientCapabilities) { 276 | throw new Error('client capabilities not available after initialization'); 277 | } 278 | 279 | const initData: InitData = { 280 | clientInfo, 281 | clientCapabilities, 282 | }; 283 | 284 | await options.onInitialize?.(initData); 285 | }; 286 | 287 | if (options.resources) { 288 | server.setRequestHandler( 289 | ListResourcesRequestSchema, 290 | async (): Promise => { 291 | const allResources = await getResources(); 292 | return { 293 | resources: allResources 294 | .filter((resource) => 'uri' in resource) 295 | .map(({ uri, name, description, mimeType }) => { 296 | return { 297 | uri, 298 | name, 299 | description, 300 | mimeType, 301 | }; 302 | }), 303 | }; 304 | } 305 | ); 306 | 307 | server.setRequestHandler( 308 | ListResourceTemplatesRequestSchema, 309 | async (): Promise => { 310 | const allResources = await getResources(); 311 | return { 312 | resourceTemplates: allResources 313 | .filter((resource) => 'uriTemplate' in resource) 314 | .map(({ uriTemplate, name, description, mimeType }) => { 315 | return { 316 | uriTemplate, 317 | name, 318 | description, 319 | mimeType, 320 | }; 321 | }), 322 | }; 323 | } 324 | ); 325 | 326 | server.setRequestHandler( 327 | ReadResourceRequestSchema, 328 | async (request): Promise => { 329 | try { 330 | const allResources = await getResources(); 331 | const { uri } = request.params; 332 | 333 | const resources = allResources.filter( 334 | (resource) => 'uri' in resource 335 | ); 336 | const resource = resources.find((resource) => 337 | compareUris(resource.uri, uri) 338 | ); 339 | 340 | if (resource) { 341 | const result = await resource.read(uri as `${string}://${string}`); 342 | 343 | const contents = Array.isArray(result) ? result : [result]; 344 | 345 | return { 346 | contents, 347 | }; 348 | } 349 | 350 | const resourceTemplates = allResources.filter( 351 | (resource) => 'uriTemplate' in resource 352 | ); 353 | const resourceTemplateUris = resourceTemplates.map( 354 | ({ uriTemplate }) => assertValidUri(uriTemplate) 355 | ); 356 | 357 | const templateMatch = matchUriTemplate(uri, resourceTemplateUris); 358 | 359 | if (!templateMatch) { 360 | throw new Error('resource not found'); 361 | } 362 | 363 | const resourceTemplate = resourceTemplates.find( 364 | (r) => r.uriTemplate === templateMatch.uri 365 | ); 366 | 367 | if (!resourceTemplate) { 368 | throw new Error('resource not found'); 369 | } 370 | 371 | const result = await resourceTemplate.read( 372 | uri as `${string}://${string}`, 373 | templateMatch.params 374 | ); 375 | 376 | const contents = Array.isArray(result) ? result : [result]; 377 | 378 | return { 379 | contents, 380 | }; 381 | } catch (error) { 382 | return { 383 | isError: true, 384 | content: [ 385 | { 386 | type: 'text', 387 | text: JSON.stringify({ error: enumerateError(error) }), 388 | }, 389 | ], 390 | } as any; 391 | } 392 | } 393 | ); 394 | } 395 | 396 | if (options.tools) { 397 | server.setRequestHandler(ListToolsRequestSchema, async () => { 398 | const tools = await getTools(); 399 | return { 400 | tools: Object.entries(tools).map( 401 | ([name, { description, parameters }]) => { 402 | return { 403 | name, 404 | description, 405 | inputSchema: zodToJsonSchema(parameters), 406 | }; 407 | } 408 | ), 409 | }; 410 | }); 411 | 412 | server.setRequestHandler(CallToolRequestSchema, async (request) => { 413 | try { 414 | const tools = await getTools(); 415 | const toolName = request.params.name; 416 | 417 | if (!(toolName in tools)) { 418 | throw new Error('tool not found'); 419 | } 420 | 421 | const tool = tools[toolName]; 422 | 423 | if (!tool) { 424 | throw new Error('tool not found'); 425 | } 426 | 427 | const args = tool.parameters 428 | .strict() 429 | .parse(request.params.arguments ?? {}); 430 | 431 | const result = await tool.execute(args); 432 | const content = result 433 | ? [{ type: 'text', text: JSON.stringify(result) }] 434 | : []; 435 | 436 | return { 437 | content, 438 | }; 439 | } catch (error) { 440 | return { 441 | isError: true, 442 | content: [ 443 | { 444 | type: 'text', 445 | text: JSON.stringify({ error: enumerateError(error) }), 446 | }, 447 | ], 448 | }; 449 | } 450 | }); 451 | } 452 | 453 | // Expand types recursively for better intellisense 454 | type Request = ExpandRecursively>; 455 | type Notification = ExpandRecursively>; 456 | type Result = ExpandRecursively>; 457 | 458 | return server as Server; 459 | } 460 | 461 | function enumerateError(error: unknown) { 462 | if (!error) { 463 | return error; 464 | } 465 | 466 | if (typeof error !== 'object') { 467 | return error; 468 | } 469 | 470 | const newError: Record = {}; 471 | 472 | const errorProps = ['name', 'message'] as const; 473 | 474 | for (const prop of errorProps) { 475 | if (prop in error) { 476 | newError[prop] = (error as Record)[prop]; 477 | } 478 | } 479 | 480 | return newError; 481 | } 482 | -------------------------------------------------------------------------------- /packages/mcp-utils/src/stream-transport.ts: -------------------------------------------------------------------------------- 1 | import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; 2 | import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; 3 | import type { DuplexStream } from './types.js'; 4 | 5 | /** 6 | * An MCP transport built on top of a duplex stream. 7 | * It uses a `ReadableStream` to receive messages and a `WritableStream` to send messages. 8 | * 9 | * Useful if you wish to pipe messages over your own stream-based transport or directly between two streams. 10 | */ 11 | export class StreamTransport 12 | implements Transport, DuplexStream 13 | { 14 | #readableStreamController?: ReadableStreamDefaultController; 15 | #writeableStreamController?: WritableStreamDefaultController; 16 | 17 | ready: Promise; 18 | 19 | readable: ReadableStream; 20 | writable: WritableStream; 21 | 22 | onclose?: () => void; 23 | onerror?: (error: Error) => void; 24 | onmessage?: (message: JSONRPCMessage) => void; 25 | 26 | constructor() { 27 | let resolveReadReady: () => void; 28 | let resolveWriteReady: () => void; 29 | 30 | const readReady = new Promise((resolve) => { 31 | resolveReadReady = resolve; 32 | }); 33 | 34 | const writeReady = new Promise((resolve) => { 35 | resolveWriteReady = resolve; 36 | }); 37 | 38 | this.ready = Promise.all([readReady, writeReady]).then(() => {}); 39 | 40 | this.readable = new ReadableStream({ 41 | start: (controller) => { 42 | this.#readableStreamController = controller; 43 | resolveReadReady(); 44 | }, 45 | }); 46 | 47 | this.writable = new WritableStream({ 48 | start: (controller) => { 49 | this.#writeableStreamController = controller; 50 | resolveWriteReady(); 51 | }, 52 | write: (message) => { 53 | this.onmessage?.(message); 54 | }, 55 | }); 56 | } 57 | 58 | async start() { 59 | await this.ready; 60 | } 61 | 62 | async send(message: JSONRPCMessage) { 63 | if (!this.#readableStreamController) { 64 | throw new Error('readable stream not initialized'); 65 | } 66 | this.#readableStreamController.enqueue(message); 67 | } 68 | 69 | async close() { 70 | this.#readableStreamController?.error(new Error('connection closed')); 71 | this.#writeableStreamController?.error(new Error('connection closed')); 72 | this.onclose?.(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /packages/mcp-utils/src/types.ts: -------------------------------------------------------------------------------- 1 | import type { Server } from '@modelcontextprotocol/sdk/server/index.js'; 2 | 3 | /** 4 | * A web stream that can be both read from and written to. 5 | */ 6 | export interface DuplexStream { 7 | readable: ReadableStream; 8 | writable: WritableStream; 9 | } 10 | 11 | /** 12 | * Expands a type into its properties recursively. 13 | * 14 | * Useful for providing better intellisense in IDEs. 15 | */ 16 | export type ExpandRecursively = T extends (...args: infer A) => infer R 17 | ? (...args: ExpandRecursively) => ExpandRecursively 18 | : T extends object 19 | ? T extends infer O 20 | ? { [K in keyof O]: ExpandRecursively } 21 | : never 22 | : T; 23 | 24 | /** 25 | * Extracts parameter names from a string path. 26 | * 27 | * @example 28 | * type Path = '/schemas/{schema}/tables/{table}'; 29 | * type Params = ExtractParams; // 'schema' | 'table' 30 | */ 31 | export type ExtractParams = 32 | Path extends `${string}{${infer P}}${infer Rest}` 33 | ? P | ExtractParams 34 | : never; 35 | 36 | /** 37 | * Extracts the request type from an MCP server. 38 | */ 39 | export type ExtractRequest = S extends Server ? R : never; 40 | 41 | /** 42 | * Extracts the notification type from an MCP server. 43 | */ 44 | export type ExtractNotification = S extends Server 45 | ? N 46 | : never; 47 | 48 | /** 49 | * Extracts the result type from an MCP server. 50 | */ 51 | export type ExtractResult = S extends Server ? R : never; 52 | -------------------------------------------------------------------------------- /packages/mcp-utils/src/util.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, test } from 'vitest'; 2 | import { matchUriTemplate } from './util.js'; 3 | 4 | describe('matchUriTemplate', () => { 5 | test('should match a URI template and extract parameters', () => { 6 | const uri = 'http://example.com/users/123'; 7 | const templates = ['http://example.com/users/{userId}']; 8 | 9 | const result = matchUriTemplate(uri, templates); 10 | 11 | expect(result).toEqual({ 12 | uri: 'http://example.com/users/{userId}', 13 | params: { userId: '123' }, 14 | }); 15 | }); 16 | 17 | test('should return undefined if no template matches', () => { 18 | const uri = 'http://example.com/users/123'; 19 | const templates = ['http://example.com/posts/{postId}']; 20 | 21 | const result = matchUriTemplate(uri, templates); 22 | 23 | expect(result).toBeUndefined(); 24 | }); 25 | 26 | test('should match the correct template when multiple templates are provided', () => { 27 | const uri = 'http://example.com/posts/456/comments/789'; 28 | const templates = [ 29 | 'http://example.com/users/{userId}', 30 | 'http://example.com/posts/{postId}/comments/{commentId}', 31 | ]; 32 | 33 | const result = matchUriTemplate(uri, templates); 34 | 35 | expect(result).toEqual({ 36 | uri: 'http://example.com/posts/{postId}/comments/{commentId}', 37 | params: { postId: '456', commentId: '789' }, 38 | }); 39 | }); 40 | 41 | test('should handle templates with multiple parameters', () => { 42 | const uri = 'http://example.com/users/123/orders/456'; 43 | const templates = ['http://example.com/users/{userId}/orders/{orderId}']; 44 | 45 | const result = matchUriTemplate(uri, templates); 46 | 47 | expect(result).toEqual({ 48 | uri: 'http://example.com/users/{userId}/orders/{orderId}', 49 | params: { userId: '123', orderId: '456' }, 50 | }); 51 | }); 52 | 53 | test('should return undefined if the URI segments do not match the template segments', () => { 54 | const uri = 'http://example.com/users/123/orders'; 55 | const templates = ['http://example.com/users/{userId}/orders/{orderId}']; 56 | 57 | const result = matchUriTemplate(uri, templates); 58 | 59 | expect(result).toBeUndefined(); 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /packages/mcp-utils/src/util.ts: -------------------------------------------------------------------------------- 1 | import type { ExtractParams } from './types.js'; 2 | 3 | /** 4 | * Asserts that a URI is valid. 5 | */ 6 | export function assertValidUri(uri: string) { 7 | try { 8 | new URL(uri); 9 | return uri; 10 | } catch { 11 | throw new Error(`invalid uri: ${uri}`); 12 | } 13 | } 14 | 15 | /** 16 | * Compares two URIs. 17 | */ 18 | export function compareUris(uriA: string, uriB: string): boolean { 19 | const urlA = new URL(uriA); 20 | const urlB = new URL(uriB); 21 | 22 | return urlA.href === urlB.href; 23 | } 24 | 25 | /** 26 | * Matches a URI to a RFC 6570 URI Template (resourceUris) and extracts 27 | * the parameters. 28 | * 29 | * Currently only supports simple string parameters. 30 | */ 31 | export function matchUriTemplate( 32 | uri: string, 33 | uriTemplates: Templates 34 | ): 35 | | { 36 | uri: Templates[number]; 37 | params: { [Param in ExtractParams]: string }; 38 | } 39 | | undefined { 40 | const url = new URL(uri); 41 | const segments = url.pathname.split('/').slice(1); 42 | 43 | for (const resourceUri of uriTemplates) { 44 | const resourceUrl = new URL(resourceUri); 45 | const resourceSegments = decodeURIComponent(resourceUrl.pathname) 46 | .split('/') 47 | .slice(1); 48 | 49 | if (segments.length !== resourceSegments.length) { 50 | continue; 51 | } 52 | 53 | const params: Record = {}; 54 | let isMatch = true; 55 | 56 | for (let i = 0; i < segments.length; i++) { 57 | const resourceSegment = resourceSegments[i]; 58 | const segment = segments[i]; 59 | 60 | if (!resourceSegment || !segment) { 61 | break; 62 | } 63 | 64 | if (resourceSegment.startsWith('{') && resourceSegment.endsWith('}')) { 65 | const paramKey = resourceSegment.slice(1, -1); 66 | 67 | if (!paramKey) { 68 | break; 69 | } 70 | 71 | params[paramKey] = segment; 72 | } else if (segments[i] !== resourceSegments[i]) { 73 | isMatch = false; 74 | break; 75 | } 76 | } 77 | 78 | if (isMatch) { 79 | return { 80 | uri: resourceUri, 81 | params: params as { 82 | [Param in ExtractParams]: string; 83 | }, 84 | }; 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /packages/mcp-utils/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@total-typescript/tsconfig/bundler/no-dom/library", 3 | "include": ["src/**/*.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /packages/mcp-utils/tsup.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'tsup'; 2 | 3 | export default defineConfig([ 4 | { 5 | entry: ['src/index.ts'], 6 | format: ['cjs', 'esm'], 7 | outDir: 'dist', 8 | sourcemap: true, 9 | dts: true, 10 | minify: true, 11 | splitting: true, 12 | }, 13 | ]); 14 | -------------------------------------------------------------------------------- /supabase/config.toml: -------------------------------------------------------------------------------- 1 | # For detailed configuration reference documentation, visit: 2 | # https://supabase.com/docs/guides/local-development/cli/config 3 | # A string used to distinguish different Supabase projects on the same host. Defaults to the 4 | # working directory name when running `supabase init`. 5 | project_id = "mcp-server-supabase" 6 | 7 | [api] 8 | enabled = true 9 | # Port to use for the API URL. 10 | port = 54321 11 | # Schemas to expose in your API. Tables, views and stored procedures in this schema will get API 12 | # endpoints. `public` and `graphql_public` schemas are included by default. 13 | schemas = ["public", "graphql_public"] 14 | # Extra schemas to add to the search_path of every request. 15 | extra_search_path = ["public", "extensions"] 16 | # The maximum number of rows returns from a view, table, or stored procedure. Limits payload size 17 | # for accidental or malicious requests. 18 | max_rows = 1000 19 | 20 | [api.tls] 21 | # Enable HTTPS endpoints locally using a self-signed certificate. 22 | enabled = false 23 | 24 | [db] 25 | # Port to use for the local database URL. 26 | port = 54322 27 | # Port used by db diff command to initialize the shadow database. 28 | shadow_port = 54320 29 | # The database major version to use. This has to be the same as your remote database's. Run `SHOW 30 | # server_version;` on the remote database to check. 31 | major_version = 15 32 | 33 | [db.pooler] 34 | enabled = false 35 | # Port to use for the local connection pooler. 36 | port = 54329 37 | # Specifies when a server connection can be reused by other clients. 38 | # Configure one of the supported pooler modes: `transaction`, `session`. 39 | pool_mode = "transaction" 40 | # How many server connections to allow per user/database pair. 41 | default_pool_size = 20 42 | # Maximum number of client connections allowed. 43 | max_client_conn = 100 44 | 45 | [db.seed] 46 | # If enabled, seeds the database after migrations during a db reset. 47 | enabled = true 48 | # Specifies an ordered list of seed files to load during db reset. 49 | # Supports glob patterns relative to supabase directory: './seeds/*.sql' 50 | sql_paths = ['./seed.sql'] 51 | 52 | [realtime] 53 | enabled = true 54 | # Bind realtime via either IPv4 or IPv6. (default: IPv4) 55 | # ip_version = "IPv6" 56 | # The maximum length in bytes of HTTP request headers. (default: 4096) 57 | # max_header_length = 4096 58 | 59 | [studio] 60 | enabled = true 61 | # Port to use for Supabase Studio. 62 | port = 54323 63 | # External URL of the API server that frontend connects to. 64 | api_url = "http://127.0.0.1" 65 | # OpenAI API Key to use for Supabase AI in the Supabase Studio. 66 | openai_api_key = "env(OPENAI_API_KEY)" 67 | 68 | # Email testing server. Emails sent with the local dev setup are not actually sent - rather, they 69 | # are monitored, and you can view the emails that would have been sent from the web interface. 70 | [inbucket] 71 | enabled = true 72 | # Port to use for the email testing server web interface. 73 | port = 54324 74 | # Uncomment to expose additional ports for testing user applications that send emails. 75 | # smtp_port = 54325 76 | # pop3_port = 54326 77 | # admin_email = "admin@email.com" 78 | # sender_name = "Admin" 79 | 80 | [storage] 81 | enabled = true 82 | # The maximum file size allowed (e.g. "5MB", "500KB"). 83 | file_size_limit = "50MiB" 84 | 85 | # Image transformation API is available to Supabase Pro plan. 86 | # [storage.image_transformation] 87 | # enabled = true 88 | 89 | # Uncomment to configure local storage buckets 90 | # [storage.buckets.images] 91 | # public = false 92 | # file_size_limit = "50MiB" 93 | # allowed_mime_types = ["image/png", "image/jpeg"] 94 | # objects_path = "./images" 95 | 96 | [auth] 97 | enabled = true 98 | # The base URL of your website. Used as an allow-list for redirects and for constructing URLs used 99 | # in emails. 100 | site_url = "http://127.0.0.1:3000" 101 | # A list of *exact* URLs that auth providers are permitted to redirect to post authentication. 102 | additional_redirect_urls = ["https://127.0.0.1:3000"] 103 | # How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week). 104 | jwt_expiry = 3600 105 | # If disabled, the refresh token will never expire. 106 | enable_refresh_token_rotation = true 107 | # Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. 108 | # Requires enable_refresh_token_rotation = true. 109 | refresh_token_reuse_interval = 10 110 | # Allow/disallow new user signups to your project. 111 | enable_signup = true 112 | # Allow/disallow anonymous sign-ins to your project. 113 | enable_anonymous_sign_ins = false 114 | # Allow/disallow testing manual linking of accounts 115 | enable_manual_linking = false 116 | # Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more. 117 | minimum_password_length = 6 118 | # Passwords that do not meet the following requirements will be rejected as weak. Supported values 119 | # are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols` 120 | password_requirements = "" 121 | 122 | [auth.email] 123 | # Allow/disallow new user signups via email to your project. 124 | enable_signup = true 125 | # If enabled, a user will be required to confirm any email change on both the old, and new email 126 | # addresses. If disabled, only the new email is required to confirm. 127 | double_confirm_changes = true 128 | # If enabled, users need to confirm their email address before signing in. 129 | enable_confirmations = false 130 | # If enabled, users will need to reauthenticate or have logged in recently to change their password. 131 | secure_password_change = false 132 | # Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email. 133 | max_frequency = "1s" 134 | # Number of characters used in the email OTP. 135 | otp_length = 6 136 | # Number of seconds before the email OTP expires (defaults to 1 hour). 137 | otp_expiry = 3600 138 | 139 | # Use a production-ready SMTP server 140 | # [auth.email.smtp] 141 | # enabled = true 142 | # host = "smtp.sendgrid.net" 143 | # port = 587 144 | # user = "apikey" 145 | # pass = "env(SENDGRID_API_KEY)" 146 | # admin_email = "admin@email.com" 147 | # sender_name = "Admin" 148 | 149 | # Uncomment to customize email template 150 | # [auth.email.template.invite] 151 | # subject = "You have been invited" 152 | # content_path = "./supabase/templates/invite.html" 153 | 154 | [auth.sms] 155 | # Allow/disallow new user signups via SMS to your project. 156 | enable_signup = false 157 | # If enabled, users need to confirm their phone number before signing in. 158 | enable_confirmations = false 159 | # Template for sending OTP to users 160 | template = "Your code is {{ .Code }}" 161 | # Controls the minimum amount of time that must pass before sending another sms otp. 162 | max_frequency = "5s" 163 | 164 | # Use pre-defined map of phone number to OTP for testing. 165 | # [auth.sms.test_otp] 166 | # 4152127777 = "123456" 167 | 168 | # Configure logged in session timeouts. 169 | # [auth.sessions] 170 | # Force log out after the specified duration. 171 | # timebox = "24h" 172 | # Force log out if the user has been inactive longer than the specified duration. 173 | # inactivity_timeout = "8h" 174 | 175 | # This hook runs before a token is issued and allows you to add additional claims based on the authentication method used. 176 | # [auth.hook.custom_access_token] 177 | # enabled = true 178 | # uri = "pg-functions:////" 179 | 180 | # Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`. 181 | [auth.sms.twilio] 182 | enabled = false 183 | account_sid = "" 184 | message_service_sid = "" 185 | # DO NOT commit your Twilio auth token to git. Use environment variable substitution instead: 186 | auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" 187 | 188 | # Multi-factor-authentication is available to Supabase Pro plan. 189 | [auth.mfa] 190 | # Control how many MFA factors can be enrolled at once per user. 191 | max_enrolled_factors = 10 192 | 193 | # Control MFA via App Authenticator (TOTP) 194 | [auth.mfa.totp] 195 | enroll_enabled = false 196 | verify_enabled = false 197 | 198 | # Configure MFA via Phone Messaging 199 | [auth.mfa.phone] 200 | enroll_enabled = false 201 | verify_enabled = false 202 | otp_length = 6 203 | template = "Your code is {{ .Code }}" 204 | max_frequency = "5s" 205 | 206 | # Configure MFA via WebAuthn 207 | # [auth.mfa.web_authn] 208 | # enroll_enabled = true 209 | # verify_enabled = true 210 | 211 | # Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`, 212 | # `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`, 213 | # `twitter`, `slack`, `spotify`, `workos`, `zoom`. 214 | [auth.external.apple] 215 | enabled = false 216 | client_id = "" 217 | # DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead: 218 | secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)" 219 | # Overrides the default auth redirectUrl. 220 | redirect_uri = "" 221 | # Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure, 222 | # or any other third-party OIDC providers. 223 | url = "" 224 | # If enabled, the nonce check will be skipped. Required for local sign in with Google auth. 225 | skip_nonce_check = false 226 | 227 | # Use Firebase Auth as a third-party provider alongside Supabase Auth. 228 | [auth.third_party.firebase] 229 | enabled = false 230 | # project_id = "my-firebase-project" 231 | 232 | # Use Auth0 as a third-party provider alongside Supabase Auth. 233 | [auth.third_party.auth0] 234 | enabled = false 235 | # tenant = "my-auth0-tenant" 236 | # tenant_region = "us" 237 | 238 | # Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth. 239 | [auth.third_party.aws_cognito] 240 | enabled = false 241 | # user_pool_id = "my-user-pool-id" 242 | # user_pool_region = "us-east-1" 243 | 244 | [edge_runtime] 245 | enabled = true 246 | # Configure one of the supported request policies: `oneshot`, `per_worker`. 247 | # Use `oneshot` for hot reload, or `per_worker` for load testing. 248 | policy = "oneshot" 249 | # Port to attach the Chrome inspector for debugging edge functions. 250 | inspector_port = 8083 251 | 252 | # Use these configurations to customize your Edge Function. 253 | # [functions.MY_FUNCTION_NAME] 254 | # enabled = true 255 | # verify_jwt = true 256 | # import_map = "./functions/MY_FUNCTION_NAME/deno.json" 257 | # Uncomment to specify a custom file path to the entrypoint. 258 | # Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx 259 | # entrypoint = "./functions/MY_FUNCTION_NAME/index.ts" 260 | 261 | [analytics] 262 | enabled = true 263 | port = 54327 264 | # Configure one of the supported backends: `postgres`, `bigquery`. 265 | backend = "postgres" 266 | 267 | # Experimental features may be deprecated any time 268 | [experimental] 269 | # Configures Postgres storage engine to use OrioleDB (S3) 270 | orioledb_version = "" 271 | # Configures S3 bucket URL, eg. .s3-.amazonaws.com 272 | s3_host = "env(S3_HOST)" 273 | # Configures S3 bucket region, eg. us-east-1 274 | s3_region = "env(S3_REGION)" 275 | # Configures AWS_ACCESS_KEY_ID for S3 bucket 276 | s3_access_key = "env(S3_ACCESS_KEY)" 277 | # Configures AWS_SECRET_ACCESS_KEY for S3 bucket 278 | s3_secret_key = "env(S3_SECRET_KEY)" 279 | -------------------------------------------------------------------------------- /supabase/migrations/20241220232417_todos.sql: -------------------------------------------------------------------------------- 1 | create table 2 | todos ( 3 | id bigint primary key generated always as identity, 4 | title text not null, 5 | description text, 6 | due_date date, 7 | is_completed boolean default false 8 | ); 9 | 10 | comment on table todos is 'Table to manage todo items with details such as title, description, due date, and completion status.'; -------------------------------------------------------------------------------- /supabase/migrations/20250109000000_add_todo_policies.sql: -------------------------------------------------------------------------------- 1 | -- Enable RLS 2 | alter table todos enable row level security; 3 | 4 | -- Add user_id column to track ownership 5 | alter table todos 6 | add column user_id uuid references auth.users (id) default auth.uid () not null; 7 | 8 | -- Create policies 9 | create policy "Users can view their own todos" on todos for 10 | select 11 | using ( 12 | ( 13 | select 14 | auth.uid () = user_id 15 | ) 16 | ); 17 | 18 | create policy "Users can create their own todos" on todos for insert 19 | with 20 | check ( 21 | ( 22 | select 23 | auth.uid () = user_id 24 | ) 25 | ); 26 | 27 | create policy "Users can update their own todos" on todos for 28 | update using ( 29 | ( 30 | select 31 | auth.uid () = user_id 32 | ) 33 | ) 34 | with 35 | check ( 36 | ( 37 | select 38 | auth.uid () = user_id 39 | ) 40 | ); 41 | 42 | create policy "Users can delete their own todos" on todos for delete using ( 43 | ( 44 | select 45 | auth.uid () = user_id 46 | ) 47 | ); -------------------------------------------------------------------------------- /supabase/seed.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/supabase-community/supabase-mcp/b54f86e53bf7eeeb90dce80e8efe4cacadab34a2/supabase/seed.sql --------------------------------------------------------------------------------