AstonDB v5 Contact us
Guide · for people who read contracts

The contract, explained for humans

Every AstonDB app has one contract: a TypeScript file that says what the app may do and what it asks to reach beyond itself. The gateway enforces it, so it is the one file you read to know what an app can change and call, which permits and secrets it needs from the admin, and which of its data and processes people's AI assistants may use. This guide walks through it part by part, in plain words.

For developers, tech leads and reviewersPackage @astondb/contractExamples from a leave-request app

01What a contract is

The contract is the only place where an app says what it is allowed to do: which data it has, who may read and change it, what the gateway does directly in the database and what it hands to a job, when jobs run and who may read files. It is also where the app asks for what lies beyond its own box: outside hosts, other apps, platform views, events of other apps, and the secrets it needs, by name.

It is written in TypeScript with @astondb/contract and has two outputs:

  • Types for the frontend and the server. The editor shows a mistake the moment it is typed, and a frontend that calls a missing operation does not compile.
  • contract.json for the gateway. This is what actually runs: the gateway reads it at deployment, checks it again, and enforces it on every request.
contract/src/index.ts
   ├─ tsc ──────────────────────▶ types for web/ and server/   (checks, emits nothing)
   └─ aston-contract extract ───▶ build/contract.json          (emits, checks nothing)

The author is treated as untrusted. App code may be written by an AI agent and nobody signs off a contract separately. Everything that matters for security (who may call what, which rows are visible, which values the gateway fills in, who may read files) is enforced by the gateway, not by the app's code.

Access itself is decided by the admin, who grants people the app's role and sub-roles. So is everything the contract asks beyond the app: a request opens nothing until the admin permits it, and a secret is only a name until the admin sets its value.

The frontend and the server never import each other. Both depend only on the contract.

02A contract at a glance

Here is the contract of a small leave-request app, shortened only where noted. On the right is how you would read it aloud.

export default contract({
  app: 'leave',
  roles: {
    manager: 'Approves leave requests of the team',
  },
  records: { request, teamRequest },
  ops: {
    myRequests: op.list(request, {
      owner: s.access,
      fields: ['id', 'from_date', 'to_date',
               'state', 'note'],
      where: { author: s.eq(s.session.email) },
      filter: ['state'],
      sort: ['-from_date'],
      limit: 100,
      mcp: 'My leave requests, newest first',
    }),
    submit: op.insert(request, {
      owner: s.access,
      input: ['from_date', 'to_date', 'note'],
      set: { author: s.session.email,
             state: 'new' },
      check: {
        to_date: s.gte(s.input('from_date')),
      },
      mcp: 'File a leave request for me',
    }),
    cancel: op.delete(request, {
      owner: s.access,
      where: { author: s.eq(s.session.email),
               state: s.eq('new') },
    }),
    teamRequests: op.list(teamRequest, {
      owner: s.role('manager'),
      fields: ['id', 'author', 'from_date',
               'to_date', 'state'],
      where: { manager: s.eq(s.session.email) },
      sort: ['from_date'],
      limit: 200,
      mcp: 'Leave requests of my team',
    }),
  },
  jobs: { review, reminder, exportRequests },
  buckets: { attachments: { read: s.access } },
  secrets: ['HR_OAUTH'],
  permits: {
    egress: ['hr.acme.example:443'],
    api: ['$view/myMembers'],
  },
})
Read aloud
  1. The app is leave. To open it at all, a person needs the role leave from the admin.
  2. There is one extra sub-role, manager. The admin sees its description when granting it.
  3. myRequests: anyone with access lists their own requests, newest first, at most 100. They may narrow the list by state.
  4. submit: anyone with access files a request. They send dates and a note; the gateway fills in who from the session and sets the state to new. A request that ends before it starts is refused.
  5. cancel: you may delete your own request while it is still new. Anybody else's request behaves as if it did not exist.
  6. teamRequests: managers list the requests of people they manage.
  7. Three jobs: review and exportRequests are called by managers, reminder runs on a schedule.
  8. The lines with mcp publish myRequests, submit, teamRequests and review to AI assistants: a person's assistant may use them, as that person. cancel has no such line, so no assistant can call it.
  9. Anyone with access may read files in attachments.
  10. The server needs one secret, HR_OAUTH, by name. The admin sets what it is.
  11. It asks to call hr.acme.example:443 and to read the people with a role in the app. Neither works until the admin permits it, and nothing else is reachable at all.

The records and jobs are declared above the contract() call in the same file:

export const request = record('request', {
  key: 'id',
  fields: {
    id: t.int(),
    author: t.email(),
    from_date: t.date(),
    to_date: t.date(),
    state: t.enum(['new', 'approved', 'rejected']),
    note: t.text().nullable(),
  },
})

// A view created by a migration: requests together with the employee's manager.
export const teamRequest = record('teamRequest', {
  table: 'v_team_requests',
  key: 'id',
  fields: { id: t.int(), author: t.email(), manager: t.email(), from_date: t.date(),
            to_date: t.date(), state: t.enum(['new', 'approved', 'rejected']) },
})

