The MCP Server
The generated MCP server — tools, access-filtered tools/list, request limits, authentication, interactive OAuth, workspace-bound tokens, split authorization server.
Every Quickback Worker exposes an MCP server generated from your features. This page covers its tools, how access filters them, request limits, and authentication. Start at AI Agent Readiness for what is generated and how to opt out.
The MCP server
Tools
Every operation in your generated OpenAPI spec becomes one MCP tool. The tool name is the operation's operationId (e.g. listCustomers, createInvoice, sendInvoice). Each tool's inputSchema is a JSON Schema combining the request body with every parameter in the operation's mounted path — including the :params contributed by a namespace prefix (e.g. /scope/:scopeId/...), so a standalone or namespace action is always callable, not just record-based ones. Nested z.object inputs are preserved as nested objects rather than flattened, so the model sees each field's real type.
List and view tools take the same query arguments as the REST endpoint: limit, offset, sort, order, and on the collection read also starting_after, ending_before, total, fields, search and the column filters. See Query parameters.
tools/call re-enters the same Hono app via app.request(...) — so every existing middleware runs exactly as it would for a direct REST call: authentication, firewall, access control, guards, masking. No bypass.
A PUBLIC read on an org-scoped table takes an organizationId argument: an anonymous agent passes it to name the organization whose public rows it wants, and gets ORG_REQUIRED without it. It is forwarded as ?organizationId=, the same as a REST call. Tools for authenticated-only operations don't have it; those act in the caller's active organization.
Path and query arguments go into the URL; the rest become the JSON body. A POST, PUT or PATCH tool always sends a JSON body, even when the operation has no body fields (an action with input: z.object({}) and only path params is sent {}), so it passes the same body validation as a REST call. A DELETE tool sends a JSON body only when the operation declares body fields (batch delete sends { ids, options }); single-record DELETE and GET tools send no body.
Access-filtered tools/list
tools/list only returns tools the calling identity could actually invoke. Each generated tool entry carries the operation's access metadata (roles, userRole, or / and combinators) and tools/list filters against ctx before responding:
- Unauthenticated callers see only tools whose access declares the
PUBLICpseudo-role, or operations that have no security requirement at all (e.g. sign-in / sign-up). - Authenticated callers see tools whose role gate intersects their
ctx.rolesorctx.userRole. Platform-operator endpoints don't appear for callers outside the required user roles. - Function-form access (escape hatch) is opaque at list time — surfaced to any authenticated caller, then evaluated for real on
tools/call. - Scoped roles (
scope:<kind>:<role>, e.g.scope:event:attendee) are opaque at list time too. They are resolved per request from the path (/event/:eventId/...) and live onctx.scope.<kind>, notctx.roles, andtools/listhas no scope id to resolve. A tool whose roles include a scoped role is listed for any authenticated caller except an external delegated principal (principals:), so an event attendee with no organization still sees the tools they can call.tools/callenforces the scope for real. - Record predicates are dropped from the list-time check (no record yet) and applied normally on the actual call.
This is recon-mitigation, not a security boundary. Hiding a tool from the list never weakens the underlying gate — tools/call still runs the full middleware chain and rejects unauthorized invocations the same way a direct REST call would.
The unauthenticated GET /mcp discovery payload returns server info only; it does not enumerate tool names. Inventory is exclusively available via the access-filtered tools/list.
Request limits
Unless requireAuth is set, /mcp accepts anonymous POSTs, so both the body
and the JSON-RPC batch array are attacker-controlled. Two limits apply:
| Limit | Value | Behaviour when exceeded |
|---|---|---|
| Request body | 1 MiB | 413 with JSON-RPC error -32600 |
| Batch elements | 50 | 413 with -32600; split the batch |
The body is read through a byte counter rather than buffered whole, so an
oversized request is cut off mid-stream instead of being materialized first.
A size rejection is deliberately distinct from -32700 Parse error — a
client told "parse error" would retry the same oversized body.
Batches are dispatched in waves of 8 rather than all at once. Every element becomes its own internal request through the full middleware chain, so peak concurrency stays flat regardless of how large a batch is submitted.
Authentication
MCP clients pass their credentials through the standard Authorization: Bearer <jwt> header. The generated MCP handler forwards the header verbatim into the internal request, and the same JWT middleware that guards /api/v1/* validates it.
Mint a JWT from an authenticated session:
curl https://my-api.example.com/auth/v1/token \
-H "Cookie: better-auth.session_token=..." \
-H "Content-Type: application/json"Interactive OAuth (requireAuth)
Statically pasting a Bearer token works, but it isn't how an MCP connector wants to authenticate — it expects to launch a sign-in flow. By default /mcp serves an anonymous session (the access-filtered public tool list), and a connector that never sees an auth challenge never offers to sign in. Set agents.mcp.requireAuth: true to turn /mcp into an authenticated-only endpoint:
export default defineConfig({
// …
agents: { mcp: { requireAuth: true } },
});This does three things:
- Force-enables the
oauthProvider+bearerBetter Auth plugins — so/oauth2/authorize,/oauth2/token, and/oauth2/register(RFC 7591 dynamic client registration) exist for a connector to discover, with PKCE. - Challenges unauthenticated
/mcprequests with401and aWWW-Authenticate: Bearer resource_metadata="…/.well-known/oauth-protected-resource"header (RFC 9728 §5.1). This is the signal MCP connectors use to start OAuth. - Makes the root
/.well-known/oauth-authorization-serverdoc delegate to Better Auth's real metadata, so discovery resolves to working/oauth2/*endpoints instead of a hand-rolled stub.
The access tokens it issues carry the OAuth issuer (BETTER_AUTH_URL + /auth/v1, or oauth.issuerUrl) and the requested resource as audience — exactly what the generated middleware verifies — with or without auth.jwt and without needing oauth.enabled.
The middleware accepts these tokens only while their Better Auth session (sid) is live, and builds the user's context from it — but not the session's organization. A token whose audience is a scope kind's resource is the other lane: confined to one instance, no session — see Instance-bound OAuth tokens.
Grant lifetime
An ordinary grant lives and dies with the sign-in session it was issued under. The token endpoint and the middleware apply the same check — the session row exists, belongs to the user and has not expired — so they cannot disagree:
- Use. The middleware refuses an access token whose session has ended.
- Refresh.
POST /oauth2/tokenwithgrant_type=refresh_tokenfails with400 invalid_grantonce the session has ended, and deletes the refresh tokens issued under it. The connector gets a clean signal to sign in again instead of a token that every request rejects. (Better Auth makes this check at the code exchange but not at refresh; the generatedoauthProviderextension adds it.) - A connector in use keeps its session live. Each successful refresh slides the session the way Better Auth's own
/get-sessiondoes: bysession.expiresIn, at most once persession.updateAge. A grant therefore does not endsession.expiresInafter consent just because the user never reopened the browser. A session that has already lapsed or been deleted is never revived,session.disableSessionRefreshturns the slide off, and an impersonation session is never extended.
Everything that ends the session ends the grant at both endpoints: sign-out, sign-out-everywhere, a password change or reset that revokes sessions, an admin revoking the user's sessions, a ban, and deleting the user. Revoking the refresh token (POST /oauth2/revoke) and removing the user's membership in the consented workspace end it too. An unused grant ends when its refresh token expires (refreshTokenExpiresIn, 30 days by default) or its session lapses, whichever comes first.
plugins.oauthProvider.extensions is generated for this check; setting it is an error. Add your own extension from a custom plugin with extendOAuthProvider().
Workspace-bound tokens
With the organization plugin on, an ordinary OAuth token is bound to the workspace the user consented in, following Better Auth's own postLogin.consentReferenceId pattern:
- Consent. Better Auth evaluates
consentReferenceIdwith the current session onGET /oauth2/authorizeand again onPOST /oauth2/consent(once to store the consent, then inside theauthorize()call that mints the code). The generated hook returnsqborg:<organizationId>for the session'sactiveOrganizationIdwhen the user is a member of it. So a consent page with a workspace picker that callsPOST /auth/v1/organization/set-activebeforePOST /oauth2/consentbinds the token to the picked workspace. Stored consent is per workspace: consent given in A is not reused in B. - Exchange and refresh. Better Auth stores the reference on the code and every rotated refresh token.
customAccessTokenClaimsre-reads the member row at every code exchange and refresh and signs the organization into aqb_orgclaim. A removed membership fails the grant withinvalid_grantbefore the refresh token rotates — the connector must reauthorize. - Use. The middleware acts in
qb_org(role re-read from the member table on every request, so a removal or role change applies immediately) and ignores the session's currentactiveOrganizationId. Switching workspaces in your app does not move a connector's token. The team is taken from the session only while the session is in that same organization.
A token without qb_org (no active workspace at consent, or minted before this behaviour) has no organization authority: activeOrgId is undefined and roles is []. To let tokens minted earlier keep following the session's active organization while connectors re-consent, opt in to the legacy behaviour explicitly:
auth: {
config: {
oauth: {
enabled: true,
orgBinding: "legacy-session", // default: "strict"
},
},
},orgBinding is read whenever the OAuth provider is active, including under agents.mcp.requireAuth without oauth.enabled. "legacy-session" only affects tokens without qb_org; a bound token always acts in its own organization. Under the default "strict", existing connectors lose organization access until the user re-consents. In a split AS / resource-server setup the resource server reads qb_org from tokens the AS mints, so recompile the AS first. Instance-bound (scope-kind) tokens are unaffected, and a scope kind may not be named qborg.
The full handshake a connector runs:
POST /mcp (no token)
→ 401 + WWW-Authenticate: resource_metadata="…/.well-known/oauth-protected-resource"
GET /.well-known/oauth-protected-resource → authorization_servers: [<origin>]
GET /.well-known/oauth-authorization-server → authorize/token/register + PKCE
POST /oauth2/register → dynamic client registration
GET /oauth2/authorize?code_challenge=… → redirect to your Account login → consent
POST /oauth2/token (code + code_verifier) → access token
POST /mcp (Bearer access token) → authenticated tool listThe login and consent screens are served by your Account SPA (ACCOUNT_URL/login, ACCOUNT_URL/consent), so users sign in with whatever methods you already enabled (Google, GitHub, email, passkey). No connector-specific configuration is required — adding the server URL is enough.
requireAuth removes anonymous public-tool access over /mcp. Use it when the MCP surface is meant for authenticated users; leave it off (the default) for servers that expose genuinely public tools.
Split authorization server / resource server (multi-app SSO)
By default a Worker is both the authorization server (AS) and the resource server — it issues and verifies its own OAuth tokens. For multi-app SSO you can run one canonical AS and many resource servers (each hosting its own /mcp) that share a single auth database (the same D1, e.g. via crossSubDomainCookies on a shared parent domain). Two config fields wire it up — both under auth.config.oauth:
On each resource server — point discovery at the external AS and verify its tokens:
auth: {
config: {
oauth: {
enabled: true,
issuerUrl: "https://auth.example.com/auth/v1", // the canonical AS
},
},
},
agents: { mcp: { requireAuth: true } },issuerUrl makes /.well-known/oauth-protected-resource advertise the AS (not this Worker), and the generated middleware verifies incoming Bearer access tokens against the shared JWKS (iss must equal issuerUrl, aud must equal this Worker's /mcp, plus exp + live-session binding). Because the auth DB is shared, the resource server reads the AS's signing keys and the session row directly — no cross-Worker HTTP call.
On the authorization server — register the resource audiences it may mint tokens for (RFC 8707 resource indicators):
auth: {
config: {
oauth: {
enabled: true,
audiences: [
"https://crm.example.com/mcp",
"https://billing.example.com/mcp",
],
},
},
},audiences is an array — list every federated resource server. The AS's own origin (and /mcp, and every named MCP server URL) is always included automatically, so you only list the other servers; a token requested with resource=https://crm.example.com/mcp is then minted with that audience instead of rejected. A resource server's own named MCP servers are accepted by its middleware automatically, but the AS mints them only if its audiences lists their URLs too.
agents.mcp.requireAuth is the documented switch for an authenticated MCP server, and it now emits the full OAuth token-verification path on its own — a resource server needs only requireAuth + oauth.issuerUrl, not a separate oauth.enabled step.
AI Agent Readiness
Every Quickback Worker ships agent-discovery files and an auto-generated MCP server. Let Claude, ChatGPT, Cursor, and Perplexity find and call your API out of the box.
Named MCP Servers
Additional MCP servers with their own path, tools and audience — MCP Apps, attendee servers, vanity hosts, login pages, transport.