Skip to content
BuildBase

MCP and agents

Run an MCP server on your own app with @buildbase/sdk/mcp, so AI agents can sign in as your users and call your product and its BuildBase capabilities.

This page is part of Agent-ready apps, the reference for serving MCP from your own app. @buildbase/sdk/mcp turns your app into an MCP (Model Context Protocol) server. An agent such as Claude Code, Cursor or ChatGPT connects to an endpoint on your domain, the user signs in and approves it on BuildBase's hosted login and consent screen, and the agent can then call tools: the BuildBase ones (workspaces, subscription, quotas, credits, feature flags, permissions) and any you write for your own product.

Note

Want to manage BuildBase itself from your AI? That is the other track, BuildBase in your AI tools: connect Claude, ChatGPT, Cursor or another AI tool to BuildBase's own MCP server, at BuildBase in your AI tools.

You need it when you want agents to operate your app on a user's behalf. You do not need it for normal human sign-in - that stays in Authentication.

Step by step, with screenshots: Set up agent access.

The entry point is server-only with no React, and it runs on Node 18+, edge runtimes, Deno and Bun. It is split from the core entry because it uses zod at runtime, which is also how you describe tool inputs. The SDK depends on zod 4, so describe them with zod 4 too: a schema built with zod 3 does not type-check against defineMcpTool.

How the pieces fit

BuildBase runs the OAuth flow - dynamic client registration, PKCE, login, consent, refresh, and the grant a company's identity provider makes for an agent (below). It never mints the access token itself. On every grant it calls a token endpoint on your app, and your app signs the token with its own secret. The per-user BuildBase session travels inside that token as an encrypted sid claim, so your MCP server can call BuildBase as that user without storing anything.

StepWho does itSDK export
Agent discovers your serverYour appcreateAgentStack() discovery routes
User signs in and approvesBuildBasenone - hosted screens
Token minted for the agentYour apphandleAppTokenRequest() + mintAgentToken()
Each MCP request is verifiedYour appbuildbaseAuth()
Tools run under the userYour appbuiltinMcpTools, defineMcpTool()
User sees and revokes the grantYour app<ConnectedAgents />, useConnectedAgents()

Every tool call runs under the granting user's BuildBase session, so the platform enforces that user's real permissions. An agent can never do more than its user could.

Before you start

Before you start

In the BuildBase console, create an OAuth2 agent client: type oauth2, client kind Agent (third-party), PKCE on. Set its Application token URL to https://<your-origin>/api/agent/token, its Application revoke URL to https://<your-origin>/api/agent/token/revoke, and leave Redirect URLs empty, since agents register their own through dynamic client registration. Then under User management > Access > Authentication > Agent readiness, enable it and Let agents register themselves, with that client as the base client.

You also need two secrets on the server:

  • BUILDBASE_AGENT_CLIENT_SECRET - the base client's secret. BuildBase signs its calls to your token and revoke endpoints with it.
  • SYSTEM_SECRET - your app's own signing and encryption key (openssl rand -hex 32). It never leaves your app.

Warning

localhost does not work for the agent flow. BuildBase calls your token endpoint server-to-server and blocks loopback addresses. For local development, run a tunnel (ngrok http 3000) and use the tunnel origin in the console URLs and in siteUrl.

The fast path: createAgentStack

One config gives you the MCP handler, token verification, CORS, the MCP server card, the RFC 9728 protected-resource metadata, the API catalog, the discovery Link header and the rest of the discovery documents (robots.txt, llms.txt, auth.md, security.txt, the Agent Card, and from @buildbase/sdk 1.0.0 the AI Catalog at /.well-known/ai-catalog.json). Every derived value can be overridden through mcp.* or discovery.*.

// lib/agent.ts
import { createAgentStack, defineMcpTool } from '@buildbase/sdk/mcp';
import { z } from 'zod';

