---
agent:
  instructions: "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://segmentstream.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Ontology SDK

Model operational records and give people, apps and agents permission to change them through actions.

## What you can build

- [Model records and relationships](https://segmentstream.com/docs/records-and-actions)

  Give business objects stable IDs and typed properties. Link a ticket to its owner or a company to its contacts.

- [Control reads and writes](https://segmentstream.com/docs/access-and-permissions)

  Declare the actions a member can run and give each role the permissions its job requires.

- [Import or update records](https://segmentstream.com/docs/sdk/ontology#match-imported-records-by-their-source-id)

  Match repeated imports to an upstream key and reconcile how many records changed.

- [Automate follow-up](https://segmentstream.com/docs/jobs-and-workflows)

  Coordinate several actions, a wait or a provider call in a workflow.

## Start in the workspace ontology

The starter already has an ontology/ package with compatible versions of the SDK and Effect. Run this from ontology/ with its committed lockfile. Keep the existing entities and roles when extending a workspace.

Terminal · ontology/

```
npm ci
```

## Match imported records by their source ID

Suppose a support system exports companies. Give each company a stable entity ID and declare a unique key for the upstream account and record ID. The action accepts a batch and returns counts the caller can reconcile.

ontology/company.ts

```
import { action, entity, p } from "@segmentstream/ontology";
import { Schema } from "effect";

export const Company = entity("company", {
  id: "ent_company",
  label: "Company",
  plural: "Companies",
  title: "name",
  description: "A company imported from a support account.",
  properties: {
    sourceAccount: p.text({ description: "The upstream account ID." }),
    sourceId: p.text({ description: "The company ID within that account." }),
    name: p.text({ description: "The company's display name." }),
  },
  indexes: [{ properties: ["sourceAccount", "sourceId"], unique: true }],
}).actions((self) => ({
  importBatch: action({
    description: "Create or update companies by their source key.",
    input: Schema.Struct({ records: Schema.Array(Schema.Struct(self.properties)) }),
    handler: ({ input }) => self.upsertMany({
      on: ["sourceAccount", "sourceId"],
      records: input.records,
      returning: "summary",
    }),
  }),
}));
```

## Expose the action to an importer

Add Company to entities in the existing defineOntology call in ontology/index.ts. Register a role with the permissions below, then grant it to the importing member. Check the definition from ontology/ with npx segmentstream-ontology check before deploying a preview.

ontology/roles.ts

```
import { role } from "@segmentstream/ontology";

export const importer = role("importer", {
  description: "Imports company records and reconciles the results.",
  permissions: ["company:read", "company:importBatch"],
});
```

## Check what happens on a retry

Run company.importBatch in the preview as the importer. With an empty target, the input below should return created 1, updated 0, unchanged 0 in the action result. Resend it and expect unchanged 1. Change just the name and expect updated 1. The company keeps its workspace record ID on both retries.

Action input · JSON

```
{
  "records": [
    {
      "sourceAccount": "support",
      "sourceId": "C-10",
      "name": "Example Co"
    }
  ]
}
```

## Selected API methods and types

### Declare an entity · `entity`

Declares an entity. Add its actions with \`.actions((self) => ({ … }))\`; see {@link ActionsBuilder}. The data access methods delegate to {@link OntologyReads} and {@link OntologyWrites}, which the ontology service provides to actions.

```
function entity<const Name extends string, const P extends Properties, const R extends Relationships = NoRelationships, const M extends Metrics = NoMetrics>(name: Name, definition: EntityDefinition<P, R> & {
    readonly source: WarehouseSource;
    readonly metrics?: M;
} & EarlierMetricsField<M>): WarehouseBackedEntity<Name, P, R, M>;
```

```
function entity<const Name extends string, const P extends Properties, const R extends Relationships = NoRelationships, const M extends Metrics = NoMetrics, const W extends EntityWrites = "generated">(name: Name, definition: EntityDefinition<P, R, M> & {
    readonly writes?: W;
}): DraftEntity<Name, P, R, M, W>;
```

### Define a write operation · `action`

```
function action<Input extends Schema.Top, Result>(config: ActionConfig<Input, Result>): Action<Input, Result>;
```

```
function action<Input extends Schema.Top, const C extends ReadonlyArray<AnyConnectionHandle>, Prepared>(config: ActionConfigWithConnections<Input, C, Prepared, never> & {
    readonly handler?: undefined;
}): Action<Input, Prepared>;
```

```
function action<Input extends Schema.Top, const C extends ReadonlyArray<AnyConnectionHandle>, Prepared, Result>(config: ActionConfigWithConnections<Input, C, Prepared, Result>): Action<Input, Result>;
```

### Grant an action · `role`

```
function role<const Name extends string>(name: Name, options: RoleOptions): Role<Name>;
```

### Inspect the batch result · `BatchSummaryResult`

Outcome counts, which together equal the number of inputs in a successful batch.

```
interface BatchSummaryResult {
    readonly created: number;
    readonly updated: number;
    readonly unchanged: number;
}
```

[Import existing records](https://segmentstream.com/docs/import-existing-records)

[Read as Markdown ↗](https://segmentstream.com/docs/sdk/ontology.md)
