Start here
Write one operation, one row rule and one tool. People call it from the web, agents call it through MCP, and both pass the same checks.
@lupinum/better-convex-functions lets you say once who may do what, and to
which rows. @lupinum/better-convex-agents turns the same functions into tools
for AI hosts such as ChatGPT and Claude. This page builds the smallest complete
example: archive a project.
At the end you have:
- one operation: a Convex mutation that names its action and checks the caller, the policy and every row it touches;
- one row rule: projects belong to an organization, and only members reach them;
- one tool: the same mutation for agents, held until a person approves it.
Both packages are experimental (0.x). Their API can change until 1.0.0.
starters/mcp-oauth-agent is the complete application, with sign-in, consent,
an approval page and tests.
Words on this page
- Action: a name for one thing a person can do, such as
projects.archive. - Policy: the list of actions, which roles may do each one, and what agents may do on their own.
- Tenant: the place a row belongs to, such as an organization. A person has a role in a tenant.
- Operation: a Convex query or mutation built with
defineFunctions. It names one action. - Actor: who calls: a person, an agent acting for a person, a signed-out visitor, or a system job.
Install
pnpm add @lupinum/better-convex-functions @lupinum/better-convex-agents @modelcontextprotocol/server@2.3.1The application needs Better Auth
and a users table with one row per Better Auth user.
User synchronization fills
it.
1. Add the tables
Spread libraryTables into the schema. The library decides who may act, and
agents are actors like people: these tables hold their grants, the approvals
that give them authority, rate limits and the activity log. Row rules keep your
handlers out of them. An app without agents keeps them empty.
import { libraryTables } from '@lupinum/better-convex-functions'
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'
export default defineSchema({
users: defineTable({ authId: v.string(), name: v.string() }).index('by_auth_id', ['authId']),
organizations: defineTable({ name: v.string() }),
memberships: defineTable({
organizationId: v.id('organizations'),
userId: v.id('users'),
role: v.union(v.literal('owner'), v.literal('member')),
}).index('by_org_user', ['organizationId', 'userId']),
projects: defineTable({
organizationId: v.id('organizations'),
name: v.string(),
status: v.union(v.literal('active'), v.literal('archived')),
archivedAt: v.optional(v.number()),
}).index('by_org_status', ['organizationId', 'status']),
...libraryTables,
})2. Write the policy
The policy is plain data. The browser can read it too, so import
definePolicy from the /policy entry, which has no server code.
import { definePolicy } from '@lupinum/better-convex-functions/policy'
export const policy = definePolicy({
actions: ['projects.list', 'projects.archive'],
roles: {
owner: ['*'],
member: ['projects.list'],
},
// What a person grants an AI host on the consent page.
scopes: {
'projects:read': { label: 'See your projects.', actions: ['projects.list'] },
'projects:write': {
label: 'Archive projects after you approve it.',
actions: ['projects.archive'],
},
},
// An agent may ask to archive, but a person decides.
agents: { 'projects.archive': 'approve' },
})An action that is not in actions is a type error everywhere else.
3. Add one rule per table
defineFunctions takes the policy, how to find the user and their role, and
one row rule for every table. A table without a rule is a type error.
import { custom, defineFunctions, owner, tenant } from '@lupinum/better-convex-functions'
import type { Doc } from './_generated/dataModel'
import { auth } from './auth'
import { policy } from './policy'
export const fns = defineFunctions({
auth,
policy,
user: (ctx, authId) =>
ctx.db
.query('users')
.withIndex('by_auth_id', (q) => q.eq('authId', authId))
.unique(),
roleOf: async (ctx, user, tenant) => {
// A call that names no organization gets no role. What every signed-in person may do is a
// role too (see Policy and roles: signedIn).
if (tenant === null) return null
if (tenant.table !== 'organizations') return null
const membership = await ctx.db
.query('memberships')
.withIndex('by_org_user', (q) => q.eq('organizationId', tenant.id).eq('userId', user._id))
.unique()
return membership?.role ?? null
},
rules: {
users: owner('_id'),
organizations: tenant('_id'),
// Every membership of an organization where your role allows the action, inside the
// organization the call names (as tenant() does). Not owner('userId'): that would let a
// member change their own role or add themselves to another organization.
memberships: custom<Doc<'memberships'>>(
(ctx, membership) =>
(ctx.tenant === undefined || ctx.tenant.id === membership.organizationId) &&
ctx.allows({ table: 'organizations', id: membership.organizationId }),
),
projects: tenant('organizationId'),
},
})
export const { query, mutation } = fnstenant('organizationId') says: a project belongs to the organization in its
organizationId field. A call reaches the project only when the caller's role
in that organization allows the call's action. Row rules
explains every rule.
4. Write the operations
Build queries and mutations with query and mutation from
convex/functions.ts, not from convex/_generated/server. Each one names its
action. The tool field makes it a tool for agents.
import { fail } from '@lupinum/better-convex-functions'
import { paginationOptsValidator, paginationResultValidator } from 'convex/server'
import { v } from 'convex/values'
import { mutation, query } from './functions'
export const list = query({
action: 'projects.list',
args: { organizationId: v.id('organizations'), paginationOpts: paginationOptsValidator },
returns: paginationResultValidator(v.object({ id: v.id('projects'), name: v.string() })),
tool: {
name: 'list_projects',
description: 'List the active projects of an organization, newest first.',
},
handler: async (ctx, { organizationId, paginationOpts }) => {
const page = await ctx.db
.query('projects')
.withIndex('by_org_status', (q) =>
q.eq('organizationId', organizationId).eq('status', 'active'),
)
.order('desc')
.paginate(paginationOpts)
return { ...page, page: page.page.map(({ _id, name }) => ({ id: _id, name })) }
},
})
export const archive = mutation({
action: 'projects.archive',
args: { projectId: v.id('projects') },
returns: v.null(),
tool: { name: 'archive_project', description: 'Archive one project. The app can restore it.' },
// What a person approves before an agent's request runs: this sentence, for this project.
plan: async (ctx, { projectId }) => ({
summary: `Archive the project "${(await ctx.db.get(projectId))?.name}".`,
}),
handler: async (ctx, { projectId }) => {
const project = await ctx.db.get(projectId)
if (project?.status !== 'active') fail('NOT_FOUND', 'This project is not active.')
await ctx.db.patch(projectId, { status: 'archived', archivedAt: Date.now() })
return null
},
})Before a handler runs, the library:
- finds the actor (
ctx.actor): a person signed in on the web, or an agent; - finds the tenant from the IDs in the arguments:
projectIdnames a project, and the project names its organization; - checks the policy: the actor's role in that organization must allow the action.
While the handler runs, ctx.db checks every row it reads or writes against
the row rules. The handler has no membership check of its own, and needs none.
5. Collect the tools
One module calls defineTools and exports one internal function per tool.
It also exports the approval functions and the activity feed for your pages.
import { defineTools } from '@lupinum/better-convex-agents'
import { internal } from './_generated/api'
import { fns } from './functions'
import * as projects from './projects'
export const tools = defineTools(fns, { projects }, { functions: internal.agents })
export const { list_projects, archive_project, check_approval, housekeeping } = tools.functions
export const { pending, get, approve, decline } = tools.approvals
export const { activity } = toolsTools and approvals shows the approval page and the activity feed.
6. Open the MCP door
Turn on the MCP OAuth profile in the auth factory. The consent page shows the label of each scope.
import { consentScopes } from '@lupinum/better-convex-functions'
import { createBetterConvexAuth } from '@lupinum/better-convex-nuxt/better-auth/server'
import { components } from './_generated/api'
import type { DataModel } from './_generated/dataModel'
import { policy } from './policy'
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
// Keep your other options.
oauth: { mcp: { scopes: consentScopes(policy), hosts: ['chatgpt', 'claude'] } },
})Serve the tools from one HTTP action:
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)
for (const method of ['POST', 'GET', 'DELETE'] as const) {
http.route({ path: '/mcp', method, handler: mcp })
}
for (const method of ['GET', 'OPTIONS'] as const) {
http.route({ path: '/.well-known/oauth-protected-resource/mcp', method, handler: mcp })
}
export default httpSet SITE_URL on the Convex deployment. The approval link that an agent hands
to the person points to ${SITE_URL}/approvals/<id>. The MCP door
covers the cron, disconnecting hosts and connecting ChatGPT and Claude.
What happens now
- A person calls
api.projects.archivefrom the web. An owner archives the project; a member getsFORBIDDEN. - An AI host with the
projects:writescope callsarchive_project. The tool returnsneeds_approvaland a link. The person opens the link, reads "Archive the project …", and approves. The archive then runs as the agent, with the same checks. - A project of another organization does not exist for either of them: they
get
NOT_FOUND.
To limit how often an action runs, or to keep a record of who did what, see Rate limits and audit log.
Work outside the database that a person starts, such as a PDF or a file
import, is a public action with the same checks. See
Internal operations.
A function built with Convex's own query or mutation skips all of this.
Test your app adds the test that finds one.
When a person leaves
erasure in defineFunctions says, table by table, which rows go when a
person deletes their account: delete them, remove the person's ID from them,
or keep them with a written reason. The library tables (activity, approvals,
grants, runs) are covered without any entry. Account deletion
shows the map and how the user projection starts it.