Files
supabase/apps/studio/lib/ai/tools/tool-sql.server.test.ts
Charis a05e7ec1d7 refactor(studio): move self-hosted Assistant tools to contracts (#52468)
Stacked on supabase/supabase#52422.

## What

The self-hosted Assistant tools become contracts, so every tool the
Assistant can call now comes from the registry and the allowlist is
derived from it.

* The fallback tools (`getSchemaTables`, `getRlsKnowledge`,
`getFunctions`, `getEdgeFunctionKnowledge`) are deleted. Self-hosted now
gets the shared tools plus:
* `list_tables`: a local contract with the same input as the MCP tool
and a similar output, built from pg-meta. It shares its prompt guidance
with the remote contract, which moves to `list-tables.remote.ts`. On
platform the remote contract is still used.
  * `list_functions`: self-hosted only, filtered by schema in SQL.
  * `list_policies`: now available in both environments.
* `runPgMetaQuery` (`tool-sql.server.ts`) runs pg-meta-built SQL and
validates the rows with the builder's zod schema. Off platform it calls
`executeQuery` directly, because the default fetcher goes through a
relative API URL that doesn't resolve server-side.
* The allowlist comes from the registry:
* `ToolName` and the tool set validation schema are built from the
contract keys. The tool category map is removed.
* `mcp-tools.ts` keeps only tools with a remote contract, before opt-in
filtering, so `UI_EXECUTED_TOOLS` is gone. `EXPECTED_MCP_TOOLS` is
derived from the contracts and type-checked against the MCP package.
* Saved chats: the legacy contracts now trim replayed outputs.
`getRlsKnowledge` replays only the saved policy list, without the stale
RLS instructions. `getEdgeFunctionKnowledge` replays a pointer to
`load_knowledge`.
* The logs reference text no longer names `query_logs`.

## Behavior changes

* `list_policies` on platform validates rows before formatting, so a row
that fails pg-meta's schema now errors the tool call instead of
returning text.
* `list_tables` on self-hosted doesn't include the MCP tool's optional
`advisory` field.
* `list_functions` with an empty `schemas` list returns every non-system
schema.
* On platform, if the MCP tools fail to load, `list_tables` is dropped
from the tool set like the other remote tools.

## Tests

* Unit tests for `runPgMetaQuery`, the local `list_tables` and
`list_functions`, and the output mapping. The SQL boundary is mocked;
not yet run against a live self-hosted database.
* Legacy contract tests cover trimming, the empty and missing policy
cases, and that replaying an already-trimmed output leaves it unchanged.

## Checklist

Check all before review:

- [X] I have read
[CONTRIBUTING.md](<https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md>)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](<https://github.com/supabase/supabase/tree/master/apps/docs/style-guide>)
2026-10-31 07:44:36 -04:00

85 lines
2.9 KiB
TypeScript

import pgMeta from '@supabase/pg-meta'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { runPgMetaQuery } from './tool-sql.server'
import { executeSql } from '@/data/sql/execute-sql-mutation'
import { executeQuery } from '@/lib/api/self-hosted/query'
const state = vi.hoisted(() => ({ isPlatform: true }))
vi.mock('common', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>()
const mocked = { ...actual }
Object.defineProperty(mocked, 'IS_PLATFORM', { get: () => state.isPlatform, enumerable: true })
return mocked
})
vi.mock('@/data/sql/execute-sql-mutation', () => ({ executeSql: vi.fn() }))
vi.mock('@/lib/api/self-hosted/query', () => ({ executeQuery: vi.fn() }))
const CTX = {
projectRef: 'abcdefghijklmnopqrst',
connectionString: 'encrypted',
authorization: 'Bearer token',
}
describe('ai/tools/tool-sql runPgMetaQuery', () => {
beforeEach(() => {
vi.mocked(executeSql).mockReset()
vi.mocked(executeSql).mockResolvedValue({ result: [] })
})
it('runs the builder SQL with the caller headers and no fetcher override on platform', async () => {
state.isPlatform = true
const query = pgMeta.schemas.list()
const controller = new AbortController()
await runPgMetaQuery(CTX, query, controller.signal)
expect(executeSql).toHaveBeenCalledWith(
expect.objectContaining({
projectRef: CTX.projectRef,
connectionString: CTX.connectionString,
sql: query.sql,
}),
controller.signal,
{ Authorization: 'Bearer token' },
undefined
)
})
it('passes executeQuery as the fetcher override off platform', async () => {
state.isPlatform = false
await runPgMetaQuery(CTX, pgMeta.schemas.list())
const fetcher = vi.mocked(executeSql).mock.calls[0][3]
vi.mocked(executeQuery).mockResolvedValue({ data: [{ ok: true }], error: undefined })
await expect(fetcher?.({ query: 'select 1' })).resolves.toEqual({ data: [{ ok: true }] })
expect(executeQuery).toHaveBeenCalledWith({ query: 'select 1' })
})
it('surfaces the database error instead of an empty result off platform', async () => {
state.isPlatform = false
// Mirror executeSql's handling: a result with a `data` key counts as success.
vi.mocked(executeSql).mockImplementation(async (_variables, _signal, _headers, fetcher) => {
const result = await fetcher!({ query: 'select 1' })
if ('data' in result) return { result: result.data }
throw result.error
})
vi.mocked(executeQuery).mockResolvedValue({
data: undefined,
error: new Error('connection refused'),
})
await expect(runPgMetaQuery(CTX, pgMeta.schemas.list())).rejects.toThrow('connection refused')
})
it('parses rows with the builder schema', async () => {
state.isPlatform = true
vi.mocked(executeSql).mockResolvedValue({ result: [{ not: 'a schema' }] })
await expect(runPgMetaQuery(CTX, pgMeta.schemas.list())).rejects.toThrow()
})
})