Problem
When actions exist only as UI handlers, agents must drive the interface click by click. Any redesign breaks them, and validation errors arrive as visual messages they may not notice.
Context
Use this pattern when:
- Agents need to perform state-changing work: adding, booking, submitting, updating.
- Your UI and your agents should share the same business logic.
Recommended solution
Define actions as typed contracts in code, then expose them to both your UI and agent interfaces. Each contract declares its input schema, preconditions, side effects, risk level, and result shape.
Validate inputs on the server, return structured errors that reference the field and rule that failed, and keep action names stable across UI changes.
- 01Define the action contract with a schema library.
- 02Check preconditions before performing side effects.
- 03Return a typed result or a structured error.
- 04Expose the same contract to the UI, API, and MCP server.
Interaction diagram
Example implementation
Illustrative exampleExamples use a fictional store and illustrative field names. Adapt the shape to your stack; the qualities matter more than the exact format.
import { z } from "zod";
import { defineAction } from "@/lib/ax";
export const addToCart = defineAction({
name: "add_to_cart",
description: "Add a product variant to the active cart.",
risk: "low",
idempotent: true,
input: z.object({
sku: z.string().describe("Variant SKU, e.g. TRAIL-RUNNER-42-BLK"),
quantity: z.number().int().min(1).max(10),
}),
preconditions: async ({ sku, quantity }, ctx) => {
const stock = await ctx.inventory.available(sku);
if (stock < quantity) {
return { code: "insufficient_stock", available: stock };
}
},
run: async ({ sku, quantity }, ctx) => {
const cart = await ctx.carts.add(ctx.session.cartId, sku, quantity);
return { status: "completed", cart };
},
});Accessibility and security
Accessibility
- Server-side validation messages written for agents also improve error messages shown to people using assistive technology.
Security
- Never trust client-supplied prices, totals, or identities; recompute them server-side.
- Apply the same authorization checks to agent calls as to UI calls, using the caller's grant.
Related patterns
Applies the principles Predictable Actions and Explicit Capabilities.