Repository navigation
feat(mcp)!: confirm destructive SQL via elicitation and rename costConfirmation option - #408
Conversation
…tion option Extract the duplicated requestState decode/tool/args/decline/cancel/drift block from create_project and create_branch into checkConfirmationState in tools/confirmation.ts (renamed from cost-confirmation.ts), validate the decoded state with zod safeParse, and rename the server option costConfirmation -> confirmation ahead of non-cost confirmations. BREAKING CHANGE: `createSupabaseMcpServer` option `costConfirmation` is now `confirmation`.
Port Studio's regex-based destructive SQL check (DROP, DELETE, TRUNCATE, ALTER TABLE ... DROP COLUMN incl. EXECUTE-string variants, and UPDATE without WHERE) with comment stripping into tools/destructive-sql.ts, along with the Studio test cases that pin its false-positive and false-negative contract. No new dependencies.
When the `confirmation` option enables them and the client declares form elicitation, execute_sql and apply_migration detect destructive SQL (DROP, DELETE, TRUNCATE, ALTER TABLE ... DROP COLUMN, UPDATE without WHERE, ported from Studio) and require an accepted action-only elicitation, bound by a signed requestState to the project and a hash of the query, before running. Read-only servers, capability-free clients and non-destructive SQL are unchanged.
Coverage Report for CI Build 35069396216Coverage increased (+0.2%) to 96.81%Details
Uncovered Changes
Coverage RegressionsNo coverage regressions found. Coverage Stats
💛 - Coveralls |
Brings in #411 (ctx-aware tools(), hidden get_cost/confirm_cost and confirm_cost_id omission for form-capable clients) and the 0.12.0 release. Conflicts resolved so #411's per-request tool shaping runs under the renamed `confirmation` option; #408's tests migrated from setupFormCapable to setupModern with explicit FORM_CAPABLE capabilities.
|
Where do you see controls for turning elicitations on/off fitting in to this? To me, destructive SQL confirmations get into territory where I could see elicitations getting in the way for users who want agents to auto approve safe actions. Wondering if we should be adding options to control elicitation behavior before / alongside this change. |
that's a good question We have two main options imo:
Open to suggestions of course - and more than happy to add on to either this PR or as a second, stacked PR. |
|
Query param sounds reasonable. At first I assumed this would just be a boolean flag, but you bring up a good point that we could make it more fine-grained so users can decide what level of safety they want. |
|
It could be a passthrough of the tools where confirmations are enabled e.g. The risk with an allowlist is if we add a new tool in the future that uses elicitations for approval, the user won't realize they opted out of its safety net. A deny-list would be safer, so they're only taking in risk in areas they've listed explicitly: |
Agreed 💯 , a per-tool deny-list is exactly what I was thinking. Since the package already exposes the per-tool mechanism, this doesn't need an MCP package change; the Platform just needs to parse the user's preference and derive the effective tool set. We'll pick that up on the Platform side shortly. |
Rodriguespn
left a comment
There was a problem hiding this comment.
Asking for changes as I identified some edge cases on the parsing that I think would need further discussion.
For example, a two-line SQL statement that starts with a comment (--) isn't sanitized correctly today:
SELECT '--';
DROP TABLE films;I tried this locally against the current regex and the table gets dropped with no confirmation prompt. The -- inside the string literal on line 1 is treated as a real comment and silently eats the rest of that line, including the ; that would otherwise separate it from the DROP.
Any reason why we're doing our own parsing instead of using the official Postgres parser libpg-query-node?
We're already using it on the backend to classify execute_sql queries: sql-classification.worker.ts.
Same scenario through the real parser:
import { parse } from '@libpg-query/parser'
const { stmts } = await parse("SELECT '--';\nDROP TABLE films;")
// stmts.length === 2
// stmts[1].stmt -> { DropStmt: { removeType: 'OBJECT_TABLE', objects: [...films] } }Two real statements come out and the DROP is fully visible, no regex needed, because the parser understands string literals natively.
I found a few other cases the current regex misses the same way:
UPDATEwithout aWHEREwhen a comment sits nearby (leading, inline, or trailing),ALTER TABLE t DROP colwithout the optionalCOLUMNkeyword,- destructive statements wrapped in
WITH ...orDO $$ ... $$.
All of these come for free with a real parser (checking the whereClause field, matching on the AlterTableCmd subtype instead of literal text, or just walking the statement list) instead of patching the regex edge case by edge case.
I've prepared some test cases that we can reuse here when I was working on the sql parsing.
Lmk what you think.
I've been hesitant to add another runtime dependency to the existing package. Happy to revisit this of course - what are your thoughts on adding this dependency? |
commit: |
Three optional
These are known regex coverage limits, not new regressions. Follow-up PRs introducing a SQL-to-AST parser are inbound to address these gaps. |
Rodriguespn
left a comment
There was a problem hiding this comment.
Approving to unlock this
🤖 I have created a release *beep* *boop* --- <details><summary>mcp-server-supabase: 0.13.0</summary> ## [0.13.0](mcp-server-supabase-v0.12.0...mcp-server-supabase-v0.13.0) (2026-09-17) ### ⚠ BREAKING CHANGES * **mcp:** confirm destructive SQL via elicitation and rename costConfirmation option ([#408](#408)) ### Features * add --http local HTTP entry to mcp-server-supabase ([#401](#401)) ([ff063b4](ff063b4)) * **management:** add v2 api client ([#419](#419)) ([02ca542](02ca542)) * **mcp:** confirm destructive SQL via elicitation and rename costConfirmation option ([#408](#408)) ([c9c4e3f](c9c4e3f)) * support skip_elicitations in the local HTTP server ([#434](#434)) ([9442e82](9442e82)) * URL-mode secret collection for create_edge_function_secret ([#412](#412)) ([fb88629](fb88629)) ### Bug Fixes * discourage host-filesystem access in raw-SQL tool descriptions ([#410](#410)) ([641ed1e](641ed1e)) </details> --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). Co-authored-by: supabase-releaser[bot] <223506987+supabase-releaser[bot]@users.noreply.github.com>
…565) ## What kind of change does this PR introduce? Bug fix ## What is the current behavior? Fixes #564 This is the follow-up named in the review of #524. `execute_sql` and `apply_migration` ask for confirmation before an `UPDATE` without `WHERE`, but not when the table is written `films*` or `ONLY (films)`. The update runs and changes every row. Postgres spells the target of an `UPDATE` four ways (`relation_expr` in `gram.y`): `t`, `t *`, `ONLY t` and `ONLY (t)`. `updateWithoutWhereRegex` matches only the first and the third, so the other two never reach the `WHERE` check. ## What is the new behavior? `updateWithoutWhereRegex` matches all four. Whitespace around `*` and the parentheses is optional, as it is in Postgres. | query | before | after | | ----- | ------ | ----- | | `update public.films* set id = 2` | runs | asks | | `update films * as f set id = 2` | runs | asks | | `update only (films) set id = 2` | runs | asks | | `update only(public.films)f set id = 2` | runs | asks | | `explain analyze update films* set id = 2` | runs | asks | | any of the above with `where id = 1` | runs | runs | `run_notebook` already asks before any cell that isn't a plain read, and its prompt now counts these statements as destructive. No change to tool names, descriptions, or input and output schemas. Not covered: the spellings under Additional context, which miss for other reasons. `UPDATE ONLY t * ...` isn't valid Postgres but now matches, so the server asks and Postgres then rejects the statement. #426 plans a parser for this check, and the regex stays on as its fallback (#532), so the fix still applies once the parser lands. ## How to Review 1. **UPDATE check** - `packages/mcp-server-supabase/src/tools/destructive-sql.ts` - `updateWithoutWhereRegex` is now built from named parts, like `directDropColumnRegex`. `updateIdentifier` and `updateTable` are the old sub-patterns, unchanged. `updateTarget` is new: it adds `\s*\*\s*` after the table and the `only\s*\(...\)` alternative. The whitespace before the alias and before `SET` now sits after the target and after the alias, since `*` and `)` need none. 2. **Tests** - `packages/mcp-server-supabase/src/tools/destructive-sql.test.ts` - Nine new rows in the `isUpdateWithoutWhere` "matches" table, two in its "with WHERE does not match" table, and one `isDestructiveSql` test with the two statements from the review of #524. **Review questions** - [ ] Is a pattern built from named parts fine, or would you rather have a one-line edit of the literal, as in #524? The built pattern is 252 characters long. - [ ] Is it fine that `UPDATE ONLY t * ...` asks before Postgres rejects it? - [ ] Do you want the spellings under Additional context as a follow-up, or as test cases for #426? ## Verification With only the test file applied on `main` (9092ab9), the 9 new "matches" rows and both `isDestructiveSql` cases fail with `expected false to be true`, and the other 145 tests pass. With the change: - `pnpm --filter @supabase/mcp-server-supabase test:unit --run`: 926 passed (34 files) - `pnpm --filter @supabase/mcp-server-supabase test:integration --run`: 7 passed - `pnpm build` (runs `tsc --noEmit` in each package), `pnpm format:check`, `biome ci .` and `pnpm test:packed-platform-consumer`: clean Through the tools, with `setupModern` and a form-capable client that declines, the mocked Management API, and PGlite holding a table and a child table: | query, through `execute_sql` and `apply_migration` | `main` | this branch | | ----- | ------ | ----------- | | `update public.films* set title = 'x'` | not asked, 4 of 4 rows changed | asked, none changed | | `update only (films) set title = 'x'` | not asked, 2 of 2 parent rows changed | asked, none changed | | either query with `where id = 1` | not asked, 1 row changed | not asked, 1 row changed | I also compared the old and the new classifier on every SQL string in the test file, on 1,874,880 combinations of statement parts and on 2,000,000 random token sequences. No statement stopped asking, and each one that started asking is an `UPDATE` with one of the two targets. Those scripts aren't part of this PR. Not run: the e2e project, which needs `ANTHROPIC_API_KEY`. I haven't tested against a hosted project or with a real MCP client. ## Additional context - Spellings that run without asking on `main` and still do after this change: an unquoted name with a character outside `[A-Za-z0-9_]` (`update café set ...`, `update films$x set ...`), whitespace around the dot or a three-part name, no whitespace next to a quoted name or after `SET` (`update "films"set ...`), a Unicode-escaped name (`update U&"films" set ...`), and `WITH ... UPDATE` or an `UPDATE` first in a `DO` body (under Trade-offs in #408). - Studio's `updateWithoutWhereRegex`, which this one was adapted from, has no `ONLY`, alias, `*` or parentheses. This PR doesn't change Studio. - #557 is open against the same function. The two changes don't overlap, and with both applied the file's 162 tests pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Why
Adds confirmation elicitations before destructive SQL, such as dropping a table
Closes AI-1186.
What changed
costConfirmation→confirmation.enabledToolscreate_project,create_branch) and SQL confirmations (execute_sql,apply_migration);How to test
Expand for details
Choose one disposable target and prepare your tools. Use either:
https://api.supabase.green, an existing staging personal access token (PAT), and a disposable staging project ref.https://api.supabase.com, an existing production PAT, and that disposable production project's ref.The server API URL, PAT, and project ref must all match your choice. Never use customer, shared, or application data.
Check out this PR (
feat/destructive-sql-confirmation, reviewed head8a7e9de) locally. Have the repository's Node LTS and pnpm 10 active (tool setup), plus a current Claude Code version with MCP elicitation form support. Disable elicitation auto-answer hooks for this session.Build and start the local HTTP server in Terminal A. Replace
/path/to/this-pr-checkoutwith your checkout root: the folder containingpackage.jsonandpackages/.Use your existing pnpm 10.33.2 executable: replace
PNPM10below with its absolute path before running. The subshell puts it ahead of Corepack shims so nested commands use the same version, without changing your shell configuration. Noapprove-buildsstep is needed;enable-pre-post-scriptsenables the package’s own prebuild step, not dependency build approval.For staging, start:
For dedicated disposable production, replace only
https://api.supabase.greenwithhttps://api.supabase.comin that command. Leave Terminal A running; HTTP mode does not need a server-side PAT export.Reuse an existing server only if it runs this PR with your chosen API URL and port. Otherwise, use a free port and change
3111in both the launch command and the config below. Do not stop an unrelated server.Create a private
.mcp.jsonat the checkout root. Open Terminal B using interactive bash or zsh, then enter the same folder:cd /path/to/this-pr-checkout git ls-files -- .mcp.jsonIf that command lists
.mcp.json, stop: an ignore rule cannot protect a tracked file. If the file already exists, do not overwrite it or add a duplicate registration. Privately reuse only a suitable entry matching the local endpoint, disposable target,read_only=false, database tools, and environment-backed PAT shown below. If incompatible, stop rather than modify, delete, or untrack it. When reusing an entry, use its actual server name and environment-variable names in the remaining steps.For a new file, first add this repository-local exclusion, not a tracked
.gitignorechange:In a local text editor, create
.mcp.jsondirectly beside the rootpackage.json, not insidepackages/mcp-server-supabaseor~/.claude. Paste this JSON, keeping both${...}placeholders literal. Never put a token in the file.{ "mcpServers": { "supabase-sql-review": { "type": "http", "url": "http://127.0.0.1:3111/mcp?project_ref=${SUPABASE_REVIEW_PROJECT_REF}&read_only=false&features=database", "headers": { "Authorization": "Bearer ${SUPABASE_REVIEW_PAT}" } } } }Check that the file is ignored:
Expect
.mcp.jsonas output; otherwise stop. Keep this config local and do not force-add or commit it. The local URL stays the same for either environment; the server's--api-urlselects staging or production.Enter your existing PAT and launch Claude from Terminal B. Run these commands one at a time, answering each prompt before continuing. Enter the PAT only at the silent input prompt, never as a shell command or JSON value. Stop if either input is missing or does not match your chosen environment.
In Claude, use
/mcpto confirm thatsupabase-sql-review(or your reused entry) is connected. Privately verify the actual target, not just the connection label. Stop on ambiguity or connection failure; do not switch servers or use an OAuth workaround.--tools ""disables built-in tools, not MCP tools. Strict config loads only the supplied config, but every server in that file can load. Use only the selected server'sexecute_sqlandapply_migration. The PAT remains in process environment/memory: do not print the environment, expose secrets in logs/screenshots, or ask Claude to inspect the config.Copy the prompt below into Claude, replacing its three bracketed header values. This is the direct-SQL confirmation matrix for feat(mcp)!: confirm destructive SQL via elicitation and rename costConfirmation option #408, not the parser matrix for feat: parse SQL before destructive confirmation #426. Answer actual server elicitation forms manually. Normal tool-permission dialogs and initial target confirmation do not replace per-operation forms.
Reusable #408 manual test prompt
Trade-offs