Files
supabase/apps/studio/pages/api/ai/sql/policy.ts
Pedro RodriguesandClaude Opus 4.8 c4c213ce3d feat(studio): switch dashboard assistant to remote MCP server (#47479)
## I have read the
[CONTRIBUTING.md](<https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md>)
file.

YES

## What kind of change does this PR introduce?

Feature / refactor.

## What is the current behavior?

The dashboard assistant runs `@supabase/mcp-server-supabase` in-process
over an in-memory transport (`lib/ai/supabase-mcp.ts`).

## What is the new behavior?

The assistant connects to the **remote MCP server** over HTTP
(`@ai-sdk/mcp`), forwarding the dashboard session token as a bearer. URL
comes from `NEXT_PUBLIC_MCP_URL` with a local-dev fallback;
platform-only, and Nimbus works via the same env var.

* **Tool model unchanged:** UI-controlled `execute_sql` (with
`needsApproval`) and `deploy_edge_function` still come from Studio; the
allowlist (`TOOL_CATEGORY_MAP`) remains the gate keeping the remote's
write tools away from the assistant (`read_only` is defense-in-depth).
* **Attribution:** sends `x-source-name: supabase-studio` (+
`x-source-version`) → logged as `source_name`/`client_name`.
* **Connection lifecycle:** the HTTP client is closed via the request's
`AbortSignal` (tools execute later during streaming); `signal` is
required on `getTools`/`getMcpTools`.
* **Resilience:** a remote-MCP failure degrades to the remaining tools
instead of failing the assistant.
* **Drift protection:** relied-upon tools are typed against `keyof
typeof supabaseMcpToolSchemas`, so a package bump that renames/removes
one fails `pnpm typecheck`; a runtime check also warns if the deployed
server returns fewer tools.
* Adds unit tests for the above.

## Additional context

* Verified end-to-end against a local remote MCP server with a dashboard
token: `initialize` 200, tools listed, a tool executed, client closed
cleanly.
* The remote MCP (mgmt-api) already accepts dashboard session tokens
(GoTrue-JWT auth path) — no backend change needed. `NEXT_PUBLIC_MCP_URL`
must point at each env's `/mcp`.
* `@supabase/mcp-server-supabase` is kept — still used by the
self-hosted `/api/mcp` routes.

Closes
[AI-137](https://linear.app/supabase/issue/AI-137/switch-dashboard-assistant-to-remote-mcp)

## Rollout

* **Rollout:** merges with `USE_REMOTE_MCP` off (in-process); flip it to
`true` per environment (staging → prod → Nimbus) once each one's
prerequisites land.
* **Rollback:** unset `USE_REMOTE_MCP` and redeploy to fall back to the
in-process client — no revert needed.

## Summary by CodeRabbit

* **Bug Fixes**
* Improved AI request handling so tool loading and generation clean up
properly when a request is cancelled or the browser connection closes.
* Added safer fallback behavior when remote tool loading fails, so AI
features can continue with available tools instead of stopping entirely.
* Updated remote tool access to use the current project reference and
preserve the correct access headers.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* AI tools now connect more reliably to remote services and stop cleanly
when requests end or are canceled.
* Tool loading is more resilient, continuing with available tools if
remote access is unavailable.

* **Bug Fixes**
* Improved cleanup to prevent lingering connections during SQL
generation and policy workflows.
  * Added safer handling for remote tool changes and invalid responses.

* **Tests**
* Expanded automated coverage for remote tool setup, cancellation, and
fallback behavior.


<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 19:38:21 +01:00

181 lines
6.4 KiB
TypeScript

import { generateText, Output, stepCountIs } from 'ai'
import { IS_PLATFORM } from 'common'
import { source } from 'common-tags'
import { NextApiRequest, NextApiResponse } from 'next'
import { z } from 'zod'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
import { getOrgAIDetails } from '@/lib/ai/ai-details'
import { getModel } from '@/lib/ai/model'
import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'
import { RLS_PROMPT } from '@/lib/ai/prompts'
import { getTools } from '@/lib/ai/tools'
import apiWrapper from '@/lib/api/apiWrapper'
const policySchema = z.object({
sql: z.string().describe('The generated Postgres CREATE POLICY statement.'),
name: z.string().describe('The name of the policy.'),
command: z
.enum(['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'ALL'])
.describe('The SQL command this policy applies to.'),
definition: z
.string()
.optional()
.describe('The USING clause expression (for SELECT, UPDATE, DELETE).'),
check: z.string().optional().describe('The WITH CHECK clause expression (for INSERT, UPDATE).'),
action: z
.enum(['PERMISSIVE', 'RESTRICTIVE'])
.default('PERMISSIVE')
.describe('Whether the policy is PERMISSIVE or RESTRICTIVE.'),
roles: z.array(z.string()).default(['public']).describe('The roles this policy applies to.'),
})
const requestBodySchema = z.object({
tableName: z.string().min(1),
schema: z.string().default('public'),
columns: z.array(z.string()).optional(),
projectRef: z.string().min(1),
connectionString: z.string().min(1),
orgSlug: z.string().optional(),
message: z.string().optional(),
})
async function handler(req: NextApiRequest, res: NextApiResponse) {
const { method } = req
switch (method) {
case 'POST':
return handlePost(req, res)
default:
res.setHeader('Allow', ['POST'])
res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
}
}
export async function handlePost(req: NextApiRequest, res: NextApiResponse) {
const authorization = req.headers.authorization
const accessToken = authorization?.replace('Bearer ', '')
if (IS_PLATFORM && !accessToken) {
return res.status(401).json({ error: 'Authorization token is required' })
}
const body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const { data, error: parseError } = requestBodySchema.safeParse(body)
if (parseError) {
return res.status(400).json({ error: 'Invalid request body', issues: parseError.issues })
}
const { tableName, schema, columns = [], projectRef, connectionString, orgSlug, message } = data
let aiOptInLevel: AiOptInLevel = 'disabled'
if (!IS_PLATFORM) {
aiOptInLevel = 'schema'
}
if (IS_PLATFORM && orgSlug && authorization) {
try {
const { aiOptInLevel: orgAIOptInLevel } = await getOrgAIDetails({
orgSlug,
authorization,
})
aiOptInLevel = orgAIOptInLevel
} catch (error) {
return res.status(400).json({
error: 'There was an error fetching your organization details',
})
}
}
try {
const { modelParams, error: modelError } = await getModel({
provider: 'openai',
modelEntry: DEFAULT_COMPLETION_MODEL,
})
if (modelError) {
return res.status(500).json({ error: modelError.message })
}
// Closes the remote MCP connection opened in getTools when generation is done,
// if anything below throws, or if the client disconnects mid-generation so the
// connection isn't held until generateText resolves on its own (mirrors the
// request-scoped cleanup in generate-v4.ts).
const toolsAbortController = new AbortController()
req.on('close', () => toolsAbortController.abort())
req.on('aborted', () => toolsAbortController.abort())
// Fires when the response finishes or the connection drops.
res.on('close', () => toolsAbortController.abort())
try {
const tools = await getTools({
projectRef,
connectionString,
authorization,
aiOptInLevel,
accessToken,
signal: toolsAbortController.signal,
})
const { experimental_output } = await generateText({
...modelParams,
stopWhen: stepCountIs(5),
prompt: source`
You are a Postgres RLS (Row Level Security) expert.
Determine the most appropriate policies for the "${schema}"."${tableName}" table within a Supabase project.
${columns.length > 0 ? `Table columns: ${columns.join(', ')}` : 'No column metadata provided.'}
${message ? `User request: ${message}` : ''}
RLS Guide: ${RLS_PROMPT}
Requirements:
- Use the available planning and schema tools (like "list_policies" or "list_tables") to inspect the "${schema}" schema and existing policies before generating new ones.
- Ensure policies strictly adhere to the existing schema
- Return a curated list of recommended CREATE POLICY statements as JSON.
- Each policy must include: name, sql, command (SELECT/INSERT/UPDATE/DELETE/ALL), action (PERMISSIVE/RESTRICTIVE), roles (array of role names).
- Include "definition" (USING clause expression without the USING keyword) for SELECT, UPDATE, DELETE policies.
- Include "check" (WITH CHECK clause expression without the WITH CHECK keywords) for INSERT, UPDATE policies.
- Avoid duplicating existing policies and reference the public schema and typical Supabase best practices when deciding the coverage.
- Prefer PERMISSIVE policies unless a RESTRICTIVE policy is explicitly required
`,
tools,
experimental_output: Output.object({
schema: z.object({
policies: z.array(policySchema),
}),
}),
})
// Add table and schema to each policy from the request
const policies = (experimental_output?.policies ?? []).map((policy) => ({
...policy,
table: tableName,
schema,
}))
return res.json(policies)
} finally {
toolsAbortController.abort()
}
} catch (error) {
if (error instanceof Error) {
console.error(`AI policy generation failed: ${error.message}`)
return res.status(500).json({
error: 'Failed to generate policy. Please try again.',
})
}
return res.status(500).json({
error: 'An unknown error occurred.',
})
}
}
const wrapper = (req: NextApiRequest, res: NextApiResponse) =>
apiWrapper(req, res, handler, { withAuth: true })
export default wrapper