The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Add search docs, advisors, and custom logging tools (#36852)
Saxon Fletcher0419d45b6fd7
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.types.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.types.tsindex 22dc02b9552..c325a2baca9 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.types.ts+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.types.ts@@ -23,7 +23,7 @@ export type LogsMeta = {currentPercentiles: Record<Percentile, number>}-export type PageParam = { cursor: number; direction: 'next' | 'prev' }+export type PageParam = { cursor: number; direction: 'next' | 'prev' } | undefinedexport type SearchParamsType = inferParserType<typeof SEARCH_PARAMS_PARSER>export type QuerySearchParamsType = Omit<SearchParamsType, 'uuid' | 'live'>diff --git a/apps/studio/data/logs/unified-logs-chart-query.ts b/apps/studio/data/logs/unified-logs-chart-query.tsindex 295078c2c44..8def604da4f 100644--- a/apps/studio/data/logs/unified-logs-chart-query.ts+++ b/apps/studio/data/logs/unified-logs-chart-query.ts@@ -8,7 +8,8 @@ import { UNIFIED_LOGS_QUERY_OPTIONS, UnifiedLogsVariables } from './unified-logsexport async function getUnifiedLogsChart({ projectRef, search }: UnifiedLogsVariables,- signal?: AbortSignal+ signal?: AbortSignal,+ headersInit?: HeadersInit) {if (typeof projectRef === 'undefined') {throw new Error('projectRef is required for getUnifiedLogsChart')@@ -21,8 +22,9 @@ export async function getUnifiedLogsChart(let endTime: Dateif (search.date && search.date.length === 2) {- startTime = new Date(search.date[0])- endTime = new Date(search.date[1])+ const parseDate = (d: string | Date) => (d instanceof Date ? d : new Date(d))+ startTime = parseDate(search.date[0])+ endTime = parseDate(search.date[1])dateStart = startTime.toISOString()dateEnd = endTime.toISOString()} else {@@ -36,10 +38,13 @@ export async function getUnifiedLogsChart(// Get SQL query from utility function (with dynamic bucketing)const sql = getLogsChartQuery(search)+ let headers = new Headers(headersInit)+const { data, error } = await post(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {params: { path: { ref: projectRef } },body: { sql, iso_timestamp_start: dateStart, iso_timestamp_end: dateEnd },signal,+ headers,})if (error) handleError(error)diff --git a/apps/studio/data/logs/unified-logs-infinite-query.ts b/apps/studio/data/logs/unified-logs-infinite-query.tsindex ee7a1cd677f..1e83b6d5360 100644--- a/apps/studio/data/logs/unified-logs-infinite-query.ts+++ b/apps/studio/data/logs/unified-logs-infinite-query.ts@@ -30,8 +30,9 @@ export const getUnifiedLogsISOStartEnd = (search: QuerySearchParamsType) => {let isoTimestampEnd: stringif (search.date && search.date.length === 2) {- isoTimestampStart = new Date(search.date[0]).toISOString()- isoTimestampEnd = new Date(search.date[1]).toISOString()+ const parseDate = (d: string | Date) => (d instanceof Date ? d : new Date(d))+ isoTimestampStart = parseDate(search.date[0]).toISOString()+ isoTimestampEnd = parseDate(search.date[1]).toISOString()} else {const now = new Date()isoTimestampEnd = now.toISOString()@@ -42,9 +43,10 @@ export const getUnifiedLogsISOStartEnd = (search: QuerySearchParamsType) => {return { isoTimestampStart, isoTimestampEnd }}-async function getUnifiedLogs(- { projectRef, search, pageParam }: UnifiedLogsVariables & { pageParam: PageParam },- signal?: AbortSignal+export async function getUnifiedLogs(+ { projectRef, search, pageParam }: UnifiedLogsVariables & { pageParam?: PageParam },+ signal?: AbortSignal,+ headersInit?: HeadersInit) {if (typeof projectRef === 'undefined')throw new Error('projectRef is required for getUnifiedLogs')@@ -94,10 +96,13 @@ async function getUnifiedLogs(timestampEnd = isoTimestampEnd}+ let headers = new Headers(headersInit)+const { data, error } = await post(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {params: { path: { ref: projectRef } },body: { iso_timestamp_start: isoTimestampStart, iso_timestamp_end: timestampEnd, sql },signal,+ headers,})if (error) handleError(error)@@ -162,12 +167,12 @@ export const useUnifiedLogsInfiniteQuery = <TData = UnifiedLogsData>(enabled: enabled && typeof projectRef !== 'undefined',getPreviousPageParam: (firstPage) => {if (!firstPage.prevCursor) return null- const result = { cursor: firstPage.prevCursor, direction: 'prev' } as PageParam+ const result = { cursor: firstPage.prevCursor, direction: 'prev' }return result},getNextPageParam(lastPage) {if (!lastPage.nextCursor || lastPage.data.length === 0) return null- return { cursor: lastPage.nextCursor, direction: 'next' } as PageParam+ return { cursor: lastPage.nextCursor, direction: 'next' }},...UNIFIED_LOGS_QUERY_OPTIONS,...options,diff --git a/apps/studio/lib/ai/supabase-mcp.ts b/apps/studio/lib/ai/supabase-mcp.tsnew file mode 100644index 00000000000..6a4a6d6b50e--- /dev/null+++ b/apps/studio/lib/ai/supabase-mcp.ts@@ -0,0 +1,39 @@+import { createSupabaseApiPlatform, createSupabaseMcpServer } from '@supabase/mcp-server-supabase'+import { StreamTransport } from '@supabase/mcp-utils'+import { experimental_createMCPClient as createMCPClient } from 'ai'++import { API_URL } from 'lib/constants'++export async function createSupabaseMCPClient({+ accessToken,+ projectId,+}: {+ accessToken: string+ projectId: string+}) {+ // Create an in-memory transport pair+ const clientTransport = new StreamTransport()+ const serverTransport = new StreamTransport()+ clientTransport.readable.pipeTo(serverTransport.writable)+ serverTransport.readable.pipeTo(clientTransport.writable)++ // Instantiate the MCP server and connect to its transport+ const apiUrl = API_URL?.replace('/platform', '')+ const server = createSupabaseMcpServer({+ platform: createSupabaseApiPlatform({+ accessToken,+ apiUrl,+ }),+ projectId,+ readOnly: true,+ })+ await server.connect(serverTransport)++ // Create the MCP client and connect to its transport+ const client = await createMCPClient({+ name: 'supabase-studio',+ transport: clientTransport,+ })++ return client+}diff --git a/apps/studio/lib/ai/tool-filter.test.ts b/apps/studio/lib/ai/tool-filter.test.tsnew file mode 100644index 00000000000..94907076e19--- /dev/null+++ b/apps/studio/lib/ai/tool-filter.test.ts@@ -0,0 +1,360 @@+import { Tool, ToolSet, ToolExecutionOptions } from 'ai'+import { describe, expect, it, vitest } from 'vitest'+import { z } from 'zod'++import {+ TOOL_CATEGORIES,+ TOOL_CATEGORY_MAP,+ filterToolsByOptInLevel,+ createPrivacyMessageTool,+ toolSetValidationSchema,+ transformToolResult,+} from './tool-filter'++describe('TOOL_CATEGORY_MAP', () => {+ it('should categorize tools correctly', () => {+ expect(TOOL_CATEGORY_MAP['display_query']).toBe(TOOL_CATEGORIES.UI)+ expect(TOOL_CATEGORY_MAP['list_tables']).toBe(TOOL_CATEGORIES.SCHEMA)+ expect(TOOL_CATEGORY_MAP['get_logs']).toBe(TOOL_CATEGORIES.LOG)+ expect(TOOL_CATEGORY_MAP['execute_sql']).toBe(TOOL_CATEGORIES.DATA)+ })+})++describe('tool allowance by opt-in level', () => {+ // Helper function to get allowed tools for a given opt-in level+ function getAllowedTools(optInLevel: string) {+ const mockTools: ToolSet = {+ // UI tools+ display_query: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ display_edge_function: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ rename_chat: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ search_docs: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ // Schema tools+ list_tables: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ list_extensions: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ list_edge_functions: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ list_branches: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ // Log tools+ get_logs: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ get_advisors: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ get_log_counts: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ // Data tools+ execute_sql: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ } as unknown as ToolSet++ const filtered = filterToolsByOptInLevel(mockTools, optInLevel as any)+ const allowedTools: string[] = []++ Object.entries(filtered).forEach(([toolName, tool]) => {+ // Check if tool is actually allowed (not stubbed)+ const isStubbed = tool.description?.includes('Requires opting in')+ if (!isStubbed) {+ allowedTools.push(toolName)+ }+ })++ return allowedTools+ }++ it('should return only UI tools for disabled opt-in level', () => {+ const tools = getAllowedTools('disabled')+ expect(tools).toContain('display_query')+ expect(tools).toContain('display_edge_function')+ expect(tools).toContain('rename_chat')+ expect(tools).toContain('search_docs')+ expect(tools).not.toContain('list_tables')+ expect(tools).not.toContain('list_extensions')+ expect(tools).not.toContain('list_edge_functions')+ expect(tools).not.toContain('list_branches')+ expect(tools).not.toContain('get_logs')+ expect(tools).not.toContain('execute_sql')+ })++ it('should return UI and schema tools for schema opt-in level', () => {+ const tools = getAllowedTools('schema')+ expect(tools).toContain('display_query')+ expect(tools).toContain('display_edge_function')+ expect(tools).toContain('rename_chat')+ expect(tools).toContain('list_tables')+ expect(tools).toContain('list_extensions')+ expect(tools).toContain('list_edge_functions')+ expect(tools).toContain('list_branches')+ expect(tools).toContain('search_docs')+ expect(tools).not.toContain('get_logs')+ expect(tools).not.toContain('get_advisors')+ expect(tools).not.toContain('get_log_counts')+ expect(tools).not.toContain('execute_sql')+ })++ it('should return UI, schema and log tools for schema_and_log opt-in level', () => {+ const tools = getAllowedTools('schema_and_log')+ expect(tools).toContain('display_query')+ expect(tools).toContain('display_edge_function')+ expect(tools).toContain('rename_chat')+ expect(tools).toContain('list_tables')+ expect(tools).toContain('list_extensions')+ expect(tools).toContain('list_edge_functions')+ expect(tools).toContain('list_branches')+ expect(tools).toContain('search_docs')+ expect(tools).toContain('get_logs')+ expect(tools).toContain('get_advisors')+ expect(tools).toContain('get_log_counts')+ expect(tools).not.toContain('execute_sql')+ })++ it('should return all tools for schema_and_log_and_data opt-in level', () => {+ const tools = getAllowedTools('schema_and_log_and_data')+ expect(tools).toContain('display_query')+ expect(tools).toContain('display_edge_function')+ expect(tools).toContain('rename_chat')+ expect(tools).toContain('list_tables')+ expect(tools).toContain('list_extensions')+ expect(tools).toContain('list_edge_functions')+ expect(tools).toContain('list_branches')+ expect(tools).toContain('search_docs')+ expect(tools).toContain('get_logs')+ expect(tools).toContain('get_advisors')+ expect(tools).toContain('get_log_counts')+ expect(tools).toContain('execute_sql')+ })+})++describe('filterToolsByOptInLevel', () => {+ const mockTools: ToolSet = {+ // UI tools - should return non-privacy responses+ display_query: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ display_edge_function: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ rename_chat: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ // Schema tools+ list_tables: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ list_extensions: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ list_edge_functions: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ list_branches: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ search_docs: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ // Log tools+ get_logs: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ get_advisors: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ get_log_counts: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ // Data tools+ execute_sql: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ // Unknown tool - should be filtered out entirely+ some_other_tool: { execute: vitest.fn().mockResolvedValue({ status: 'success' }) },+ } as unknown as ToolSet++ const stubResultSchema = z.object({+ status: z.string(),+ })++ async function checkStub(name: string, tool: Tool<any, any>) {+ if (!tool.execute) {+ throw new Error(`Tool ${name} does not have an execute function`)+ }++ const result: { status: string } = await (tool.execute as any)()+ const parsedResult = stubResultSchema.safeParse(result)++ return (+ parsedResult.success &&+ parsedResult.data.status.includes("You don't have permission to use this tool")+ )+ }++ async function expectStubsFor(tools: ToolSet, expectedStubTools: string[]) {+ for (const toolName in tools) {+ const tool = tools[toolName]++ const shouldBeStub = expectedStubTools.includes(toolName)+ const hasStub = await checkStub(toolName, tool)++ expect(hasStub).toBe(shouldBeStub)+ }+ }++ it('should filter out unknown tools entirely', async () => {+ const tools = filterToolsByOptInLevel(mockTools, 'disabled')++ // Unknown tools should be completely filtered out (not present in result)+ expect(tools).not.toHaveProperty('some_other_tool')+ })++ it('should always allow UI tools regardless of opt-in level', async () => {+ const tools = filterToolsByOptInLevel(mockTools, 'disabled')++ expect(tools).toHaveProperty('display_query')+ expect(tools).toHaveProperty('display_edge_function')+ expect(tools).toHaveProperty('rename_chat')++ // UI tools should not be stubbed, but managed tools should be+ await expectStubsFor(tools, [+ 'list_tables',+ 'list_extensions',+ 'list_edge_functions',+ 'list_branches',+ 'get_logs',+ 'get_advisors',+ 'get_log_counts',+ 'execute_sql',+ ])+ })++ it('should stub all managed tools for disabled opt-in level', async () => {+ const tools = filterToolsByOptInLevel(mockTools, 'disabled')++ await expectStubsFor(tools, [+ 'list_tables',+ 'list_extensions',+ 'list_edge_functions',+ 'list_branches',+ 'get_logs',+ 'get_advisors',+ 'get_log_counts',+ 'execute_sql',+ ])+ })++ it('should stub log and execute tools for schema opt-in level', async () => {+ const tools = filterToolsByOptInLevel(mockTools, 'schema')++ await expectStubsFor(tools, ['get_logs', 'get_advisors', 'get_log_counts', 'execute_sql'])+ })++ it('should stub execute tool for schema_and_log opt-in level', async () => {+ const tools = filterToolsByOptInLevel(mockTools, 'schema_and_log')++ await expectStubsFor(tools, ['execute_sql'])+ })++ it('should not stub any tools for schema_and_log_and_data opt-in level', async () => {+ const tools = filterToolsByOptInLevel(mockTools, 'schema_and_log_and_data')++ await expectStubsFor(tools, [])+ })+})++describe('createPrivacyMessageTool', () => {+ it('should create a privacy message tool', async () => {+ const originalTool = {+ description: 'Original description',+ parameters: z.object({}),+ execute: vitest.fn(),+ }++ const privacyTool = createPrivacyMessageTool(originalTool)++ expect(privacyTool.description).toContain('Original description')+ expect(privacyTool.description).toContain('Requires opting in')++ const result = await privacyTool.execute({}, {})+ expect(result.status).toContain("You don't have permission to use this tool")+ })+})++describe('transformToolResult', () => {+ it('should wrap a tool with a result transformation function', async () => {+ const originalResult = { data: 'original' }++ const mockTool = {+ description: 'Test tool',+ execute: vitest.fn().mockResolvedValue(originalResult),+ } as unknown as Tool<any, typeof originalResult>++ const transformFn = vitest.fn((result: typeof originalResult) => ({+ data: `${result.data} - transformed`,+ }))++ const transformedTool = transformToolResult(mockTool, transformFn)++ // Tool properties should be preserved+ expect(transformedTool.description).toBe(mockTool.description)++ // Execute the transformed tool+ const args = { key: 'value' }+ const options = {} as ToolExecutionOptions++ if (!transformedTool.execute) {+ throw new Error('Transformed tool does not have an execute function')+ }++ const result = await transformedTool.execute(args, options)++ // Original tool should have been called with the same arguments+ expect(mockTool.execute).toHaveBeenCalledWith(args, options)++ // Transform function should have been called with the original result+ expect(transformFn).toHaveBeenCalledWith(originalResult)++ // Final result should be the transformed value+ expect(result).toEqual({ data: 'original - transformed' })+ })++ it('should throw an error if tool is null', () => {+ expect(() => transformToolResult(null as any, () => ({}))).toThrow('Tool is required')+ })++ it('should throw an error if tool does not have an execute function', () => {+ const invalidTool = { name: 'invalid' } as any+ expect(() => transformToolResult(invalidTool, () => ({}))).toThrow(+ 'Tool does not have an execute function'+ )+ })+})++describe('toolSetValidationSchema', () => {+ it('should accept subset of known tools', () => {+ const validSubset = {+ list_tables: { parameters: z.object({}), execute: vitest.fn() },+ get_logs: { parameters: z.object({}), execute: vitest.fn() },+ display_query: { parameters: z.object({}), execute: vitest.fn() },+ }++ const result = toolSetValidationSchema.safeParse(validSubset)+ expect(result.success).toBe(true)+ })++ it('should reject unknown tools', () => {+ const toolsWithUnknown = {+ list_tables: { parameters: z.object({}), execute: vitest.fn() },+ unknown_tool: { parameters: z.object({}), execute: vitest.fn() },+ another_unknown: { parameters: z.object({}), execute: vitest.fn() },+ }++ const result = toolSetValidationSchema.safeParse(toolsWithUnknown)+ expect(result.success).toBe(false)+ if (!result.success) {+ expect(result.error.issues).toHaveLength(2) // Two unknown tools+ expect(result.error.issues[0].message).toContain('Invalid enum value')+ }+ })++ it('should accept empty tool set', () => {+ const result = toolSetValidationSchema.safeParse({})+ expect(result.success).toBe(true)+ })++ it('should validate all expected tools from the old schema', () => {+ const allExpectedTools = {+ list_tables: { parameters: z.object({}), execute: vitest.fn() },+ list_extensions: { parameters: z.object({}), execute: vitest.fn() },+ list_edge_functions: { parameters: z.object({}), execute: vitest.fn() },+ list_branches: { parameters: z.object({}), execute: vitest.fn() },+ get_logs: { parameters: z.object({}), execute: vitest.fn() },+ execute_sql: { parameters: z.object({}), execute: vitest.fn() },+ search_docs: { parameters: z.object({}), execute: vitest.fn() },+ get_advisors: { parameters: z.object({}), execute: vitest.fn() },+ display_query: { parameters: z.object({}), execute: vitest.fn() },+ display_edge_function: { parameters: z.object({}), execute: vitest.fn() },+ rename_chat: { parameters: z.object({}), execute: vitest.fn() },+ get_log_counts: { parameters: z.object({}), execute: vitest.fn() },+ }++ const validationResult = toolSetValidationSchema.safeParse(allExpectedTools)+ expect(validationResult.success).toBe(true)++ // Test with missing tool+ const incompleteTools = { ...allExpectedTools }+ delete (incompleteTools as any).execute_sql++ const incompleteValidationResult = toolSetValidationSchema.safeParse(incompleteTools)+ expect(incompleteValidationResult.success).toBe(true) // Should still pass as we allow subsets+ })+})diff --git a/apps/studio/lib/ai/tool-filter.ts b/apps/studio/lib/ai/tool-filter.tsnew file mode 100644index 00000000000..363ec0ccf88--- /dev/null+++ b/apps/studio/lib/ai/tool-filter.ts@@ -0,0 +1,182 @@+import { Tool, ToolSet, ToolExecutionOptions } from 'ai'+import { z } from 'zod'+import { AiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'++const basicToolSchema = z.custom<Tool>((value) => typeof value === 'object')++/**+ * Schema for validating that a tool set only contains known tools.+ */+export const toolSetValidationSchema = z.record(+ z.enum([+ // MCP tools+ 'list_tables',+ 'list_extensions',+ 'list_edge_functions',+ 'list_branches',+ 'get_logs',+ 'execute_sql',+ 'search_docs',+ 'get_advisors',++ // Local tools+ 'display_query',+ 'display_edge_function',+ 'rename_chat',+ 'get_log_counts',+ 'getSchemaTables',+ 'getRlsKnowledge',+ 'getFunctions',+ 'getEdgeFunctionKnowledge',+ ]),+ basicToolSchema+)++/**+ * Transforms the result of a tool execution to a new output.+ */+export function transformToolResult<OriginalResult, NewResult>(+ tool: Tool<any, OriginalResult>,+ execute: (result: OriginalResult) => NewResult+): Tool<any, NewResult> {+ if (!tool) {+ throw new Error('Tool is required')+ }++ if (!tool.execute) {+ throw new Error('Tool does not have an execute function')+ }++ // Intercept the tool to add a custom execute function+ return {+ ...tool,+ execute: async (args: any, options: ToolExecutionOptions) => {+ const result = await tool.execute!(args, options)+ return execute(result)+ },+ } as Tool<any, NewResult>+}++/**+ * Tool categories based on the data they access+ */+export const TOOL_CATEGORIES = {+ // UI tools that are always available regardless of opt-in level+ UI: 'ui',+ // Schema-level tools that require schema opt-in+ SCHEMA: 'schema',+ // Log-level tools that require schema_and_log opt-in+ LOG: 'log',+ // Data-level tools that require schema_and_log_and_data opt-in+ DATA: 'data',+} as const++type ToolCategory = (typeof TOOL_CATEGORIES)[keyof typeof TOOL_CATEGORIES]++/**+ * Mapping of tool names to their categories+ */+export const TOOL_CATEGORY_MAP: Record<string, ToolCategory> = {+ // UI tools - always available+ display_query: TOOL_CATEGORIES.UI,+ display_edge_function: TOOL_CATEGORIES.UI,+ rename_chat: TOOL_CATEGORIES.UI,+ search_docs: 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,++ // Log tools - MCP and local+ get_logs: TOOL_CATEGORIES.LOG,+ get_advisors: TOOL_CATEGORIES.LOG,+ get_log_counts: TOOL_CATEGORIES.LOG,++ // Data tools - MCP only+ execute_sql: TOOL_CATEGORIES.DATA,+}++/**+ * Get the minimum opt-in level required for a tool category+ */+function getMinimumOptInLevel(category: ToolCategory): AiOptInLevel | null {+ switch (category) {+ case TOOL_CATEGORIES.UI:+ return null // Always available+ case TOOL_CATEGORIES.SCHEMA:+ return 'schema'+ case TOOL_CATEGORIES.LOG:+ return 'schema_and_log'+ case TOOL_CATEGORIES.DATA:+ return 'schema_and_log_and_data'+ default:+ return null+ }+}++/**+ * Check if a tool is allowed based on the current opt-in level+ */+function isToolAllowed(toolName: string, aiOptInLevel: AiOptInLevel): boolean {+ const category = TOOL_CATEGORY_MAP[toolName]++ if (!category) {+ return false+ }++ const minimumLevel = getMinimumOptInLevel(category)++ // UI tools are always allowed+ if (!minimumLevel) {+ return true+ }++ // Check if current opt-in level meets the minimum requirement+ const optInHierarchy: AiOptInLevel[] = [+ 'disabled',+ 'schema',+ 'schema_and_log',+ 'schema_and_log_and_data',+ ]++ const currentLevelIndex = optInHierarchy.indexOf(aiOptInLevel)+ const minimumLevelIndex = optInHierarchy.indexOf(minimumLevel)++ return currentLevelIndex >= minimumLevelIndex+}++/**+ * Create a privacy message tool that explains why the tool is not available+ */+export function createPrivacyMessageTool(toolInstance: Tool<any, any>) {+ const privacyMessage =+ "You don't have permission to use this tool. This is an organization-wide setting requiring you to opt-in. Please choose your preferred data sharing level in your organization's settings. Supabase Assistant uses Amazon Bedrock, which does not store or log your prompts and completions, use them to train AWS models, or distribute them to third parties. By default, no data is shared. Granting permission allows Supabase to send information (like schema, logs, or data, depending on your chosen level) to Bedrock solely to generate responses."+ const condensedPrivacyMessage =+ 'Requires opting in to sending data to Bedrock which does not store, train on, or distribute it. You can opt in via organization settings.'++ return {+ ...toolInstance,+ description: `${toolInstance.description} (Note: ${condensedPrivacyMessage})`,+ execute: async (_args: any, _context: any) => ({ status: privacyMessage }),+ }+}++/**+ * Filter tools based on the AI opt-in level+ */+export function filterToolsByOptInLevel(tools: ToolSet, aiOptInLevel: AiOptInLevel): ToolSet {+ return Object.fromEntries(+ Object.entries(tools)+ .filter(([toolName]) => TOOL_CATEGORY_MAP[toolName] !== undefined)+ .map(([toolName, toolInstance]) => {+ if (isToolAllowed(toolName, aiOptInLevel)) {+ return [toolName, toolInstance]+ }++ // If the tool is not allowed, provide a stub that returns a privacy message+ return [toolName, createPrivacyMessageTool(toolInstance)]+ })+ )+}diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.tsindex 2445209f96b..982ba7036b5 100644--- a/apps/studio/pages/api/ai/sql/generate-v4.ts+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts@@ -13,12 +13,15 @@ import { getAiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'import { getModel } from 'lib/ai/model'import apiWrapper from 'lib/api/apiWrapper'import { queryPgMetaSelfHosted } from 'lib/self-hosted'+import { getUnifiedLogsChart } from 'data/logs/unified-logs-chart-query'+import { getUnifiedLogs } from 'data/logs/unified-logs-infinite-query'+import { QuerySearchParamsType } from 'components/interfaces/UnifiedLogs/UnifiedLogs.types'+import { createSupabaseMCPClient } from 'lib/ai/supabase-mcp'import {- createSupabaseMCPClient,- expectedToolsSchema,filterToolsByOptInLevel,+ toolSetValidationSchema,transformToolResult,-} from './supabase-mcp'+} from 'lib/ai/tool-filter'import { getTools } from './tools'export const maxDuration = 120@@ -159,6 +162,188 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {return { status: 'Tool call sent to client for rendering.' }},}),+ get_log_counts: tool({+ description:+ 'Get log counts aggregated by time buckets to understand system health and activity levels. Returns success, warning, and error counts over time. Can filter by log types (edge, auth, postgres, etc.) and levels.',+ parameters: z.object({+ dateStart: z+ .string()+ .optional()+ .describe('Start date as ISO string (defaults to 1 hour ago)'),+ dateEnd: z.string().optional().describe('End date as ISO string (defaults to now)'),+ level: z+ .array(z.enum(['success', 'warning', 'error']))+ .optional()+ .describe('Filter by log levels'),+ log_type: z+ .array(+ z.enum([+ 'postgres',+ 'edge_function',+ 'auth',+ 'postgrest',+ 'storage',+ 'edge',+ 'function_events',+ 'postgres_upgrade',+ 'supavisor',+ ])+ )+ .optional()+ .describe('Filter by log types (e.g., ["edge"] for edge logs only)'),+ }),+ execute: async (args) => {+ try {+ let dateArray: Date[] | null = null+ if (args.dateStart && args.dateEnd) {+ dateArray = [new Date(args.dateStart), new Date(args.dateEnd)]+ }++ const search: QuerySearchParamsType = {+ date: dateArray,+ level: args.level || null,+ log_type: args.log_type || null,+ latency: null,+ 'timing.dns': null,+ 'timing.connection': null,+ 'timing.tls': null,+ 'timing.ttfb': null,+ 'timing.transfer': null,+ status: null,+ regions: null,+ method: null,+ host: null,+ pathname: null,+ sort: null,+ size: 40,+ start: 0,+ direction: 'next',+ cursor: new Date(),+ id: null,+ }++ let headers = new Headers()+ if (authorization) headers.set('Authorization', authorization)++ const chartData = await getUnifiedLogsChart({ projectRef, search }, undefined, headers)++ const totalSuccess = chartData.reduce((sum: number, point) => sum + point.success, 0)+ const totalWarning = chartData.reduce((sum: number, point) => sum + point.warning, 0)+ const totalError = chartData.reduce((sum: number, point) => sum + point.error, 0)++ return {+ status: 'success',+ data: chartData,+ summary: `Found ${chartData.length} time buckets. Total: ${totalSuccess} success, ${totalWarning} warning, ${totalError} error logs`,+ totals: {+ success: totalSuccess,+ warning: totalWarning,+ error: totalError,+ },+ }+ } catch (error) {+ return {+ status: 'error',+ error: error instanceof Error ? error.message : 'Unknown error occurred',+ }+ }+ },+ }),+ get_logs: tool({+ description:+ 'Get detailed log entries for analysis and debugging. Use this after get_log_counts to examine specific logs during time periods with errors or unusual activity.',+ parameters: z.object({+ dateStart: z+ .string()+ .optional()+ .describe('Start date as ISO string (defaults to 1 hour ago)'),+ dateEnd: z.string().optional().describe('End date as ISO string (defaults to now)'),+ level: z+ .array(z.enum(['success', 'warning', 'error']))+ .optional()+ .describe('Filter by log levels'),+ log_type: z+ .array(+ z.enum([+ 'postgres',+ 'edge_function',+ 'auth',+ 'postgrest',+ 'storage',+ 'edge',+ 'function_events',+ 'postgres_upgrade',+ 'supavisor',+ ])+ )+ .optional()+ .describe('Filter by log types'),+ limit: z+ .number()+ .min(1)+ .max(100)+ .default(20)+ .describe('Maximum number of logs to return (1-100, defaults to 20)'),+ }),+ execute: async (args) => {+ try {+ let dateArray: Date[] | null = null+ if (args.dateStart && args.dateEnd) {+ dateArray = [new Date(args.dateStart), new Date(args.dateEnd)]+ }++ const search: QuerySearchParamsType = {+ date: dateArray,+ level: args.level || null,+ log_type: args.log_type || null,+ latency: null,+ 'timing.dns': null,+ 'timing.connection': null,+ 'timing.tls': null,+ 'timing.ttfb': null,+ 'timing.transfer': null,+ status: null,+ regions: null,+ method: null,+ host: null,+ pathname: null,+ sort: null,+ size: 40,+ start: 0,+ direction: 'next',+ cursor: new Date(),+ id: null,+ }++ let headers = new Headers()+ if (authorization) headers.set('Authorization', authorization)++ const logsData = await getUnifiedLogs(+ {+ projectRef,+ search,+ },+ undefined,+ headers+ )++ const logs = logsData.data.slice(0, args.limit)++ return {+ status: 'success',+ data: logs,+ summary: `Found ${logs.length} log entries. Showing details for analysis.`,+ totalFetched: logs.length,+ hasMore: logsData.nextCursor !== null,+ }+ } catch (error) {+ return {+ status: 'error',+ error: error instanceof Error ? error.message : 'Unknown error occurred',+ }+ }+ },+ }),rename_chat: tool({description: `Rename the current chat session when the current chat name doesn't describe the conversation topic.`,parameters: z.object({@@ -214,10 +399,12 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {})const availableMcpTools = await mcpClient.tools()+ // Filter tools based on the AI opt-in level+ const allowedMcpTools = filterToolsByOptInLevel(availableMcpTools, aiOptInLevel)- // Validate that the expected tools are available+ // Validate that only known tools are providedconst { data: validatedTools, error: validationError } =- expectedToolsSchema.safeParse(availableMcpTools)+ toolSetValidationSchema.safeParse(allowedMcpTools)if (validationError) {console.error('MCP tools validation error:', validationError)@@ -227,32 +414,34 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {})}- // Modify the execute_sql tool to add manualToolCallId- const modifiedMcpTools = {- ...availableMcpTools,- execute_sql: transformToolResult(validatedTools.execute_sql, (result) => {- const manualToolCallId = `manual_${crypto.randomUUID()}`-- if (typeof result === 'object') {- return { ...result, manualToolCallId }- } else {- console.warn('execute_sql result is not an object, cannot add manualToolCallId')- return {- error: 'Internal error: Unexpected tool result format',- manualToolCallId,+ // Modify the execute_sql tool to add manualToolCallId (if it exists)+ mcpTools = {+ ...validatedTools,+ ...(validatedTools.execute_sql && {+ execute_sql: transformToolResult(validatedTools.execute_sql, (result) => {+ const manualToolCallId = `manual_${crypto.randomUUID()}`++ if (typeof result === 'object') {+ return { ...result, manualToolCallId }+ } else {+ console.warn('execute_sql result is not an object, cannot add manualToolCallId')+ return {+ error: 'Internal error: Unexpected tool result format',+ manualToolCallId,+ }}- }+ }),}),}-- // Filter tools based on the AI opt-in level- mcpTools = filterToolsByOptInLevel(modifiedMcpTools, aiOptInLevel)}- // Combine MCP tools with custom tools+ // Filter local tools based on the AI opt-in level+ const filteredLocalTools = filterToolsByOptInLevel(localTools, aiOptInLevel)++ // Combine MCP tools with filtered local toolsconst tools: ToolSet = {...mcpTools,- ...localTools,+ ...filteredLocalTools,}const system = source`@@ -297,11 +486,12 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {# Supabase Health & Debugging- **General Status**:- - **If \`get_logs\`, \`list_tables\`, \`list_extensions\` are available**: Use them to provide a summary overview of the project's health (check recent errors/activity for relevant services like 'postgres', 'api', 'auth').+ - **If \`get_log_counts\`, \`get_logs\`, \`list_tables\`, \`list_extensions\` are available**: Use \`get_log_counts\` first to get a high-level view of system health by checking success/warning/error counts over time. You can filter by specific log types (e.g., \`log_type: ["edge"]\` for edge logs, \`log_type: ["postgres"]\` for database logs). Then use \`get_logs\` and schema tools to provide a detailed summary overview of the project's health (check recent errors/activity for relevant services like 'postgres', 'api', 'auth').- **If tools are NOT available**: Ask the user to check their Supabase dashboard or logs for project health information.- **Service Errors**:- - **If \`get_logs\` is available**: If facing specific errors related to the database, Edge Functions, or other Supabase services, explain the problem and use the \`get_logs\` tool, specifying the relevant service type (e.g., 'postgres', 'edge functions', 'api') to retrieve logs and diagnose the issue. Briefly summarize the relevant log information in your text response before suggesting a fix.- - **If \`get_logs\` is NOT available**: Ask the user to provide relevant logs for the service experiencing errors.+ - **If \`get_log_counts\` and \`get_logs\` are available**: Start with \`get_log_counts\` to understand the overall error patterns and timeframes. Use log type filtering to focus on specific services (e.g., \`log_type: ["edge"]\` for API errors, \`log_type: ["postgres"]\` for database errors). Then use \`get_logs\` to dive deeper into specific errors. When facing specific errors related to the database, Edge Functions, or other Supabase services, explain the problem and use the \`get_logs\` tool, specifying the relevant service type (e.g., 'postgres', 'edge functions', 'api') to retrieve logs and diagnose the issue. Briefly summarize the relevant log information in your text response before suggesting a fix.+ - **If only \`get_logs\` is available**: Use the \`get_logs\` tool directly to retrieve logs for the service experiencing errors.+ - **If tools are NOT available**: Ask the user to provide relevant logs for the service experiencing errors.# SQL Style:- Generated SQL must be valid Postgres SQL.@@ -416,7 +606,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {result.pipeDataStreamToResponse(res, {getErrorMessage: (error) => {if (error == null) {- return 'Untitled error'+ return 'unknown error'}if (typeof error === 'string') {diff --git a/apps/studio/pages/api/ai/sql/supabase-mcp.test.ts b/apps/studio/pages/api/ai/sql/supabase-mcp.test.tsdeleted file mode 100644index c667d211316..00000000000--- a/apps/studio/pages/api/ai/sql/supabase-mcp.test.ts+++ /dev/null@@ -1,199 +0,0 @@-import { Tool, ToolExecutionOptions, ToolSet } from 'ai'-import { describe, expect, it, vitest } from 'vitest'-import { z } from 'zod'--import {- expectedToolsSchema,- filterToolsByOptInLevel,- getAllowedTools,- transformToolResult,-} from './supabase-mcp'--describe('getAllowedTools', () => {- it('should return empty array for disabled opt-in level', () => {- const tools = getAllowedTools('disabled')- expect(tools).toEqual([])- })-- it('should return schema tools for schema opt-in level', () => {- const tools = getAllowedTools('schema')- expect(tools).toContain('list_tables')- expect(tools).toContain('list_extensions')- expect(tools).toContain('list_edge_functions')- expect(tools).toContain('list_branches')- expect(tools).not.toContain('get_logs')- expect(tools).not.toContain('execute_sql')- })-- it('should return schema and log tools for schema_and_log opt-in level', () => {- const tools = getAllowedTools('schema_and_log')- expect(tools).toContain('list_tables')- expect(tools).toContain('list_extensions')- expect(tools).toContain('list_edge_functions')- expect(tools).toContain('list_branches')- expect(tools).toContain('get_logs')- expect(tools).not.toContain('execute_sql')- })-- it('should return all tools for schema_and_log_and_data opt-in level', () => {- const tools = getAllowedTools('schema_and_log_and_data')- expect(tools).toContain('list_tables')- expect(tools).toContain('list_extensions')- expect(tools).toContain('list_edge_functions')- expect(tools).toContain('list_branches')- expect(tools).toContain('get_logs')- expect(tools).toContain('execute_sql')- })-})--describe('filterToolsByOptInLevel', () => {- const mockTools: ToolSet = {- list_tables: { execute: vitest.fn() },- list_extensions: { execute: vitest.fn() },- list_edge_functions: { execute: vitest.fn() },- list_branches: { execute: vitest.fn() },- get_logs: { execute: vitest.fn() },- execute_sql: { execute: vitest.fn() },- other: { execute: vitest.fn() }, // This tool should be filtered out- } as unknown as ToolSet-- const stubResultSchema = z.object({- status: z.string(),- })-- async function checkStub(name: string, tool: Tool<any, any>) {- if (!tool.execute) {- throw new Error(`Tool ${name} does not have an execute function`)- }-- const result: { status: string } = await (tool.execute as any)()- const parsedResult = stubResultSchema.safeParse(result)-- return (- parsedResult.success &&- parsedResult.data.status.includes("You don't have permission to use this tool")- )- }-- async function expectStubsFor(tools: ToolSet, expectedStubTools: string[]) {- for (const toolName in tools) {- const tool = tools[toolName]-- const shouldBeStub = expectedStubTools.includes(toolName)- const hasStub = await checkStub(toolName, tool)-- expect(hasStub).toBe(shouldBeStub)- }- }-- it('should filter out tools not in tool whitelist', async () => {- const tools = filterToolsByOptInLevel(mockTools, 'disabled')-- expect(tools).not.toHaveProperty('other')- })-- it('should stub all functions for disabled opt-in level', async () => {- const tools = filterToolsByOptInLevel(mockTools, 'disabled')-- await expectStubsFor(tools, [- 'list_tables',- 'list_extensions',- 'list_edge_functions',- 'list_branches',- 'get_logs',- 'execute_sql',- ])- })-- it('should stub log and execute tools for schema opt-in level', async () => {- const tools = filterToolsByOptInLevel(mockTools, 'schema')-- await expectStubsFor(tools, ['get_logs', 'execute_sql'])- })-- it('should stub execute tool for schema_and_log opt-in level', async () => {- const tools = filterToolsByOptInLevel(mockTools, 'schema_and_log')-- await expectStubsFor(tools, ['execute_sql'])- })-- it('should not stub any tools for schema_and_log_and_data opt-in level', async () => {- const tools = filterToolsByOptInLevel(mockTools, 'schema_and_log_and_data')-- await expectStubsFor(tools, [])- })-})--describe('transformToolResult', () => {- it('should wrap a tool with a result transformation function', async () => {- const originalResult = { data: 'original' }-- const mockTool = {- description: 'Test tool',- execute: vitest.fn().mockResolvedValue(originalResult),- } as unknown as Tool<any, typeof originalResult>-- const transformFn = vitest.fn((result: typeof originalResult) => ({- data: `${result.data} - transformed`,- }))-- const transformedTool = transformToolResult(mockTool, transformFn)-- // Tool properties should be preserved- expect(transformedTool.description).toBe(mockTool.description)-- // Execute the transformed tool- const args = { key: 'value' }- const options = {} as ToolExecutionOptions-- if (!transformedTool.execute) {- throw new Error('Transformed tool does not have an execute function')- }-- const result = await transformedTool.execute(args, options)-- // Original tool should have been called with the same arguments- expect(mockTool.execute).toHaveBeenCalledWith(args, options)-- // Transform function should have been called with the original result- expect(transformFn).toHaveBeenCalledWith(originalResult)-- // Final result should be the transformed value- expect(result).toEqual({ data: 'original - transformed' })- })-- it('should throw an error if tool is null', () => {- expect(() => transformToolResult(null as any, () => ({}))).toThrow('Tool is required')- })-- it('should throw an error if tool does not have an execute function', () => {- const invalidTool = { name: 'invalid' } as any- expect(() => transformToolResult(invalidTool, () => ({}))).toThrow(- 'Tool does not have an execute function'- )- })-})--describe('expectedToolsSchema', () => {- it('should validate the expected tools schema', () => {- const validTools = {- list_tables: {},- list_extensions: {},- list_edge_functions: {},- list_branches: {},- get_logs: {},- execute_sql: {},- other: {},- }-- const validationResult = expectedToolsSchema.safeParse(validTools)- expect(validationResult.success).toBe(true)-- // Test with missing tool- const invalidTools = { ...validTools }- delete (invalidTools as any).execute_sql-- const invalidValidationResult = expectedToolsSchema.safeParse(invalidTools)- expect(invalidValidationResult.success).toBe(false)- })-})diff --git a/apps/studio/pages/api/ai/sql/supabase-mcp.ts b/apps/studio/pages/api/ai/sql/supabase-mcp.tsdeleted file mode 100644index 3d7b84956a9..00000000000--- a/apps/studio/pages/api/ai/sql/supabase-mcp.ts+++ /dev/null@@ -1,147 +0,0 @@-import { createSupabaseApiPlatform, createSupabaseMcpServer } from '@supabase/mcp-server-supabase'-import { StreamTransport } from '@supabase/mcp-utils'-import {- experimental_createMCPClient as createMCPClient,- Tool,- ToolExecutionOptions,- ToolSet,-} from 'ai'-import { z } from 'zod'--import { AiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'-import { API_URL } from 'lib/constants'--export async function createSupabaseMCPClient({- accessToken,- projectId,-}: {- accessToken: string- projectId: string-}) {- // Create an in-memory transport pair- const clientTransport = new StreamTransport()- const serverTransport = new StreamTransport()- clientTransport.readable.pipeTo(serverTransport.writable)- serverTransport.readable.pipeTo(clientTransport.writable)-- // Instantiate the MCP server and connect to its transport- const apiUrl = API_URL?.replace('/platform', '')- const server = createSupabaseMcpServer({- platform: createSupabaseApiPlatform({- accessToken,- apiUrl,- }),- projectId,- readOnly: true,- })- await server.connect(serverTransport)-- // Create the MCP client and connect to its transport- const client = await createMCPClient({- name: 'supabase-studio',- transport: clientTransport,- })-- return client-}--const basicToolSchema = z.custom<Tool>((value) => typeof value === 'object')--/**- * Schema to validate that the expected tools are available from the Supabase MCP.- *- * Note that tool structure itself is not validated, only that the tools exist.- */-export const expectedToolsSchema = z.object({- list_tables: basicToolSchema,- list_extensions: basicToolSchema,- list_edge_functions: basicToolSchema,- list_branches: basicToolSchema,- get_logs: basicToolSchema,- execute_sql: basicToolSchema,-})--export const toolWhitelist = Object.keys(expectedToolsSchema.shape)--export function createPrivacyMessageTool(toolInstance: Tool<any, any>) {- const privacyMessage =- "You don't have permission to use this tool. This is an organization-wide setting requiring you to opt-in. Please choose your preferred data sharing level in your organization's settings. Supabase Assistant uses Amazon Bedrock, which does not store or log your prompts and completions, use them to train AWS models, or distribute them to third parties. By default, no data is shared. Granting permission allows Supabase to send information (like schema, logs, or data, depending on your chosen level) to Bedrock solely to generate responses."- const condensedPrivacyMessage =- 'Requires opting in to sending data to Bedrock which does not store, train on, or distribute it. You can opt in via organization settings.'-- return {- ...toolInstance,- description: `${toolInstance.description} (Note: ${condensedPrivacyMessage})`,- execute: async (_args: any, _context: any) => ({ status: privacyMessage }),- }-}--export function filterToolsByOptInLevel(tools: ToolSet, aiOptInLevel: AiOptInLevel) {- // Get allowed tools based on the AI opt-in level- const allowedTools = getAllowedTools(aiOptInLevel)-- // Filter the tools to only include those that are allowed- return Object.fromEntries(- Object.entries(tools)- .filter(([key]) => toolWhitelist.includes(key))- .map(([key, toolInstance]) => {- if (allowedTools.includes(key)) {- return [key, toolInstance]- }-- // If the tool is not allowed, provide a stub that returns a privacy message- return [key, createPrivacyMessageTool(toolInstance)]- })- )-}--/**- * Transforms the result of a tool execution to a new output.- */-export function transformToolResult<OriginalResult, NewResult>(- tool: Tool<any, OriginalResult>,- execute: (result: OriginalResult) => NewResult-): Tool<any, NewResult> {- if (!tool) {- throw new Error('Tool is required')- }-- if (!tool.execute) {- throw new Error('Tool does not have an execute function')- }-- // Intercept the tool to add a custom execute function- return {- ...tool,- execute: async (args: any, options: ToolExecutionOptions) => {- const result = await tool.execute!(args, options)- return execute(result)- },- } as Tool<any, NewResult>-}--export function getAllowedTools(aiOptInLevel: AiOptInLevel) {- // Build allowed tools based on permission level- const allowedTools: string[] = []-- // For schema and above permission levels- if (- aiOptInLevel === 'schema' ||- aiOptInLevel === 'schema_and_log' ||- aiOptInLevel === 'schema_and_log_and_data'- ) {- allowedTools.push('list_tables', 'list_extensions', 'list_edge_functions', 'list_branches')- }-- // For schema_and_log permission level, add log access tools- if (aiOptInLevel === 'schema_and_log' || aiOptInLevel === 'schema_and_log_and_data') {- allowedTools.push('get_logs')- }-- // For schema_and_log_and_data permission level, add data access tools- if (aiOptInLevel === 'schema_and_log_and_data') {- allowedTools.push('execute_sql')- }-- return allowedTools-}