# Capabilities kit (TypeScript)

Reference for @omazyai/sdk/capabilities. Define each action your product offers once and generate its MCP tools, model tools, forms, logs and tools changelog from it.

Source: https://docs.omazy.ai/build-on-omazy/kits/capabilities/

:::caution[Preview]
The kit is a preview in `@omazyai/sdk` 0.5.3. Its interface may change before 1.0, so pin the exact version. It is TypeScript only.
:::

```ts
import { type Ctx, defineCapabilities, registry, schema } from '@omazyai/sdk/capabilities'
```

The kit has no dependencies and uses only Web standard APIs, so it runs on Cloudflare Workers, Node, Bun and Deno.

## Define a capability

```ts
type AppCtx = Ctx<{ locale: 'en' | 'bn' }>
const { capability } = defineCapabilities<AppCtx, { org: string }, 'platform' | 'org'>()

export const staffList = capability({
  name: 'staff_list',
  audiences: ['org'],
  title: 'List staff',
  description: 'Lists the staff of the current tenant with their names and teams. Not for console members: use members_list.',
  synonyms: ['employees', 'team'],
  permission: { org: 'staff.read' },
  risk: 'R1',
  input: schema.object({ team: schema.text(80).optional(), limit: schema.integer({ min: 1, max: 100 }).default(20) }),
  output: schema.object({ rows: schema.array(schema.object({ name: schema.text(120) })) }),
  pii: ['rows.*.name'],
  version: 1,
  run: (ctx, input) => staff.list(ctx, input),
})
```

`capability()` checks the definition when the module loads and throws `CapabilityError` with every problem it finds.

| Field | Rule |
|---|---|
| `name` | `<noun>_<verb>`: lower case words joined by `_`, at most 64 characters. Never renamed once shipped |
| `audiences` | At least one door, none repeated |
| `title` | Not empty |
| `description` | 80 to 600 characters. It is a prompt: what it does, what it does not, "Not for X: use Y" |
| `synonyms` | Optional. Used by search. Sent to the model only with `{ synonyms: true }` |
| `permission` | Any value. The kit passes it to your permission check and never reads it |
| `risk` | `R0` to `R4` |
| `riskFor(input)` | Optional. A lower tier for some inputs. It never weakens caution: a tier above `risk` is used and reported once through `console.warn` (`setTierAboveRiskHandler` to change that), and a value that is not a tier, or a throw, counts as R4 |
| `approval` | A policy name from your policy table. Required at R3 and R4 |
| `input` | A closed object schema |
| `output` | Optional. Becomes the MCP `outputSchema` |
| `pii` | Dotted paths of personal fields in the input or output. `*` matches any key or index |
| `version` | A whole number from 1, raised on every schema change |
| `deprecated` | `{ since, removeAfter?, use?, reason? }`, dates as `YYYY-MM-DD`. `removeAfter` defaults to 90 days after `since` |
| `openWorld` | Optional. The capability reaches outside the product (mail, the web) |
| `preview(ctx, input)` | Required at R2 and above. Returns `{ summary, before?, after?, stateVersion? }` |
| `run(ctx, input)` | Does the work |
| `say(output, ctx)` | Optional. The text a model reads for a completed call, such as `Filed NCR-10042: pothole at Main St.` The output still goes out as `structuredContent`. Default: the output as JSON text |
| `unknownFields` | `'refuse'` (default) or `'strip'`. With `strip`, an argument the input schema does not name is dropped and the call runs; the dropped paths go to the request log as `stripped:<paths>`. Use it only to keep clients that always sent extra fields working |
| `invalidMessage(issues)` | Optional. The one sentence for an `invalid` call, built from its issues. Default: each issue with its path. A model sees only this sentence, not the list |

`capability()` without `defineCapabilities` also works. It takes the context type from the type annotations on `run` and `preview`.

## Context

