Skip to content

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

fix(studio): reject unknown database_identifier before writing a notebook (#49333)

Charisee59d28240a8
diff --git a/apps/studio/lib/ai/tools/notebook-tools.test.ts b/apps/studio/lib/ai/tools/notebook-tools.test.ts
index 918a702210d..7df9b8b72a6 100644
--- a/apps/studio/lib/ai/tools/notebook-tools.test.ts
+++ b/apps/studio/lib/ai/tools/notebook-tools.test.ts
@@ -11,6 +11,39 @@ import {
import type { AgentNotebook } from '@/data/content/notebooks/notebook-schema'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
+type DatabaseDetailResponse = components['schemas']['DatabaseDetailResponse']
+
+function mockDatabases(identifiers: string[]) {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref/databases',
+ response: () =>
+ HttpResponse.json<DatabaseDetailResponse[]>(
+ identifiers.map((identifier) => ({
+ identifier,
+ region: 'us-east-1',
+ status: 'ACTIVE_HEALTHY',
+ cloud_provider: 'AWS',
+ db_host: `db.${identifier}.supabase.co`,
+ db_name: 'postgres',
+ db_port: 5432,
+ db_user: 'postgres',
+ inserted_at: '2026-01-01T00:00:00.000Z',
+ restUrl: `https://${identifier}.supabase.co/rest/v1`,
+ size: 't4g.micro',
+ }))
+ ),
+ })
+}
+
+function mockCreateNotebookPut() {
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: () => new HttpResponse(null),
+ })
+}
+
const VALID_AGENT_CONTENT: AgentNotebook = {
schema_version: 1,
cells: [
@@ -432,6 +465,107 @@ describe('ai/tools/notebook-tools', () => {
expect(typeof sentBody?.id).toBe('string')
expect(result).toEqual({ id: sentBody?.id, name: 'Signup funnel' })
})
+
+ it('should throw an assistant-exposable error instead of PUTting when a database_cell carries an unknown database_identifier', async () => {
+ mockDatabases(['test-project', 'test-project-replica-1'])
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.create_notebook.execute) throw new Error('execute is undefined')
+
+ const execute = tools.create_notebook.execute(
+ {
+ name: 'Signup funnel',
+ content: {
+ schema_version: 1,
+ cells: [
+ {
+ _tag: 'database_cell',
+ sql: 'select 1',
+ row_limit: 100,
+ database_identifier: 'made-up-replica',
+ },
+ ],
+ },
+ },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+
+ await expect(execute).rejects.toThrow(/made-up-replica/)
+ await expect(execute).rejects.toBeInstanceOf(NotebookToolError)
+ await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })
+ })
+
+ it('should throw an assistant-exposable error instead of PUTting when a database_cell carries an empty database_identifier', async () => {
+ mockDatabases(['test-project', 'test-project-replica-1'])
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.create_notebook.execute) throw new Error('execute is undefined')
+
+ const execute = tools.create_notebook.execute(
+ {
+ name: 'Signup funnel',
+ content: {
+ schema_version: 1,
+ cells: [
+ {
+ _tag: 'database_cell',
+ sql: 'select 1',
+ row_limit: 100,
+ database_identifier: '',
+ },
+ ],
+ },
+ },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+
+ await expect(execute).rejects.toBeInstanceOf(NotebookToolError)
+ await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })
+ })
+
+ it('should succeed when a database_cell carries a database_identifier that matches a real database', async () => {
+ mockDatabases(['test-project', 'test-project-replica-1'])
+ mockCreateNotebookPut()
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.create_notebook.execute) throw new Error('execute is undefined')
+
+ await expect(
+ tools.create_notebook.execute(
+ {
+ name: 'Signup funnel',
+ content: {
+ schema_version: 1,
+ cells: [
+ {
+ _tag: 'database_cell',
+ sql: 'select 1',
+ row_limit: 100,
+ database_identifier: 'test-project-replica-1',
+ },
+ ],
+ },
+ },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+ ).resolves.toMatchObject({ name: 'Signup funnel' })
+ })
+
+ it('should succeed without ever calling the databases endpoint when no cell sets database_identifier', async () => {
+ mockCreateNotebookPut()
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.create_notebook.execute) throw new Error('execute is undefined')
+
+ // No mock registered for GET /platform/projects/:ref/databases: MSW fails the test
+ // on any unhandled request, so this also asserts the endpoint was never called.
+ await expect(
+ tools.create_notebook.execute(
+ { name: 'Signup funnel', content: VALID_AGENT_CONTENT },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+ ).resolves.toMatchObject({ name: 'Signup funnel' })
+ })
})
describe('update_notebook', () => {
@@ -540,6 +674,193 @@ describe('ai/tools/notebook-tools', () => {
await expect(execute).rejects.toBeInstanceOf(NotebookToolError)
await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })
})
+
+ it('should throw an assistant-exposable error instead of PUTting when a resulting database_cell carries an unknown database_identifier', async () => {
+ mockGetNotebook()
+ mockDatabases(['test-project'])
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.update_notebook.execute) throw new Error('execute is undefined')
+
+ const execute = tools.update_notebook.execute(
+ {
+ id: 'notebook-1',
+ expected_updated_at: '2026-01-01T00:00:00.000Z',
+ operations: [
+ {
+ _tag: 'replace_cell',
+ cell_id: 'cell-2',
+ cell: {
+ _tag: 'database_cell',
+ sql: 'select * from auth.users limit 100',
+ row_limit: 100,
+ database_identifier: 'made-up-replica',
+ },
+ },
+ ],
+ },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+
+ await expect(execute).rejects.toThrow(/made-up-replica/)
+ await expect(execute).rejects.toBeInstanceOf(NotebookToolError)
+ await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })
+ })
+
+ it('should succeed when a resulting database_cell carries a database_identifier that matches a real database', async () => {
+ mockGetNotebook()
+ mockDatabases(['test-project', 'test-project-replica-1'])
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: () => new HttpResponse(null),
+ })
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.update_notebook.execute) throw new Error('execute is undefined')
+
+ await expect(
+ tools.update_notebook.execute(
+ {
+ id: 'notebook-1',
+ expected_updated_at: '2026-01-01T00:00:00.000Z',
+ operations: [
+ {
+ _tag: 'replace_cell',
+ cell_id: 'cell-2',
+ cell: {
+ _tag: 'database_cell',
+ sql: 'select * from auth.users limit 100',
+ row_limit: 100,
+ database_identifier: 'test-project-replica-1',
+ },
+ },
+ ],
+ },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+ ).resolves.toMatchObject({ id: 'notebook-1', name: 'Signup funnel' })
+ })
+
+ it('should throw an assistant-exposable error instead of PUTting when an inserted database_cell carries an unknown database_identifier', async () => {
+ mockGetNotebook()
+ mockDatabases(['test-project'])
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.update_notebook.execute) throw new Error('execute is undefined')
+
+ const execute = tools.update_notebook.execute(
+ {
+ id: 'notebook-1',
+ expected_updated_at: '2026-01-01T00:00:00.000Z',
+ operations: [
+ {
+ _tag: 'insert_cell',
+ after_cell_id: 'cell-1',
+ cell: {
+ _tag: 'database_cell',
+ sql: 'select * from auth.users limit 100',
+ row_limit: 100,
+ database_identifier: 'made-up-replica',
+ },
+ },
+ ],
+ },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+
+ await expect(execute).rejects.toThrow(/made-up-replica/)
+ await expect(execute).rejects.toBeInstanceOf(NotebookToolError)
+ await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })
+ })
+
+ it('should succeed when an inserted database_cell carries a database_identifier that matches a real database', async () => {
+ mockGetNotebook()
+ mockDatabases(['test-project', 'test-project-replica-1'])
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: () => new HttpResponse(null),
+ })
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.update_notebook.execute) throw new Error('execute is undefined')
+
+ await expect(
+ tools.update_notebook.execute(
+ {
+ id: 'notebook-1',
+ expected_updated_at: '2026-01-01T00:00:00.000Z',
+ operations: [
+ {
+ _tag: 'insert_cell',
+ after_cell_id: 'cell-1',
+ cell: {
+ _tag: 'database_cell',
+ sql: 'select * from auth.users limit 100',
+ row_limit: 100,
+ database_identifier: 'test-project-replica-1',
+ },
+ },
+ ],
+ },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+ ).resolves.toMatchObject({ id: 'notebook-1', name: 'Signup funnel' })
+ })
+
+ it('should succeed without validating or fetching databases when no operation introduces a database_cell', async () => {
+ // cell-2 already carries an identifier that wouldn't validate today (e.g. its
+ // replica was since removed) — but this update never touches it, so it must not
+ // be re-checked, and the databases endpoint must not be called at all.
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref/content/item/:id',
+ response: () =>
+ HttpResponse.json<GetUserContentByIdResponse>({
+ id: 'notebook-1',
+ name: 'Signup funnel',
+ description: undefined,
+ visibility: 'project',
+ favorite: false,
+ folder_id: null,
+ inserted_at: '2026-01-01T00:00:00.000Z',
+ updated_at: '2026-01-01T00:00:00.000Z',
+ owner_id: 1,
+ project_id: 1,
+ type: 'notebook',
+ content: {
+ ...NOTEBOOK_CONTENT,
+ cells: NOTEBOOK_CONTENT.cells.map((cell) =>
+ cell._tag === 'database_cell'
+ ? { ...cell, database_identifier: 'stale-replica-removed-long-ago' }
+ : cell
+ ),
+ },
+ }),
+ })
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: () => new HttpResponse(null),
+ })
+
+ const tools = getNotebookTools({ projectRef: 'test-project' })
+ if (!tools.update_notebook.execute) throw new Error('execute is undefined')
+
+ // No mock registered for GET /platform/projects/:ref/databases: MSW fails the test
+ // on any unhandled request, so this also asserts the endpoint was never called.
+ await expect(
+ tools.update_notebook.execute(
+ {
+ id: 'notebook-1',
+ expected_updated_at: '2026-01-01T00:00:00.000Z',
+ operations: [{ _tag: 'delete_cell', cell_id: 'cell-3' }],
+ },
+ { toolCallId: 'test', messages: [], context: {} }
+ )
+ ).resolves.toMatchObject({ id: 'notebook-1', name: 'Signup funnel' })
+ })
})
describe('encodeNotebookToolError / decodeNotebookToolError', () => {
diff --git a/apps/studio/lib/ai/tools/notebook-tools.ts b/apps/studio/lib/ai/tools/notebook-tools.ts
index b0dfae57074..0b7f18ba2df 100644
--- a/apps/studio/lib/ai/tools/notebook-tools.ts
+++ b/apps/studio/lib/ai/tools/notebook-tools.ts
@@ -73,6 +73,29 @@ export function decodeNotebookToolError(errorText: string): EncodedNotebookToolE
return result.success ? result.data : null
}
+/**
+ * Rejects a made-up `database_identifier` before it's written: it would pass schema
+ * validation (it's just a string) but silently break the cell at run time, since
+ * QueryEditor's connection-string lookup can't resolve an identifier that isn't real.
+ *
+ * @throws NotebookToolError if any cell has a `database_identifier` that isn't in the
+ * list of valid identifiers for this project.
+ */
+function assertValidDatabaseIdentifiers(
+ cells: ReadonlyArray<{ _tag: string; database_identifier?: string }>,
+ validIdentifiers: Set<string>
+): void {
+ for (const cell of cells) {
+ if (cell._tag !== 'database_cell' || cell.database_identifier === undefined) continue
+ if (!validIdentifiers.has(cell.database_identifier)) {
+ throw new NotebookToolError(
+ `Unknown database_identifier "${cell.database_identifier}" — call list_databases to see this project's valid identifiers.`,
+ { exposeToAssistant: true }
+ )
+ }
+ }
+}
+
export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {
const { projectRef, authorization } = ctx
const authHeaders = authorization ? { Authorization: authorization } : undefined
@@ -172,6 +195,18 @@ export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {
}),
needsApproval: true,
execute: async ({ name, description, content }) => {
+ if (
+ content.cells.some(
+ (cell) => cell._tag === 'database_cell' && cell.database_identifier !== undefined
+ )
+ ) {
+ const databases = await getReadReplicas({ projectRef }, undefined, authHeaders)
+ assertValidDatabaseIdentifiers(
+ content.cells,
+ new Set((databases ?? []).map((database) => database.identifier))
+ )
+ }
+
// This approval gate is the user gesture that promotes each cell's SQL from
// untrusted to safe — keep the promotion here, not in a shared helper, so it's
// auditable directly alongside the `needsApproval: true` above.
@@ -216,6 +251,23 @@ export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {
}),
needsApproval: true,
execute: async ({ id, expected_updated_at, operations }) => {
+ const newCells = operations.flatMap((operation) =>
+ operation._tag === 'insert_cell' || operation._tag === 'replace_cell'
+ ? [operation.cell]
+ : []
+ )
+ if (
+ newCells.some(
+ (cell) => cell._tag === 'database_cell' && cell.database_identifier !== undefined
+ )
+ ) {
+ const databases = await getReadReplicas({ projectRef }, undefined, authHeaders)
+ assertValidDatabaseIdentifiers(
+ newCells,
+ new Set((databases ?? []).map((database) => database.identifier))
+ )
+ }
+
const notebook = await getNotebook({ projectRef, id }, undefined, authHeaders)
if (notebook.updated_at !== expected_updated_at) {