export const agent = createAgentStack({
  serverUrl: process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL!,
  orgId: process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID!,
  siteUrl: 'https://app.example.com',
  site: { name: 'Acme', description: 'Render images from templates.' },
  secret: process.env.SYSTEM_SECRET!, // wires buildbaseAuth for you
  mcp: {
    path: '/mcp',
    builtinTools: 'readonly',
    tools: [
      defineMcpTool({
        name: 'app_health',
        description: 'Liveness check for this app.',
        inputSchema: z.object({}),
        annotations: { readOnlyHint: true },
        execute: async () => ({ status: 'ok' }),
      }),
    ],
  },
  discovery: {
    security: { contact: 'mailto:[email protected]' },
  },
});

Then wire the routes. In the Next.js App Router each one is a single line:

// app/mcp/[[...card]]/route.ts - an optional catch-all at your mcp.path, so
// from SDK 1.0.0 the same route also answers the SEP-2127 server
// card at /mcp/server-card. A plain app/mcp/route.ts serves the endpoint only.
import { agent } from '@/lib/agent';

export const { GET, POST, DELETE, OPTIONS } = agent.routes;
// app/.well-known/[...path]/route.ts - and the same file at
// app/robots.txt, app/llms.txt, app/auth.md and app/security.txt
import { agent } from '@/lib/agent';

export const GET = agent.serveAgentPath;

Tip

mcp.path defaults to /api/mcp. From @buildbase/sdk 1.0.0 the protected resource and its metadata URL derive from siteUrl plus mcp.path, so the default path works: the 401 challenge names /.well-known/oauth-protected-resource/api/mcp, whose resource is <site>/api/mcp. Up to 0.0.90 the stack advertised <site>/mcp whatever the path, and MCP clients refuse metadata whose resource differs from the URL they called, so on 0.0.90 set path: '/mcp' as above (the starter does). <site>/mcp stays an accepted token audience after the change.

Outside Next.js, use agent.mcp.handle({ method, headers, body }) for the MCP endpoint (Express, Fastify) or agent.mcp.fetch(request) (Hono, Bun, Deno, edge), and agent.resolvePath(path) for discovery, which returns null for any path it does not own.

Minting the agent's token

BuildBase calls your Application token URL on every grant, including refreshes. handleAppTokenRequest verifies the call and mintAgentToken signs the token: HS256 with your secret, aud bound to the granted resource, scopes carried through, and the session embedded as an encrypted sid. Both run locally with no platform call.

// app/api/agent/token/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { handleAppTokenRequest, mintAgentToken } from '@buildbase/sdk';

export async function POST(request: NextRequest) {
  const { status, body } = await handleAppTokenRequest({
    authorization: request.headers.get('authorization'),
    clientSecret: process.env.BUILDBASE_AGENT_CLIENT_SECRET!,
    mintToken: (claims) =>
      mintAgentToken({ claims, secret: process.env.SYSTEM_SECRET! }),
  });
  return NextResponse.json(body, { status });
}

mintAgentToken also takes expiresInSec (default 3600) and extraClaims, for example a workspaceId your own user sync resolved. When a company's identity provider approved the agent, the call carries grantType: "id_jag" and expiresInMax, the longest your token may live (below). The revoke endpoint has a matching handleAppRevokeRequest({ authorization, clientSecret, onRevoke }). Tokens minted this way are short-lived and stateless, so onRevoke only has work to do if you keep a denylist or session store.

Wiring it by hand: createMcpHandler + buildbaseAuth

Use the primitives when you want your own route layout or discovery documents. buildbaseAuth verifies what mintAgentToken minted: the signature, audience binding, and sid decryption, mapped to the McpAuthInfo your tools receive.

// lib/mcp.ts
import BuildBase from '@buildbase/sdk';
import { buildbaseAuth, createMcpHandler } from '@buildbase/sdk/mcp';

const buildbase = BuildBase({
  serverUrl: process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL!,
  orgId: process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID!,
});

export const mcp = createMcpHandler({
  buildbase,
  serverInfo: { name: 'acme', version: '1.0.0' },
  auth: buildbaseAuth({
    secret: process.env.SYSTEM_SECRET!,
    resource: 'https://app.example.com/mcp',
    requireAudience: true,
  }),
  builtinTools: 'readonly',
});
// app/mcp/route.ts
import { mcp } from '@/lib/mcp';

