The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(ui-library): add MCP server block (#49573)
Saxon Fletcherb04e26872b11
diff --git a/apps/ui-library/components/block-item-code.tsx b/apps/ui-library/components/block-item-code.tsxindex b12512b6ddd..acb6e8def46 100644--- a/apps/ui-library/components/block-item-code.tsx+++ b/apps/ui-library/components/block-item-code.tsx@@ -3,7 +3,7 @@import { File } from 'lucide-react'import { useState } from 'react'import { flattenTree, TreeView, TreeViewItem } from 'ui'-import { CodeBlock } from 'ui-patterns/CodeBlock'+import { CodeBlock, type CodeBlockLang } from 'ui-patterns/CodeBlock'import { RegistryNode } from '@/lib/process-registry'@@ -27,6 +27,27 @@ const flattenChildren = (files: RegistryNode[]): TreeNode[] => {)}+const LANGUAGES: Record<string, CodeBlockLang> = {+ bash: 'bash',+ html: 'html',+ js: 'js',+ json: 'json',+ jsx: 'jsx',+ sh: 'bash',+ sql: 'sql',+ toml: 'toml',+ yaml: 'yaml',+ yml: 'yaml',+}++const languageFor = (fileName: string | undefined): CodeBlockLang => {+ const normalized = fileName?.toLowerCase() ?? ''+ if (normalized.startsWith('.env')) return 'bash'+ if (normalized === 'deno.lock') return 'json'++ return LANGUAGES[normalized.split('.').pop() ?? ''] ?? 'ts'+}+const findFirstFile = (nodes: RegistryNode[]): RegistryNode | null => {for (const node of nodes) {if (node.type === 'file') {@@ -105,7 +126,7 @@ export function BlockItemCode({ files }: BlockItemCodeProps) {<CodeBlockwrapperClassName="w-full"className="h-full max-w-none w-full! flex-1 font-mono text-xs rounded-none border-none"- language="ts"+ language={languageFor(selectedFile.name)}>{selectedFile?.content}</CodeBlock>diff --git a/apps/ui-library/components/block-item.tsx b/apps/ui-library/components/block-item.tsxindex 4285aea9e7f..26c6d9504ec 100644--- a/apps/ui-library/components/block-item.tsx+++ b/apps/ui-library/components/block-item.tsx@@ -9,15 +9,16 @@ const Command = dynamic(() => import('./command').then((mod) => mod.Command), {interface BlockItemProps {name: string+ showOpenInV0?: boolean}-export const BlockItem = ({ name }: BlockItemProps) => {+export const BlockItem = ({ name, showOpenInV0 = true }: BlockItemProps) => {const framework = name.includes('vue') || name.includes('nuxtjs') ? 'vue' : 'react'return (<div className="mt-4"><Command name={name} highlight framework={framework} />- <OpenInV0Button name={name} className="w-fit shrink-0 mt-4" />+ {showOpenInV0 && <OpenInV0Button name={name} className="w-fit shrink-0 mt-4" />}</div>)}diff --git a/apps/ui-library/components/side-navigation.tsx b/apps/ui-library/components/side-navigation.tsxindex b0932110c33..d24ee10c70f 100644--- a/apps/ui-library/components/side-navigation.tsx+++ b/apps/ui-library/components/side-navigation.tsx@@ -3,7 +3,13 @@ import Link from 'next/link'import { CommandMenu } from './command-menu'import { ThemeSwitcherDropdown } from './theme-switcher-dropdown'import NavigationItem from '@/components/side-navigation-item'-import { componentPages, gettingStarted, oauthBlocks, platformBlocks } from '@/config/docs'+import {+ componentPages,+ gettingStarted,+ mcpBlocks,+ oauthBlocks,+ platformBlocks,+} from '@/config/docs'function SideNavigation() {return (@@ -96,6 +102,14 @@ function SideNavigation() {<NavigationItem item={item} key={`${item.href}-${i}`} />))}</div>+ <div className="pb-6">+ <div className="font-mono uppercase text-xs text-foreground-lighter/75 mb-2 px-6 tracking-widest">+ {mcpBlocks.title}+ </div>+ {mcpBlocks.items.map((item, i) => (+ <NavigationItem item={item} key={`${item.href}-${i}`} />+ ))}+ </div><div className="pb-6"><div className="font-mono uppercase text-xs text-foreground-lighter/75 mb-2 px-6 tracking-widest">{platformBlocks.title}diff --git a/apps/ui-library/config/docs.ts b/apps/ui-library/config/docs.tsindex 3e496318a66..7d7f24bb650 100644--- a/apps/ui-library/config/docs.ts+++ b/apps/ui-library/config/docs.ts@@ -50,6 +50,19 @@ export const oauthBlocks: SidebarNavGroup = {],}+export const mcpBlocks: SidebarNavGroup = {+ title: 'MCP',+ items: [+ {+ title: 'MCP Server',+ href: '/docs/headless/mcp-server',+ items: [],+ new: true,+ commandItemLabel: 'MCP Server',+ },+ ],+}+// Component definitions with supported frameworksexport const componentPages: SidebarNavGroup = {title: 'Components',@@ -151,6 +164,10 @@ export const COMMAND_ITEMS = [label: item.commandItemLabel,href: item.href,})),+ ...mcpBlocks.items.map((item) => ({+ label: item.commandItemLabel,+ href: item.href,+ })),]// Framework titles for displaydiff --git a/apps/ui-library/content/docs/headless/mcp-server.mdx b/apps/ui-library/content/docs/headless/mcp-server.mdxnew file mode 100644index 00000000000..fc63aaceac6--- /dev/null+++ b/apps/ui-library/content/docs/headless/mcp-server.mdx@@ -0,0 +1,187 @@+---+title: MCP Server+description: Add a user-scoped MCP server to your product+---++Give embedded product agents and external clients such as Codex, Claude Code,+and ChatGPT secure, user-scoped access to your product through MCP tools. This+block runs as a Supabase Edge Function, verifies Supabase user access tokens,+and gives every tool an RLS-scoped client.++## Installation++<BlockItem name="mcp-server" showOpenInV0={false} />++Installs Deno Edge Function files into a Supabase project or empty directory. No+`components.json` is required.++## Folder structure++<RegistryBlock itemName="mcp-server" />++## Configure the project++The function verifies access tokens itself, so disable the gateway JWT check:++```toml+[functions.mcp-server]+verify_jwt = false+```++The project must sign JWTs with an asymmetric key. Projects that still use the+legacy HS256 secret do not expose signing keys from the JWKS endpoint, so the+function cannot authenticate embedded product sessions or external MCP clients.+Switch to an ES256 or RS256 key in+[JWT Keys](https://supabase.com/dashboard/project/_/settings/jwt).++## Choose how agents authenticate++### Embedded product agents++A trusted product backend can forward its signed-in user's Supabase access+token as `Authorization: Bearer <token>`. This reuses the product session, so+the user does not need to authorize their own product again.++Keep the token inside your backend or agent orchestrator. Never place it in a+prompt or expose it directly to a model provider.++### External MCP clients++External clients authenticate with OAuth, so users approve and revoke each+client separately. Install the [OAuth Consent block](../nextjs/oauth-consent),+then enable OAuth in `supabase/config.toml`:++```toml+[auth.oauth_server]+enabled = true+authorization_url_path = "/oauth/consent"+allow_dynamic_registration = true+```++Set the Auth **Site URL** to the origin that serves `/oauth/consent`. Use HTTPS+in production. Run `supabase config push` or restart the local stack to apply the+change.++`allow_dynamic_registration` lets any compatible client register itself. Set it+to `false` if you register clients yourself.++## Authentication++`withOAuthProtectedResource` serves RFC 9728 metadata at+`/functions/v1/mcp-server/oauth-protected-resource` and adds a+`WWW-Authenticate` challenge to `401` responses so MCP clients can discover the+authorization server.++`withSupabase({ auth: 'user' })` verifies the JWT and provides an RLS-scoped+client. It accepts both product session tokens and OAuth access tokens. OAuth+tokens include `client_id`; ordinary product sessions do not. The included+`whoami` tool exposes that difference.++Any holder of a valid user token can call this function directly. Treat its+tools as an authenticated product API: keep RLS enabled, check authorization for+business operations, and do not add admin clients to the shared tool context.++OAuth scopes control identity, not database or tool access. Use `client_id` for+client-specific policies when it is present, and define the intended behavior+for product sessions where it is null. Never use user-editable metadata for+authorization decisions.++## Add tools++Each tool module exports one registration function:++```ts+// supabase/functions/mcp-server/tools/tasks.ts+import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'+import { z } from 'npm:[email protected]'++import { jsonResult, runtimeErrorResult } from './result.ts'+import type { ToolContext } from './types.ts'++export function registerTasksTools(server: McpServer, { supabase }: ToolContext): void {+ server.registerTool(+ 'close_task',+ {+ description: 'Mark a task as closed.',+ inputSchema: z.object({ id: z.string().uuid() }),+ annotations: { readOnlyHint: false, idempotentHint: true },+ },+ async ({ id }) => {+ try {+ const { data, error } = await supabase+ .from('tasks')+ .update({ closed: true })+ .eq('id', id)+ .select()+ if (error) throw error+ return jsonResult(data)+ } catch (error) {+ return runtimeErrorResult(error)+ }+ }+ )+}+```++Then add one call in `tools/index.ts`, the server's composition point:++```ts+import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'++import { registerTasksTools } from './tasks.ts'+import type { ToolContext } from './types.ts'+import { registerWhoamiTool } from './whoami.ts'++export function registerTools(server: McpServer, context: ToolContext): void {+ registerWhoamiTool(server, context)+ registerTasksTools(server, context)+}+```++Each registration function receives:++- `supabase`, a user-scoped client for Database, Auth, Storage, and Functions+- `userClaims`, the normalized signed-in user identity+- `jwtClaims`, including `client_id` when the caller used OAuth++The context deliberately excludes `supabaseAdmin`. The MCP SDK rejects duplicate+tool names, and `jsonResult` returns both structured data and a text fallback for+older clients.++For typed table and column autocomplete, generate `database.types.ts` and make+the `SupabaseClient` in `tools/types.ts` a `SupabaseClient<Database>`.++## Environment++| Variable | Default | Purpose |+| ------------------------ | ---------------- | -------------------------------- |+| `MCP_SERVER_NAME` | `supabase-mcp` | Server name shown to MCP clients |+| `MCP_SERVER_DESCRIPTION` | Generic sentence | Instructions shown to clients |++## Deploy++Check the function before serving or deploying it:++```bash+cd supabase/functions/mcp-server+deno task check+cd ../../..+supabase functions serve mcp-server --env-file supabase/functions/.env+```++Then deploy:++```bash+supabase config push+supabase functions deploy mcp-server+```++## Further reading++- [OAuth Consent block](../nextjs/oauth-consent)+- [OAuth protected resource middleware](https://supabase.com/docs/reference/server/middleware-withoauthprotectedresource)+- [MCP authentication](https://supabase.com/docs/guides/auth/oauth-server/mcp-authentication)+- [OAuth 2.1 server](https://supabase.com/docs/guides/auth/oauth-server/getting-started)+- [Token security and RLS](https://supabase.com/docs/guides/auth/oauth-server/token-security)+- [OAuth grant management](https://supabase.com/docs/guides/auth/oauth-server/oauth-flows#managing-user-grants)+- [Edge Functions](https://supabase.com/docs/guides/functions)diff --git a/apps/ui-library/public/r/mcp-server.json b/apps/ui-library/public/r/mcp-server.jsonnew file mode 100644index 00000000000..d0a1b02387b--- /dev/null+++ b/apps/ui-library/public/r/mcp-server.json@@ -0,0 +1,52 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "mcp-server",+ "type": "registry:item",+ "title": "MCP Server",+ "description": "Add a user-scoped MCP server to your product.",+ "files": [+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/index.ts",+ "content": "import 'jsr:@supabase/[email protected]/edge-runtime.d.ts'\n\nimport { createMcpHandler, McpServer } from 'npm:@modelcontextprotocol/[email protected]'\nimport {\n withOAuthProtectedResource,\n withSupabase,\n type SupabaseContext,\n} from 'npm:@supabase/[email protected]'\n\nimport { registerTools, type ToolContext } from './tools/index.ts'\n\n// An MCP server as a single Supabase Edge Function. withSupabase accepts any\n// verified user access token and builds an RLS-scoped client, so both embedded\n// product agents and external OAuth clients can act as the signed-in user.\n//\n// withOAuthProtectedResource adds OAuth discovery for external MCP clients and\n// points authentication failures at it. Tools are composed in ./tools/index.ts.\n\nfunction readTextEnv(name: string, fallback: string): string {\n return Deno.env.get(name)?.trim() || fallback\n}\n\nconst SERVER_NAME = readTextEnv('MCP_SERVER_NAME', 'supabase-mcp')\nconst SERVER_DESCRIPTION = readTextEnv(\n 'MCP_SERVER_DESCRIPTION',\n 'MCP access to this Supabase project for the signed-in user.'\n)\n\nconst SERVER_INSTRUCTIONS =\n `${SERVER_DESCRIPTION} ` +\n 'Every tool runs as the signed-in Supabase user, so role grants and Row Level Security apply. ' +\n \"Call tools/list to discover what this project exposes, and read a tool's description and \" +\n 'annotations before calling it — some tools have side effects.'\n\nconst CORS_HEADERS: Record<string, string> = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Authorization, Content-Type, Accept, Mcp-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name',\n 'Access-Control-Expose-Headers': 'WWW-Authenticate, Mcp-Session-Id',\n}\n\nfunction createServer(context: ToolContext): McpServer {\n const server = new McpServer(\n { name: SERVER_NAME, version: '1.0.0' },\n { instructions: SERVER_INSTRUCTIONS }\n )\n\n registerTools(server, context)\n return server\n}\n\nasync function handleMcp(request: Request, ctx: SupabaseContext): Promise<Response> {\n // The server and its tools are bound to this caller for exactly one request.\n const handler = createMcpHandler(\n () =>\n createServer({\n supabase: ctx.supabase,\n // auth: 'user' guarantees both claim shapes before this handler runs.\n userClaims: ctx.userClaims!,\n jwtClaims: ctx.jwtClaims!,\n }),\n { onerror: (error) => console.error('MCP request failed', error) }\n )\n\n return handler.fetch(request)\n}\n\nDeno.serve(\n withOAuthProtectedResource(\n withSupabase({ auth: 'user', cors: { headers: CORS_HEADERS } }, handleMcp)\n )\n)\n",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/index.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.json",+ "content": "{\n \"nodeModulesDir\": \"none\",\n \"compilerOptions\": {\n \"strict\": true\n },\n \"tasks\": {\n \"check\": \"deno check index.ts\"\n }\n}\n",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/deno.json"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/.env.example",+ "content": "# Copy this file to supabase/functions/.env before serving locally:\n# cp supabase/functions/mcp-server/.env.example supabase/functions/.env\n# supabase functions serve mcp-server --env-file supabase/functions/.env\n\n# Keep the protocol-level server name short and project-specific.\nMCP_SERVER_NAME=supabase-mcp\nMCP_SERVER_DESCRIPTION=\"MCP access to this Supabase project for the signed-in user.\"\n",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/.env.example"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/types.ts",+ "content": "import type { SupabaseContext } from 'npm:@supabase/[email protected]'\nimport type { SupabaseClient } from 'npm:@supabase/[email protected]'\n\n// Only expose the user-scoped client and verified identity to tools. Keeping\n// supabaseAdmin out of this type makes bypassing RLS an explicit design choice.\nexport type ToolContext = {\n supabase: SupabaseClient\n userClaims: NonNullable<SupabaseContext['userClaims']>\n jwtClaims: NonNullable<SupabaseContext['jwtClaims']>\n}\n",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/types.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/result.ts",+ "content": "import type { CallToolResult } from 'npm:@modelcontextprotocol/[email protected]'\n\n// Shared helpers for building MCP tool results, so every tool returns the same\n// shape and signals failure the same way.\n\n/**\n * A successful structured result with a JSON text fallback for older clients.\n */\nexport function jsonResult(value: unknown): CallToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(value) ?? 'null' }],\n structuredContent: value ?? null,\n }\n}\n\n/**\n * A failed result. The message goes back to the model so it can correct itself,\n * so keep it actionable — and free of credentials, claims, and stack traces.\n */\nexport function errorResult(message: string): CallToolResult {\n return {\n isError: true,\n content: [{ type: 'text', text: message }],\n }\n}\n\nfunction readString(value: unknown, key: string): string | null {\n if (!value || typeof value !== 'object' || !(key in value)) return null\n const property = (value as Record<string, unknown>)[key]\n return typeof property === 'string' && property ? property : null\n}\n\n/**\n * Turn an unknown thrown value into a safe MCP error. Supabase API errors often\n * carry a `code` and `hint`, both of which help a model fix its next call.\n */\nexport function runtimeErrorResult(error: unknown): CallToolResult {\n const message = error instanceof Error ? error.message : String(error)\n const code = readString(error, 'code')\n const hint = readString(error, 'hint')\n\n return errorResult(\n [code ? `[${code}]` : null, message, hint ? `Hint: ${hint}` : null].filter(Boolean).join(' ')\n )\n}\n",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/result.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/whoami.ts",+ "content": "import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'\n\nimport { jsonResult } from './result.ts'\nimport type { ToolContext } from './types.ts'\n\n// Answers from verified claims, demonstrating that every tool runs as the\n// signed-in user. client_id is present for OAuth tokens and null for ordinary\n// product sessions.\nexport function registerWhoamiTool(\n server: McpServer,\n { userClaims, jwtClaims }: ToolContext\n): void {\n const clientId =\n typeof jwtClaims?.client_id === 'string' && jwtClaims.client_id ? jwtClaims.client_id : null\n\n server.registerTool(\n 'whoami',\n {\n description: \"Return the signed-in user's identity and OAuth client id, when present.\",\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n },\n () =>\n jsonResult({\n id: userClaims.id,\n email: userClaims.email ?? null,\n role: userClaims.role ?? null,\n client_id: clientId,\n })\n )\n}\n",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/whoami.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/index.ts",+ "content": "import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'\n\nimport type { ToolContext } from './types.ts'\nimport { registerWhoamiTool } from './whoami.ts'\n\nexport type { ToolContext } from './types.ts'\n\n// The one composition point for this server. Add one registration call for\n// each tool module; the MCP SDK rejects duplicate protocol tool names.\nexport function registerTools(server: McpServer, context: ToolContext): void {\n registerWhoamiTool(server, context)\n}\n",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/index.ts"+ }+ ],+ "docs": "Disable gateway JWT verification, then deploy the Edge Function. A trusted product backend can call it with the signed-in user's access token. For external clients, install the [OAuth Consent block](https://supabase.com/library/docs/nextjs/oauth-consent), enable OAuth and dynamic registration, and set the Auth Site URL to the consent app. Every call runs through the user's RLS-scoped client. OAuth tokens include `client_id`; product sessions do not, so define policies for both paths. See [MCP authentication](https://supabase.com/docs/guides/auth/oauth-server/mcp-authentication) and [token security](https://supabase.com/docs/guides/auth/oauth-server/token-security)."+}\ No newline at end of filediff --git a/apps/ui-library/public/r/registry.json b/apps/ui-library/public/r/registry.jsonindex 4afb6f79ca5..297a50fdbdb 100644--- a/apps/ui-library/public/r/registry.json+++ b/apps/ui-library/public/r/registry.json@@ -1746,6 +1746,50 @@}]},+ {+ "name": "mcp-server",+ "type": "registry:item",+ "title": "MCP Server",+ "description": "Add a user-scoped MCP server to your product.",+ "docs": "Disable gateway JWT verification, then deploy the Edge Function. A trusted product backend can call it with the signed-in user's access token. For external clients, install the [OAuth Consent block](https://supabase.com/library/docs/nextjs/oauth-consent), enable OAuth and dynamic registration, and set the Auth Site URL to the consent app. Every call runs through the user's RLS-scoped client. OAuth tokens include `client_id`; product sessions do not, so define policies for both paths. See [MCP authentication](https://supabase.com/docs/guides/auth/oauth-server/mcp-authentication) and [token security](https://supabase.com/docs/guides/auth/oauth-server/token-security).",+ "files": [+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/index.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/index.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.json",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/deno.json"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/.env.example",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/.env.example"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/types.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/types.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/result.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/result.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/whoami.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/whoami.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/index.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/index.ts"+ }+ ]+ },{"name": "oauth-consent-nextjs","type": "registry:block",diff --git a/apps/ui-library/registry/blocks.ts b/apps/ui-library/registry/blocks.tsindex f1c045df999..73fcff5d5fc 100644--- a/apps/ui-library/registry/blocks.ts+++ b/apps/ui-library/registry/blocks.ts@@ -4,6 +4,7 @@ import { clients } from './clients'import currentUserAvatar from './default/blocks/current-user-avatar/registry-item.json' with { type: 'json' }import dropzone from './default/blocks/dropzone/registry-item.json' with { type: 'json' }import infiniteQueryHook from './default/blocks/infinite-query-hook/registry-item.json' with { type: 'json' }+import mcpServer from './default/blocks/mcp-server/registry-item.json' with { type: 'json' }import oauthConsentNextjs from './default/blocks/oauth-consent-nextjs/registry-item.json' with { type: 'json' }import oauthConsentReactRouter from './default/blocks/oauth-consent-react-router/registry-item.json' with { type: 'json' }import oauthConsentReact from './default/blocks/oauth-consent-react/registry-item.json' with { type: 'json' }@@ -70,6 +71,10 @@ export const blocks = [// infinite query hook is intentionally not combined with the clients since it depends on clients having database types.infiniteQueryHook as RegistryItem,+ // Backend-only Deno Edge Function block. Every file has an explicit target,+ // so it can be installed directly into a Supabase project.+ mcpServer as RegistryItem,+withClientAndDocs(oauthConsentNextjs as RegistryItem, nextjsClient!),withClientAndDocs(oauthConsentReact as RegistryItem, reactClient!),withClientAndDocs(oauthConsentReactRouter as RegistryItem, reactRouterClient!),diff --git a/apps/ui-library/registry/default/blocks/mcp-server/registry-item.json b/apps/ui-library/registry/default/blocks/mcp-server/registry-item.jsonnew file mode 100644index 00000000000..db05367a31b--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/registry-item.json@@ -0,0 +1,44 @@+{+ "name": "mcp-server",+ "type": "registry:item",+ "title": "MCP Server",+ "description": "Add a user-scoped MCP server to your product.",+ "docs": "Disable gateway JWT verification, then deploy the Edge Function. A trusted product backend can call it with the signed-in user's access token. For external clients, install the [OAuth Consent block](https://supabase.com/library/docs/nextjs/oauth-consent), enable OAuth and dynamic registration, and set the Auth Site URL to the consent app. Every call runs through the user's RLS-scoped client. OAuth tokens include `client_id`; product sessions do not, so define policies for both paths. See [MCP authentication](https://supabase.com/docs/guides/auth/oauth-server/mcp-authentication) and [token security](https://supabase.com/docs/guides/auth/oauth-server/token-security).",+ "files": [+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/index.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/index.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.json",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/deno.json"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/.env.example",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/.env.example"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/types.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/types.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/result.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/result.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/whoami.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/whoami.ts"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/index.ts",+ "type": "registry:file",+ "target": "supabase/functions/mcp-server/tools/index.ts"+ }+ ]+}diff --git a/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/.env.example b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/.env.examplenew file mode 100644index 00000000000..3e99789d9ee--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/.env.example@@ -0,0 +1,7 @@+# Copy this file to supabase/functions/.env before serving locally:+# cp supabase/functions/mcp-server/.env.example supabase/functions/.env+# supabase functions serve mcp-server --env-file supabase/functions/.env++# Keep the protocol-level server name short and project-specific.+MCP_SERVER_NAME=supabase-mcp+MCP_SERVER_DESCRIPTION="MCP access to this Supabase project for the signed-in user."diff --git a/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.json b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.jsonnew file mode 100644index 00000000000..193d6e74a80--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.json@@ -0,0 +1,9 @@+{+ "nodeModulesDir": "none",+ "compilerOptions": {+ "strict": true+ },+ "tasks": {+ "check": "deno check index.ts"+ }+}diff --git a/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/index.ts b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/index.tsnew file mode 100644index 00000000000..95278a36be2--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/index.ts@@ -0,0 +1,73 @@+import 'jsr:@supabase/[email protected]/edge-runtime.d.ts'++import { createMcpHandler, McpServer } from 'npm:@modelcontextprotocol/[email protected]'+import {+ withOAuthProtectedResource,+ withSupabase,+ type SupabaseContext,+} from 'npm:@supabase/[email protected]'++import { registerTools, type ToolContext } from './tools/index.ts'++// An MCP server as a single Supabase Edge Function. withSupabase accepts any+// verified user access token and builds an RLS-scoped client, so both embedded+// product agents and external OAuth clients can act as the signed-in user.+//+// withOAuthProtectedResource adds OAuth discovery for external MCP clients and+// points authentication failures at it. Tools are composed in ./tools/index.ts.++function readTextEnv(name: string, fallback: string): string {+ return Deno.env.get(name)?.trim() || fallback+}++const SERVER_NAME = readTextEnv('MCP_SERVER_NAME', 'supabase-mcp')+const SERVER_DESCRIPTION = readTextEnv(+ 'MCP_SERVER_DESCRIPTION',+ 'MCP access to this Supabase project for the signed-in user.'+)++const SERVER_INSTRUCTIONS =+ `${SERVER_DESCRIPTION} ` ++ 'Every tool runs as the signed-in Supabase user, so role grants and Row Level Security apply. ' ++ "Call tools/list to discover what this project exposes, and read a tool's description and " ++ 'annotations before calling it — some tools have side effects.'++const CORS_HEADERS: Record<string, string> = {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',+ 'Access-Control-Allow-Headers':+ 'Authorization, Content-Type, Accept, Mcp-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name',+ 'Access-Control-Expose-Headers': 'WWW-Authenticate, Mcp-Session-Id',+}++function createServer(context: ToolContext): McpServer {+ const server = new McpServer(+ { name: SERVER_NAME, version: '1.0.0' },+ { instructions: SERVER_INSTRUCTIONS }+ )++ registerTools(server, context)+ return server+}++async function handleMcp(request: Request, ctx: SupabaseContext): Promise<Response> {+ // The server and its tools are bound to this caller for exactly one request.+ const handler = createMcpHandler(+ () =>+ createServer({+ supabase: ctx.supabase,+ // auth: 'user' guarantees both claim shapes before this handler runs.+ userClaims: ctx.userClaims!,+ jwtClaims: ctx.jwtClaims!,+ }),+ { onerror: (error) => console.error('MCP request failed', error) }+ )++ return handler.fetch(request)+}++Deno.serve(+ withOAuthProtectedResource(+ withSupabase({ auth: 'user', cors: { headers: CORS_HEADERS } }, handleMcp)+ )+)diff --git a/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/index.ts b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/index.tsnew file mode 100644index 00000000000..8106f70d70f--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/index.ts@@ -0,0 +1,12 @@+import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'++import type { ToolContext } from './types.ts'+import { registerWhoamiTool } from './whoami.ts'++export type { ToolContext } from './types.ts'++// The one composition point for this server. Add one registration call for+// each tool module; the MCP SDK rejects duplicate protocol tool names.+export function registerTools(server: McpServer, context: ToolContext): void {+ registerWhoamiTool(server, context)+}diff --git a/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/result.ts b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/result.tsnew file mode 100644index 00000000000..33b7071810c--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/result.ts@@ -0,0 +1,45 @@+import type { CallToolResult } from 'npm:@modelcontextprotocol/[email protected]'++// Shared helpers for building MCP tool results, so every tool returns the same+// shape and signals failure the same way.++/**+ * A successful structured result with a JSON text fallback for older clients.+ */+export function jsonResult(value: unknown): CallToolResult {+ return {+ content: [{ type: 'text', text: JSON.stringify(value) ?? 'null' }],+ structuredContent: value ?? null,+ }+}++/**+ * A failed result. The message goes back to the model so it can correct itself,+ * so keep it actionable — and free of credentials, claims, and stack traces.+ */+export function errorResult(message: string): CallToolResult {+ return {+ isError: true,+ content: [{ type: 'text', text: message }],+ }+}++function readString(value: unknown, key: string): string | null {+ if (!value || typeof value !== 'object' || !(key in value)) return null+ const property = (value as Record<string, unknown>)[key]+ return typeof property === 'string' && property ? property : null+}++/**+ * Turn an unknown thrown value into a safe MCP error. Supabase API errors often+ * carry a `code` and `hint`, both of which help a model fix its next call.+ */+export function runtimeErrorResult(error: unknown): CallToolResult {+ const message = error instanceof Error ? error.message : String(error)+ const code = readString(error, 'code')+ const hint = readString(error, 'hint')++ return errorResult(+ [code ? `[${code}]` : null, message, hint ? `Hint: ${hint}` : null].filter(Boolean).join(' ')+ )+}diff --git a/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/types.ts b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/types.tsnew file mode 100644index 00000000000..e88542238b5--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/types.ts@@ -0,0 +1,10 @@+import type { SupabaseContext } from 'npm:@supabase/[email protected]'+import type { SupabaseClient } from 'npm:@supabase/[email protected]'++// Only expose the user-scoped client and verified identity to tools. Keeping+// supabaseAdmin out of this type makes bypassing RLS an explicit design choice.+export type ToolContext = {+ supabase: SupabaseClient+ userClaims: NonNullable<SupabaseContext['userClaims']>+ jwtClaims: NonNullable<SupabaseContext['jwtClaims']>+}diff --git a/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/whoami.ts b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/whoami.tsnew file mode 100644index 00000000000..f01872073e4--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/tools/whoami.ts@@ -0,0 +1,34 @@+import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'++import { jsonResult } from './result.ts'+import type { ToolContext } from './types.ts'++// Answers from verified claims, demonstrating that every tool runs as the+// signed-in user. client_id is present for OAuth tokens and null for ordinary+// product sessions.+export function registerWhoamiTool(+ server: McpServer,+ { userClaims, jwtClaims }: ToolContext+): void {+ const clientId =+ typeof jwtClaims?.client_id === 'string' && jwtClaims.client_id ? jwtClaims.client_id : null++ server.registerTool(+ 'whoami',+ {+ description: "Return the signed-in user's identity and OAuth client id, when present.",+ annotations: {+ readOnlyHint: true,+ destructiveHint: false,+ openWorldHint: false,+ },+ },+ () =>+ jsonResult({+ id: userClaims.id,+ email: userClaims.email ?? null,+ role: userClaims.role ?? null,+ client_id: clientId,+ })+ )+}diff --git a/apps/ui-library/tsconfig.json b/apps/ui-library/tsconfig.jsonindex 6d096180fd0..ea4050eb454 100644--- a/apps/ui-library/tsconfig.json+++ b/apps/ui-library/tsconfig.json@@ -17,5 +17,9 @@".next/types/**/*.ts",".contentlayer/generated"],- "exclude": ["node_modules", "./scripts/build-registry.mts"]+ "exclude": [+ "node_modules",+ "./scripts/build-registry.mts",+ "registry/default/blocks/*/supabase/**"+ ]}