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

92 lines
3.9 KiB
TypeScript

import type { JSONValue } from 'ai'
import { z } from 'zod'
import { isOptInLevelAtLeast } from '../opt-in-level'
import type { LegacyToolContract } from './types'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
const HIDDEN_LEGACY_OUTPUT_MESSAGE =
'The output of this tool is not shared with the Assistant at the current permission level. It requires the `schema` opt-in level.'
const INVALID_LEGACY_OUTPUT_MESSAGE =
'The tool ran, but its saved output could not be read, so it is not shared with the Assistant.'
/** Output that describes the project, so it needs at least the `schema` level. */
function gatedBySchemaLevel(output: JSONValue, optInLevel: AiOptInLevel): JSONValue {
return isOptInLevelAtLeast(optInLevel, 'schema') ? output : HIDDEN_LEGACY_OUTPUT_MESSAGE
}
const stringOutputSchema = z.string()
// Marks where `getRlsKnowledge` started its saved policies, after a block of RLS instructions
// that the model now gets from `load_knowledge`.
const EXISTING_POLICIES_MARKER = 'Here are my existing policies:'
const STALE_RLS_INSTRUCTIONS_START =
"You're a Supabase Postgres expert in writing row level security"
const NO_LEGACY_POLICIES_MESSAGE = 'No existing policies were found when this tool ran.'
/** Replays only the policies, not the stale instructions saved with them. */
function trimRlsKnowledge(output: string, optInLevel: AiOptInLevel): JSONValue {
const gated = gatedBySchemaLevel(output, optInLevel)
if (gated !== output) return gated
// Without the instructions there's nothing to trim, which keeps this safe on its own result.
if (!output.includes(STALE_RLS_INSTRUCTIONS_START)) return output
const markerIndex = output.indexOf(EXISTING_POLICIES_MARKER)
if (markerIndex === -1) return NO_LEGACY_POLICIES_MESSAGE
const policies = output.slice(markerIndex + EXISTING_POLICIES_MARKER.length).trim()
return policies || NO_LEGACY_POLICIES_MESSAGE
}
const EDGE_FUNCTION_KNOWLEDGE_MOVED_MESSAGE =
'The Edge Function guidance returned here is no longer available in this tool. Call `load_knowledge` with `edge_functions` to load it.'
/** The row `getEntityDefinitionsSql` returns. */
const entityDefinitionsRowSchema = z.object({
data: z.object({
definitions: z.array(z.object({ id: z.number(), sql: z.string().nullable() })),
}),
})
/**
* Removed self-hosted fallback tools. Saved chats still hold their outputs,
* so they replay through these contracts. Nothing registers them as tools.
*/
export const LEGACY_TOOL_CONTRACTS = {
getSchemaTables: {
name: 'getSchemaTables',
outputSchema: z.union([z.array(entityDefinitionsRowSchema), stringOutputSchema]),
toModelOutput: gatedBySchemaLevel,
outputOnInvalid: INVALID_LEGACY_OUTPUT_MESSAGE,
},
getRlsKnowledge: {
name: 'getRlsKnowledge',
outputSchema: stringOutputSchema,
toModelOutput: trimRlsKnowledge,
outputOnInvalid: INVALID_LEGACY_OUTPUT_MESSAGE,
},
getFunctions: {
name: 'getFunctions',
outputSchema: stringOutputSchema,
toModelOutput: gatedBySchemaLevel,
outputOnInvalid: INVALID_LEGACY_OUTPUT_MESSAGE,
},
// The saved guidance is stale and `load_knowledge` replaces it, so replay a pointer instead.
// It holds no project data, so it is safe at every level.
getEdgeFunctionKnowledge: {
name: 'getEdgeFunctionKnowledge',
outputSchema: stringOutputSchema,
toModelOutput: () => EDGE_FUNCTION_KNOWLEDGE_MOVED_MESSAGE,
outputOnInvalid: INVALID_LEGACY_OUTPUT_MESSAGE,
},
} as const satisfies Record<string, LegacyToolContract>
export type LegacyToolName = keyof typeof LEGACY_TOOL_CONTRACTS
/** The contract for a removed tool, or `undefined` if the name isn't a legacy tool. */
export function getLegacyToolContract(toolName: string): LegacyToolContract | undefined {
const contracts: Partial<Record<string, LegacyToolContract>> = LEGACY_TOOL_CONTRACTS
return Object.hasOwn(contracts, toolName) ? contracts[toolName] : undefined
}