const handler = (request: Request) => mcp.fetch(request);

export {
  handler as DELETE,
  handler as GET,
  handler as OPTIONS,
  handler as POST,
};

resource accepts an array when the server answers under more than one URI; the first entry is canonical and drives the 401 challenge's resourceMetadataUrl. Setting auth: false disables verification, for local development only. Leave out buildbase entirely to run an MCP server with only your own tools.

createMcpHandler also takes the production controls: rateLimit(auth, req) (return false or { ok: false, retryAfter } for a 429 - the SDK keeps no counters, so back it with your own store), maxRequestBytes (default 1 MiB), allowedOrigins, cors (on by default, *), onError and formatToolError for redacting errors before they reach the agent. With createAgentStack, pass these under mcp.handler.

From @buildbase/sdk 1.0.0 the handler also has:

  • Tool errors an agent can act on. A failed tool call returns, beside its text, structuredContent: { ok: false, error: { code, message, retryable, status?, retryAfter?, details? } }, so the agent can retry, re-authenticate or fix its arguments without parsing prose. Every failed result also carries the envelope in _meta["app.buildbase/error"], and a tool that declares an outputSchema carries it only there, because clients validate structuredContent against the schema even on an error. Throw McpToolError(message, { code, status, retryable, retryAfter, details }) to choose the code; any other error is classified by its HTTP status, and an upstream that never answered is unavailable and retryable. formatToolError redacts the message in both places, and structuredErrors: false keeps the text-only result.
  • onToolCall, an audit row per tool call. Called once per tools/call with tool, outcome (ok, error, invalid_arguments or unknown_tool), durationMs, readOnly, destructive, userId, workspaceId, scopes, clientId (which agent acted), errorCode, traceparent and argumentKeys. Argument values, the token and the BuildBase session are never included. It is not awaited, and a hook that throws is reported to onError.
  • fetchPublicUrl, for tools that take a URL from the agent. Exported from @buildbase/sdk/mcp. It allows only http: and https:, refuses localhost and private, loopback, link-local and reserved addresses, checks every redirect hop (maxRedirects, default 3) and caps the body (maxBytes, default 10 MiB) and the time (timeoutMs, default 15 s). Pass resolveHost (on Node, dns.promises.lookup) to also refuse a hostname that resolves to a blocked address. Failures are McpToolErrors.
  • DNS-rebinding protection on your own machine. A createAgentStack whose siteUrl is a loopback URL (localhost, 127.0.0.0/8, [::1]) refuses with 403 any request whose Host is not loopback or whose browser Origin is not a loopback origin. Requests without an Origin (curl, server to server) are judged by Host only, and deployed stacks are unchanged. dnsRebindingProtection sets it yourself (on when allowedHosts is set, otherwise off; false turns it off), and allowedHosts lists extra Host values to accept.

MCP protocol 2026-07-28 and the server card

MCP has a new protocol version, 2026-07-28. From @buildbase/sdk 1.0.0 your server speaks it next to the current one, 2025-11-25, so new and older AI clients both connect. It also publishes a server card: a short file that tells clients and agent directories what your server is.

Requires @buildbase/sdk 1.0.0 or later. 0.0.90 and earlier serve MCP protocol 2025-11-25 and the older server card only.

What the new protocol adds

A 2025-11-25 client, and every initialize, behave exactly as before. A request that carries the per-request _meta is served under 2026-07-28, statelessly: each request stands on its own, with no session kept between them.

  • server/discover answers with the supported versions, capabilities and instructions, so a client can learn what the server offers. Every result carries resultType and the server's identity in its _meta.
  • Cache hints. Lists, resources/read and discover carry ttlMs and cacheScope, which tell a client how long it may reuse an answer, and whether it may share it between users. Set them with the cacheHints option.
  • Mirrored headers. Mcp-Method, Mcp-Name and Mcp-Param-* repeat parts of the request body as HTTP headers, and the handler checks them against the body. A mismatch answers 400 with -32020, a missing client capability -32021, and an unsupported version -32022 naming the supported ones. To mirror one of your tool's input fields, mark it in its zod schema with x-mcp-header through .meta().
  • Asking the user mid-call. A tool, prompt or resource can stop and ask the user something. It returns mcpInputRequired({ inputRequests, requestState }), and the client's next call carries the answers in ctx.inputResponses and the signed, verified ctx.requestState. Set requestStateSecret when several instances serve one endpoint. requiredClientCapabilities on a tool refuses a client that lacks them, and ctx.client holds the request's version and declared capabilities.

