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

116 lines
4.1 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest'
import { getTools } from './index'
import { getMcpTools } from './mcp-tools'
vi.mock('common', () => ({ IS_PLATFORM: true }))
vi.mock('./mcp-tools', () => ({ getMcpTools: vi.fn() }))
vi.mock('./registry.server', () => ({ buildLocalTools: vi.fn(() => ({ local_tool: {} })) }))
// Identity filter so assertions can check the raw merged tool set
vi.mock('../tool-filter', async (importOriginal) => ({
...(await importOriginal<typeof import('../tool-filter')>()),
filterToolsByOptInLevel: vi.fn((tools) => tools),
}))
const BASE_PARAMS = {
projectRef: 'abcdefghijklmnopqrst',
connectionString: 'postgresql://localhost',
authorization: 'Bearer token',
aiOptInLevel: 'schema_and_log_and_data' as const,
accessToken: 'access-token',
baseUrl: 'https://supabase.com/dashboard',
signal: new AbortController().signal,
}
describe('ai/tools getTools', () => {
beforeEach(async () => {
vi.mocked(getMcpTools).mockResolvedValue({ list_tables: {} } as any)
// Reset to platform each test; the self-hosted test overrides to false.
// Done here (not afterEach) so the spy can't leak across tests via order.
const common = await import('common')
vi.spyOn(common, 'IS_PLATFORM', 'get').mockReturnValue(true)
})
it('includes local and MCP tools on platform', async () => {
const tools = await getTools(BASE_PARAMS)
expect(getMcpTools).toHaveBeenCalledWith({
accessToken: BASE_PARAMS.accessToken,
projectRef: BASE_PARAMS.projectRef,
aiOptInLevel: BASE_PARAMS.aiOptInLevel,
signal: BASE_PARAMS.signal,
})
expect(tools).toHaveProperty('local_tool')
expect(tools).toHaveProperty('list_tables')
})
it('builds local tools from the request context and the satisfied requirements', async () => {
const { buildLocalTools } = await import('./registry.server')
await getTools({ ...BASE_PARAMS, isExplorerEnabled: true, supportMode: true })
expect(buildLocalTools).toHaveBeenLastCalledWith(
{
projectRef: BASE_PARAMS.projectRef,
connectionString: BASE_PARAMS.connectionString,
authorization: BASE_PARAMS.authorization,
aiOptInLevel: BASE_PARAMS.aiOptInLevel,
baseUrl: BASE_PARAMS.baseUrl,
},
{
environment: 'platform',
satisfied: new Set(['explorer', 'supportMode', 'baseUrl']),
}
)
})
it('degrades gracefully to the remaining tools when remote MCP fetch fails', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
vi.mocked(getMcpTools).mockRejectedValueOnce(new Error('remote MCP unreachable'))
const tools = await getTools(BASE_PARAMS)
// The assistant still works with the non-MCP tools instead of throwing
expect(tools).toHaveProperty('local_tool')
expect(tools).not.toHaveProperty('list_tables')
expect(consoleSpy).toHaveBeenCalled()
consoleSpy.mockRestore()
})
it('does not fetch MCP tools when no access token is provided', async () => {
const tools = await getTools({ ...BASE_PARAMS, accessToken: undefined })
expect(getMcpTools).not.toHaveBeenCalled()
expect(tools).toHaveProperty('local_tool')
expect(tools).not.toHaveProperty('list_tables')
})
it('skips MCP when self-hosted', async () => {
const { buildLocalTools } = await import('./registry.server')
const common = await import('common')
vi.spyOn(common, 'IS_PLATFORM', 'get').mockReturnValue(false)
const tools = await getTools(BASE_PARAMS)
expect(getMcpTools).not.toHaveBeenCalled()
expect(buildLocalTools).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ environment: 'self-hosted' })
)
expect(tools).toHaveProperty('local_tool')
expect(tools).not.toHaveProperty('list_tables')
})
it('lets a local tool win over an MCP tool of the same name', async () => {
const { buildLocalTools } = await import('./registry.server')
const localTool = { description: 'local' }
vi.mocked(buildLocalTools).mockReturnValueOnce({ list_tables: localTool } as never)
const tools = await getTools(BASE_PARAMS)
expect(tools.list_tables).toBe(localTool)
})
})