Skip to content

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

refactor: migrate list_databases, list_notebooks, and get_notebook to tool contracts (#51937)

Charis2d79674ab36f
diff --git a/apps/studio/lib/ai/tool-filter.test.ts b/apps/studio/lib/ai/tool-filter.test.ts
index 244c0858328..e391062c41b 100644
--- a/apps/studio/lib/ai/tool-filter.test.ts
+++ b/apps/studio/lib/ai/tool-filter.test.ts
@@ -11,6 +11,9 @@ import {
} from './tool-filter'
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 listDatabasesContract } from './tools/list-databases'
+import { contract as listNotebooksContract } from './tools/list-notebooks'
import { contract as runNotebookContract } from './tools/run-notebook'
import { contract as updateNotebookContract } from './tools/update-notebook'
@@ -18,7 +21,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_notebooks']).toBe(TOOL_CATEGORIES.SCHEMA)
+ expect(TOOL_CATEGORY_MAP['list_reports']).toBe(TOOL_CATEGORIES.SCHEMA)
})
})
@@ -26,6 +29,9 @@ describe('tools with a contract', () => {
const contracts = {
create_notebook: createNotebookContract,
delete_notebook: deleteNotebookContract,
+ get_notebook: getNotebookContract,
+ list_databases: listDatabasesContract,
+ list_notebooks: listNotebooksContract,
run_notebook: runNotebookContract,
update_notebook: updateNotebookContract,
}
diff --git a/apps/studio/lib/ai/tool-filter.ts b/apps/studio/lib/ai/tool-filter.ts
index e49c107b720..e25ae44002f 100644
--- a/apps/studio/lib/ai/tool-filter.ts
+++ b/apps/studio/lib/ai/tool-filter.ts
@@ -111,9 +111,6 @@ export const TOOL_CATEGORY_MAP: Record<Exclude<ToolName, ContractToolName>, Tool
list_policies: TOOL_CATEGORIES.SCHEMA,
list_reports: TOOL_CATEGORIES.SCHEMA,
get_report: TOOL_CATEGORIES.SCHEMA,
- list_databases: TOOL_CATEGORIES.SCHEMA,
- list_notebooks: TOOL_CATEGORIES.SCHEMA,
- get_notebook: TOOL_CATEGORIES.SCHEMA,
getSchemaTables: TOOL_CATEGORIES.SCHEMA,
getRlsKnowledge: TOOL_CATEGORIES.SCHEMA,
getFunctions: TOOL_CATEGORIES.SCHEMA,
diff --git a/apps/studio/lib/ai/tools/get-notebook.server.ts b/apps/studio/lib/ai/tools/get-notebook.server.ts
new file mode 100644
index 00000000000..efefb5671f7
--- /dev/null
+++ b/apps/studio/lib/ai/tools/get-notebook.server.ts
@@ -0,0 +1,24 @@
+import { getAuthHeaders } from './auth-headers'
+import { contract } from './get-notebook'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+import { getNotebook } from '@/data/content/notebooks/notebook-query'
+import { toWireNotebook } from '@/data/content/notebooks/notebook-schema'
+
+export const createTool: ToolFactory<typeof contract> = (ctx) => {
+ const { projectRef } = ctx
+ const authHeaders = getAuthHeaders(ctx.authorization)
+
+ return toolFromContract(contract, ctx, async ({ id }, { abortSignal }) => {
+ const notebook = await getNotebook({ projectRef, id }, abortSignal, authHeaders)
+
+ return {
+ id: notebook.id,
+ name: notebook.name,
+ description: notebook.description,
+ visibility: notebook.visibility,
+ updated_at: notebook.updated_at,
+ cells: toWireNotebook(notebook.content).cells,
+ }
+ })
+}
diff --git a/apps/studio/lib/ai/tools/get-notebook.ts b/apps/studio/lib/ai/tools/get-notebook.ts
new file mode 100644
index 00000000000..ec0f5060c4a
--- /dev/null
+++ b/apps/studio/lib/ai/tools/get-notebook.ts
@@ -0,0 +1,28 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+import { notebookSchema } from '@/data/content/notebooks/notebook-schema'
+
+const inputSchema = z.object({
+ id: z.string().describe('The id of the notebook to fetch.'),
+})
+
+const outputSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ description: z.string().nullish(),
+ visibility: z.string(),
+ updated_at: z.string(),
+ cells: notebookSchema.shape.cells,
+})
+
+export const contract = {
+ name: 'get_notebook',
+ description:
+ 'Get a single notebook by id, including the markdown text and resolved SQL of every cell.',
+ 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/list-databases.server.ts b/apps/studio/lib/ai/tools/list-databases.server.ts
new file mode 100644
index 00000000000..a87f4d3f345
--- /dev/null
+++ b/apps/studio/lib/ai/tools/list-databases.server.ts
@@ -0,0 +1,23 @@
+import { getAuthHeaders } from './auth-headers'
+import { contract } from './list-databases'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+import { getReadReplicas } from '@/data/read-replicas/replicas-query'
+
+export const createTool: ToolFactory<typeof contract> = (ctx) => {
+ const { projectRef } = ctx
+ const authHeaders = getAuthHeaders(ctx.authorization)
+
+ return toolFromContract(contract, ctx, async (_input, { abortSignal }) => {
+ const databases = await getReadReplicas({ projectRef }, abortSignal, authHeaders)
+
+ return {
+ databases: (databases ?? []).map((database) => ({
+ identifier: database.identifier,
+ is_primary: database.identifier === projectRef,
+ region: database.region,
+ status: database.status,
+ })),
+ }
+ })
+}
diff --git a/apps/studio/lib/ai/tools/list-databases.ts b/apps/studio/lib/ai/tools/list-databases.ts
new file mode 100644
index 00000000000..f84a3499d4f
--- /dev/null
+++ b/apps/studio/lib/ai/tools/list-databases.ts
@@ -0,0 +1,26 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+
+const inputSchema = z.object({})
+
+const outputSchema = z.object({
+ databases: z.array(
+ z.object({
+ identifier: z.string(),
+ is_primary: z.boolean(),
+ region: z.string(),
+ status: z.string(),
+ })
+ ),
+})
+
+export const contract = {
+ name: 'list_databases',
+ description: 'List the databases available for this project — the primary and any read replicas.',
+ 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/list-notebooks.server.ts b/apps/studio/lib/ai/tools/list-notebooks.server.ts
new file mode 100644
index 00000000000..4be75415913
--- /dev/null
+++ b/apps/studio/lib/ai/tools/list-notebooks.server.ts
@@ -0,0 +1,31 @@
+import { getAuthHeaders } from './auth-headers'
+import { contract } from './list-notebooks'
+import { toolFromContract } from './tool-from-contract'
+import type { ToolFactory } from './types'
+import { getContent } from '@/data/content/content-infinite-query'
+import type { Notebooks } from '@/types'
+
+export const createTool: ToolFactory<typeof contract> = (ctx) => {
+ const { projectRef } = ctx
+ const authHeaders = getAuthHeaders(ctx.authorization)
+
+ return toolFromContract(contract, ctx, async ({ cursor, limit, sort_by }, { abortSignal }) => {
+ const { content, cursor: nextCursor } = await getContent(
+ { projectRef, type: 'notebook', limit, cursor, sort: sort_by },
+ abortSignal,
+ authHeaders
+ )
+
+ return {
+ notebooks: content.map((notebook) => ({
+ id: notebook.id,
+ name: notebook.name,
+ description: notebook.description,
+ visibility: notebook.visibility,
+ updated_at: notebook.updated_at,
+ cell_count: (notebook.content as Notebooks.Content).cells.length,
+ })),
+ cursor: nextCursor,
+ }
+ })
+}
diff --git a/apps/studio/lib/ai/tools/list-notebooks.ts b/apps/studio/lib/ai/tools/list-notebooks.ts
new file mode 100644
index 00000000000..c50cdbfa1f2
--- /dev/null
+++ b/apps/studio/lib/ai/tools/list-notebooks.ts
@@ -0,0 +1,47 @@
+import { z } from 'zod'
+
+import type { ToolContract } from './types'
+
+const inputSchema = z.object({
+ cursor: z
+ .string()
+ .optional()
+ .describe('Cursor from a previous call, used to fetch the next page.'),
+ limit: z
+ .number()
+ .int()
+ .positive()
+ .max(100)
+ .default(20)
+ .describe('Max number of notebooks to return.'),
+ sort_by: z
+ .enum(['name', 'inserted_at'])
+ .optional()
+ .describe(
+ 'Field to sort notebooks by. There is no "updated_at" sort — use "inserted_at" for creation order.'
+ ),
+})
+
+const outputSchema = z.object({
+ notebooks: z.array(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ description: z.string().nullish(),
+ visibility: z.string(),
+ updated_at: z.string(),
+ cell_count: z.number(),
+ })
+ ),
+ cursor: z.string().optional(),
+})
+
+export const contract = {
+ name: 'list_notebooks',
+ description: 'List the notebooks 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/notebook-tools.test.ts b/apps/studio/lib/ai/tools/notebook-tools.test.ts
index 451c0e7a039..11c6c5c0fb5 100644
--- a/apps/studio/lib/ai/tools/notebook-tools.test.ts
+++ b/apps/studio/lib/ai/tools/notebook-tools.test.ts
@@ -129,8 +129,9 @@ describe('ai/tools/notebook-tools', () => {
it('should not require approval to read notebooks', () => {
const tools = getNotebookTools()
- expect(tools.list_notebooks.needsApproval).toBeUndefined()
- expect(tools.get_notebook.needsApproval).toBeUndefined()
+ expect(tools.list_databases.needsApproval).toBe(false)
+ expect(tools.list_notebooks.needsApproval).toBe(false)
+ expect(tools.get_notebook.needsApproval).toBe(false)
})
it('should require approval to run, create, update, or delete a notebook', () => {
diff --git a/apps/studio/lib/ai/tools/notebook-tools.ts b/apps/studio/lib/ai/tools/notebook-tools.ts
index 07913af05c9..6bb60f0d9fc 100644
--- a/apps/studio/lib/ai/tools/notebook-tools.ts
+++ b/apps/studio/lib/ai/tools/notebook-tools.ts
@@ -1,102 +1,17 @@
-import { tool } from 'ai'
-import { z } from 'zod'
-
-import { getAuthHeaders } from './auth-headers'
import { createTool as createCreateNotebookTool } from './create-notebook.server'
import { createTool as createDeleteNotebookTool } from './delete-notebook.server'
+import { createTool as createGetNotebookTool } from './get-notebook.server'
+import { createTool as createListDatabasesTool } from './list-databases.server'
+import { createTool as createListNotebooksTool } from './list-notebooks.server'
import { createTool as createRunNotebookTool } from './run-notebook.server'
import type { ToolContext } from './types'
import { createTool as createUpdateNotebookTool } from './update-notebook.server'
-import { getContent } from '@/data/content/content-infinite-query'
-import { getNotebook } from '@/data/content/notebooks/notebook-query'
-import { toWireNotebook } from '@/data/content/notebooks/notebook-schema'
-import { getReadReplicas } from '@/data/read-replicas/replicas-query'
-import type { Notebooks } from '@/types'
export const getNotebookTools = (ctx: ToolContext = {}) => {
- const { projectRef, authorization } = ctx
- const authHeaders = getAuthHeaders(authorization)
-
return {
- list_databases: tool({
- description:
- 'List the databases available for this project — the primary and any read replicas.',
- inputSchema: z.object({}),
- execute: async (_input, { abortSignal }) => {
- const databases = await getReadReplicas({ projectRef }, abortSignal, authHeaders)
-
- return {
- databases: (databases ?? []).map((database) => ({
- identifier: database.identifier,
- is_primary: database.identifier === projectRef,
- region: database.region,
- status: database.status,
- })),
- }
- },
- }),
- list_notebooks: tool({
- description: 'List the notebooks saved for this project',
- inputSchema: z.object({
- cursor: z
- .string()
- .optional()
- .describe('Cursor from a previous call, used to fetch the next page.'),
- limit: z
- .number()
- .int()
- .positive()
- .max(100)
- .default(20)
- .describe('Max number of notebooks to return.'),
- sort_by: z
- .enum(['name', 'inserted_at'])
- .optional()
- .describe(
- 'Field to sort notebooks by. There is no "updated_at" sort — use "inserted_at" for creation order.'
- ),
- }),
- execute: async ({ cursor, limit, sort_by }, { abortSignal }) => {
- const { content, cursor: nextCursor } = await getContent(
- { projectRef, type: 'notebook', limit, cursor, sort: sort_by },
- abortSignal,
- authHeaders
- )
-
- return {
- notebooks: content.map((notebook) => ({
- id: notebook.id,
- name: notebook.name,
- description: notebook.description,
- visibility: notebook.visibility,
- updated_at: notebook.updated_at,
- cell_count: (notebook.content as Notebooks.Content).cells.length,
- })),
- cursor: nextCursor,
- }
- },
- }),
- get_notebook: tool({
- description:
- 'Get a single notebook by id, including the markdown text and resolved SQL of every cell.',
- inputSchema: z.object({
- id: z.string().describe('The id of the notebook to fetch.'),
- }),
- execute: async ({ id }, { abortSignal }) => {
- const notebook = await getNotebook({ projectRef, id }, abortSignal, authHeaders)
-
- // toWireNotebook discards the `unchecked_sql` brand for display purposes only — the
- // result is returned to the agent, never written back.
- return {
- id: notebook.id,
- name: notebook.name,
- description: notebook.description,
- visibility: notebook.visibility,
- updated_at: notebook.updated_at,
- cells: toWireNotebook(notebook.content).cells,
- }
- },
- }),
+ list_databases: createListDatabasesTool(ctx),
+ list_notebooks: createListNotebooksTool(ctx),
+ get_notebook: createGetNotebookTool(ctx),
run_notebook: createRunNotebookTool(ctx),
create_notebook: createCreateNotebookTool(ctx),
update_notebook: createUpdateNotebookTool(ctx),
diff --git a/apps/studio/lib/ai/tools/registry.test.ts b/apps/studio/lib/ai/tools/registry.test.ts
index c823ee22cd8..545d54845a3 100644
--- a/apps/studio/lib/ai/tools/registry.test.ts
+++ b/apps/studio/lib/ai/tools/registry.test.ts
@@ -2,7 +2,9 @@ import type { ToolUIPart } from 'ai'
import { describe, expect, expectTypeOf, it } from 'vitest'
import { INVALID_NOTEBOOK_RUN_OUTPUT_MESSAGE } from './notebook-run-output'
-import { sanitizeContractPart, type StudioUIMessage } from './registry'
+import { sanitizeContractPart, TOOL_CONTRACTS, type StudioUIMessage } from './registry'
+import type { ToolContract } from './types'
+import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
describe('TOOL_CONTRACTS', () => {
it('types contract tool parts on StudioUIMessage', () => {
@@ -103,3 +105,98 @@ describe('notebook mutation contracts', () => {
}
)
})
+
+describe('read-only notebook contracts', () => {
+ const cells = [
+ { _tag: 'markdown_cell', _id: 'cell-1', text: '# Signup funnel' },
+ {
+ _tag: 'database_cell',
+ _id: 'cell-2',
+ sql: 'select 1',
+ row_limit: 100,
+ view: 'table',
+ },
+ ]
+ const outputs = {
+ list_databases: {
+ databases: [
+ { identifier: 'ref', is_primary: true, region: 'us-east-1', status: 'ACTIVE_HEALTHY' },
+ ],
+ },
+ list_notebooks: {
+ notebooks: [
+ {
+ id: 'notebook-1',
+ name: 'Signup funnel',
+ description: null,
+ visibility: 'project',
+ updated_at: '2026-01-01T00:00:00.000Z',
+ cell_count: 2,
+ },
+ ],
+ cursor: 'next',
+ },
+ get_notebook: {
+ id: 'notebook-1',
+ name: 'Signup funnel',
+ description: 'About signups',
+ visibility: 'project',
+ updated_at: '2026-01-01T00:00:00.000Z',
+ cells,
+ },
+ }
+
+ const levels = [
+ 'disabled',
+ 'schema',
+ 'schema_and_log',
+ 'schema_and_log_and_data',
+ ] as const satisfies AiOptInLevel[]
+
+ describe.each(Object.entries(outputs))('%s', (name, output) => {
+ const part = {
+ type: `tool-${name}`,
+ toolCallId: 'call-4',
+ state: 'output-available',
+ input: {},
+ output,
+ } as ToolUIPart
+
+ it.each(levels)('shows the output unchanged on replay at %s', (level) => {
+ expect(sanitizeContractPart(part, level)?.output).toEqual(output)
+ })
+
+ it('drops an output that does not match the schema', () => {
+ expect(
+ sanitizeContractPart({ ...part, output: 'oops' } as ToolUIPart, 'schema')?.output
+ ).toBe(undefined)
+ })
+
+ it.each(levels)('shows the live output unchanged at %s', (level) => {
+ const contract: ToolContract = TOOL_CONTRACTS[name as keyof typeof outputs]
+ expect(contract.toModelOutput(output, level)).toEqual(output)
+ })
+ })
+
+ it('accepts a notebook list without a cursor or description', () => {
+ const output = {
+ notebooks: [
+ {
+ id: 'notebook-1',
+ name: 'Notebook',
+ visibility: 'project',
+ updated_at: '2026-01-01T00:00:00.000Z',
+ cell_count: 0,
+ },
+ ],
+ }
+ const part = {
+ type: 'tool-list_notebooks',
+ toolCallId: 'call-5',
+ state: 'output-available',
+ input: {},
+ output,
+ } as ToolUIPart
+ expect(sanitizeContractPart(part, 'schema')?.output).toEqual(output)
+ })
+})
diff --git a/apps/studio/lib/ai/tools/registry.ts b/apps/studio/lib/ai/tools/registry.ts
index 25c2ccd964c..08feb9ca9b1 100644
--- a/apps/studio/lib/ai/tools/registry.ts
+++ b/apps/studio/lib/ai/tools/registry.ts
@@ -5,6 +5,9 @@ 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 executeSql } from './execute-sql'
+import { contract as getNotebook } from './get-notebook'
+import { contract as listDatabases } from './list-databases'
+import { contract as listNotebooks } from './list-notebooks'
import { contract as loadKnowledge } from './load-knowledge'
import { contract as renameChat } from './rename-chat'
import { contract as runNotebook } from './run-notebook'
@@ -21,6 +24,9 @@ export const TOOL_CONTRACTS = {
delete_notebook: deleteNotebook,
deploy_edge_function: deployEdgeFunction,
execute_sql: executeSql,
+ get_notebook: getNotebook,
+ list_databases: listDatabases,
+ list_notebooks: listNotebooks,
load_knowledge: loadKnowledge,
rename_chat: renameChat,
run_notebook: runNotebook,