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

149 lines
5.3 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createSupabaseMCPClient } from '../supabase-mcp'
import { getMcpTools } from './mcp-tools'
import { REMOTE_TOOL_CONTRACTS } from './registry'
vi.mock('../supabase-mcp', () => ({
createSupabaseMCPClient: vi.fn(),
}))
const BASE_PARAMS = {
accessToken: 'token',
projectRef: 'abcdefghijklmnopqrst',
aiOptInLevel: 'schema_and_log_and_data' as const,
// A fresh, non-aborted signal by default; lifecycle tests override it
signal: new AbortController().signal,
}
// A realistic remote tool set: all expected read tools plus write tools Studio must not expose
const FULL_REMOTE_TOOLS = {
search_docs: { description: 'docs' },
list_tables: { description: 'list tables' },
list_extensions: { description: 'extensions' },
list_edge_functions: { description: 'edge functions' },
list_branches: { description: 'branches' },
get_advisors: { description: 'advisors' },
query_logs: { description: 'query logs' },
execute_sql: { description: 'execute sql' },
deploy_edge_function: { description: 'deploy' },
apply_migration: { description: 'migrate' },
create_branch: { description: 'branch' },
}
describe('ai/tools/mcp-tools getMcpTools', () => {
let close: ReturnType<typeof vi.fn>
let tools: ReturnType<typeof vi.fn>
let consoleErrorSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
close = vi.fn().mockResolvedValue(undefined)
tools = vi.fn().mockResolvedValue({ ...FULL_REMOTE_TOOLS })
vi.mocked(createSupabaseMCPClient).mockResolvedValue({ tools, close } as any)
})
afterEach(() => {
consoleErrorSpy.mockRestore()
})
it('returns only tools with a remote contract', async () => {
const result = await getMcpTools(BASE_PARAMS)
expect(result).toHaveProperty('list_tables')
expect(result).toHaveProperty('query_logs')
// MCP's versions lose to Studio's own, and write tools never get through
for (const name of [
'execute_sql',
'deploy_edge_function',
'apply_migration',
'create_branch',
]) {
expect(result).not.toHaveProperty(name)
}
expect(Object.keys(result).sort()).toEqual(Object.keys(REMOTE_TOOL_CONTRACTS).sort())
})
it('takes needsApproval from the contract', async () => {
const result = await getMcpTools(BASE_PARAMS)
for (const contract of Object.values(REMOTE_TOOL_CONTRACTS)) {
expect(result[contract.name]?.needsApproval).toBe(contract.needsApproval)
}
})
it('warns when the remote server is missing an expected tool (contract drift)', async () => {
const { list_branches, ...withoutBranches } = FULL_REMOTE_TOOLS
tools.mockResolvedValueOnce(withoutBranches)
await getMcpTools(BASE_PARAMS)
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('list_branches'))
})
it('does not warn about drift when all expected tools are present', async () => {
await getMcpTools(BASE_PARAMS)
const driftWarnings = consoleErrorSpy.mock.calls.filter(
([msg]: unknown[]) => typeof msg === 'string' && msg.includes('missing expected tools')
)
expect(driftWarnings).toHaveLength(0)
})
it('keeps the connection open until the request signal aborts', async () => {
const controller = new AbortController()
await getMcpTools({ ...BASE_PARAMS, signal: controller.signal })
// Tools execute later during streaming, so the client must stay open
expect(close).not.toHaveBeenCalled()
controller.abort()
await Promise.resolve()
expect(close).toHaveBeenCalledTimes(1)
})
it('closes the client and skips fetching tools when the signal is already aborted', async () => {
const controller = new AbortController()
controller.abort()
const result = await getMcpTools({ ...BASE_PARAMS, signal: controller.signal })
expect(close).toHaveBeenCalledTimes(1)
expect(tools).not.toHaveBeenCalled()
expect(result).toEqual({})
})
it('closes the client and rethrows when fetching tools fails, without double-closing on later abort', async () => {
tools.mockRejectedValueOnce(new Error('network unreachable'))
const controller = new AbortController()
await expect(getMcpTools({ ...BASE_PARAMS, signal: controller.signal })).rejects.toThrow(
'network unreachable'
)
expect(close).toHaveBeenCalledTimes(1)
// A subsequent abort must not close the (already closed) client again
controller.abort()
await Promise.resolve()
expect(close).toHaveBeenCalledTimes(1)
})
it('closes the client and rethrows when tool validation fails', async () => {
// A known tool name with a non-object value passes the opt-in filter but
// fails schema validation
tools.mockResolvedValueOnce({ ...FULL_REMOTE_TOOLS, list_tables: 'not-an-object' })
await expect(getMcpTools(BASE_PARAMS)).rejects.toThrow('MCP tools validation failed')
expect(close).toHaveBeenCalledTimes(1)
})
it('rejects a malformed contract tool even when the opt-in level would stub it', async () => {
tools.mockResolvedValueOnce({ ...FULL_REMOTE_TOOLS, list_tables: 'not-an-object' })
await expect(getMcpTools({ ...BASE_PARAMS, aiOptInLevel: 'disabled' })).rejects.toThrow(
'MCP tools validation failed'
)
expect(close).toHaveBeenCalledTimes(1)
})
})