Adding API operations
When to use: Adding a new operation to the public API, changing an existing one, or wondering why mcp.json / openapi.json / the SDK aren't in sync.
Before you start — reuse the UI's logic via the domain layer
When you add a new operation, check whether the same action or read is already available in the web UI. The goal isn't full surface parity, it's not duplicating logic that the web already implements.
For each new operation, open apps/web/src/domains/<entity>/<entity>.functions.ts. Three cases:
- The web's server fn already calls a domain use-case (imports
*UseCasefrom@domain/*): reuse that use-case in the operation. Don't reimplement the logic. - The web's server fn has the logic inline (raw repository calls, validation, side effects in the server fn body itself): extract it into a new domain use-case first, then have both the web server fn AND your operation call it. The domain use-case becomes the shared seam.
- The web's server fn delegates to a third-party API like
getBetterAuth().api.*: the API process can't reach the same in-process instance. Write a domain use-case that replicates that behavior (carefully — read the third-party source so your use-case matches its rules), then point both the web and the operation at the use-case. Adds parity tests so the migration doesn't silently drift.
The domain use-case is the shared seam between web and API. Duplicating logic in both surfaces creates drift — one gets a bug fix the other doesn't.
If the entity doesn't have a .functions.ts because the UI doesn't expose this action yet, you're designing fresh. That's fine; just don't lose the option to share later — put the business logic in a @domain/* use-case from the start rather than inline in the operation.
What you're really doing
Every operation in packages/operations is one declaration that fans out into every generated surface:
| Surface | Generated from | Consumed by |
| --- | --- | --- |
| HTTP route (Hono) | route.method + route.path + execute/handler | curl, internal services — mounted by apps/api |
| OpenAPI operation | route.name (→ operationId), route.description, request/response schemas | apps/api/openapi.json — the source Fern reads for the SDKs + CLI |
| MCP tool | route.name, route.description, flattened input + 2xx-JSON output schema | apps/api/mcp.json, runtime /v1/mcp transport |
| TS + Python SDK methods | Fern reads openapi.json; group/sdkMethod name the method | end-user TypeScript (@latitude-data/sdk) and Python (latitude-sdk) code |
| latitude CLI command | Fern reads openapi.json | shell users + AI agents (latitude <resource> <verb>, --help, --schema) |
| In-process agent tool | defineToolset({ groups }) selection over execute-form operations | internal AI agents (e.g. the signal-creation agent) — no HTTP, no tokens |
You don't write these configs separately. You write one. The machinery in packages/operations/src/core/* derives the MCP tool and agent tools, and Fern derives the SDKs + CLI from openapi.json.
This means: the descriptions you put on routes and on schema fields are read by SDK users, by AI agents calling the MCP or an internal toolset, AND by CLI users (as --help/--schema text). Treat every description as user-facing copy. Vague or absent descriptions are bugs.
Recipe: add a new operation module
1. Create `packages/operations/src/operations/<resource>.ts`
Prefer execute-form (execute + typedResponses) for new operations — it's transport-neutral, so the operation is eligible for in-process agent toolsets and gets a typed status/body union. handler-form (a raw Hono handler + openApiResponses) still exists on unconverted modules; convert opportunistically when touching one.
import { createRoute, z } from "@hono/zod-openapi"
import { Effect } from "effect"
import { defineOperation } from "../core/define-operation.ts"
import type { OperationModule } from "../core/mount.ts"
import { jsonBody, PROTECTED_SECURITY, typedResponses } from "../openapi/schemas.ts"
import type { OrganizationScopedEnv } from "../types.ts"
// Step 1: declare the mount path once; the module carries it.
const widgetsPath = "/widgets"
// Step 2: bind the operation factory to the Env type AND the path.
const widgetOperation = defineOperation<OrganizationScopedEnv>(widgetsPath)
// Step 3: define the boundary schemas. EVERY field gets `.describe(...)` if its
// purpose isn't obvious from the name. Descriptions land in `openapi.json`
// (SDK docstrings), `mcp.json` (MCP tools), and agent toolsets.
const WidgetSchema = z
.object({
id: z.string().describe("Stable identifier; safe to use as a primary key in client storage."),
name: z.string().describe("Human-readable label, unique within an organization."),
createdAt: z.string().describe("ISO-8601 timestamp of creation."),
})
.openapi("Widget") // ← registers a named OpenAPI component (needed by Fern). Different from `.openapi({ description })`.
const CreateWidgetBody = z
.object({
name: z.string().min(1).describe("Display name for the new widget. Must be non-empty."),
})
.openapi("CreateWidgetBody")
// Step 4: declare each operation.
const createWidget = widgetOperation({
route: createRoute({
method: "post",
path: "/",
name: "createWidget", // ← camelCase. Becomes OpenAPI `operationId` AND MCP tool name.
tags: ["Widgets"],
group: "widgets", // ← SDK group (x-fern-sdk-group-name) AND agent-toolset selector. Declare right after `tags`.
sdkMethod: "create", // ← SDK method name inside the group (x-fern-sdk-method-name).
summary: "Create widget", // ← short label; falls through to MCP tool `title`.
description: "Creates a widget in the caller's organization. Returns the persisted record.",
security: PROTECTED_SECURITY,
request: { body: jsonBody(CreateWidgetBody) },
responses: typedResponses({ status: 201, schema: WidgetSchema, description: "Widget created" }),
}),
access: "write", // ← required: "read-only" | "write" | "destructive". See "Access" below.
rateLimitTier: "low", // ← declarative; apps/api maps it to middleware at mount time.
execute: (input, ctx) =>
Effect.gen(function* () {
// input.body / input.params / input.query are pre-validated; ctx carries
// organization, auth, and clients. Pipe your layers exactly as before:
// .pipe(withPostgres(..., ctx.postgresClient, ctx.organization.id), withTracing)
const widget = yield* createWidgetUseCase({ name: input.body.name })
return { status: 201, body: toResponse(widget) } as const
}).pipe(/* withPostgres(...), withTracing */),
})
// Step 5: export the module — mount order within `operations` is meaningful
// (Hono matches static-before-param routes in registration order).
export const widgetsModule: OperationModule = {
path: widgetsPath,
operations: [createWidget],
}
Execute-form notes:
typedResponsesis the literal-keyed twin ofopenApiResponses(identical runtime output). It makes the{ status, body }union checkable: declared non-2xx variants (400/401/404) are returnable values; domain failures left in the Effect error channel re-throw and reachhonoErrorHandlerexactly as in handler-form. Keep its response keys literal — deriving them from a generic collapses the inference under tsgo (see the comment ontypedResponses).ctx(OperationContext) carriesorganization,auth, and the platform clients — everything the oldc.varprovided. Tenancy is baked in: the organization is resolved beforeexecuteruns and is never part of the input.inputcontains only the sections the route declares (params/query/body), already validated.
2. Register the module in `packages/operations/src/operations/index.ts`
Add the import and one entry to operationModules. Position = mount position: openapi.json path order and mcp.json tool order derive from it, so append new modules at the end unless there's a routing reason not to.
3. Regenerate manifests
pnpm openapi:emit # rewrites apps/api/openapi.json
pnpm mcp:emit # rewrites apps/api/mcp.json
Both files are checked in. CI guards against drift, so commit them alongside the module.
The TS + Python SDKs and the latitude CLI all regenerate from openapi.json via Fern — pnpm generate:sdk (both SDKs), pnpm generate:cli (CLI), or pnpm generate:all (all three; needs Docker + a Rust toolchain for the CLI). CI (api-manifests.yml) regenerates all of them and fails on drift, so run pnpm generate:all and commit the results when your PR changes the surface — otherwise the drift check goes red.
Always use these pnpm scripts — never run fern generate directly. The generate:sdk:* scripts pin --version (from the SDK's package.json / pyproject.toml) so the version Fern bakes into the generated Python client_wrapper.py User-Agent is deterministic; a bare fern generate omits it and re-stamps a registry-derived version ("last published + a patch"), which flaps the drift check on every SDK publish. See