One behaviour changes. A request without _meta is now refused with 400 when its MCP-Protocol-Version header names a revision the server does not know. It used to be served. MCP_PROTOCOL_VERSIONS lists what the handler negotiates.

The server card

A server card describes your MCP server so directories and clients can find out what it is before they connect. The same release serves the card defined by SEP-2127, an MCP proposal:

  • Where: the MCP endpoint's own path plus /server-card (/api/mcp/server-card on the default path), as application/mcp-server-card+json.
  • What it holds: a reverse-DNS name such as com.example/app (from your host and the server's name, or registryName), version, a description clipped to 100 characters, optional title, websiteUrl, repository and icons, and remotes[] with every protocol version the handler negotiates.
  • How agents find it: /.well-known/ai-catalog.json indexes it, and the discovery Link header points at both (rel="mcp-server-card" and rel="ai-catalog"). From the next release of @buildbase/sdk, discovery answers carry an ETag and answer a matching If-None-Match with 304. Earlier releases send no ETag, so a client polling the card downloads it in full each time.

In Next.js the card needs the MCP route to be the optional catch-all shown above. buildServerCard, buildAiCatalog and serverCardPath build them yourself. The older card at /.well-known/mcp/server-card.json and the manifest at /.well-known/mcp.json stay, for scanners.

Completions, paging and tool details

Two more arrive with it:

  • Completions. Give a prompt argument a complete(value, ctx) function, or a resource template a complete: { variable: fn } map, and hosts suggest values as the user types.
  • Paging. pageSize on createMcpHandler pages tools/list, prompts/list, resources/list and resources/templates/list with an opaque nextCursor.

Every tool in tools/list also gets a top-level title (the title field on defineMcpTool) and every behaviour hint as an explicit boolean. The behaviour hints tell a client things like whether a tool only reads, or can delete something. It also gets the outputSchema and _meta you declare. That is what the Claude and ChatGPT directories check.

npx @buildbase/sdk agent doctor --url <your MCP URL> checks all of this the way a client does, and agent install and agent listing print install links and write the directory listing files: the buildbase CLI. How each client connects is in Connect an AI agent.

Built-in tools

builtinMcpTools holds 82 tools, 49 that only read and 33 that write, covering workspaces, users, subscription, plans, invoices, quotas and usage, credits, add-ons and grants, a person's own plan and limits, whether a checkout the user came back from is done (get_checkout_status), feature flags, permissions, notifications, settings and commerce. @buildbase/sdk 1.1.0 added select_free_plan (earlier versions hold 59), and 1.2.0 added the commerce tools and get_checkout_status; before it there are 60. Which ones you expose is your call through builtinTools:

ValueExposes
'readonly'Reads only. The default whenever a buildbase client is configured
'all'Reads, writes and destructive or billing operations (delete_workspace, cancel_subscription, purchase_credits)
falseNone - custom tools only
{ include: [...] }Exactly the named tools
{ exclude: [...] }All reads, minus the named tools

selectBuiltinTools(selection) resolves the same value to the tool list, if you want to inspect it. Workspace-scoped tools take an optional workspaceId and fall back to the workspace pinned on the token. A custom tool with a built-in's name replaces the built-in.

From @buildbase/sdk 1.0.0 one server can give each connection its own surface through query parameters on the MCP URL. They only narrow what scopes and builtinTools already allow:

ParameterEffect
?readonly=true (or 1)Lists and allows only tools whose readOnlyHint is true
?toolsets=a,bThe union of the groups you define with toolsets: { name: [tool names] } on createMcpHandler. claude and chatgpt are built in for directory listings unless you define them
?omit_tools=a,bHides the named tools
?workspace=<id>Pins the connection to one workspace: tools default to it, and a call naming another workspace gets a forbidden tool error

An unknown name is refused with 400 after authentication: unknown_toolset for a toolset (the answer lists the defined ones), unknown_tool for an omitted tool no visible tool has. A workspace pin the user may not use answers 403 workspace_not_allowed. The claude and chatgpt toolsets leave out destructive tools and every tool that moves money; chatgpt also leaves out plans, prices and packages. With handle(), pass the request URL (req.originalUrl in Express) as url, or no parameter applies.

Commerce tools

When your app sells through items and checkout, the agent can buy and sell for its user. Every commerce tool runs as that user: a buyer sees only their own orders, holdings and subscriptions, and a seller only their own sales.

ToolReads or acts
search_itemsReads the published items, by words in the title or item type
get_itemReads one item: its variants, price ids and amounts in minor units
list_item_slotsReads the open times of an item booked by time: each start and end as a UTC instant, the seats left and the seller's time zone
list_my_orders, get_my_orderReads the user's orders
list_my_bookingsReads the user's bookings, soonest first, with whether they may cancel or move each now and what a cancel would refund
list_my_holdingsReads what the user holds from them, by order or kind
check_item_accessAnswers whether something the user bought opens one object of your app
list_my_item_subscriptionsReads the user's item subscriptions
preview_item_subscription_changeSays what moving to another tier would charge, changing nothing
list_my_commissionsReads the user's own commissions as an affiliate: amount, status and when each can be paid out
list_my_sales, get_saleReads the user's sales as a seller
start_item_checkoutActs: opens checkout and answers Stripe's page for the user to open (or completes a free claim). An item booked by time takes slotStart, a start from list_item_slots
cancel_my_bookingActs: cancels one of the user's bookings while the seller's rule allows it, refunding as that rule says
reschedule_my_bookingActs: moves one of the user's bookings to another open time (slotStart from list_item_slots) while the seller's rule allows it
cancel_item_subscriptionActs: cancels at the end of the period paid for
resume_item_subscriptionActs: undoes that cancel
change_item_subscriptionActs: moves to another tier, now or at the renewal as the item type sets
fulfil_sale_lineActs: marks a line of a sale in progress or fulfilled, with a note to the buyer
refund_saleActs: refunds a line, an amount or all that is left (a seller refunds only in the storefront shape)

The reads are in builtinTools: 'readonly'; the rest need 'all' or include. The sale tools read the person's own sales unless sellAs: 'workspace' or a workspaceId asks for a workspace they sell as; they do not fall back to the token's workspace by themselves. The claude and chatgpt toolsets leave out checkout, the subscription moves, refunds and the booking cancel and move, and chatgpt also leaves out the item reads, the open times and the tier-change preview, as they do for plans and prices. A buyer's move into the seller's cancel window is refused (reschedule_into_cancel_window), so pick a time from list_item_slots that starts after it; see bookings.

Set builtinResources: true to also serve read-only context a host can load without spending tool calls: buildbase://profile, buildbase://workspaces and buildbase://workspace/{workspaceId}.

Your own tools, resources and prompts

defineMcpTool infers the input type from its zod schema. execute gets the parsed input and a context: ctx.bb (BuildBase actions under the user's session), ctx.auth (userId, sessionId, scopes), ctx.workspaceId, and ctx.custom from your context factory.

import {
  defineMcpPrompt,
  defineMcpResource,
  defineMcpTool,
  mcpImage,
  mcpText,
} from '@buildbase/sdk/mcp';
import { z } from 'zod';

const renderImage = defineMcpTool({
  name: 'render_image',
  description: 'Render an image from a template.',
  inputSchema: z.object({ templateId: z.string() }),
  requiredScopes: ['render:execute'],
  execute: async (input, ctx) => {
    await ctx.bb.usage.record(ctx.workspaceId!, {
      quotaSlug: 'images',
      quantity: 1,
    });
    const png = await render(input.templateId); // your code, base64
    return { content: [mcpText('Rendered.'), mcpImage(png, 'image/png')] };
  },
});

const guide = defineMcpResource({
  uri: 'app://docs/getting-started',
  name: 'getting-started',
  mimeType: 'text/markdown',
  read: () => gettingStartedMarkdown,
});

const weeklyReport = defineMcpPrompt({
  name: 'weekly_report',
  arguments: [{ name: 'workspace', required: true }],
  get: (args) => `Summarize this week's usage for ${args.workspace}.`,
});

Pass them as tools, resources and prompts to createMcpHandler (with createAgentStack, tools goes under mcp and the other two under mcp.handler). A tool that returns a plain object is sent as JSON text plus structuredContent; return an McpToolResult built with mcpText, mcpImage, mcpAudio, mcpResourceLink or mcpEmbeddedResource for full control. defineMcpResourceTemplate covers parameterized URIs such as app://orders/{orderId}.

requiredScopes hides the tool from tools/list and refuses the call unless the token carries every listed scope. A token with no scopes sees only tools that require none. The scope names are yours - declare them in the stack's scopes catalog so they appear in the protected-resource metadata and on the consent screen.

The user's side

Users need to see which agents they connected and cut one off. Pass the endpoint to the provider with the mcp prop:

<SaaSOSProvider
  // ...
  mcp={{ url: 'https://app.example.com/mcp', name: 'Acme' }}
>

That adds a Connect an agent guide to the Connected Agents settings screen, with setup steps for ChatGPT, Claude, Cursor, VS Code, Windsurf and Cline by default; replace them with your own McpClientGuide entries through mcp.clients. The screen itself is <ConnectedAgents />, the guide alone is <ConnectMcpGuide />, and useConnectedAgents() gives you the list and revoke() for a custom UI. See Connected agents.

Agents a company's identity provider approves

Everything above has each person approve each agent on the consent screen. A company that sells your app to its people may want its identity provider to decide instead: its IT admin approves an agent for everyone, once, and the agent gets a token for any of them with no consent screen. This is the MCP specification's Enterprise-Managed Authorization extension, the Identity Assertion JWT Authorization Grant (ID-JAG) that Okta calls Cross App Access. It is built for Okta. The full setup, for you and for the company, is agents through a company's identity provider.

How an agent such as Claude connects

  1. You turn it on. Under User management > Access > Authentication > Agent readiness, turn on Let companies' identity providers approve agents and Let agents identify themselves by a metadata document, with your agent client as the Base client for agents identified by a metadata document. Your RFC 8414 metadata then lists urn:ietf:params:oauth:grant-type:jwt-bearer in grant_types_supported, authorization_grant_profiles_supported, and client_id_metadata_document_supported: true beside none in token_endpoint_auth_methods_supported, which is what Claude looks for before it offers this.
  2. The company sets it up. Its IT admin pastes its Okta issuer into your app, turns on Cross App Access for your app in Okta with your app's issuer, and connects the agent to your app with its client ID in your app. For Claude that is the URL of Claude's Client ID Metadata Document, which Claude's documentation gives, and the resource is your MCP server's URL.
  3. The person uses it. When one of the company's people, signed in to the agent with Okta, uses your MCP server, the agent asks Okta for an ID-JAG for your app and presents it at your token endpoint (grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer, assertion, client_id, optionally resource and scope). BuildBase checks it, calls your Application token URL, and answers your token with its expires_in and no refresh token. When it expires, the agent asks Okta again.
  4. Your MCP server verifies it as any token: buildbaseAuth({ secret, resource, requireAudience: true }). The MCP extension requires the token to be bound to your MCP server, so keep requireAudience on: a token minted without a resource carries no aud and is refused.

A registered agent client with a secret, such as a company's own agent, works the same way with its client ID instead of a metadata document. A dynamically registered client never can: its ID is new on every registration, so no identity provider can name it (unauthorized_client).

Public clients known by a metadata document

An agent identified by its Client ID Metadata Document has no secret: its client ID is the https URL of a JSON document it publishes about itself. The draft prefers confidential clients for this grant, so BuildBase holds these to the following:

  • The document vouches for itself. It is fetched through the outbound guard: https and a public address only, even on a self-hosted server that otherwise allows private ones, no redirects, 5 seconds for the whole fetch, 5 KB. Its client_id must equal its URL exactly, and its token_endpoint_auth_method must be absent or none. It is refetched at most once an hour, and a failing fetch keeps the last good copy for a day, then refuses.
  • It is only ever a public agent. Never an app client, never confidential, never a base client, and PKCE is required when it goes through the consent screen.
  • Each assertion works once. Its jti is recorded per issuer until it expires, after the signature is checked, so a captured assertion cannot be replayed and a forged one cannot burn a real one. If that record cannot be checked, the request is refused with temporarily_unavailable, never let through.
  • Assertions are short and name the client. At most an hour from iat to exp, and client_id must be the agent presenting it.
  • The company decides, by name. The issuer is one the company chose, its keys come only from the key set stored for that company, the person must already be one of the company's people, and the company's connected-apps policy must approve the agent by name: allowing any agent is not enough for one with no secret (not_approved_by_name in the company's trail).
  • The consent page says who vouched. It names the agent by its document's host and marks it unverified, with a warning, unless your team listed that host under Vetted document hosts in Agent readiness.
  • Strangers cannot fill your client list, or lock a real agent out. Only agents in use (a consent, an identity provider's approval, a company's policy naming it) count against maxClients (1,000 by default), and one nobody uses goes a day after it was made. At most 20 are made an hour from one host and 50 from one registrable domain, counted only once a valid document made one, and attempts are limited per requesting address (30 an hour) and per registrable domain (120 an hour).

What your token and revoke URLs receive

Your Application token URL gets the same signed request as for every grant, with grantType: "id_jag" and expiresInMax, in seconds: the BuildBase session inside your token (sessionId) ends then, so do not mint for longer. The clientId is the agent's client ID, which for a metadata-document agent is its URL; the request is signed with your base client's secret. From @buildbase/sdk 1.0.0, AppTokenRequestClaims types it and mintAgentToken caps itself at expiresInMax. The sample below also works on an older SDK, where it is an untyped claim:

import { mintAgentToken, type AppTokenRequestClaims } from '@buildbase/sdk';

export function mintForAgent(claims: AppTokenRequestClaims, secret: string) {
  const max =
    typeof claims.expiresInMax === 'number' ? claims.expiresInMax : 3600;
  return mintAgentToken({ claims, secret, expiresInSec: Math.min(3600, max) });
}

Your Application revoke URL gets { userId, clientId, reason }. Besides token_revoked, consent_revoked, client_deleted, user_disconnected and enterprise_revoked, the reasons are now user_deprovisioned, user_blocked, enterprise_signout, enterprise_agents_ended, enterprise_app_not_allowed and agent_access_off. The full table says when each is sent.

Agent accounts without a browser

Everything above acts for a person who signed in and approved. Some agents have no person behind them and need an account of their own. POST /api/v1/auth/agent/register creates one: a user marked as an agent and linked to the client that created it, already verified (no verification email goes out), with a session token in the response. The account is an ordinary user with no console access. There is no SDK method for it; it is one HTTP call from your server.

It is off by default, and a call succeeds only when all three hold:

  • Your server makes it, as one of your OAuth clients. Send that client's client_id and client_secret in the body, or as HTTP Basic. The secret stays on your server, so the agent never holds it. A missing client, an unknown one or a wrong secret answers 401 with invalid_client.
  • The organization has opted in. In the console under User management > Access > Authentication > Agent readiness, switch on Allow agent self-signup. It needs a plan that includes agent readiness, and on a plan without it the switch reads as off. Off answers 403 with access_denied.
  • There is room under your plan's end-user limit. An agent account counts as a user. At the limit the answer is the same 403, so the caller learns nothing about your plan.
// On your server - never in the browser or inside the agent.
const res = await fetch(
  `${process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL}/api/v1/auth/agent/register?org=${process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID}`,
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      client_id: process.env.NEXT_PUBLIC_BUILDBASE_CLIENT_ID,
      client_secret: process.env.BUILDBASE_CLIENT_SECRET,
      email: '[email protected]',
      name: 'Invoice bot',
      password: agentPassword, // generated and stored by your server
      context: { timezone: 'UTC', language: 'en' },
    }),
  }
);
const body = await res.json();
if (!res.ok || !body.success) {
  throw new Error(body.message ?? body.error_description);
}
const { token } = body.data; // the agent's session token
FieldRequiredNotes
emailYesThe account's address, unique in your app
nameYesAt least 2 characters
passwordYesAt least 8 characters. The agent can sign in with it later through /api/v1/auth/login?org=<orgId>, while your organization has an Email/Password method
contextNotimezone, country, language and currency, all strings
client_id, client_secretYesOr HTTP Basic in their place

