Skip to content

feat: parse SQL before destructive confirmation - #426

Open
barryroodt wants to merge 5 commits into
feat/destructive-sql-confirmationfrom
feat/destructive-sql-parser
Open

barryroodt wants to merge 5 commits into
feat/destructive-sql-confirmationfrom
feat/destructive-sql-parser

Conversation

@barryroodt

@barryroodt barryroodt commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Why

Regex checks can mistake strings and comments for SQL structure, missing destructive statements. For example, SELECT '--'; can hide a following DROP, and a WHERE inside a nested SELECT can hide an UPDATE without its own WHERE.

This replaces those ordinary-SQL checks with parsing. Stacked on #408, with feat/destructive-sql-confirmation as the base branch.

What changed

  • Check SQL structure. Detect DROP, DELETE, TRUNCATE, UPDATE without its own WHERE, and table-column drops, including operations in executing CTEs. EXPLAIN checks the wrapped query only when ANALYZE enables execution.
  • Keep procedural detection best-effort. DO, an anonymous procedural block, retains text checks within its body only. If those checks suggest potentially destructive operations, the tool asks for confirmation before executing the original SQL. A nonmatch does not trigger confirmation from that body check, but does not mean the block is safe; other destructive statements can still trigger confirmation. Stored-function creation no longer warns about its unexecuted body; CALL and other runtime effects remain outside coverage.
  • Separate syntax from operational failures. Recognized syntax failures ask for consent before attempting the original SQL. Resource and unknown parser failures stop the request, including accepted retries. Error recognition is version-specific and requires review when upgrading.
  • Preserve confirmation safeguards. Read-only, per-tool and form-capability gates, original SQL and argument bindings, and existing destructive prompts and decline/cancel behavior stay intact.

Rationale

Use the direct [email protected] package rather than adding a wrapper. Its PostgreSQL-derived parser supplies statement structure that regex cannot reliably recover.

The parser loads only when classification is needed, and module-level initialization is reused for later queries rather than creating an instance per query. This build starts with 32MiB linear memory and an 8MiB stack, versus 128MiB and 32MiB for the default PG18 build. Smaller initial allocation is not a leak fix or an RSS budget.

How to test

These instructions are derived from source and documentation, not a live staging or production run.

  1. Choose one disposable target and prepare your tools. Use either:

    • Staging: API https://api.supabase.green, an existing staging personal access token (PAT), and a disposable staging project ref.
    • Dedicated disposable production: API 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-parser) 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.

  2. Build and start the local HTTP server in Terminal A. Replace /path/to/this-pr-checkout with your checkout root: the folder containing package.json and packages/.

    cd /path/to/this-pr-checkout
    pnpm install
    pnpm --config.enable-pre-post-scripts=true --filter '@supabase/mcp-server-supabase...' build

    For staging, start:

    node packages/mcp-server-supabase/dist/cli.js --http --port 3111 --api-url https://api.supabase.green

    For dedicated disposable production, replace only https://api.supabase.green with https://api.supabase.com in 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 3111 in both the launch command and the config below. Do not stop an unrelated server.

  3. Create a private .mcp.json at 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.json

    If 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 .gitignore change:

    printf '\n/.mcp.json\n' >> "$(git rev-parse --git-path info/exclude)"

    In a local text editor, create .mcp.json directly beside the root package.json, not inside packages/mcp-server-supabase or ~/.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:

    git check-ignore .mcp.json

    Expect .mcp.json as 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-url selects staging or production.

  4. 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.

    printf 'Chosen disposable project ref: ' >&2
    IFS= read -r SUPABASE_REVIEW_PROJECT_REF
    export SUPABASE_REVIEW_PROJECT_REF
    printf 'Existing PAT for the same environment: ' >&2
    IFS= read -r -s SUPABASE_REVIEW_PAT
    printf '\n' >&2
    export SUPABASE_REVIEW_PAT
    claude --tools "" --strict-mcp-config --mcp-config .mcp.json

    In Claude, use /mcp to confirm that supabase-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's execute_sql and apply_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.

  5. Run the attached manual test prompt. Open the attachment and copy its reusable prompt into Claude. Before that prompt, add the following with all three bracketed values replaced:

    Target environment: [staging or dedicated disposable production]
    MCP server: [supabase-sql-review or your selected server name]
    Exact disposable project ref: [your chosen project ref]
    
    The attachment calls staging "Green". If I selected dedicated disposable
    production above, its Green references mean only that explicitly named
    disposable production target. Do not switch environments or servers.
    Confirm this disposable target with me before any writes. All other
    safety instructions in the prompt still apply.
    

    Follow the attachment's full SQL/migration matrix, cancellation checks, and cleanup. Answer the actual server elicitation forms manually; normal tool-permission dialogs are separate and do not count. Initial target confirmation does not replace per-operation forms. Successful migrations can leave migration-history records after schema cleanup; do not delete that history.

