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 headless app block for TanStack Start (#49579)
Saxon Fletcher19d723358092
diff --git a/.prettierignore b/.prettierignoreindex 1f07211dd8f..41a171fe018 100644--- a/.prettierignore+++ b/.prettierignore@@ -7,6 +7,7 @@ apps/**/out.context/**# prettier-plugin-sql-cst only supports sqlite syntax**/supabase/migrations/*.sql+**/supabase/schemas/**/*.sqlapps/www/schema.sqlapps/www/public/images/*# Generated by apps/www/scripts/generateStaticContent.mjs (GitHub discussion bodies)diff --git a/apps/ui-library/app/example/headless-app/layout.tsx b/apps/ui-library/app/example/headless-app/layout.tsxnew file mode 100644index 00000000000..638e3558e5b--- /dev/null+++ b/apps/ui-library/app/example/headless-app/layout.tsx@@ -0,0 +1,19 @@+import { Metadata } from 'next'++import { BaseInjector } from './../base-injector'++export const metadata: Metadata = {+ title: 'Headless App Example',+}++export default function RootLayout({ children }: { children: React.ReactNode }) {+ return (+ <>+ <BaseInjector />+ <div className="relative flex min-h-screen w-full items-start justify-center bg-studio p-6 preview md:p-10">+ <div className="pointer-events-none absolute z-0 h-full w-full bg-[radial-gradient(oklch(from_var(--foreground-default)_l_c_h_/_0.02)_1px,transparent_1px)] bg-size-[16px_16px] mask-[radial-gradient(ellipse_50%_50%_at_50%_50%,#000_70%,transparent_100%)]" />+ <div className="z-10 w-full max-w-2xl">{children}</div>+ </div>+ </>+ )+}diff --git a/apps/ui-library/app/example/headless-app/page.tsx b/apps/ui-library/app/example/headless-app/page.tsxnew file mode 100644index 00000000000..5d1d1bf0d5f--- /dev/null+++ b/apps/ui-library/app/example/headless-app/page.tsx@@ -0,0 +1,86 @@+'use client'++import { useState } from 'react'++import { ConnectedAgentsView } from '@/registry/default/blocks/headless-app-tanstack/components/connected-agents'+import type { OAuthGrant } from '@/registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants'+import { OAuthConsentCard } from '@/registry/default/blocks/oauth-consent/components/oauth-consent'+import { LoginForm } from '@/registry/default/blocks/password-based-auth-nextjs/components/login-form'++const PRODUCT_NAME = 'Acme'+const MCP_SERVER_URL = 'https://your-project.supabase.co/functions/v1/mcp-server'++const grants: OAuthGrant[] = [+ {+ client: { id: 'claude-code', name: 'Claude Code', uri: '', logo_uri: '' },+ scopes: ['openid', 'profile'],+ granted_at: '2026-08-20T09:12:00Z',+ },+ {+ client: { id: 'codex', name: 'Codex', uri: '', logo_uri: '' },+ scopes: ['openid'],+ granted_at: '2026-08-24T16:40:00Z',+ },+]++const screens = {+ 'sign-in': <LoginForm className="mx-auto w-full max-w-sm" />,+ consent: (+ <OAuthConsentCard+ className="mx-auto w-full max-w-lg"+ clientName="Claude Code"+ productName={PRODUCT_NAME}+ redirectUri="http://localhost:3000/callback"+ email="[email protected]"+ scopes={['openid', 'profile']}+ />+ ),+ connect: (+ <ConnectedAgentsView+ className="mx-auto w-full max-w-lg"+ mcpServerUrl={MCP_SERVER_URL}+ productName={PRODUCT_NAME}+ grants={[]}+ />+ ),+ connected: (+ <ConnectedAgentsView+ className="mx-auto w-full max-w-lg"+ mcpServerUrl={MCP_SERVER_URL}+ productName={PRODUCT_NAME}+ grants={grants}+ />+ ),+}++const labels: Record<keyof typeof screens, string> = {+ 'sign-in': 'Sign in',+ consent: 'Consent',+ connect: 'Connect',+ connected: 'Connected',+}++export default function HeadlessAppDemo() {+ const [screen, setScreen] = useState<keyof typeof screens>('sign-in')++ return (+ <div className="flex flex-col gap-8">+ <div className="mx-auto flex rounded-lg bg-secondary p-1" role="group" aria-label="Screen">+ {(Object.keys(screens) as (keyof typeof screens)[]).map((key) => (+ <button+ key={key}+ type="button"+ tabIndex={0}+ aria-pressed={screen === key}+ data-active={screen === key}+ className="rounded-md px-3 py-1.5 text-xs text-muted-foreground transition-colors data-[active=true]:bg-background data-[active=true]:text-foreground"+ onClick={() => setScreen(key)}+ >+ {labels[key]}+ </button>+ ))}+ </div>+ {screens[screen]}+ </div>+ )+}diff --git a/apps/ui-library/config/docs.ts b/apps/ui-library/config/docs.tsindex 7d7f24bb650..e91b532d833 100644--- a/apps/ui-library/config/docs.ts+++ b/apps/ui-library/config/docs.ts@@ -60,6 +60,14 @@ export const mcpBlocks: SidebarNavGroup = {new: true,commandItemLabel: 'MCP Server',},+ {+ title: 'Headless App',+ supportedFrameworks: ['tanstack'],+ href: '/docs/tanstack/headless-app',+ items: [],+ new: true,+ commandItemLabel: 'Headless App',+ },],}diff --git a/apps/ui-library/content/docs/headless/mcp-server.mdx b/apps/ui-library/content/docs/headless/mcp-server.mdxindex fc63aaceac6..5aa8421caff 100644--- a/apps/ui-library/content/docs/headless/mcp-server.mdx+++ b/apps/ui-library/content/docs/headless/mcp-server.mdx@@ -13,7 +13,11 @@ and gives every tool an RLS-scoped client.<BlockItem name="mcp-server" showOpenInV0={false} />Installs Deno Edge Function files into a Supabase project or empty directory. No-`components.json` is required.+`components.json` is required. Backend files stay in `supabase/` at the project+root even when the frontend uses `src/`.++In a frontend app, add `"supabase/functions/**"` to the app's `tsconfig.json` `exclude`+list, preserving existing entries. Check the function separately with Deno.## Folder structure@@ -28,12 +32,17 @@ The function verifies access tokens itself, so disable the gateway JWT check: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+The project must sign JWTs with an asymmetric key. `withSupabase` verifies user+tokens against the project JWKS and rejects legacy HS256 tokens, so a project+that still uses the legacy secret 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).+Use Supabase CLI 2.117.0 or later. It supplies asymmetric signing keys for local+development and injects the function slug into the Edge Function, so the URL+advertised in the OAuth discovery metadata is canonical whatever path a request+arrives on.+## Choose how agents authenticate### Embedded product agents@@ -67,15 +76,33 @@ to `false` if you register clients yourself.## Authentication-`withOAuthProtectedResource` serves RFC 9728 metadata at-`/functions/v1/mcp-server/oauth-protected-resource` and adds a+The function is a `pipeline` from `@supabase/middleware` with two entries from+`@supabase/server`, in this order:++```ts+Deno.serve(+ pipeline(+ [withOAuthProtectedResource(), withSupabase({ auth: 'user', cors: { headers: CORS_HEADERS } })],+ handleMcp+ )+)+```++`withOAuthProtectedResource()` runs before the auth gate. It 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.+authorization server. On Edge Functions it derives the public URLs itself, locally+and hosted; off Edge Functions pass `resourceServer` and `authorizationServer`.-`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.+`withSupabase({ auth: 'user' })` is the gate. It verifies the JWT and hands+`handleMcp` 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.++Composing `withSupabase` as a `pipeline` entry is alpha in `@supabase/server`+and tracks `@supabase/middleware` 0.x. The nested form,+`withOAuthProtectedResource(withSupabase(config, handleMcp))`, is stable and+behaves the same.Any holder of a valid user token can call this function directly. Treat itstools as an authenticated product API: keep RLS enabled, check authorization for@@ -158,6 +185,18 @@ the `SupabaseClient` in `tools/types.ts` a `SupabaseClient<Database>`.| `MCP_SERVER_NAME` | `supabase-mcp` | Server name shown to MCP clients || `MCP_SERVER_DESCRIPTION` | Generic sentence | Instructions shown to clients |+The block includes `supabase/functions/mcp-server/.env.example`. Copy it before+serving locally, then customize the name and description:++```bash+cp supabase/functions/mcp-server/.env.example supabase/functions/.env+```++Add `supabase/functions/.env` to `.gitignore`. Supabase supplies the project URL,+API keys, and function slug to Edge Functions automatically; OAuth discovery+combines the slug with the public origin the gateway forwards to advertise the+function's public URL.+## DeployCheck the function before serving or deploying it:@@ -173,13 +212,14 @@ Then deploy:```bashsupabase config push+supabase secrets set --env-file supabase/functions/.envsupabase functions deploy mcp-server```## Further reading- [OAuth Consent block](../nextjs/oauth-consent)-- [OAuth protected resource middleware](https://supabase.com/docs/reference/server/middleware-withoauthprotectedresource)+- [`withOAuthProtectedResource` and `pipeline` composition](https://github.com/supabase/server/blob/main/docs/api-reference.md)- [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)diff --git a/apps/ui-library/content/docs/tanstack/headless-app.mdx b/apps/ui-library/content/docs/tanstack/headless-app.mdxnew file mode 100644index 00000000000..17f57b44b9c--- /dev/null+++ b/apps/ui-library/content/docs/tanstack/headless-app.mdx@@ -0,0 +1,82 @@+---+title: Headless App+description: A backend with an agent as the primary interface+---++A headless app uses an AI agent as its primary interface. Users sign in and+approve access in the browser, then work through their agent using MCP tools.+This starter includes task tools and a database with Row Level Security (RLS)+that limits each user to their own data.++<BlockPreview name="headless-app" />++## Installation++Create a TanStack Start app:++```bash+pnpm dlx shadcn@latest init --template start --name my-app+cd my-app+```++Install the headless app:++<BlockItem name="headless-app-tanstack" showOpenInV0={false} />++Merge `supabase/config.toml` if you already have project settings. Add+`"supabase/functions/**"` to your app's `tsconfig.json` exclusions.++## Customize++- Set `VITE_PRODUCT_NAME` in `.env.local` and edit the generated pages and components.+- Define your tables, grants, and RLS policies in `supabase/schemas/`.+- Replace `supabase/functions/mcp-server/tools/tasks.ts` with your app's operations+ and register them in `tools/index.ts`. Use the supplied user-scoped `supabase` client.+- Set `MCP_SERVER_NAME` and `MCP_SERVER_DESCRIPTION` with `supabase secrets set`.++## Deploy++Deploy the frontend using a [TanStack Start hosting adapter](https://tanstack.com/start/latest/docs/framework/react/guide/hosting).+Set these environment variables in your hosting provider before building:++```env+VITE_SUPABASE_URL=https://<project-ref>.supabase.co+VITE_SUPABASE_PUBLISHABLE_KEY=<publishable-key>+VITE_PRODUCT_NAME="Your app"+```++In `supabase/config.toml`, set `auth.site_url` to your deployed HTTPS origin,+update `auth.additional_redirect_urls` for your app's destinations, and set+`auth.email.enable_confirmations = true`. Keep the supplied OAuth and function settings.+Use an ES256 or RS256 signing key in your project's+[JWT Keys](https://supabase.com/dashboard/project/_/settings/jwt).++In [Email Templates](https://supabase.com/dashboard/project/_/auth/templates),+use this confirmation link for sign-up and change `type=email` to `type=recovery`+for password reset:++```html+<a+ href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&next={{ .RedirectTo | urlquery }}"+ >Confirm email</a+>+```++With the [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started)+(2.117.0 or later) and Docker installed, generate a migration:++```bash+supabase db diff -f create_tasks+```++Review the migration, including grants and RLS policies, then deploy:++```bash+supabase link --project-ref <project-ref>+supabase db push+supabase config push+supabase functions deploy mcp-server+```++Open `/agents` on your deployed app, sign in, and copy the server URL into an+MCP client that supports HTTP and OAuth. Approve access to start using your tools.diff --git a/apps/ui-library/content/docs/tanstack/oauth-consent.mdx b/apps/ui-library/content/docs/tanstack/oauth-consent.mdxindex 01e57232cac..b96a944eb96 100644--- a/apps/ui-library/content/docs/tanstack/oauth-consent.mdx+++ b/apps/ui-library/content/docs/tanstack/oauth-consent.mdx@@ -22,7 +22,7 @@ This block includes the [Supabase client](/library/docs/tanstack/client). If youThis block installs an OAuth 2.1 consent route at `/oauth/consent`. It is designed for an app that already has authentication: it does not install sign-in, sign-up, or callback routes.-When the visitor has no session, the consent screen redirects to `/auth/login` and preserves the original consent URL in the `next` query parameter. Update the `signInPath` prop in `routes/oauth/consent.tsx` if your sign-in route is different.+When the visitor has no session, the consent screen redirects to `/login` and preserves the original consent URL in the `next` query parameter. Update the `signInPath` prop in `routes/oauth/consent.tsx` if your sign-in route is different.After sign-in, your login page must send the visitor back to the path in `next`; otherwise the OAuth flow stops at your login screen. The password-based auth and social auth blocks follow `next` automatically. For a custom login page, validate that `next` is a relative path before redirecting to it:@@ -35,7 +35,10 @@ if (next?.startsWith('/') && !next.startsWith('//')) {}```-Set the `productName` prop to replace the `Your product` placeholder in the consent header.+Set `VITE_PRODUCT_NAME` in `.env.local` to replace the `Your product` placeholder+in the consent header. The [Headless App](/library/docs/tanstack/headless-app) uses+the same value for its agents page. For a custom value in code, change the+`productName` prop in `routes/oauth/consent.tsx`.### Getting starteddiff --git a/apps/ui-library/lib/process-registry.ts b/apps/ui-library/lib/process-registry.tsindex 3d8bd3d04bf..738d6ab3507 100644--- a/apps/ui-library/lib/process-registry.ts+++ b/apps/ui-library/lib/process-registry.ts@@ -32,7 +32,7 @@ export function generateRegistryTree(registryPath: string): RegistryNode[] {const sortedRegistry = [...registry.files].sort((a, b) => a.path.localeCompare(b.path))for (const file of sortedRegistry) {- const itemPath = file.target || getDefaultPath(file)+ const itemPath = (file.target || getDefaultPath(file)).replace(/^~\//, '')const pathParts = itemPath.split('/').filter(Boolean)let currentLevel = treediff --git a/apps/ui-library/package.json b/apps/ui-library/package.jsonindex f6d2c00e580..e4c2b22aca5 100644--- a/apps/ui-library/package.json+++ b/apps/ui-library/package.json@@ -15,6 +15,8 @@"build:next": "next build --turbopack","build": "run-p build:content build:registry build:llms build:markdown && pnpm build:next","test:markdown": "tsx --test scripts/library-mdx-to-markdown.test.ts",+ "test:headless-app": "vitest run --config vitest.config.ts",+ "test:headless-tools": "tsx scripts/test-headless-tools.mts","test:middleware": "pnpm run build:markdown && tsx --test middleware.test.ts","start": "next start","lint": "eslint .",@@ -108,6 +110,7 @@"tsconfig": "workspace:*","tsx": "catalog:","typescript": "catalog:",- "vite": "catalog:"+ "vite": "catalog:",+ "vitest": "catalog:"}}diff --git a/apps/ui-library/public/r/headless-app-tanstack.json b/apps/ui-library/public/r/headless-app-tanstack.jsonnew file mode 100644index 00000000000..393171e9d4e--- /dev/null+++ b/apps/ui-library/public/r/headless-app-tanstack.json@@ -0,0 +1,116 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "headless-app-tanstack",+ "type": "registry:block",+ "title": "Headless App for TanStack Start",+ "description": "A backend with an agent as the primary interface, combining auth, OAuth consent, and an MCP server.",+ "dependencies": [+ "@supabase/ssr@latest",+ "@supabase/supabase-js@latest"+ ],+ "registryDependencies": [+ "button",+ "https://supabase.com/library/r/password-based-auth-tanstack.json",+ "https://supabase.com/library/r/oauth-consent-tanstack.json"+ ],+ "files": [+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/index.ts",+ "content": "import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'\n\nimport { registerTaskTools } from './tasks.ts'\nimport type { ToolContext } from './types.ts'\nimport { registerWhoamiTool } from './whoami.ts'\n\nexport type { ToolContext } from './types.ts'\n\n// Add your product's tool modules here. The shared MCP runtime supplies the\n// authenticated context for each request.\nexport function registerTools(server: McpServer, context: ToolContext): void {\n registerWhoamiTool(server, context)\n registerTaskTools(server, context)\n}\n",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/tools/index.ts"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/tasks.ts",+ "content": "import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'\nimport { z } from 'npm:[email protected]'\n\nimport { errorResult, jsonResult, runtimeErrorResult } from './result.ts'\nimport type { ToolContext } from './types.ts'\n\nconst taskFields = 'id, title, closed, created_at'\nconst taskId = z.uuid().describe('The task ID returned by list_tasks or create_task.')\nconst taskTitle = z\n .string()\n .trim()\n .min(1)\n .max(200)\n .describe('A task title, 1–200 characters after trimming surrounding whitespace.')\nconst taskNotFound = 'Task not found or you do not have access.'\n\n// Use only the caller's client. Ownership comes from auth.uid() in the schema,\n// and RLS applies to reads and writes, including queries by a supplied task ID.\nexport function registerTaskTools(server: McpServer, { supabase }: ToolContext): void {\n server.registerTool(\n 'list_tasks',\n {\n description:\n 'List your tasks, newest first. Optionally filter by closed status. Pass next_offset as offset to fetch another page; null means there are no more tasks.',\n inputSchema: z.strictObject({\n closed: z.boolean().optional().describe('False for open tasks, true for closed tasks.'),\n limit: z.int().min(1).max(100).default(20).describe('Maximum tasks per page (1–100).'),\n offset: z.int().min(0).default(0).describe('Number of tasks to skip.'),\n }),\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n async ({ closed, limit, offset }) => {\n try {\n let query = supabase\n .from('tasks')\n .select(taskFields)\n .order('created_at', { ascending: false })\n .order('id', { ascending: false })\n .range(offset, offset + limit)\n\n if (closed !== undefined) query = query.eq('closed', closed)\n\n const { data } = await query.throwOnError()\n return jsonResult({\n tasks: data.slice(0, limit),\n next_offset: data.length > limit ? offset + limit : null,\n })\n } catch (error) {\n return runtimeErrorResult(error)\n }\n }\n )\n\n server.registerTool(\n 'create_task',\n {\n description:\n 'Create an open task for yourself and return it. Each call creates a new task; do not retry blindly after a connection failure.',\n inputSchema: z.strictObject({ title: taskTitle }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n async ({ title }) => {\n try {\n const { data } = await supabase\n .from('tasks')\n .insert({ title })\n .select(taskFields)\n .single()\n .throwOnError()\n\n return jsonResult({ task: data })\n } catch (error) {\n return runtimeErrorResult(error)\n }\n }\n )\n\n server.registerTool(\n 'update_task',\n {\n description:\n 'Rename, close, or reopen one of your tasks and return it. Supply title, closed, or both. Fields you omit keep their current values.',\n inputSchema: z\n .strictObject({\n id: taskId,\n title: taskTitle.optional(),\n closed: z.boolean().optional().describe('True to close the task; false to reopen it.'),\n })\n .refine(({ title, closed }) => title !== undefined || closed !== undefined, {\n message: 'Supply title or closed to update a task.',\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n async ({ id, title, closed }) => {\n try {\n const changes = {\n ...(title !== undefined ? { title } : {}),\n ...(closed !== undefined ? { closed } : {}),\n }\n const { data } = await supabase\n .from('tasks')\n .update(changes)\n .eq('id', id)\n .select(taskFields)\n .maybeSingle()\n .throwOnError()\n\n return data ? jsonResult({ task: data }) : errorResult(taskNotFound)\n } catch (error) {\n return runtimeErrorResult(error)\n }\n }\n )\n\n server.registerTool(\n 'delete_task',\n {\n description:\n 'Permanently delete one of your tasks by ID. Use update_task with closed: true to keep a completed task instead.',\n inputSchema: z.strictObject({ id: taskId }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n async ({ id }) => {\n try {\n const { data } = await supabase\n .from('tasks')\n .delete()\n .eq('id', id)\n .select('id')\n .maybeSingle()\n .throwOnError()\n\n return data ? jsonResult({ deleted: true, id: data.id }) : errorResult(taskNotFound)\n } catch (error) {\n return runtimeErrorResult(error)\n }\n }\n )\n}\n",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/tools/tasks.ts"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/routes/_protected/agents.tsx",+ "content": "/// <reference types=\"vite/types/importMeta.d.ts\" />\nimport { createFileRoute } from '@tanstack/react-router'\n\nimport { ConnectedAgents } from '@/registry/default/blocks/headless-app-tanstack/components/connected-agents'\n\nconst PRODUCT_NAME = import.meta.env.VITE_PRODUCT_NAME?.trim() || 'Your product'\nconst MCP_SERVER_URL = `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/mcp-server`\n\n// Nested under _protected, so the layout route redirects signed-out visitors\n// before this renders.\nexport const Route = createFileRoute('/_protected/agents')({\n component: AgentsPage,\n})\n\nfunction AgentsPage() {\n return (\n <main className=\"flex min-h-svh items-center justify-center p-6 md:p-10\">\n <ConnectedAgents\n className=\"w-full max-w-lg\"\n mcpServerUrl={MCP_SERVER_URL}\n productName={PRODUCT_NAME}\n />\n </main>\n )\n}\n",+ "type": "registry:file",+ "target": "routes/_protected/agents.tsx"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/components/connected-agents.tsx",+ "content": "import { Check, Copy } from 'lucide-react'\nimport { useEffect, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\nimport {\n useOAuthGrants,\n type OAuthGrant,\n} from '@/registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants'\nimport { Button } from '@/registry/default/components/ui/button'\n\nconst buildPrompt = (productName: string, mcpServerUrl: string) =>\n `Connect to ${productName} using this MCP server:\\n\\n${mcpServerUrl}\\n\\nUse your MCP connection setup to authorize access in my browser. Then call whoami to verify the connection and list the available tools.`\n\nconst formatDate = (value: string) =>\n new Date(value).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' })\n\nfunction ConnectAgent({\n productName,\n mcpServerUrl,\n}: {\n productName: string\n mcpServerUrl: string\n}) {\n const [copied, setCopied] = useState<'url' | 'prompt' | null>(null)\n const [error, setError] = useState<string | null>(null)\n\n useEffect(() => {\n if (!copied) return\n const timeout = window.setTimeout(() => setCopied(null), 2000)\n return () => window.clearTimeout(timeout)\n }, [copied])\n\n const copy = async (type: 'url' | 'prompt') => {\n setError(null)\n try {\n await navigator.clipboard.writeText(\n type === 'url' ? mcpServerUrl : buildPrompt(productName, mcpServerUrl)\n )\n setCopied(type)\n } catch {\n setCopied(null)\n setError('Unable to copy. Select and copy the server URL above.')\n }\n }\n\n return (\n <section className=\"flex flex-col gap-3\" aria-label=\"Connect an agent\">\n <h2 className=\"font-medium\">Connect an agent</h2>\n <p className=\"text-sm text-muted-foreground\">\n Add this server URL in your agent’s MCP settings, then sign in and approve access.\n </p>\n <div className=\"overflow-hidden rounded-lg border bg-muted\">\n <pre className=\"overflow-x-auto whitespace-pre-wrap break-all p-4 font-mono text-sm\">\n {mcpServerUrl}\n </pre>\n <div className=\"flex flex-wrap justify-end gap-2 border-t p-2\">\n <Button type=\"button\" size=\"sm\" variant=\"outline\" onClick={() => void copy('prompt')}>\n {copied === 'prompt' ? 'Prompt copied' : 'Copy prompt'}\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"outline\" onClick={() => void copy('url')}>\n {copied === 'url' ? <Check className=\"size-4\" /> : <Copy className=\"size-4\" />}\n {copied === 'url' ? 'URL copied' : 'Copy URL'}\n </Button>\n </div>\n </div>\n <p className=\"text-xs text-muted-foreground\">\n Use the prompt if your agent supports adding MCP servers through chat.\n </p>\n {/* Always mounted so screen readers announce the change. */}\n <span role=\"status\" className=\"sr-only\">\n {copied ? 'Copied to clipboard' : ''}\n </span>\n {error && (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n )}\n </section>\n )\n}\n\nfunction GrantRow({\n grant,\n isRevoking,\n disabled,\n onRevoke,\n}: {\n grant: OAuthGrant\n isRevoking: boolean\n disabled: boolean\n onRevoke: () => void\n}) {\n return (\n <li className=\"flex items-center gap-4 p-4\">\n <div className=\"flex min-w-0 flex-1 flex-col gap-1\">\n <span className=\"truncate font-medium\">{grant.client.name}</span>\n <span className=\"truncate text-muted-foreground\">\n Authorized {formatDate(grant.granted_at)}\n {grant.scopes.length > 0 && ` · ${grant.scopes.join(', ')}`}\n </span>\n </div>\n <Button type=\"button\" size=\"sm\" variant=\"outline\" disabled={disabled} onClick={onRevoke}>\n {isRevoking ? 'Revoking access...' : 'Revoke access'}\n </Button>\n </li>\n )\n}\n\nexport interface ConnectedAgentsViewProps extends React.ComponentPropsWithoutRef<'div'> {\n mcpServerUrl: string\n productName?: string\n grants?: OAuthGrant[] | null\n isLoading?: boolean\n error?: string | null\n revokingClientId?: string | null\n onRefresh?: () => void\n onRevoke?: (clientId: string) => void\n}\n\nexport function ConnectedAgentsView({\n mcpServerUrl,\n productName = 'this app',\n grants = null,\n isLoading = false,\n error = null,\n revokingClientId = null,\n onRefresh,\n onRevoke,\n className,\n ...props\n}: ConnectedAgentsViewProps) {\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n <div className=\"flex flex-col space-y-1.5\">\n <h1 className=\"text-2xl font-semibold leading-none tracking-tight\">Connected agents</h1>\n <p className=\"text-sm text-muted-foreground\">\n Authorize agents to use {productName} on your behalf.\n </p>\n </div>\n\n <ConnectAgent productName={productName} mcpServerUrl={mcpServerUrl} />\n\n <section className=\"flex flex-col gap-3\" aria-label=\"Authorized agents\">\n <div className=\"flex items-center justify-between gap-4\">\n <h2 className=\"font-medium\">Authorized agents</h2>\n {onRefresh && (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n disabled={isLoading || revokingClientId !== null}\n onClick={onRefresh}\n >\n {isLoading ? 'Refreshing...' : 'Refresh'}\n </Button>\n )}\n </div>\n {/* Always mounted so screen readers announce the change. */}\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n {isLoading ? 'Loading connected agents...' : ''}\n </p>\n {grants && grants.length > 0 && (\n <ul className=\"divide-y rounded-lg border bg-muted text-sm\">\n {grants.map((grant) => (\n <GrantRow\n key={grant.client.id}\n grant={grant}\n isRevoking={revokingClientId === grant.client.id}\n disabled={isLoading || revokingClientId !== null || !onRevoke}\n onRevoke={() => onRevoke?.(grant.client.id)}\n />\n ))}\n </ul>\n )}\n {!isLoading && !error && grants?.length === 0 && (\n <p className=\"text-sm text-muted-foreground\">\n No agents authorized yet. Connect an agent using the server URL above.\n </p>\n )}\n {error && (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n )}\n {grants && grants.length > 0 && (\n <p className=\"text-xs text-muted-foreground\">\n Revoking access prevents an agent from renewing its session. Its current access token\n may work until it expires.\n </p>\n )}\n </section>\n </div>\n )\n}\n\ninterface ConnectedAgentsProps extends React.ComponentPropsWithoutRef<'div'> {\n mcpServerUrl: string\n productName?: string\n}\n\nexport function ConnectedAgents(props: ConnectedAgentsProps) {\n const { grants, error, isLoading, revokingClientId, refresh, revoke } = useOAuthGrants()\n\n return (\n <ConnectedAgentsView\n grants={grants}\n error={error}\n isLoading={isLoading}\n revokingClientId={revokingClientId}\n onRefresh={() => void refresh()}\n onRevoke={(clientId) => void revoke(clientId)}\n {...props}\n />\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants.ts",+ "content": "import type { OAuthGrant } from '@supabase/supabase-js'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\n// Revocation invalidates refresh tokens. Already-issued access tokens can still\n// be accepted by the MCP server until they expire.\nconst useOAuthGrants = () => {\n const [grants, setGrants] = useState<OAuthGrant[] | null>(null)\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(true)\n const [revokingClientId, setRevokingClientId] = useState<string | null>(null)\n const mounted = useRef(false)\n const requestId = useRef(0)\n const isRevoking = useRef(false)\n\n const refresh = useCallback(async () => {\n if (!mounted.current || isRevoking.current) return\n const id = ++requestId.current\n setIsLoading(true)\n setError(null)\n\n try {\n const { data, error } = await createClient().auth.oauth.listGrants()\n if (error) throw error\n if (mounted.current && id === requestId.current) setGrants(data)\n } catch (error) {\n if (mounted.current && id === requestId.current) {\n setError(\n `Unable to load connected agents. ${error instanceof Error ? error.message : 'Try refreshing the list.'}`\n )\n }\n } finally {\n if (mounted.current && id === requestId.current) setIsLoading(false)\n }\n }, [])\n\n useEffect(() => {\n mounted.current = true\n const onFocus = () => void refresh()\n void refresh()\n window.addEventListener('focus', onFocus)\n return () => {\n mounted.current = false\n window.removeEventListener('focus', onFocus)\n }\n }, [refresh])\n\n const revoke = useCallback(async (clientId: string) => {\n if (!mounted.current || isRevoking.current) return\n isRevoking.current = true\n // A list request started before revocation must not restore the removed grant.\n const id = ++requestId.current\n setIsLoading(false)\n setRevokingClientId(clientId)\n setError(null)\n\n try {\n const { error } = await createClient().auth.oauth.revokeGrant({ clientId })\n if (error) throw error\n if (mounted.current && id === requestId.current) {\n setGrants((current) => current?.filter((grant) => grant.client.id !== clientId) ?? null)\n }\n } catch (error) {\n if (mounted.current && id === requestId.current) {\n setError(\n `Unable to revoke access. ${error instanceof Error ? error.message : 'Try revoking access again.'}`\n )\n }\n } finally {\n isRevoking.current = false\n if (mounted.current && id === requestId.current) setRevokingClientId(null)\n }\n }, [])\n\n return { grants, error, isLoading, revokingClientId, refresh, revoke }\n}\n\ntype UseOAuthGrantsReturn = ReturnType<typeof useOAuthGrants>\n\nexport { useOAuthGrants, type OAuthGrant, type UseOAuthGrantsReturn }\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/config.toml",+ "content": "# Supabase configuration for a headless app: password auth for the product\n# session, an OAuth 2.1 server for external agents, and the MCP server that both\n# call. Values below are for local development. Set production Auth URLs and\n# enable email confirmations before running `supabase config push`.\n\nproject_id = \"headless-app\"\n\n[api]\nenabled = true\nport = 54321\nschemas = [\"public\", \"graphql_public\"]\nextra_search_path = [\"public\", \"extensions\"]\nmax_rows = 1000\n\n[db]\nport = 54322\n# Used to diff ./schemas into a migration.\nshadow_port = 54320\nmajor_version = 17\n\n# One directory per schema, then one file per object, in dependency order.\n[db.migrations]\nschema_paths = [\n \"./schemas/*/tables/*.sql\",\n \"./schemas/*/views/*.sql\",\n \"./schemas/*/functions/*.sql\",\n]\n\n[studio]\nenabled = true\nport = 54323\n\n[inbucket]\nenabled = true\nport = 54324\n\n[auth]\nenabled = true\n# Origin that serves this app, including /oauth/consent. Use HTTPS in production.\nsite_url = \"http://localhost:3000\"\nadditional_redirect_urls = [\"http://localhost:3000/**\"]\njwt_expiry = 3600\nenable_signup = true\n\n[auth.email]\nenable_signup = true\n# Confirmations are off so local sign-ups can reach the app immediately.\nenable_confirmations = false\n\n# External MCP clients authorize here. Auth sends the user to\n# authorization_url_path, which the OAuth Consent block serves.\n[auth.oauth_server]\nenabled = true\nauthorization_url_path = \"/oauth/consent\"\n# Lets any compatible client register itself. Set to false to register clients\n# yourself.\nallow_dynamic_registration = true\n\n# The MCP server verifies user access tokens itself, so skip the gateway check.\n[functions.mcp-server]\nverify_jwt = false\n",+ "type": "registry:file",+ "target": "~/supabase/config.toml"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/schemas/public/tables/tasks.sql",+ "content": "-- Declarative schema. This file is the source of truth for the tasks table:\n-- edit it, then run `supabase db diff -f <name>` to generate the migration.\n-- Changes made in Studio or the SQL editor are not picked up by the diff.\n\ncreate table public.tasks (\n id uuid primary key default gen_random_uuid(),\n user_id uuid not null default auth.uid() references auth.users (id) on delete cascade,\n title text not null constraint tasks_title_length check (\n char_length(title) between 1 and 200 and title ~ '[^[:space:]]'\n ),\n closed boolean not null default false,\n created_at timestamptz not null default now()\n);\n\n-- Support the ownership policies and the tools' newest-first ordering.\ncreate index tasks_user_id_created_at_id_idx on public.tasks (user_id, created_at desc, id desc);\n\n-- Agents call the MCP server with the user's access token, so every tool runs\n-- under these policies. A tool cannot reach another user's rows.\nalter table public.tasks enable row level security;\n\n-- Expose task operations to signed-in users even when automatic API grants are disabled.\ngrant select, insert, update, delete on table public.tasks to authenticated;\n\ncreate policy \"Users can view their own tasks\"\non public.tasks\nfor select\nto authenticated\nusing ((select auth.uid()) = user_id);\n\ncreate policy \"Users can create their own tasks\"\non public.tasks\nfor insert\nto authenticated\nwith check ((select auth.uid()) = user_id);\n\ncreate policy \"Users can update their own tasks\"\non public.tasks\nfor update\nto authenticated\nusing ((select auth.uid()) = user_id)\nwith check ((select auth.uid()) = user_id);\n\ncreate policy \"Users can delete their own tasks\"\non public.tasks\nfor delete\nto authenticated\nusing ((select auth.uid()) = user_id);\n",+ "type": "registry:file",+ "target": "~/supabase/schemas/public/tables/tasks.sql"+ },+ {+ "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 { pipeline } from 'npm:@supabase/[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, composed as a pipeline:\n//\n// withOAuthProtectedResource OAuth discovery for external MCP clients. Runs\n// before the auth gate so unauthenticated clients\n// can fetch the RFC 9728 metadata, and adds the\n// WWW-Authenticate challenge to the gate's 401.\n// withSupabase Verifies the user access token and builds an\n// RLS-scoped client, so both embedded product\n// agents and external OAuth clients act as the\n// signed-in user.\n// handleMcp MCP transport and tools (./tools/index.ts).\n//\n// On Supabase Edge Functions the public URLs in the OAuth metadata are derived\n// automatically, locally and hosted. Off Edge Functions, pass `resourceServer`\n// and `authorizationServer` to withOAuthProtectedResource.\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\n// The handler is passed inline so TypeScript infers its context from the entries.\n// Passing `handleMcp` directly collapses the inferred context to `object`.\nDeno.serve(\n pipeline(\n [withOAuthProtectedResource(), withSupabase({ auth: 'user', cors: { headers: CORS_HEADERS } })],\n (request, ctx) => handleMcp(request, ctx)\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/deno.lock",+ "content": "{\n \"version\": \"5\",\n \"specifiers\": {\n \"jsr:@supabase/[email protected]\": \"2.108.2\",\n \"npm:@modelcontextprotocol/[email protected]\": \"2.0.0\",\n \"npm:@supabase/[email protected]\": \"0.5.0\",\n \"npm:@supabase/[email protected]\": \"1.6.0_@[email protected]\",\n \"npm:@supabase/[email protected]\": \"2.108.2\",\n \"npm:openai@^4.52.5\": \"[email protected]\",\n \"npm:[email protected]\": \"4.4.3\"\n },\n \"jsr\": {\n \"@supabase/[email protected]\": {\n \"integrity\": \"39665d68e1cb721b0714ed1f55c075fba16f8d992672b51458660b3c1ec77c8f\",\n \"dependencies\": [\n \"npm:openai\"\n ]\n }\n },\n \"npm\": {\n \"@modelcontextprotocol/[email protected]\": {\n \"integrity\": \"sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==\",\n \"dependencies\": [\n \"zod\"\n ]\n },\n \"@modelcontextprotocol/[email protected]\": {\n \"integrity\": \"sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==\",\n \"dependencies\": [\n \"@modelcontextprotocol/core\",\n \"zod\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-tNaQmBgodDZwgB40mRwVbxFy8IDYwjdpcZ0BYrWiwlULCSQoJj4QoG4zgJT7QRPXcqipefNOzvO/qAu4dF98ag==\",\n \"dependencies\": [\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-RNUX8EiBy3iLwAX19jtRzLyePnl11/fHcgwDHLnpKcDSXt/5qBnh3LUwAtIjT21Q66QsmNUR2esrHziLCpNubw==\",\n \"dependencies\": [\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-OjukUo+5p14zxTuylf2zVg1hZCHWKLO6VrZhtVeQQw09yrVo3GAduvFJPiFDhTAz/Du1ZfEzAR+s6aRAWD5wzQ==\",\n \"dependencies\": [\n \"std-env\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==\"\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-GQ28/Y8hk3CFmkb3kXH1h/AQx6JIYSQfO0CJMRVBcEKZoNy6C45cXAZ4fcJvRC5Id0cs6xnkUV0+c0rIocigsw==\",\n \"dependencies\": [\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-aAGxCSUemZvQIibnCdvNvgaKib28I4rfrNjKbQ9cG1uBLwUsI7hVpGXgEbypCCDhLjQlDTAiJlu7rgljYUT73g==\",\n \"dependencies\": [\n \"@supabase/phoenix\",\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]_@[email protected]\": {\n \"integrity\": \"sha512-LtUkzUqUGip6I2+kvSmA04u3s+npwLseer2yomBnUdQ1zyJPtlgjAqbwsNuGC1DT/FHi1BvvJluI7dZVV2XdTw==\",\n \"dependencies\": [\n \"@supabase/middleware\",\n \"@supabase/supabase-js\",\n \"jose\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-TVZPQxXGxY2+A6yTtm77zUHsh70lBhYUEaJL8RQC+BghcX/ygiMG/rmXrNVBce30/WAeNPa8FiG8HbqlGeV05g==\",\n \"dependencies\": [\n \"iceberg-js\",\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-hFhnPveb5JQg4a0QYicM0swT253YHMdfeRAl2BKHOlI5VAzuHxUGSr8RbwNLYNPauWOgQMS1H8sz8bvYlgwUfQ==\",\n \"dependencies\": [\n \"@supabase/auth-js\",\n \"@supabase/functions-js\",\n \"@supabase/postgrest-js\",\n \"@supabase/realtime-js\",\n \"@supabase/storage-js\"\n ]\n },\n \"@types/[email protected]\": {\n \"integrity\": \"sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==\",\n \"dependencies\": [\n \"@types/node\",\n \"form-data\"\n ]\n },\n \"@types/[email protected]\": {\n \"integrity\": \"sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==\",\n \"dependencies\": [\n \"undici-types\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==\",\n \"dependencies\": [\n \"event-target-shim\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==\",\n \"dependencies\": [\n \"humanize-ms\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==\",\n \"dependencies\": [\n \"es-errors\",\n \"function-bind\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==\",\n \"dependencies\": [\n \"delayed-stream\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==\",\n \"dependencies\": [\n \"call-bind-apply-helpers\",\n \"es-errors\",\n \"gopd\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==\",\n \"dependencies\": [\n \"es-errors\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==\",\n \"dependencies\": [\n \"es-errors\",\n \"get-intrinsic\",\n \"has-tostringtag\",\n \"hasown\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==\",\n \"dependencies\": [\n \"asynckit\",\n \"combined-stream\",\n \"es-set-tostringtag\",\n \"hasown\",\n \"mime-types\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==\",\n \"dependencies\": [\n \"node-domexception\",\n \"web-streams-polyfill\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==\",\n \"dependencies\": [\n \"call-bind-apply-helpers\",\n \"es-define-property\",\n \"es-errors\",\n \"es-object-atoms\",\n \"function-bind\",\n \"get-proto\",\n \"gopd\",\n \"has-symbols\",\n \"hasown\",\n \"math-intrinsics\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==\",\n \"dependencies\": [\n \"dunder-proto\",\n \"es-object-atoms\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==\",\n \"dependencies\": [\n \"has-symbols\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==\",\n \"dependencies\": [\n \"function-bind\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==\",\n \"dependencies\": [\n \"ms\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-iiW7J9qRFlGxvCOIBDBDxFePQSn7ZMAnrYGhrrOo6siO/MIqwfyilLR27pkfDgUk+raLuzADS8A3S/KLBisc0g==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==\",\n \"dependencies\": [\n \"mime-db\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==\",\n \"deprecated\": true\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==\",\n \"dependencies\": [\n \"whatwg-url\"\n ]\n },\n \"[email protected][email protected]\": {\n \"integrity\": \"sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==\",\n \"dependencies\": [\n \"@types/node\",\n \"@types/node-fetch\",\n \"abort-controller\",\n \"agentkeepalive\",\n \"form-data-encoder\",\n \"formdata-node\",\n \"node-fetch\",\n \"zod\"\n ],\n \"optionalPeers\": [\n \"zod\"\n ],\n \"bin\": true\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==\",\n \"dependencies\": [\n \"tr46\",\n \"webidl-conversions\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==\"\n }\n }\n}\n",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/deno.lock"+ },+ {+ "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# Deploy these values after linking your project:\n# supabase secrets set --env-file supabase/functions/.env\n# Supabase provides the project URL and API keys automatically.\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/clients/tanstack/lib/supabase/client.ts",+ "content": "/// <reference types=\"vite/types/importMeta.d.ts\" />\nimport { createBrowserClient } from '@supabase/ssr'\n\nexport function createClient() {\n return createBrowserClient(\n import.meta.env.VITE_SUPABASE_URL!,\n import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY!\n )\n}\n",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/tanstack/lib/supabase/server.ts",+ "content": "import { createServerClient } from '@supabase/ssr'\nimport { getCookies, setCookie } from '@tanstack/react-start/server'\n\nexport function createClient() {\n return createServerClient(\n process.env.VITE_SUPABASE_URL!,\n process.env.VITE_SUPABASE_PUBLISHABLE_KEY!,\n {\n cookies: {\n getAll() {\n return Object.entries(getCookies()).map(\n ([name, value]) =>\n ({\n name,\n value,\n }) as { name: string; value: string }\n )\n },\n setAll(cookies) {\n cookies.forEach((cookie) => {\n setCookie(cookie.name, cookie.value)\n })\n },\n },\n }\n )\n}\n",+ "type": "registry:lib"+ }+ ],+ "envVars": {+ "VITE_PRODUCT_NAME": "Your product",+ "VITE_SUPABASE_URL": "",+ "VITE_SUPABASE_PUBLISHABLE_KEY": ""+ },+ "docs": "Follow https://supabase.com/library/docs/tanstack/headless-app for setup. Merge `supabase/config.toml` with existing project settings. Open `/agents` to connect your agent and approve access, then try the example task tools.\n\nYou'll need to set the following environment variables in your project: `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY`."+}\ No newline at end of filediff --git a/apps/ui-library/public/r/mcp-server.json b/apps/ui-library/public/r/mcp-server.jsonindex cf28c1d344c..f3f1b33971f 100644--- a/apps/ui-library/public/r/mcp-server.json+++ b/apps/ui-library/public/r/mcp-server.json@@ -7,45 +7,51 @@"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",+ "content": "import 'jsr:@supabase/[email protected]/edge-runtime.d.ts'\n\nimport { createMcpHandler, McpServer } from 'npm:@modelcontextprotocol/[email protected]'\nimport { pipeline } from 'npm:@supabase/[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, composed as a pipeline:\n//\n// withOAuthProtectedResource OAuth discovery for external MCP clients. Runs\n// before the auth gate so unauthenticated clients\n// can fetch the RFC 9728 metadata, and adds the\n// WWW-Authenticate challenge to the gate's 401.\n// withSupabase Verifies the user access token and builds an\n// RLS-scoped client, so both embedded product\n// agents and external OAuth clients act as the\n// signed-in user.\n// handleMcp MCP transport and tools (./tools/index.ts).\n//\n// On Supabase Edge Functions the public URLs in the OAuth metadata are derived\n// automatically, locally and hosted. Off Edge Functions, pass `resourceServer`\n// and `authorizationServer` to withOAuthProtectedResource.\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\n// The handler is passed inline so TypeScript infers its context from the entries.\n// Passing `handleMcp` directly collapses the inferred context to `object`.\nDeno.serve(\n pipeline(\n [withOAuthProtectedResource(), withSupabase({ auth: 'user', cors: { headers: CORS_HEADERS } })],\n (request, ctx) => handleMcp(request, ctx)\n )\n)\n","type": "registry:file",- "target": "supabase/functions/mcp-server/index.ts"+ "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"+ "target": "~/supabase/functions/mcp-server/deno.json"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.lock",+ "content": "{\n \"version\": \"5\",\n \"specifiers\": {\n \"jsr:@supabase/[email protected]\": \"2.108.2\",\n \"npm:@modelcontextprotocol/[email protected]\": \"2.0.0\",\n \"npm:@supabase/[email protected]\": \"0.5.0\",\n \"npm:@supabase/[email protected]\": \"1.6.0_@[email protected]\",\n \"npm:@supabase/[email protected]\": \"2.108.2\",\n \"npm:openai@^4.52.5\": \"[email protected]\",\n \"npm:[email protected]\": \"4.4.3\"\n },\n \"jsr\": {\n \"@supabase/[email protected]\": {\n \"integrity\": \"39665d68e1cb721b0714ed1f55c075fba16f8d992672b51458660b3c1ec77c8f\",\n \"dependencies\": [\n \"npm:openai\"\n ]\n }\n },\n \"npm\": {\n \"@modelcontextprotocol/[email protected]\": {\n \"integrity\": \"sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==\",\n \"dependencies\": [\n \"zod\"\n ]\n },\n \"@modelcontextprotocol/[email protected]\": {\n \"integrity\": \"sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==\",\n \"dependencies\": [\n \"@modelcontextprotocol/core\",\n \"zod\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-tNaQmBgodDZwgB40mRwVbxFy8IDYwjdpcZ0BYrWiwlULCSQoJj4QoG4zgJT7QRPXcqipefNOzvO/qAu4dF98ag==\",\n \"dependencies\": [\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-RNUX8EiBy3iLwAX19jtRzLyePnl11/fHcgwDHLnpKcDSXt/5qBnh3LUwAtIjT21Q66QsmNUR2esrHziLCpNubw==\",\n \"dependencies\": [\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-OjukUo+5p14zxTuylf2zVg1hZCHWKLO6VrZhtVeQQw09yrVo3GAduvFJPiFDhTAz/Du1ZfEzAR+s6aRAWD5wzQ==\",\n \"dependencies\": [\n \"std-env\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==\"\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-GQ28/Y8hk3CFmkb3kXH1h/AQx6JIYSQfO0CJMRVBcEKZoNy6C45cXAZ4fcJvRC5Id0cs6xnkUV0+c0rIocigsw==\",\n \"dependencies\": [\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-aAGxCSUemZvQIibnCdvNvgaKib28I4rfrNjKbQ9cG1uBLwUsI7hVpGXgEbypCCDhLjQlDTAiJlu7rgljYUT73g==\",\n \"dependencies\": [\n \"@supabase/phoenix\",\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]_@[email protected]\": {\n \"integrity\": \"sha512-LtUkzUqUGip6I2+kvSmA04u3s+npwLseer2yomBnUdQ1zyJPtlgjAqbwsNuGC1DT/FHi1BvvJluI7dZVV2XdTw==\",\n \"dependencies\": [\n \"@supabase/middleware\",\n \"@supabase/supabase-js\",\n \"jose\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-TVZPQxXGxY2+A6yTtm77zUHsh70lBhYUEaJL8RQC+BghcX/ygiMG/rmXrNVBce30/WAeNPa8FiG8HbqlGeV05g==\",\n \"dependencies\": [\n \"iceberg-js\",\n \"tslib\"\n ]\n },\n \"@supabase/[email protected]\": {\n \"integrity\": \"sha512-hFhnPveb5JQg4a0QYicM0swT253YHMdfeRAl2BKHOlI5VAzuHxUGSr8RbwNLYNPauWOgQMS1H8sz8bvYlgwUfQ==\",\n \"dependencies\": [\n \"@supabase/auth-js\",\n \"@supabase/functions-js\",\n \"@supabase/postgrest-js\",\n \"@supabase/realtime-js\",\n \"@supabase/storage-js\"\n ]\n },\n \"@types/[email protected]\": {\n \"integrity\": \"sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==\",\n \"dependencies\": [\n \"@types/node\",\n \"form-data\"\n ]\n },\n \"@types/[email protected]\": {\n \"integrity\": \"sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==\",\n \"dependencies\": [\n \"undici-types\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==\",\n \"dependencies\": [\n \"event-target-shim\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==\",\n \"dependencies\": [\n \"humanize-ms\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==\",\n \"dependencies\": [\n \"es-errors\",\n \"function-bind\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==\",\n \"dependencies\": [\n \"delayed-stream\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==\",\n \"dependencies\": [\n \"call-bind-apply-helpers\",\n \"es-errors\",\n \"gopd\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==\",\n \"dependencies\": [\n \"es-errors\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==\",\n \"dependencies\": [\n \"es-errors\",\n \"get-intrinsic\",\n \"has-tostringtag\",\n \"hasown\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==\",\n \"dependencies\": [\n \"asynckit\",\n \"combined-stream\",\n \"es-set-tostringtag\",\n \"hasown\",\n \"mime-types\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==\",\n \"dependencies\": [\n \"node-domexception\",\n \"web-streams-polyfill\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==\",\n \"dependencies\": [\n \"call-bind-apply-helpers\",\n \"es-define-property\",\n \"es-errors\",\n \"es-object-atoms\",\n \"function-bind\",\n \"get-proto\",\n \"gopd\",\n \"has-symbols\",\n \"hasown\",\n \"math-intrinsics\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==\",\n \"dependencies\": [\n \"dunder-proto\",\n \"es-object-atoms\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==\",\n \"dependencies\": [\n \"has-symbols\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==\",\n \"dependencies\": [\n \"function-bind\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==\",\n \"dependencies\": [\n \"ms\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-iiW7J9qRFlGxvCOIBDBDxFePQSn7ZMAnrYGhrrOo6siO/MIqwfyilLR27pkfDgUk+raLuzADS8A3S/KLBisc0g==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==\",\n \"dependencies\": [\n \"mime-db\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==\",\n \"deprecated\": true\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==\",\n \"dependencies\": [\n \"whatwg-url\"\n ]\n },\n \"[email protected][email protected]\": {\n \"integrity\": \"sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==\",\n \"dependencies\": [\n \"@types/node\",\n \"@types/node-fetch\",\n \"abort-controller\",\n \"agentkeepalive\",\n \"form-data-encoder\",\n \"formdata-node\",\n \"node-fetch\",\n \"zod\"\n ],\n \"optionalPeers\": [\n \"zod\"\n ],\n \"bin\": true\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==\"\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==\",\n \"dependencies\": [\n \"tr46\",\n \"webidl-conversions\"\n ]\n },\n \"[email protected]\": {\n \"integrity\": \"sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==\"\n }\n }\n}\n",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/deno.lock"},{"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",+ "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# Deploy these values after linking your project:\n# supabase secrets set --env-file supabase/functions/.env\n# Supabase provides the project URL and API keys automatically.\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"+ "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"+ "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"+ "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"+ "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"+ "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)."diff --git a/apps/ui-library/public/r/oauth-consent-tanstack.json b/apps/ui-library/public/r/oauth-consent-tanstack.jsonindex 34cc335915f..8f5020e36a0 100644--- a/apps/ui-library/public/r/oauth-consent-tanstack.json+++ b/apps/ui-library/public/r/oauth-consent-tanstack.json@@ -26,7 +26,7 @@},{"path": "registry/default/blocks/oauth-consent-tanstack/routes/oauth/consent.tsx",- "content": "import { createFileRoute } from '@tanstack/react-router'\n\nimport { OAuthConsent } from '@/registry/default/blocks/oauth-consent/components/oauth-consent'\n\n// This route is installed into the consumer's routes directory. Their TanStack\n// route generator adds it to FileRoutesByPath after installation.\n// @ts-expect-error The local generated route tree does not include this block route.\nexport const Route = createFileRoute('/oauth/consent')({\n component: ConsentPage,\n validateSearch: (search) => ({\n authorization_id: typeof search.authorization_id === 'string' ? search.authorization_id : null,\n }),\n})\n\nfunction ConsentPage() {\n const { authorization_id } = Route.useSearch()\n\n return (\n <main className=\"flex min-h-svh items-center justify-center p-6 md:p-10\">\n <OAuthConsent className=\"w-full max-w-lg\" authorizationId={authorization_id} />\n </main>\n )\n}\n",+ "content": "/// <reference types=\"vite/types/importMeta.d.ts\" />\nimport { createFileRoute } from '@tanstack/react-router'\n\nimport { OAuthConsent } from '@/registry/default/blocks/oauth-consent/components/oauth-consent'\n\n// This route is installed into the consumer's routes directory. Their TanStack\n// route generator adds it to FileRoutesByPath after installation.\nexport const Route = createFileRoute('/oauth/consent')({\n component: ConsentPage,\n validateSearch: (search) => ({\n authorization_id:\n typeof search.authorization_id === 'string' ? search.authorization_id : undefined,\n }),\n})\n\nfunction ConsentPage() {\n const { authorization_id } = Route.useSearch()\n\n return (\n <main className=\"flex min-h-svh items-center justify-center p-6 md:p-10\">\n <OAuthConsent\n className=\"w-full max-w-lg\"\n authorizationId={authorization_id}\n signInPath=\"/login\"\n productName={import.meta.env.VITE_PRODUCT_NAME?.trim() || 'Your product'}\n />\n </main>\n )\n}\n","type": "registry:file","target": "routes/oauth/consent.tsx"},diff --git a/apps/ui-library/public/r/password-based-auth-tanstack.json b/apps/ui-library/public/r/password-based-auth-tanstack.jsonindex 69f33414965..3f51ccb8487 100644--- a/apps/ui-library/public/r/password-based-auth-tanstack.json+++ b/apps/ui-library/public/r/password-based-auth-tanstack.json@@ -30,7 +30,7 @@},{"path": "registry/default/blocks/password-based-auth-tanstack/routes/_protected.tsx",- "content": "import { createFileRoute, redirect } from '@tanstack/react-router'\n\nimport { fetchUser } from '@/registry/default/blocks/password-based-auth-tanstack/lib/supabase/fetch-user-server-fn'\n\nexport const Route = createFileRoute('/_protected')({\n beforeLoad: async () => {\n const user = await fetchUser()\n\n if (!user) {\n throw redirect({ to: '/login' })\n }\n\n return {\n user,\n }\n },\n})\n",+ "content": "import { createFileRoute, redirect } from '@tanstack/react-router'\n\nimport { fetchUser } from '@/registry/default/blocks/password-based-auth-tanstack/lib/supabase/fetch-user-server-fn'\n\nexport const Route = createFileRoute('/_protected')({\n beforeLoad: async ({ location }) => {\n const user = await fetchUser()\n\n if (!user) {\n throw redirect({ href: `/login?next=${encodeURIComponent(location.href)}` })\n }\n\n return {\n user,\n }\n },\n})\n","type": "registry:file","target": "routes/_protected.tsx"},@@ -42,13 +42,13 @@},{"path": "registry/default/blocks/password-based-auth-tanstack/routes/auth/confirm.ts",- "content": "import { type EmailOtpType } from '@supabase/supabase-js'\nimport { createFileRoute, redirect } from '@tanstack/react-router'\nimport { createServerFn } from '@tanstack/react-start'\nimport { getRequest } from '@tanstack/react-start/server'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/server'\n\nconst confirmFn = createServerFn({ method: 'GET' })\n .inputValidator((searchParams: unknown) => {\n if (\n searchParams &&\n typeof searchParams === 'object' &&\n 'token_hash' in searchParams &&\n 'type' in searchParams &&\n 'next' in searchParams\n ) {\n return searchParams\n }\n throw new Error('Invalid search params')\n })\n .handler(async (ctx) => {\n const request = getRequest()\n\n if (!request) {\n throw redirect({ to: `/auth/error`, search: { error: 'No request' } })\n }\n\n const searchParams = ctx.data\n const token_hash = searchParams['token_hash'] as string\n const type = searchParams['type'] as EmailOtpType | null\n const _next = searchParams['next'] as string\n const next = _next?.startsWith('/') ? _next : '/'\n\n if (token_hash && type) {\n const supabase = createClient()\n\n const { error } = await supabase.auth.verifyOtp({\n type,\n token_hash,\n })\n console.log(error?.message)\n if (!error) {\n // redirect user to specified redirect URL or root of app\n throw redirect({ href: next })\n } else {\n // redirect the user to an error page with some instructions\n throw redirect({\n to: `/auth/error`,\n search: { error: error?.message },\n })\n }\n }\n\n // redirect the user to an error page with some instructions\n throw redirect({\n to: `/auth/error`,\n search: { error: 'No token hash or type' },\n })\n })\n\nexport const Route = createFileRoute('/auth/confirm')({\n preload: false,\n loader: (opts) => confirmFn({ data: opts.location.search }),\n})\n",+ "content": "import { type EmailOtpType } from '@supabase/supabase-js'\nimport { createFileRoute, redirect } from '@tanstack/react-router'\nimport { createServerFn } from '@tanstack/react-start'\nimport { getRequest } from '@tanstack/react-start/server'\n\nimport { safeNextPath } from '@/registry/default/blocks/safe-next-path/lib/safe-next-path'\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/server'\n\nconst confirmFn = createServerFn({ method: 'GET' })\n .inputValidator((searchParams: unknown) => {\n if (\n searchParams &&\n typeof searchParams === 'object' &&\n 'token_hash' in searchParams &&\n 'type' in searchParams &&\n 'next' in searchParams\n ) {\n return searchParams\n }\n throw new Error('Invalid search params')\n })\n .handler(async (ctx) => {\n const request = getRequest()\n\n if (!request) {\n throw redirect({ to: `/auth/error`, search: { error: 'No request' } })\n }\n\n const searchParams = ctx.data\n const token_hash = searchParams['token_hash'] as string\n const type = searchParams['type'] as EmailOtpType | null\n const _next = searchParams['next'] as string\n const origin = new URL(request.url).origin\n const next = safeNextPath(\n _next?.startsWith(`${origin}/`) ? _next.slice(origin.length) : _next,\n '/',\n origin\n )\n\n if (token_hash && type) {\n const supabase = createClient()\n\n const { error } = await supabase.auth.verifyOtp({\n type,\n token_hash,\n })\n console.log(error?.message)\n if (!error) {\n // redirect user to specified redirect URL or root of app\n throw redirect({ href: next })\n } else {\n // redirect the user to an error page with some instructions\n throw redirect({\n to: `/auth/error`,\n search: { error: error?.message },\n })\n }\n }\n\n // redirect the user to an error page with some instructions\n throw redirect({\n to: `/auth/error`,\n search: { error: 'No token hash or type' },\n })\n })\n\nexport const Route = createFileRoute('/auth/confirm')({\n preload: false,\n loader: (opts) => confirmFn({ data: opts.location.search }),\n})\n","type": "registry:file","target": "routes/auth/confirm.ts"},{"path": "registry/default/blocks/password-based-auth-tanstack/components/login-form.tsx",- "content": "import { Link } from '@tanstack/react-router'\nimport { useState } from 'react'\n\nimport { cn } from '@/lib/utils'\nimport { safeNextPath } from '@/registry/default/blocks/safe-next-path/lib/safe-next-path'\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\nimport { Button } from '@/registry/default/components/ui/button'\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/registry/default/components/ui/card'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Label } from '@/registry/default/components/ui/label'\n\nexport function LoginForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {\n const [email, setEmail] = useState('')\n const [password, setPassword] = useState('')\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n\n const handleLogin = async (e: React.FormEvent) => {\n e.preventDefault()\n const supabase = createClient()\n setIsLoading(true)\n setError(null)\n\n try {\n const { error } = await supabase.auth.signInWithPassword({\n email,\n password,\n })\n if (error) throw error\n // Follow the `next` query parameter if it is a same-origin relative path, e.g. when\n // the OAuth consent screen sent the user here to sign in first. It may point outside\n // the typed route tree, so it needs a full navigation.\n const next = new URLSearchParams(window.location.search).get('next')\n window.location.assign(safeNextPath(next, '/protected'))\n } catch (error: unknown) {\n setError(error instanceof Error ? error.message : 'An error occurred')\n } finally {\n setIsLoading(false)\n }\n }\n\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Sign in</CardTitle>\n <CardDescription>Enter your email below to sign in to your account</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleLogin}>\n <div className=\"flex flex-col gap-6\">\n <div className=\"grid gap-2\">\n <Label htmlFor=\"email\">Email</Label>\n <Input\n id=\"email\"\n type=\"email\"\n placeholder=\"[email protected]\"\n required\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"password\">Password</Label>\n <Link\n to=\"/forgot-password\"\n className=\"ml-auto inline-block text-sm underline-offset-4 hover:underline\"\n >\n Forgot your password?\n </Link>\n </div>\n <Input\n id=\"password\"\n type=\"password\"\n required\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n />\n </div>\n {error && <p className=\"text-sm text-red-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n {isLoading ? 'Signing in...' : 'Sign in'}\n </Button>\n </div>\n <div className=\"mt-4 text-center text-sm\">\n Don't have an account?{' '}\n <Link to=\"/sign-up\" className=\"underline underline-offset-4\">\n Sign up\n </Link>\n </div>\n </form>\n </CardContent>\n </Card>\n </div>\n )\n}\n",+ "content": "import { Link } from '@tanstack/react-router'\nimport { useState } from 'react'\n\nimport { cn } from '@/lib/utils'\nimport { safeNextPath } from '@/registry/default/blocks/safe-next-path/lib/safe-next-path'\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\nimport { Button } from '@/registry/default/components/ui/button'\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/registry/default/components/ui/card'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Label } from '@/registry/default/components/ui/label'\n\nexport function LoginForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {\n const [email, setEmail] = useState('')\n const [password, setPassword] = useState('')\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n\n const handleLogin = async (e: React.FormEvent) => {\n e.preventDefault()\n const supabase = createClient()\n setIsLoading(true)\n setError(null)\n\n try {\n const { error } = await supabase.auth.signInWithPassword({\n email,\n password,\n })\n if (error) throw error\n // Follow the `next` query parameter if it is a same-origin relative path, e.g. when\n // the OAuth consent screen sent the user here to sign in first. It may point outside\n // the typed route tree, so it needs a full navigation.\n const next = new URLSearchParams(window.location.search).get('next')\n window.location.assign(safeNextPath(next, '/protected'))\n } catch (error: unknown) {\n setError(error instanceof Error ? error.message : 'An error occurred')\n } finally {\n setIsLoading(false)\n }\n }\n\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Sign in</CardTitle>\n <CardDescription>Enter your email below to sign in to your account</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleLogin}>\n <div className=\"flex flex-col gap-6\">\n <div className=\"grid gap-2\">\n <Label htmlFor=\"email\">Email</Label>\n <Input\n id=\"email\"\n type=\"email\"\n placeholder=\"[email protected]\"\n required\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"password\">Password</Label>\n <Link\n to=\"/forgot-password\"\n className=\"ml-auto inline-block text-sm underline-offset-4 hover:underline\"\n >\n Forgot your password?\n </Link>\n </div>\n <Input\n id=\"password\"\n type=\"password\"\n required\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n />\n </div>\n {error && <p className=\"text-sm text-red-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n {isLoading ? 'Signing in...' : 'Sign in'}\n </Button>\n </div>\n <div className=\"mt-4 text-center text-sm\">\n Don't have an account?{' '}\n <Link to=\"/sign-up\" search className=\"underline underline-offset-4\">\n Sign up\n </Link>\n </div>\n </form>\n </CardContent>\n </Card>\n </div>\n )\n}\n","type": "registry:component"},{@@ -65,7 +65,7 @@},{"path": "registry/default/blocks/password-based-auth-tanstack/components/sign-up-form.tsx",- "content": "import { Link, useNavigate } from '@tanstack/react-router'\nimport { useState } from 'react'\n\nimport { cn } from '@/lib/utils'\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\nimport { Button } from '@/registry/default/components/ui/button'\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/registry/default/components/ui/card'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Label } from '@/registry/default/components/ui/label'\n\nexport function SignUpForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {\n const [email, setEmail] = useState('')\n const [password, setPassword] = useState('')\n const [repeatPassword, setRepeatPassword] = useState('')\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const navigate = useNavigate()\n\n const handleSignUp = async (e: React.FormEvent) => {\n e.preventDefault()\n const supabase = createClient()\n setError(null)\n\n if (password !== repeatPassword) {\n setError('Passwords do not match')\n return\n }\n setIsLoading(true)\n\n try {\n const { error } = await supabase.auth.signUp({\n email,\n password,\n options: {\n emailRedirectTo: `${window.location.origin}/protected`,\n },\n })\n if (error) throw error\n await navigate({ to: '/sign-up-success' })\n } catch (error: unknown) {\n setError(error instanceof Error ? error.message : 'An error occurred')\n } finally {\n setIsLoading(false)\n }\n }\n\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Sign up</CardTitle>\n <CardDescription>Create a new account</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSignUp}>\n <div className=\"flex flex-col gap-6\">\n <div className=\"grid gap-2\">\n <Label htmlFor=\"email\">Email</Label>\n <Input\n id=\"email\"\n type=\"email\"\n placeholder=\"[email protected]\"\n required\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"password\">Password</Label>\n </div>\n <Input\n id=\"password\"\n type=\"password\"\n required\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"repeat-password\">Repeat Password</Label>\n </div>\n <Input\n id=\"repeat-password\"\n type=\"password\"\n required\n value={repeatPassword}\n onChange={(e) => setRepeatPassword(e.target.value)}\n />\n </div>\n {error && <p className=\"text-sm text-red-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n {isLoading ? 'Creating an account...' : 'Sign up'}\n </Button>\n </div>\n <div className=\"mt-4 text-center text-sm\">\n Already have an account?{' '}\n <Link to=\"/login\" className=\"underline underline-offset-4\">\n Sign in\n </Link>\n </div>\n </form>\n </CardContent>\n </Card>\n </div>\n )\n}\n",+ "content": "import { Link, useNavigate } from '@tanstack/react-router'\nimport { useState } from 'react'\n\nimport { cn } from '@/lib/utils'\nimport { safeNextPath } from '@/registry/default/blocks/safe-next-path/lib/safe-next-path'\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\nimport { Button } from '@/registry/default/components/ui/button'\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/registry/default/components/ui/card'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Label } from '@/registry/default/components/ui/label'\n\nexport function SignUpForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {\n const [email, setEmail] = useState('')\n const [password, setPassword] = useState('')\n const [repeatPassword, setRepeatPassword] = useState('')\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const navigate = useNavigate()\n\n const handleSignUp = async (e: React.FormEvent) => {\n e.preventDefault()\n const supabase = createClient()\n setError(null)\n\n if (password !== repeatPassword) {\n setError('Passwords do not match')\n return\n }\n setIsLoading(true)\n\n try {\n const next = safeNextPath(\n new URLSearchParams(window.location.search).get('next'),\n '/protected'\n )\n const { data, error } = await supabase.auth.signUp({\n email,\n password,\n options: {\n emailRedirectTo: `${window.location.origin}${next}`,\n },\n })\n if (error) throw error\n if (data.session) {\n window.location.assign(next)\n } else {\n await navigate({ to: '/sign-up-success' })\n }\n } catch (error: unknown) {\n setError(error instanceof Error ? error.message : 'An error occurred')\n } finally {\n setIsLoading(false)\n }\n }\n\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Sign up</CardTitle>\n <CardDescription>Create a new account</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSignUp}>\n <div className=\"flex flex-col gap-6\">\n <div className=\"grid gap-2\">\n <Label htmlFor=\"email\">Email</Label>\n <Input\n id=\"email\"\n type=\"email\"\n placeholder=\"[email protected]\"\n required\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"password\">Password</Label>\n </div>\n <Input\n id=\"password\"\n type=\"password\"\n required\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"repeat-password\">Repeat Password</Label>\n </div>\n <Input\n id=\"repeat-password\"\n type=\"password\"\n required\n value={repeatPassword}\n onChange={(e) => setRepeatPassword(e.target.value)}\n />\n </div>\n {error && <p className=\"text-sm text-red-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n {isLoading ? 'Creating an account...' : 'Sign up'}\n </Button>\n </div>\n <div className=\"mt-4 text-center text-sm\">\n Already have an account?{' '}\n <Link to=\"/login\" search className=\"underline underline-offset-4\">\n Sign in\n </Link>\n </div>\n </form>\n </CardContent>\n </Card>\n </div>\n )\n}\n","type": "registry:component"},{diff --git a/apps/ui-library/public/r/registry.json b/apps/ui-library/public/r/registry.jsonindex 297a50fdbdb..631f8cdbeb9 100644--- a/apps/ui-library/public/r/registry.json+++ b/apps/ui-library/public/r/registry.json@@ -1756,40 +1756,144 @@{"path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/index.ts","type": "registry:file",- "target": "supabase/functions/mcp-server/index.ts"+ "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"+ "target": "~/supabase/functions/mcp-server/deno.json"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.lock",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/deno.lock"},{"path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/.env.example","type": "registry:file",- "target": "supabase/functions/mcp-server/.env.example"+ "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"+ "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"+ "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"+ "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"+ "target": "~/supabase/functions/mcp-server/tools/index.ts"}]},+ {+ "name": "headless-app-tanstack",+ "type": "registry:block",+ "title": "Headless App for TanStack Start",+ "description": "A backend with an agent as the primary interface, combining auth, OAuth consent, and an MCP server.",+ "docs": "Follow https://supabase.com/library/docs/tanstack/headless-app for setup. Merge `supabase/config.toml` with existing project settings. Open `/agents` to connect your agent and approve access, then try the example task tools.\n\nYou'll need to set the following environment variables in your project: `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY`.",+ "envVars": {+ "VITE_PRODUCT_NAME": "Your product",+ "VITE_SUPABASE_URL": "",+ "VITE_SUPABASE_PUBLISHABLE_KEY": ""+ },+ "registryDependencies": [+ "button",+ "https://supabase.com/library/r/password-based-auth-tanstack.json",+ "https://supabase.com/library/r/oauth-consent-tanstack.json"+ ],+ "files": [+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/index.ts",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/tools/index.ts"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/tasks.ts",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/tools/tasks.ts"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/routes/_protected/agents.tsx",+ "type": "registry:file",+ "target": "routes/_protected/agents.tsx"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/components/connected-agents.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants.ts",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/config.toml",+ "type": "registry:file",+ "target": "~/supabase/config.toml"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/schemas/public/tables/tasks.sql",+ "type": "registry:file",+ "target": "~/supabase/schemas/public/tables/tasks.sql"+ },+ {+ "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/deno.lock",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/deno.lock"+ },+ {+ "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/clients/tanstack/lib/supabase/client.ts",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/tanstack/lib/supabase/server.ts",+ "type": "registry:lib"+ }+ ],+ "dependencies": [+ "@supabase/ssr@latest",+ "@supabase/supabase-js@latest"+ ]+ },{"name": "oauth-consent-nextjs","type": "registry:block",diff --git a/apps/ui-library/registry/blocks.ts b/apps/ui-library/registry/blocks.tsindex 73fcff5d5fc..3748445afc1 100644--- a/apps/ui-library/registry/blocks.ts+++ b/apps/ui-library/registry/blocks.ts@@ -3,6 +3,7 @@ import { type RegistryItem } from 'shadcn/schema'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 headlessAppTanstack from './default/blocks/headless-app-tanstack/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' }@@ -48,6 +49,18 @@ const reactClient = clients.find((client) => client.name === 'supabase-client-reconst tanstackClient = clients.find((client) => client.name === 'supabase-client-tanstack')const reactRouterClient = clients.find((client) => client.name === 'supabase-client-react-router')+// Reuse the MCP runtime at build time so installing the headless app writes+// exactly one tool entrypoint, already wired to its example tools.+const headlessApp = {+ ...headlessAppTanstack,+ files: [+ ...headlessAppTanstack.files,+ ...mcpServer.files.filter(+ (file) => !headlessAppTanstack.files.some((ownFile) => ownFile.target === file.target)+ ),+ ],+} as RegistryItem+export const blocks = [safeNextPath as RegistryItem,@@ -75,6 +88,9 @@ export const blocks = [// so it can be installed directly into a Supabase project.mcpServer as RegistryItem,+ // Composes the auth, OAuth consent and MCP server blocks into one app.+ withClientAndDocs(headlessApp, tanstackClient!),+withClientAndDocs(oauthConsentNextjs as RegistryItem, nextjsClient!),withClientAndDocs(oauthConsentReact as RegistryItem, reactClient!),withClientAndDocs(oauthConsentReactRouter as RegistryItem, reactRouterClient!),diff --git a/apps/ui-library/registry/default/blocks/headless-app-tanstack/components/connected-agents.tsx b/apps/ui-library/registry/default/blocks/headless-app-tanstack/components/connected-agents.tsxnew file mode 100644index 00000000000..e763340961e--- /dev/null+++ b/apps/ui-library/registry/default/blocks/headless-app-tanstack/components/connected-agents.tsx@@ -0,0 +1,215 @@+import { Check, Copy } from 'lucide-react'+import { useEffect, useState } from 'react'++import { cn } from '@/lib/utils'+import {+ useOAuthGrants,+ type OAuthGrant,+} from '@/registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants'+import { Button } from '@/registry/default/components/ui/button'++const buildPrompt = (productName: string, mcpServerUrl: string) =>+ `Connect to ${productName} using this MCP server:\n\n${mcpServerUrl}\n\nUse your MCP connection setup to authorize access in my browser. Then call whoami to verify the connection and list the available tools.`++const formatDate = (value: string) =>+ new Date(value).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' })++function ConnectAgent({+ productName,+ mcpServerUrl,+}: {+ productName: string+ mcpServerUrl: string+}) {+ const [copied, setCopied] = useState<'url' | 'prompt' | null>(null)+ const [error, setError] = useState<string | null>(null)++ useEffect(() => {+ if (!copied) return+ const timeout = window.setTimeout(() => setCopied(null), 2000)+ return () => window.clearTimeout(timeout)+ }, [copied])++ const copy = async (type: 'url' | 'prompt') => {+ setError(null)+ try {+ await navigator.clipboard.writeText(+ type === 'url' ? mcpServerUrl : buildPrompt(productName, mcpServerUrl)+ )+ setCopied(type)+ } catch {+ setCopied(null)+ setError('Unable to copy. Select and copy the server URL above.')+ }+ }++ return (+ <section className="flex flex-col gap-3" aria-label="Connect an agent">+ <h2 className="font-medium">Connect an agent</h2>+ <p className="text-sm text-muted-foreground">+ Add this server URL in your agent’s MCP settings, then sign in and approve access.+ </p>+ <div className="overflow-hidden rounded-lg border bg-muted">+ <pre className="overflow-x-auto whitespace-pre-wrap break-all p-4 font-mono text-sm">+ {mcpServerUrl}+ </pre>+ <div className="flex flex-wrap justify-end gap-2 border-t p-2">+ <Button type="button" size="sm" variant="outline" onClick={() => void copy('prompt')}>+ {copied === 'prompt' ? 'Prompt copied' : 'Copy prompt'}+ </Button>+ <Button type="button" size="sm" variant="outline" onClick={() => void copy('url')}>+ {copied === 'url' ? <Check className="size-4" /> : <Copy className="size-4" />}+ {copied === 'url' ? 'URL copied' : 'Copy URL'}+ </Button>+ </div>+ </div>+ <p className="text-xs text-muted-foreground">+ Use the prompt if your agent supports adding MCP servers through chat.+ </p>+ {/* Always mounted so screen readers announce the change. */}+ <span role="status" className="sr-only">+ {copied ? 'Copied to clipboard' : ''}+ </span>+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ </section>+ )+}++function GrantRow({+ grant,+ isRevoking,+ disabled,+ onRevoke,+}: {+ grant: OAuthGrant+ isRevoking: boolean+ disabled: boolean+ onRevoke: () => void+}) {+ return (+ <li className="flex items-center gap-4 p-4">+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="truncate font-medium">{grant.client.name}</span>+ <span className="truncate text-muted-foreground">+ Authorized {formatDate(grant.granted_at)}+ {grant.scopes.length > 0 && ` · ${grant.scopes.join(', ')}`}+ </span>+ </div>+ <Button type="button" size="sm" variant="outline" disabled={disabled} onClick={onRevoke}>+ {isRevoking ? 'Revoking access...' : 'Revoke access'}+ </Button>+ </li>+ )+}++export interface ConnectedAgentsViewProps extends React.ComponentPropsWithoutRef<'div'> {+ mcpServerUrl: string+ productName?: string+ grants?: OAuthGrant[] | null+ isLoading?: boolean+ error?: string | null+ revokingClientId?: string | null+ onRefresh?: () => void+ onRevoke?: (clientId: string) => void+}++export function ConnectedAgentsView({+ mcpServerUrl,+ productName = 'this app',+ grants = null,+ isLoading = false,+ error = null,+ revokingClientId = null,+ onRefresh,+ onRevoke,+ className,+ ...props+}: ConnectedAgentsViewProps) {+ return (+ <div className={cn('flex flex-col gap-6', className)} {...props}>+ <div className="flex flex-col space-y-1.5">+ <h1 className="text-2xl font-semibold leading-none tracking-tight">Connected agents</h1>+ <p className="text-sm text-muted-foreground">+ Authorize agents to use {productName} on your behalf.+ </p>+ </div>++ <ConnectAgent productName={productName} mcpServerUrl={mcpServerUrl} />++ <section className="flex flex-col gap-3" aria-label="Authorized agents">+ <div className="flex items-center justify-between gap-4">+ <h2 className="font-medium">Authorized agents</h2>+ {onRefresh && (+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={isLoading || revokingClientId !== null}+ onClick={onRefresh}+ >+ {isLoading ? 'Refreshing...' : 'Refresh'}+ </Button>+ )}+ </div>+ {/* Always mounted so screen readers announce the change. */}+ <p role="status" className="text-sm text-muted-foreground">+ {isLoading ? 'Loading connected agents...' : ''}+ </p>+ {grants && grants.length > 0 && (+ <ul className="divide-y rounded-lg border bg-muted text-sm">+ {grants.map((grant) => (+ <GrantRow+ key={grant.client.id}+ grant={grant}+ isRevoking={revokingClientId === grant.client.id}+ disabled={isLoading || revokingClientId !== null || !onRevoke}+ onRevoke={() => onRevoke?.(grant.client.id)}+ />+ ))}+ </ul>+ )}+ {!isLoading && !error && grants?.length === 0 && (+ <p className="text-sm text-muted-foreground">+ No agents authorized yet. Connect an agent using the server URL above.+ </p>+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ {grants && grants.length > 0 && (+ <p className="text-xs text-muted-foreground">+ Revoking access prevents an agent from renewing its session. Its current access token+ may work until it expires.+ </p>+ )}+ </section>+ </div>+ )+}++interface ConnectedAgentsProps extends React.ComponentPropsWithoutRef<'div'> {+ mcpServerUrl: string+ productName?: string+}++export function ConnectedAgents(props: ConnectedAgentsProps) {+ const { grants, error, isLoading, revokingClientId, refresh, revoke } = useOAuthGrants()++ return (+ <ConnectedAgentsView+ grants={grants}+ error={error}+ isLoading={isLoading}+ revokingClientId={revokingClientId}+ onRefresh={() => void refresh()}+ onRevoke={(clientId) => void revoke(clientId)}+ {...props}+ />+ )+}diff --git a/apps/ui-library/registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants.ts b/apps/ui-library/registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants.tsnew file mode 100644index 00000000000..403505e52a3--- /dev/null+++ b/apps/ui-library/registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants.ts@@ -0,0 +1,81 @@+import type { OAuthGrant } from '@supabase/supabase-js'+import { useCallback, useEffect, useRef, useState } from 'react'++import { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'++// Revocation invalidates refresh tokens. Already-issued access tokens can still+// be accepted by the MCP server until they expire.+const useOAuthGrants = () => {+ const [grants, setGrants] = useState<OAuthGrant[] | null>(null)+ const [error, setError] = useState<string | null>(null)+ const [isLoading, setIsLoading] = useState(true)+ const [revokingClientId, setRevokingClientId] = useState<string | null>(null)+ const mounted = useRef(false)+ const requestId = useRef(0)+ const isRevoking = useRef(false)++ const refresh = useCallback(async () => {+ if (!mounted.current || isRevoking.current) return+ const id = ++requestId.current+ setIsLoading(true)+ setError(null)++ try {+ const { data, error } = await createClient().auth.oauth.listGrants()+ if (error) throw error+ if (mounted.current && id === requestId.current) setGrants(data)+ } catch (error) {+ if (mounted.current && id === requestId.current) {+ setError(+ `Unable to load connected agents. ${error instanceof Error ? error.message : 'Try refreshing the list.'}`+ )+ }+ } finally {+ if (mounted.current && id === requestId.current) setIsLoading(false)+ }+ }, [])++ useEffect(() => {+ mounted.current = true+ const onFocus = () => void refresh()+ void refresh()+ window.addEventListener('focus', onFocus)+ return () => {+ mounted.current = false+ window.removeEventListener('focus', onFocus)+ }+ }, [refresh])++ const revoke = useCallback(async (clientId: string) => {+ if (!mounted.current || isRevoking.current) return+ isRevoking.current = true+ // A list request started before revocation must not restore the removed grant.+ const id = ++requestId.current+ setIsLoading(false)+ setRevokingClientId(clientId)+ setError(null)++ try {+ const { error } = await createClient().auth.oauth.revokeGrant({ clientId })+ if (error) throw error+ if (mounted.current && id === requestId.current) {+ setGrants((current) => current?.filter((grant) => grant.client.id !== clientId) ?? null)+ }+ } catch (error) {+ if (mounted.current && id === requestId.current) {+ setError(+ `Unable to revoke access. ${error instanceof Error ? error.message : 'Try revoking access again.'}`+ )+ }+ } finally {+ isRevoking.current = false+ if (mounted.current && id === requestId.current) setRevokingClientId(null)+ }+ }, [])++ return { grants, error, isLoading, revokingClientId, refresh, revoke }+}++type UseOAuthGrantsReturn = ReturnType<typeof useOAuthGrants>++export { useOAuthGrants, type OAuthGrant, type UseOAuthGrantsReturn }diff --git a/apps/ui-library/registry/default/blocks/headless-app-tanstack/registry-item.json b/apps/ui-library/registry/default/blocks/headless-app-tanstack/registry-item.jsonnew file mode 100644index 00000000000..c16b04643c1--- /dev/null+++ b/apps/ui-library/registry/default/blocks/headless-app-tanstack/registry-item.json@@ -0,0 +1,50 @@+{+ "name": "headless-app-tanstack",+ "type": "registry:block",+ "title": "Headless App for TanStack Start",+ "description": "A backend with an agent as the primary interface, combining auth, OAuth consent, and an MCP server.",+ "docs": "Follow https://supabase.com/library/docs/tanstack/headless-app for setup. Merge `supabase/config.toml` with existing project settings. Open `/agents` to connect your agent and approve access, then try the example task tools.",+ "envVars": {+ "VITE_PRODUCT_NAME": "Your product"+ },+ "registryDependencies": [+ "button",+ "https://supabase.com/library/r/password-based-auth-tanstack.json",+ "https://supabase.com/library/r/oauth-consent-tanstack.json"+ ],+ "files": [+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/index.ts",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/tools/index.ts"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/tasks.ts",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/tools/tasks.ts"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/routes/_protected/agents.tsx",+ "type": "registry:file",+ "target": "routes/_protected/agents.tsx"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/components/connected-agents.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/hooks/use-oauth-grants.ts",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/config.toml",+ "type": "registry:file",+ "target": "~/supabase/config.toml"+ },+ {+ "path": "registry/default/blocks/headless-app-tanstack/supabase/schemas/public/tables/tasks.sql",+ "type": "registry:file",+ "target": "~/supabase/schemas/public/tables/tasks.sql"+ }+ ]+}diff --git a/apps/ui-library/registry/default/blocks/headless-app-tanstack/routes/_protected/agents.tsx b/apps/ui-library/registry/default/blocks/headless-app-tanstack/routes/_protected/agents.tsxnew file mode 100644index 00000000000..6e53f821030--- /dev/null+++ b/apps/ui-library/registry/default/blocks/headless-app-tanstack/routes/_protected/agents.tsx@@ -0,0 +1,26 @@+/// <reference types="vite/types/importMeta.d.ts" />+import { createFileRoute } from '@tanstack/react-router'++import { ConnectedAgents } from '@/registry/default/blocks/headless-app-tanstack/components/connected-agents'++const PRODUCT_NAME = import.meta.env.VITE_PRODUCT_NAME?.trim() || 'Your product'+const MCP_SERVER_URL = `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/mcp-server`++// Nested under _protected, so the layout route redirects signed-out visitors+// before this renders.+// @ts-expect-error The local generated route tree does not include this block route.+export const Route = createFileRoute('/_protected/agents')({+ component: AgentsPage,+})++function AgentsPage() {+ return (+ <main className="flex min-h-svh items-center justify-center p-6 md:p-10">+ <ConnectedAgents+ className="w-full max-w-lg"+ mcpServerUrl={MCP_SERVER_URL}+ productName={PRODUCT_NAME}+ />+ </main>+ )+}diff --git a/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/config.toml b/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/config.tomlnew file mode 100644index 00000000000..fd5021ba93f--- /dev/null+++ b/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/config.toml@@ -0,0 +1,61 @@+# Supabase configuration for a headless app: password auth for the product+# session, an OAuth 2.1 server for external agents, and the MCP server that both+# call. Values below are for local development. Set production Auth URLs and+# enable email confirmations before running `supabase config push`.++project_id = "headless-app"++[api]+enabled = true+port = 54321+schemas = ["public", "graphql_public"]+extra_search_path = ["public", "extensions"]+max_rows = 1000++[db]+port = 54322+# Used to diff ./schemas into a migration.+shadow_port = 54320+major_version = 17++# One directory per schema, then one file per object, in dependency order.+[db.migrations]+schema_paths = [+ "./schemas/*/tables/*.sql",+ "./schemas/*/views/*.sql",+ "./schemas/*/functions/*.sql",+]++[studio]+enabled = true+port = 54323++[inbucket]+enabled = true+port = 54324++[auth]+enabled = true+# Origin that serves this app, including /oauth/consent. Use HTTPS in production.+site_url = "http://localhost:3000"+additional_redirect_urls = ["http://localhost:3000/**"]+jwt_expiry = 3600+enable_signup = true++[auth.email]+enable_signup = true+# Confirmations are off so local sign-ups can reach the app immediately.+enable_confirmations = false++# External MCP clients authorize here. Auth sends the user to+# authorization_url_path, which the OAuth Consent block serves.+[auth.oauth_server]+enabled = true+authorization_url_path = "/oauth/consent"+# Lets any compatible client register itself. Set to false to register clients+# yourself.+allow_dynamic_registration = true++# The MCP server verifies user access tokens itself, so skip the gateway check.+[functions.mcp-server]+verify_jwt = falsediff --git a/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/index.ts b/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/index.tsnew file mode 100644index 00000000000..df49a47aae7--- /dev/null+++ b/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/index.ts@@ -0,0 +1,14 @@+import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'++import { registerTaskTools } from './tasks.ts'+import type { ToolContext } from './types.ts'+import { registerWhoamiTool } from './whoami.ts'++export type { ToolContext } from './types.ts'++// Add your product's tool modules here. The shared MCP runtime supplies the+// authenticated context for each request.+export function registerTools(server: McpServer, context: ToolContext): void {+ registerWhoamiTool(server, context)+ registerTaskTools(server, context)+}diff --git a/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/tasks.ts b/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/tasks.tsnew file mode 100644index 00000000000..7ee79fa0dad--- /dev/null+++ b/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/functions/mcp-server/tools/tasks.ts@@ -0,0 +1,159 @@+import type { McpServer } from 'npm:@modelcontextprotocol/[email protected]'+import { z } from 'npm:[email protected]'++import { errorResult, jsonResult, runtimeErrorResult } from './result.ts'+import type { ToolContext } from './types.ts'++const taskFields = 'id, title, closed, created_at'+const taskId = z.uuid().describe('The task ID returned by list_tasks or create_task.')+const taskTitle = z+ .string()+ .trim()+ .min(1)+ .max(200)+ .describe('A task title, 1–200 characters after trimming surrounding whitespace.')+const taskNotFound = 'Task not found or you do not have access.'++// Use only the caller's client. Ownership comes from auth.uid() in the schema,+// and RLS applies to reads and writes, including queries by a supplied task ID.+export function registerTaskTools(server: McpServer, { supabase }: ToolContext): void {+ server.registerTool(+ 'list_tasks',+ {+ description:+ 'List your tasks, newest first. Optionally filter by closed status. Pass next_offset as offset to fetch another page; null means there are no more tasks.',+ inputSchema: z.strictObject({+ closed: z.boolean().optional().describe('False for open tasks, true for closed tasks.'),+ limit: z.int().min(1).max(100).default(20).describe('Maximum tasks per page (1–100).'),+ offset: z.int().min(0).default(0).describe('Number of tasks to skip.'),+ }),+ annotations: {+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+ },+ },+ async ({ closed, limit, offset }) => {+ try {+ let query = supabase+ .from('tasks')+ .select(taskFields)+ .order('created_at', { ascending: false })+ .order('id', { ascending: false })+ .range(offset, offset + limit)++ if (closed !== undefined) query = query.eq('closed', closed)++ const { data } = await query.throwOnError()+ return jsonResult({+ tasks: data.slice(0, limit),+ next_offset: data.length > limit ? offset + limit : null,+ })+ } catch (error) {+ return runtimeErrorResult(error)+ }+ }+ )++ server.registerTool(+ 'create_task',+ {+ description:+ 'Create an open task for yourself and return it. Each call creates a new task; do not retry blindly after a connection failure.',+ inputSchema: z.strictObject({ title: taskTitle }),+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false,+ },+ },+ async ({ title }) => {+ try {+ const { data } = await supabase+ .from('tasks')+ .insert({ title })+ .select(taskFields)+ .single()+ .throwOnError()++ return jsonResult({ task: data })+ } catch (error) {+ return runtimeErrorResult(error)+ }+ }+ )++ server.registerTool(+ 'update_task',+ {+ description:+ 'Rename, close, or reopen one of your tasks and return it. Supply title, closed, or both. Fields you omit keep their current values.',+ inputSchema: z+ .strictObject({+ id: taskId,+ title: taskTitle.optional(),+ closed: z.boolean().optional().describe('True to close the task; false to reopen it.'),+ })+ .refine(({ title, closed }) => title !== undefined || closed !== undefined, {+ message: 'Supply title or closed to update a task.',+ }),+ annotations: {+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: true,+ openWorldHint: false,+ },+ },+ async ({ id, title, closed }) => {+ try {+ const changes = {+ ...(title !== undefined ? { title } : {}),+ ...(closed !== undefined ? { closed } : {}),+ }+ const { data } = await supabase+ .from('tasks')+ .update(changes)+ .eq('id', id)+ .select(taskFields)+ .maybeSingle()+ .throwOnError()++ return data ? jsonResult({ task: data }) : errorResult(taskNotFound)+ } catch (error) {+ return runtimeErrorResult(error)+ }+ }+ )++ server.registerTool(+ 'delete_task',+ {+ description:+ 'Permanently delete one of your tasks by ID. Use update_task with closed: true to keep a completed task instead.',+ inputSchema: z.strictObject({ id: taskId }),+ annotations: {+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: true,+ openWorldHint: false,+ },+ },+ async ({ id }) => {+ try {+ const { data } = await supabase+ .from('tasks')+ .delete()+ .eq('id', id)+ .select('id')+ .maybeSingle()+ .throwOnError()++ return data ? jsonResult({ deleted: true, id: data.id }) : errorResult(taskNotFound)+ } catch (error) {+ return runtimeErrorResult(error)+ }+ }+ )+}diff --git a/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/schemas/public/tables/tasks.sql b/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/schemas/public/tables/tasks.sqlnew file mode 100644index 00000000000..9cc51ce042d--- /dev/null+++ b/apps/ui-library/registry/default/blocks/headless-app-tanstack/supabase/schemas/public/tables/tasks.sql@@ -0,0 +1,48 @@+-- Declarative schema. This file is the source of truth for the tasks table:+-- edit it, then run `supabase db diff -f <name>` to generate the migration.+-- Changes made in Studio or the SQL editor are not picked up by the diff.++create table public.tasks (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null default auth.uid() references auth.users (id) on delete cascade,+ title text not null constraint tasks_title_length check (+ char_length(title) between 1 and 200 and title ~ '[^[:space:]]'+ ),+ closed boolean not null default false,+ created_at timestamptz not null default now()+);++-- Support the ownership policies and the tools' newest-first ordering.+create index tasks_user_id_created_at_id_idx on public.tasks (user_id, created_at desc, id desc);++-- Agents call the MCP server with the user's access token, so every tool runs+-- under these policies. A tool cannot reach another user's rows.+alter table public.tasks enable row level security;++-- Expose task operations to signed-in users even when automatic API grants are disabled.+grant select, insert, update, delete on table public.tasks to authenticated;++create policy "Users can view their own tasks"+on public.tasks+for select+to authenticated+using ((select auth.uid()) = user_id);++create policy "Users can create their own tasks"+on public.tasks+for insert+to authenticated+with check ((select auth.uid()) = user_id);++create policy "Users can update their own tasks"+on public.tasks+for update+to authenticated+using ((select auth.uid()) = user_id)+with check ((select auth.uid()) = user_id);++create policy "Users can delete their own tasks"+on public.tasks+for delete+to authenticated+using ((select auth.uid()) = user_id);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.jsonindex db05367a31b..c95cc022ef8 100644--- a/apps/ui-library/registry/default/blocks/mcp-server/registry-item.json+++ b/apps/ui-library/registry/default/blocks/mcp-server/registry-item.json@@ -8,37 +8,42 @@{"path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/index.ts","type": "registry:file",- "target": "supabase/functions/mcp-server/index.ts"+ "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"+ "target": "~/supabase/functions/mcp-server/deno.json"+ },+ {+ "path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.lock",+ "type": "registry:file",+ "target": "~/supabase/functions/mcp-server/deno.lock"},{"path": "registry/default/blocks/mcp-server/supabase/functions/mcp-server/.env.example","type": "registry:file",- "target": "supabase/functions/mcp-server/.env.example"+ "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"+ "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"+ "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"+ "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"+ "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.exampleindex 3e99789d9ee..7d5b7932140 100644--- 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.example@@ -2,6 +2,10 @@# cp supabase/functions/mcp-server/.env.example supabase/functions/.env# supabase functions serve mcp-server --env-file supabase/functions/.env+# Deploy these values after linking your project:+# supabase secrets set --env-file supabase/functions/.env+# Supabase provides the project URL and API keys automatically.+# Keep the protocol-level server name short and project-specific.MCP_SERVER_NAME=supabase-mcpMCP_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.lock b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.locknew file mode 100644index 00000000000..09992bad33d--- /dev/null+++ b/apps/ui-library/registry/default/blocks/mcp-server/supabase/functions/mcp-server/deno.lock@@ -0,0 +1,315 @@+{+ "version": "5",+ "specifiers": {+ "jsr:@supabase/[email protected]": "2.108.2",+ "npm:@modelcontextprotocol/[email protected]": "2.0.0",+ "npm:@supabase/[email protected]": "0.5.0",+ "npm:@supabase/[email protected]": "1.6.0_@[email protected]",+ "npm:@supabase/[email protected]": "2.108.2",+ "npm:openai@^4.52.5": "[email protected]",+ "npm:[email protected]": "4.4.3"+ },+ "jsr": {+ "@supabase/[email protected]": {+ "integrity": "39665d68e1cb721b0714ed1f55c075fba16f8d992672b51458660b3c1ec77c8f",+ "dependencies": [+ "npm:openai"+ ]+ }+ },+ "npm": {+ "@modelcontextprotocol/[email protected]": {+ "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==",+ "dependencies": [+ "zod"+ ]+ },+ "@modelcontextprotocol/[email protected]": {+ "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==",+ "dependencies": [+ "@modelcontextprotocol/core",+ "zod"+ ]+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-tNaQmBgodDZwgB40mRwVbxFy8IDYwjdpcZ0BYrWiwlULCSQoJj4QoG4zgJT7QRPXcqipefNOzvO/qAu4dF98ag==",+ "dependencies": [+ "tslib"+ ]+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-RNUX8EiBy3iLwAX19jtRzLyePnl11/fHcgwDHLnpKcDSXt/5qBnh3LUwAtIjT21Q66QsmNUR2esrHziLCpNubw==",+ "dependencies": [+ "tslib"+ ]+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-OjukUo+5p14zxTuylf2zVg1hZCHWKLO6VrZhtVeQQw09yrVo3GAduvFJPiFDhTAz/Du1ZfEzAR+s6aRAWD5wzQ==",+ "dependencies": [+ "std-env"+ ]+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw=="+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-GQ28/Y8hk3CFmkb3kXH1h/AQx6JIYSQfO0CJMRVBcEKZoNy6C45cXAZ4fcJvRC5Id0cs6xnkUV0+c0rIocigsw==",+ "dependencies": [+ "tslib"+ ]+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-aAGxCSUemZvQIibnCdvNvgaKib28I4rfrNjKbQ9cG1uBLwUsI7hVpGXgEbypCCDhLjQlDTAiJlu7rgljYUT73g==",+ "dependencies": [+ "@supabase/phoenix",+ "tslib"+ ]+ },+ "@supabase/[email protected]_@[email protected]": {+ "integrity": "sha512-LtUkzUqUGip6I2+kvSmA04u3s+npwLseer2yomBnUdQ1zyJPtlgjAqbwsNuGC1DT/FHi1BvvJluI7dZVV2XdTw==",+ "dependencies": [+ "@supabase/middleware",+ "@supabase/supabase-js",+ "jose"+ ]+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-TVZPQxXGxY2+A6yTtm77zUHsh70lBhYUEaJL8RQC+BghcX/ygiMG/rmXrNVBce30/WAeNPa8FiG8HbqlGeV05g==",+ "dependencies": [+ "iceberg-js",+ "tslib"+ ]+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-hFhnPveb5JQg4a0QYicM0swT253YHMdfeRAl2BKHOlI5VAzuHxUGSr8RbwNLYNPauWOgQMS1H8sz8bvYlgwUfQ==",+ "dependencies": [+ "@supabase/auth-js",+ "@supabase/functions-js",+ "@supabase/postgrest-js",+ "@supabase/realtime-js",+ "@supabase/storage-js"+ ]+ },+ "@types/[email protected]": {+ "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==",+ "dependencies": [+ "@types/node",+ "form-data"+ ]+ },+ "@types/[email protected]": {+ "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==",+ "dependencies": [+ "undici-types"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",+ "dependencies": [+ "event-target-shim"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==",+ "dependencies": [+ "humanize-ms"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="+ },+ "[email protected]": {+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "dependencies": [+ "es-errors",+ "function-bind"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "dependencies": [+ "delayed-stream"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="+ },+ "[email protected]": {+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "dependencies": [+ "call-bind-apply-helpers",+ "es-errors",+ "gopd"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="+ },+ "[email protected]": {+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="+ },+ "[email protected]": {+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",+ "dependencies": [+ "es-errors"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "dependencies": [+ "es-errors",+ "get-intrinsic",+ "has-tostringtag",+ "hasown"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="+ },+ "[email protected]": {+ "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A=="+ },+ "[email protected]": {+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",+ "dependencies": [+ "asynckit",+ "combined-stream",+ "es-set-tostringtag",+ "hasown",+ "mime-types"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",+ "dependencies": [+ "node-domexception",+ "web-streams-polyfill"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="+ },+ "[email protected]": {+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "dependencies": [+ "call-bind-apply-helpers",+ "es-define-property",+ "es-errors",+ "es-object-atoms",+ "function-bind",+ "get-proto",+ "gopd",+ "has-symbols",+ "hasown",+ "math-intrinsics"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "dependencies": [+ "dunder-proto",+ "es-object-atoms"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="+ },+ "[email protected]": {+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="+ },+ "[email protected]": {+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "dependencies": [+ "has-symbols"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "dependencies": [+ "function-bind"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",+ "dependencies": [+ "ms"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA=="+ },+ "[email protected]": {+ "integrity": "sha512-iiW7J9qRFlGxvCOIBDBDxFePQSn7ZMAnrYGhrrOo6siO/MIqwfyilLR27pkfDgUk+raLuzADS8A3S/KLBisc0g=="+ },+ "[email protected]": {+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="+ },+ "[email protected]": {+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="+ },+ "[email protected]": {+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "dependencies": [+ "mime-db"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="+ },+ "[email protected]": {+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",+ "deprecated": true+ },+ "[email protected]": {+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",+ "dependencies": [+ "whatwg-url"+ ]+ },+ "integrity": "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==",+ "dependencies": [+ "@types/node",+ "@types/node-fetch",+ "abort-controller",+ "agentkeepalive",+ "form-data-encoder",+ "formdata-node",+ "node-fetch",+ "zod"+ ],+ "optionalPeers": [+ "zod"+ ],+ "bin": true+ },+ "[email protected]": {+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="+ },+ "[email protected]": {+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="+ },+ "[email protected]": {+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="+ },+ "[email protected]": {+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="+ },+ "[email protected]": {+ "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug=="+ },+ "[email protected]": {+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="+ },+ "[email protected]": {+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",+ "dependencies": [+ "tr46",+ "webidl-conversions"+ ]+ },+ "[email protected]": {+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="+ }+ }+}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.tsindex b9e1b1b3d79..4a38c3b4a4f 100644--- 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.ts@@ -1,6 +1,7 @@import 'jsr:@supabase/[email protected]/edge-runtime.d.ts'import { createMcpHandler, McpServer } from 'npm:@modelcontextprotocol/[email protected]'+import { pipeline } from 'npm:@supabase/[email protected]'import {withOAuthProtectedResource,withSupabase,@@ -9,12 +10,21 @@ import {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.+// An MCP server as a single Supabase Edge Function, composed as a pipeline://-// withOAuthProtectedResource adds OAuth discovery for external MCP clients and-// points authentication failures at it. Tools are composed in ./tools/index.ts.+// withOAuthProtectedResource OAuth discovery for external MCP clients. Runs+// before the auth gate so unauthenticated clients+// can fetch the RFC 9728 metadata, and adds the+// WWW-Authenticate challenge to the gate's 401.+// withSupabase Verifies the user access token and builds an+// RLS-scoped client, so both embedded product+// agents and external OAuth clients act as the+// signed-in user.+// handleMcp MCP transport and tools (./tools/index.ts).+//+// On Supabase Edge Functions the public URLs in the OAuth metadata are derived+// automatically, locally and hosted. Off Edge Functions, pass `resourceServer`+// and `authorizationServer` to withOAuthProtectedResource.function readTextEnv(name: string, fallback: string): string {return Deno.env.get(name)?.trim() || fallback@@ -66,8 +76,11 @@ async function handleMcp(request: Request, ctx: SupabaseContext): Promise<Responreturn handler.fetch(request)}+// The handler is passed inline so TypeScript infers its context from the entries.+// Passing `handleMcp` directly collapses the inferred context to `object`.Deno.serve(- withOAuthProtectedResource(- withSupabase({ auth: 'user', cors: { headers: CORS_HEADERS } }, handleMcp)+ pipeline(+ [withOAuthProtectedResource(), withSupabase({ auth: 'user', cors: { headers: CORS_HEADERS } })],+ (request, ctx) => handleMcp(request, ctx)))diff --git a/apps/ui-library/registry/default/blocks/oauth-consent-tanstack/routes/oauth/consent.tsx b/apps/ui-library/registry/default/blocks/oauth-consent-tanstack/routes/oauth/consent.tsxindex ba795f23955..771d5fd6167 100644--- a/apps/ui-library/registry/default/blocks/oauth-consent-tanstack/routes/oauth/consent.tsx+++ b/apps/ui-library/registry/default/blocks/oauth-consent-tanstack/routes/oauth/consent.tsx@@ -1,3 +1,4 @@+/// <reference types="vite/types/importMeta.d.ts" />import { createFileRoute } from '@tanstack/react-router'import { OAuthConsent } from '@/registry/default/blocks/oauth-consent/components/oauth-consent'@@ -8,7 +9,8 @@ import { OAuthConsent } from '@/registry/default/blocks/oauth-consent/componentsexport const Route = createFileRoute('/oauth/consent')({component: ConsentPage,validateSearch: (search) => ({- authorization_id: typeof search.authorization_id === 'string' ? search.authorization_id : null,+ authorization_id:+ typeof search.authorization_id === 'string' ? search.authorization_id : undefined,}),})@@ -17,7 +19,12 @@ function ConsentPage() {return (<main className="flex min-h-svh items-center justify-center p-6 md:p-10">- <OAuthConsent className="w-full max-w-lg" authorizationId={authorization_id} />+ <OAuthConsent+ className="w-full max-w-lg"+ authorizationId={authorization_id}+ signInPath="/login"+ productName={import.meta.env.VITE_PRODUCT_NAME?.trim() || 'Your product'}+ /></main>)}diff --git a/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/components/login-form.tsx b/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/components/login-form.tsxindex ef16768f2ed..8a0b1a08d54 100644--- a/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/components/login-form.tsx+++ b/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/components/login-form.tsx@@ -91,7 +91,7 @@ export function LoginForm({ className, ...props }: React.ComponentPropsWithoutRe</div><div className="mt-4 text-center text-sm">Don't have an account?{' '}- <Link to="/sign-up" className="underline underline-offset-4">+ <Link to="/sign-up" search className="underline underline-offset-4">Sign up</Link></div>diff --git a/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/components/sign-up-form.tsx b/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/components/sign-up-form.tsxindex 6ccd6a1fdff..ca3bb4778c2 100644--- a/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/components/sign-up-form.tsx+++ b/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/components/sign-up-form.tsx@@ -2,6 +2,7 @@ import { Link, useNavigate } from '@tanstack/react-router'import { useState } from 'react'import { cn } from '@/lib/utils'+import { safeNextPath } from '@/registry/default/blocks/safe-next-path/lib/safe-next-path'import { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'import { Button } from '@/registry/default/components/ui/button'import {@@ -34,15 +35,23 @@ export function SignUpForm({ className, ...props }: React.ComponentPropsWithoutRsetIsLoading(true)try {- const { error } = await supabase.auth.signUp({+ const next = safeNextPath(+ new URLSearchParams(window.location.search).get('next'),+ '/protected'+ )+ const { data, error } = await supabase.auth.signUp({email,password,options: {- emailRedirectTo: `${window.location.origin}/protected`,+ emailRedirectTo: `${window.location.origin}${next}`,},})if (error) throw error- await navigate({ to: '/sign-up-success' })+ if (data.session) {+ window.location.assign(next)+ } else {+ await navigate({ to: '/sign-up-success' })+ }} catch (error: unknown) {setError(error instanceof Error ? error.message : 'An error occurred')} finally {@@ -102,7 +111,7 @@ export function SignUpForm({ className, ...props }: React.ComponentPropsWithoutR</div><div className="mt-4 text-center text-sm">Already have an account?{' '}- <Link to="/login" className="underline underline-offset-4">+ <Link to="/login" search className="underline underline-offset-4">Sign in</Link></div>diff --git a/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/routes/_protected.tsx b/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/routes/_protected.tsxindex 237e6b55345..0e6a99eef9d 100644--- a/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/routes/_protected.tsx+++ b/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/routes/_protected.tsx@@ -3,11 +3,11 @@ import { createFileRoute, redirect } from '@tanstack/react-router'import { fetchUser } from '@/registry/default/blocks/password-based-auth-tanstack/lib/supabase/fetch-user-server-fn'export const Route = createFileRoute('/_protected')({- beforeLoad: async () => {+ beforeLoad: async ({ location }) => {const user = await fetchUser()if (!user) {- throw redirect({ to: '/login' })+ throw redirect({ href: `/login?next=${encodeURIComponent(location.href)}` })}return {diff --git a/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/routes/auth/confirm.ts b/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/routes/auth/confirm.tsindex a64be5237a0..a213dfed2eb 100644--- a/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/routes/auth/confirm.ts+++ b/apps/ui-library/registry/default/blocks/password-based-auth-tanstack/routes/auth/confirm.ts@@ -3,6 +3,7 @@ import { createFileRoute, redirect } from '@tanstack/react-router'import { createServerFn } from '@tanstack/react-start'import { getRequest } from '@tanstack/react-start/server'+import { safeNextPath } from '@/registry/default/blocks/safe-next-path/lib/safe-next-path'import { createClient } from '@/registry/default/clients/tanstack/lib/supabase/server'const confirmFn = createServerFn({ method: 'GET' })@@ -29,7 +30,12 @@ const confirmFn = createServerFn({ method: 'GET' })const token_hash = searchParams['token_hash'] as stringconst type = searchParams['type'] as EmailOtpType | nullconst _next = searchParams['next'] as string- const next = _next?.startsWith('/') ? _next : '/'+ const origin = new URL(request.url).origin+ const next = safeNextPath(+ _next?.startsWith(`${origin}/`) ? _next.slice(origin.length) : _next,+ '/',+ origin+ )if (token_hash && type) {const supabase = createClient()diff --git a/apps/ui-library/scripts/clean-registry.ts b/apps/ui-library/scripts/clean-registry.tsindex ea9a44cbd9d..2ad99680366 100644--- a/apps/ui-library/scripts/clean-registry.ts+++ b/apps/ui-library/scripts/clean-registry.ts@@ -40,6 +40,13 @@ function processJsonFile(filePath: string) {}}+ // Registry source routes are absent from this app's generated TanStack tree.+ // Consumers generate their own tree, where this suppression would be unused.+ stringified = stringified.replaceAll(+ '// @ts-expect-error The local generated route tree does not include this block route.\\n',+ ''+ )+// Write back to filefs.writeFileSync(filePath, stringified)console.log(`✓ Updated ${filePath}`)diff --git a/apps/ui-library/scripts/test-headless-tools.mts b/apps/ui-library/scripts/test-headless-tools.mtsnew file mode 100644index 00000000000..62b049d1a6e--- /dev/null+++ b/apps/ui-library/scripts/test-headless-tools.mts@@ -0,0 +1,42 @@+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++import { blocks } from '../registry/blocks.ts'++const appRoot = fileURLToPath(new URL('../', import.meta.url))+const installRoot = await mkdtemp(join(tmpdir(), 'headless-tools-'))++try {+ const block = blocks.find((item) => item.name === 'headless-app-tanstack')!+ const files = block.files!.filter((file) => file.target?.startsWith('~/supabase/'))+ const targets = files.map((file) => file.target!)+ assert.equal(new Set(targets).size, targets.length, 'Install targets must be unique')+ assert(!block.registryDependencies?.some((dependency) => dependency.endsWith('/mcp-server.json')))++ for (const file of files) {+ const destination = join(installRoot, file.target!.replace(/^~\//, ''))+ await mkdir(dirname(destination), { recursive: true })+ await copyFile(join(appRoot, file.path), destination)+ }++ const functionRoot = join(installRoot, 'supabase/functions/mcp-server')+ await copyFile(+ join(appRoot, 'tests/headless-task-tools.test.mts'),+ join(functionRoot, 'tasks.test.ts')+ )++ for (const args of [+ ['check', '--frozen', 'index.ts'],+ ['test', '--frozen', 'tasks.test.ts'],+ ]) {+ const result = spawnSync('deno', args, { cwd: functionRoot, stdio: 'inherit' })+ if (result.error) throw result.error+ assert.equal(result.status, 0, `deno ${args.join(' ')} failed`)+ }+} finally {+ await rm(installRoot, { recursive: true, force: true })+}diff --git a/apps/ui-library/tests/headless-app.test.tsx b/apps/ui-library/tests/headless-app.test.tsxnew file mode 100644index 00000000000..169c3355032--- /dev/null+++ b/apps/ui-library/tests/headless-app.test.tsx@@ -0,0 +1,157 @@+import type { OAuthGrant } from '@supabase/supabase-js'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { ConnectedAgents } from '@/registry/default/blocks/headless-app-tanstack/components/connected-agents'++const { listGrants, revokeGrant } = vi.hoisted(() => ({+ listGrants: vi.fn(),+ revokeGrant: vi.fn(),+}))++vi.mock('@/registry/default/clients/tanstack/lib/supabase/client', () => ({+ createClient: () => ({ auth: { oauth: { listGrants, revokeGrant } } }),+}))++const serverUrl = 'https://example.supabase.co/functions/v1/mcp-server'+const grant: OAuthGrant = {+ client: { id: 'test-agent', name: 'Test agent', uri: '', logo_uri: '' },+ granted_at: '2026-09-01T00:00:00Z',+ scopes: ['openid'],+}+const success = (grants: OAuthGrant[]) => ({ data: grants, error: null })++let container: HTMLDivElement+let root: Root+let writeText: ReturnType<typeof vi.fn>++beforeEach(() => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })+ vi.resetAllMocks()+ listGrants.mockResolvedValue(success([]))+ revokeGrant.mockResolvedValue({ error: null })+ writeText = vi.fn().mockResolvedValue(undefined)+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })+ container = document.createElement('div')+ document.body.append(container)+ root = createRoot(container)+})++afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+})++const render = async () => {+ await act(async () =>+ root.render(<ConnectedAgents mcpServerUrl={serverUrl} productName="Acme" />)+ )+}++const button = (label: string) => {+ const match = Array.from(container.querySelectorAll('button')).find(+ (button) => button.textContent === label+ )+ if (!match) throw new Error(`Missing button: ${label}`)+ return match+}++const click = async (label: string) => {+ await act(async () => button(label).click())+}++describe('Headless app connections', () => {+ it('keeps the server URL available after an agent is authorized', async () => {+ listGrants.mockResolvedValue(success([grant]))+ await render()+ expect(container.textContent).toContain(serverUrl)+ expect(container.textContent).toContain('Test agent')+ await click('Copy URL')+ expect(writeText).toHaveBeenCalledWith(serverUrl)+ await click('Copy prompt')+ expect(writeText).toHaveBeenLastCalledWith(expect.stringContaining('Then call whoami'))+ expect(writeText).toHaveBeenLastCalledWith(expect.stringContaining(serverUrl))+ })++ it('shows a recovery message if clipboard access is denied', async () => {+ writeText.mockRejectedValue(new Error('Clipboard denied'))+ await render()+ await click('Copy URL')+ expect(container.querySelector('[role="alert"]')?.textContent).toContain(+ 'Select and copy the server URL above.'+ )+ expect(button('Copy URL').disabled).toBe(false)+ writeText.mockResolvedValue(undefined)+ await click('Copy URL')+ expect(container.querySelector('[role="alert"]')).toBeNull()+ })++ it('distinguishes loading and failure from an empty grant list, and supports retry', async () => {+ const pending = Promise.withResolvers<ReturnType<typeof success>>()+ listGrants.mockReturnValueOnce(pending.promise)+ await render()+ expect(container.textContent).toContain('Loading connected agents...')+ expect(container.textContent).not.toContain('No agents authorized yet.')+ await act(async () => pending.reject(new Error('Network unavailable')))+ expect(container.textContent).toContain('Unable to load connected agents. Network unavailable')+ expect(container.textContent).not.toContain('No agents authorized yet.')+ expect(container.textContent).toContain(serverUrl)+ await click('Refresh')+ expect(container.textContent).toContain('No agents authorized yet.')+ expect(container.querySelector('[role="alert"]')).toBeNull()+ })++ it('refreshes grants when the customer returns from authorizing an agent', async () => {+ listGrants.mockResolvedValueOnce(success([])).mockResolvedValueOnce(success([grant]))+ await render()+ await act(async () => window.dispatchEvent(new Event('focus')))+ expect(listGrants).toHaveBeenCalledTimes(2)+ expect(container.textContent).toContain('Test agent')+ })++ it('does not allow a stale list response to restore a revoked grant', async () => {+ const pending = Promise.withResolvers<ReturnType<typeof success>>()+ listGrants.mockResolvedValueOnce(success([grant])).mockReturnValueOnce(pending.promise)+ await render()+ // Start revocation and an older list request in the same render window.+ await act(async () => {+ window.dispatchEvent(new Event('focus'))+ button('Revoke access').click()+ })+ expect(revokeGrant).toHaveBeenCalledWith({ clientId: grant.client.id })+ expect(container.textContent).not.toContain('Test agent')+ await act(async () => pending.resolve(success([grant])))+ expect(container.textContent).not.toContain('Test agent')+ expect(container.textContent).toContain('No agents authorized yet.')+ })++ it('prevents duplicate revocations and recovers after a rejected request', async () => {+ const pending = Promise.withResolvers<{ error: null }>()+ listGrants.mockResolvedValue(success([grant]))+ revokeGrant.mockReturnValueOnce(pending.promise)+ await render()+ await act(async () => {+ button('Revoke access').click()+ button('Revoke access').click()+ })+ expect(revokeGrant).toHaveBeenCalledTimes(1)+ expect(button('Revoking access...').disabled).toBe(true)+ await act(async () => pending.reject(new Error('Network unavailable')))+ expect(container.textContent).toContain('Test agent')+ expect(container.textContent).toContain('Unable to revoke access. Network unavailable')+ expect(button('Revoke access').disabled).toBe(false)+ await click('Revoke access')+ expect(container.textContent).not.toContain('Test agent')+ })++ it('keeps the grant when Supabase returns a revocation error', async () => {+ listGrants.mockResolvedValue(success([grant]))+ revokeGrant.mockResolvedValueOnce({ error: new Error('Session expired') })+ await render()+ await click('Revoke access')+ expect(container.textContent).toContain('Unable to revoke access. Session expired')+ expect(container.textContent).toContain('Test agent')+ expect(button('Revoke access').disabled).toBe(false)+ })+})diff --git a/apps/ui-library/tests/headless-task-tools.test.mts b/apps/ui-library/tests/headless-task-tools.test.mtsnew file mode 100644index 00000000000..b04aa405b9d--- /dev/null+++ b/apps/ui-library/tests/headless-task-tools.test.mts@@ -0,0 +1,223 @@+// Copied beside the assembled Edge Function by scripts/test-headless-tools.mts.+// Real MCP input validation and Supabase queries run against an in-memory HTTP fixture.+import assert from 'node:assert/strict'+import { createMcpHandler, McpServer } from 'npm:@modelcontextprotocol/[email protected]'+import { createClient } from 'npm:@supabase/[email protected]'++import { registerTools, type ToolContext } from './tools/index.ts'++const id = 'ab4cbbf1-f726-4bf4-b852-684f21f470ae'+const task = { id, title: 'Try task tools', closed: false, created_at: '2026-01-01T00:00:00Z' }++function fixture(data: unknown = [], status = 200) {+ const requests: Request[] = []+ const supabase = createClient('http://supabase.test', 'test-publishable-key', {+ auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },+ global: {+ headers: { Authorization: 'Bearer caller-token' },+ fetch: (input, init) => {+ requests.push(new Request(input, init))+ return Promise.resolve(Response.json(data, { status }))+ },+ },+ })+ const handler = createMcpHandler(() => {+ const server = new McpServer({ name: 'headless-test', version: '1.0.0' })+ registerTools(server, {+ supabase,+ userClaims: { id, role: 'authenticated' } as ToolContext['userClaims'],+ jwtClaims: { sub: id, client_id: 'agent-client' } as ToolContext['jwtClaims'],+ })+ return server+ })++ async function rpc(method: string, params: Record<string, unknown>) {+ const response = await handler.fetch(+ new Request('http://mcp.test', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json, text/event-stream',+ 'MCP-Protocol-Version': '2025-11-25',+ },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ })+ )+ const text = await response.text()+ assert.equal(response.status, 200, text)+ const json = response.headers.get('content-type')?.includes('text/event-stream')+ ? text+ .split('\n')+ .find((line) => line.startsWith('data: '))!+ .slice(6)+ : text+ const message = JSON.parse(json)+ assert.equal(message.error, undefined, json)+ return message.result+ }++ return {+ requests,+ rpc,+ call: (name: string, args: Record<string, unknown> = {}) =>+ rpc('tools/call', { name, arguments: args }),+ close: handler.close,+ }+}++Deno.test(+ 'assembled server exposes identity and all four task tools with side-effect hints',+ async () => {+ const app = fixture()+ try {+ const { tools } = await app.rpc('tools/list', {})+ assert.deepEqual(tools.map((tool: { name: string }) => tool.name).sort(), [+ 'create_task',+ 'delete_task',+ 'list_tasks',+ 'update_task',+ 'whoami',+ ])+ const byName = Object.fromEntries(tools.map((tool: { name: string }) => [tool.name, tool]))+ assert.equal(byName.list_tasks.annotations.readOnlyHint, true)+ assert.equal(byName.create_task.annotations.idempotentHint, false)+ assert.equal(byName.delete_task.annotations.destructiveHint, true)+ const identity = await app.call('whoami')+ assert.equal(identity.structuredContent.client_id, 'agent-client')+ assert.equal(app.requests.length, 0)+ } finally {+ await app.close()+ }+ }+)++Deno.test('create trims the title and sends only it through the caller-scoped client', async () => {+ const app = fixture(task)+ try {+ const result = await app.call('create_task', { title: ' Try task tools ' })+ assert.deepEqual(result.structuredContent, { task })+ assert.equal(app.requests.length, 1)+ const [request] = app.requests+ assert.equal(request.method, 'POST')+ assert.equal(request.headers.get('authorization'), 'Bearer caller-token')+ assert.deepEqual(await request.json(), { title: task.title })+ } finally {+ await app.close()+ }+})++Deno.test('invalid inputs fail MCP validation before any database request', async () => {+ const app = fixture()+ try {+ for (const [name, args] of [+ ['create_task', { title: ' \t\n ' }],+ ['create_task', { title: 'x'.repeat(201) }],+ ['create_task', { title: 'Spoof owner', user_id: id }],+ ['update_task', { id }],+ ['update_task', { id, closed: 'true' }],+ ['update_task', { id, closed: false, user_id: id }],+ ['delete_task', { id: 'invalid' }],+ ['list_tasks', { limit: 101 }],+ ['list_tasks', { offset: -1 }],+ ] as const) {+ const result = await app.call(name, args)+ assert.equal(result.isError, true, `${name}: ${JSON.stringify(args)}`)+ }+ assert.equal(app.requests.length, 0)+ } finally {+ await app.close()+ }+})++Deno.test(+ 'list filters open tasks and returns a bounded page with a continuation offset',+ async () => {+ const app = fixture([task, { ...task, id: 'extra-row' }])+ try {+ const result = await app.call('list_tasks', { closed: false, limit: 1, offset: 3 })+ assert.deepEqual(result.structuredContent, { tasks: [task], next_offset: 4 })+ const url = new URL(app.requests[0].url)+ assert.equal(url.pathname, '/rest/v1/tasks')+ assert.equal(url.searchParams.get('closed'), 'eq.false')+ assert.equal(url.searchParams.get('order'), 'created_at.desc,id.desc')+ assert.equal(url.searchParams.get('offset'), '3')+ assert.equal(url.searchParams.get('limit'), '2')+ } finally {+ await app.close()+ }+ }+)++Deno.test('list supplies defaults and an empty final page', async () => {+ const app = fixture([])+ try {+ const result = await app.call('list_tasks')+ assert.deepEqual(result.structuredContent, { tasks: [], next_offset: null })+ const url = new URL(app.requests[0].url)+ assert.equal(url.searchParams.get('limit'), '21')+ assert.equal(url.searchParams.get('offset'), '0')+ assert.equal(url.searchParams.has('closed'), false)+ } finally {+ await app.close()+ }+})++Deno.test('update preserves omitted fields and supports reopening a task', async () => {+ const app = fixture([task])+ try {+ const result = await app.call('update_task', { id, closed: false })+ assert.deepEqual(result.structuredContent, { task })+ const [request] = app.requests+ assert.equal(request.method, 'PATCH')+ assert.equal(new URL(request.url).searchParams.get('id'), `eq.${id}`)+ assert.deepEqual(await request.json(), { closed: false })+ } finally {+ await app.close()+ }+})++Deno.test('delete returns the deleted ID and limits deletion to that ID', async () => {+ const app = fixture([{ id }])+ try {+ const result = await app.call('delete_task', { id })+ assert.deepEqual(result.structuredContent, { deleted: true, id })+ assert.equal(app.requests[0].method, 'DELETE')+ assert.equal(new URL(app.requests[0].url).searchParams.get('id'), `eq.${id}`)+ } finally {+ await app.close()+ }+})++Deno.test('mutations report an error when RLS hides the row or it does not exist', async () => {+ const app = fixture([])+ try {+ for (const name of ['update_task', 'delete_task']) {+ const result = await app.call(name, name === 'update_task' ? { id, closed: true } : { id })+ assert.equal(result.isError, true)+ assert.equal(result.content[0].text, 'Task not found or you do not have access.')+ }+ } finally {+ await app.close()+ }+})++Deno.test('database failures retain their actionable message and error code', async () => {+ const app = fixture(+ { code: '42501', message: 'permission denied for table tasks', hint: null },+ 403+ )+ try {+ for (const [name, args] of [+ ['list_tasks', {}],+ ['create_task', { title: 'Test permissions' }],+ ['update_task', { id, closed: true }],+ ['delete_task', { id }],+ ] as const) {+ const result = await app.call(name, args)+ assert.equal(result.isError, true)+ assert.match(result.content[0].text, /\[42501\] permission denied for table tasks/)+ }+ } finally {+ await app.close()+ }+})diff --git a/apps/ui-library/tests/sign-up-redirect.test.tsx b/apps/ui-library/tests/sign-up-redirect.test.tsxnew file mode 100644index 00000000000..2b64bc531fd--- /dev/null+++ b/apps/ui-library/tests/sign-up-redirect.test.tsx@@ -0,0 +1,136 @@+import { act, type ReactNode } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { SignUpForm } from '@/registry/default/blocks/password-based-auth-tanstack/components/sign-up-form'++import '@/registry/default/blocks/password-based-auth-tanstack/routes/auth/confirm'++const { signUp, navigate, verifyOtp, confirm } = vi.hoisted(() => ({+ signUp: vi.fn(),+ navigate: vi.fn(),+ verifyOtp: vi.fn(),+ confirm: vi.fn(),+}))++vi.mock('@tanstack/react-router', () => ({+ Link: ({ children }: { children: ReactNode }) => <a>{children}</a>,+ useNavigate: () => navigate,+ createFileRoute: () => (options: unknown) => options,+ redirect: (options: unknown) => options,+}))+vi.mock('@tanstack/react-start', () => ({+ createServerFn: () => ({+ inputValidator: () => ({+ handler: (handler: (ctx: { data: Record<string, unknown> }) => Promise<unknown>) => {+ confirm.mockImplementation(handler)+ return confirm+ },+ }),+ }),+}))+vi.mock('@tanstack/react-start/server', () => ({+ getRequest: () => new Request('https://app.example.com/auth/confirm'),+}))+vi.mock('@/registry/default/clients/tanstack/lib/supabase/client', () => ({+ createClient: () => ({ auth: { signUp } }),+}))+vi.mock('@/registry/default/clients/tanstack/lib/supabase/server', () => ({+ createClient: () => ({ auth: { verifyOtp } }),+}))++const origin = 'https://app.example.com'+let container: HTMLDivElement+let root: Root+let location: { origin: string; search: string; assign: ReturnType<typeof vi.fn> }++beforeEach(() => {+ vi.clearAllMocks()+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })+ location = { origin, search: '', assign: vi.fn() }+ const testWindow = Object.create(window)+ Object.defineProperty(testWindow, 'location', { value: location })+ vi.stubGlobal('window', testWindow)+ container = document.createElement('div')+ document.body.append(container)+ root = createRoot(container)+ verifyOtp.mockResolvedValue({ error: null })+})++afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.unstubAllGlobals()+})++async function submit(next: string | null) {+ location.search = next === null ? '' : `?${new URLSearchParams({ next })}`+ await act(async () => root.render(<SignUpForm />))+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!+ for (const [id, value] of [+ ['email', '[email protected]'],+ ['password', 'test-password'],+ ['repeat-password', 'test-password'],+ ]) {+ await act(async () => {+ const input = container.querySelector<HTMLInputElement>(`#${id}`)!+ setValue.call(input, value)+ input.dispatchEvent(new Event('input', { bubbles: true }))+ })+ }+ await act(async () => {+ container+ .querySelector('form')!+ .dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))+ })+}++const destinations = [+ ['/oauth/consent?authorization_id=request-123', '/oauth/consent?authorization_id=request-123'],+ ['/agents?tab=connected&sort=name#tools', '/agents?tab=connected&sort=name#tools'],+ [null, '/protected'],+ ['', '/protected'],+ ['https://evil.example/agents', '/protected'],+ ['//evil.example/agents', '/protected'],+ ['/\\evil.example/agents', '/protected'],+] as const++describe.each([false, true])('Sign-up redirects with immediate session: %s', (hasSession) => {+ it.each(destinations)('validates destination %s before sign-up', async (next, expected) => {+ signUp.mockImplementation(async () => {+ // A pending auth request must not pick up a subsequently changed destination.+ location.search = '?next=/changed'+ return { data: { session: hasSession ? { access_token: 'test-token' } : null }, error: null }+ })+ await submit(next)+ expect(signUp).toHaveBeenCalledWith({+ email: '[email protected]',+ password: 'test-password',+ options: { emailRedirectTo: `${origin}${expected}` },+ })+ if (hasSession) {+ expect(location.assign).toHaveBeenCalledWith(expected)+ expect(navigate).not.toHaveBeenCalled()+ } else {+ expect(location.assign).not.toHaveBeenCalled()+ expect(navigate).toHaveBeenCalledWith({ to: '/sign-up-success' })+ await expect(+ confirm({ data: { token_hash: 'test-hash', type: 'email', next: `${origin}${expected}` } })+ ).rejects.toEqual({ href: expected })+ expect(verifyOtp).toHaveBeenCalledWith({ token_hash: 'test-hash', type: 'email' })+ }+ })+})++it.each([+ ['/agents', '/agents'],+ ['//evil.example/agents', '/'],+ ['/\\evil.example/agents', '/'],+ ['https://evil.example/agents', '/'],+ [`${origin}.evil.example/agents`, '/'],+ [`${origin}//evil.example/agents`, '/'],+])('validates confirmation destination %s', async (next, expected) => {+ await expect(confirm({ data: { token_hash: 'test-hash', type: 'email', next } })).rejects.toEqual(+ { href: expected }+ )+})diff --git a/apps/ui-library/vitest.config.ts b/apps/ui-library/vitest.config.tsnew file mode 100644index 00000000000..a1425221a5f--- /dev/null+++ b/apps/ui-library/vitest.config.ts@@ -0,0 +1,11 @@+import { fileURLToPath } from 'node:url'+import { defineConfig } from 'vitest/config'++export default defineConfig({+ resolve: { alias: { '@': fileURLToPath(new URL('.', import.meta.url)) } },+ oxc: { jsx: { runtime: 'automatic' } },+ test: {+ environment: 'jsdom',+ include: ['tests/**/*.test.tsx'],+ },+})diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e4886869599..ebe7509dc76 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1730,6 +1730,9 @@ importers:vite:specifier: 'catalog:'version: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: 'catalog:'+ version: 5.0.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))apps/www:dependencies: