Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

refactor(studio): migrate list_policies, list_reports, get_report, get_active_incidents, escalate_to_human, and resolve_support_conversation to tool contracts (#52015)

Charise21b69c602a9
diff --git a/apps/studio/lib/ai/tool-filter.test.ts b/apps/studio/lib/ai/tool-filter.test.ts
index e391062c41b..6df4273826c 100644
--- a/apps/studio/lib/ai/tool-filter.test.ts
+++ b/apps/studio/lib/ai/tool-filter.test.ts
@@ -12,8 +12,12 @@ import {
import { contract as createNotebookContract } from './tools/create-notebook'
import { contract as deleteNotebookContract } from './tools/delete-notebook'
import { contract as getNotebookContract } from './tools/get-notebook'
+import { contract as getReportContract } from './tools/get-report'
import { contract as listDatabasesContract } from './tools/list-databases'
import { contract as listNotebooksContract } from './tools/list-notebooks'
+import { contract as listPoliciesContract } from './tools/list-policies'
+import { contract as listReportsContract } from './tools/list-reports'
+import { getToolContract } from './tools/registry'
import { contract as runNotebookContract } from './tools/run-notebook'
import { contract as updateNotebookContract } from './tools/update-notebook'
@@ -21,7 +25,7 @@ describe('TOOL_CATEGORY_MAP', () => {
it('should categorize tools correctly', () => {
expect(TOOL_CATEGORY_MAP['search_docs']).toBe(TOOL_CATEGORIES.UI)
expect(TOOL_CATEGORY_MAP['list_tables']).toBe(TOOL_CATEGORIES.SCHEMA)
- expect(TOOL_CATEGORY_MAP['list_reports']).toBe(TOOL_CATEGORIES.SCHEMA)
+ expect(TOOL_CATEGORY_MAP['get_advisors']).toBe(TOOL_CATEGORIES.LOG)
})
})
@@ -30,8 +34,11 @@ describe('tools with a contract', () => {
create_notebook: createNotebookContract,
delete_notebook: deleteNotebookContract,
get_notebook: getNotebookContract,
+ get_report: getReportContract,
list_databases: listDatabasesContract,
list_notebooks: listNotebooksContract,
+ list_policies: listPoliciesContract,
+ list_reports: listReportsContract,
run_notebook: runNotebookContract,
update_notebook: updateNotebookContract,
}
@@ -55,6 +62,21 @@ describe('tools with a contract', () => {
)
})
+describe('always-available tools with a contract', () => {
+ it.each(['escalate_to_human', 'resolve_support_conversation', 'get_active_incidents'])(
+ '%s is allowed at every opt-in level',
+ (name) => {
+ const tools = {
+ [name]: { description: 'A tool', execute: vitest.fn() },
+ } as unknown as ToolSet
+
+ expect(getToolContract(name)?.minOptInLevel).toBeNull()
+ expect(Object.hasOwn(TOOL_CATEGORY_MAP, name)).toBe(false)
+ expect(filterToolsByOptInLevel(tools, 'disabled')[name].description).toBe('A tool')
+ }
+ )
+})
+
describe('tool allowance by opt-in level', () => {
// Helper function to get allowed tools for a given opt-in level
function getAllowedTools(optInLevel: string) {
diff --git a/apps/studio/lib/ai/tool-filter.ts b/apps/studio/lib/ai/tool-filter.ts
index e25ae44002f..ad6ab41a3bd 100644
--- a/apps/studio/lib/ai/tool-filter.ts
+++ b/apps/studio/lib/ai/tool-filter.ts
@@ -98,19 +98,13 @@ type ToolCategory = (typeof TOOL_CATEGORIES)[keyof typeof TOOL_CATEGORIES]
export const TOOL_CATEGORY_MAP: Record<Exclude<ToolName, ContractToolName>, ToolCategory> = {
// UI tools - always available
update_opt_in_level: TOOL_CATEGORIES.UI,
- escalate_to_human: TOOL_CATEGORIES.UI,
- resolve_support_conversation: TOOL_CATEGORIES.UI,
search_docs: TOOL_CATEGORIES.UI,
- get_active_incidents: TOOL_CATEGORIES.UI,
// Schema tools - MCP
list_tables: TOOL_CATEGORIES.SCHEMA,
list_extensions: TOOL_CATEGORIES.SCHEMA,
list_edge_functions: TOOL_CATEGORIES.SCHEMA,
list_branches: TOOL_CATEGORIES.SCHEMA,
- list_policies: TOOL_CATEGORIES.SCHEMA,
- list_reports: TOOL_CATEGORIES.SCHEMA,
- get_report: TOOL_CATEGORIES.SCHEMA,
getSchemaTables: TOOL_CATEGORIES.SCHEMA,
getRlsKnowledge: TOOL_CATEGORIES.SCHEMA,
getFunctions: TOOL_CATEGORIES.SCHEMA,
diff --git a/apps/studio/lib/ai/tools/escalate-to-human.server.ts b/apps/studio/lib/ai/tools/escalate-to-human.server.ts
new file mode 100644
index 00000000000..f3190158cff
--- /dev/null
+++ b/apps/studio/lib/ai/tools/escalate-to-human.server.ts
@@ -0,0 +1,6 @@
+import { contract } from './escalate-to-human'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+
+export const createTool: ToolFactory<typeof contract> = (ctx) =>
+ toolFromContract(contract, ctx, async () => ({ status: 'Escalation request sent to client.' }))
diff --git a/apps/studio/lib/ai/tools/escalate-to-human.ts b/apps/studio/lib/ai/tools/escalate-to-human.ts
new file mode 100644
index 00000000000..9a97bf58907
--- /dev/null
+++ b/apps/studio/lib/ai/tools/escalate-to-human.ts
@@ -0,0 +1,22 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+
+const inputSchema = z.object({
+ reason: z
+ .string()
+ .trim()
+ .min(1, 'Escalation reason is required')
+ .describe('A short reason that explains why this support chat should be escalated.'),
+})
+
+export const contract = {
+ name: 'escalate_to_human',
+ description:
+ 'Escalate this support conversation to a human support agent when the assistant cannot resolve the issue.',
+ inputSchema,
+ outputSchema: z.object({ status: z.string() }),
+ minOptInLevel: null,
+ needsApproval: false,
+ toModelOutput: ({ status }) => ({ status }),
+} as const satisfies ToolContract
diff --git a/apps/studio/lib/ai/tools/get-active-incidents.server.ts b/apps/studio/lib/ai/tools/get-active-incidents.server.ts
new file mode 100644
index 00000000000..6b99d3b1a66
--- /dev/null
+++ b/apps/studio/lib/ai/tools/get-active-incidents.server.ts
@@ -0,0 +1,112 @@
+import { IS_PLATFORM } from 'common'
+
+import { contract } from './get-active-incidents'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+import {
+ StatusPageResponseSchema,
+ type AffectedComponent,
+} from '@/lib/status-page/status-page.schema'
+
+const NO_ACTIVE_INCIDENTS_MESSAGE = 'No active incidents.'
+const DEFAULT_STATUS_PAGE_URL = 'https://status.supabase.com'
+
+function timeoutSignal(abortSignal?: AbortSignal) {
+ return abortSignal
+ ? AbortSignal.any([abortSignal, AbortSignal.timeout(5_000)])
+ : AbortSignal.timeout(5_000)
+}
+
+function formatAffectedComponents(affectedComponents: Array<AffectedComponent>): Array<string> {
+ return affectedComponents.map((component) =>
+ component.group_name ? `${component.group_name} / ${component.name}` : component.name
+ )
+}
+
+function buildActiveIncidentsMessage(
+ incidentCount: number,
+ maintenanceCount: number,
+ statusPageUrl: string
+) {
+ const parts: Array<string> = []
+ if (incidentCount > 0) {
+ parts.push(`${incidentCount} active incident${incidentCount === 1 ? '' : 's'}`)
+ }
+ if (maintenanceCount > 0) {
+ parts.push(`${maintenanceCount} in-progress maintenance${maintenanceCount === 1 ? '' : 's'}`)
+ }
+
+ const totalCount = incidentCount + maintenanceCount
+
+ return `There ${totalCount === 1 ? 'is' : 'are'} ${parts.join(' and ')} on Supabase infrastructure. If the user's issue appears related, inform them about the ongoing issue(s) and direct them to ${statusPageUrl} for real-time updates.`
+}
+
+export const createTool: ToolFactory<typeof contract> = (ctx) => {
+ const { baseUrl } = ctx
+
+ return toolFromContract(contract, ctx, async (_input, { abortSignal }) => {
+ if (!IS_PLATFORM) {
+ return {
+ incidents: [],
+ message: 'Incident checking is only available on Supabase platform.',
+ }
+ }
+
+ const response = await fetch(`${baseUrl}/api/status-page`, {
+ signal: timeoutSignal(abortSignal),
+ })
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch status page: ${response.status}`)
+ }
+
+ const json = await response.json()
+ const parseResult = StatusPageResponseSchema.safeParse(json)
+
+ if (!parseResult.success) {
+ throw new Error(`Failed to parse status page response: ${parseResult.error.message}`)
+ }
+
+ const { data } = parseResult
+
+ const incidents = data.ongoing_incidents
+ .filter((incident) => incident.visible)
+ .map((incident) => ({
+ kind: 'incident' as const,
+ name: incident.name,
+ status: incident.status,
+ impact: incident.current_worst_impact,
+ affected_components: formatAffectedComponents(incident.affected_components),
+ last_update_message: incident.last_update_message ?? null,
+ url: incident.url,
+ }))
+
+ const maintenances = data.in_progress_maintenances
+ .filter((maintenance) => maintenance.visible)
+ .map((maintenance) => ({
+ kind: 'maintenance' as const,
+ name: maintenance.name,
+ status: maintenance.status,
+ affected_components: formatAffectedComponents(maintenance.affected_components),
+ last_update_message: maintenance.last_update_message ?? null,
+ url: maintenance.url,
+ started_at: maintenance.started_at,
+ }))
+
+ const combined = [...incidents, ...maintenances]
+
+ if (combined.length === 0) {
+ return {
+ incidents: [],
+ message: NO_ACTIVE_INCIDENTS_MESSAGE,
+ }
+ }
+
+ const statusPageUrl = DEFAULT_STATUS_PAGE_URL
+
+ return {
+ incidents: combined,
+ message: buildActiveIncidentsMessage(incidents.length, maintenances.length, statusPageUrl),
+ }
+ })
+}
diff --git a/apps/studio/lib/ai/tools/get-active-incidents.ts b/apps/studio/lib/ai/tools/get-active-incidents.ts
new file mode 100644
index 00000000000..9cea12b1a16
--- /dev/null
+++ b/apps/studio/lib/ai/tools/get-active-incidents.ts
@@ -0,0 +1,32 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+
+const inputSchema = z.object({})
+
+const outputSchema = z.object({
+ incidents: z.array(
+ z.object({
+ kind: z.enum(['incident', 'maintenance']),
+ name: z.string(),
+ status: z.string(),
+ impact: z.string().optional(),
+ affected_components: z.array(z.string()),
+ last_update_message: z.string().nullable(),
+ url: z.string(),
+ started_at: z.string().optional(),
+ })
+ ),
+ message: z.string(),
+})
+
+export const contract = {
+ name: 'get_active_incidents',
+ description:
+ 'Check for active incidents. Use this tool when the user reports issues with any Supabase service, including the database, authentication, realtime, storage, and functions. Possible problems include, but are not limited to, connection issues, timeouts, service unavailability, authentication failures, or unexpected errors.',
+ inputSchema,
+ outputSchema,
+ minOptInLevel: null,
+ needsApproval: false,
+ toModelOutput: (output: z.infer<typeof outputSchema>) => output,
+} as const satisfies ToolContract
diff --git a/apps/studio/lib/ai/tools/get-report.server.ts b/apps/studio/lib/ai/tools/get-report.server.ts
new file mode 100644
index 00000000000..259d155bef0
--- /dev/null
+++ b/apps/studio/lib/ai/tools/get-report.server.ts
@@ -0,0 +1,49 @@
+import { getAuthHeaders } from './auth-headers'
+import { contract } from './get-report'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+import { getContentById } from '@/data/content/content-id-query'
+import type { Dashboards, SqlSnippets } from '@/types'
+
+export const createTool: ToolFactory<typeof contract> = (ctx) => {
+ const { projectRef } = ctx
+ const authHeaders = getAuthHeaders(ctx.authorization)
+
+ return toolFromContract(contract, ctx, async ({ id }, { abortSignal }) => {
+ const report = await getContentById({ projectRef, id }, abortSignal, authHeaders)
+ if (report.type !== 'report') {
+ throw new Error(`Content ${id} is not a report (type: ${report.type})`)
+ }
+
+ const content = report.content as Dashboards.Content
+ const layout = await Promise.all(
+ content.layout.map(async (chart) => {
+ if (!chart.attribute.startsWith('snippet_')) return chart
+
+ const snippet = await getContentById(
+ { projectRef, id: chart.id },
+ abortSignal,
+ authHeaders
+ ).catch(() => null)
+
+ const sql =
+ snippet?.type === 'sql'
+ ? (snippet.content as SqlSnippets.Content).unchecked_sql
+ : undefined
+
+ return { ...chart, sql }
+ })
+ )
+
+ return {
+ id: report.id,
+ name: report.name,
+ description: report.description,
+ visibility: report.visibility,
+ period_start: content.period_start,
+ period_end: content.period_end,
+ interval: content.interval,
+ layout,
+ }
+ })
+}
diff --git a/apps/studio/lib/ai/tools/get-report.ts b/apps/studio/lib/ai/tools/get-report.ts
new file mode 100644
index 00000000000..c61a8fa3fef
--- /dev/null
+++ b/apps/studio/lib/ai/tools/get-report.ts
@@ -0,0 +1,59 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+
+const inputSchema = z.object({
+ id: z.string().describe('The id of the report to fetch.'),
+})
+
+const timePeriodSchema = z.object({
+ time_period: z.string().optional(),
+ date: z.string().optional(),
+})
+
+const chartConfigSchema = z.object({
+ view: z.string().optional(),
+ type: z.string().optional(),
+ cumulative: z.boolean().optional(),
+ xKey: z.string().optional(),
+ yKey: z.string().optional(),
+ showLabels: z.boolean().optional(),
+ showGrid: z.boolean().optional(),
+ logScale: z.boolean().optional(),
+})
+
+const chartSchema = z.object({
+ id: z.string(),
+ x: z.number(),
+ y: z.number(),
+ w: z.number(),
+ h: z.number(),
+ label: z.string(),
+ attribute: z.string(),
+ provider: z.string(),
+ chart_type: z.string(),
+ chartConfig: chartConfigSchema.optional(),
+ sql: z.string().optional(),
+})
+
+const outputSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ description: z.string().nullish(),
+ visibility: z.string(),
+ period_start: timePeriodSchema,
+ period_end: timePeriodSchema,
+ interval: z.string(),
+ layout: z.array(chartSchema),
+})
+
+export const contract = {
+ name: 'get_report',
+ description:
+ 'Get a single custom report by id, including the resolved SQL for any SQL-based chart blocks it contains.',
+ inputSchema,
+ outputSchema,
+ minOptInLevel: 'schema',
+ needsApproval: false,
+ toModelOutput: (output: z.infer<typeof outputSchema>) => output,
+} as const satisfies ToolContract
diff --git a/apps/studio/lib/ai/tools/incident-tools.ts b/apps/studio/lib/ai/tools/incident-tools.ts
index 8997878f97f..e95553cdb38 100644
--- a/apps/studio/lib/ai/tools/incident-tools.ts
+++ b/apps/studio/lib/ai/tools/incident-tools.ts
@@ -1,120 +1,10 @@
-import { tool } from 'ai'
-import { IS_PLATFORM } from 'common'
-import { z } from 'zod'
-
-import {
- StatusPageResponseSchema,
- type AffectedComponent,
-} from '@/lib/status-page/status-page.schema'
-
-const NO_ACTIVE_INCIDENTS_MESSAGE = 'No active incidents.'
-const DEFAULT_STATUS_PAGE_URL = 'https://status.supabase.com'
-
-function timeoutSignal(abortSignal?: AbortSignal) {
- return abortSignal
- ? AbortSignal.any([abortSignal, AbortSignal.timeout(5_000)])
- : AbortSignal.timeout(5_000)
-}
-
-function formatAffectedComponents(affectedComponents: Array<AffectedComponent>): Array<string> {
- return affectedComponents.map((component) =>
- component.group_name ? `${component.group_name} / ${component.name}` : component.name
- )
-}
-
-function buildActiveIncidentsMessage(
- incidentCount: number,
- maintenanceCount: number,
- statusPageUrl: string
-) {
- const parts: Array<string> = []
- if (incidentCount > 0) {
- parts.push(`${incidentCount} active incident${incidentCount === 1 ? '' : 's'}`)
- }
- if (maintenanceCount > 0) {
- parts.push(`${maintenanceCount} in-progress maintenance${maintenanceCount === 1 ? '' : 's'}`)
- }
-
- const totalCount = incidentCount + maintenanceCount
-
- return `There ${totalCount === 1 ? 'is' : 'are'} ${parts.join(' and ')} on Supabase infrastructure. If the user's issue appears related, inform them about the ongoing issue(s) and direct them to ${statusPageUrl} for real-time updates.`
-}
+import { createTool as createGetActiveIncidentsTool } from './get-active-incidents.server'
+import type { ToolContext } from './types'
/**
- * Creates incident-related tools for the AI assistant.
- *
* @param baseUrl - The base URL for API requests (e.g., https://supabase.com/dashboard)
* This should be the public URL to leverage CDN caching.
*/
-export const getIncidentTools = ({ baseUrl }: { baseUrl: string }) => ({
- get_active_incidents: tool({
- description:
- 'Check for active incidents. Use this tool when the user reports issues with any Supabase service, including the database, authentication, realtime, storage, and functions. Possible problems include, but are not limited to, connection issues, timeouts, service unavailability, authentication failures, or unexpected errors.',
- inputSchema: z.object({}),
- execute: async (_input, { abortSignal }) => {
- if (!IS_PLATFORM) {
- return {
- incidents: [],
- message: 'Incident checking is only available on Supabase platform.',
- }
- }
-
- const response = await fetch(`${baseUrl}/api/status-page`, {
- signal: timeoutSignal(abortSignal),
- })
-
- if (!response.ok) {
- throw new Error(`Failed to fetch status page: ${response.status}`)
- }
-
- const json = await response.json()
- const parseResult = StatusPageResponseSchema.safeParse(json)
-
- if (!parseResult.success) {
- throw new Error(`Failed to parse status page response: ${parseResult.error.message}`)
- }
-
- const { data } = parseResult
-
- const incidents = data.ongoing_incidents
- .filter((incident) => incident.visible)
- .map((incident) => ({
- kind: 'incident' as const,
- name: incident.name,
- status: incident.status,
- impact: incident.current_worst_impact,
- affected_components: formatAffectedComponents(incident.affected_components),
- last_update_message: incident.last_update_message ?? null,
- url: incident.url,
- }))
-
- const maintenances = data.in_progress_maintenances
- .filter((maintenance) => maintenance.visible)
- .map((maintenance) => ({
- kind: 'maintenance' as const,
- name: maintenance.name,
- status: maintenance.status,
- affected_components: formatAffectedComponents(maintenance.affected_components),
- last_update_message: maintenance.last_update_message ?? null,
- url: maintenance.url,
- started_at: maintenance.started_at,
- }))
-
- const combined = [...incidents, ...maintenances]
-
- if (combined.length === 0) {
- return {
- incidents: [],
- message: NO_ACTIVE_INCIDENTS_MESSAGE,
- }
- }
-
- const statusPageUrl = data.page_url || DEFAULT_STATUS_PAGE_URL
-
- return {
- incidents: combined,
- message: buildActiveIncidentsMessage(incidents.length, maintenances.length, statusPageUrl),
- }
- },
- }),
+export const getIncidentTools = ({ baseUrl, ...ctx }: ToolContext & { baseUrl: string }) => ({
+ get_active_incidents: createGetActiveIncidentsTool({ ...ctx, baseUrl }),
})
diff --git a/apps/studio/lib/ai/tools/list-policies.server.ts b/apps/studio/lib/ai/tools/list-policies.server.ts
new file mode 100644
index 00000000000..ed2a8a25d89
--- /dev/null
+++ b/apps/studio/lib/ai/tools/list-policies.server.ts
@@ -0,0 +1,34 @@
+import { stripIndent } from 'common-tags'
+
+import { getAuthHeaders } from './auth-headers'
+import { contract } from './list-policies'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+import { getDatabasePolicies } from '@/data/database-policies/database-policies-query'
+
+export const createTool: ToolFactory<typeof contract> = (ctx) => {
+ const { projectRef, connectionString } = ctx
+ const authHeaders = getAuthHeaders(ctx.authorization)
+
+ return toolFromContract(contract, ctx, async ({ schemas }, { abortSignal }) => {
+ const data = await getDatabasePolicies(
+ { projectRef, connectionString, schemas },
+ abortSignal,
+ authHeaders
+ )
+
+ return data
+ .map(
+ (policy) => stripIndent`
+ Policy Name: "${policy.name}"
+ Table: "${policy.table}"
+ Action: ${policy.action}
+ Roles: ${policy.roles.join(', ')}
+ Command: ${policy.command}
+ Definition: ${policy.definition}
+ ${policy.check ? `Check: ${policy.check}` : ''}
+ `
+ )
+ .join('\n')
+ })
+}
diff --git a/apps/studio/lib/ai/tools/list-policies.ts b/apps/studio/lib/ai/tools/list-policies.ts
new file mode 100644
index 00000000000..f6d9d1ea1fc
--- /dev/null
+++ b/apps/studio/lib/ai/tools/list-policies.ts
@@ -0,0 +1,17 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+
+const inputSchema = z.object({
+ schemas: z.array(z.string()).describe('The schema names to get the policies for'),
+})
+
+export const contract = {
+ name: 'list_policies',
+ description: 'Get existing RLS policies for a given schema',
+ inputSchema,
+ outputSchema: z.string(),
+ minOptInLevel: 'schema',
+ needsApproval: false,
+ toModelOutput: (output: string) => output,
+} as const satisfies ToolContract
diff --git a/apps/studio/lib/ai/tools/list-reports.server.ts b/apps/studio/lib/ai/tools/list-reports.server.ts
new file mode 100644
index 00000000000..dc5759c7425
--- /dev/null
+++ b/apps/studio/lib/ai/tools/list-reports.server.ts
@@ -0,0 +1,28 @@
+import { getAuthHeaders } from './auth-headers'
+import { contract } from './list-reports'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+import { getContent } from '@/data/content/content-query'
+import type { Dashboards } from '@/types'
+
+export const createTool: ToolFactory<typeof contract> = (ctx) => {
+ const { projectRef } = ctx
+ const authHeaders = getAuthHeaders(ctx.authorization)
+
+ return toolFromContract(contract, ctx, async ({ limit }, { abortSignal }) => {
+ const { content } = await getContent(
+ { projectRef, type: 'report', limit },
+ abortSignal,
+ authHeaders
+ )
+
+ return content.map((report) => ({
+ id: report.id,
+ name: report.name,
+ description: report.description,
+ visibility: report.visibility,
+ updated_at: report.updated_at,
+ chart_count: (report.content as Dashboards.Content).layout?.length ?? 0,
+ }))
+ })
+}
diff --git a/apps/studio/lib/ai/tools/list-reports.ts b/apps/studio/lib/ai/tools/list-reports.ts
new file mode 100644
index 00000000000..483d009ebd4
--- /dev/null
+++ b/apps/studio/lib/ai/tools/list-reports.ts
@@ -0,0 +1,34 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+
+const inputSchema = z.object({
+ limit: z
+ .number()
+ .int()
+ .positive()
+ .max(100)
+ .default(20)
+ .describe('Max number of reports to return.'),
+})
+
+const outputSchema = z.array(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ description: z.string().nullish(),
+ visibility: z.string(),
+ updated_at: z.string(),
+ chart_count: z.number(),
+ })
+)
+
+export const contract = {
+ name: 'list_reports',
+ description: 'List the custom reports saved for this project',
+ inputSchema,
+ outputSchema,
+ minOptInLevel: 'schema',
+ needsApproval: false,
+ toModelOutput: (output: z.infer<typeof outputSchema>) => output,
+} as const satisfies ToolContract
diff --git a/apps/studio/lib/ai/tools/registry.test.ts b/apps/studio/lib/ai/tools/registry.test.ts
index 545d54845a3..39f81e3ac9e 100644
--- a/apps/studio/lib/ai/tools/registry.test.ts
+++ b/apps/studio/lib/ai/tools/registry.test.ts
@@ -106,7 +106,7 @@ describe('notebook mutation contracts', () => {
)
})
-describe('read-only notebook contracts', () => {
+describe('read-only contracts', () => {
const cells = [
{ _tag: 'markdown_cell', _id: 'cell-1', text: '# Signup funnel' },
{
@@ -136,6 +136,54 @@ describe('read-only notebook contracts', () => {
],
cursor: 'next',
},
+ list_policies: 'Policy Name: "Users can read own rows"',
+ list_reports: [
+ {
+ id: 'report-1',
+ name: 'Home',
+ description: null,
+ visibility: 'project',
+ updated_at: '2026-01-01T00:00:00.000Z',
+ chart_count: 1,
+ },
+ ],
+ get_report: {
+ id: 'report-1',
+ name: 'Home',
+ visibility: 'project',
+ period_start: { time_period: '7d' },
+ period_end: { time_period: 'today' },
+ interval: '1d',
+ layout: [
+ {
+ id: 'chart-1',
+ x: 0,
+ y: 0,
+ w: 6,
+ h: 4,
+ label: 'Signups',
+ attribute: 'snippet_chart-1',
+ provider: 'daily-stats',
+ chart_type: 'bar',
+ sql: 'select 1',
+ chartConfig: { type: 'bar', cumulative: false, xKey: 'day', yKey: 'count' },
+ },
+ ],
+ },
+ get_active_incidents: {
+ incidents: [
+ {
+ kind: 'incident',
+ name: 'Elevated errors',
+ status: 'investigating',
+ impact: 'partial_outage',
+ affected_components: ['Database / API'],
+ last_update_message: null,
+ url: 'https://status.supabase.com/incidents/1',
+ },
+ ],
+ message: 'There is 1 active incident on Supabase infrastructure.',
+ },
get_notebook: {
id: 'notebook-1',
name: 'Signup funnel',
@@ -167,9 +215,9 @@ describe('read-only notebook contracts', () => {
})
it('drops an output that does not match the schema', () => {
- expect(
- sanitizeContractPart({ ...part, output: 'oops' } as ToolUIPart, 'schema')?.output
- ).toBe(undefined)
+ expect(sanitizeContractPart({ ...part, output: 12345 } as ToolUIPart, 'schema')?.output).toBe(
+ undefined
+ )
})
it.each(levels)('shows the live output unchanged at %s', (level) => {
@@ -178,6 +226,20 @@ describe('read-only notebook contracts', () => {
})
})
+ it.each(['escalate_to_human', 'resolve_support_conversation'] as const)(
+ '%s output is limited to status on replay',
+ (name) => {
+ const part = {
+ type: `tool-${name}`,
+ toolCallId: 'call-6',
+ state: 'output-available',
+ input: {},
+ output: { status: 'sent', extra: 'ignored' },
+ } as ToolUIPart
+ expect(sanitizeContractPart(part, 'disabled')?.output).toEqual({ status: 'sent' })
+ }
+ )
+
it('accepts a notebook list without a cursor or description', () => {
const output = {
notebooks: [
diff --git a/apps/studio/lib/ai/tools/registry.ts b/apps/studio/lib/ai/tools/registry.ts
index 08feb9ca9b1..d7af98698f5 100644
--- a/apps/studio/lib/ai/tools/registry.ts
+++ b/apps/studio/lib/ai/tools/registry.ts
@@ -4,12 +4,18 @@ import type { ToolName } from '../tool-filter'
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 getNotebook } from './get-notebook'
+import { contract as getReport } from './get-report'
import { contract as listDatabases } from './list-databases'
import { contract as listNotebooks } from './list-notebooks'
+import { contract as listPolicies } from './list-policies'
+import { contract as listReports } from './list-reports'
import { contract as loadKnowledge } from './load-knowledge'
import { contract as renameChat } from './rename-chat'
+import { contract as resolveSupportConversation } from './resolve-support-conversation'
import { contract as runNotebook } from './run-notebook'
import type { ToolContract, ToolContractInput, ToolContractOutput } from './types'
import { contract as updateNotebook } from './update-notebook'
@@ -23,12 +29,18 @@ 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_notebooks: listNotebooks,
+ list_policies: listPolicies,
+ list_reports: listReports,
load_knowledge: loadKnowledge,
rename_chat: renameChat,
+ resolve_support_conversation: resolveSupportConversation,
run_notebook: runNotebook,
update_notebook: updateNotebook,
} as const satisfies Partial<Record<ToolName, ToolContract>>
diff --git a/apps/studio/lib/ai/tools/report-tools.test.ts b/apps/studio/lib/ai/tools/report-tools.test.ts
index ae421dc538a..d83b4f1613f 100644
--- a/apps/studio/lib/ai/tools/report-tools.test.ts
+++ b/apps/studio/lib/ai/tools/report-tools.test.ts
@@ -18,8 +18,8 @@ describe('ai/tools/report-tools', () => {
it('should not require approval to read reports', () => {
const tools = getReportTools()
- expect(tools.list_reports.needsApproval).toBeUndefined()
- expect(tools.get_report.needsApproval).toBeUndefined()
+ expect(tools.list_reports.needsApproval).toBe(false)
+ expect(tools.get_report.needsApproval).toBe(false)
})
})
diff --git a/apps/studio/lib/ai/tools/report-tools.ts b/apps/studio/lib/ai/tools/report-tools.ts
index d80a365014c..34fdb27d366 100644
--- a/apps/studio/lib/ai/tools/report-tools.ts
+++ b/apps/studio/lib/ai/tools/report-tools.ts
@@ -1,89 +1,8 @@
-import { tool } from 'ai'
-import { z } from 'zod'
-
-import { getAuthHeaders } from './auth-headers'
+import { createTool as createGetReportTool } from './get-report.server'
+import { createTool as createListReportsTool } from './list-reports.server'
import type { ToolContext } from './types'
-import { getContentById } from '@/data/content/content-id-query'
-import { getContent } from '@/data/content/content-query'
-import type { Dashboards, SqlSnippets } from '@/types'
-
-export const getReportTools = (ctx: ToolContext = {}) => {
- const { projectRef, authorization } = ctx
- const authHeaders = getAuthHeaders(authorization)
-
- return {
- list_reports: tool({
- description: 'List the custom reports saved for this project',
- inputSchema: z.object({
- limit: z
- .number()
- .int()
- .positive()
- .max(100)
- .default(20)
- .describe('Max number of reports to return.'),
- }),
- execute: async ({ limit }, { abortSignal }) => {
- const { content } = await getContent(
- { projectRef, type: 'report', limit },
- abortSignal,
- authHeaders
- )
-
- return content.map((report) => ({
- id: report.id,
- name: report.name,
- description: report.description,
- visibility: report.visibility,
- updated_at: report.updated_at,
- chart_count: (report.content as Dashboards.Content).layout?.length ?? 0,
- }))
- },
- }),
- get_report: tool({
- description:
- 'Get a single custom report by id, including the resolved SQL for any SQL-based chart blocks it contains.',
- inputSchema: z.object({
- id: z.string().describe('The id of the report to fetch.'),
- }),
- execute: async ({ id }, { abortSignal }) => {
- const report = await getContentById({ projectRef, id }, abortSignal, authHeaders)
- if (report.type !== 'report') {
- throw new Error(`Content ${id} is not a report (type: ${report.type})`)
- }
-
- const content = report.content as Dashboards.Content
- const layout = await Promise.all(
- content.layout.map(async (chart) => {
- if (!chart.attribute.startsWith('snippet_')) return chart
-
- // A SQL-block chart's `id` is the id of its linked `type: 'sql'` content row.
- const snippet = await getContentById(
- { projectRef, id: chart.id },
- abortSignal,
- authHeaders
- ).catch(() => null)
-
- const sql =
- snippet?.type === 'sql'
- ? (snippet.content as SqlSnippets.Content).unchecked_sql
- : undefined
-
- return { ...chart, sql }
- })
- )
- return {
- id: report.id,
- name: report.name,
- description: report.description,
- visibility: report.visibility,
- period_start: content.period_start,
- period_end: content.period_end,
- interval: content.interval,
- layout,
- }
- },
- }),
- }
-}
+export const getReportTools = (ctx: ToolContext = {}) => ({
+ list_reports: createListReportsTool(ctx),
+ get_report: createGetReportTool(ctx),
+})
diff --git a/apps/studio/lib/ai/tools/resolve-support-conversation.server.ts b/apps/studio/lib/ai/tools/resolve-support-conversation.server.ts
new file mode 100644
index 00000000000..760c3a39537
--- /dev/null
+++ b/apps/studio/lib/ai/tools/resolve-support-conversation.server.ts
@@ -0,0 +1,6 @@
+import { contract } from './resolve-support-conversation'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+
+export const createTool: ToolFactory<typeof contract> = (ctx) =>
+ toolFromContract(contract, ctx, async () => ({ status: 'Resolve request sent to client.' }))
diff --git a/apps/studio/lib/ai/tools/resolve-support-conversation.ts b/apps/studio/lib/ai/tools/resolve-support-conversation.ts
new file mode 100644
index 00000000000..8dcc1a2c4ce
--- /dev/null
+++ b/apps/studio/lib/ai/tools/resolve-support-conversation.ts
@@ -0,0 +1,22 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+
+const inputSchema = z.object({
+ summary: z
+ .string()
+ .trim()
+ .min(1, 'Resolution summary is required')
+ .describe('A concise summary of the fix or guidance that resolved the support request.'),
+})
+
+export const contract = {
+ name: 'resolve_support_conversation',
+ description:
+ 'Mark this support conversation as resolved when the issue appears solved from the user perspective.',
+ inputSchema,
+ outputSchema: z.object({ status: z.string() }),
+ minOptInLevel: null,
+ needsApproval: false,
+ toModelOutput: ({ status }) => ({ status }),
+} as const satisfies ToolContract
diff --git a/apps/studio/lib/ai/tools/schema-tools.ts b/apps/studio/lib/ai/tools/schema-tools.ts
index eea9451ec9d..093bd5689a9 100644
--- a/apps/studio/lib/ai/tools/schema-tools.ts
+++ b/apps/studio/lib/ai/tools/schema-tools.ts
@@ -1,46 +1,6 @@
-import { tool } from 'ai'
-import { z } from 'zod'
-
-import { getAuthHeaders } from './auth-headers'
+import { createTool as createListPoliciesTool } from './list-policies.server'
import type { ToolContext } from './types'
-import { getDatabasePolicies } from '@/data/database-policies/database-policies-query'
-
-export const getSchemaTools = ({
- projectRef,
- connectionString,
- authorization,
-}: ToolContext & { projectRef: string; connectionString: string }) => ({
- list_policies: tool({
- description: 'Get existing RLS policies for a given schema',
- inputSchema: z.object({
- schemas: z.array(z.string()).describe('The schema names to get the policies for'),
- }),
- execute: async ({ schemas }, { abortSignal }) => {
- const data = await getDatabasePolicies(
- {
- projectRef,
- connectionString,
- schemas,
- },
- abortSignal,
- getAuthHeaders(authorization)
- )
-
- const formattedPolicies = data
- .map(
- (policy) => `
- Policy Name: "${policy.name}"
- Table: "${policy.table}"
- Action: ${policy.action}
- Roles: ${policy.roles.join(', ')}
- Command: ${policy.command}
- Definition: ${policy.definition}
- ${policy.check ? `Check: ${policy.check}` : ''}
- `
- )
- .join('\n')
- return formattedPolicies
- },
- }),
+export const getSchemaTools = (ctx: ToolContext = {}) => ({
+ list_policies: createListPoliciesTool(ctx),
})
diff --git a/apps/studio/lib/ai/tools/support-tools.ts b/apps/studio/lib/ai/tools/support-tools.ts
index 352875c369a..1c8dabe6b3b 100644
--- a/apps/studio/lib/ai/tools/support-tools.ts
+++ b/apps/studio/lib/ai/tools/support-tools.ts
@@ -1,33 +1,8 @@
-import { tool } from 'ai'
-import { z } from 'zod'
+import { createTool as createEscalateToHumanTool } from './escalate-to-human.server'
+import { createTool as createResolveSupportConversationTool } from './resolve-support-conversation.server'
+import type { ToolContext } from './types'
-export const getSupportLifecycleTools = () => ({
- escalate_to_human: tool({
- description:
- 'Escalate this support conversation to a human support agent when the assistant cannot resolve the issue.',
- inputSchema: z.object({
- reason: z
- .string()
- .trim()
- .min(1, 'Escalation reason is required')
- .describe('A short reason that explains why this support chat should be escalated.'),
- }),
- execute: async () => {
- return { status: 'Escalation request sent to client.' }
- },
- }),
- resolve_support_conversation: tool({
- description:
- 'Mark this support conversation as resolved when the issue appears solved from the user perspective.',
- inputSchema: z.object({
- summary: z
- .string()
- .trim()
- .min(1, 'Resolution summary is required')
- .describe('A concise summary of the fix or guidance that resolved the support request.'),
- }),
- execute: async () => {
- return { status: 'Resolve request sent to client.' }
- },
- }),
+export const getSupportLifecycleTools = (ctx: ToolContext = {}) => ({
+ escalate_to_human: createEscalateToHumanTool(ctx),
+ resolve_support_conversation: createResolveSupportConversationTool(ctx),
})
diff --git a/apps/studio/lib/ai/tools/types.ts b/apps/studio/lib/ai/tools/types.ts
index e5832cceacd..fc897faf9d6 100644
--- a/apps/studio/lib/ai/tools/types.ts
+++ b/apps/studio/lib/ai/tools/types.ts
@@ -8,6 +8,8 @@ export type ToolContext = {
connectionString?: string
authorization?: string
aiOptInLevel?: AiOptInLevel
+ /** Public dashboard URL, used by tools that call Studio's own API routes. */
+ baseUrl?: string
}
/**