Functions overview
Functions are versioned TypeScript or Python that read the Ontology and return typed results. You write one in TypeScript or Python against a client generated from your own object types, publish it under an ID, and call it from actions, derived properties, applications, agents, automations and the REST API. Every call runs with the caller's permissions
In the platform today
- Functions in TypeScript and Python run in the platform service with tests
- Python functions live in an ontology's
functions.py, registered with@function(description=…, inputs={…}, output=…), and read throughctxas the caller:get,query,linked,aggregate,call,member,userandnow() ctx.sql(text, params)is one SELECT, read as the caller reads the lake in the SQL workspace: only the schemassql.grantsgives them,objects.<type>filtered to their view, and a backing dataset under its type's row policy with hidden and sealed columns removed. It is refused as the workspace refuses (PERMISSION_DENIED.TABLE_GRANT_REQUIRED,NOT_FOUND.TABLE_NOT_FOUND)ctx.predict(model, rows, alias=…)returns a trained model's predictions, with rows checked against its input columns and every prediction loggedctx.file(id)andctx.file_info(id)return an attachment's bytes and metadata, for a file the caller may readctx.service_sql(text, params)is a service read for lookups, such as the next free document number, shown in the trace- TypeScript functions live in
functions.ts, declared withquery({ description, inputs, output, timeoutMs, memoryMB }, async (ctx, args) => …)from@marklandstreet/functions, and each call runs with the caller's permissions in a restricted process - Their limits are 5 s per call by default and 30 s at most, 128 MB of heap by default and 1 GB at most, 500 reads per call and calls nested 8 deep, set per implementation
- Both kinds are called the same way by actions, agents, automations, evaluations, the Assistant and
POST /api/v2/functions/{name}:invoke, which takes{"arguments": {…}}and returns{"function", "result", "ms"};GET /api/v2/functions/typescriptlists the TypeScript functions and their runtime functions.tsis type-checked with a pinned TypeScript compiler against types generated from the ontology and thectxAPI, when the ontology loads or reloads and onPOST /api/v2/functions/typescript:check; errors carry the line and column, and by default the last version that passed keeps running- A thrown
FunctionErrorreturns its message asFUNCTION_FAILED.USER_FACING_ERROR(422) - Each accepted content of
functions.tsis a version, set withexport const version = "1.4.0"or numbered automatically, and callers can pinname@1.2.0,@^1,@~1.2or@>=1.1 - Inputs can be interface-typed,
{ type: "object", interface: "cold-asset" }in TypeScript or{'type': 'object', 'interface': 'cold-asset'}in Python, and receive the object with interface property names plus_type,_keyand_title;ctx.member(interface, ref)reads one in either language
- Signatures read from types, the result cache, the egress allowlist, gVisor sandboxes for Python and higher limits
What a function is
Operations logic tends to end up in three places: spreadsheet formulas nobody can review, stored procedures in a system of record, and application code that each screen reimplements. Functions move that logic into one place that sits next to the model it reasons about. A function that computes how many hours of strawberry a shop has left is written once, tested once and released once. The operations view, the planning agent, the Saturday automation and a partner's integration all call the same version and get the same answer
A function has a signature (named, typed inputs and one typed output), a body, a version and an owner. The signature is extracted from your source code at publish time, stored in the Ontology registry as an immutable revision, and used to generate typed call sites in the Client SDK. Callers never pass untyped JSON blobs to a function. If a caller sends a Production batch where a Scoop shop is expected, the call fails before your code runs
There are four kinds of function. They share a runtime, a type system and a release process, and differ in what they are allowed to do
| Kind and example | What it may do | Typical use |
|---|---|---|
Query functionweekend_cover(shopId) | Read objects, links, time series and other functions. Never writes | Derived properties, screen widgets, agent tools, API endpoints |
Edit functionproduct_hold_edits(batch, hold) | Read, then return an edit set. Edits apply only when an action runs the function | Actions whose edits depend on logic too rich for declarative rules |
AI functionclassify-supplier-email(subject, body) | Call a language model through the model gateway with a typed prompt and a schema for the output | Classifying, extracting, drafting text, ranking options |
Model functionweekend-demand(shopId, sku) | Wrap a registered statistical or machine learning model with a typed signature | Forecasts, anomaly scores, equipment health |
Edit functions are covered in Edits from functions and AI functions in AI functions. The rest of this page applies to all four kinds
A function in TypeScript
TypeScript functions live in an ontology's functions.ts. Any exported constant created with query() becomes a function, with its signature in the definition, type-checked against the types generated from the ontology
import { query, FunctionError, type Shop } from "@marklandstreet/functions";
export const flavourStock = query({
description: "Tubs on hand by flavour for one shop",
inputs: { shop: { type: "string", objectType: "shop", required: true } },
output: "struct",
}, async (ctx, { shop }: { shop: Shop }) => {
if (shop.status === "Closed")
throw new FunctionError(`${shop.name} is closed for this period`);
const stops = await ctx.linked("shop", shop.shopId, "delivery-stop-shop");
return { onHand: shop.tubsOnHand, strawberry: shop.stkStr, inboundRuns: stops.length };
});
On request, functions live in a repository with their own dependencies, and the compiler reads the signature from the TypeScript types
A function in Python
Python functions live in an ontology's functions.py, registered with @function and its description, inputs and output, and read through ctx as the caller. The function below is the Python form of the TypeScript one above
from mso.registry import function
@function(description='Tubs on hand and inbound delivery stops for one shop',
inputs={'shop': 'string'}, output='struct')
def flavour_stock(ctx, shop):
s = ctx.get('shop', shop)
if not s:
raise ValueError(f'shop {shop} not found')
stops = ctx.linked('shop', s['shopId'], 'delivery-stop-shop')
return {'onHand': s.get('tubsOnHand'),
'strawberry': s.get('stkStr'),
'inboundRuns': len(stops)}
On request, Python functions take their signature from type annotations and dataclasses, with dependencies locked at publish time
TypeScript functions start in milliseconds and suit anything on a screen or in an agent's inner loop. Python functions start slower but bring NumPy, pandas, Polars, SciPy and your own models. A common split is TypeScript for derived properties and action logic, Python for forecasts, optimization and heavy aggregation
Types and the Ontology client
Every type in a signature maps to an Ontology type, so a function published from TypeScript can be called from Python and the reverse. Value types such as Temperature °C carry their constraints across the boundary: a function that declares a TemperatureC input rejects a value outside the value type's range before your code sees it
| Ontology type | TypeScript | Python |
|---|---|---|
| String, Boolean | string, boolean | str, bool |
| Integer, Long | number (checked integer), bigint | int |
| Double, Decimal | number, Decimal | float, decimal.Decimal |
| Date, Timestamp | LocalDate, Timestamp (UTC instant) | datetime.date, timezone-aware datetime |
| Value type | Branded type, e.g. TemperatureC | NewType, e.g. TemperatureC |
| Struct | interface or type alias | @dataclass or TypedDict |
| List, optional | T[], T | undefined | list[T], T | None |
| Object | Generated class, e.g. Shop | Generated class, e.g. Shop |
| Object set | ObjectSet<Shop> | ObjectSet[Shop] |
| Geopoint, time series, attachment | GeoPoint, TimeSeries, Attachment | GeoPoint, TimeSeries, Attachment |
| Edits (edit functions only) | Edits | Edits |
Reads are consistent and permissioned
The client inside a function is the same client the SDK generates, with two differences. First, every read in one call is pinned to a single snapshot of the object store taken when the call starts, so a function that reads a shop's stock and then its deliveries never sees one at 14:00:01 and the other at 14:00:03. Second, the client always reads as the caller. When a store manager calls weekend_cover for a shop outside their region, the row access policy on Scoop shop applies inside the function exactly as it would on the screen, and properties hidden from them by field access come back as unavailable rather than as values
That second rule means a function is never a way around access controls. In the platform service, ctx.sql reads with the caller's SQL grants, row policies and hidden properties too. ctx.service_sql is a service read for lookups, such as the next free number, shown in the call's trace. Publishing a function does not grant anyone access to the data it reads. To call a function, a person needs the Viewer role on the function's project; what the function can then see is limited by what that person can see
Prefer object sets to arrays
An object set is a description of objects, not the objects. Filtering, link traversal and aggregation on an object set are pushed down to the object query service and run against the index and the object store. Loading objects into an array and filtering in your code moves the data to the function instead, which is slower, costs memory and counts against the reads a call may make. Use arrays when you need to run logic that the query service cannot express, and only after narrowing the set as far as filters allow
The runtime
Today each TypeScript call runs in a restricted process with the caller's permissions. On request, TypeScript runs in V8 isolates and Python in gVisor sandboxes, with outbound calls limited to allowed hosts
Caching
On request, query functions cache results by version, arguments and the caller's access, cleared when an object they read changes
Where functions are called from
| Caller | How it calls | Identity used |
|---|---|---|
| Actions | A function rule runs an edit function and applies its edit set | The person applying the action |
| Derived properties | The object query service evaluates a query function per object, in batches of up to 1,000 | The person reading the objects |
| Applications | Generated SDK call or a widget bound to a function | The signed-in person |
| Agents | A function exposed as a tool | The person the agent acts on behalf of |
| Automations | An effect that runs a function on matching objects | The automation's owner |
| REST API | POST /functions/{function}:invoke | The OAuth client or user token |
POST /api/v2/functions/weekend_cover:invoke HTTP/1.1
Host: creamery.ontology.marklandstreet.com
Authorization: Bearer eyJhbGciOi…
Content-Type: application/json
{ "arguments": { "shopId": "SHP-BSL" } }
HTTP/1.1 200 OK
{ "function": "weekend_cover",
"result": { "shopId": "SHP-BSL", "level": "At risk",
"need": 34, "stock": 29, "arriving": 36, "short": 4,
"flavours": [
{ "key": "stkStr", "need": 5.4, "forecast": 3.0, "stock": 5, "short": 0, "…": "…" },
"…" ],
"…": "…" },
"ms": 83.8 }
A TypeScript function's version is pinned in the path, as flavourStock@^1.4:invoke. On request: version, cached and traceId in the response
Object inputs are passed by primary key over the API and loaded by the runtime at the caller's permissions. If the caller cannot see SHP-BSL, the response is a 404 with the same body as for a shop that does not exist, so a function cannot be used to probe for objects
Limits and errors
| TypeScript limit | Default | Highest |
|---|---|---|
| Time per call | 5 s | 30 s |
| V8 heap per call | 128 MB | 1 GB |
Reads through ctx per call | 500 | Set per implementation |
| Nested function call depth | 8 | 8 |
A definition can ask for more time or heap with timeoutMs and memoryMB, up to the highest values. All of these limits are set per implementation
A call that exceeds a limit fails with a typed error such as FUNCTION_TIMEOUT, MEMORY_LIMIT_EXCEEDED or FUNCTION_READ_LIMIT, and the trace shows how far it got. Exceptions you throw are reported to administrators with the stack trace and to end users as a generic failure. To show a specific message in a form or a screen, throw FunctionError (TypeScript) or, on request, raise FunctionError (Python). Its text is shown verbatim, so write it for the person reading it: "B-0841 has no QA results yet", not "qa_status was null"
A function that catches its own timeout and returns what it has will look correct to every caller and be silently wrong. Narrow the object set, raise the limit, or move the work to a pipeline that precomputes it as a property
Limitations
- Only edit functions produce edits, and only an action applies them. Query, AI and model functions never write
- A function always reads as its caller and cannot see more than that person or client can. Publishing a function grants no access to data
- Every read in a call is pinned to the snapshot taken when the call starts, so a function never sees changes committed while it runs
- TypeScript functions have no file or child process access. On request, functions have no network access until an Administrator allow-lists hosts for the project
- Do not rely on state between calls; anything to keep belongs in an object. On request, Python sandboxes are reset after each call
- A function that makes outbound calls is treated as non-deterministic, so its action is not retried automatically on a write conflict
- Only query functions can use the result cache. Edit functions are never cached