Client SDK and notebooks
The Client SDK is a typed client generated from your own ontology. Every object type becomes a class, every link a traversal, every action a function with typed parameters and every property a field your editor can complete. It is the same client the platform's own screens use, over the same REST API, with the same permissions and the same audit trail
mso command runs the Python client's calls from a shellIn the platform today
A Python client and a TypeScript client run against the platform service
- Python: the package
mso_clientneeds Python 3.11 or later andhttpx, with a sync client (Client) and an asyncio client (AsyncClient) that make the same calls - TypeScript:
@marklandstreet/ontology-clienthas no runtime dependencies and runs on Node 22.18 or later, Deno, Bun and browsers - Both cover object sets over object types and interfaces (
where,followup to 3 links,derive,select,orderBy,page,iterate,all,first,one,aggregateandcount) and actions (check,runwithdryRunandincludeEdits,runBatchandpropose) - Both also cover proposals, the action log with revert, functions with traces, agents, metrics, dashboards, SQL and change feeds, with typed errors, retries and pagination. The TypeScript client also covers the Assistant, time series and search
- Push updates:
mso.stream.subscribe(topics)in TypeScript andmso.subscribe(topics)onAsyncClientread server-sent events with one-use tickets, resume by event id and fall back to long polling, and both keep object sets live with filtered subscriptions that send entered, changed and left - The
msocommand runs the Python client's calls from a shell - Typed code comes from
mso generate(orpython -m mso_client.generate) and the TypeScript client'sgeneratescript
Object set subscriptions over websockets, OAuth sign-in flows and versioned per-tenant package generation described on the rest of this page are delivered on request
import os
from mso_client import Client, ActionValidationFailed
# or set MSO_API_URL and MSO_TOKEN
mso = Client("https://ontology.example.com", token=os.environ["MSO_TOKEN"])
aog = (
mso.objects("aircraft")
.where({"status": "AOG"})
.follow("flight-aircraft")
.page(page_size=50)
)
fleet = mso.objects("aircraft").order_by("fleetNumber").all()
by_type = mso.objects("aircraft").aggregate(group=["aircraftType"], measure={"n": "count"})
try:
mso.actions("swap-aircraft").run(
{"flight": "MKA214-20261023", "newAircraft": "411", "reason": "407 AOG at YYT"},
dry_run=True,
)
except ActionValidationFailed as err:
print(err.code, err.reason, err.request_id)
dispatch = mso.metrics("dispatch-reliability").query(group=["origin"], time={"last": "7d"})
late = mso.sql(
"select origin, avg(delayMinutes) as mins from gold.flights group by origin"
).to_polars()
changes = mso.changes("aircraft").since(cursor=-1)
The same calls from TypeScript
import { Client, ActionValidationError } from "@marklandstreet/ontology-client";
const mso = new Client("https://ontology.example.com", { token }); // or { getToken }
const aog = await mso.objects("aircraft")
.where({ status: "AOG" })
.follow("flight-aircraft")
.page({ pageSize: 50 });
const byType = await mso.objects("aircraft")
.aggregate({ group: ["aircraftType"], measure: { n: "count" } });
try {
await mso.actions("swap-aircraft").run(
{ flight: "MKA214-20261023", newAircraft: "411", reason: "407 AOG at YYT" },
{ dryRun: true },
);
} catch (err) {
if (err instanceof ActionValidationError) console.log(err.conditions);
}
const life = await mso.functions
.invoke("remaining_life", { fleetNumber: "401" }, { trace: true });
for await (const e of mso.stream.subscribe(["objects:aircraft"])) {
console.log(e.data.op, e.data.key);
}
| Part | In the Python client |
|---|---|
| Object sets | where, follow, derive, select and order_by build an immutable query; page, iterate, all, first, one, aggregate and count run it |
| Actions | describe, check, run with dry_run and include_edits, run_batch and propose |
| Functions and agents | mso.functions(name).invoke(...); mso.agents(id).run(...), runs() and trace(run) |
| Metrics and dashboards | query, explain and versions; dashboards list, create, get, render, update, copy and delete |
| SQL and changes | mso.sql(...) with to_arrow, to_polars and to_pandas; mso.changes(type).since(cursor) |
| Errors | Every failure is an OntologyError with the stable code, reason, HTTP status, request id and problem body, in subclasses such as PermissionDenied, ObjectNotFound, ActionValidationFailed, ConcurrencyConflict and RateLimited |
| Retries | Reads, checks, dry runs and SQL are retried 3 times by default with exponential backoff and full jitter from 200 ms, honouring Retry-After. Action runs, batches and proposals are never retried |
| Async | AsyncClient: every call above, awaited; iterate is an async generator; subscribe and ObjectSet.subscribe keep sets live |
| Proposals and the action log | mso.proposals list, approve and reject; mso.action_log list and revert with dry_run |
| Inbox | mso.inbox list, read and read_all |
| Command line | mso: query, get, actions, proposals, log, undo, functions, sql, watch, generate and inbox |
The generator writes typed dataclasses for the object types the generating person can see, with enum values as Literal types and link names on each class, a TypedDict of parameters per action type, and the ontology revision it was generated from
python -m mso_client.generate --api https://ontology.example.com \
--token "$MSO_TOKEN" --out generated/markham_ontology
from markham_ontology import Aircraft
for a in mso.objects(Aircraft).where({"status": "AOG"}).iterate():
print(a.fleetNumber, a.statusSince) # a is an Aircraft
The TypeScript generator writes an interface per object type the generating person can see, with its links and the type on the far side, a parameter interface per action type, argument types per function, a descriptor constant for each and an Ontology map that types the client. It imports types only, so it runs under type stripping with no build step. Run it with the TypeScript client's generate script
npm run generate -- https://ontology.example.com \
--token "$MSO_TOKEN" > markham-types.ts
import { Client } from "@marklandstreet/ontology-client";
import { Aircraft, groundAircraft, type Ontology } from "./markham-types.ts";
const mso = new Client<Ontology>("https://ontology.example.com", { token });
// aog.data[0].status: "In service" | "AOG" | …
const aog = await mso.objects(Aircraft).where({ status: "AOG" }).page();
// parameters checked by the compiler
await mso.actions(groundAircraft)
.run({ aircraft: "401", reason: "Bird strike" }, { dryRun: true });
Command line
The mso command runs the Python client's calls from a shell. It comes with the Python client package, mso-client. It connects to --url or $MSO_API_URL as --token or $MSO_TOKEN. Parameters are key=value for text and key:=JSON for numbers, lists and objects; lists print as tables, and --json prints the API's JSON
mso query aircraft --where '{"status": "AOG"}' --select fleetNumber,currentStation,statusSince
mso query tracked-unit --interface --where '{"hoursRemaining": {"$lt": 300}}'
mso actions run ground-aircraft aircraft=401 reason="Bird strike" --dry-run
mso proposals list --status pending
mso undo <logId> --dry-run
mso functions invoke remaining_life fleetNumber=401 --trace
mso watch objects:aircraft --where '{"status": "AOG"}' --properties status,currentStation
mso generate > markham_types.py
mso inbox
Exit codes say what went wrong: 2 an invalid argument, 3 not signed in or not allowed, 4 not found, 5 an action's conditions failed or a conflict, 6 the service is unavailable. Per-tenant packages with their own versions are delivered on request
How generation works
An ontology changes as the operation changes: a new property on Raw milk silo, a new action for holding a batch, a link from QA test to Dairy farm. A hand-written client drifts from that model within weeks. The SDK avoids drift by being generated: mso generate, or python -m mso_client.generate, and the TypeScript client's generate script read the ontology from the running API and write typed code, as shown above. The generated code holds types and descriptors only; the client package does the work of authenticating, querying, paging and retrying
What is generated
| Ontology element | TypeScript | Python |
|---|---|---|
| Object type | An interface with typed properties and a descriptor constant, for example Aircraft | A dataclass with typed attributes, for example Aircraft |
| Link type | The link ids of each type, with the type on the far side | Link names on each class |
| Action type | A parameter interface, with required parameters required, and a descriptor such as groundAircraft | A TypedDict of parameters |
| Function | Argument types and a descriptor | The function ids, in FUNCTIONS |
| Interface | Not generated | A dataclass with its properties and the implementing types |
| Property with listed values | A string literal union | A Literal type |
Only types the calling user can see are generated. If a property is hidden from you by field access, it is absent from the package you generate, and a colleague with wider access generates a wider package from the same revision. The server still enforces security on every call, so a package generated by someone else never grants access you do not have
Install and authenticate
In the platform today the client sends a bearer token from your identity provider: token, or getToken, which it calls before every request, so your sign-in library keeps the token fresh
import { Client } from "@marklandstreet/ontology-client";
// A service or scheduled job: an OpenID Connect access token from your identity provider
const svc = new Client("https://creamery.ontology.marklandstreet.com", {
token: process.env.MSO_TOKEN,
});
// A browser app: your sign-in library hands over the person's current token before each request
const app = new Client("https://creamery.ontology.marklandstreet.com", {
getToken: () => auth.accessToken(),
});
// An agent acting for the signed-in person
const forAgent = new Client("https://creamery.ontology.marklandstreet.com", {
getToken: () => auth.accessToken(),
agent: "agt-weekend",
});
On request, the runtime runs the OAuth 2.0 flows itself, as in the Python example below
- Services and scheduled jobs use client credentials with a client registered in the console
- Browser and desktop apps use the authorization code flow with PKCE, so no secret ships in front-end code
- Access tokens last 60 minutes and the runtime refreshes them 5 minutes before expiry, with one refresh in flight at a time however many requests are waiting
import os
from mso_client import Client
from mso_client.auth import ConfidentialClientAuth
auth = ConfidentialClientAuth(
client_id=os.environ["MS_CLIENT_ID"],
client_secret=os.environ["MS_CLIENT_SECRET"],
scopes=["ontology:read", "actions:apply"],
)
client = Client("https://creamery.ontology.marklandstreet.com", auth=auth)
A client-credentials token acts as its service principal, which holds roles and access labels like any user. When your code starts an agent run on behalf of a signed-in person, pass that person's token; the agent then reads and proposes with their access and never more
Query objects
Queries are built fluently and run only when you call a terminal method: page, pages, iterate, all, first, one, aggregate or count. Until then a query is an immutable object set definition that you can pass around, extend and reuse. Each method returns a new definition, so branching from a shared base is safe. On request, derive also takes a function's result, such as siloRisk.property("hoursToLimit"), filters compare durations such as { $lt: { hours: 60 } }, and follow takes a link side's id such as deliveries
import { Client } from "@marklandstreet/ontology-client";
// npm run generate -- <url> --token "$MSO_TOKEN" > ontology-types.ts
import { Shop, Delivery, type Ontology } from "./ontology-types.ts";
const mso = new Client<Ontology>("https://creamery.ontology.marklandstreet.com", { getToken });
// One object by primary key
const run = await mso.objects(Delivery).one("DLV-5521");
run.temp; // number | null | undefined, typed from the ontology
// Island shops still open, then the runs that serve them
const runs = await mso.objects(Shop)
.where({ province: "PE", status: { $ne: "Closed" } })
.follow("delivery-stop-shop") // a link type id: the shop's stops
.follow("delivery-stop-delivery") // then the runs they are on
.where({ status: { $in: ["Scheduled", "In transit"] } })
.page({ pageSize: 50, orderBy: "eta", select: ["crossing", "eta", "status"] });
// Aggregate: runs, warmest reefer and average delay by crossing this month
const byCrossing = await mso.objects(Delivery)
.where({ departs: { $gte: "2026-10-01T00:00:00-03:00" } })
.aggregate({
group: ["crossing"],
measure: { runs: "count", maxTemp: { max: "temp" }, avgDelay: { avg: "delayH" } },
});
# python -m mso_client.generate --out ontology_types
from ontology_types import Shop, Delivery
runs = (
mso.objects(Shop)
.where({"province": "PE", "status": {"$ne": "Closed"}})
.follow("delivery-stop-shop")
.follow("delivery-stop-delivery", as_type=Delivery)
.where({"status": {"$in": ["Scheduled", "In transit"]}})
.page(page_size=50, order_by="eta")
)
for run in runs.data:
print(run.primary_key, run.crossing, run.eta)
On request, generated Python classes also carry query expressions and snake case link names
runs = (
mso.objects(Shop)
.where(Shop.province == "PE", Shop.status != "Closed")
.follow("delivery_stop_shop")
.follow("delivery_stop_delivery")
.where(Delivery.status.in_(["Scheduled", "In transit"]))
.page(page_size=50, order_by=Delivery.eta.asc())
)
for run in runs.data:
print(run.primary_key, run.crossing, run.eta)
Filter operators
| Operator | Applies to | Example |
|---|---|---|
$eq, $ne | Any property; a bare value means $eq | { qaStatus: "Released" } |
$in, $nin | Any property; on request, up to 1,000 values | { line: { $in: ["Line 1", "Line 2"] } } |
$lt, $lte, $gt, $gte | Numbers, dates, timestamps, durations | { hoursSinceReceipt: { $gte: 60 } } |
$missing | Any property | { resultAt: { $missing: true } } |
$prefix | Strings | { batchNo: { $prefix: "B-08" } } |
$has, $hasAll | Arrays | { silos: { $has: "SIL-2" } } |
$phrase, $anyWord, $allWords, $fuzzy | Text | { holdReason: { $allWords: "underfill re-weigh" } } |
$near, $inBox, $inArea | Geopoints | { position: { $near: {center: { lat: 46.24, lon: -63.13 },distance: { value: 25, unit: "km" } } } } |
$and, $or, $not | Clauses; on request, up to 500 per query | { $or: [{ hold: true }, { $not: { qaStatus: "Released" } }] } |
A query may traverse at most 3 links with follow. Filters on stored, indexed properties are pushed down to the search index; filters on derived properties from derive are evaluated by a distributed scan after the index narrows the set, so put indexed filters first when you can. See object sets for the full query model
Pagination
page returns at most one page and a token for the next one. The default page size is 100 and the maximum is 1,000. In the platform today a page token does not pin a snapshot, so a long walk can see objects that changed while it ran
On request, a page token pins the query to the read version of the first page, so a paged walk sees one consistent snapshot even while objects change underneath it. Tokens are valid for 60 minutes; after that the next call fails with PageTokenExpiredError and the walk must restart
// Explicit pages
let pageToken: string | null = null;
do {
const page = await mso.objects(Batch)
.where({ qaStatus: "On hold" })
.page({ pageSize: 500, pageToken });
for (const batch of page.data) review(batch);
pageToken = page.nextPageToken;
} while (pageToken);
// Or let the client page for you
const held = mso.objects(Batch).where({ qaStatus: "On hold" });
for await (const batch of held.iterate({ pageSize: 500 })) {
review(batch);
}
held = mso.objects(Batch).where({"qaStatus": "On hold"})
for batch in held.iterate(page_size=500):
review(batch)
If you are paging through objects to count, sum or group them, use aggregate. It runs where the data is, returns one response and is not affected by the page size limit or the token lifetime
Actions, functions and agents
Actions are the only way the SDK changes the Ontology. run runs the full action pipeline: parameter validation, action conditions, edit computation, an atomic commit with optimistic concurrency, the action log entry and queued writeback. Pass dryRun to check everything without committing, which is how forms show inline errors before a person presses submit
import { ActionValidationError } from "@marklandstreet/ontology-client";
import { sendSiloToCheese, placeHold } from "./ontology-types.ts";
// Check first: per-parameter and per-condition results, commits nothing
const check = await mso.actions(sendSiloToCheese).check({
silo: "SIL-2", litres: 17300, start: "Tonight 22:00",
});
if (check.result === "INVALID") return showErrors(check.conditions, check.parameters);
// Apply, asking for the changes back. A failing condition throws ActionValidationError (422)
const applied = await mso.actions(sendSiloToCheese).run(
{ silo: "SIL-2", litres: 17300, start: "Tonight 22:00" },
{ includeEdits: true }
);
applied.logId; // "alog_01M5Y37V2WMVAKSWEET55FJ4Y3"
applied.edits; // 3, the number of objects edited
applied.changes;
// [{ op: "create", objectType: "batch", primaryKey: "CH-0232", … },
// { op: "create", objectType: "silo-draw", … },
// { op: "modify", objectType: "silo", primaryKey: "SIL-2", … }]
// Several applications in one request, each applied on its own
const batch = await mso.actions(placeHold).runBatch([
{ batch: "B-0840", reason: "Same silo draw as B-0841" },
{ batch: "B-0843", reason: "Same silo draw as B-0841" },
]);
batch.applied; // 2
In the platform today each request in a batch is checked and applied on its own, and the response gives each one's result. A single application may produce up to 10,000 edits, else it fails with ACTION_VALIDATION_FAILED and reason EDIT_LIMIT_EXCEEDED. On request, a batch commits all or none, an Idempotency-Key makes a retried apply safe, and a batch accepts up to 1,000 parameter sets per request and up to 100,000 edited objects in total. Batches skip includeEdits by default, because the response would be large; the action log has every edit
from ontology_types import SEND_SILO_TO_CHEESE
result = mso.actions(SEND_SILO_TO_CHEESE).run(
{"silo": "SIL-2", "litres": 17300, "start": "Tonight 22:00"},
dry_run=False,
include_edits=True,
)
# Functions run with your permissions
risk = mso.functions("silo_risk").invoke({"silo": "SIL-2"})
print(risk["hoursToLimit"], risk["risk"])
Agent runs
In the platform today mso.agents.run(id, input) runs the agent and returns when it has finished, with its run id, and mso.agents.trace(id, runId) reads its trace. On request, agents are started by name and a run returns immediately with an id; you can wait for it, stream its steps, or fetch its reasoning trace later. Runs never apply actions on their own unless the agent is configured to; they produce proposals for a person to approve
The built call
const run = await mso.agents.run(
"agt-weekend",
"Will any island shop run short of strawberry before Sunday close?",
);
const trace = await mso.agents.trace("agt-weekend", run.run_id);
// what it proposed, for a person to approve
const waiting = await mso.proposals.list({ status: "pending" });
On request, the asynchronous form
const run = await client.agents("agt-weekend").startRun({
input: { question: "Will any island shop run short of strawberry before Sunday close?" },
onBehalfOf: userAuth,
});
for await (const step of run.steps()) console.log(step.index, step.tool, step.durationMs);
const done = await run.wait({ timeoutMs: 120_000 });
done.proposals; // staged actions waiting for approval, with citations
Subscriptions
The platform service pushes object, action, proposal, edge and alert events as server-sent events at /api/v2/stream, filtered by the caller's access and resumable by event id; see push updates. The TypeScript client subscribes with mso.stream.subscribe(["objects:aircraft", "actions"]) and the Python AsyncClient with mso.subscribe(...), to topics or to filtered object sets. Object set subscriptions over a websocket are delivered on request
In the platform today a subscription is to topics: objects:<type>, actions, proposals, edge and alerts. Each object event carries op (created, modified or deleted), the type, the key, the changed properties and the object as the caller may see it
const sub = mso.stream.subscribe(["objects:silo", "actions"]);
for await (const e of sub) {
// too far behind to replay: reload
if (e.event === "reset") refetchAll();
else if (e.data.type === "silo") render(e.data.key, e.data.object);
}
// resume later after sub.lastEventId; sub.close() to stop
A filtered subscription keeps an object set live: the objects of one type or interface that match a where in the query grammar, optionally only some properties
- Each change is matched before and after it, so you get
entered,changedandleft(withreasonunmatched or deleted), with the same access rules as a query - By default the objects that match now come first, then
synced;reloadfollows a bulk change - Resuming by event id works as for topics
const sub = mso.stream.subscribe([], {
subscriptions: [{
id: "full-silos",
objectType: "silo",
where: { volume: { $gt: 30000 } },
properties: ["volume", "temp"],
}],
});
for await (const e of sub) {
if (e.event !== "subscription") continue;
// entered, changed, left; synced after the snapshot; reload
const { op, key, object } = e.data;
if (op === "left") remove(key);
else if (op === "entered" || op === "changed") render(key, object);
}
from mso_client import AsyncClient
async with AsyncClient("https://creamery.ontology.marklandstreet.com", token=token) as mso:
full = mso.objects("silo").where({"volume": {"$gt": 30000}})
async with full.subscribe(properties=["volume", "temp"]) as sub:
# entered, changed, left, then synced after the snapshot
async for e in sub:
print(e.data["op"], e.data["key"])
On request, an object set can be kept live over a websocket, with events as objects enter, change or leave it, checked against the reader's access each time
Errors
Every failure is a subclass of OntologyError in TypeScript and of mso_client.OntologyError in Python. Each carries the stable error code from the API's problem details, the HTTP status, the requestId to quote to support and the full problem object for anything else
| Class in TypeScript and Python | Code | Retried |
|---|---|---|
InvalidArgumentErrorInvalidArgument | INVALID_ARGUMENT | No |
PermissionDeniedErrorPermissionDenied | PERMISSION_DENIED | No |
ObjectNotFoundErrorObjectNotFound | NOT_FOUND with reason OBJECT_NOT_FOUND | No |
ActionValidationErrorActionValidationFailed | ACTION_VALIDATION_FAILED | No; inspect conditions |
ConcurrencyConflictErrorConcurrencyConflict | CONCURRENCY_CONFLICT | No; re-read and decide |
PageTokenExpiredErrorPageTokenExpired | PAGE_TOKEN_EXPIRED, on request with expiring page tokens | No; restart the walk |
RevisionIncompatibleErrorRevisionIncompatible | ONTOLOGY_REVISION_INCOMPATIBLE, on request with versioned packages | No; regenerate the package |
RateLimitedErrorRateLimited | RATE_LIMITED | Yes, after Retry-After when sent, else with backoff |
FunctionTimeoutErrorFunctionTimeout | FUNCTION_TIMEOUT | No |
UnavailableErrorServiceUnavailable | SERVICE_UNAVAILABLE | Yes, with backoff |
The client retries reads, queries, checks and dry runs up to 3 times with exponential backoff and full jitter, starting at 200 ms and honouring Retry-After. Runs, batches, proposals, approvals, reverts and function calls are sent once. On request, it retries action applies when an idempotency key is set; if you do not pass one, the runtime generates a key per call, so a retried apply after a dropped connection never applies twice
import { ActionValidationError, ConcurrencyConflictError } from "@marklandstreet/ontology-client";
import { placeHold } from "./ontology-types.ts";
try {
await mso.actions(placeHold).run({ batch: "B-0841", reason: "QA-7710 underfill" });
} catch (err) {
if (err instanceof ActionValidationError) {
// "notHeld", "B-0841 is already on hold"
for (const c of err.conditions) console.warn(c.name, c.message);
} else if (err instanceof ConcurrencyConflictError) {
// Someone changed B-0841 since we read it; reload and show the person the new state
} else throw err;
}
Versioning the generated package
The Python package records the ontology revision it was generated from. On request, per-tenant packages carry their own semantic version, bumped from what changed in the ontology
Notebooks
Notebooks read through the client, so a notebook sees only what the person running it may see. The platform service works with marimo notebooks, plain .py files that run in the browser, headless, or export to HTML. A sample notebook shows the demo airline's aircraft by status, flights at risk, dispatch reliability by day against its target, flights at risk by origin, and the SQL behind the metric
marimo edit fleet.py # edit in the browser
python fleet.py # run headless
marimo export html fleet.py -o fleet.html
MSO_API_URL and MSO_TOKEN choose the service and the person. Notebooks hosted inside the platform, with scheduling and sharing, are delivered on request
Limitations
- A generated package contains only the types its generator could see. A colleague with wider access generates a wider package, and neither package grants access the server does not
- A query can follow at most 3 links. Derived properties are filtered by a scan after the index narrows the set, so they are slower than indexed filters
- Page tokens do not pin a snapshot, so a long walk can see objects that changed while it ran. On request they pin a snapshot and expire after 60 minutes
- Action applies are never retried by the client, and two calls with the same parameters are two applies
- Live object set subscriptions follow one type or interface with filters;
followandderivesteps,$fuzzyand$inAreaare for queries