Open MercatoDocsSearch docsAPI reference

User guide

Workflow Activities

An activity performs work inside a workflow step. Choose the activity type, supply its inputs and decide how the following step uses its result.

For example, a step can send an email, update a record or call another service.

What Are Activities?

An activity is a discrete unit of work performed by the workflow engine. While steps define the structure of your workflow, activities define what actually happens at each stage.

Key Points:

Activity Types

Activity TypePurposeCommon Use Cases
SEND_EMAILSend email notificationsApproval requests, status updates, alerts
CALL_APICall this app's own /api/* endpointsRead or update Open Mercato records through the API
EMIT_EVENTPublish domain eventsTrigger other workflows, update dashboards, log actions
UPDATE_ENTITYModify records through a commandUpdate order status, mark tasks complete, change flags
CALL_WEBHOOKCall external HTTP endpointsIntegrate with Zapier, Slack, custom services
EXECUTE_FUNCTIONRun a registered workflow functionCustom business logic, complex transformations
SET_VARIABLEWrite values into workflow contextSet flags, compute defaults, stage data for later steps
WAITPause for a duration or until a timestampCool-off periods, scheduled follow-ups

⚠️ Calling third-party services: use CALL_WEBHOOK, not CALL_API. CALL_API targets this application only – it rejects any endpoint whose origin (scheme, host and port) differs from APP_URL (SSRF prevention).

Configuring Activities

Each activity type has a dedicated configuration form in the visual editor – for example SEND_EMAIL shows recipient, subject, and body fields, and EMIT_EVENT offers an event picker. The raw JSON editor is still available under the collapsed Advanced section of every activity for copy-pasting or fields the form doesn't cover.

Configurations are validated against each type's schema when you save. Problems appear as warnings in the editor – they don't block saving, so existing definitions keep working while you fix them.

SEND_EMAIL

Send email notifications with dynamic content from workflow context.

Configuration:

{
  "activityId": "send-approval-email",
  "activityName": "Send Approval Request Email",
  "activityType": "SEND_EMAIL",
  "config": {
    "to": "{{context.approverEmail}}",
    "subject": "Approval Required: {{context.requestTitle}}",
    "body": "A new request requires your approval.\n\nRequest: {{context.requestTitle}}\nAmount: ${{context.amount}}\nRequester: {{context.requesterName}}\n\nPlease review and approve or reject this request.",
    "template": "approval-request",
    "templateData": {
      "requestTitle": "{{context.requestTitle}}"
    }
  }
}

Parameters:

Only these fields are forwarded to the email service – cc / bcc are not supported.

CALL_API

Call one of the application's own API endpoints. (For third-party HTTP calls, use CALL_WEBHOOK – it is the one that goes off-instance and is SSRF-guarded.) The engine authenticates the request with a one-time API key that it creates and deletes around the call, so no credentials belong in the configuration.

Configuration:

{
  "activityId": "create-order",
  "activityName": "Create Sales Order",
  "activityType": "CALL_API",
  "config": {
    "endpoint": "/api/sales/orders",
    "method": "POST",
    "headers": {
      "Content-Type": "application/json"
    },
    "body": {
      "customerEntityId": "{{context.customer.id}}",
      "currencyCode": "{{context.cart.currency}}",
      "placedAt": "{{now}}"
    }
  },
  "async": true,
  "retryPolicy": {
    "maxAttempts": 3,
    "initialIntervalMs": 1000,
    "backoffCoefficient": 2,
    "maxIntervalMs": 10000
  }
}

Parameters:

Picking the Endpoint

You do not have to know the path by heart. The endpoint field opens a picker listing the application's documented API surface: browse or search by path, method, tag and summary, then pick one. The picker fills in the method, shows the endpoint's declared parameters as typed rows instead of a raw query string, and free text remains available for anything the catalogue does not cover.

When the chosen endpoint declares a response schema, that schema becomes the activity's output contract: the variable picker at every later step then offers the response's fields with real types instead of unknown. Endpoints without a declared response schema stay honestly untyped rather than guessing.

The picker is specific to CALL_API, because it browses this application's endpoints. CALL_WEBHOOK's URL is a free-text field – it points at somebody else's service.

⚠️ Internal endpoints only: relative paths are resolved against APP_URL and must start with /api/; an absolute URL must have the same origin (scheme, host and port) as APP_URL and a path under its /api/. Anything else fails with an SSRF-prevention error before the one-time API key is created. A redirect is followed only when its target passes the same check (at most three hops); any other redirect fails the activity. This includes redirects that an app behind a TLS-terminating proxy builds from its internal or http:// origin. To reach a third-party service, use CALL_WEBHOOK.

Response Handling:

When an activity runs asynchronously, its output is merged into the workflow context under <activityId>_result once the workflow resumes:

{
  "activities": {
    "create-order": {
      "output": {
        "id": "ord_123",
        "status": "draft"
      }
    }
  }
}