const review = job('review', {
  description: 'Manager approves or rejects a request',
  api: {
    owner: s.role('manager'),
    mcp: 'Approve or reject a request of my team by its id',
    input: t.object({ id: t.int(), approve: t.bool() }),
    output: t.object({ ok: t.bool(), state: t.enum(['approved', 'rejected']).optional() }),
  },
})
const reminder = job('reminder', {
  description: 'Morning reminder of waiting requests',
  cron: '0 8 * * 1-5',                       // 8:00 on workdays
})
const exportRequests = job('exportRequests', {
  api: { owner: s.role('manager'), input: t.object({ state: t.text() }), command: true },
})
SectionWhat it holds
appThe app's name: lowercase letters, digits and _. It must equal the name the admin created the app under, otherwise deployment is rejected. The address (host and path) is set by the admin, not here.
rolesSub-roles of the app, each with a description for the admin.
recordsThe data: tables or views in the app's own schema, with their key and field types.
opsOperations: create, read, update, delete and list, executed by the gateway with no app code.
jobsJob declarations: what starts them, including events of other apps, who may call them and with what. The code is on the server.
bucketsFile buckets and who may read them.
secretsThe names of the secrets the server needs. No values: the admin sets them. Optional.
permitsRequests to reach beyond the app: outside hosts in egress, jobs and operations of other apps, platform views and the person's token in api. A request opens nothing until the admin permits it. Optional.
flowsLong-running processes: their data, steps and the graph between them.

03Records: the data

A record describes one table or view in the app's schema: its name, its key and the type of each field. Tables are created by migrations (migrations/NNN_*.sql), not by the contract. At every deployment the gateway runs the new migrations and then compares the schema with the records; a mismatch rejects the build.

Field typeFits these PostgreSQL columns
t.int()int2, int4, int8
t.number()integers, numeric, float4, float8
t.text(), t.email(), t.enum([…])text, varchar, bpchar, citext, uuid
t.bool()bool
t.date()date
t.datetime()timestamptz
t.object({…}), t.array(…)json, jsonb
  • .nullable() means a nullable column. A required field over a column that allows nulls is a finding.
  • The table name has no schema. A record always lives in the app's schema, so a contract cannot name a platform table or another app's table. The prefix _aston_ is reserved for the platform.
  • A record may sit on a view that a migration creates over the app's own tables.
  • People are not in the app's database. The app's role sees nothing of the platform's tables. Names and roles of people come through a read-only platform view, $view, and only with a permit (see Permits).
  • Relations between tables are the app's business, written in its migrations. The platform does not model them.

04Operations: CRUD the gateway runs

An operation is a create, read, update, delete or list that the gateway performs without any app code. It lives at {app path}api/{name}, for example /leave/api/submit. The gateway fills in the conditions and values from the session and the input, turns them into parameterised SQL and runs it over the connection of the app's own database role.

KindMethodThe client sendsThe client gets
op.listGEToptional filter, limit, offsetrows
op.readGETthe keyone row, or 404
op.insertPOSTthe input fieldsthe new key
op.updatePOSTthe key and the input fields{ updated }
op.deletePOSTthe key{ deleted }

Who decides what

PartDecided byMeaning
ownercontractWho may call the operation (see Access).
fieldscontractWhich columns come back.
wherecontractThe row perimeter. The client never sees it and cannot bypass it. A row outside it behaves as missing: 404 on read, updated: 0 or deleted: 0 on writes.
filterclient, within the contract's listColumns the client may narrow by, with equality only. Nothing else can be added to the query.
sort, limitcontractOrder and maximum rows (1 to 1000). The client may ask for fewer rows and page with an offset.
inputclientColumns the client sends. They are validated against the record's types; an extra field is an error.
setgatewayValues the gateway fills in: a literal, or the caller's email or name from the session. The client may not send these columns.
checkcontractA condition the written row must meet, which may refer to the input. Failing it is 400.
mcpcontractOptional. A description for AI assistants that publishes the operation as their tool (see AI assistants). The browser and the web API ignore it.

What happens when the browser calls submit

  1. The browser posts { from_date, to_date, note } to /leave/api/submit. The session cookie goes along by itself; the client library adds the CSRF header.
  2. The gateway checks that the app is running, the session is valid, the person has the role leave and the operation's owner allows them.
  3. It validates the body against the JSON Schema derived from the record. A missing, extra or mistyped field is 400.
  4. It adds author from the session and state = 'new'.
  5. It inserts the row only if to_date ≥ from_date; otherwise 400.
  6. All values travel as SQL parameters, under the app's database role.
  7. It returns the new key and emits the table event request.create, so jobs subscribed to it start.

A write that needs code is a job, not an operation. Operations cannot be replaced or extended by code. When a write needs logic, such as "only a manager of this employee", the contract declares a job with a web API (see Jobs).