Trade-offs

  • Memory: combined client/server/confirmation/parser RSS reached 684MB, not an isolated parser measurement or budget acceptance.
  • Complex SQL performance remains unverified: the largest measured input was mostly a comment.
  • Dynamic SQL is best-effort: variable-assembled SQL and quote/comment cases can still be missed.
  • Hosted parsing needs rollout measurements. The same package can run in hosted handlers, but after shared initialization, parsing runs synchronously on the caller's JS thread; the async interface does not offload it. Before hosted production enablement, we need representative eligible per-replica peak-load measurements of cold/warm latency, event-loop responsiveness, and process/cgroup memory against owned budgets. We're awaiting Pedro's existing stress results; no byte cap or worker pool has been selected.

@barryroodt barryroodt self-assigned this Sep 11, 2026
@barryroodt

Copy link
Copy Markdown
Contributor Author

@barryroodt

barryroodt commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Following up, both previously failing DO-block cases now pass the targeted manual retest after the DO-fallback fix.

  • September 13: 25 passes, 2 failures. September 14: only E19 and M04 were rerun, not all 27 cases. Both tools showed confirmation, preserved the table on decline, and dropped it on acceptance.

This is manual evidence, not a new CI result.
claude-code-manual-sql-elicitation-test-results-2026-09-13.md