```ts
interface BaseCtx {
  principal: { kind: string; id: string; name?: string }
  seat: { id: string; door: string; tenant: string | null } | null
  tenant: string | null
  channel: 'console' | 'mcp' | 'copilot' | 'actor' | 'workflow' | 'automation' | string
  approvalId: string | null
  requestId: string
}
type Ctx<X extends object = {}> = BaseCtx & X
```

## Tiers

| Tier | Meaning | Mode | MCP annotations |
|---|---|---|---|
| R0 | Read, no personal data | read | read only, idempotent |
| R1 | Read with personal data | read | read only, idempotent |
| R2 | Reversible change inside one tenant | write | not destructive |
| R3 | Sensitive, outward facing, or hard to undo | write | destructive |
| R4 | Irreversible across a tenant | write | destructive |

The mode and the annotations are worked out from the tier each time and never stored. A value that is not a tier counts as R4. `openWorldHint` is true only when the capability sets `openWorld`.

### A write that reaches only your own staff

Mail or a message to your own staff is outward in form but not in reach. Keep it at R2 with
`openWorld: true` when all of these hold:

- the recipients come from your configuration (a fixed staff list, an on-call rota), never from
  an argument the caller fills;
- what is sent is built from the arguments by your code, not passed through as free text to a
  third party;
- holding it for an approver would defeat it, as with an urgent safety alert.

Use R3 when the caller names the recipient, when it reaches a customer, a partner or the public,
or when it changes what your product says to the world. `openWorld: true` sets the MCP
`openWorldHint` either way, so a client still sees that the tool reaches beyond the product.

Helpers: `modeOf(tier)`, `annotationsOf(tier, { title, openWorld })`, `tierRank(tier)`, `needsConfirm(tier)` (R2 and above), `needsApproval(tier)` (R3 and above), `tierFor(capability, input)`.

## Schemas