05Expressions

Conditions in where, check and the values in set come from a small, closed set of expressions. They are never an SQL string, so there is nothing to inject into. Values always go to PostgreSQL as parameters, cast to the column's type, and column names come only from the record.

ExpressionMeaning
{ col: s.eq(v) }, s.ne, s.gt, s.gte, s.lt, s.ltecomparison
s.in([…])one of a list
s.isNull(), s.isNull(false)is null, is not null
s.and(…), s.or(…), s.not(…)combination; several columns in one object also mean AND
s.session.email, s.session.namethe caller's e-mail or name from the session
s.input('field')a value from the input, only in check and set

The e-mail is the identity of the session. The name is read from the person's account in the platform on every request, together with their roles.

06Access: who may do what

  • Every app requires login. There is no public app, and not even a signed file link replaces the session; it is checked on top of it.
  • Access to the app is the role named after the app (leave). The admin grants it per app. The contract does not declare it.
  • The contract names only sub-roles (manager). They belong to this app alone and are stored as leave:manager, so a sub-role of one app never opens another.
  • owner is either s.access or s.role('a', 'b', …). With s.role, any one of the listed sub-roles is enough.
  • The rule is AND. A sub-role without access to the app allows nothing.
  • Being an admin gives no access to apps. An admin who wants to use an app needs its role like anybody else.
  • Rights are checked on entry. The gateway decides before any code runs. Inside the app a job may do anything with the app's data and files; outside the app, only what its permits allow (see Permits).
WhereFieldDecides
operationownerwho may call it
jobapi.ownerwho may call the job's web API
jobapi.asAppwhether another app with a permit may call the job on its own behalf, without a person
bucketreadwho may read files without a signed link (may also be s.signed)

Two named ways in without a person. When a job declares api.key: 'ERP_INBOUND', another system may call it with the header X-API-Key and no session. The key's name is one of the app's secrets (see Secrets): the admin sets the key in the app's detail, and until then such calls are 401.

When a job declares api.asApp: true, another app that has a permit for it may call it on its own behalf: without the person's roles and without the job's owner check. From the frontend and from AI assistants the job still takes only people who pass owner.

In both cases the run acts for the app, not for a person.

In the frontend, can(c, me, 'teamRequests') tells the page whether to show a button. It is a hint for the interface, not protection; the gateway checks again.

07Jobs: declarations

A job has two halves. The declaration in the contract says what starts it and, for a web API, who may call it with what. The body is code on the server (see the handler API guide). The gateway knows only the declaration and the names of the bodies. Jobs are the only way into app code.

FieldDefaultMeaning
description—Shown to the admin in the list of jobs.
api—A web API at POST {app path}api/{name}: owner, optional key, input, and either output or command. Optional mcp publishes it to AI assistants and readOnly: true says it only reads (see AI assistants). Optional asApp: true lets another app call it on its own behalf (see Permits).
cron—A five-field schedule: minute, hour, day of month, month, day of week.
events[]Table events such as request.create, request.update, request.delete. An event of another app is written with its name in front, leave:request.create, and is a request for a permit. An event of one of the app's own flows is written $flow:invoicing.finished and asks for nothing.
continue—The job takes the answer of an async call another job of the same app made; state is the shape of the context that job passed on. It excludes every other trigger and the queue settings (below).
maxConcurrency1How many queued runs of this job may run at once.
maxWaitCount-1What the queue does when the job is busy (below).

What starts a job

  • Web API (api): one surface for the frontend, for other systems and for other apps with a permit. The call is synchronous and does not wait in the queue; the default time limit is 60 seconds.
  • Schedule (cron): local time of the gateway. Day of month and day of week combine with AND. Missed runs are not caught up. An admin may run a cron job by hand; it then runs for the app, just as on schedule.
  • Table events (events): operations emit them by themselves; jobs emit them explicitly. The event name is the table, not the record. Events of another app arrive only with a permit.
  • Flow events (events): the platform announces what the app's own flows do — $flow:{name}.started, .advanced on every move and .finished when a run ends. The job gets the flow's name, the instance id and which of the three it was, nothing more. Only the app's own flows, so no permit; .advanced may be subscribed only with maxWaitCount: 1, because it fires per step per instance and must collapse into one run.
  • A continuation (continue): started only by the answer to an async call or fetch of another job of the same app (below). It runs outside the queue, so an answer is never dropped, and nothing from outside can reach it.

A job may have web API, schedule and events at once. A job with no trigger at all is rejected, and continue excludes the other three. Schedules and events have no input and cannot be started from outside; the only way in from outside is api.

The checks on a web API call

The gateway checks a call in this order and stops at the first failure:

