Skip to Content
ZenoZENO

MCP server

Serve your agent tools to MCP clients such as Claude, behind Supabase Auth's OAuth 2.1 server

An MCP client the user brings (Claude, for one) connects to your app's /mcp route. The user signs in to your app once, approves the client on your consent page, and from then on the client calls your tools with an access token that Supabase Auth issued for that user. Every call runs as the user, under row level security.

client → /mcp ── 401, WWW-Authenticate ──→ /.well-known/oauth-protected-resource/mcp
       → Supabase Auth's OAuth server → your /oauth/consent page → access token
       → /mcp with Authorization: Bearer → getBearerContext → your tools, as the user

Reads run when the model calls them. A write runs only once the user confirms its change in a card the client shows in the chat: see Writes the user approves.

Turn on the OAuth server

Supabase Auth's OAuth 2.1 server issues the tokens. Turn it on locally in supabase/config.toml (recent CLI versions already have the section, with enabled = false: edit it rather than adding a second one):

supabase/config.toml
[auth.oauth_server]
enabled = true
authorization_url_path = "/oauth/consent"
allow_dynamic_registration = false

On a hosted project, set the same under Authentication > OAuth Server. The consent page lives at your Site URL plus that path. Keep dynamic registration off: you register each client yourself, below, and the bearer context refuses any other.

pnpm dlx shadcn@latest add zeno-lib/zeno/oauth-consent
app/oauth/consent/page.tsx
import { OAuthConsent } from "@/components/auth/oauth-consent"

export default async function Page({
  searchParams,
}: {
  searchParams: Promise<{ authorization_id?: string }>
}) {
  const { authorization_id } = await searchParams
  return (
    <main className="flex min-h-svh items-center justify-center p-6">
      <OAuthConsent authorizationId={authorization_id} productName="Acme" />
    </main>
  )
}

