The MCP door
Publish the tools of defineTools to ChatGPT, Claude and other MCP hosts from one Convex HTTP action.
createMcpServer from @lupinum/better-convex-agents/mcp serves your tools
to MCP hosts. A host is an AI application, such as ChatGPT or Claude, that
calls tools for a person. The person signs in to your application and grants
the host some scopes on a consent page. From then on, the host calls tools
with a short-lived OAuth access token.
You need:
- the tools from Tools and approvals;
- Better Auth with the MCP OAuth profile, and the OAuth tables in the auth schema (step 1 of Add MCP to your application);
- a login page and a consent page in your application.
starters/mcp-oauth-agenthas both, inapp/pages/login.vueandapp/pages/oauth/consent.vue.
Turn on the OAuth profile
Pass the policy's scopes to the auth factory, as in
Start here:
oauth: { mcp: { scopes: consentScopes(policy), hosts: ['chatgpt', 'claude'] } }.
The profile admits only clients that an operator created, with PKCE and
explicit consent. Access tokens are bound to your /mcp URL and live for at
most ten minutes. Delegated OAuth and MCP
explains every setting.
Register the routes
import { createMcpServer } from '@lupinum/better-convex-agents/mcp'
import { httpRouter } from 'convex/server'
import * as agents from './agents'
import { auth } from './auth'
const http = httpRouter()
const mcp = createMcpServer(auth, { name: 'Projects', agents })
auth.registerRoutes(http)
// GET and DELETE reach the handler's 405 answer instead of a router 404.
for (const method of ['POST', 'GET', 'DELETE'] as const) {
http.route({ path: '/mcp', method, handler: mcp })
}
// The OAuth discovery document. Convex serves HEAD through GET.
for (const method of ['GET', 'OPTIONS'] as const) {
http.route({ path: '/.well-known/oauth-protected-resource/mcp', method, handler: mcp })
}
export default httpname is the server name that hosts show. agents is the module that calls
defineTools. Do not register OPTIONS /mcp: it would let web pages on other
origins call your tools.
What one tool call does
- The door checks the request: its size (at most 64 KiB, else
413), the protocol, and the access token (issuer, audience, expiry, scopes). A missing or wrong token gets the OAuth challenge that sends the host to sign-in. - The host sees only the tools whose actions its scopes include. Read tools are marked read-only. Tools that may need approval say so in their description.
- The tool runs its own internal Convex function. That function checks the live grant again (session, client, consent), then the user, the role and every row, in the same transaction as the write.
The token never reaches a Convex function. The functions receive the verified principal: the user, the client, the scopes and the grant.
Set SITE_URL
Set SITE_URL on the Convex deployment to the public origin of your
application. Approval links point to ${SITE_URL}/approvals/<id>, and a tool
that needs approval fails without it.
Run the housekeeping
housekeeping expires requests that nobody decided, deletes activity after one
year, and deletes decided requests after 90 days. Run it from a cron:
import { cronJobs } from 'convex/server'
import { internal } from './_generated/api'
const crons = cronJobs()
crons.hourly('agent housekeeping', { minuteUTC: 7 }, internal.agents.housekeeping, {})
export default cronsLet people disconnect a host
Show the person's hosts and let them disconnect one. Call
tools.disconnected next to the revoke, so the host's open requests leave the
approval list.
import { trusted } from '@lupinum/better-convex-functions'
import { v } from 'convex/values'
import { mutation, query } from './_generated/server'
import { tools } from './agents'
import { auth } from './auth'
// Connections live in the auth component, outside the row rules. Each function checks the
// signed-in user itself.
const ownConnections = 'Checks the signed-in user; touches only their connections.'
/** The hosts that the signed-in person connected. */
export const list = trusted(
ownConnections,
query({
args: {},
handler: async (ctx) => {
const user = await auth.requireUser(ctx)
return await auth.oauthConnections.list(ctx, { userId: user.id })
},
}),
)
/** Disconnects one host. Its next call fails, and it cannot renew its access. */
export const revoke = trusted(
ownConnections,
mutation({
args: { clientId: v.string() },
handler: async (ctx, { clientId }) => {
const user = await auth.requireUser(ctx)
const result = await auth.oauthConnections.revoke(ctx, { userId: user.id, clientId })
const appUser = await ctx.db
.query('users')
.withIndex('by_auth_id', (q) => q.eq('authId', user.id))
.unique()
if (appUser) await tools.disconnected(ctx, appUser._id, clientId)
return result
},
}),
)Signing out of the application ends the session that granted consent, so it disconnects the person's hosts too. The person connects them again after the next sign-in.
Files from agents
An MCP request carries at most 64 KiB, so a file cannot travel inside a tool call. An agent sends a file in three steps instead:
- It calls the built-in tool
request_uploadand gets one-time upload tokens. - It sends each file's bytes to the application's upload route, with one token per file. The route answers with an
uploadId. - It calls one of your tools with the
uploadId. The tool callsclaimUpload, which hands it the stored file.
Only agents that can read local files and send HTTP requests can do this, for example Claude Code or Codex. A chat app such as Claude on the web or ChatGPT cannot send a file from the person's computer.
Why a claim
A storage ID gives whoever holds it the file (see
Threat model). An uploadId does not.
claimUpload passes only when all of these are true:
- The call comes from the same actor that asked for the link: the same agent connection of the same person.
- The file was not claimed before.
- The file arrived less than 24 hours ago.
- The type and size are ones the tool allows. The route decides the type from the file's first bytes, never from its name.
A missing, foreign or already claimed upload fails with NOT_FOUND. A type or
size the tool does not allow fails with INVALID_INPUT, and the file stays
claimable for another call.
Turn uploads on
Add uploads to defineTools. scopes names the OAuth scopes whose
connections may ask for links; a read-only connection does not see the tool.
The samples in this section come from an expense app with an expenses table.
// convex/agents.ts
import { defineTools } from '@lupinum/better-convex-agents'
import { internal } from './_generated/api'
import { fns } from './functions'
import * as receipts from './receipts'
export const tools = defineTools(
fns,
{ receipts },
{
functions: internal.agents,
uploads: { scopes: ['write'], types: ['application/pdf'], maxBytes: 10 * 1024 * 1024 },
},
)
export const {
attach_receipt,
check_approval,
housekeeping,
request_upload,
upload_ticket,
upload_stored,
} = tools.functionstypes takes application/pdf, image/png, image/jpeg, image/webp and
text/csv. A CSV file has no signature: the route accepts UTF-8 text without
control characters other than tab and line breaks, and your parser checks the
rest. maxBytes is at most 20 MiB, the request limit of a Convex HTTP action.
Add the upload route to convex/http.ts, next to the MCP door:
import { uploadRoute } from '@lupinum/better-convex-agents'
// POST /mcp/upload, or the `path` you set in `uploads`.
http.route(uploadRoute(agents))Take a file in a tool
Call claimUpload inside a mutation operation, in the same transaction as the
write that stores the file. Read the target row first, so the row rules decide
whether this caller may change it.
// convex/receipts.ts
import { claimUpload, fail } from '@lupinum/better-convex-functions'
import { v } from 'convex/values'
import { mutation } from './functions'
export const attach = mutation({
action: 'receipts.attach',
args: { expenseId: v.id('expenses'), uploadId: v.string() },
returns: v.null(),
tool: {
name: 'attach_receipt',
description: 'Attach a receipt PDF you sent with request_upload to an expense.',
},
handler: async (ctx, { expenseId, uploadId }) => {
const expense = await ctx.db.get(expenseId)
if (!expense) fail('NOT_FOUND', 'No expense with this ID.')
const file = await claimUpload(ctx, uploadId, {
types: ['application/pdf'],
maxBytes: 10 * 1024 * 1024,
})
await ctx.db.patch(expenseId, { receipt: file.storageId, receiptSha256: file.sha256 })
return null
},
})claimUpload returns { storageId, type, size, sha256 }. The same file sent
twice has the same sha256, so a tool can find a duplicate with an index on
it. A tool that needs a person's approval claims the file when the person
approves, as the same agent connection.
What the agent sees
request_upload takes count, from 1 to 20 files, and returns the URL, the
tokens and short instructions:
{
"url": "https://happy-otter-123.convex.site/mcp/upload",
"method": "POST",
"tokens": ["bcu_…"],
"expiresAt": "2026-10-15T09:30:00.000Z",
"maxBytes": 10485760,
"types": ["application/pdf"]
}The agent sends each file as the raw request body:
curl -X POST --data-binary @receipt.pdf -H "Authorization: Bearer bcu_…" https://happy-otter-123.convex.site/mcp/uploadThe route answers 201 with { uploadId, type, size, sha256 }. It answers
401 for a token that expired, was used or never existed, 413 for a file
over maxBytes, and 415 for a file of another type. A refused file is not
stored. Without a valid token the route reads at most 4 MiB of a refused
body, so a larger file may get a 520 from Convex instead of the 401.
Limits and cleanup
| Limit | Value | When reached |
|---|---|---|
Links in one request_upload call | 1 to 20 | INVALID_INPUT |
| Links and files a connection leaves unclaimed | 100 | RATE_LIMITED; use them, or wait until they expire |
| Time to send a file with a link | 15 minutes | the route answers 401 |
| Time to claim a stored file | 24 hours | NOT_FOUND; housekeeping deletes the file |
| Record of a claimed upload | 30 days | housekeeping deletes the record; the file stays |
request_upload counts against the 60 writes a minute of the connection.
housekeeping deletes expired links and unclaimed files in the same run as
the other retention work, and account deletion removes a person's links and
unclaimed files. A claimed file belongs to the row that stores its ID: delete
it with that row.
Cost
request_upload: reads up to 202 upload rows of the connection by index, writes one row per link and one rate-limit row.- The upload route: one query, one storage write and one mutation that writes one row.
claimUpload: reads and writes one row. It invalidates no query of the application.
Connect a host
Create one OAuth client for each host with auth.oauthOperator.createHostClient,
then follow Connect ChatGPT and Claude.
Hosts keep the tool list until they reconnect; see the rule for changing
tools in Tools and approvals.
createMcpServer uses handleMcpRequest under it. To register tools by
hand, without operations, see MCP on Convex.