CheckOn failure
the app is running503
the name is a job with api404
the method is POST405
a valid X-API-Key or a session401
the CSRF header, with a session403
access to the app and api.owner, with a session403
body up to 1 MB413
body matches api.input400 with the list of errors
the run itselfa JobError the job threw: the status it names, out of 400, 404, 409, 422, 429. Any other exception 500, time limit 504, runtime unavailable 502

A refusal the job means is not a failure of the gateway. The job throws a JobError with one of those five statuses, a sentence for the person and any JSON beside it, and the caller gets all three in the platform's usual error shape. The list is closed and the gateway holds it: 401 and 403 stay the platform's answers about who may call, and 5xx stays a statement about the platform. How a job raises one →

api.output is not a gate on this path. The gateway streams the answer to the caller as it comes and never holds the value to check it. The declared shape is a promise: it types the frontend's client and describes the tool for AI, and typecheck keeps the two sides together. It is enforced where a value enters another app, in a call through env.APPS.

api.owner says who may call, not what the job may do. A rule like "only requests of my team" is the job's own code. That is why the review body looks the request up in teamRequest with the manager's e-mail.

Answers the gateway builds: command

A job with api.command: true may return a command instead of data. The gateway runs it after the job and streams the result to the caller: a select as JSON, a CSV file, an Excel file with one sheet per select, or a file from a bucket. Large exports therefore never pass through the job, and the job's own time limit does not apply; the command has 5 minutes. Such a job declares no output.

Bytes the job makes itself

The same api.command: true also lets a job return a Response and stream its body to the caller: an export it assembles from several sources, a format it converts, the tokens of a model as they are written. The bytes do not pass through the platform's 1 MB answer envelope, and the run lasts until the last byte, so the database and calls outwards keep working while the stream flows. The job may set a 2xx status and the content type, disposition and length; an error status comes from a JobError thrown before the first byte, while there is still nothing on the wire to interrupt. In the browser the typed client hands the response over untouched with { raw: true }.

Answers that come later: the async call

Some answers do not fit inside one run — a model that writes for minutes, another app whose work takes an hour. A job can make such a call and finish without waiting: the answer of a run is still its return value, it is only allowed to be produced by a later run. The platform holds the wait, and when the answer arrives it starts the continuation job with it and with the state the first job passed on. The same call reaches outwards (a request to another system) and inwards (a job of another app). In the contract it costs one job with continue; the code is in the handler API guide.

  • The permits are the ones you already have. A call outwards runs under the same egress rules as the job's own fetch; a call into another app needs the same permits.api as a direct one, and the target must be a job with asApp, because a wait of hours carries no person. No new kind of permit exists, and no app gains the right to call back: the caller's context never leaves the caller, and the one who answers only returns a value, as every job does.
  • The called job may answer from a later run too. Its own answer may be another async call, so a chain forms — an app can check the credit, call the model, book what it cost and only then answer. Up to five links, shared with the chain of events. The value of the last link is checked against the output of the job that was called.
  • The called run waits in the queue, with its own maxConcurrency and a full queued run's time limit, so an app keeps control of what other apps can load onto it. A continuation runs outside the queue.
  • Every wait ends. timeout is an hour by default and twelve at most; a timeout, a failure or a refusal arrive as an error the continuation handles. At most a hundred calls and a hundred fetches may be waiting per app. For waiting that lasts days, or on a person, there is a flow.

The queue

Scheduled, event, manual and re-runs go through a queue in the gateway. Web API calls do not.

maxWaitCountWhen the job is busy
-1Unlimited queue; the new run always waits its turn.
0No waiting; the new run is dropped.
1"Dirty flag": after the current run, exactly one more run follows.
2 and moreQueue limit; beyond it the new run is dropped.

The queue lives in memory. A restart of the gateway loses runs that were waiting, and nothing else.

Telling the page that work is done

Work moved off the web call ends somewhere the browser cannot see. Any run may therefore send a short message to a named person with env.PUSH, and every page of that app they have open picks it up with $subscribe. The contract declares nothing for it and no permit is involved, because the message reaches only this app and only the person the app named. Delivery is not promised, so what matters is in the database and the message is a nudge to reload (see the handler API guide).

08Files and buckets

An app keeps files in buckets. Every bucket must say who may read it without a signed link:

buckets: {
  attachments: { read: s.access },          // anyone with access to the app
  contracts:   { read: s.role('manager') },  // a sub-role
  signatures:  { read: s.signed },           // nobody, except with a signed link
}
  • From outside, writing is possible only through a signed link that a job issues, and deleting is not possible at all. The job decides who may upload what, and sets the link's lifetime and limits.
  • Inside the app, jobs may do everything in every bucket of the app: read, write, list, delete and sign.
  • A file id is bucket/key. The app stores ids in its own columns. Nothing deletes orphaned files automatically.
  • The platform does not check where an id came from. If a job passes on an id it got from a user, it should first check that the file belongs to that user.
  • A file can travel to another app as a share link. A job signs one for a single file with a lifetime of up to 24 hours and passes it, for example, in a call to the other app, whose job reads the file with it. Whether the file may leave is decided by the job that signs the link.

