Skip to content

The operation registry

The registry in packages/core/src/operations/ is the spine of the platform. Each operation is defined once:

export const ordersAdvance = defineOperation({
name: "orders.advance", // group.verb; the MCP tool is "orders_advance"
title: "Advance an order to the next stage",
description: "Written for a tool caller: what it does, when to use it, what comes back.",
kind: "write", // "read" | "write"
roles: ["admin", "editor"], // staff roles, "customer" for portal ops, "system" for internal ones
entity: "order", // main entity, for the default audit row
view: "order", // in-chat view that renders the output (optional)
input: z.object({ id: Id, toStage: OrderStageSchema.optional() }),
output: z.object({ order: OrderSchema, events: z.array(OrderEventSchema) }),
});

packages/core holds contracts only: no SQL, no I/O. The handler lives in workers/api.

workers/api/src/framework/dispatch.ts runs every call the same way, whether it came over HTTP, RPC, MCP or from an agent:

  1. Look up the operation (unknown name: not_found).
  2. Check the actor’s role against roles (forbidden).
  3. For a customer, replace any accountId in the input with the customer’s own account.
  4. Validate the input with the Zod schema, applying defaults (validation, with one issue per field).
  5. Call the handler with the parsed input and a context.
  6. Validate the output against the output schema. A mismatch is a 500: the contract is the truth.
  7. Write the audit rows and send the queued events, only after success.

Handlers go in workers/api/src/handlers/<group>.ts, keyed by full operation name:

import { CrmError } from "@cemco/core";
import type { GroupHandlers } from "../types";
export const ordersHandlers = {
"orders.get": async (input, ctx) => {
const row = await ctx.db.prepare("SELECT * FROM orders WHERE id = ?").bind(input.id).first();
if (!row) throw CrmError.notFound("Order", input.id);
ctx.assertAccountAccess(row.account_id as string);
return { order: mapOrderRow(row) };
},
} satisfies Partial<GroupHandlers<"orders">>;

The context gives you:

  • db, env, actor, operation, requestId;
  • now, nowIso and today (a YYYY-MM-DD date in America/Chicago). Use these, never new Date(), so tests can fix the clock;
  • accountScope (the customer’s account, or null for staff) and assertAccountAccess(accountId);
  • audit(entry) or auditStatement(entry) to put the audit row in your own db.batch;
  • emit(event) to queue an event to cemco-events after success;
  • invoke(name, input) and invokeAsSystem(name, input) to call another operation;
  • waitUntil(promise).

Throw CrmError (notFound, conflict, validation, invalidOrder) for domain errors. A unique-constraint failure that escapes becomes a 409 conflict.

  1. Define it in packages/core/src/operations/<group>.ts with defineOperation, and add it to the group’s exported list. Write the description for an LLM: it becomes the MCP tool description.
  2. Implement it in workers/api/src/handlers/<group>.ts.
  3. Test it in workers/api/test/<group>.test.ts with callOp(actor, "group.verb", input); cover each role and, for portal operations, that one customer cannot reach another’s data.
  4. Run bun run typecheck && bun run test.

The HTTP route, OpenAPI entry, MCP tool, agent tool and the API reference page all appear without further work.

createCrmClient from @cemco/core/client gives a typed crm.orders.advance({ id }) over either transport: httpTransport (the app, scripts) or bindingTransport(env.API, actor) (other Workers). Domain errors come back as thrown CrmErrors.