# Automations

Build an automation from your own code or an AI assistant, check its flow before you save it, try it on a record, switch it on, start it by hand and read its runs.

An automation is a flow of steps that starts on a trigger, such as a work item being created, a schedule, another system calling it or a person starting it by hand. Everything you build in plnnrly's automation builder can be built over the API too, with the same checks. Every request on this page is a real operation with its own page in the [reference](https://developers.plnnrly.com/en/docs/api/v2/), under **Automations**.

> **Warning:**
> Automations are in beta, in plnnrly and in the API. Until they leave beta, their operations may change without the usual deprecation period. The endpoints are there only while your organisation has the Automations feature; without it they answer `404` [endpoint-not-found](https://developers.plnnrly.com/en/docs/api/v2/guides/errors/#endpoint-not-found).

Replace anything in angle brackets. `<your-url>` is the address you sign in to plnnrly on, such as `acme.plnnrly.com`, or your organisation's own domain.

## How an automation is put together

- **A scope.** An automation belongs to the whole organisation, to every project or every customer, or to one project or customer. `context_type` is `null`, `project` or `customer`, and `context_id` names the one project or customer, or is `null` for all of them. Each scope has its own permissions and its own token option: **Organisation automations**, **Project automations** and **Customer automations**. See [API tokens](https://developers.plnnrly.com/en/docs/api/v2/guides/tokens/#resources).
- **An owner.** Whoever creates the automation becomes its owner, and its runs use the owner's permissions. When you save a flow, every step is checked for you and for the owner: a step either of you may not do is refused.
- **Versions.** The flow is saved as versions. Each save adds one, which becomes the version that runs; `current_version_id` names it. A version never changes once saved.
- **Switched off until you switch it on.** A new automation, a copy and a restored one are always off. Its trigger starts runs only after `actions/activate`.

## The flow format

A flow is a set of steps, `nodes`, and the lines between them, `edges`:

```json
{
  "nodes": [
    {"key": "6f1c2a9e-4b7d-4e2a-9c1b-0d3e5f7a8b90", "type": "trigger.record_created", "config": {"model": "work_item"}, "ui": {"x": 0, "y": 0}},
    {"key": "9d4f6b8a-3c5e-4a7b-9e1d-2f4a6c8e0b13", "type": "action.notify", "config": {"recipients": {"fields": ["assignee_id"]}, "title": "New: {{ record.title }}"}}
  ],
  "edges": [
    {"from": "6f1c2a9e-4b7d-4e2a-9c1b-0d3e5f7a8b90", "lane": "next", "to": "9d4f6b8a-3c5e-4a7b-9e1d-2f4a6c8e0b13"}
  ]
}
```

- **A step** has a `key` you choose, a UUID, a `type` from the step types, its settings in `config`, and optionally its position on the builder's canvas in `ui`. Leave `ui` out and plnnrly places the step for you; the builder lays the flow out again when it is opened.
- **Exactly one step is a trigger**, and every other step is reached by a line from it.
- **A line** leaves one step by a lane and leads to another. `next` follows an action or a trigger. A condition has `yes` and `no`. A split (`logic.paths`) has one lane per path, by the path's key, and `otherwise`. A loop (`logic.for_each`) has `each` for the steps it repeats and `after` for what follows once every item is done.
- **Lines that come together** in one step make it run once for each line that reaches it. A merge step (`logic.merge`) waits for the branches and runs once.
- **Data** goes into a setting as a tag: `{{ record.title }}` for the trigger's record, `{{ steps.<key>.<field> }}` for what an earlier step handed on, the trigger included, `{{ prev.<field> }}` for the step whose line led here, `{{ loop.item }}` inside a loop, `{{ vars.<name> }}` for a value set earlier, `{{ input.<name> }}` for what a person filled in when they started it, and `{{ context.<field> }}` for the project or customer of the automation, such as `{{ context.title }}`. A field that names a record keeps its own name, so the assignee of a work item is `{{ record.assignee_id }}` and their name `{{ record.assignee.name }}`. Which tags exist depends on where a step sits, such as the fields a webhook receives, so ask [inspect-step](#inspect-a-step) for the step's own list.
- A flow has at most 100 steps and 300 lines.

## Find the step types

`GET /automation-node-types` lists every step type. Each says its `kind` and its `lanes`. `available` says whether it fits a flow whose trigger has no record, such as a schedule: it is `false` for a step that works only on a record, such as "Add to timeline", which you can still use after a record trigger. Read one type for the schema of its settings. Its address is its type with `.` replaced by `-`:

```bash
curl "https://<your-url>/api/v2/automation-node-types/action-notify" \
  -H "Authorization: Bearer <token>" \
  -H "Accept: application/json"
```

- `config_schema` is the JSON Schema of the step's settings, translated from the very checks saving a flow runs. A setting it does not list is refused.
- A setting marked `x-plnnrly-checked-on-save` depends on the step's other settings or on the data before the step, such as the fields of the trigger's record. Its `x-plnnrly-constraint` says what is checked. Inspect the step in its flow to see its choices there.
- A setting marked `x-plnnrly-record-reference` takes one record: a tag that holds it, or its key. The mark is the record type, such as `work_item`, once it is known; where the step's other settings decide it, [inspect-step](#inspect-a-step) names it after you filled them in.
- **People and teams** are chosen by id, one list per kind, as in `"recipients": {"principals": {"users": [12], "teams": [3]}}`. A person's id comes from `GET /users`, a team's from `GET /teams`. See [Find a team's id](#team-ids).
- A setting that holds values by name, such as the `path_params` of "Change records", is an object; `[]` stands for none.
- `secret_inputs` names the settings that take a secret, such as a token for another system. See [Secrets](#secrets).
- `outputs` says what the step hands to later steps.

## Find a team's id

`GET /teams` lists your organisation's teams by name, each with its `id`, its `name` and how many members it has. Search by name with `q`:

```bash
curl "https://<your-url>/api/v2/teams?q=Support" \
  -H "Authorization: Bearer <token>" \
  -H "Accept: application/json"
```

```jsonc
{
  "data": [
    {
      "id": 3,
      "name": "Support",
      "users_count": 4
      // 1 more field: links
      // with teams::read, 4 more: description, budget_group_ids, created_at, updated_at
    }
  ]
  // 2 more members: meta, links
}
```

- **Use the team's id** wherever a step or a template answer takes teams, such as `"recipients": {"principals": {"teams": [3]}}` or `"template_answers": {"teams": [3]}`.
- **Who may list teams.** Anyone who may create or change an automation, as in plnnrly's builder, or whose role has `teams::read`. A token narrowed to **Organisation automations**, **Project automations** or **Customer automations** reaches the list too.
- **What you see.** Without `teams::read` and a token that covers **Teams**, a team shows what the builder's team picker shows: its `id`, `name`, `users_count` and `links`. With both, it also has its `description`, `budget_group_ids`, `created_at` and `updated_at`.
- **Members.** Add `include=users` for the members, and `filter[users.id]=me` for your own teams. Both read people, so they also need `users::read` and a token that covers **Users**. `links.users` lists every member through `GET /users?filter[teams.id]=3`, which needs `users::read` and `teams::read`.
- Teams are kept up to date in plnnrly; the API does not change them.

## Worked example

This example builds "When an urgent work item is created, notify its assignee and note it on the work item's timeline".

### 1. Get a token

In plnnrly, open **API access** in the user menu and choose **Create token**. Tick **Write**, and pick **Organisation automations** and **Project workspace** under **Resources**, or leave it on **All resources**. Your role needs the `automations::create`, `automations::read` and `automations::update` permissions, plus `project_management::view_backlog`, because the flow reads work items. See [API tokens](https://developers.plnnrly.com/en/docs/api/v2/guides/tokens/).

### 2. Set up your script

```bash [curl]
export PLNNRLY_BASE_URL="https://<your-url>/api/v2"
export PLNNRLY_TOKEN="<token>"
```

```js [JavaScript]
const BASE_URL = process.env.PLNNRLY_BASE_URL
const TOKEN = process.env.PLNNRLY_TOKEN

async function api(method, path, body) {
  const response = await fetch(`${BASE_URL}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${TOKEN}`,
      Accept: 'application/json',
      ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  })

  const json = response.status === 204 ? null : await response.json()
  if (!response.ok) {
    throw new Error(`${response.status} ${json.type}: ${json.detail} (request ${json.request_id})`)
  }

  return json
}
```

```python [Python]
import os

import httpx

client = httpx.Client(
    base_url=os.environ["PLNNRLY_BASE_URL"],
    headers={"Authorization": f"Bearer {os.environ['PLNNRLY_TOKEN']}", "Accept": "application/json"},
    timeout=30.0,
)


def api(method, path, json=None):
    response = client.request(method, path, json=json)
    if response.is_error:
        problem = response.json()
        raise RuntimeError(f"{response.status_code} {problem['type']}: {problem['detail']} (request {problem['request_id']})")
    return response.json() if response.content else None
```

### 3. Create the automation

```bash [curl]
curl -X POST "$PLNNRLY_BASE_URL/automations" \
  -H "Authorization: Bearer $PLNNRLY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "Tell assignees about urgent work"}'
```

```js [JavaScript]
const { data: automation } = await api('POST', '/automations', { name: 'Tell assignees about urgent work' })
```

```python [Python]
automation = api("POST", "/automations", {"name": "Tell assignees about urgent work"})["data"]
```

The answer is `201`, with the automation switched off and no flow yet: `is_active` is `false` and `current_version_id` is `null`. Leave `context_type` out to make it for the whole organisation.

### 4. Read the step types you need

Read `trigger-record_created`, `condition-field_compare`, `action-notify` and `action-log_activity` at `GET /automation-node-types/{slug}`, as in [Find the step types](#step-types). Their `config_schema` tells you that the notification needs `recipients` and a `title`, and that the timeline step needs a `description`.

### 5. Build the flow and check it

Choose a key for every step, connect them, and check the flow before you save it. This first try leaves out the notification's title on purpose:

```bash [curl]
curl -X POST "$PLNNRLY_BASE_URL/automations/<automation-id>/actions/check-flow" \
  -H "Authorization: Bearer $PLNNRLY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "definition": {
      "nodes": [
        {"key": "6f1c2a9e-4b7d-4e2a-9c1b-0d3e5f7a8b90", "type": "trigger.record_created", "config": {"model": "work_item"}},
        {"key": "2b8e4d6f-1a3c-4e5b-8d7f-9a0c1e2b3d45", "type": "condition.field_compare", "config": {"match": "all", "rules": [{"data": "{{ record.priority }}", "operator": "in", "values": ["highest", "high"]}]}},
        {"key": "9d4f6b8a-3c5e-4a7b-9e1d-2f4a6c8e0b13", "type": "action.notify", "config": {"recipients": {"fields": ["assignee_id"]}, "link_record": true}},
        {"key": "4a6c8e0b-2d4f-4b8d-8f2b-6c8e0a2c4e57", "type": "action.log_activity", "config": {"description": "Told the assignee about this urgent work item."}}
      ],
      "edges": [
        {"from": "6f1c2a9e-4b7d-4e2a-9c1b-0d3e5f7a8b90", "lane": "next", "to": "2b8e4d6f-1a3c-4e5b-8d7f-9a0c1e2b3d45"},
        {"from": "2b8e4d6f-1a3c-4e5b-8d7f-9a0c1e2b3d45", "lane": "yes", "to": "9d4f6b8a-3c5e-4a7b-9e1d-2f4a6c8e0b13"},
        {"from": "9d4f6b8a-3c5e-4a7b-9e1d-2f4a6c8e0b13", "lane": "next", "to": "4a6c8e0b-2d4f-4b8d-8f2b-6c8e0a2c4e57"}
      ]
    }
  }'
```

```js [JavaScript]
const [trigger, urgent, notify, note] = [crypto.randomUUID(), crypto.randomUUID(), crypto.randomUUID(), crypto.randomUUID()]

const definition = {
  nodes: [
    { key: trigger, type: 'trigger.record_created', config: { model: 'work_item' } },
    { key: urgent, type: 'condition.field_compare', config: { match: 'all', rules: [{ data: '{{ record.priority }}', operator: 'in', values: ['highest', 'high'] }] } },
    { key: notify, type: 'action.notify', config: { recipients: { fields: ['assignee_id'] }, link_record: true } },
    { key: note, type: 'action.log_activity', config: { description: 'Told the assignee about this urgent work item.' } },
  ],
  edges: [
    { from: trigger, lane: 'next', to: urgent },
    { from: urgent, lane: 'yes', to: notify },
    { from: notify, lane: 'next', to: note },
  ],
}

const { data: check } = await api('POST', `/automations/${automation.id}/actions/check-flow`, { definition })
console.log(check.valid, check.problems)
```

```python [Python]
import uuid

trigger, urgent, notify, note = (str(uuid.uuid4()) for _ in range(4))

definition = {
    "nodes": [
        {"key": trigger, "type": "trigger.record_created", "config": {"model": "work_item"}},
        {"key": urgent, "type": "condition.field_compare", "config": {"match": "all", "rules": [{"data": "{{ record.priority }}", "operator": "in", "values": ["highest", "high"]}]}},
        {"key": notify, "type": "action.notify", "config": {"recipients": {"fields": ["assignee_id"]}, "link_record": True}},
        {"key": note, "type": "action.log_activity", "config": {"description": "Told the assignee about this urgent work item."}},
    ],
    "edges": [
        {"from": trigger, "lane": "next", "to": urgent},
        {"from": urgent, "lane": "yes", "to": notify},
        {"from": notify, "lane": "next", "to": note},
    ],
}

check = api("POST", f"/automations/{automation['id']}/actions/check-flow", {"definition": definition})["data"]
print(check["valid"], check["problems"])
```

The check saves nothing and answers `200`. It finds the missing title:

```json
{
  "data": {
    "valid": false,
    "checked_version": null,
    "problems": [
      {
        "kind": "setting",
        "message": "The title field is required.",
        "pointer": "/definition/nodes/2/config/title",
        "node_index": 2,
        "node_key": "9d4f6b8a-3c5e-4a7b-9e1d-2f4a6c8e0b13",
        "node_type": "action.notify",
        "edge_index": null,
        "setting": "title"
      }
    ],
    "attention": []
  }
}
```

Add `"title": "Urgent: {{ record.title }}"` to the notification's `config` and check again, until `valid` is `true`.

### 6. Save the flow

Save it as the first version, with `base_version` set to `0`:

```bash [curl]
curl -X POST "$PLNNRLY_BASE_URL/automations/<automation-id>/versions" \
  -H "Authorization: Bearer $PLNNRLY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"base_version": 0, "definition": <the definition from step 5, with the title>}'
```

```js [JavaScript]
definition.nodes[2].config.title = 'Urgent: {{ record.title }}'

const { data: version } = await api('POST', `/automations/${automation.id}/versions`, { base_version: 0, definition })
console.log(version.version, version.outline)
```

```python [Python]
definition["nodes"][2]["config"]["title"] = "Urgent: {{ record.title }}"

version = api("POST", f"/automations/{automation['id']}/versions", {"base_version": 0, "definition": definition})["data"]
print(version["version"], version["outline"])
```

The answer is `201` with version 1. Its `outline` lists the steps in the order people read the flow, each with a summary such as "Priority is one of Highest, High".

### 7. Try it out

Try the flow on a work item you may see before you switch it on. A dry run walks the flow as a run would, as you, and writes and sends nothing:

```bash [curl]
curl -X POST "$PLNNRLY_BASE_URL/automations/<automation-id>/actions/dry-run" \
  -H "Authorization: Bearer $PLNNRLY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"record_id": "<work-item-id>"}'
```

```js [JavaScript]
const { data: dryRun } = await api('POST', `/automations/${automation.id}/actions/dry-run`, { record_id: '<work-item-id>' })
console.log(dryRun.outcome, dryRun.steps.map((step) => step.headline))
```

```python [Python]
dry_run = api("POST", f"/automations/{automation['id']}/actions/dry-run", {"record_id": "<work-item-id>"})["data"]
print(dry_run["outcome"], [step["headline"] for step in dry_run["steps"]])
```

For an urgent work item the `outcome` is `completed`, and `steps` says what each step would do, such as who would get the notification. For one that is not urgent it is `stopped`: the condition did not hold, so the steps after it were left alone. `record_id` is a string, such as `"42"`, and a work item can be named by its issue key, such as `"ACM-12"`. Leave it out to use the example the builder's editors share.

### 8. Switch it on

```bash [curl]
curl -X POST "$PLNNRLY_BASE_URL/automations/<automation-id>/actions/activate" \
  -H "Authorization: Bearer $PLNNRLY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{}'
```

```js [JavaScript]
await api('POST', `/automations/${automation.id}/actions/activate`, {})
```

```python [Python]
api("POST", f"/automations/{automation['id']}/actions/activate", {})
```

From now on every new work item starts a run. Switch it off with `actions/deactivate`.

## Checking a flow

Saving a version runs exactly the checks the builder runs. A refused save is one `422` [validation-failed](https://developers.plnnrly.com/en/docs/api/v2/guides/errors/#validation-failed) listing every problem of every step, each at its JSON Pointer into your body, and nothing is saved. `check-flow` gives the same list without saving, as data.

| `kind`            | Error `code`         | What to do                                                                                                                                                                                     |
| ----------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `structure`       | `flow_structure`     | Fix the flow's shape: one trigger, lines between existing steps on lanes they have, no loose steps. A line from a way out its step lacks is refused at its `lane`, with the ways the step has. |
| `setting`         | `step_setting`       | Fix the setting the pointer names, as the step type's schema describes it.                                                                                                                     |
| `unknown_setting` | `prohibited`         | Remove the setting: the step type does not have it.                                                                                                                                            |
| `not_permitted`   | `step_not_permitted` | You, or the owner whose permissions runs use, may not do or read what the step does. Change the step or ask for the permission.                                                                |
| `unavailable`     | `step_unavailable`   | The step type, a record type or data is not available, for example because your organisation does not have the module.                                                                         |

A member the flow format does not have, such as a typo in a step's own keys, is refused with `prohibited` before anything else is checked.

### Inspect a step

The pattern that works best is "add the step with empty settings, then inspect it". `POST /automations/{automation}/actions/inspect-step` takes a `definition` and a `node_key` and answers with the step's settings schema where it sits, so a choice such as a field of the trigger's record is listed, and with `data`: every tag the step can use, ready to paste, as far as you may read it. Name records whose own data you want listed in `expand`, such as `record.project_id`.

## Changing a flow

- **Send the version you started from.** `base_version` is the version your change is based on. If the flow was saved again since, the save answers `409` [state-conflict](https://developers.plnnrly.com/en/docs/api/v2/guides/errors/#state-conflict) with `conflict.reason` `stale_version` and `conflict.current_version`: read that version, apply your change to it and save again. Two editors cannot overwrite each other this way, and a retried save cannot save twice.
- **Keep the steps you do not change.** Send `{"key": "<key>", "unchanged": true}` for a step to keep it exactly as `base_version` has it, and send in full only the steps you change. The lines are always sent in full.
- **Say when it is switched on.** Saving a new version of an automation that is on takes effect on its next trigger, so it answers `409` with `conflict.reason` `automation_active` unless you send `"while_active": true`.
- **Never echo a shortened step.** An AI assistant reading a long flow may get long texts cut short to fit its budget. Saving such a step back would save the shortened text: keep it with `unchanged` instead.

## Secrets and webhooks

- **A step's secrets are write-only.** Send a token or password in the setting the step type's `secret_inputs` names, such as `auth_value` of `action.http_request`. Saving stores it encrypted and keeps only its reference, in `auth_secret`; no read ever returns the secret. Send the reference without a value to keep the stored secret, or a value with it to replace it. Checking a flow never stores a secret.
- **A copy has no secrets.** Copying an automation with `actions/duplicate` never takes the original's secrets along. Switching the copy on answers `409` with `conflict.reason` `secret_missing` and `conflict.node_key` until the secret is entered again.
- **Type production credentials in plnnrly.** Anything you send through an AI assistant passes through the model's context, so enter real secrets in the builder.
- **The inbound address.** An automation whose trigger receives webhooks shows the address other systems send requests to in `webhook_url`. Requests prove they come from the right sender with the automation's secret. Depending on the trigger's settings, they send it as is in the `X-Automation-Secret` header, or sign with it: an HMAC-SHA256 of `<unix time>.<body>`, as lowercase hex, in `X-Automation-Signature`, with that Unix time in `X-Automation-Timestamp`, at most 300 seconds off. The API never returns the secret. `POST /automations/{automation}/actions/rotate-webhook-secret` sets a new one that you choose, at least 32 characters, and from then on requests with the old one are refused.

## Templates

`GET /automation-templates` lists plnnrly's template library with how often your organisation used each. Read one for its questions and whether you may use it at each level you may make automations at: the whole organisation, every project or customer, one project or customer. `forbidden` comes with the reason, such as a step the owner may not do.

To start from one, send `template_key`, and the answers by question name in `template_answers`, when you create the automation:

```json
{"name": "Escalate urgent work", "template_key": "escalate_urgent_unassigned", "template_answers": {"teams": [3]}}
```

A question that asks for teams takes team ids from `GET /teams`, as [Find a team's id](#team-ids) shows, and one that asks for people takes user ids from `GET /users`. The template's flow is saved as version 1 and the automation stays switched off. A template you may not use, a missing or wrong answer, or one the template does not ask, answers `422` at `/template_key` or `/template_answers/<name>`, and nothing is kept.

## Runs

- **Start one by hand.** `POST /automation-runs` with `automation_id` starts an automation whose trigger is started by hand, as you. Send `record_id`, as a string, when it runs on a record, and what it asks for in `inputs`, by name; the automation's `manual_inputs` lists them, and at most 20 are accepted. The answer is `201` with the run, usually `pending` until a worker picks it up. Send an `Idempotency-Key`, so a retry does not start a second run. An automation that is off answers `409` `not_runnable`, one that is not started by hand `409` `not_manual`.
- **Read runs.** `GET /automation-runs` lists the runs of the automations you may see, newest first; narrow it with `filter[automation_id]` and `filter[status][in]=failed,halted`. A run can also be read by the `uuid` a webhook's answer hands the sender. `GET /automation-runs/{run}/steps` says what each step did; add `view=detail` for each step's `input` and `output`.
- **What you see of a run.** A run shows what it worked with only to someone who may see its record, or, for a run without a record, who may change the automation. `reveals_data` says which. Without it `inputs`, `changes` and the steps' `input` and `output` are empty, and messages carry no record data.
- **Cancel a waiting run.** `POST /automation-runs/{run}/actions/cancel` stops a run that waits, such as at a Wait step. A run that is not waiting answers `409` `not_waiting`.

## From an AI assistant

plnnrly's MCP server reaches every operation on this page through `search_api`, `api_read` and `api_write`. Its instructions tell the assistant to create an automation switched off, read the step types it needs, inspect each step where it sits, check the flow and fix every problem before saving, and switch it on only after you agreed.

- Switching an automation on, starting a run and setting a new webhook secret need `confirm: true`, which an assistant sends only after you agreed. Deleting an automation needs it too, and only works while your organisation allows destructive actions.
- An assistant cannot change a switched-on automation without `while_active: true`, so ask it to say so first.
- Automations cannot change automations: no step of a flow can create, change or switch on an automation.

See [MCP](https://developers.plnnrly.com/en/docs/mcp/) to connect an assistant.