09Permits: what an app may reach beyond itself

An app without a permit lives in its own box: its schema, its buckets, events, flows and schedules, with no fetch out, no other app and no platform data. The contract asks for a permit, the admin gives it by name, and only the permit counts.

export default contract({
  app: 'reports',
  secrets: ['CRM_URL'],
  permits: {
    egress: ['api.acme.example:443', { secret: 'CRM_URL' }],
    api: ['erp/orderStatus', 'wiki/importPages', '$view/myMembers', '$idp/accessToken'],
  },
  jobs: {
    digest: job('digest', { events: ['leave:request.create'] }),   // another app's event
  },
  // …
})
PermitAsked asOpens
egresspermits.egress: 'host:port' or { secret: NAME }fetch to that host and port
apipermits.api: '{app}/{name}'a call to one job or operation of another app through env.APPS
api on a viewpermits.api: '$view/{view}'reading a platform view: users, apps, allMembers, myMembers or runUser
api on the person's tokenpermits.api: '$idp/accessToken'the signed-in person's access token from the company login
eventa job's events: '{app}:{table}.{op}'receiving another app's table event
  • Asking opens nothing, and never blocks a deploy. The build goes live, and what has no permit stays shut: fetch and calls get 403, a foreign event does not arrive. The admin sees every request in the app's detail as permitted, denied or undecided.
  • A permit belongs to the app, not to the build. It survives deploys and rollbacks and changes without either. Revoking or denying applies from the next request, call or event.
  • A permit names one thing. There are no wildcards. { secret: 'CRM_URL' } asks for the host in that secret's value, so test and production can differ; the permit itself is still the concrete host:port, and a changed value shows up as a new request.
  • Some rules hold even with a permit: internal addresses are never reachable; no CONNECT or protocol upgrade; no Authorization header over plain http://; at most 1,000 outgoing calls per run, counted together with calls to other apps.
  • The permit is checked before the target is looked up. Without one, an app cannot even find out what another app contains.

Calling another app: as the person, or as the app

The permit says who may call. How the call runs is decided by the target, because only its author knows whether its code can do without a person.

TargetRunsThe target checksMay call it
any operation, a job without asAppas the signed-in persontheir role and owner, exactly as from its own frontend; an operation also applies its where, set and checka run with a person
a job with api.asApp: trueas the calling appnothing more: the permit is the authorisation, like an API keyany run of the calling app, also a schedule
// contract of the app wiki, the target
const importPages = job('importPages', {
  api: { owner: s.role('editor'), input: …, asApp: true },
})
  • A call as the person needs a permit even when the person has roles in both apps. Otherwise the code of any app could act for everybody who opens it, in every app where they have roles.
  • The admin sees what asApp skips. The permit is marked as app together with the owner it bypasses, and the target's detail lists every app that can reach it.
  • Calls go one level deep. A job called from another app does not call further apps, so calls alone cannot form a loop.

People, and the person's own token

  • An app reads no platform table. People and apps come from fixed, read-only views, read on the app's behalf: users (e-mail and name), apps, allMembers (people with roles in any app), myMembers (people with a role in this app) and runUser (the person of the run, with the identifiers from the company login). Each is a permit of its own.
  • $idp/accessToken lets a job act in another system in the person's name. It gets the access token that the company login issued to the signed-in person, so the other system allows only what that person may do there, and the audit shows the person, not the app. Only runs started by a signed-in person get it, in the browser or through their AI assistant, and only while that login lasts. The company login has to be set up for it.

Events of other apps

  • A job subscribes as to its own event, with the app in front: leave:request.create. That subscription is the request; there is no second entry in permits.
  • The run acts for the app and gets only the key. To read the row, the app asks for an api permit on a job or operation of the source app.

Admin apps are never a target. An admin app administers the platform and is uploaded and used only by admins. No permit lets another app call it or receive its events. It gets its own permits only from a human admin, like any other app.

The whole story, from request to revocation, is walked through on one app in Permits and secrets, step by step.

10Secrets: names in the contract, values with the admin

A secret in a committed contract would stay in the repository's history forever, and the admin reads contract.json. So the contract carries only names: the list secrets and the names of incoming API keys in api.key. Values live in the platform's encrypted store, and the admin sets the source of every name.

