mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
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>)
205 lines
6.2 KiB
TypeScript
205 lines
6.2 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
import { createTool as createListTablesTool } from './list-tables.server'
|
|
import { executeSql } from '@/data/sql/execute-sql-mutation'
|
|
import { executeQuery } from '@/lib/api/self-hosted/query'
|
|
|
|
vi.mock('common', async (importOriginal) => ({
|
|
...(await importOriginal<Record<string, unknown>>()),
|
|
IS_PLATFORM: false,
|
|
}))
|
|
vi.mock('@/data/sql/execute-sql-mutation', () => ({ executeSql: vi.fn() }))
|
|
vi.mock('@/lib/api/self-hosted/query', () => ({ executeQuery: vi.fn() }))
|
|
|
|
const TOOL_CONTEXT = { toolCallId: 'test', messages: [], context: {} }
|
|
|
|
const TABLE_ROW = {
|
|
id: 1,
|
|
schema: 'public',
|
|
name: 'todos',
|
|
rls_enabled: false,
|
|
rls_forced: false,
|
|
replica_identity: 'DEFAULT',
|
|
bytes: 0,
|
|
size: '0 bytes',
|
|
live_rows_estimate: 0,
|
|
dead_rows_estimate: 0,
|
|
comment: null,
|
|
primary_keys: [],
|
|
relationships: [],
|
|
}
|
|
|
|
describe('ai/tools/list-tables (self-hosted)', () => {
|
|
beforeEach(() => {
|
|
vi.mocked(executeSql).mockReset()
|
|
vi.mocked(executeSql).mockImplementation(async ({ sql }) => ({
|
|
result: relkindOf(sql) === 'table' ? [TABLE_ROW] : [],
|
|
}))
|
|
})
|
|
|
|
function relkindOf(sql: string) {
|
|
if (/relkind\s*=\s*'v'/i.test(sql)) return 'view'
|
|
if (/relkind\s*=\s*'m'/i.test(sql)) return 'materialized_view'
|
|
if (/relkind\s*=\s*'f'/i.test(sql)) return 'foreign_table'
|
|
return 'table'
|
|
}
|
|
|
|
function run(input: { schemas: string[]; verbose: boolean }) {
|
|
const tool = createListTablesTool({
|
|
projectRef: 'default',
|
|
connectionString: 'encrypted',
|
|
aiOptInLevel: 'schema',
|
|
})
|
|
if (!tool.execute) throw new Error('execute is undefined')
|
|
return tool.execute(input, TOOL_CONTEXT)
|
|
}
|
|
|
|
it('filters by schema in SQL, runs through executeQuery, and maps the rows', async () => {
|
|
const result = await run({ schemas: ['public'], verbose: false })
|
|
|
|
const [variables, , , fetcher] = vi.mocked(executeSql).mock.calls[0]
|
|
expect(variables.sql).toContain(`IN ('public')`)
|
|
vi.mocked(executeQuery).mockResolvedValue({ data: [], error: undefined })
|
|
await expect(fetcher?.({ query: 'select 1' })).resolves.toEqual({ data: [] })
|
|
expect(executeQuery).toHaveBeenCalledWith({ query: 'select 1' })
|
|
expect(result).toEqual({
|
|
tables: [{ name: 'public.todos', rls_enabled: false, rows: 0 }],
|
|
})
|
|
})
|
|
|
|
it('selects columns only when verbose', async () => {
|
|
await run({ schemas: ['public'], verbose: false })
|
|
await run({ schemas: ['public'], verbose: true })
|
|
|
|
const [compact, verbose] = vi
|
|
.mocked(executeSql)
|
|
.mock.calls.map(([variables]) => variables.sql)
|
|
.filter((sql) => relkindOf(sql) === 'table')
|
|
expect(compact).not.toContain('columns as (')
|
|
expect(verbose).toContain('columns as (')
|
|
})
|
|
it('runs all four relation queries, each filtered by schema', async () => {
|
|
await run({ schemas: ['public'], verbose: false })
|
|
|
|
const queries = vi.mocked(executeSql).mock.calls.map(([variables]) => variables.sql)
|
|
expect(queries.map(relkindOf).sort()).toEqual([
|
|
'foreign_table',
|
|
'materialized_view',
|
|
'table',
|
|
'view',
|
|
])
|
|
for (const sql of queries) expect(sql).toContain(`IN ('public')`)
|
|
})
|
|
|
|
it('includes views, materialized views, and foreign tables with their type', async () => {
|
|
vi.mocked(executeSql).mockImplementation(async ({ sql }) => {
|
|
switch (relkindOf(sql)) {
|
|
case 'view':
|
|
return {
|
|
result: [{ id: 2, schema: 'public', name: 'v', is_updatable: true, comment: null }],
|
|
}
|
|
case 'materialized_view':
|
|
return {
|
|
result: [
|
|
{ id: 3, schema: 'public', name: 'mv', is_populated: true, comment: 'cached' },
|
|
],
|
|
}
|
|
case 'foreign_table':
|
|
return {
|
|
result: [
|
|
{
|
|
id: 4,
|
|
schema: 'public',
|
|
name: 'ft',
|
|
comment: null,
|
|
foreign_server_name: 's',
|
|
foreign_data_wrapper_name: 'w',
|
|
foreign_data_wrapper_handler: 'h',
|
|
},
|
|
],
|
|
}
|
|
default:
|
|
return { result: [TABLE_ROW] }
|
|
}
|
|
})
|
|
|
|
const result = await run({ schemas: ['public'], verbose: false })
|
|
|
|
expect(result).toEqual({
|
|
tables: [
|
|
{ name: 'public.todos', rls_enabled: false, rows: 0 },
|
|
{ name: 'public.v', type: 'view', rls_enabled: false, rows: null },
|
|
{
|
|
name: 'public.mv',
|
|
type: 'materialized_view',
|
|
rls_enabled: false,
|
|
rows: null,
|
|
comment: 'cached',
|
|
},
|
|
{ name: 'public.ft', type: 'foreign_table', rls_enabled: false, rows: null },
|
|
],
|
|
})
|
|
})
|
|
|
|
it('includes view columns when verbose', async () => {
|
|
vi.mocked(executeSql).mockImplementation(async ({ sql }) => ({
|
|
result:
|
|
relkindOf(sql) === 'view'
|
|
? [
|
|
{
|
|
id: 2,
|
|
schema: 'public',
|
|
name: 'v',
|
|
is_updatable: false,
|
|
comment: null,
|
|
columns: [
|
|
{
|
|
id: '2.1',
|
|
table_id: 2,
|
|
schema: 'public',
|
|
table: 'v',
|
|
name: 'id',
|
|
ordinal_position: 1,
|
|
data_type: 'bigint',
|
|
format: 'int8',
|
|
is_identity: false,
|
|
identity_generation: null,
|
|
is_generated: false,
|
|
is_nullable: true,
|
|
is_updatable: false,
|
|
is_unique: false,
|
|
check: null,
|
|
default_value: null,
|
|
enums: [],
|
|
comment: null,
|
|
},
|
|
],
|
|
},
|
|
]
|
|
: [],
|
|
}))
|
|
|
|
const result = await run({ schemas: ['public'], verbose: true })
|
|
|
|
expect(result).toEqual({
|
|
tables: [
|
|
{
|
|
name: 'public.v',
|
|
type: 'view',
|
|
rls_enabled: false,
|
|
rows: null,
|
|
columns: [
|
|
{
|
|
name: 'id',
|
|
data_type: 'bigint',
|
|
format: 'int8',
|
|
options: ['nullable'],
|
|
},
|
|
],
|
|
primary_keys: [],
|
|
},
|
|
],
|
|
})
|
|
})
|
|
})
|