Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Migrate MCP server to @supabase/server middleware

Claude891d42650811
diff --git a/supabase/functions/mcp/index.ts b/supabase/functions/mcp/index.ts
index 6f1f2b78..12d83735 100644
--- a/supabase/functions/mcp/index.ts
+++ b/supabase/functions/mcp/index.ts
@@ -1,270 +1,205 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
-import { McpServer } from "npm:@modelcontextprotocol/[email protected]/server/mcp.js";
-import { WebStandardStreamableHTTPServerTransport } from "npm:@modelcontextprotocol/[email protected]/server/webStandardStreamableHttp.js";
-import { createRemoteJWKSet, jwtVerify, decodeJwt } from "npm:jose@5";
-import { Pool } from "https://deno.land/x/[email protected]/mod.ts";
-import { z } from "npm:zod@^3.25";
+import {
+ createMcpHandler,
+ McpServer,
+} from "npm:@modelcontextprotocol/[email protected]";
+import { pipeline } from "npm:@supabase/[email protected]";
+import { withCors } from "npm:@supabase/[email protected]/cors";
+import {
+ withOAuthProtectedResource,
+ withSupabase,
+} from "npm:@supabase/[email protected]";
+import {
+ withPostgresClient,
+ type PostgresApi,
+} from "npm:@supabase/[email protected]/middleware/postgres";
+// pg is an optional peer dependency of @supabase/server, required by
+// withPostgresClient: importing it puts it in the module graph.
+import pg from "npm:[email protected]";
+import { z } from "npm:zod@^4.3.6";
import { validateReadOnly, validateWrite } from "./validateSql.ts";
import { TASK_LIST_HTML, TASK_LIST_UI_URI } from "./taskListUi.ts";
-import { corsHeaders } from "../_shared/cors.ts";
-// --- Environment & Config ---
-
-const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!;
-const SUPABASE_JWT_ISSUER =
- Deno.env.get("SB_JWT_ISSUER") ?? `${SUPABASE_URL}/auth/v1`;
const CRM_BASE_URL = (Deno.env.get("CRM_BASE_URL") ?? "").replace(/\/$/, "");
-const JWKS = createRemoteJWKSet(
- new URL(`${SUPABASE_URL}/auth/v1/.well-known/jwks.json`),
-);
-
-const connectionString =
- Deno.env.get("SUPABASE_DB_URL") ||
- "postgresql://postgres:postgres@db:5432/postgres";
-const pool = new Pool(connectionString, 1);
-
-// --- URL Helpers ---
+// pg returns int8 (ids, COUNT(*)) as strings. Return numbers instead, so the
+// model can pass ids straight back to the tools that expect integers.
+pg.types.setTypeParser(pg.types.builtins.INT8, Number);
-function getBaseUrl(req: Request): string {
- const forwardedHost = req.headers.get("x-forwarded-host");
- if (forwardedHost) {
- // When behind a proxy (ngrok, production), always use HTTPS.
- // x-forwarded-proto may not survive the Supabase gateway chain.
- return `https://${forwardedHost}`;
- }
- const url = new URL(req.url);
- const host = url.host;
- // Supabase edge functions see http:// internally, but are served over HTTPS publicly
- const proto =
- host.includes("localhost") || host.includes("127.0.0.1") ? "http" : "https";
- return `${proto}://${host}`;
-}
-
-function getResourceMetadataUrl(req: Request): string {
- return `${getBaseUrl(req)}/functions/v1/mcp/oauth-protected-resource`;
-}
-
-// --- Auth ---
+// --- Database: get_schema ---
-interface AuthInfo {
- token: string;
- userId: string;
- role?: string;
- clientId?: string;
+interface ColumnRow {
+ table_name: string;
+ column_name: string;
+ data_type: string;
+ is_nullable: string;
+ column_default: string | null;
+ table_type: string;
}
-async function validateToken(req: Request): Promise<AuthInfo | null> {
- const authHeader = req.headers.get("authorization");
- if (!authHeader) return null;
-
- const [bearer, token] = authHeader.split(" ");
- if (bearer !== "Bearer" || !token) return null;
-
- try {
- const { payload } = await jwtVerify(token, JWKS, {
- issuer: SUPABASE_JWT_ISSUER,
- });
-
- if (!payload.sub) return null;
-
- return {
- token,
- userId: payload.sub,
- role: payload.role as string | undefined,
- clientId: payload.client_id as string | undefined,
- };
- } catch {
- return null;
- }
+interface ForeignKeyRow {
+ source_table: string;
+ source_column: string;
+ target_table: string;
+ target_column: string;
}
-// --- Database: get_schema ---
-
-async function getSchemaData(): Promise<string> {
- const client = await pool.connect();
- try {
- // Query 1: All columns from public schema
- const columnsResult = await client.queryObject<{
- table_name: string;
- column_name: string;
- data_type: string;
- is_nullable: string;
- column_default: string | null;
- table_type: string;
- }>(`
- SELECT
- c.table_name,
- c.column_name,
- c.data_type,
- c.is_nullable,
- c.column_default,
- t.table_type
- FROM information_schema.columns c
- JOIN information_schema.tables t
- ON c.table_name = t.table_name AND c.table_schema = t.table_schema
- WHERE c.table_schema = 'public'
- ORDER BY c.table_name, c.ordinal_position
- `);
-
- // Query 2: Foreign key relationships
- const fkResult = await client.queryObject<{
- source_table: string;
- source_column: string;
- target_table: string;
- target_column: string;
- }>(`
- SELECT
- src.relname AS source_table,
- src_att.attname AS source_column,
- tgt.relname AS target_table,
- tgt_att.attname AS target_column
- FROM pg_catalog.pg_constraint con
- JOIN pg_catalog.pg_class src ON con.conrelid = src.oid
- JOIN pg_catalog.pg_namespace nsp ON src.relnamespace = nsp.oid
- JOIN pg_catalog.pg_class tgt ON con.confrelid = tgt.oid
- JOIN pg_catalog.pg_attribute src_att
- ON src_att.attrelid = con.conrelid AND src_att.attnum = ANY(con.conkey)
- JOIN pg_catalog.pg_attribute tgt_att
- ON tgt_att.attrelid = con.confrelid AND tgt_att.attnum = ANY(con.confkey)
- WHERE con.contype = 'f' AND nsp.nspname = 'public'
- ORDER BY src.relname
- `);
-
- // Group columns by table
- const tables = new Map<
- string,
- {
+async function getSchemaData(postgres: PostgresApi): Promise<string> {
+ // Runs as the caller's role, so information_schema only lists the
+ // columns the caller can actually read.
+ const columns: ColumnRow[] = await postgres.query`
+ SELECT
+ c.table_name,
+ c.column_name,
+ c.data_type,
+ c.is_nullable,
+ c.column_default,
+ t.table_type
+ FROM information_schema.columns c
+ JOIN information_schema.tables t
+ ON c.table_name = t.table_name AND c.table_schema = t.table_schema
+ WHERE c.table_schema = 'public'
+ ORDER BY c.table_name, c.ordinal_position
+ `;
+
+ const foreignKeyRows: ForeignKeyRow[] = await postgres.query`
+ SELECT
+ src.relname AS source_table,
+ src_att.attname AS source_column,
+ tgt.relname AS target_table,
+ tgt_att.attname AS target_column
+ FROM pg_catalog.pg_constraint con
+ JOIN pg_catalog.pg_class src ON con.conrelid = src.oid
+ JOIN pg_catalog.pg_namespace nsp ON src.relnamespace = nsp.oid
+ JOIN pg_catalog.pg_class tgt ON con.confrelid = tgt.oid
+ JOIN pg_catalog.pg_attribute src_att
+ ON src_att.attrelid = con.conrelid AND src_att.attnum = ANY(con.conkey)
+ JOIN pg_catalog.pg_attribute tgt_att
+ ON tgt_att.attrelid = con.confrelid AND tgt_att.attnum = ANY(con.confkey)
+ WHERE con.contype = 'f' AND nsp.nspname = 'public'
+ ORDER BY src.relname
+ `;
+
+ // Group columns by table
+ const tables = new Map<
+ string,
+ {
+ type: string;
+ columns: {
+ name: string;
type: string;
- columns: {
- name: string;
- type: string;
- nullable: boolean;
- default: string | null;
- }[];
- }
- >();
- for (const row of columnsResult.rows) {
- if (!tables.has(row.table_name)) {
- tables.set(row.table_name, {
- type: row.table_type === "VIEW" ? "View" : "Table",
- columns: [],
- });
- }
- tables.get(row.table_name)!.columns.push({
- name: row.column_name,
- type: row.data_type,
- nullable: row.is_nullable === "YES",
- default: row.column_default,
+ nullable: boolean;
+ default: string | null;
+ }[];
+ }
+ >();
+ for (const row of columns) {
+ if (!tables.has(row.table_name)) {
+ tables.set(row.table_name, {
+ type: row.table_type === "VIEW" ? "View" : "Table",
+ columns: [],
});
}
+ tables.get(row.table_name)!.columns.push({
+ name: row.column_name,
+ type: row.data_type,
+ nullable: row.is_nullable === "YES",
+ default: row.column_default,
+ });
+ }
- // Group foreign keys by source table
- const foreignKeys = new Map<
- string,
- { source_column: string; target_table: string; target_column: string }[]
- >();
- for (const row of fkResult.rows) {
- if (!foreignKeys.has(row.source_table)) {
- foreignKeys.set(row.source_table, []);
- }
- foreignKeys.get(row.source_table)!.push({
- source_column: row.source_column,
- target_table: row.target_table,
- target_column: row.target_column,
- });
+ // Group foreign keys by source table
+ const foreignKeys = new Map<
+ string,
+ { source_column: string; target_table: string; target_column: string }[]
+ >();
+ for (const row of foreignKeyRows) {
+ if (!foreignKeys.has(row.source_table)) {
+ foreignKeys.set(row.source_table, []);
}
+ foreignKeys.get(row.source_table)!.push({
+ source_column: row.source_column,
+ target_table: row.target_table,
+ target_column: row.target_column,
+ });
+ }
- // Format output
- const lines: string[] = [];
- for (const [tableName, table] of tables) {
- lines.push(`${table.type}: ${tableName}`);
- for (const col of table.columns) {
- const parts = [` - ${col.name}: ${col.type}`];
- if (col.nullable) parts.push("(nullable)");
- if (col.default) parts.push(`default: ${col.default}`);
- lines.push(parts.join(" "));
- }
- const fks = foreignKeys.get(tableName);
- if (fks && fks.length > 0) {
- lines.push(" Foreign Keys:");
- for (const fk of fks) {
- lines.push(
- ` - ${fk.source_column} -> ${fk.target_table}.${fk.target_column}`,
- );
- }
+ // Format output
+ const lines: string[] = [];
+ for (const [tableName, table] of tables) {
+ lines.push(`${table.type}: ${tableName}`);
+ for (const col of table.columns) {
+ const parts = [` - ${col.name}: ${col.type}`];
+ if (col.nullable) parts.push("(nullable)");
+ if (col.default) parts.push(`default: ${col.default}`);
+ lines.push(parts.join(" "));
+ }
+ const fks = foreignKeys.get(tableName);
+ if (fks && fks.length > 0) {
+ lines.push(" Foreign Keys:");
+ for (const fk of fks) {
+ lines.push(
+ ` - ${fk.source_column} -> ${fk.target_table}.${fk.target_column}`,
+ );
}
- lines.push("");
}
-
- return lines.join("\n");
- } finally {
- client.release();
+ lines.push("");
}
+
+ return lines.join("\n");
}
-// --- Database: query with RLS ---
+// --- Database: LLM-written SQL with RLS ---
-async function executeQueryWithRLS(
+function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+async function runValidatedSql(
+ postgres: PostgresApi,
sql: string,
- userToken: string,
validate: (sql: string) => string | null,
): Promise<
{ success: true; data: unknown[] } | { success: false; error: string }
> {
+ // validate() also guarantees a single statement: queryRaw without params
+ // uses the simple query protocol, which would otherwise accept a COMMIT
+ // that ends the RLS-scoped transaction.
const validationError = validate(sql);
if (validationError) {
return { success: false, error: validationError };
}
-
- const client = await pool.connect();
try {
- const jwtClaims = decodeJwt(userToken);
- const claimsJson = JSON.stringify(jwtClaims);
-
- await client.queryObject("BEGIN");
- // set_config(..., is_local=true) is the parameterized equivalent of
- // SET LOCAL — avoids interpolating JWT claims into a SQL string.
- await client.queryObject(
- "SELECT set_config('role', 'authenticated', true)",
- );
- await client.queryObject({
- text: "SELECT set_config('request.jwt.claims', $1, true)",
- args: [claimsJson],
- });
-
- const result = await client.queryObject(sql);
- await client.queryObject("COMMIT");
-
- // Convert BigInt values to numbers (Deno Postgres returns bigint for
- // PostgreSQL int8/count results, but JSON.stringify can't handle them)
- const rows = JSON.parse(
- JSON.stringify(result.rows, (_key, value) =>
- typeof value === "bigint" ? Number(value) : value,
- ),
- );
- return { success: true, data: rows };
+ return { success: true, data: await postgres.queryRaw(sql) };
} catch (error) {
- try {
- await client.queryObject("ROLLBACK");
- } catch {
- // Ignore rollback errors
- }
- const message =
- error instanceof AggregateError
- ? error.errors.map((e) => e.message).join("; ")
- : error instanceof Error
- ? error.message
- : String(error);
- return { success: false, error: message };
- } finally {
- client.release();
+ return { success: false, error: errorMessage(error) };
}
}
+function sqlToolResult(
+ result:
+ | { success: true; data: unknown[] }
+ | { success: false; error: string },
+) {
+ if (result.success) {
+ return {
+ content: [
+ {
+ type: "text" as const,
+ text: JSON.stringify(result.data, null, 2),
+ },
+ ],
+ };
+ }
+ return {
+ content: [{ type: "text" as const, text: `Error: ${result.error}` }],
+ isError: true,
+ };
+}
+
// --- MCP Server Factory ---
-function createMcpServer(authInfo: AuthInfo): McpServer {
+function createMcpServer(postgres: PostgresApi, userId: string): McpServer {
const server = new McpServer({
name: "atomic-crm",
version: "1.0.0",
@@ -279,7 +214,7 @@ function createMcpServer(authInfo: AuthInfo): McpServer {
annotations: { readOnlyHint: true },
},
async () => {
- const schema = await getSchemaData();
+ const schema = await getSchemaData(postgres);
return { content: [{ type: "text" as const, text: schema }] };
},
);
@@ -317,28 +252,12 @@ Examples:
}),
annotations: { readOnlyHint: true },
},
- async ({ sql }: { sql: string }) => {
+ async ({ sql }) => {
// eslint-disable-next-line no-console
- console.log(`[MCP query] user=${authInfo.userId} sql=${sql}`);
- const result = await executeQueryWithRLS(
- sql,
- authInfo.token,
- validateReadOnly,
+ console.log(`[MCP query] user=${userId} sql=${sql}`);
+ return sqlToolResult(
+ await runValidatedSql(postgres, sql, validateReadOnly),
);
- if (result.success) {
- return {
- content: [
- {
- type: "text" as const,
- text: JSON.stringify(result.data, null, 2),
- },
- ],
- };
- }
- return {
- content: [{ type: "text" as const, text: `Error: ${result.error}` }],
- isError: true,
- };
},
);
@@ -372,28 +291,10 @@ Examples:
}),
annotations: { destructiveHint: true },
},
- async ({ sql }: { sql: string }) => {
+ async ({ sql }) => {
// eslint-disable-next-line no-console
- console.log(`[MCP mutate] user=${authInfo.userId} sql=${sql}`);
- const result = await executeQueryWithRLS(
- sql,
- authInfo.token,
- validateWrite,
- );
- if (result.success) {
- return {
- content: [
- {
- type: "text" as const,
- text: JSON.stringify(result.data, null, 2),
- },
- ],
- };
- }
- return {
- content: [{ type: "text" as const, text: `Error: ${result.error}` }],
- isError: true,
- };
+ console.log(`[MCP mutate] user=${userId} sql=${sql}`);
+ return sqlToolResult(await runValidatedSql(postgres, sql, validateWrite));
},
);
@@ -456,7 +357,6 @@ Examples:
"Id of the linked contact — used to render the contact name as a link to the CRM contact page",
),
});
- type Task = z.infer<typeof taskSchema>;
server.registerTool(
"display_task_list",
@@ -467,9 +367,9 @@ Examples:
This tool is presentational: it does not query the database. Fetch the rows yourself via the query tool (joining contacts for contact_name when useful), then pass them here. Prefer this over replying with a bulleted list of tasks.
Each task should include at least: id (required, used for the mark-as-done action), text, type, due_date, done_date, and optionally contact_name + contact_id (the UI renders the name as a link to the CRM contact page when contact_id is provided).`,
- inputSchema: {
+ inputSchema: z.object({
tasks: z.array(taskSchema).describe("Array of task objects to render"),
- },
+ }),
annotations: { readOnlyHint: true },
_meta: {
ui: {
@@ -478,10 +378,10 @@ Each task should include at least: id (required, used for the mark-as-done actio
},
},
},
- ({ tasks }: { tasks: Task[] }) => {
+ ({ tasks }) => {
// eslint-disable-next-line no-console
console.log(
- `[MCP display_task_list] user=${authInfo.userId} count=${tasks.length}`,
+ `[MCP display_task_list] user=${userId} count=${tasks.length}`,
);
// content carries the display text (used by Claude's guest HTML);
// structuredContent carries the typed data (used by ChatGPT's Apps SDK
@@ -499,13 +399,13 @@ Each task should include at least: id (required, used for the mark-as-done actio
title: "Mark Task Done",
description:
"Mark a single task as done by id. Used by the task-list UI when the user clicks a task's checkmark, and also callable directly by the model.",
- inputSchema: {
+ inputSchema: z.object({
id: z
.number()
.int()
.positive()
.describe("The id of the task to mark as done"),
- },
+ }),
annotations: { idempotentHint: true },
_meta: {
ui: {
@@ -513,136 +413,64 @@ Each task should include at least: id (required, used for the mark-as-done actio
},
},
},
- async ({ id }: { id: number }) => {
- // RETURNING id lets us distinguish a successful update from an
- // RLS-blocked or non-existent row (executeQueryWithRLS would otherwise
- // report success on 0 rows affected).
- const sql = `UPDATE tasks SET done_date = NOW() WHERE id = ${id} RETURNING id`;
+ async ({ id }) => {
// eslint-disable-next-line no-console
- console.log(`[MCP complete_task] user=${authInfo.userId} id=${id}`);
- const result = await executeQueryWithRLS(
- sql,
- authInfo.token,
- validateWrite,
- );
- if (!result.success) {
+ console.log(`[MCP complete_task] user=${userId} id=${id}`);
+ try {
+ // RETURNING id distinguishes a successful update from an RLS-blocked
+ // or non-existent row (both affect 0 rows without an error).
+ const rows = await postgres.query`
+ UPDATE tasks SET done_date = NOW() WHERE id = ${id} RETURNING id
+ `;
+ if (rows.length === 0) {
+ return {
+ content: [
+ {
+ type: "text" as const,
+ text: `Error: task ${id} not found or permission denied.`,
+ },
+ ],
+ isError: true,
+ };
+ }
return {
- content: [{ type: "text" as const, text: `Error: ${result.error}` }],
- isError: true,
+ content: [
+ { type: "text" as const, text: `Task ${id} marked as done.` },
+ ],
};
- }
- if (result.data.length === 0) {
+ } catch (error) {
return {
content: [
- {
- type: "text" as const,
- text: `Error: task ${id} not found or permission denied.`,
- },
+ { type: "text" as const, text: `Error: ${errorMessage(error)}` },
],
isError: true,
};
}
- return {
- content: [
- { type: "text" as const, text: `Task ${id} marked as done.` },
- ],
- };
},
);
return server;
}
-// --- OAuth Protected Resource Metadata ---
-
-function handleProtectedResourceMetadata(req: Request): Response {
- const baseUrl = getBaseUrl(req);
- return new Response(
- JSON.stringify({
- resource: `${baseUrl}/functions/v1/mcp`,
- authorization_servers: [`${baseUrl}/auth/v1`],
- bearer_methods_supported: ["header"],
- }),
- {
- headers: { "Content-Type": "application/json" },
+// --- Request pipeline ---
+
+// withOAuthProtectedResource serves the RFC 9728 metadata and adds the
+// WWW-Authenticate challenge to 401s; withSupabase verifies the user's token
+// against the project JWKS; withPostgresClient runs every query in a
+// transaction scoped to the caller's claims and role, so RLS applies.
+Deno.serve(
+ pipeline(
+ [
+ withCors({}),
+ withOAuthProtectedResource(),
+ withSupabase({ auth: "user" }),
+ withPostgresClient(),
+ ],
+ (req, { postgres, jwtClaims }) => {
+ const userId = String(jwtClaims?.sub);
+ // A fresh server per request: Edge Functions are stateless
+ const handler = createMcpHandler(() => createMcpServer(postgres, userId));
+ return handler.fetch(req);
},
- );
-}
-
-// --- MCP Request Handler ---
-
-async function handleMcpRequest(req: Request): Promise<Response> {
- // Validate auth
- const authInfo = await validateToken(req);
- if (!authInfo) {
- const metadataUrl = getResourceMetadataUrl(req);
- return new Response("Unauthorized", {
- status: 401,
- headers: {
- "WWW-Authenticate": `Bearer resource_metadata="${metadataUrl}"`,
- },
- });
- }
-
- // Create stateless MCP server + transport for this request
- const server = createMcpServer(authInfo);
- const transport = new WebStandardStreamableHTTPServerTransport({
- sessionIdGenerator: undefined, // Stateless
- });
-
- await server.connect(transport);
-
- // Clean up server + transport when the connection closes.
- // Do NOT close in a finally block — the SSE response body is a
- // ReadableStream that must remain open until the client consumes it.
- transport.onclose = () => {
- server.close().catch(() => {});
- };
-
- try {
- return await transport.handleRequest(req);
- } catch (error) {
- console.error("MCP request error:", error);
- await transport.close();
- await server.close();
- return new Response("Internal Server Error", { status: 500 });
- }
-}
-
-// --- CORS Helper ---
-
-function withCorsHeaders(response: Response): Response {
- const headers = new Headers(response.headers);
- for (const [key, value] of Object.entries(corsHeaders)) {
- headers.set(key, value);
- }
- return new Response(response.body, {
- status: response.status,
- statusText: response.statusText,
- headers,
- });
-}
-
-// --- Route Dispatcher ---
-
-Deno.serve(async (req: Request) => {
- // Handle CORS preflight
- if (req.method === "OPTIONS") {
- return new Response(null, { status: 204, headers: corsHeaders });
- }
-
- const url = new URL(req.url);
- const path = url.pathname;
-
- // GET /functions/v1/mcp/oauth-protected-resource → RFC 9728 metadata
- if (path.endsWith("/oauth-protected-resource") && req.method === "GET") {
- return withCorsHeaders(handleProtectedResourceMetadata(req));
- }
-
- // POST/GET/DELETE /functions/v1/mcp → MCP protocol handler
- if (path.endsWith("/mcp") || path.endsWith("/mcp/")) {
- return withCorsHeaders(await handleMcpRequest(req));
- }
-
- return withCorsHeaders(new Response("Not Found", { status: 404 }));
-});
+ ),
+);
diff --git a/supabase/functions/mcp/validateSql.test.ts b/supabase/functions/mcp/validateSql.test.ts
index eaba3ee5..8b3f9829 100644
--- a/supabase/functions/mcp/validateSql.test.ts
+++ b/supabase/functions/mcp/validateSql.test.ts
@@ -72,6 +72,22 @@ describe("validateReadOnly", () => {
["multi-statement (SELECT; SET)", "SELECT 1; SET LOCAL role = 'postgres'"],
["multi-statement (two SELECTs)", "SELECT 1; SELECT 2"],
["unparseable SQL", "NOT VALID SQL %%%"],
+ [
+ "set_config in a CTE (claims impersonation)",
+ "WITH x AS (SELECT set_config('request.jwt.claims', '{\"sub\":\"other\"}', true)) SELECT * FROM x, contacts",
+ ],
+ [
+ "set_config as a table function",
+ "SELECT * FROM set_config('role', 'postgres', true)",
+ ],
+ [
+ "schema-qualified, uppercase set_config",
+ "SELECT pg_catalog.SET_CONFIG('role', 'postgres', true)",
+ ],
+ [
+ "set_config in a subquery",
+ "SELECT id FROM contacts WHERE first_name = (SELECT set_config('role', 'postgres', true))",
+ ],
])("rejects %s", (_label, sql) => {
expect(validateReadOnly(sql)).not.toBeNull();
});
@@ -116,6 +132,14 @@ describe("validateWrite", () => {
"DELETE FROM contacts; SET LOCAL role = 'postgres'",
],
["unparseable SQL", "NOT VALID SQL %%%"],
+ [
+ "set_config in an upsert (admin impersonation)",
+ "INSERT INTO configuration (id, config) VALUES (1, to_jsonb(set_config('request.jwt.claims', '{\"sub\":\"admin-id\"}', true))) ON CONFLICT (id) DO UPDATE SET config = '{}' RETURNING id",
+ ],
+ [
+ "set_config in an UPDATE",
+ "UPDATE tasks SET text = set_config('role', 'postgres', true) WHERE id = 1",
+ ],
])("rejects %s", (_label, sql) => {
expect(validateWrite(sql)).not.toBeNull();
});
diff --git a/supabase/functions/mcp/validateSql.ts b/supabase/functions/mcp/validateSql.ts
index 2f34168e..b5c5491d 100644
--- a/supabase/functions/mcp/validateSql.ts
+++ b/supabase/functions/mcp/validateSql.ts
@@ -1,8 +1,27 @@
-import { parse, type Statement } from "npm:pgsql-ast-parser@^12";
+import { astVisitor, parse, type Statement } from "npm:pgsql-ast-parser@^12";
const ALLOWED_READ_TYPES = new Set(["select", "with"]);
const ALLOWED_WRITE_TYPES = new Set(["insert", "update", "delete", "with"]);
+// RLS reads the caller's identity from the request.jwt.claims setting, and the
+// role from the role setting. A query able to call set_config() could rewrite
+// either mid-statement and act as another user, so it is never allowed.
+const FORBIDDEN_FUNCTIONS = new Set(["set_config"]);
+
+function findForbiddenCall(stmts: Statement[]): string | null {
+ let found: string | null = null;
+ const visitor = astVisitor((map) => ({
+ call: (call) => {
+ if (FORBIDDEN_FUNCTIONS.has(call.function.name.toLowerCase())) {
+ found = call.function.name;
+ }
+ map.super().call(call);
+ },
+ }));
+ for (const stmt of stmts) visitor.statement(stmt);
+ return found;
+}
+
// Collect all statement types found in a parsed AST, including inner
// statements in WITH (CTE) bindings which can contain writable DML.
function collectStatementTypes(stmts: Statement[]): Set<string> {
@@ -43,6 +62,10 @@ export function validateReadOnly(sql: string): string | null {
return `Statement type "${type}" is not allowed in read-only queries. Use the mutate tool for data modifications.`;
}
}
+ const forbiddenCall = findForbiddenCall(stmts);
+ if (forbiddenCall) {
+ return `Function "${forbiddenCall}" is not allowed.`;
+ }
return null;
}
@@ -69,5 +92,9 @@ export function validateWrite(sql: string): string | null {
return `Statement type "${type}" is not allowed. Only INSERT, UPDATE, and DELETE statements are supported.`;
}
}
+ const forbiddenCall = findForbiddenCall(stmts);
+ if (forbiddenCall) {
+ return `Function "${forbiddenCall}" is not allowed.`;
+ }
return null;
}