secrets: ['CRM_URL', 'CRM_TOKEN', 'ERP_BASIC', 'MAIL_OAUTH'],
NameSource the admin setsThe code gets
ends with _OAUTHan OAuth clientenv.OAUTH.token('MAIL_OAUTH'): an access token the gateway obtains, never the client secret
from a job's api.keyan incoming API keynothing: the gateway checks X-API-Key before the run
any othera plain value, a secret, or a login and passwordenv.SECRETS.CRM_TOKEN: the value, decrypted for the run; for a login, the ready base64(user:password)
  • The admin picks a source for every name: a value for this app alone, or a pair to a shared entry that several apps use. A shared entry rotates for all of them at once.
  • A name without a source gives the app nothing: undefined in env.SECRETS, an error from env.OAUTH.token, 401 for every caller with a key. Never somebody else's value.
  • Changes need no deploy. A new value or source applies from the next run, without a build or a restart. A deploy therefore does not check sources.
  • Types come from the contract. A typo such as env.SECRETS.CRM_TOKN is a type error, and env.OAUTH.token accepts only the _OAUTH names. The type helps the author; the boundary is that a run gets only its own app's names.
  • A secret is not a permit. Naming CRM_URL lets the app read the value; calling the host in it still needs an egress permit.

How a job uses them is in the handler API guide.

11Flows: long-running processes

A flow is a chain of steps with shared data (ctx) that survives restarts and waiting for other systems. In between, the process sleeps as a row in the database. The contract holds the whole definition: the data, the steps and the graph between them. The server holds only code: the bodies of the steps and the decisions.

Flows have no triggers of their own. A job starts one with env.FLOWS.start and wakes a waiting step with env.FLOWS.resume or reject. A running instance is a row in the same PostgreSQL, so it survives a restart of the server and needs no service beside it. The graph is walked by an engine inside the contract itself, and the code of a step runs as an ordinary short run in the app's runtime, like any job.

export const invoicing = flow('invoicing', {
  description: 'Checks credit, collects the payment, then invoices or cancels',
  ctx: { order_id: t.int(), amount: t.number(), credit_ok: t.bool().nullable(),
         payment_id: t.text().nullable(), invoice_id: t.int().nullable() },
  input: ['order_id', 'amount'],
  start: 'split',
  steps: {
    split:          fork({ branches: ['credit', 'payment'], catch: 'merge' }),
    checkCredit:    task(),
    collectPayment: asyncTask({ waitFor: '1h' }),
    merge:          join({ of: 'split', take: 'all' }),
    invoice:        task(),
    cancelOrder:    task(),
  },
  route: {
    split:          { credit: 'checkCredit', payment: 'collectPayment' },
    checkCredit:    { ok: 'merge' },
    collectPayment: { ok: 'merge', timeout: 'merge' },
    merge:          { ok: choose('afterChecks', ['invoice', 'cancelOrder']), error: 'cancelOrder' },
    invoice:        { ok: done(['invoice_id']), error: 'cancelOrder' },
    cancelOrder:    { ok: fail('REJECTED'), error: fail('CANCEL_FAILED') },
  },
})
creditpaymentokoktimeoutokinvoicecancelOrdererrorokokstartsplit · forkcheckCredittask()collectPaymentasyncTask · 1hmerge · joinchoose afterChecksinvoicetask()cancelOrdertask()done['invoice_id']fail'REJECTED'

The same flow drawn as a diagram. Error edges of the branch steps are added by catch; only one error edge is drawn here.

FieldDefaultMeaning
ctxrequiredThe data of one run: key → type. Nullable keys are optional.
inputrequiredThe ctx keys a job passes to start.
startrequiredThe first step.
stepsrequiredStep name → shape of the step.
routerequiredThe graph: step → edge → target.
maxSteps1000Moves per run; beyond it the run fails with MAX_STEPS.
ctxTable—A table of the app's own that the platform keeps up to date with the state of every instance (below).
description—For the admin.
StepWhat it doesEdges
task()Runs code and returns changes to ctx.ok, error
asyncTask({ waitFor })Sends a request, then waits for another system to answer through a job. After waitFor (like 30s, 15m, 1h, 3d) it gives up.ok, timeout, error
subFlow({ flow, waitFor })Runs another flow of the same app and waits for it.ok, timeout, error
fork({ branches, catch? })Splits the run into branches that wait in parallel.one per branch
join({ of, take })Joins the branches of a fork when take of them (a number or 'all') arrived successfully.ok, error
  • Targets are a step, an ending, or a decision. done(['invoice_id']) ends the run and returns the listed ctx keys; fail('REJECTED') ends it as failed with a code.
  • choose(name, candidates) is the only edge decided by code. The server's decision returns one of the declared candidates; the engine checks that it really is one, against the definition the run started with.
  • Every edge is spelled out. error is required on every step with a body, so a failure cannot get lost. Cycles are allowed; maxSteps guards against endless runs.
  • Branches wait in parallel, they do not compute in parallel. A fork makes sense when the process waits for several independent things at once.
  • Deploying a new version does not change running instances. Each run follows the definition it started with.

A table of your own: ctxTable

A screen that lists processes should not have to ask the platform for them one at a time. A flow may name a table in the app's own schema, and after every move the platform writes the state of the instance into it, together with those ctx keys that have a column there:

