OpenCore MES Try the demo

Docs Integration 5

Reference

On this page
The ERP connection's Allowed requests: POST /confirmations and GET /orders
A connection's Allowed requests: the only calls a service may send that system.
The ERP connection's Allowed requests: POST /confirmations and GET /ordersA connection's Allowed requests: the only calls a service may send that system.

5.1 Connection

KeyWhatRules
nameits namelower case letters, digits and _
labelwhat people readrequired
baseUrlthe system's addresshttp:// or https://; no user, password, query or fragment
auth.kindhow it authenticatesnone, bearer, header, basic. bearer: Authorization: Bearer <secret>; basic: the secret is user:password, sent base64; header: the secret in the header auth.header (not host, cookie, content-length, transfer-encoding, connection)
auth.secretthe secret's namelower case, digits, _; its value is MES_SECRET_<NAME> on the server
allowthe only requests services may sendeach { "method", "path" }: GET, POST, PUT, PATCH, DELETE; a path starts with /, a trailing * allows what follows (/orders/*), nothing else is a pattern
timeoutMshow long a request may take100 to 30 000; 5 000 when left out
stewardsthe departments that answer for itat least one; they approve every service that starts using it

5.2 Service

KeyWhatRules
nameits name; its script has the samelower case letters, digits and _
inputwhat a caller sends, typed like fieldstypes string, text, integer, decimal, boolean, date, enum, ref, image, file; required; an enum's values; a ref's to. Text is at most 2 000 characters (or the input's max); a date is YYYY-MM-DD; a ref is a record id
http.enableda web servicePOST /svc/v1/<name>
callerswho may call it{ "users": [], "groups": [] }: nobody until named
onits triggers{ "object", "event" } with create, update, archive, restore or transition:<action>; or a schedule (5.6)
runAswho it acts asservice, caller, actor or a user id (3.3); triggers and schedules need service or a user
rolesits service role{ "<object>": ["<role>"] }, roles the object declares; it needs one on every object it reaches
uses.objectswhat it may do to records{ "<object>": [ops] }, ops of read, create, update, action, archive (archive is archiving and restoring)
uses.transactionsthe transactions it may run["<transaction>"]; run as its own service role, each transaction's callers.services names it too, and its stewards approve. Not a signed transaction
uses.connectionsthe connections it may callpublished connections, or ones in the same change
runOnkeeps its triggers and scheduled runs to nodes with this taglower case letters, digits, _ and -
stewardsthe departments that answer for itat least one

5.3 The script contract

One file, one function of the service's name, context in, context out. Nothing else in the file: no import, no other statement. The new script the designer makes:

// What this service does, in one line.
// ctx.input: what the caller sent · ctx.event: the record event, or { kind: "schedule", scheduledAt, previous } · ctx.user: who it acts as
// ctx.records.get/list/create/update/action/archive/restore(object, …): as ctx.user, through policy and the rule pipe
// ctx.http(connection, { method, path, query, body }) → { status, ok, body }: only what the connection allows
// ctx.transactions.run(name, input, { key }) → { run, changes, records, then? }: a transaction it may run (uses.transactions), all or nothing
// ctx.peers.run(peer, name, input, { key }) / .preview(peer, transaction, input) / .read(peer, query, params): what another OpenCore MES publishes (a peer connection it may use)
export default async function my_service(ctx) {
  // throw Object.assign(new Error("Say what is wrong."), { field: "some_input" });
  ctx.output = { ok: true };
  return ctx;
}
ctxWhat
ctx.inputwhat the caller sent, checked against the input; empty for a trigger or a schedule
ctx.eventa trigger's { kind, object, id, by } (kind is the event, "transition:release"); a schedule's { kind: "schedule", scheduledAt, previous: { at, output }, page }; null for a call
ctx.userwho it acts as: { id, name, onBehalfOf }
ctx.nowthe time it started (ISO); use it, not the system clock
ctx.serviceits name
ctx.outputwhat the caller gets back (a web service answers { output }); a scheduled run's is kept for the next (its cursor)
ctx.records.get(object, id)a record, or null; needs read
ctx.records.list(object, where)records whose fields equal where's values; needs read. Found in the database among every record in use its identity may read, the 200 changed last of them; a field it may not read is never filtered on. Without where: the 200 changed last
ctx.records.create(object, data)a new record; needs create
ctx.records.update(object, id, data)changed fields; needs update
ctx.records.action(object, id, action)a transition (release); needs action
ctx.records.archive / restore(object, id)needs archive
ctx.http(connection, { method, path, query, body })a request; answers { status, ok, body } whatever the status (the script decides what a 404 means)
ctx.transactions.run(name, input, { key })a transaction its design lists in uses.transactions, run as ctx.user: its callers (the service in callers.services, when it runs as its own role), its checks, its steps through each object's policies and rule pipe, all or nothing; answers { run, changes, records }. A refusal throws with the transaction's words and fields. key (at most 60 characters: the lot's number, the event's id) makes a retried run answer the first. A transaction a person signs is never run by a service. In a dry run it is planned, not run

Every record call goes through the object's policies and rule pipe as ctx.user, is audited, and seals the record. Write records only this way: one written straight in the database (an import by SQL, a fix by hand) is found by the data integrity review, with the database user it came from, and stays a finding until someone closes it with a signed non-conformance report. A refused write throws with the object's own words. About ctx.http:

  • The path is relative to the connection's base URL, starts with /, has no .., //, ?, # or backslash; parameters go in query.
  • The body is sent as JSON (not with GET); the answer is parsed when it says it is JSON. Answers over 1 MB are refused.
  • Redirects are never followed. The connection's credential is added on the server; the script never sees it.
  • An unreachable system or a timeout throws a fault that asks for a retry.

5.4 Refusals, faults and retries

The script…It isA caller getsA trigger's run is
throws new Error("words"), optionally with field or fieldsa refusal422 with the words and fieldsrejected: retrying would say the same
has a record write refused (policy, rule pipe, state)a refusal422 (403, 404 or 409 as the records said)rejected
throws with { retry: true }, or a connection is unreachablethe other system is down502retry, with a growing wait, then dead
throws anything else (a TypeError, a call it may not make, a missing secret)a fault: a mistake in the design or script500 (the words go to the log, not the caller)retry, then dead
returns its contextdone200 { output }done

A trigger's run is claimed for 2 minutes (a node that dies mid-run leaves it to another), and retried after 2, 4, 8, … seconds (at most 5 minutes apart), up to 10 attempts; then it is dead, and the event log says so (trigger.dead). Send again on the service's Activity tab runs a retrying, dead or rejected one again.

5.5 Triggers: exactly once to enqueue, at least once to run

  • A record write that matches a trigger writes its outbox row in its own database transaction: a committed release always sets the trigger off, a rolled-back one never.
  • Every node's outbox worker claims due rows with FOR UPDATE SKIP LOCKED, ten at a time: several nodes share the work, none runs a row twice at once.
  • The service runs as its current published version, as its identity, after the event.
  • A service never sets itself off; a chain of services setting each other off stops at three.
  • Make the other side idempotent. A run may, rarely, reach it twice (a node dies after ERP answered). Send the event's id (ctx.event.id with the event kind) as the other system's key.
A service's Triggers tab: a schedule every 15 minutes
A service's triggers: on a record event, on a transaction's run, or on a schedule, here every 15 minutes.
A service's Triggers tab: a schedule every 15 minutesA service's triggers: on a record event, on a transaction's run, or on a schedule, here every 15 minutes.

5.6 Schedules

A schedule is a trigger the clock sets off: structured, not cron.

"on": [{
  "schedule": { "every": { "minutes": 15 }, "between": ["06:00", "22:00"],
                "days": ["mon", "tue", "wed", "thu", "fri"], "tz": "Europe/Berlin" },
  "missed": "last", "overlap": "skip"
}]
KeyValues
every{ "minutes": 1–720 } or { "hours": 1–24 }, counted from midnight
attimes of day, ["06:00", "14:00"]
betweennarrows every to a window; it may cross midnight
daysmon, tue, wed, thu, fri, sat, sun; all when left out
tzan IANA time zone; the plant's (PLANT_TZ) when left out. A time daylight saving skips runs once when it would have been; one that happens twice runs once
missednone, last, all (the default is last): runs that could not start within a minute of their time; all runs up to 100
overlapskip, queue (the default is skip: nothing is queued while a run is waiting or running)
frominstead of every, at, between and days: "<suite>.<kind>", a kind of schedule an installed suite adds, whose times the suite works out (a shift calendar it keeps, say), with the settings that kind names beside it ({ "from": "<suite>.<kind>", "<setting>": value, "tz": "…" }). The designer lists the kinds installed. With the suite removed the service stays published, nothing is planned for that schedule, and the monitor says which suite it needs

A run is planned once, however many nodes plan; a schedule seen for the first time is planned from then on. ctx.event.previous is the last successful run ({ at, output }), so a script keeps its cursor in its output. A run that answers output.more: true gets its next page at once (ctx.event.page), up to 100 pages. Pause, resume and Run now are operations in the monitor: audited, not design changes.

A sync by the clock: its connection allows GET /orders, and it reaches work_order with read, create and update.

// Every 15 minutes: the orders ERP changed since the last successful run, a page at a time.
export default async function erp_orders_pull(ctx) {
  const since = ctx.event.previous?.output?.cursor ?? "2026-01-01T00:00:00Z";
  const res = await ctx.http("erp", { method: "GET", path: "/orders", query: { changedSince: since } });
  if (res.status >= 500) throw Object.assign(new Error("ERP is unavailable"), { retry: true });
  if (!res.ok) throw new Error(`ERP refused the order list (${res.status})`);
  for (const order of res.body.orders) {
    const [known] = await ctx.records.list("work_order", { wo_no: order.wo_no });
    if (known) await ctx.records.update("work_order", known.id, { qty: order.qty });
    else await ctx.records.create("work_order", { wo_no: order.wo_no, item: order.item, qty: order.qty, line: order.line });
  }
  ctx.output = { cursor: res.body.until, more: res.body.hasMore === true };
  return ctx;
}

5.7 The web service API

CallPOST /svc/v1/<service>, Content-Type: application/json, the input as the body (at most 256 KB)
Run a transactionPOST /svc/v1/<transaction> (scope transaction:run), one its design publishes over HTTP: its inputs by name, a reference as its record's id or title; POST /svc/v1/<transaction>/preview says what it would change, writing nothing. Answers { "ok", "run", "transaction", "changes", "records", "then"? }: then where its design runs other transactions once it has committed, each ran, skipped (its condition did not hold) or refused (in words; the first run stays done)
Read a named queryGET /svc/v1/<query>?<parameter>=… (scope query:run, read only), one its design publishes over HTTP to named callers; offset, limit, sort, dir page it. Answers { "columns", "rows": [{ column: value }], "next" }
AuthenticateAuthorization: Bearer mes_…: a token with the scope service:call, transaction:run or query:run (node app/mes/db/token.mjs <user> "<name>" --scope …)
DescribeGET /svc/v1/openapi.json: OpenAPI 3.1, only what this token's user may call, as its scopes allow; it changes as changes execute
Against the test sandboxThe test sandbox (the shared pre-production copy: what is published and every change under test, on records made there) answers /svc/v1 on its own address (this server's port + 1000 unless TEST_SANDBOX_PORT or TEST_SANDBOX_URL says), the same way, before anything is approved. It takes a test token only (node app/mes/db/token.mjs <user> "<name>" --test --scope …, the web scopes only), and the live address never takes one: either is refused 401, token.elsewhere, saying where it belongs. A suite reaches outside from there only with its test secrets (MES_SECRET_<SUITE>_TEST_<NAME>)
Retry safelyIdempotency-Key: 8 to 100 characters. The same key from the same caller answers the first successful answer again, without running it
Answer{ "output": … }; refused: { "error", "fields"?, "code" }
StatusMeanscode
200done—
400bad input (each field named), or a body that is not JSONservice.input
401no token, or a token that is not valid; a test token at the live address, or a live one at the test sandbox'stoken.missing, token.elsewhere
403the token lacks service:call, or its user is not among the service's callersscope.missing, service.denied
404no such web service, transaction or query published over HTTP—
405the wrong method: a query is read (GET), a service or a transaction is called (POST); Allow says whichmethod
409the first request with this key still runs (ask again), or a record a transaction read changed meanwhile (run it again)idempotency.running, stale
413 · 415the body is over 256 KB · not application/json—
422refused by the script, a rule or a policy: its words, and the fieldsservice.rejected or the rule's
500 · 502the service failed · a system it depends on could not be reachedservice.fault
503busy, or the database out of reach: nothing changed; ask again after Retry-Afterdb.busy, db.unavailable

5.8 Limits

WhatLimit
A web service request body256 KB
An answer from a connection1 MB
A connection's timeout100 ms to 30 s (default 5 s)
A service run200 ms of CPU at a time, 15 s in all, 64 MB of memory; past them it is stopped and fails closed
A dry run5 s
Trigger attempts10, waiting 2, 4, 8, … s, at most 5 minutes
A chain of services3
Schedule catch-upup to 100 missed runs, from the last 7 days
Pages of a scheduled run100
ctx.records.listwith where, the 200 changed last of the matching records its identity may read, among all of them; without, the 200 changed last

5.9 Security

  • Scripts run apart. Every rule and service script runs in the script runner: a process of its own beside each web process, started with Node's permission model (it reads only the app's files, writes none, starts no process) and an empty environment, so it holds no database address, secret or key. Jobs run in worker threads with a memory limit; one past its deadline is terminated. A script reaches records and systems only through ctx.
  • No network from a script but ctx.http, through a connection's allow list. No fetch, no Math.random: the editor warns about both.
  • Secrets are set on the server (MES_SECRET_<NAME>), never in a design, a review, the copilot's context or the audit. Changing a value is operations; changing which secret a connection uses is a design change.
  • Tokens are shown once and kept as a hash; a designer revokes an AI token in AI access.
  • Public demos and sandboxes reach no outside system: a call is refused, saying so.

The operating system's walls are each installation's to turn on. What the product does everywhere stops at Node's walls and the script's context. On Linux, add the kernel's: install bubblewrap (apt-get install bubblewrap) and, on Ubuntu 23.10 and later, its AppArmor profile (install -m 0644 ops/script-runner-sandbox.apparmor /etc/apparmor.d/opencore-mes-bwrap && apparmor_parser -r /etc/apparmor.d/opencore-mes-bwrap: those versions refuse user namespaces without one, which is also why unshare -r -n fails there); then set SCRIPT_RUNNER_WRAP=ops/script-runner-sandbox.sh. The runner then has a network namespace with loopback only, a read-only file system of the libraries, Node and the app's code, and no capabilities.

Check it by what the runner finds. At start it reports whether it sees any network and the sandbox it is in: the start log says scripts: isolated (bwrap): no network, …, and /healthz shows "scripts": {"network": "none", "sandbox": "bwrap", …}. "network": "host" means the walls are not there (a production instance also writes scripts.unisolated to its event log). Once they hold, set SCRIPT_ISOLATION=required: the instance refuses to start without them.

Caution. Until SCRIPT_RUNNER_WRAP is set, and /healthz shows "network": "none", a script that found a way out of its context would have the host's network (though no credentials). Off Linux there is no wrapper.

5.10 Testing

  • As you type: the script is parsed in the browser (never run there); syntax errors are marked on their line anywhere; calls the script will not have are warned about.
  • Dry run: executed on the server as the service will run: real reads; writes through policy and the rule pipe, not saved; requests checked and answered from responses ({ "POST /confirmations": { status, body } }), never sent. A runtime error is marked on its line.
  • Test cases (Save as test case, or written): { name, run: { input } | { event, responses }, as?, expect: { ok?, output?, error?, writes?, requests? } }. A new or changed script without one, or with a failing one, fails the fitness test, which runs them all on submit.
  • End to end: app/mes/test/integration.mjs designs, approves and calls an ERP integration against a fake ERP (wrong caller, bad input, a rule's refusal, a retry by key, a confirmation while ERP is down); app/mes/test/scheduler.mjs proves the schedules. Both run in npm run test:all.
The integration monitor's Health tab: an instance's database, audit chain, integrity and the hours behind
The monitor's Health tab: each instance's database, audit chain, data integrity, event log and scripts' walls, now and over time.
The integration monitor's Health tab: an instance's database, audit chain, integrity and the hours behindThe monitor's Health tab: each instance's database, audit chain, data integrity, event log and scripts' walls, now and over time.

5.11 Running it: nodes, settings, the monitor

SettingWhat
MES_SECRET_<NAME>a connection's secret, on every node that runs its services
NODE_TAGS=erp,plant1this node's tags; a service with runOn: "erp" has its triggers and scheduled runs run only on nodes tagged erp (inside the network that reaches ERP). Calls from outside run wherever they arrive
SCHEDULER=0this node plans no schedules
OUTBOX=0this node runs no triggers or scheduled runs
PLANT_TZthe plant's time zone, for schedules that name none

Every node reports itself every 10 s. The integration monitor (/_design/integration) shows the nodes (and warns when none plans schedules or runs the outbox, or none has a service's tag), the schedules (next and last run, totals, queue; Pause, Resume, Run now), inbound calls and outbound requests of the last 24 hours, and the record triggers' queues. The event log has trigger.dead, schedule.missed, schedule.skipped, schedule.paused, schedule.resumed, schedule.suite_missing (a schedule from a suite that is not installed) and schedule.suite_failed (an installed suite could not give a schedule's times: nothing was planned for it then).