It shows the app, where it returns, the signed-in account and the scopes, then approves or denies. An app the user already approved goes straight back to it.

  • Add /oauth/consent to the middleware's publicPaths. A signed-out user must reach the page, which sends them to /sign-in?next=… itself. The middleware's own redirect would drop the request.

  • The sign-in flows return to next when it is a path on your app. For a magic link, add the page to your Redirect URLs (https://app.example.com/**), and have the Magic Link email template pass {{ .RedirectTo }} on as next:

    <a href="{{ .SiteURL }}/verify?token_hash={{ .TokenHash }}&type=magiclink&next={{ .RedirectTo }}">

    confirm follows that next only on your app's origin: the request's, or NEXT_PUBLIC_SITE_URL when a proxy sits in front.

Register the clients

Each MCP client gets an OAuth client of its own, which you register in your app:

pnpm dlx shadcn@latest add zeno-lib/zeno/oauth-clients zeno-lib/zeno/connected-apps
  • OAuthClients, for admins: register a client, rotate its secret, delete it. It runs server actions with the secret key, so canManageOAuthClients in components/auth/oauth-clients/access.ts refuses everyone until you fill it in from the caller's claims. The secret is shown once.
  • ConnectedApps, for every user: the apps they approved, each with a Disconnect button.

Pick how the client sends its secret to match it, or its token request fails. Claude's custom connectors send it in the request body: register them with client_secret_post. A connector's client can't be edited from Claude, only replaced, so a new secret means updating the connector.

The bearer context

The /mcp route resolves its caller from the token with getBearerContext, from createRequestDb's bearer option. Its client callback is your allowlist: map each registered client to the label its calls carry (app.via), from auth.admin.oauth.listClients(), cached:

client: async (clientId) => (await registeredClients()).get(clientId), // "Claude"

Disconnecting an app ends its refresh token at once, but its last access token keeps working until it expires (an hour by default). Set confirmSession: true to check the session on every call instead.

The /mcp route

app/mcp/route.ts
import { createMcpRoute } from "@zeno-lib/ai/mcp"
import { getOAuthProtectedResourceMetadataUrl } from "@modelcontextprotocol/server"
import { agentReads } from "@/app/agent-tools"
import { getBearerContext } from "@/lib/server-db"

export const { GET, POST, DELETE } = createMcpRoute({
  name: "acme",
  version: "1.0.0",
  tools: agentReads,
  getContext: getBearerContext,
  resourceMetadataUrl: () =>
    getOAuthProtectedResourceMetadataUrl(new URL(process.env.MCP_URL!)),
})
  • MCP_URL is the route's public URL (https://app.example.com/mcp), from config: behind a proxy, or called on 127.0.0.1, request.url names a host clients can't use.
  • Every request needs a token. Without a valid one, the route answers 401 with a WWW-Authenticate header that points at the metadata below.
  • The route is stateless: each request gets a fresh MCP server. It answers the 2026-07-28 revision and the 2025-era initialize handshake clients fall back to.
  • setup(server, context) runs on each request's server after the tools are registered, to add a resource or a tool of your own.

The metadata tells the client which authorization server issues tokens for this resource. Serve it at the RFC 9728 path with @supabase/server (pnpm add @supabase/server):

app/.well-known/oauth-protected-resource/mcp/route.ts
import { resourceMetadataResponse } from "@supabase/server/oauth-protected-resource"

export const GET = (request: Request) =>
  resourceMetadataResponse(request, {
    resource: process.env.MCP_URL!,
    authorizationServers: [`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1`],
  })

Add /mcp and /.well-known/oauth-protected-resource to the middleware's publicPaths: both do their own bearer auth, and a redirect to sign-in would break the client.

Writes the user approves

An MCP client asks before each tool call, but its prompt names the tool, not the change. So with writes, a write never runs from the model's call: its tool only proposes the change, and the user confirms it in an MCP Apps card the client renders in the chat.

model → rename_post({ id, title }) → describe → card: Post 12, title "Draft" → "Launch"   nothing written
user  → Confirm → apply_change({ proposal }) → checks → describe again → invoke            written once
  1. The write's tool (rename_post) is read-only. It runs describe and answers with the change, for the card, and a proposal: the write, its input, the user, each field's old value, an id and an expiry, signed with your secret. The model reads that nothing is saved until the user confirms.
  2. The card shows the record and each field, old → new, with Confirm and Cancel.
  3. Confirm calls apply_change, a tool only the card can call. It checks the signature, the expiry and that the caller is the proposal's user, marks the proposal used, reads the record again, and writes through invoke only if every field still holds the value the card showed.
app/mcp/route.ts
import { createMcpRoute } from "@zeno-lib/ai/mcp"
import { agentReads, agentWrites } from "@/app/agent-tools"

export const { GET, POST, DELETE } = createMcpRoute({
  // …
  tools: agentReads,
  writes: {
    tools: agentWrites,
    secret: process.env.MCP_PROPOSAL_SECRET!,
    markUsed: async ({ id, expiresAt }) => {
      const rows = await adminDb
        .insert(usedProposals)
        .values({ id, expiresAt })
        .onConflictDoNothing()
        .returning({ id: usedProposals.id })
      return rows.length === 1
    },
    // Only clients you know render the card and hide app-only tools.
    enabled: ({ via }) => via === "Claude",
  },
})

What you provide

  • secret: at least 32 characters, from config (openssl rand -base64 32), never committed. It signs every proposal. To rotate it, pass [newSecret, oldSecret]: the first signs and both verify. Drop the old one once its proposals have expired (after 10 minutes; ttlSeconds changes that).

  • markUsed, the replay guard: insert the proposal's id under a unique key and resolve whether this call inserted it. It must be atomic, so two Confirms at once can't both win. It runs before the record is read again, so a proposal whose write then fails is spent and the user asks again. Delete rows past expiresAt whenever you like.

    {project}-db/src/schemas/used-proposals.ts
    // RLS on with no policy: only the server's admin client reads or writes it.
    export const usedProposals = table("used_proposals", {
      id: uuid().primaryKey(),
      expiresAt: timestamp({ withTimezone: true }).notNull(),
    })
  • enabled(context): which callers get the writes, per request. Return true only for clients you know render MCP Apps cards and keep app-only tools from their model. A client that can't render the card gets proposals nobody can confirm, and one that hands app-only tools to its model lets the model confirm its own change. Without enabled, every client gets the writes.

  • A context with the user's claims.sub, as getBearerContext returns: every proposal is sealed for it. writes doesn't type-check with a context that lacks it.

What the card shows

The route serves the card itself, as a ui:// resource: one HTML page that follows the client's theme. After Confirm, it shows one outcome:

OutcomeWhat happened
SavedThe write ran, once.
Record changedA field's value moved since the proposal. Nothing was written; the card shows the change as it would be now, to confirm again.
ExpiredThe proposal is past its expiry. The user asks again.
Already confirmedThe proposal was confirmed before: a second click, or a reloaded chat. Nothing more was written.
Not savedThe write threw, or a form write refused its input. The card shows why.

When the client supports it, the card also tells the model what the user did: confirmed, cancelled, or not saved.

The trust model

The route trusts the client with one thing: keeping the proposal and apply_change from the model. A client that renders MCP Apps leaves a tool marked app-only (visibility: ["app"]) off the model's tool list, and passes a result's structuredContent and _meta to the card, not the model. That is why enabled matters: a plain MCP client lists apply_change like any other tool.

Whatever the client, the route checks on every apply_change call:

  • the signature, so no one can make up a proposal or edit its input, user or old values;
  • the expiry;
  • that the caller is the user the proposal was made for;
  • that the proposal was never used (markUsed);
  • that the record still holds each old value the card showed.

The write then runs as the user, under row level security, through the same invoke as in your app. The proposal is signed, not encrypted: the card can read the input and the values, which the user sees anyway.

Audit tool calls

onToolCall(call, context) runs once after each call to one of tools, with the caller's context, to keep a record of who called what:

app/mcp/route.ts
export const { GET, POST, DELETE } = createMcpRoute({
  // …
  onToolCall: async (call, { claims, via }) => {
    // A paged read returns { items, total, hasMore }.
    const page = call.ok
      ? (call.result as { items?: unknown[]; total?: number } | null)
      : null
    await adminDb.insert(mcpToolCalls).values({
      userId: claims.sub,
      client: via,
      tool: call.name,
      input: toText(call.input).slice(0, 4096),
      rows: page?.items?.length ?? null,
      total: page?.total ?? null,
      error: call.ok ? null : String(call.error),
      durationMs: Math.round(call.durationMs),
    })
  },
  onError: (error) => console.error(error),
})

// JSON text, with a bigint (a transform's output, a bigint column) as its digits.
const toText = (value: unknown) =>
  JSON.stringify(value, (_key, item: unknown) =>
    typeof item === "bigint" ? item.toString() : item
  )
  • call.input is the input as the tool's schema parsed it, with a paged read's limit and offset filled in. It can hold what JSON can't (a bigint from a transform), and a refused call's input is whatever the client sent, at any size: turn it into bounded text before you store it. call.result is what the definition returned, before it became JSON text: what to count from it is yours to pick.
  • A failed call has ok: false and the error the tool threw. Input the schema refuses is reported too, with the arguments the client sent and a ToolInputError whose message names each refused field and whose issues hold the details; the tool never ran. A schema that throws is reported with what it threw.
  • The answer waits for onToolCall, so the record is written before the client sees the result: on a serverless host, work left running after the response can be frozen or dropped. Its time adds to every call's, so keep it to one write and bound it (a statement timeout).
  • Whatever onToolCall throws goes to onError, and the client's answer is unchanged. Set onError too, or a failing audit write goes unnoticed.
  • A write is reported twice. Its propose call has result: { change, proposalId }. The apply_change call has input: { proposalId, tool, input } (the write and the input the model sent it) and what the write returned. A proposal it refused is reported with a ProposalRefusedError whose reason is invalid, expired, wrong-user, stale or used.
  • A call naming a tool the route doesn't serve is refused by the MCP SDK before any of the route's code runs, so it is not reported. Neither are the tools setup registers: instrument their handlers yourself.