Implementation
Action Contracts
Defining typed, documented actions shared by your UI, API, and agents.
An action contract defines an operation once, in code, and lets you expose it consistently to your UI, your HTTP API, and your MCP server. This page shows one way to build it in TypeScript.
The contract type
// lib/ax/define-action.ts
import { z, type ZodType } from "zod";
export type Risk = "read" | "low" | "medium" | "high";
export type ActionContext = {
actor: { type: "user" | "agent"; principal: string; grant?: Grant };
idempotencyKey?: string;
approvalId?: string;
};
export type ActionResult<O> =
| { status: "completed"; data: O; receipt: Receipt }
| { status: "accepted"; statusUrl: string }
| { status: "approval_required"; approval: Approval }
| { status: "needs_clarification"; field: string; options: unknown[] }
| { status: "failed"; error: AxError };
export type ActionDefinition<I extends ZodType, O> = {
name: string;
description: string;
risk: Risk;
scopes: string[];
idempotent?: boolean;
requiresApproval?: boolean | ((input: z.infer<I>, ctx: ActionContext) => boolean);
input: I;
preconditions?: (input: z.infer<I>, ctx: ActionContext) => Promise<AxError | void>;
run: (input: z.infer<I>, ctx: ActionContext) => Promise<ActionResult<O>>;
};
export function defineAction<I extends ZodType, O>(def: ActionDefinition<I, O>) {
return def;
}Defining an action
// lib/actions/start-return.ts
import { z } from "zod";
import { defineAction } from "@/lib/ax/define-action";
export const startReturn = defineAction({
name: "start_return",
description: "Start a return for one or more items in a delivered order.",
risk: "medium",
scopes: ["returns:create"],
idempotent: true,
input: z.object({
orderId: z.string(),
items: z.array(z.object({ lineId: z.string(), quantity: z.number().int().min(1) })).min(1),
reason: z.enum(["wrong_size", "damaged", "not_as_described", "changed_mind"]),
}),
preconditions: async ({ orderId }, ctx) => {
const order = await orders.get(orderId, ctx);
if (order.status !== "delivered") {
return { code: "invalid_state", message: `Order is ${order.status}, not delivered.`, retryable: false };
}
if (daysSince(order.deliveredAt) > 30) {
return { code: "return_window_closed", message: "The 30-day return window has closed.", retryable: false };
}
},
run: async (input, ctx) => {
const ret = await returns.create(input, ctx);
return {
status: "completed",
data: { returnId: ret.id, label: ret.labelUrl, refund: ret.estimatedRefund },
receipt: await receipts.record("start_return", input, [{ type: "created", resource: `/returns/${ret.id}` }], ctx),
};
},
});Executing actions
A single executor applies validation, authorization, preconditions, approvals, and idempotency the same way for every caller:
// lib/ax/execute.ts
export async function execute<I extends ZodType, O>(action: ActionDefinition<I, O>, raw: unknown, ctx: ActionContext) {
const parsed = action.input.safeParse(raw);
if (!parsed.success) return failed(validationError(parsed.error));
const missing = action.scopes.filter((s) => !hasScope(ctx, s));
if (missing.length) return failed({ code: "insufficient_scope", requiredScopes: missing, retryable: false });
const pre = await action.preconditions?.(parsed.data, ctx);
if (pre) return failed(pre);
const needsApproval =
typeof action.requiresApproval === "function" ? action.requiresApproval(parsed.data, ctx) : action.requiresApproval;
if (needsApproval && ctx.actor.type === "agent") {
const gate = await checkApproval(action.name, parsed.data, ctx);
if (gate) return gate; // { status: "approval_required", approval }
}
return withIdempotency(action.idempotent ? ctx.idempotencyKey : undefined, `${ctx.actor.principal}:${action.name}`, () =>
action.run(parsed.data, ctx),
);
}Exposing the contract
Because the definition carries everything, each channel is a thin adapter:
- Manifest: map
name,description,risk,scopes,requiresApproval, and a JSON Schema derived frominput. - HTTP: one route per action, or a single
POST /api/ax/:actiondispatcher. - MCP: register each action as a tool. See MCP Integration.
- UI: call
executefrom Server Actions with a user context.
// app/api/ax/[action]/route.ts
import { actions } from "@/lib/actions";
import { execute } from "@/lib/ax/execute";
import { contextFromRequest } from "@/lib/ax/context";
export async function POST(req: Request, { params }: RouteContext<"/api/ax/[action]">) {
const { action } = await params;
const def = actions[action];
if (!def) return Response.json({ error: { code: "unknown_action" } }, { status: 404 });
const result = await execute(def, await req.json(), await contextFromRequest(req));
return Response.json(result, { status: statusFor(result) });
}Related
Last updated 2026-10-06. AX Framework documentation describes proposals unless a section is marked as an established standard.