An agent's model can choose tool arguments from untrusted text. Derive the customer identifier from authentication and check that customer's access in the SQL for every operation.
This guide uses a refund request as an example. The model can select an order and explain the reason, while the server determines which customer may request the refund. A refund request records proposed work; it does not transfer money.
Watch the agent refund another customer's order
If a write accepts both customerId and orderId from the model, a pasted support thread can supply another customer's values. Moving customerId into fromIdentity prevents the caller from overriding that argument.
The order check remains necessary. Inserting an arbitrary order ID alongside the authenticated customer ID can create an inconsistent refund request, so the write below selects the order through a customer-scoped condition.
Fill the customer from the session
Save this complete, side-effect-free registry as support-operations.ts. Install Valibot in the application with pnpm add -E valibot so that the server validates argument values as well as their presence.
import { type OperationArguments, type OperationRegistry, type OperationStatement, RequestDeniedError } from '@delali/sirannon-db'
import * as v from 'valibot'
export interface SupportSession {
customerId: string
}
const refundArguments = v.strictObject({
orderId: v.pipe(v.number(), v.safeInteger(), v.minValue(1)),
reason: v.pipe(v.string(), v.minLength(1), v.maxLength(500)),
})
export const operations: OperationRegistry<SupportSession> = {
support: {
reads: {
openOrders: {
fromIdentity: { customerId: 'customerId' },
columns: ['id', 'description', 'total_pence'],
statement: ({ customerId }: OperationArguments): OperationStatement => ({
sql: `SELECT id, description, total_pence FROM orders
WHERE customer_id = ? AND status = 'delivered' ORDER BY id`,
params: [customerId],
}),
},
},
writes: {
requestRefund: {
args: ['orderId', 'reason'],
fromIdentity: { customerId: 'customerId' },
statements: ({ orderId, reason, customerId }: OperationArguments): OperationStatement => {
const parsed = v.safeParse(refundArguments, { orderId, reason })
if (!parsed.success) throw new RequestDeniedError(400, 'INVALID_ARGUMENT', 'Check the order ID and reason')
return {
sql: `INSERT INTO refund_request (order_id, customer_id, reason)
SELECT id, customer_id, ? FROM orders
WHERE id = ? AND customer_id = ? AND status = 'delivered'
ON CONFLICT(order_id) DO NOTHING`,
params: [parsed.output.reason, parsed.output.orderId, customerId],
}
},
},
},
},
}The insert changes zero rows for an absent order, another customer's order, an ineligible status, or an existing refund request. Treat zero as 'no request created'. The caller must inspect the returned change count before telling the customer that a request exists.
This complete support-server.ts provides the schema and a local server. Set SIRANNON_SUPPORT_TOKEN to a secret application credential. The example maps that credential to one customer; connect a deployed service to its session system.
import { timingSafeEqual } from 'node:crypto'
import { mkdir } from 'node:fs/promises'
import { type RequestContext, RequestDeniedError, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { createServer } from '@delali/sirannon-db/server'
import { operations, type SupportSession } from './support-operations.ts'
const token = process.env.SIRANNON_SUPPORT_TOKEN
if (!token) throw new Error('Set SIRANNON_SUPPORT_TOKEN')
const expected = Buffer.from(`Bearer ${token}`)
await mkdir('./data', { recursive: true })
const sirannon = new Sirannon({ driver: betterSqlite3() })
const db = await sirannon.open('support', './data/support-tools.db')
await db.execute(`CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY, customer_id TEXT NOT NULL, description TEXT NOT NULL,
total_pence INTEGER NOT NULL, status TEXT NOT NULL
)`)
await db.execute(`CREATE TABLE IF NOT EXISTS refund_request (
id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL UNIQUE REFERENCES orders(id),
customer_id TEXT NOT NULL, reason TEXT NOT NULL
)`)
await db.executeBatch('INSERT OR IGNORE INTO orders VALUES (?, ?, ?, ?, ?)', [
[1, 'customer-a', 'Headphones', 12999, 'delivered'],
[2, 'customer-a', 'USB-C dock', 8450, 'delivered'],
[3, 'customer-b', 'Espresso machine', 34900, 'delivered'],
])
const server = createServer<SupportSession>(sirannon, {
host: '127.0.0.1',
port: 9876,
operations,
authenticate: (context: RequestContext): SupportSession => {
const received = Buffer.from(context.headers.authorization ?? '')
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
throw new RequestDeniedError(401, 'UNAUTHORIZED', 'Sign in to use support tools')
}
const resource = context.path.split('/')[3]
if (context.databaseId !== 'support' || resource === 'backup' || resource === 'encryption') {
throw new RequestDeniedError(403, 'FORBIDDEN', 'Route access refused')
}
return { customerId: 'customer-a' }
},
})
let stopping: Promise<void> | undefined
const stop = (): Promise<void> => {
stopping ??= server.close().finally((): Promise<void> => sirannon.shutdown())
return stopping
}
const handleSignal = (): void => {
stop().catch((error: unknown): void => {
console.error(error)
process.exitCode = 1
})
}
process.once('SIGINT', handleSignal)
process.once('SIGTERM', handleSignal)
try {
await server.listen()
} catch (error) {
await stop()
throw error
}What the server refuses
Registered operations separate caller arguments from identity-derived arguments. The server checks their shape before executing the operation, while the registry's validation checks their values.
| Code | HTTP | Meaning |
|---|---|---|
UNKNOWN_QUERY | 404 | The registry contains no operation with that identifier. |
ARGUMENT_NOT_ALLOWED | 400 | The caller includes an undeclared or identity-derived argument. |
MISSING_ARGUMENT | 400 | The caller omits a declared argument. |
IDENTITY_REQUIRED | 401 | The authenticated identity lacks a required field. |
SQL_NOT_ACCEPTED | 403 | The server refuses SQL sent over the network. |
Keep acceptSql disabled for this service. A client-side tool schema improves model calls, but a hostile caller can bypass it and send an HTTP request directly. Database authorisation and operator-route restrictions therefore remain server responsibilities.
This complete support-client.ts invokes the operation through the public HTTP client. It tests the ownership condition without requiring a model or an external API key.
import { operationRef } from '@delali/sirannon-db'
import { SirannonClient } from '@delali/sirannon-db/client'
const token = process.env.SIRANNON_SUPPORT_TOKEN
if (!token) throw new Error('Set SIRANNON_SUPPORT_TOKEN')
const requestRefund = operationRef<{ orderId: number; reason: string }>('requestRefund')
const client = new SirannonClient('http://127.0.0.1:9876', {
transport: 'http', headers: { Authorization: `Bearer ${token}` },
})
try {
const db = client.database('support')
const otherCustomer = await db.execute(requestRefund, { orderId: 3, reason: 'Arrived damaged' })
const permitted = await db.execute(requestRefund, { orderId: 1, reason: 'Arrived damaged' })
console.log({ otherCustomerCreated: otherCustomer[0]?.changes === 1, permittedCreated: permitted[0]?.changes === 1 })
} finally {
client.close()
}Repeated executions can find an existing refund request, so this example has no fixed result panel. Reconcile an uncertain response through an authorised read before repeating a non-idempotent operation.
Generate the model's tool list from the registry
The code generator produces typed references and a manifest from support-operations.ts. The manifest includes caller arguments and identity-derived arguments separately. Describe only caller arguments to the model, and compare the generated digest with /capabilities before accepting traffic that depends on that contract.
The digest describes operation identifiers and argument contracts. Changing SQL without changing that contract leaves the digest unchanged, so review ownership conditions separately.
For an AI SDK 7 tool, install ai, valibot, and @ai-sdk/valibot with pnpm add -E ai valibot @ai-sdk/valibot. Save this complete module as model-tools.ts.
import { valibotSchema } from '@ai-sdk/valibot'
import { operationRef } from '@delali/sirannon-db'
import type { RemoteDatabase } from '@delali/sirannon-db/client'
import { tool, type ToolSet } from 'ai'
import * as v from 'valibot'
interface DeliveredOrder { id: number; description: string; total_pence: number }
interface RefundArguments { orderId: number; reason: string }
const openOrders = operationRef<Record<string, never>, DeliveredOrder>('openOrders')
const requestRefund = operationRef<RefundArguments>('requestRefund')
export const supportTools = (database: RemoteDatabase): ToolSet => ({
openOrders: tool({
description: 'List the delivered orders for the signed-in customer.',
inputSchema: valibotSchema(v.strictObject({})),
execute: async (): Promise<DeliveredOrder[]> => database.query(openOrders, {}),
}),
requestRefund: tool({
description: 'Request a refund for a delivered order. Report whether a new request was created.',
inputSchema: valibotSchema(v.strictObject({
orderId: v.pipe(v.number(), v.safeInteger(), v.minValue(1)),
reason: v.pipe(v.string(), v.minLength(1), v.maxLength(500)),
})),
execute: async (args: RefundArguments): Promise<{ created: boolean }> => {
const replies = await database.execute(requestRefund, args)
return { created: replies[0]?.changes === 1 }
},
}),
})Pass supportTools() to the agent with a client already bound to the authenticated customer's credential. Keep customer identifiers out of model-controlled arguments, including when constructing tools from a manifest. Validate that each tool description's argument list matches the manifest's args and excludes its identityArgs.
Return a recoverable refusal to the model when it can change its request. Propagate infrastructure and authentication failures to the application so that a model cannot mistake a failed call for a completed refund.
Where to go next
Shared state coordinates agents that claim work from one queue. Auditing a fleet records each caller, while rewinding memory recovers an earlier database state after an unwanted write.