Tools and approvals
Turn operations into tools for agents, hold risky actions for a person, and show what agents did.
@lupinum/better-convex-agents turns operations from
@lupinum/better-convex-functions into tools. A tool call runs the same
operation as the web, with the same policy and row rules, as an agent: the
AI host or in-app assistant that acts for one person, within the scopes that
person granted. Start with Start here if
you have no operations yet.
Give an operation a tool
Add a tool field to a query or mutation, as list and archive in
Start here do:
tool: { name, description, args }.
| Field | Rule |
|---|---|
name | 1 to 64 letters, digits, _ or -. Unique. check_approval and housekeeping are taken |
description | What the tool does, for the model. Say which other tool gives the IDs it needs |
args | Optional text for each argument. Convex validators carry no descriptions |
The tool's input schema comes from the operation's validators. The tool
checks every input against the same validators, and a wrong field fails with
INVALID_INPUT and a message that names it.
- A query with
paginationOptsbecomes a tool withcursorandlimit(1 to 100, 50 by default). Itsresultis{ items, next }; see What a tool returns. - A mutation gets an optional
request_id. A host that retries with the same value gets the first result back; the write runs once. A new value is a new call: while the same call waits for a person, it joins that request, but after the decision it asks again. Do not name an argumentrequest_id,cursororlimityourself;defineToolsrefuses it.
Collect the tools
One module calls defineTools with the operation modules, and exports one
internal function per tool under the tool's name. Logs and usage then name the
tool.
import { defineTools } from '@lupinum/better-convex-agents'
import { internal } from './_generated/api'
import { fns } from './functions'
import * as pages from './pages'
import * as projects from './projects'
export const tools = defineTools(fns, { pages, projects }, { functions: internal.agents })
export const { edit_page, list_projects, archive_project, check_approval, housekeeping } =
tools.functions
// For the approval page: open requests, one request, and the decision.
export const { pending, get, approve, decline } = tools.approvals
// What agents did, newest first.
export const { activity } = toolsfunctions must be internal.<this module>. When createMcpServer loads, a
tool that is not exported fails, with the missing names in the message. An
operation in a module that you do not pass to defineTools has no tool. The
launch check names each such
operation that has a tool field.
Every tool's action must be in at least one scope of the policy; defineTools throws for a tool whose action is in none.
Hold an action for a person
Set the agent rule of the action to 'approve' in the
policy. An agent that calls the tool
then gets this result instead of the effect:
{
"status": "needs_approval",
"approvalId": "k57…",
"summary": "Archive the project \"Website relaunch\".",
"url": "https://app.example.com/approvals/k57…"
}The agent tells the person to open the link. Your approval page at
/approvals/[id] reads the request with api.agents.get and calls
api.agents.approve or api.agents.decline. starters/mcp-oauth-agent has
the page in app/pages/approvals/[id].vue. Set SITE_URL on the Convex
deployment: the link is built from it.
Use 'approve' for every action that destroys, publishes, sends, spends or
changes who has access. See Prompt injection.
The plan
A person approves a plan: a fixed list, not an instruction. Give the mutation a
plan function, as archive in Start here does. It returns the sentence the
person reads and the existing rows the work will change:
import { v } from 'convex/values'
import { mutation } from './functions'
export const archiveMatching = mutation({
action: 'projects.archive',
args: { organizationId: v.id('organizations'), prefix: v.string() },
returns: v.number(),
tool: {
name: 'archive_matching',
description: 'Archive the active projects whose name starts so.',
},
plan: async (ctx, { organizationId, prefix }) => {
const active = await ctx.db
.query('projects')
.withIndex('by_org_status', (q) =>
q.eq('organizationId', organizationId).eq('status', 'active'),
)
.take(50)
const found = active.filter((project) => project.name.startsWith(prefix))
return {
summary: `Archive ${found.length} projects: ${found.map((p) => p.name).join(', ')}.`,
rows: found.map((p) => p._id),
}
},
// Works on the plan, not on a new search: a project that matches later is not touched.
handler: async (ctx, _args, plan) => {
for (const id of plan.rows)
await ctx.db.patch(id, { status: 'archived', archivedAt: Date.now() })
return plan.rows.length
},
})planruns when the agent asks, before the request is stored. It reads only, with the call's row rules. It cannot paginate (read a fixed list withtake), and its input is frozen.- Without
rows, the work changes the rows the input names. Withoutplan, the person reads the action and the input as JSON. - Put any other value the work needs into the plan too, such as a price the person sees. The handler gets the plan exactly as it was stored.
- A row the plan lists or the input names that the agent may not read fails
the call with
NOT_FOUND, so it never reaches a person. Fail inplanfor work that can never run. planalso runs, right before the handler, when a person calls the operation in the app, so the handler always has a plan.
Approving
approve runs the operation as the agent, in the same transaction, on the
stored plan. It does not need the agent or its chat: the person may approve
after the agent has gone.
- It checks the agent's grant again. A revoked connection cannot run.
- It fails with
STALEwhen a row the plan lists or the input names changed or went away. Nothing is done. The same call is asked again at once, with a summary of the data as it is now, and waits for a person as a new request. Asking again never runs the work, even when the agent rule now allows it; an in-app run that waited on the old request waits on the new one. - The work, and every internal operation or follow-up it starts, may change
only the plan's rows and rows it creates itself, cancel only jobs it
scheduled itself, and delete only the files the plan lists in
files. Anything else fails withFORBIDDEN, and nothing the work did is kept. An internal action under an approval deletes files through an internal mutation: it cannot read the plan itself. - The limit guards against mistakes in your own code, such as a handler that looks again and finds more. It is not a sandbox against code that tries to get around it on purpose. Calls to components (a rate limiter, a workpool, a file component) are outside it: what they change is up to your code.
- Work that turns out to need another row, such as a follow-up that finds its destination later, cannot widen the approval. List the row in the plan, or let the agent ask for that change as a new request.
- Other failures are stored on the request with their code.
approve returns { status: 'approved' }, or
{ status: 'failed', error: { code, message } } when nothing was done. After
STALE it also returns next, the ID of the new request, so your approval
page can open it. decline returns null.
The agent learns the outcome with the built-in check_approval tool, or by
calling the same tool again with the same request_id. A request that nobody
decides expires after 30 minutes.
Who may decide
The person the agent acts for may always decide. With
approvers: { 'orders.cancel': ['owner'] }, an owner of the request's tenant
may decide too. The request's tenant is the call's: the deepest tenant its
input names.
A row that two tenants share can give the other tenant a say too, when the
action asks for it with sharedRows:
approvers: { 'orders.cancel': { roles: ['owner'], sharedRows: true } },A buyer's agent cancels an order. The order names the buyer and the seller organization, so an owner of the seller may decide too. Only rows that the call's input names and that the agent may change count. Rows that the call only reads, such as a seller's public listing in a purchase, give their tenant no say, and neither does the row of the call's own tenant. When one such row does not belong to the other tenant, its approvers cannot decide.
Without sharedRows, only roles in the call's own tenant count. Keep it that
way unless the other party must agree: an approver of the other tenant may
gain from what the agent asks for.
api.agents.pending({})lists the requests of the signed-in person's own agents. With{ tenantId }, it adds the requests of that tenant, and of rows it shares, that this person may decide as an approver.api.agents.getreturnsnull, andapproveanddeclinefail withAPPROVAL_NOT_FOUND, for a person who may not decide.- A role in a tenant that the rows do not name does not count.
pending({ tenantId }) for each client.The activity feed
Every agent write, approval decision and job run adds one row to activity.
api.agents.activity({ tenantId })lists a tenant's activity. Every member of the tenant may read it; anyone else getsNOT_FOUND.api.agents.activity({})lists what the signed-in person's own agents did. A call without a tenant of its own (crossTenant, or only rows ofanyOftables) is only here, in no tenant's feed.
Each row has the actor (person, agent, or system job), the action, the tool,
the status, and who decided an approval. limit is 1 to 200, 50 by default.
housekeeping deletes activity after one year and decided requests after 90
days; see The MCP door.
What a tool returns
The MCP door sends each result as the tool's structuredContent, and as JSON
text for models that read only text. A tool function that a test calls
directly returns the same object; it throws instead of returning error.
| Call | Result |
|---|---|
| A query, or a write that runs | { status: 'done', result } |
A query with paginationOpts | { status: 'done', result: { items, next } } |
| A write that waits for a person | { status: 'needs_approval', approvalId, summary, url } |
check_approval with { approvalId } | { status: 'done', result: { status, summary, result, error } } |
| A failure | { error: { code, message } }, with isError: true |
resultis what the operation returns. A retry with the samerequest_idreturns the stored result; one larger than 64 KiB comes back as{ truncated: true, bytes }.nextis thecursorfor the next page, ornullon the last page.- For
needs_approval, the text tells the model to send the person tourland then to callcheck_approvalwithapprovalId. - In
check_approval,statusispending,approved,declined,failed,expiredorcancelled(the host was disconnected).resultis the operation's result after approval, anderroris{ code, message }after a failure. Both arenullotherwise. Only the connection that asked can check a request.
Known failures keep their code and message: everything from
fail(code, message) and the library's own checks. Every other error becomes
FAILED with a generic message, and the detail goes to the Convex log. The
error code reference lists every
code.