Any other field is refused with 400, as is a missing or too-short one.

StatusBodyWhen
200{ success: true, data: { user: { name, role }, token } }The account was created
200{ success: false, message }Not created, for example because the address is taken - check success, not only the status
401{ error: 'invalid_client', error_description }Client authentication failed
403{ error: 'access_denied', error_description }Self-signup is off, the plan does not include agent readiness, or the end-user limit is reached
429Too many calls. The endpoint shares the sign-in rate limit

Agent readiness scanners

Scanners such as isitagentready.com read your site the way an agent does. createAgentStack and resolveAgentPath serve most of what they look for from your one config: robots.txt with Content Signals, the discovery Link header, llms.txt, the Agent Card, the A2A card at /.well-known/agent-card.json, the agent skills index, the API catalog, the MCP server card and the AI Catalog, the RFC 9728 and RFC 8414 metadata, auth.md and security.txt. A Web Bot Auth key directory is served when you set webBotAuth.keys or webBotAuth.signingKeys. Step by step, with every option and the browser and DNS pieces: Make your app agent ready.

The next release of @buildbase/sdk fixes four documents scanners rejected, so upgrade before you scan:

  • A2A card: each supportedInterfaces entry has the url, protocolBinding and protocolVersion A2A 1.0 requires. The binding defaults to JSONRPC.
  • AI Catalog: the entry has a displayName, and the catalog a host block. Add representativeQueries to mcpServerCard to help registries match requests to your server.
  • auth.md: the generated file opens with an H1 naming auth.md, which readers look for first.
  • /.well-known/poppy.json: the Personal Agent Protocol document, website-only, is served by default. personalAgent: false turns it off.