export const approval = flow('approval', {
  ctx: { request_id: t.int(), amount: t.number(), approved_by: t.email().nullable() },
  input: ['request_id', 'amount'],
  ctxTable: 'processes',        // a table in the app's own schema
  steps: { … },
})
  • The app owns the table and creates it in a migration, with the fixed columns instance, status, step, version, created_at and finished_at, plus a column for each ctx key it wants to have. There is no mapping to declare: a key with no column is skipped. A deployment checks that the table and the column types are there, and rejects the build if they are not.
  • One row per instance, kept current — a state, not a journal. From then on the app has plain SQL over its own processes: filters, counts and joins against its business data, with no cursor to keep and nothing to miss.
  • The platform never deletes the row, not even when the run is archived. When it stops being useful is the app's own business.

When a run ends

  • With a projected table, the app gets the final state first. A finished instance is archived only once its row there holds that state, so "the app knows how the process ended" is a property of the platform, not a race the app has to win.
  • The detail then leaves the database for the file storage: one object per instance with the definition it ran with and its whole chronicle, step by step. The header stays behind, so finished runs can still be listed and counted in SQL.
  • A job can read its own instances through env.FLOWS: a listing and counts of the running ones, the same pair over the archive, and one call for the detail that finds an instance wherever it is. An admin has the same as a screen, with the chronicle, the ctx after each step, and a button that cancels a run.
  • Other jobs can react. A job subscribed to $flow:approval.finished runs when an instance ends, and gets its id — no polling (see Jobs).

The flow's code and the env.FLOWS calls are described in the handler API guide.

12AI assistants: publishing over MCP

An app can publish its data and processes as tools for AI assistants. People connect an assistant that speaks MCP, such as Claude, GitHub Copilot, VS Code or opencode, once to one company address and sign in with their company account. From then on the assistant can use the published tools of every app they may open, as them and with their roles, to look things up and to get daily work done.

The contract decides what is published, with one field: mcp, a description of the tool written for the model.

ops: {
  myRequests: op.list(request, {
    owner: s.access,
    fields: ['id', 'from_date', 'to_date', 'state', 'note'],
    where: { author: s.eq(s.session.email) },
    filter: ['state'],
    limit: 100,
    mcp: 'My leave requests, newest first. Narrow by state: new, approved or rejected.',
  }),
}

// a job that only reads
const teamSummary = job('teamSummary', {
  description: 'Leave days of the team for a period',
  api: {
    owner: s.role('manager'),
    readOnly: true,
    mcp: 'Leave days of my team between from and to, one row per person',
    input: t.object({ from: t.date(), to: t.date() }),
    output: t.array(t.object({ email: t.email(), days: t.int() })),
  },
})

What becomes a tool

In the contractThe assistant canKind
op.list with mcpsearch and filter the rowsread
op.read with mcpread one record by its keyread
op.insert, op.update, op.delete with mcpwritewrite
a job with api.mcp and api.readOnly: truecall it and filter its outputread
a job with api.mcpcall itwrite
  • No mcp, no tool. An operation or a job without it never reaches an assistant, even though the person may call it from the browser. The author picks what AI may use, and the list stays short.
  • The description is the manual. The model chooses a tool and fills in its input from this text alone. Say what it returns, when to use it and what the inputs mean; it may be longer than the description for the admin. An empty string is a contract error.
  • Tools are named {app}.{name}, for example leave.myRequests. One connection covers the tools of all the person's apps.
  • Same rights as the browser. A tool shows up only when the person has the app's role and passes its owner, and the gateway checks both again on every call. An operation runs with the person's e-mail in the session; a job gets the person in run.user, exactly as from the frontend.
  • Nothing to reconnect. A new app, a new tool or a role taken away shows on the person's next question.

Jobs write unless they say otherwise

For an operation, the gateway knows whether it reads or writes. For a job it cannot know, so the contract says it: api.readOnly: true. Reads and writes reach the assistant as separate tools, so an assistant can run reads without asking and ask the person before a write.

  • The default is write. A forgotten readOnly means one more confirmation, never one less.
  • The gateway enforces the kind. A read tool cannot start a job that is not marked readOnly.
  • readOnly does not limit the job's code. Inside the app a job may still do anything; the flag only decides which tool it is called through. Mark only jobs that truly just read.

What the assistant gets back

  • The gateway decides how much leaves, as for the frontend: at most the operation's limit, at most 1 MB of job output.
  • The MCP service trims it for the model. It searches without regard to accents and case, filters by field type, and returns counts and value overviews instead of a wall of rows. It never widens what the gateway handed over.
  • Files do not go to AI. A job whose command returns an Excel file or a file from a bucket ends with an error over MCP; JSON and CSV answers go through up to 256 KB; a larger one comes back as a summary of its size.
  • Only on the production gateway. In local development and in tests there is no MCP. Published tools are ordinary operations and jobs and are tested as such.

An assistant gets the same access as its person, and that is the point. Text stored in the app's data reaches the model too and could try to steer it. AstonDB does not filter for that. Publish what a person would let their own assistant read and change, and keep writes as writes.

13contract.json and its hash

