Files
supabase/apps/studio/lib/ai/tools/legacy-tools.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

135 lines
5.0 KiB
TypeScript

import type { ToolUIPart } from 'ai'
import { describe, expect, it } from 'vitest'
import { OPT_IN_LEVELS } from '../opt-in-level'
import { getLegacyToolContract, LEGACY_TOOL_CONTRACTS } from './legacy-tools'
import { REMOTE_TOOL_CONTRACTS, sanitizeContractPart, TOOL_CONTRACTS } from './registry'
import { sanitizeMessagePart } from './tool-sanitizer'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
function part(tool: string, output: unknown) {
return {
type: `tool-${tool}`,
toolCallId: 'call-1',
state: 'output-available',
input: {},
output,
} as ToolUIPart
}
const outputOf = (tool: string, output: unknown, level: AiOptInLevel) =>
sanitizeContractPart(part(tool, output), level)?.output
const hiddenAt = (tool: string, level: AiOptInLevel) => outputOf(tool, 'x', level)
const SCHEMA_ROW = {
data: { definitions: [{ id: 16384, sql: 'CREATE TABLE public.todos (id bigint)' }] },
}
describe('legacy tool contracts', () => {
it('looks up only own keys', () => {
expect(getLegacyToolContract('getFunctions')).toBe(LEGACY_TOOL_CONTRACTS.getFunctions)
expect(getLegacyToolContract('toString')).toBeUndefined()
expect(getLegacyToolContract('execute_sql')).toBeUndefined()
})
it('never shares a name with a registry tool', () => {
const live = new Set([...Object.keys(TOOL_CONTRACTS), ...Object.keys(REMOTE_TOOL_CONTRACTS)])
expect(Object.keys(LEGACY_TOOL_CONTRACTS).filter((name) => live.has(name))).toEqual([])
})
const gated: [string, unknown[]][] = [
['getSchemaTables', [[SCHEMA_ROW], [], 'Failed to fetch schema: boom']],
['getFunctions', ['Function: add\nReturn Type: int', '', 'Failed to fetch functions: boom']],
]
describe.each(gated)('%s', (tool, outputs) => {
it.each(OPT_IN_LEVELS)('gates stored shapes at %s', (level) => {
const hidden = hiddenAt(tool, 'disabled')
expect(typeof hidden).toBe('string')
for (const output of outputs) {
expect(outputOf(tool, output, level)).toEqual(level === 'disabled' ? hidden : output)
}
})
it('replaces an invalid output', () => {
const invalid = outputOf(tool, 42, 'schema')
expect(invalid).toBe(
LEGACY_TOOL_CONTRACTS[tool as keyof typeof LEGACY_TOOL_CONTRACTS].outputOnInvalid
)
expect(typeof invalid).toBe('string')
})
})
it.each([[[null]], [[{ schema: 'public', name: 'todos' }]]])(
'replaces a malformed getSchemaTables array %j',
(output) => {
expect(outputOf('getSchemaTables', output, 'schema')).toBe(
LEGACY_TOOL_CONTRACTS.getSchemaTables.outputOnInvalid
)
}
)
describe('getRlsKnowledge', () => {
const SAVED_OUTPUT = `You're a Supabase Postgres expert in writing row level security policies.
Here are my existing policies:
Policy Name: "Read own rows"
Action: PERMISSIVE
`
it.each(OPT_IN_LEVELS)('replays only the saved policies at %s', (level) => {
const replayed = outputOf('getRlsKnowledge', SAVED_OUTPUT, level)
if (level === 'disabled') {
expect(replayed).toBe(hiddenAt('getRlsKnowledge', 'disabled'))
return
}
expect(replayed).toBe('Policy Name: "Read own rows"\n Action: PERMISSIVE')
})
it('replaces an invalid output', () => {
expect(outputOf('getRlsKnowledge', 42, 'schema')).toBe(
LEGACY_TOOL_CONTRACTS.getRlsKnowledge.outputOnInvalid
)
})
it.each([
['has no marker', SAVED_OUTPUT.slice(0, SAVED_OUTPUT.indexOf('Here are my existing'))],
[
'has an empty policy list',
`${SAVED_OUTPUT.slice(0, SAVED_OUTPUT.indexOf('Here are my existing'))}Here are my existing policies: `,
],
])('replays a note when the output %s', (_label, output) => {
expect(outputOf('getRlsKnowledge', output, 'schema')).toBe(
'No existing policies were found when this tool ran.'
)
})
it('is safe to run on its own result', () => {
const once = outputOf('getRlsKnowledge', SAVED_OUTPUT, 'schema')
expect(outputOf('getRlsKnowledge', once, 'schema')).toBe(once)
const note = 'No existing policies were found when this tool ran.'
expect(outputOf('getRlsKnowledge', note, 'schema')).toBe(note)
})
})
it.each(OPT_IN_LEVELS)('points getEdgeFunctionKnowledge at load_knowledge at %s', (level) => {
const replayed = outputOf('getEdgeFunctionKnowledge', 'Stale Edge guidance', level)
expect(replayed).toContain('`load_knowledge`')
expect(replayed).toContain('`edge_functions`')
expect(replayed).not.toContain('Stale Edge guidance')
})
it('replaces an invalid getEdgeFunctionKnowledge output', () => {
expect(outputOf('getEdgeFunctionKnowledge', { a: 1 }, 'schema')).toBe(
LEGACY_TOOL_CONTRACTS.getEdgeFunctionKnowledge.outputOnInvalid
)
})
it('is reached through sanitizeMessagePart', () => {
const result = sanitizeMessagePart(part('getFunctions', 'Function: add'), 'disabled')
expect(result).toMatchObject({ type: 'tool-getFunctions' })
expect((result as ToolUIPart).output).not.toBe('Function: add')
})
})