`input` and `output` take any [Standard Schema](https://standardschema.dev) that also gives Standard JSON Schema:

- **zod 4.2 and later** as is. Use `z.strictObject` so zod refuses unknown fields too. `parse` refuses them either way.
- **valibot, TypeBox and others** through `withJsonSchema(schema, jsonSchema)`, with the JSON Schema from the library's own converter.
- **The built-in helpers**, with no dependency:

| Helper | JSON Schema |
|---|---|
| `schema.object(shape)` | closed object, `required` from fields that are not optional |
| `schema.string({ min, max, pattern, format })` | string. Lengths count characters, not bytes |
| `schema.text(max, min = 1)` | string of `min` to `max` characters |
| `schema.id()` | 1 to 128 characters, no spaces |
| `schema.integer({ min, max })`, `schema.number(...)` | integer, number |
| `schema.minorUnits({ max })` | whole number from 0, a money amount in cents or poisha |
| `schema.boolean()`, `schema.enum([...])`, `schema.literal(v)` | boolean, enum, const |
| `schema.array(item, { min, max })` | array |
| `schema.unknown()` | any JSON |
| `.optional()`, `.default(v)`, `.nullable()`, `.describe(text)` | on any helper |

The kit closes every object in the JSON Schema with `additionalProperties: false` unless it is already set (a record map keeps its value schema) and drops `$schema`. An input that is not a closed object does not load.

`unknownFields(jsonSchema, value)` lists the fields a closed JSON Schema does not name, following local `$ref`s, `anyOf` and `oneOf`.

`validate(schema, value)` returns `{ ok: true, value }` or `{ ok: false, issues: [{ message, path }] }`. `toJsonSchema(schema, 'input' | 'output')` gives the closed JSON Schema.

## Registry

```ts
const reg = registry([staffList, paymentRecord /* , ... */])
```

A name used twice throws.

| Method | Returns |
|---|---|
| `list(door?)` | Capabilities, in definition order |
| `get(name)`, `has(name)` | One capability |
| `mode(name)` | `read` or `write`. An unknown name is a write |
| `tier(name, input?)` | The declared tier, or the tier of one call. An unknown name is R4 |
| `annotations(name)` | MCP annotations from the declared tier |
| `parse(name, args)` | `{ ok: true, capability, input, tier, mode }`, or `{ ok: false, reason: 'unknown_tool' \| 'invalid', issues }`. A field the closed JSON Schema does not name, at any depth, is refused whatever the schema library does |
| `mcpTools(door, { maxTier, names, synonyms })` | `tools/list` entries: `name`, `title`, `description`, `inputSchema`, `outputSchema`, `annotations` |
| `modelTools({ audience, names, maxTier, synonyms })` | `ToolDefinition[]` for `omazy.ai.complete({ tools })` |
| `select(options)` | The capabilities either list would hold |
| `describe(name)` | The description, with a deprecation note first when deprecated |
| `formSchema(name)` | The input JSON Schema with `title` and `description` |
| `redact(name, value)` | A copy with the personal fields replaced by `[redacted]` |
| `logArgs(name, value, maxBytes = 4096)` | Redacted JSON, cut on a character boundary |
| `search(query, { audience, limit = 8, exclude })` | `[{ name, score }]`, best first |
| `snapshot()` | The catalog as data |
| `parity(surfaces, { audiences })` | Throws `ParityError` on any problem |

The registry checks arguments and works out the tier. It does not check permissions, confirm or approve. The guard kit does that.

`mcpTools()` fits the `tools` list of `serveMcp` in `@omazyai/sdk/server`.

## Tool search

`reg.search()` ranks with BM25 over the name, title, description and synonyms. Name and synonyms count most. It works in any script, and drops common English words and plural `s`. A copilot can send the model a core set of tools and a search tool, then add the hits to the next call. `searchIndex(items)` and `tokenize(text)` are exported for other catalogs.

## Versioning

Schema changes are additive only. A breaking change gets a new name, and the old capability is deprecated and kept until its `removeAfter` date.

```ts
import before from './tools.snapshot.json'
import { assertAdditive, toolsChangelog } from '@omazyai/sdk/capabilities'

test('the catalog only grows', () => {
  assertAdditive(before, reg.snapshot())
})
// After review: write reg.snapshot() back to tools.snapshot.json, and add
// toolsChangelog(before, reg.snapshot(), { date }) to your tools changelog.
```

`compareSnapshots(before, after, { today })` lists every change. `assertAdditive` throws `BreakingChangeError` when any of them breaks a client:

- an input field removed, a new required input field, a type, enum, length, range, pattern or format that accepts less;
- an output field removed or no longer required, an output that may return new types or values;
- a schema change with the same `version`, or a lower `version`;
- a door removed from `audiences`;
- a capability removed before its `removeAfter` date.

A tier or approval change is listed but is not breaking: it changes who may call, not the shape.

## Parity

Run it in CI with every list of tool names your product keeps outside the registry:

```ts
reg.parity(
  {
    'console routes': consoleRoutes.map((r) => r.capability),
    'copilot core set': copilotCore,
    'mcp /org': { audience: 'org', tools: orgDoorTools },
  },
  { audiences: ['platform', 'org', 'host'] },
)
```

It fails when an entry breaks a definition rule (including a missing audience or tier), a name is used twice, a capability is on an unknown door, a deprecation points at a capability that is not there, or a surface names a tool the registry lacks, lists it twice, or lists one its door cannot see. `parityProblems(catalog, { surfaces, audiences })` returns the problems instead of throwing, and takes a registry or a plain list. Its `surfaces` is the same record `reg.parity` takes (the `Surfaces` type), so a check moves between the two unchanged:

```ts
const problems = parityProblems(reg, { surfaces: { 'mcp /org': { audience: 'org', tools: orgDoorTools } } })
```

The array form, `surfaces: [{ name, audience?, tools }]`, still works and is deprecated: it goes before the first release.