aston-contract extract turns the TypeScript contract into contract.json:

  1. It bundles the contract. A contract may import only @astondb/contract and files inside contract/.
  2. It runs the bundle in a separate Node process with no permissions: no files, no network, no environment.
  3. It runs it twice and requires identical output, so the result is stable.
  4. It writes canonical JSON with sorted keys and prints its SHA-256.

The gateway computes the same hash at deployment and stores it with the build. The admin shows it, so you can always see which contract is running.

"ops": { "submit": { "kind": "insert", "record": "request", "owner": { "access": true },
                     "input": ["from_date", "to_date", "note"],
                     "set": { "author": { "$session": "email" }, "state": "new" },
                     "check": { "to_date": { "gte": { "$input": "from_date" } } } } }

The gateway reads contract.json strictly: an unknown key is a finding. Because the file could also be written by hand, the gateway repeats every security-relevant check itself at deployment and does not rely on the TypeScript step having run.

14What gets rejected, and when

contract({…}) checks itself when it runs and reports all findings at once. Among others it refuses:

  • an operation or a web job without owner, or one naming a sub-role that is not in roles;
  • a sub-role without a description;
  • a column that is not in the record, in fields, filter, sort, where, set or check;
  • a column both in set and in input, since the client must not send what the gateway fills in;
  • an update that changes the key, and a limit outside 1 to 1000;
  • a job that nothing starts, a schedule without five fields, an event outside {table}.{create|update|delete};
  • a continue next to another trigger or next to the queue settings, and a subscription to .advanced of a flow without maxWaitCount: 1;
  • a web job named like an operation, since both live at the same address;
  • s.signed anywhere except a bucket's read;
  • an empty mcp description, and an api.readOnly or api.asApp other than true;
  • a permits request of the wrong shape: an egress that is neither host:port nor { secret } with a name from secrets, an api that is neither {app}/{name}, a known $view nor $idp/accessToken, a request into the app itself, or the same request twice;
  • a secret name outside UPPER_SNAKE_CASE or listed twice, a name both in secrets and in an api.key, and an api.key ending in _OAUTH;
  • a flow whose graph is incomplete: missing edges, unknown targets, branches that overlap, or two flows projecting into one table;
  • validation that cannot be expressed as JSON Schema, because the gateway could not enforce it.
WhenWhat is checkedIf something is wrong
typecheckthe frontend and the server against the contract; the server registers exactly the contract's jobs and flowstype error in the editor
extracteverything contract() checksthe build stops
server buildthe server's job list against the contractthe build stops
deploymentapp name, shape of contract.json, schedules, JSON Schemas, a trial run of the worker, migrations, schema against the records and against the tables flows project intothe deployment is rejected with all findings and the old version keeps running
gateway startthe same checks over the stored buildthat one app stays down, the others run

What is never a finding: a request without a permit, a secret without a source, a target app that does not exist yet. All of these change without a deploy, so the admin sees them in the app's detail instead, with a reason when a request cannot work.

15Reviewing a contract an AI wrote

The gateway guarantees that an app cannot do more than its contract says. Whether the contract says the right thing is a question for a person. These are the questions worth asking, roughly in order of impact.

  1. Who gets in?Which sub-roles exist, and do their descriptions say plainly what they allow? Anything open to s.access is open to everyone with the app's role.
  2. Can people see other people's rows?For every list and read: is there a where tying the rows to the caller, or is everything in the table meant to be visible?
  3. Who is the author?Columns that say who did something should come from set and the session, never from input.
  4. Can people change what they shouldn't?For every update and delete: does where limit it to the caller's rows and to the right states, like "only while new"?
  5. Are the business rules in check?Conditions such as "end after start" belong to the gateway, not only to the form.
  6. What do web jobs open up?For every job with api: who is the owner, and does the job's code check row-level rules itself? The owner says only who may call.
  7. What may AI assistants use?Every operation and job with mcp is a tool for every person who may call it. Is each one meant for that, does its description say truthfully what it does, and is readOnly only on jobs that really just read?
  8. Which machines may call in?Every api.key is a door without a person behind it. Is each one needed, and is its input narrow?
  9. What runs on its own?Schedules and events run without a person. What do they change?
  10. Who may read files?Is s.access right for every bucket, or should some be limited to a sub-role or to signed links?
  11. What does it ask to reach?Every host in permits.egress is a place data may go, every {app}/{name} a door into another app, every foreign event a stream of keys from it. Is each one expected? These are the rows the admin will decide.
  12. Which of its jobs may other apps call as the app?Every api.asApp skips the job's owner for callers from permitted apps. Should the code still check run.trigger.app or run.trigger.user?
  13. Does it want to act as the person elsewhere?$idp/accessToken lets the app work in other systems in the person's name. Is that the point of the app, and which jobs use it?
  14. Which secrets does it name?Each name in secrets and api.key is a credential the admin will have to set. Is nothing secret written into the code itself?