npx @buildbase/sdk agent doctor --site <url> checks the same shapes before a scanner does.

Some checks need work outside the SDK:

CheckWhat to do
Markdown negotiationA request for your home page with Accept: text/markdown must get Markdown. A server-rendered app can use negotiateMarkdown in middleware. A static export cannot negotiate, so turn on Cloudflare's Markdown for Agents for the zone, or rewrite those requests to the page's .md twin at the edge.
DNS for AI Discovery (DNS-AID)Publish the records buildDnsAidRecords(config) returns at your DNS provider, and sign the zone with DNSSEC.
auth.md agent registrationOnce your app publishes protected-resource metadata, scanners read the authorization server's own metadata for an agent_auth block. Turn on Let agents register with a person's email on the Agent readiness tab and pick one of your agent clients with Device code on; BuildBase's authorization server then publishes the block and its endpoints (Set up agent access).
Commerce (x402, MPP, UCP, ACP, AP2)Agent payment protocols. Scanners show them for sites with prices and leave them out of the score. BuildBase does not support them yet.

Reference implementation

nextjs-agent-mcp-starter is a Next.js app built on createAgentStack(), verified end to end with Claude Code as the client: discovery, dynamic client registration, consent, token mint and tool calls including writes. It exposes every built-in to show the surface, plus a CRUD example scoped by ctx.auth.userId, rate limiting and error redaction. Its README says to narrow the built-ins before production - start by removing the destructive group.

To connect an agent to your deployed server:

claude mcp add --transport http my-app https://app.example.com/mcp

MCP clients cache tools/list per connection, so reconnect after you add or change tools.

Claude, ChatGPT, Cursor, VS Code, Gemini CLI, Goose and the rest each add a server their own way: Connect an AI agent has the steps for each, and how to list your server in the MCP Registry.