Access response data in subsequent steps: {{activities.create-order.output.id}}

EMIT_EVENT

Publish domain events to trigger other workflows or update application state.

Configuration:

{
  "activityId": "emit-order-placed",
  "activityName": "Emit Order Placed Event",
  "activityType": "EMIT_EVENT",
  "config": {
    "eventName": "order.placed",
    "payload": {
      "orderId": "{{context.orderId}}",
      "customerId": "{{context.customerId}}",
      "amount": "{{context.totalAmount}}",
      "items": "{{context.items}}"
    }
  }
}

Parameters:

The engine adds a _workflow block (instance id, workflow id, tenant, organization) to every payload it publishes. A configuration without eventName fails the activity with EMIT_EVENT requires "eventName" field.

UPDATE_ENTITY

Update records through a command, so the change keeps its audit log, undo support, and side effects.

Configuration:

{
  "activityId": "update-order-status",
  "activityName": "Mark Order as Shipped",
  "activityType": "UPDATE_ENTITY",
  "config": {
    "commandId": "sales.orders.update",
    "input": {
      "id": "{{context.orderId}}",
      "trackingNumber": "{{context.trackingNumber}}"
    }
  }
}

Parameters:

To set a status by its label instead of its id, name the dictionary and pass statusValue; the engine resolves it to statusEntryId before running the command:

{
  "config": {
    "commandId": "sales.orders.update",
    "statusDictionary": "sales.order_status",
    "input": {
      "id": "{{context.id}}",
      "statusValue": "pending_approval"
    }
  }
}

The activity runs as the workflow's user and fails when that user is missing or lacks the command's required features. Only commands registered as workflow-safe can be used – the sales module ships sales.orders.update, and a module adds its own with registerWorkflowSafeCommands().

CALL_WEBHOOK

Generic webhook calls for integrations with Zapier, Slack, or custom services.

Configuration:

{
  "activityId": "notify-slack",
  "activityName": "Post to Slack",
  "activityType": "CALL_WEBHOOK",
  "config": {
    "url": "{{env.SLACK_WEBHOOK_URL}}",
    "method": "POST",
    "body": {
      "text": "New order received: {{context.orderId}} for ${{context.totalAmount}}"
    }
  }
}

Parameters:

Requests to private or loopback addresses are blocked, and redirects are rejected rather than followed.

EXECUTE_FUNCTION

Run a function registered in the DI container under workflowFunction:<functionName>.

Configuration:

{
  "activityId": "calculate-discount",
  "activityName": "Calculate Volume Discount",
  "activityType": "EXECUTE_FUNCTION",
  "config": {
    "functionName": "calculateVolumeDiscount",
    "args": {
      "quantity": "{{context.quantity}}",
      "unitPrice": "{{context.unitPrice}}",
      "customerTier": "{{context.customerTier}}"
    }
  }
}

Parameters:

Function signature:

Registered functions receive three arguments: (args, context, signal?: AbortSignal). Existing two-argument functions are unaffected – the third parameter is additive and may be ignored. Functions that support cooperative cancellation can use it to abort long-running work when the activity's timeout fires:

container.register('workflowFunction:myFn', asValue(
  async (args, _context, signal?: AbortSignal) => {
    return await longRunningTask(args, { signal })
  }
))

SET_VARIABLE

Write values directly into workflow context. Each assignment lands at its dot path in top-level context (unlike other activities, whose output is namespaced under the activity name).

Configuration:

{
  "activityId": "stage-approval-data",
  "activityName": "Stage Approval Data",
  "activityType": "SET_VARIABLE",
  "config": {
    "assignments": [
      { "path": "approval.required", "value": true },
      { "path": "approval.threshold", "value": 10000 },
      { "path": "requesterName", "value": "{{context.customerName}}" }
    ]
  }
}

Parameters:

After this activity runs, later steps can read {{context.approval.required}} or use context.approval.threshold in transition conditions.

WAIT

Pause the workflow for a relative duration or until an absolute moment.

{
  "activityId": "cool-off",
  "activityName": "Wait Before Follow-up",
  "activityType": "WAIT",
  "config": {
    "duration": "PT5M"
  },
  "async": true
}

Parameters:

Provide duration or until – a WAIT activity with neither is rejected when the definition is saved. Prefer "async": true so the delay is scheduled on the queue instead of blocking the worker.

A synchronous WAIT longer than one minute that is the last activity of its transition is scheduled on the queue automatically, exactly as if it were marked async, so a wait of weeks or months (for example "P90D") holds the run for its full length. A synchronous WAIT longer than ~24.8 days that is followed by other activities is refused with an error rather than resolving early – move it to the end of the transition, mark it async, or use a WAIT_FOR_TIMER step.

Execution Modes

Synchronous (Default)

The workflow waits for the activity to complete before continuing.

{
  "async": false
}

Use When:

Asynchronous

The workflow continues immediately while the activity runs in the background on the queue.

