Webhooks, scripts & custom actions
Three Action types reach beyond the database:
| ActionType | What it does | Who writes it |
|---|---|---|
CallWebhook |
Calls an HTTP API: auth, a templated or SQL-shaped payload, retries, response → context mapping, optional write-back SQL. | Workflow author (XML / designer). |
Script |
Runs inline C# against the workflow context. | A user granted WorkflowScripts (off by default). |
| your key | Runs a host-registered IWorkflowActionHandler. |
Host developer (C#). |
All three get the same context, and they all hand values back the same way. Their outputs become
context variables, so later nodes can use them as @Var in SQL, as {{Var}} in templates and in
Decision expressions. They can also route the flow to a named outgoing transition.
Routing out of an Action node
Section titled “Routing out of an Action node”An Action node normally takes its first outgoing transition. A handler can name a different one,
by label or by target node key. CallWebhook does this through <OnError Transition="…">, and a
Script does it by returning the label. The default route always skips the error branch, even when that
branch is drawn first. A route that names no outgoing transition fails the transition, because it is an
authoring error.
CallWebhook
Section titled “CallWebhook”<Node Key="CreateShipment" Type="Action" Label="Create shipment"> <ActionConfig> <ActionType>CallWebhook</ActionType> <Payload> <CallWebhook Name="CourierCreateShipment" TimeoutSeconds="30">
<!-- 1. Auth: get a token from the auth link; cached until shortly before it expires --> <Auth Type="OAuth2" Grant="client_credentials" TokenUrl="https://auth.courier.com/oauth/token" ClientId="{{Secret:Courier.ClientId}}" ClientSecret="{{Secret:Courier.ClientSecret}}" Scope="shipments.write" />
<!-- 2. The main API call --> <Request Method="POST" Url="https://api.courier.com/v2/shipments?ref={{Record.OrderNo}}"> <Headers> <Header Name="Idempotency-Key" Value="{{Instance.Id}}-{{Node.Key}}" /> <Header Name="X-Tenant" Value="{{Session.CompanyId}}" /> </Headers> <!-- the body, shaped by SQL (one variant per dialect) --> <SqlPayload Format="Json"> <SqlServer><![CDATA[ SELECT o.OrderNo AS reference, c.Name AS [receiver.name], c.Phone AS [receiver.phone], (SELECT i.Sku AS sku, i.Qty AS qty FROM OrderItems i WHERE i.OrderId = o.Id FOR JSON PATH) AS items FROM Orders o JOIN Customers c ON c.Id = o.CustomerId WHERE o.Id = @RecordId FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ]]></SqlServer> <PostgreSql><![CDATA[ SELECT json_build_object( 'reference', o.order_no, 'receiver', json_build_object('name', c.name, 'phone', c.phone), 'items', (SELECT json_agg(json_build_object('sku', i.sku, 'qty', i.qty)) FROM order_items i WHERE i.order_id = o.id)) FROM orders o JOIN customers c ON c.id = o.customer_id WHERE o.id = @RecordId ]]></PostgreSql> </SqlPayload> </Request>
<!-- 3. Retries --> <Retry MaxAttempts="4" Backoff="Exponential" BaseDelayMs="500" OnStatus="408,429,500-599" RespectRetryAfter="true" />
<!-- 4. Response → context, then write back to the record --> <Response SuccessStatus="200-299"> <Map From="$.shipment.id" To="ShipmentId" /> <Map From="$.shipment.trackingNo" To="TrackingNo" /> <Map From="$.labels[0].url" To="LabelUrl" /> <Map From="$.carrier" To="Carrier" Default="courier" /> <Map From="$status" To="CourierHttpStatus" /> <WriteBack><![CDATA[ UPDATE Orders SET TrackingNo = @TrackingNo, ShipmentRef = @ShipmentId WHERE Id = @RecordId ]]></WriteBack> </Response>
<!-- 5. On failure: record the error and take the "ShipmentFailed" transition --> <OnError Transition="ShipmentFailed" MapErrorFrom="$.error.message" To="CourierError" /> </CallWebhook> </Payload> </ActionConfig></Node>Auth types (<Auth Type="…">)
Section titled “Auth types (<Auth Type="…">)”| Type | Attributes | Sends |
|---|---|---|
None |
— | nothing |
Basic |
UserName, Password |
Authorization: Basic base64(user:pass) |
Bearer |
Token |
Authorization: Bearer <Token> |
ApiKey |
Value; Name (default X-Api-Key); In="Header" (default) or "Query" |
the key as a header or a query parameter |
OAuth2 |
TokenUrl, ClientId; ClientSecret; Grant = client_credentials (default) / password (UserName, Password) / refresh_token (RefreshToken); Scope; Audience; ClientAuth="Basic" sends the client credentials as Basic auth instead of form fields |
Authorization: Bearer <access_token> |
TokenExchange |
Url, TokenPath; Method (POST); Body (a template, JSON-escaped); ContentType (JSON); ExpiresPath or ExpiresIn (seconds); Header (Authorization); Scheme (Bearer, or None for the bare token) |
your own login link: Genie calls it, reads the token at TokenPath, then sends it on the main call |
Tokens from OAuth2 and TokenExchange are cached in the engine cache (Redis when configured) until
30 s before they expire. With no stated lifetime they are cached for 5 minutes. CacheKey="name" pins
the cache entry name. If the API answers 401, the cached token is dropped and the call is sent
once more with a fresh token.
Request
Section titled “Request”- URL:
Urlis a template, and values are URL-encoded. WithConnection="Name", a relativeUrlis appended to the connection’sBaseUrl. - Query parameters:
<Query><Param Name="…" Value="…" /></Query>appends URL-encoded query parameters. - Headers:
<Headers><Header Name="…" Value="…" /></Headers>sets request headers. - Body: use exactly one of these.
<Body ContentType="application/json">…</Body>: a template. Values are JSON-escaped when the content type is JSON.<SqlPayload Format="Json|Text">: SQL whose first column becomes the body. All rows are concatenated, which is how SQL Server returns longFOR JSONoutput. Put the SQL in<SqlServer>/<PostgreSql>variants, or as plain text when it works on both.<Form><Field Name="…" Value="…" /></Form>:application/x-www-form-urlencoded.
- Redirects are never followed. A 3xx is just a non-success status.
Templates ({{…}})
Section titled “Templates ({{…}})”| Token | Value |
|---|---|
{{Name}}, {{Record.Name}} |
a context variable (the record fields captured into the context, and earlier nodes’ outputs) |
{{Instance.Id}}, {{Node.Key}}, {{Workflow.Name}} |
the instance, the node, the workflow |
{{Entity.Id}}, {{Entity.Type}} |
the bound record |
{{Session.UserId}}, {{Session.CompanyId}} |
the acting user and company |
{{Secret:Name}} |
an entry from Genie:Workflow:Secrets. An unknown name fails the call. |
A missing variable renders as an empty string.
Retries (<Retry>)
Section titled “Retries (<Retry>)”The retry loop is Genie’s own; it doesn’t use Polly. MaxAttempts (1–10) counts the first attempt.
Backoff is Fixed or Exponential, using BaseDelayMs × 2ⁿ plus jitter, capped at MaxDelayMs.
- Retried: network errors, per-attempt timeouts (
TimeoutSeconds), and theOnStatuscodes (default408,429,500-599). Retry-After: honoured unlessRespectRetryAfter="false".- Never retried: the caller’s own cancellation.
A retried POST can reach the API twice, so send an Idempotency-Key header when the API supports one.
Response
Section titled “Response”SuccessStatus: the status ranges that count as success (default200-299).<Map From="…" To="Var" Default="…">: copies one value from the response into a context variable.Fromis a JSONPath ($.a.b,$.list[0],$.list[-1],$['odd key']), or$status,$body(the raw text) or$headers.Name.- Property names match case-insensitively when there is no exact match.
- A value that isn’t found gets
Default(a template), or null.
<WriteBack>: SQL that runs after a success. The mapped values are bound as@Varalongside the usual workflow parameters.
Errors (<OnError>)
Section titled “Errors (<OnError>)”A failure is a status outside SuccessStatus after the retries, a network error, a timeout, or a
refused host.
- Without
<OnError>: the failure fails the transition. - With
<OnError>: the error message goes intoTo(defaultWebhookError) and the flow takesTransition. With noTransition, the flow continues on the normal path. - Error message: read from
MapErrorFrom(a JSONPath into the error body) when set. Otherwise it isHTTP <status>: <first 500 chars of the body>.
Outbound policy (Genie:Workflow:Webhooks)
Section titled “Outbound policy (Genie:Workflow:Webhooks)”AllowedHosts: the hosts a webhook may call. Use exact names,*.example.comwildcards, or*for any public host. Empty, the default, means no call is allowed. The list also applies toOAuth2/TokenExchangeauth links and to a script’sHttp.- Private networks: addresses are checked after DNS, so loopback, private, link-local, CGNAT and unique-local addresses are refused even when a public name resolves to them.
AllowPrivateNetworks: truelifts this, for example for an on-prem API. - HTTPS only: plain
http://is refused unlessAllowInsecureHttp: true. MaxResponseBytes: caps the response read (default 1 MiB).DefaultTimeoutSeconds: the per-attempt timeout when a node sets none (default 30).- Logs: auth headers and request bodies are never logged. A webhook logs its name, status, number of attempts and duration.
Script (inline C#)
Section titled “Script (inline C#)”<Node Key="ComputeDiscount" Type="Action" Label="Compute discount"> <ActionConfig> <ActionType>Script</ActionType> <Payload> <Script Language="CSharp" TimeoutMs="2000"><![CDATA[var total = Ctx.Record.Get<decimal>("Total");var tier = await Sql.ScalarAsync<string>( "SELECT Tier FROM Customers WHERE Id = @Id", new { Id = Ctx.Record.Get<long>("CustomerId") });
Outputs["Discount"] = tier == "Gold" && total > 1000 ? total * 0.1m : 0m;return tier == "Gold" ? "Discounted" : null; // optional: the transition to take ]]></Script> </Payload> </ActionConfig></Node>Language is required. CSharp is the only language today; any other value is rejected at save,
and the attribute exists so more languages can be added later without changing the contract.
TimeoutMs defaults to Genie:Workflow:Scripting:DefaultTimeoutMs (2000) and is capped at
MaxTimeoutMs (30000).
What a script sees
Section titled “What a script sees”| Name | What it is |
|---|---|
Ctx |
InstanceId, WorkflowName, NodeKey, EntityType, EntityId, Session (UserId, CompanyId), Variables (every context variable), and Record: Get<T>("Name"), GetOrDefault<T>("Name", fallback), Has("Name"), ["Name"]. |
Sql |
ScalarAsync<T>(sql, args), QueryAsync(sql, args) (rows as column → value), ExecuteAsync(sql, args), IsPostgreSql. args is an anonymous object or a dictionary. @RecordId, @InstanceId, the session parameters and the context variables are always bound. SQL runs on the request’s connection and transaction. |
Http |
GetAsync(url), PostAsync(url, body), SendAsync(method, url, body, headers), and ConnectionAsync(connection, method, path, body) (a configured connection’s base URL and auth). All of them go through the webhook outbound policy. The result has Status, IsSuccess, Body, Json (a JsonElement), Header(name) and Read("$.json.path"). |
Log |
Info, Warn and Error, tagged with the instance and node. |
Outputs |
values merged into the context when the script finishes. |
CancellationToken |
cancelled when the timeout elapses. |
Imported namespaces: System, System.Collections.Generic, System.Globalization, System.Linq,
System.Text, System.Text.Json, System.Text.RegularExpressions and System.Threading.Tasks.
A script may declare its own records, classes and local functions.
A returned string names the transition to take. Throwing, timing out or failing to compile fails the transition with the message.
Security
Section titled “Security”A Roslyn script runs in-process with the engine’s privileges, so Genie limits what one can do in several ways. None of them is an OS sandbox.
- API allowlist: every symbol a script uses, and the type of every expression, must come from
the namespaces above or the script globals.
System.IO,System.Net,System.Reflection,System.Diagnostics,System.Threading(other thanCancellationToken) and every other namespace are refused. So areType/GetType()/typeof,Environment,AppDomain,Activator,GC,Console,dynamic,unsafe,goto, and the#r/#loaddirectives. The check runs at save time and again at run time. - Timeouts: Genie inserts a cancellation check at the top of every loop and every block-bodied
function or lambda, so
while (true) {}stops at the timeout. Deep recursion can still crash the process, so keep scripts short and iterative. - Off by default:
Genie:Workflow:Scripting:Enabledmust betruefor a Script node to run. - Authoring needs a grant: adding or changing a script needs Update on the
WorkflowScriptsresource. The check fails closed: if the resource isn’t declared, only System users may author scripts. Declare and grant it in your app’srbac.xml. A save that leaves every script unchanged needs no grant, so other people can keep editing the rest of the workflow.
For anything substantial, prefer a custom action: it is compiled, reviewed and tested with your app.
SetVariable
Section titled “SetVariable”<ActionConfig> <ActionType>SetVariable</ActionType> <Payload><Name>Priority</Name><Value>@Level</Value></Payload></ActionConfig><Value> of @Other copies another context variable and keeps its type. Anything else is a
template rendered over the context, such as Order {{Record.OrderNo}}.
Designing these in the workflow designer
Section titled “Designing these in the workflow designer”The designer edits all of this through typed rows instead of raw XML. It has Monaco code editors with C# / SQL / template IntelliSense, sample values from a picked record, and a Test call whose response you can click to create maps. See Engine → Code editors, IntelliSense and sample values.
Custom actions (host code)
Section titled “Custom actions (host code)”builder.Services.AddGenieWorkflowAction<CreditScoringHandler>("credit-scoring");
[Description("Scores the customer with the credit bureau.")] // shown in the designer's ActionType pickerpublic sealed class CreditScoringHandler(IBureauClient bureau) : IWorkflowActionHandler{ public async Task<WorkflowActionResult> ExecuteAsync(WorkflowActionContext context, CancellationToken ct) { var score = await bureau.ScoreAsync(context.WorkflowContext.Variables["CustomerId"], ct); return new WorkflowActionResult { Success = true, Outputs = new Dictionary<string, object?> { ["CreditScore"] = score }, Transition = score < 600 ? "Declined" : null, }; }}See Engine → Custom action handlers for the full context shape.
Configuration
Section titled “Configuration”{ "Genie": { "Workflow": { "Secrets": { "Courier.ClientId": "…", "Courier.ClientSecret": "…" }, "Webhooks": { "AllowedHosts": ["api.courier.com", "auth.courier.com", "*.partner.com"], "AllowPrivateNetworks": false, "AllowInsecureHttp": false, "MaxResponseBytes": 1048576, "DefaultTimeoutSeconds": 30 }, "Connections": { "Courier": { "BaseUrl": "https://api.courier.com/v2", "Auth": { "Type": "OAuth2", "TokenUrl": "https://auth.courier.com/oauth/token", "ClientId": "{{Secret:Courier.ClientId}}", "ClientSecret": "{{Secret:Courier.ClientSecret}}" } } }, "Scripting": { "Enabled": false, "DefaultTimeoutMs": 2000, "MaxTimeoutMs": 30000 } } }}Keep secret values out of committed files. Use user-secrets or environment variables
(Genie__Workflow__Secrets__Courier.ClientSecret). In code: genie.ConfigureWorkflow(w => …).
A node references a connection with <CallWebhook Connection="Courier">. The node’s own <Auth>, when
present, overrides the connection’s.
Copyright © 2026 Orbyn Technologies. All rights reserved.