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

156 lines
6.1 KiB
TypeScript

import type { InferUITools, Tool, ToolUIPart, UIDataTypes, UIMessage } from 'ai'
import { contract as createNotebook } from './create-notebook'
import { contract as deleteNotebook } from './delete-notebook'
import { contract as deployEdgeFunction } from './deploy-edge-function'
import { contract as escalateToHuman } from './escalate-to-human'
import { contract as executeSql } from './execute-sql'
import { contract as getActiveIncidents } from './get-active-incidents'
import { contract as getAdvisors } from './get-advisors'
import { contract as getNotebook } from './get-notebook'
import { contract as getReport } from './get-report'
import { getLegacyToolContract } from './legacy-tools'
import { contract as listBranches } from './list-branches'
import { contract as listDatabases } from './list-databases'
import { contract as listEdgeFunctions } from './list-edge-functions'
import { contract as listExtensions } from './list-extensions'
import { contract as listFunctions } from './list-functions'
import { contract as listNotebooks } from './list-notebooks'
import { contract as listPolicies } from './list-policies'
import { contract as listReports } from './list-reports'
import { contract as listTables } from './list-tables'
import { contract as listTablesRemote } from './list-tables.remote'
import { contract as loadKnowledge } from './load-knowledge'
import { contract as queryLogs } from './query-logs'
import { contract as renameChat } from './rename-chat'
import { contract as resolveSupportConversation } from './resolve-support-conversation'
import { contract as runNotebook } from './run-notebook'
import { contract as searchDocs } from './search-docs'
import type {
RemoteToolContract,
ToolAvailability,
ToolContract,
ToolContractInput,
ToolContractOutput,
ToolEnvironment,
ToolRequirement,
} from './types'
import { contract as updateNotebook } from './update-notebook'
import { contract as updateOptInLevel } from './update-opt-in-level'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
/**
* Every tool that has migrated to a contract. Tools not listed here are still described
* by hand in the places the contract replaces.
*/
export const TOOL_CONTRACTS = {
create_notebook: createNotebook,
delete_notebook: deleteNotebook,
deploy_edge_function: deployEdgeFunction,
escalate_to_human: escalateToHuman,
execute_sql: executeSql,
get_active_incidents: getActiveIncidents,
get_notebook: getNotebook,
get_report: getReport,
list_databases: listDatabases,
list_functions: listFunctions,
list_notebooks: listNotebooks,
list_policies: listPolicies,
list_reports: listReports,
list_tables: listTables,
load_knowledge: loadKnowledge,
rename_chat: renameChat,
resolve_support_conversation: resolveSupportConversation,
run_notebook: runNotebook,
update_notebook: updateNotebook,
update_opt_in_level: updateOptInLevel,
} as const satisfies Record<string, ToolContract>
export type ContractToolName = keyof typeof TOOL_CONTRACTS
type ContractTools = {
[K in ContractToolName]: Tool<
ToolContractInput<(typeof TOOL_CONTRACTS)[K]>,
ToolContractOutput<(typeof TOOL_CONTRACTS)[K]>
>
}
export type ContractUITools = InferUITools<ContractTools>
/**
* A message whose `tool-<name>` parts are typed for every contract tool. The first two type
* parameters are the SDK defaults, since the assistant types neither message metadata nor
* custom data parts.
*/
export type StudioUIMessage = UIMessage<unknown, UIDataTypes, ContractUITools>
/** The contract for a migrated tool, or `undefined` if the tool hasn't been migrated. */
export function getToolContract(toolName: string): ToolContract | undefined {
return Object.hasOwn(TOOL_CONTRACTS, toolName)
? TOOL_CONTRACTS[toolName as ContractToolName]
: undefined
}
/**
* Remote MCP tools whose access Studio declares. Their parts stay `dynamic-tool`, so they aren't
* part of `StudioUIMessage`.
*/
export const REMOTE_TOOL_CONTRACTS = {
get_advisors: getAdvisors,
list_branches: listBranches,
list_edge_functions: listEdgeFunctions,
list_extensions: listExtensions,
list_tables: listTablesRemote,
query_logs: queryLogs,
search_docs: searchDocs,
} as const satisfies Record<string, RemoteToolContract>
export type RemoteContractToolName = keyof typeof REMOTE_TOOL_CONTRACTS
/** Every tool Studio allows: the names are the keys of the two registries. */
export type ToolName = ContractToolName | RemoteContractToolName
/** The contract for a migrated remote tool, or `undefined` if the tool hasn't been migrated. */
export function getRemoteToolContract(toolName: string): RemoteToolContract | undefined {
const contracts: Partial<Record<string, RemoteToolContract>> = REMOTE_TOOL_CONTRACTS
return Object.hasOwn(contracts, toolName) ? contracts[toolName] : undefined
}
/**
* Applies the contract's `toModelOutput` to a persisted tool part, for history replay (where
* the SDK doesn't call it). Falls back to a legacy contract for a tool that no longer exists.
* Returns `undefined` when the tool has neither. An output that doesn't match the contract's
* schema is dropped rather than passed through unchecked.
*/
export function sanitizeContractPart<Part extends ToolUIPart>(
part: Part,
optInLevel: AiOptInLevel
): Part | undefined {
const toolName = part.type.slice('tool-'.length)
const contract = getToolContract(toolName) ?? getLegacyToolContract(toolName)
if (!contract) return undefined
const parsed = contract.outputSchema.safeParse(part.output)
return {
...part,
output: parsed.success
? contract.toModelOutput(parsed.data, optInLevel)
: contract.outputOnInvalid,
}
}
/** Whether a tool is offered in `environment`, given the requirements the request satisfies. */
export function isToolAvailable(
availability: ToolAvailability,
{ environment, satisfied }: ToolRequest
): boolean {
if (!availability.environments.has(environment)) return false
return [...(availability.requires ?? [])].every((requirement) => satisfied.has(requirement))
}
/** The request conditions that decide which tools exist: the environment and the requirements met. */
export type ToolRequest = {
environment: ToolEnvironment
satisfied: ReadonlySet<ToolRequirement>
}