{
  "async": true
}

Use When:

💡 Tip: Long-running API calls should be async to avoid blocking the workflow.

⚠️ Note: Not every activity type can run asynchronously. CALL_API is sync-only – marking it async is refused immediately with a clear error when the workflow tries to enqueue it, instead of failing later in the background worker.

Retry Policies

Configure automatic retries for activities that might fail temporarily (network errors, rate limits).

{
  "retryPolicy": {
    "maxAttempts": 3,
    "initialIntervalMs": 1000,
    "backoffCoefficient": 2,
    "maxIntervalMs": 10000
  }
}

Parameters:

The delay grows exponentially and is capped at maxIntervalMs – the example above waits about 1s, then 2s, before the activity finally fails. Without a retryPolicy an activity is attempted once. Every attempt is retried the same way; there is no per-error-type filter.

Variable Interpolation

Use {{variable}} syntax to inject workflow data into activity configurations.

Available Variables:

A token that stands alone in its value keeps the original type, so "{{context.items}}" passes an array rather than a string.

⚠️ Environment variables are allowlisted: only APP_URL resolves by default, and anything else returns an empty string. Add more keys with the OM_WORKFLOWS_ENV_INTERPOLATION_ALLOWLIST environment variable (comma-separated) before referencing them.

Example:

{
  "config": {
    "to": "{{context.customerEmail}}",
    "subject": "Order {{context.orderId}} Confirmation",
    "body": "Thank you for your order, {{context.customerName}}! Your order will arrive by {{context.estimatedDelivery}}."
  }
}

You do not have to type these paths by hand: template-capable fields carry a variable picker that lists exactly what is available at that step, with type badges and maybe markers for values that only exist on some paths. References to context nothing produces surface as warnings in the editor's Problems panel. To verify an activity's config against sample data without running the workflow, use the Test step panel – side-effecting activities are simulated, never executed.

Transform Pipelines

A token can pipe its value through one or more transforms before it is inserted, so you rarely need an extra step just to format something:

{{ context.order.total | number(2) }}
{{ context.customer.name | title }}
{{ context.order.placedAt | date('yyyy-MM-dd') }}
{{ context.customer.nickname | default('there') }}
{{ context.order.lines | pick(0) | pick('sku') }}
{{ context.order.reference | upper | prepend('#') }}

The grammar is deliberately small – a lookup path, then |-separated transform calls whose arguments are plain literals (quoted strings, numbers, true, false, null). There are no expressions and nothing is evaluated as code.

TransformArgumentsResult
dateoptional format string (yyyy, MM, dd, HH, mm, ss, SSS, in UTC)Formats a date value; with no argument, ISO-8601
numberoptional decimals, optional localeFixed decimals, or a locale-formatted number when a locale is given
upper / lower / titlenoneUpper-cases, lower-cases, or title-cases text
concatone stringAppends it
prependone stringPrepends it
defaultone valueSubstitutes it when the value is missing, null or empty
pickfield name or array indexReads one field out of an object, or one element out of an array

A token with no | behaves exactly as it always has.

Note · A pipe inside {{ }} is now a transform

Before transforms existed, a | inside {{ }} was part of the lookup path. If you have a definition whose context genuinely contains a key with a | in it, that token now parses as a transform pipeline instead.

Strict Interpolation

A definition can declare how it treats a token it cannot resolve, through definition.interpolation:

New workflows are created in strict mode; the toggle sits in the workflow's details panel. Existing definitions are never switched for you – updating an old definition keeps whatever mode it had.

Common Patterns

Send Approval Email on Transition

Configure an activity on the transition from an AUTOMATED step to a USER_TASK:

{
  "fromStepId": "start",
  "toStepId": "approve-request",
  "activities": [
    {
      "activityId": "notify-approver",
      "activityName": "Notify Approver",
      "activityType": "SEND_EMAIL",
      "config": {
        "to": "{{context.approverEmail}}",
        "subject": "Approval Required",
        "body": "Please review the request."
      }
    }
  ]
}

Call an Internal API and Use the Response

Call one of this app's endpoints asynchronously, then read the response in a later step:

{
  "activityId": "get-inventory",
  "activityName": "Check Inventory",
  "activityType": "CALL_API",
  "config": {
    "endpoint": "/api/inventory/levels?productId={{context.productId}}"
  },
  "async": true
}

Access the response: {{context.get-inventory_result.body.quantityAvailable}}

Update Record After Approval

Update a record through a command when a task is completed:

{
  "activityId": "mark-approved",
  "activityName": "Mark Request Approved",
  "activityType": "UPDATE_ENTITY",
  "config": {
    "commandId": "sales.orders.update",
    "statusDictionary": "sales.order_status",
    "input": {
      "id": "{{context.requestId}}",
      "statusValue": "approved"
    }
  }
}

Next Steps

See Also:

Previous: Custom Webhooks · Next: Creating Workflows