@barryroodt
barryroodt marked this pull request as ready for review September 14, 2026 11:00
@barryroodt
barryroodt requested a review from a team as a code owner September 14, 2026 11:00
barryroodt added a commit that referenced this pull request Sep 17, 2026
…nfirmation option (#408)

## Why

Adds confirmation elicitations before destructive SQL, such as dropping
a table

Closes [AI-1186](https://linear.app/supabase/issue/AI-1186).

## What changed

- Renames `costConfirmation` → `confirmation`. `enabledTools` 
- Supports existing cost confirmations (`create_project`,
`create_branch`) and SQL confirmations (`execute_sql`,
`apply_migration`);
- Local HTTP opts into both SQL tools. 
- No new dependencies.

## How to test
<details>
<summary>Expand for details</summary>

1. **Choose one disposable target and prepare your tools.** Use either:
- **Staging:** API `https://api.supabase.green`, an existing staging
personal access token (PAT), and a disposable staging project ref.
- **Dedicated disposable production:** API `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 head
`8a7e9de`) locally. Have the repository's Node LTS and pnpm 10 active
([tool
setup](https://github.com/supabase/mcp/blob/a4f435165357d9ddaa7bf3e7b0fc4bbfcb9bc07d/CONTRIBUTING.md)),
plus a current Claude Code version with MCP elicitation form support.
Disable elicitation auto-answer hooks for this session.

2. **Build and start the local HTTP server in Terminal A.** Replace
`/path/to/this-pr-checkout` with your checkout root: the folder
containing `package.json` and `packages/`.

Use your existing pnpm 10.33.2 executable: replace `PNPM10` below 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. No `approve-builds` step is needed;
`enable-pre-post-scripts` enables the package’s own prebuild step, not
dependency build approval.

   ```sh
   cd /path/to/this-pr-checkout && (
     PNPM10=/absolute/path/to/existing/pnpm10/pnpm
     export PATH="$(dirname "$PNPM10"):$PATH"
     export npm_config_manage_package_manager_versions=false

"$PNPM10" --config.manage-package-manager-versions=false install
--frozen-lockfile &&
"$PNPM10" --config.manage-package-manager-versions=false
--config.enable-pre-post-scripts=true --filter
'@supabase/mcp-server-supabase...' build
   )
   ```

   For **staging**, start:

   ```sh
node packages/mcp-server-supabase/dist/cli.js --http --port 3111
--api-url https://api.supabase.green
   ```

For **dedicated disposable production**, replace only
`https://api.supabase.green` with `https://api.supabase.com` in 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 `3111` in both the
launch command and the config below. Do not stop an unrelated server.

3. **Create a private `.mcp.json` at the checkout root.** Open Terminal
B using interactive **bash or zsh**, then enter the same folder:

   ```sh
   cd /path/to/this-pr-checkout
   git ls-files -- .mcp.json
   ```

If 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 `.gitignore` change:

   ```sh
   printf '\n/.mcp.json\n' >> "$(git rev-parse --git-path info/exclude)"
   ```

In a local text editor, create `.mcp.json` directly beside the root
`package.json`, **not** inside `packages/mcp-server-supabase` or
`~/.claude`. Paste this JSON, keeping both `${...}` placeholders
literal. Never put a token in the file.

   ```json
   {
     "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:

   ```sh
   git check-ignore .mcp.json
   ```

Expect `.mcp.json` as 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-url` selects staging or production.

4. **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.

   ```sh
   printf 'Chosen disposable project ref: ' >&2
   IFS= read -r SUPABASE_REVIEW_PROJECT_REF
   export SUPABASE_REVIEW_PROJECT_REF
   printf 'Existing PAT for the same environment: ' >&2
   IFS= read -r -s SUPABASE_REVIEW_PAT
   printf '\n' >&2
   export SUPABASE_REVIEW_PAT
   claude --tools "" --strict-mcp-config --mcp-config .mcp.json
   ```

In Claude, use `/mcp` to confirm that `supabase-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's `execute_sql` and `apply_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.

5. **Copy the prompt below into Claude**, replacing its three bracketed
header values. This is the direct-SQL confirmation matrix for #408, not
the parser matrix for #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

```text
Target environment: [staging or dedicated disposable production]
MCP server: [supabase-sql-review or selected server]
Exact disposable project ref: [...]

Run this manual check only against the selected MCP server and the exact disposable project above. Confirm the target with me before any writes. Never use a customer, shared, or application-data project. Before starting, confirm that both execute_sql and apply_migration are available and the client supports form elicitation. Do not change or bypass configured readOnly, per-tool, or form gates. Stop if the target or prerequisites are ambiguous.

Use only that server's execute_sql and apply_migration tools. Do not use shell, HTTP, psql, other servers, configuration or secret reads, new credentials, server changes, automatic response hooks, or scripted approvals. I must answer every server elicitation form manually. A tool-permission dialog or approval in chat is not that form. If you cannot observe the form or my response, ask me what appeared; do not infer it from the tool result.

This is not a dry run. Setup, two accepted UPDATEs, and separately approved cleanup execute SQL. The six other destructive patterns per tool must all be denied. A missing form may mean SQL executed unexpectedly: stop writes immediately, report the failure, and use read-only diagnostics if needed. Also stop on an unexpected result, a changed target, changed state after Deny/Cancel, or a repeated form after an accepted call. Check the catalog before reading a table that may have been dropped. Do not retry, rewrite SQL, change a migration name to bypass a failure, or continue to cleanup after a stop.

1. Create two small fixtures

Choose one identifier-safe, unique schema name mcp_elicitation_test_<UTC>_<random>. Replace <schema> below with that exact name. Use a read-only catalog check to confirm it does not exist; never reuse an existing schema. Keep a record of every object and migration created by this run. Fully qualify all fixture references. Do not touch existing schemas, other objects, roles, or extensions.

Before every write call, show the exact target, tool, SQL, and migration name if applicable. Run calls sequentially, never concurrently.

Through execute_sql, run:

CREATE SCHEMA <schema>;
CREATE TABLE <schema>.sql_rows (
  id int PRIMARY KEY,
  n int NOT NULL,
  keep int,
  doomed int
);
INSERT INTO <schema>.sql_rows (id, n, keep, doomed)
VALUES (1, 10, 100, 1000), (2, 20, 200, 2000), (3, 30, 300, 3000);

Through apply_migration, use the unique name <schema>_setup and run:

CREATE TABLE <schema>.migration_rows (
  id int PRIMARY KEY,
  n int NOT NULL,
  keep int,
  doomed int
);
INSERT INTO <schema>.migration_rows (id, n, keep, doomed)
VALUES (1, 10, 100, 1000), (2, 20, 200, 2000), (3, 30, 300, 3000);

Both setup calls are benign baselines: expect no server elicitation form. Also check the bounded UPDATE baseline once per tool, expecting no form:

execute_sql:
UPDATE <schema>.sql_rows SET n = n WHERE id = 1;

apply_migration, name <schema>_bounded_update:
UPDATE <schema>.migration_rows SET n = n WHERE id = 1;

If any benign baseline unexpectedly prompts, stop and report it; do not accept it.

Use read-only execute_sql calls to save an initial snapshot of each table's existence, column definitions, and rows ordered by id. Both must contain exactly the three seeded rows. Use this row-query template with the appropriate table:

SELECT id, n, keep, doomed FROM <schema>.<table> ORDER BY id;

Keep these same two tables throughout. Do not reseed or create replacement fixtures between cases.

2. Check response handling once per tool

Complete the whole execute_sql sequence first, then the whole apply_migration sequence. Each uses its own table:

execute_sql:
UPDATE <schema>.sql_rows SET n = n + 1;

apply_migration, name <schema>_response_update:
UPDATE <schema>.migration_rows SET n = n + 1;

For each tool, submit that exact SQL in this order. For apply_migration, keep the same name and SQL across all attempts:

- Deny/Decline: expect a server form and wait for me to deny it. Read back the fixture. Its schema and all rows must match the initial snapshot, including n = 10, 20, 30.
- Cancel: only if the client exposes a distinct cancellation of the server form, submit the same call and wait for me to cancel it. Read back the fixture and require the same unchanged snapshot. If no distinct cancellation is available, record NOT OBSERVABLE and skip this attempt. A CLI interrupt or another Deny is not cancellation evidence.
- Accept: submit the same call and wait for me to accept the form once. Read back the fixture. Expect exactly n = 11, 21, 31 by id, with all other data and column definitions unchanged. Save this as the post-accept snapshot. Do not retry after success.

Only these two test UPDATEs are accepted. Each affects the three rows in its own fixture. Their readbacks check this run's outcome, not a general exactly-once guarantee.

3. Check the remaining SQL patterns with Deny only

Run the following six cases once through execute_sql on sql_rows, then once through apply_migration on migration_rows. Replace <table> accordingly. Every case must produce a server elicitation form; wait for me to choose Deny/Decline every time.

Case                   SQL                                                        apply_migration name
D1 delete with WHERE   DELETE FROM <schema>.<table> WHERE id = 1;                  <schema>_d1
D2 delete all          DELETE FROM <schema>.<table>;                               <schema>_d2
D3 truncate            TRUNCATE TABLE <schema>.<table>;                            <schema>_d3
D4 drop table          DROP TABLE <schema>.<table>;                                <schema>_d4
D5 drop column         ALTER TABLE <schema>.<table> DROP COLUMN doomed;            <schema>_d5
D6 drop shorthand      ALTER TABLE <schema>.<table> DROP doomed;                   <schema>_d6

Do not repeat the unbounded UPDATE case, which phase 2 already covers. Do not accept or cancel any detection case. Do not reset fixtures or read them back after individual detection cases. The tables and doomed columns must remain available because every case is denied. No migration-history write is expected for these denied apply_migration calls.

At the end of each tool's six-case block, make one read-only comparison of the table's existence, column definitions, and ordered rows against its post-accept snapshot. Expect n = 11, 21, 31 and no other changes. This is an aggregate check for the block, not a per-case readback. If a form is missing or another stop condition occurs mid-block, stop immediately rather than finishing the block.

4. Report before cleanup

Return a compact table with tool, case/SQL reference, expected form, observed form, manual action, result, and PASS/FAIL/NOT OBSERVABLE. Include the benign baselines, response checks, and each detection case. Distinguish tool results from my observations of the actual forms. Report the initial, response, and aggregate readback comparisons, any skipped cancellation, and any stop condition. List the schema and migration names created by this run.

With cancellation available, the response and detection phases contain 18 form actions: 2 Accept, 14 Deny, and 2 Cancel. Without it, they contain 16 actions and two cancellation checks marked NOT OBSERVABLE. Setup, benign baselines, read-only checks, and cleanup are outside those counts.

Keep the conclusion limited to manual form behavior and observed database outcomes. This does not prove SDK authentication, request binding, replay protection, or that classification was skipped on the accepted retry. That last claim needs the separate automated issued-state test whose classifier throws if called. Comment, CTE, and DO-block regex limitations are outside this run; do not add experiments or runnable examples for them. Do not add resource, performance, deep-nesting, or parser cases.

5. Cleanup only after separate approval

After the report, ask whether I want cleanup. If approved, use read-only checks to list the schema's contents and confirm every contained object belongs to this run. If ownership is uncertain, stop and leave it intact.

Show the exact target and SQL, then call execute_sql with:

DROP SCHEMA <schema> CASCADE;

Expect a server elicitation form and wait for my manual Accept. If I decline or cancel, leave the fixtures in place. If the form is missing, stop and report the failure, using only read-only diagnostics if needed. After an accepted cleanup, verify schema absence with a read-only catalog check. Never delete migration history, modify client configuration, or stop the server.
```
</details>

## Trade-offs

- Best-effort regex is not a security barrier: literal-comment,
UPDATE-comment and WITH/DO misses remain.
- Clients without elicitation support maintain current behaviour: SQL
can execute unprompted.
- Hosted-platform SQL opt-in is separate
([#38211](supabase/platform#38211)), defaults to
off behind a feature flag.
barryroodt pushed a commit that referenced this pull request Nov 9, 2026
…structive SQL (#533)

## What kind of change does this PR introduce?

Bug fix. Fixes #531.

## What is the current behavior?

Thanks so much @zmcray for the really careful write up in #531, and to
everyone in the #457 thread. The point raised there about `DO '...'`
bodies shaped this whole change.

Right now `execute_sql` asks for a destructive confirmation when a plain
INSERT, UPDATE or SELECT only has `; drop`, `; delete` or `; truncate`
inside a text value, or has the word `Execute` inside a value:

1. An agent sends `insert into notes (body) values ('Moved the list to
11/3; drop the two duplicates')`.
2. `checkDestructiveQueryFromScan` removes comments but keeps every
literal as is, then runs `cleanedSql.split(';')`.
3. One piece is ` drop the two duplicates')`, which matches
`/^\s*(drop|delete|truncate)\s/i`.
4. `isDestructiveSql` returns `true`, the client gets a confirmation
nobody answers, and in an unattended run the write is lost after the
timeout.

The same thing happens with `$b$...$b$` values, UPDATE values, `select
'a; truncate b'`, and `values ('Execute the plan', '{"proposed":
"drop"}')` (the `execute\s+` check matched inside the first value).

## What is the new behavior?

Before the existing checks run, a new `maskDataLiterals` replaces each
string, E string or dollar quoted literal with `''`, unless that literal
is code. A literal stays as is when:

- its statement starts with `DO` (so `do 'begin perform 1; drop table t;
end'` is still flagged, like today),
- `EXECUTE` appears earlier in the same statement, outside any literal
(so `EXECUTE 'DROP TABLE films'` and the `format` / `concat` cases work
exactly as today),
- it comes right after `AS`, which is where function and procedure
bodies go (main flags `create function ... as 'begin; delete from t;
end'` today, so I kept that),
- or it is unterminated, so incomplete input still fails closed.

Everything after that point (the `;` split, the ALTER TABLE check, the
EXECUTE checks) is unchanged and just reads the masked text. Comments
now become a space instead of disappearing, so `delete/**/from t` is
caught too (main read it as `deletefrom`).

```mermaid
flowchart TD
  A[SQL text] --> B[lexSql spans]
  B --> C{literal?}
  C -- no --> E[keep text]
  C -- yes --> D{"DO statement, EXECUTE earlier,<br/>right after AS, or unterminated?"}
  D -- yes --> E
  D -- no --> F["replace with ''"]
  E --> G[existing checks: split on ;, ALTER, EXECUTE]
  F --> G
```

To make sure nothing real got lost, I ran 341 statements through
`isDestructiveSql` on main and on this branch: every string from
`destructive-sql.test.ts`, plus `drop`, `delete`, `truncate` and `alter
table ... drop` wrapped in DO bodies (quoted, E quoted, dollar quoted,
with and without LANGUAGE), EXECUTE strings, function and procedure
bodies, comments, unterminated input and data literals. Nothing that
main flags in code stopped being flagged. The only changes were 37
statements where the destructive words sat inside a data value.

I know @barryroodt has #426 open to parse SQL properly before
confirming, which is the real long term answer here. This is meant as a
small interim fix on the current scanner, and I'm very happy to close it
if #426 is close to landing.

## How to Review

1. **Masking**
   - `packages/mcp-server-supabase/src/tools/sql-data-literals.ts`
- Which literals stay as code (DO, EXECUTE, AS, unterminated) and which
become `''`.

2. **Call site**
   - `packages/mcp-server-supabase/src/tools/destructive-sql.ts`
- `checkDestructiveQueryFromScan` reads the masked text instead of the
comment free text; nothing else moved.

3. **Tests**
   - `packages/mcp-server-supabase/src/tools/destructive-sql.test.ts`
- Data literals from #531 no longer match; DO, EXECUTE, function bodies
and plain statements still do.

**Review questions**

- [ ] Do DO, EXECUTE and AS cover the places where a literal is code for
you, or is there one I missed?
- [ ] Do the main execution paths preserve existing behavior?
- [ ] Do failures stop safely (unterminated input stays unmasked)?
- [ ] Do tests protect observable behavior rather than implementation
details?

## Verification

- `pnpm --filter @supabase/mcp-server-supabase typecheck`: clean
- `pnpm --filter @supabase/mcp-server-supabase test:unit --run`: 891
passed
- `pnpm format:check`: clean
- The 11 new cases that should change fail on main and pass here; the 14
"still matches" cases pass on both.
- The main vs branch comparison over 341 statements described above.

## Additional context

A couple of things I wasn't sure about and would love your take on:

- Function bodies after `AS '...'` are still read as code, matching
main. But main only flags them when a `;` comes before the destructive
word, so `create function f() returns void as 'delete from t' language
sql` isn't flagged on main or here. Should those bodies be rechecked as
their own statements, or is creating a function (which doesn't run it
yet) fine to leave alone?
- Strings passed to functions that run SQL, like `dblink_exec('...')` or
`cron.schedule(..., '...')`, are now treated as data. Main only caught
them by accident when the text had a `;` before the keyword. Is that
okay for now, or would you rather keep a short list of those functions
as code?
barryroodt pushed a commit that referenced this pull request Nov 9, 2026
…ONLY or an alias (#524)

## What kind of change does this PR introduce?

Bug fix

## What is the current behavior?

Fixes #523

`isUpdateWithoutWhere` checks each statement with the `--` or `/* */`
marker left by `splitStatements` still in front of it, so a leading
comment hides the `UPDATE`. Its regex also expects the table name right
before `SET`, so `UPDATE ONLY t` and `UPDATE t [AS] x` do not match.

## What is the new behavior?

`isUpdateWithoutWhere` strips the comment markers before checking, the
same way `isDestructiveSql` already does for `EXPLAIN`. That existing
one-liner is now a shared `stripCommentMarkers` helper. The regex
accepts an optional `ONLY` before the table name and an optional `[AS]
alias` after it.

| query | before | after |
| ----- | ------ | ----- |
| `-- reset ids`<br>`update films set id = 2` | runs | asks |
| `update only films set id = 2` | runs | asks |
| `update films as f set id = 2` | runs | asks |
| any of the above with `where id = 1` | runs | runs |

No change to tool names, descriptions, or input and output schemas.

## How to Review

1. **UPDATE check**
   - `packages/mcp-server-supabase/src/tools/destructive-sql.ts`
- `isUpdateWithoutWhereFromScan` now runs `stripCommentMarkers` on each
statement, and `updateWithoutWhereRegex` has the `ONLY` and alias
groups.

2. **Tests**
   - `packages/mcp-server-supabase/src/tools/destructive-sql.test.ts`
- New `isUpdateWithoutWhere` rows for a leading `--` or `/* */` comment,
`ONLY`, `AS f` and a bare alias, plus the same shapes with `WHERE`
staying unmatched. One `isDestructiveSql` test for the leading-comment
case.

**Review questions**

- [ ] Is stripping the markers in `isUpdateWithoutWhereFromScan` the
right place, or should `splitStatements` drop them instead?
- [ ] Should a regex fix land here while #426 is open, or should these
cases wait for the parser?

## Verification

- With only the test file applied on `main`, the 7 new "matches" rows
and the new `isDestructiveSql` test fail, and every other test passes.
- `CI=1 npx vitest run --project unit`: 34 files, 878 passed.
- `npx tsc --noEmit` and `pnpm format:check`: clean.
- On a hosted project, through `dist/cli.js --http` with a form-capable
client that declines: `main` runs the comment, `ONLY` and `AS` updates
without asking, and this branch asks for all three. The same update with
`where id = 1` runs without asking on both.
barryroodt pushed a commit that referenced this pull request Nov 24, 2026
…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)
barryroodt pushed a commit that referenced this pull request Nov 26, 2026
… a dollar-quoted value (#612)

## What kind of change does this PR introduce?

Bug fix

## What is the current behavior?

Fixes #611

`splitStatements()` keeps `--`, `/*`, and `*/` markers in `blanked`
until callers strip them (#524), so
`valueDollarQuoteStatement.test(blanked)`
(`/^\s*(?:update\s|explain(?![\w$\u0080-\uffff]))/i`) fails whenever a
comment precedes `UPDATE`/`EXPLAIN` or sits directly after `UPDATE`
(`UPDATE/* reset */films`). Leaving dollar-quoted values unmasked causes
`execute_sql`, `apply_migration`, and `run_notebook` (both confirmation
and destructive label) to:

- run comment-prefixed `UPDATE`s without `WHERE` unprompted when a
dollar-quoted value contains `where`, and
- prompt on comment-prefixed `UPDATE ... WHERE` and read-only `EXPLAIN`
/ `EXPLAIN ANALYZE` statements when a dollar-quoted value contains `;`.

Calling `valueDollarQuoteStatement.test(blanked)` on every dollar-quoted
span also repeatedly flattens V8's `+=` rope (`O(N²)` on statements with
many `$$...$$` values).

## What is the new behavior?

`splitStatements()` emits `' '` for `line-comment` and `block-comment`
spans — matching `maskDataLiterals()` in `sql-data-literals.ts` and
taking the alternative raised in #524's review question — and caches
`valueStatement` per statement (resetting on every `;`).
`stripCommentMarkers()` remains for unmasked dollar bodies and the
unterminated fallback.

| Query | `d670445` | This branch |
| --- | --- | --- |
| `/* reset */ UPDATE films SET bio = $$ where 1=1 $$;` | runs | asks |
| `-- reset`<br>`UPDATE films SET bio = $$ where 1=1 $$;` | runs | asks
|
| `UPDATE/* reset */films SET bio = $$ where 1=1 $$;` | runs | asks |
| `/* reset */ UPDATE films SET bio = $$a; b$$ WHERE id = 1;` | asks |
runs |
| `/* plan */ EXPLAIN SELECT $$ ; UPDATE films SET id = 2 $$;` | asks |
runs |
| `/* plan */ EXPLAIN (ANALYZE) UPDATE films SET bio = $$a; b$$ WHERE id
= 1;` | asks | runs |

No changes to tool names, descriptions, or schemas. Keeps the regex
fallback minimal (#532) while #426 / #582 are in flight.

## How to Review

1. **Statement splitting**
   - `packages/mcp-server-supabase/src/tools/destructive-sql.ts`
- `blanked += ' '` in `line-comment` and `block-comment` preserves token
separation (`UPDATE/* reset */films`, `EXPLAIN /**/ ANALYZE`) without
changing `block-comment` `;` splitting or unterminated-comment behavior.
- `valueStatement` resets at every `blanked = ''` site; caching at the
first dollar body is safe because `valueDollarQuoteStatement` checks
only a short leading prefix already settled before any dollar quote
(`sql-lexer.ts` never starts `$` after an identifier character).

2. **Tests**
   - `packages/mcp-server-supabase/src/tools/destructive-sql.test.ts`
- Covers comment-prefixed and glued-comment `UPDATE`s (with/without
`WHERE`), comment-prefixed `EXPLAIN` / `EXPLAIN (ANALYZE FALSE)` /
`EXPLAIN ANALYZE`, an unterminated block comment, and a 40k-comment /
40k-dollar smoke test.

**Review questions**

- [ ] Is normalizing comments to `' '` inside `splitStatements()`
(keeping `stripCommentMarkers()` for unmasked dollar bodies and the
unterminated fallback) the right boundary?
- [ ] Is caching `valueStatement` per statement worth including here?
- [ ] Should a `;` inside a block comment (`UPDATE /* ; */ films SET id
= 2;`) stop splitting statements in a follow-up, or stay fail-closed as
documented?
- [ ] Do the tests guard observable behavior without freezing internals?

## Verification

- **RED on `d670445`:** 16 of 18 new functional assertions fail on
`d670445` and pass here (2 controls pass on both).
- **Suite & build:** `vitest run --project unit` (36 files, 1,048
passed; `destructive-sql.test.ts`: 183 passed), `pnpm build` (4
packages), `tsc --noEmit`, and `biome check` on both touched files — all
clean.
- **Large-input timings (`isDestructiveSql`, `d670445` → branch):** 40k
comments (no-regression) `28.9 ms` → `25.1 ms` (80k: `44.7 ms` → `33.4
ms`); 40k dollar values `3,434.6 ms` → `22.4 ms`; 40k comments + 40k
dollar values `34.3 ms`.
- **Tool path (`execute_sql` and `apply_migration` via built
`dist/index.js`, form-capable client declining, backed by PGlite):** the
3 comment + unfiltered `UPDATE` + `$$ where 1=1 $$` queries ask and
leave both `films` rows untouched (`exec=0`); the 3 safe `UPDATE ...
WHERE` / `EXPLAIN` queries run unprompted (`exec=1`) and mutate 1 row or
0 rows as expected.
- **Not run:** `test:e2e` (needs `ANTHROPIC_API_KEY`) and live hosted
project.

## Additional context

Known remaining cases, not changed here:
- `UPDATE /* ; */ films SET id = 2;` — block-comment `;` still splits
statements as documented (`runs` on both `d670445` and this branch).
- `DO $$ BEGIN PERFORM 1; /* c */ UPDATE films SET id = 2; END $$;` —
`stripCommentMarkers()` leaves comment text inside unmasked dollar
bodies (`runs` on both).
- `INSERT INTO notes (body) VALUES ($b$Kept the deck; update notes set
body = null$b$);` — known false positive (`UPDATE`-path counterpart of
#533).
- `CREATE FUNCTION /*;*/ update (x int) RETURNS void AS $$ SELECT 1;
UPDATE t SET a = 1; $$ LANGUAGE sql;` — now masks its body (`asks` →
`runs`; defining a function does not run it, per #533).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant