MCP connectors
Authorize a user with an MCP server through OAuth with dynamic client registration in Vault, connect with the stored session and give the model the server's tools.
better-supabase/ai-sdk/mcp connects the connectors
block to MCP servers through @ai-sdk/mcp. It runs the OAuth flow for a
user, keeps the tokens in Vault, reuses the MCP session of a chat and only
returns tools from a tool list an admin approved.
pnpm add ai @ai-sdk/mcpAuthorize a user
import { authorizeConnector } from "better-supabase/ai-sdk/mcp";
const result = await authorizeConnector({
connectors,
vault,
server,
userId,
redirectUrl: `${origin}/connectors/callback`,
}).orThrow();
if (result.url) return Response.redirect(result.url);import { completeConnector } from "better-supabase/ai-sdk/mcp";
await completeConnector({
connectors,
vault,
server,
userId,
redirectUrl: `${origin}/connectors/callback`,
callback: request.url,
}).orThrow();authorizeConnector registers the app with the server's authorization
server when it has no client yet (dynamic client registration) and returns
the URL to send the user to, or no URL when the stored tokens still work.
completeConnector checks the state, exchanges the code, then records the
grant. vaultOAuthProvider is the OAuthClientProvider
behind both: the client information goes in an app secret
mcp-client:<serverId> and the user's tokens and PKCE verifier in a user
secret under mcpOAuthRef(serverId).
Connect and get tools
import { connectAll } from "better-supabase/ai-sdk/mcp";
const servers = await connectors.servers.list(organizationId).orThrow();
const { tools, skipped, close } = await connectAll(servers, {
connectors,
userId,
vault,
credentials,
chatKey: chatId,
});
try {
return streamText({ model, messages, tools });
} finally {
await close();
}connectTools connects to one server and connectAll to many, naming each
tool after its server (github_create_issue). A server's auth type sets
the credential:
| Auth | Sends |
|---|---|
none | Nothing |
header | The headers of the server's credential_ref, resolved for the app |
oauth | The user's Vault tokens, or their grant through another provider |
An oauth server whose grant is a vercel-connect ref doesn't send a
header: the transport gets connectAuthProvider from @vercel/connect/mcp
as its authProvider, so the MCP SDK reads and refreshes the user's token
through Connect. Install @vercel/connect for it; without it the server is
skipped with CONNECTOR_NOT_AUTHORIZED. When Connect needs the user's
consent first, the connection fails with forbidden, the hint
CONNECTOR_AUTHORIZATION_REQUIRED and the consent URL in details, so the
chat can show the user a link.
With chatKey, the MCP session id and initialize result are stored per
chat and reused on the next request. A server that is disabled, has no
grant for the user or can't be reached fails with the hint
CONNECTOR_DISABLED, CONNECTOR_NOT_AUTHORIZED or CONNECTOR_UNREACHABLE;
connectAll lists those in skipped and keeps the rest. A tool list that
changed returns CONNECTOR_TOOLS_CHANGED until an admin approves it.
Pass apps: true to split out MCP Apps tools into appTools, and elicit
to answer a server's elicitation requests; without it they are declined.
The transport refuses an HTTP redirect by default (redirect: "error"), so
a server that moved can't send the user's token to another origin. Update
the server's URL, or pass redirect: "follow" for a server you trust to
redirect. @ai-sdk/mcp first probes a server with server/discover; pass
protocolVersionDiscovery: false for an older server that needs
initialize as its first request. connectAll takes serverOptions(server)
to set either one for a single server:
await connectAll(servers, {
connectors,
userId,
vault,
serverOptions: (server) =>
server.name === "Legacy CRM" ? { protocolVersionDiscovery: false } : {},
});maxRetries retries a tool call after a transient transport failure (default
0). askUnlessReadOnly: true fills toolApproval on the result with every tool
the server doesn't mark readOnlyHint: true. Pass it to the agent's
toolApproval (connectAll returns the merged map). The annotation is the
server's own claim, so use the option only for a server you trust.
Supabase's MCP server
Supabase's MCP server
gives an agent project tools: list tables, run SQL, read the logs and search
the Supabase docs. supabaseMcp returns the URL to register as a connector
server and the tool schemas from @supabase/mcp-server-supabase, so
connectTools types each tool's input and output:
pnpm add @supabase/mcp-server-supabaseimport { connectTools, supabaseMcp } from "better-supabase/ai-sdk/mcp";
const supabase = await supabaseMcp({
projectRef: "abcdefghijklmnopqrst",
features: ["database", "docs"],
});
// supabase.url is
// https://mcp.supabase.com/mcp?project_ref=abcdefghijklmnopqrst&read_only=true&features=database%2Cdocs
const { tools, close } = await connectTools({
connectors,
server, // a connector server registered with supabase.url
userId,
vault,
schemas: supabase.schemas,
}).orThrow();supabaseMcp is read-only unless you pass readOnly: false: the URL sets
read_only=true, so SQL runs read-only, and the schemas leave out the tools
that write, such as apply_migration.
connectTools returns only the tools the schemas name, and the fingerprint
an admin approves still covers every tool the server lists. Pass
url: "http://localhost:54321/mcp" for the server of the local Supabase
stack.
The hosted server signs the user in with their Supabase account through
OAuth, so register it with the oauth auth type and send the user through
authorizeConnector first. To serve it from your own app with a Management
API token you hold, see
Supabase's MCP server on the MCP
page.
Supabase's server and better-supabase's MCP tools answer different needs.
Supabase's tools administer a project (SQL, migrations, logs, branches) for
the people who run it. createMcp tools are typed,
RLS-scoped tools over your tables for your app's own users.
Event subscriptions
postgresMcpEventStore({ vault, scope }) implements the AI SDK's MCPEventStore with Vault, so the
signing secret of a subscription never sits in a table a browser can read. update merges without a
lock; serialize deliveries for one subscription. dedupeMcpEvents(handlers, { claim }) makes a
delivery that the server sent twice run once, keyed on the subscription id and the eventId or
messageId. Refreshing subscriptions before refreshBefore is the app's job; see ADR 0224.
Tool search over a catalog
toolSearchFrom({ catalog }) is the SDK's toolSearch with your catalog's ranking, for example a
pgvector search over a tools table under the caller's RLS. A catalog error throws a DbException.
Event webhook
mcpEventRoute({ store, onEvent, claim }) wraps the SDK's experimental_createMCPEventWebhook as a Fetch
handler. Pass claim and a delivery the server sent twice runs once (the same rule as
dedupeMcpEvents). Keep the subscription state in postgresMcpEventStore.
import { mcpEventRoute } from "better-supabase/ai-sdk/mcp";
export const POST = mcpEventRoute({
store,
onEvent: async (event) => refresh(event),
claim: (key) => claimDelivery(key),
});Resources and prompts
mcpResourceTools({ client, maxChars }) gives the model two tools, list_resources and
read_resource. The model can only read a URI that the server listed, text longer than maxChars
is cut, and a binary resource is reported by its size instead of its bytes.
import { mcpResourceTools } from "better-supabase/ai-sdk/mcp";
const tools = {
...serverTools,
...mcpResourceTools({ client, maxChars: 20_000 }),
};mcpPrompts(client) lists the server's prompts and mcpPromptMessages(client, name, args) returns
the messages of one prompt, both as an AsyncResult.
Last updated on