Skip to content

Webhooks Connections Action Steps

Marcello Marchetti edited this page Jul 29, 2026 · 4 revisions

Connections & Action Steps — Provider Configuration Guide

This page describes how to configure per-tenant Connections and how an orchestrator workflow uses the Action step to invoke an external HTTP endpoint (webhook/request) or run a sandboxed script (javascript/run).

For triggering an Agent Task from an external system (and receiving results back), see Webhooks-Agent-Tasks. For low-code recipes, see Integration-Templates.


Table of Contents


Overview

The Action step lets an orchestrator workflow invoke external systems (HTTP webhooks, future native connectors). The platform ships with two built-in providers:

Provider Action Connection Use case
email send None Send an email via Azure Communication Services
webhook request Optional Invoke any HTTP endpoint, with templated body + structured auth
javascript run None Run a sandboxed deterministic script over context data (including uploaded files)

This guide covers the Connection entity, the webhook provider (in depth) and the JavaScript provider.

A Connection is a per-tenant, reusable configuration holder for a remote endpoint:

  • baseUrl + default headers + structured auth + (optionally) an encrypted secret
  • Referenced by Action steps via ConnectionId
  • Persisted per tenant in SQL Server

When an Action step runs, the orchestrator dispatches a message to Service Bus (action-dispatch queue). A background worker resolves the Connection, applies the auth, performs the HTTP call, then publishes the completion back (action-completion queue). The orchestrator resumes, applies the configured OutputMapping, and continues to the next step.


Quick Start

  1. Create a Connection (one-time, per tenant):

    • Navigate to /connections (admin section)
    • Click New connection
    • Provider: HTTP Webhook
    • Connection ID: lowercase slug (e.g., partner-api)
    • Display name: human-friendly label
    • baseUrl: e.g., https://your-server.example.com/api
    • Configure auth (see Authentication Modes)
    • Click Set / update secret and paste the actual secret value
    • Click Save, then Test connection
  2. Add an Action step in an orchestrator:

    • In the orchestrator editor, drag an Action step onto the canvas
    • Provider: HTTP Webhook
    • Action: HTTP Request
    • Connection: select the one created above
    • Method: GET / POST / PUT / PATCH / DELETE
    • Path (relative): e.g., /common/voices
    • Configure body, headers, query params, expected status range as needed
    • Output Mapping: extract specific fields from the response into context variables
  3. Reference the response in downstream steps:

    • In a SendMessage or Agent step prompt, use {{contextVariable}} to interpolate the mapped value

Connections

Connection Data Model

Field Type Description
CompanyId NVARCHAR(64) Tenant discriminator (composite PK)
ConnectionId NVARCHAR(64) Slug; unique per tenant (composite PK)
ProviderId NVARCHAR(64) e.g., webhook
DisplayName NVARCHAR(256) Human-readable label
ConfigJson NVARCHAR(MAX) Provider-specific non-secret JSON (see schema below)
SecretRef NVARCHAR(MAX) AES-256 encrypted blob; null if no secret
IsActive BIT Soft-delete flag
CreatedAt, UpdatedAt, CreatedBy — Audit fields

The SecretRef is encrypted at rest with AES-256 GCM. Plaintext is never persisted or returned to clients; responses include a HasSecret boolean flag only.

Connection Admin UI

Located at /connections:

  • List page:

    • Data grid showing Name, Provider, Updated, Status
    • Toolbar: + New connection
    • Per-row: Edit, Delete
  • Edit dialog:

    • Provider picker (read-only on edit)
    • Connection ID (slug, auto-suggested from display name on create, read-only on edit)
    • Schema-driven configuration form
    • Secret field — write-only with explicit Set / update secret toggle on edit
    • Test connection button — performs a server-side load + decrypt verification (see Test Connection)

Webhook Connection Configuration Schema

The webhook provider exposes the following ConfigJson shape:

Field Type Description
baseUrl string (URI) Required. Base URL for all calls through this Connection
defaultHeaders object<string,string> Optional. Headers added to every outbound request
auth object Optional. Structured authentication (see below)
ignoreSslErrors boolean Optional, default false. Skip TLS certificate validation for every call through this Connection. Use only against trusted endpoints with self-signed/expired certs.
bodyTemplates array Optional. A curated library of reusable body templates that the step editor exposes for quick reuse.

Example ConfigJson:

{
  "baseUrl": "https://your-server.example.com/api",
  "defaultHeaders": {
    "Accept": "application/json"
  },
  "auth": {
    "type": "header",
    "headerName": "x-functions-key"
  },
  "ignoreSslErrors": false
}

Authentication Modes

Configured under ConfigJson.auth:

type Required fields Effect on outbound request
none — No auth header added
bearer (none) Authorization: Bearer <secret>
basic username Authorization: Basic base64(username:<secret>)
header headerName <headerName>: <secret> (custom header)

Where the secret comes from: the top-level Secret field of the Connection (decrypted just-in-time). Never embedded in ConfigJson itself.

Per-step override: an Action step can override the Connection's auth by providing an auth object directly in its step config. Inline secretValue is also encrypted at rest. See Path vs URL — Connection vs Inline.

Test Connection

The Test connection button in the edit dialog verifies that:

  • The Connection record loads from SQL filtered by CompanyId
  • SecretRef decrypts successfully

A deeper provider-specific round-trip (an actual HTTP probe against baseUrl) is available via the webhook test runner. A round-trip probe can also be performed from the orchestrator step editor before saving.

Delete Behavior

Deleting a Connection:

  • Counts references: orchestrator steps whose action expression connectionId equals this connectionId
  • If there are still references and the delete is not forced, the request is rejected with 409 Conflict and a payload that reports the reference count and an explanatory message
  • The UI then offers a confirmation prompt with the reference count before re-issuing the delete with force=true
  • Implementation is soft-delete: IsActive is flipped to 0 and the row is retained for audit

Action Step — Webhook Provider

Provider Capabilities

The connectionRequirement is Optional for the webhook/request action — a Connection can be selected or cleared.

{
  "providerId": "webhook",
  "displayName": "HTTP Webhook",
  "iconName": "webhook",
  "capabilities": {
    "supportsSecrets": true,
    "supportsTesting": true
  },
  "connectionRequirement": "Optional"
}

The webhook provider has one action: request.

Input Schema

Field Type Default Description
method enum POST GET | POST | PUT | PATCH | DELETE
path string — Relative path appended to Connection.baseUrl (when a Connection is selected)
url string (URI) — Absolute URL — used only when no Connection is selected
queryParams object<string,string> null Query string pairs (each value supports {{var}} interpolation)
headers object<string,string> null Custom request headers (templated)
body any — Request body (object, array, or string — templated)
contentType enum application/json application/json | application/x-www-form-urlencoded | text/plain
auth object null Inline auth (overrides Connection's auth if provided)
expectedStatusRange string 200-299 Allowed status codes. Format: 200-299 or 200,201,204 or a mix
timeoutSeconds integer 30 Per-request timeout (clamped to 1–60s)
ignoreSslErrors boolean false Per-step override of the Connection-level flag

Output Schema

When the call succeeds, the handler publishes a structured completion that the orchestrator's OutputMapping can pull apart. All keys are camelCase:

Field Type Description
statusCode integer HTTP status returned by the endpoint
headers object<string,string> Response headers (joined with , if multi-valued)
body any Response body — parsed as JSON when Content-Type contains json, else raw text
elapsedMs integer Round-trip duration in milliseconds

URL Resolution

When a Connection is selected:

finalUrl = Connection.baseUrl.TrimEnd('/') + '/' + step.path.TrimStart('/')

Examples:

baseUrl path Result
https://x.com/api /voices https://x.com/api/voices
https://x.com/api voices https://x.com/api/voices
https://x.com/api/ /voices https://x.com/api/voices
https://x.com/api/ — (empty) https://x.com/api

This is additive concatenation, deliberately different from System.Uri's RFC 3986 behavior (which would discard /api when path starts with /).

When no Connection is selected, step.url is used directly as an absolute URL.

Path vs URL — Connection vs Inline

Mode Connection Step config Outbound URL
Connection mode Selected path: "/voices" Connection.baseUrl + path
Inline mode (cleared) url: "https://x.com/voices" url verbatim

The dropdown in the step editor supports clearing the Connection for providers with connectionRequirement = Optional.

Body Templates

The body field accepts arbitrary JSON. Two interpolation rules are applied at dispatch time:

  1. Classic interpolation: every string value goes through the orchestration templater, substituting {{varname}} with values from the orchestration context.
  2. Rich substitution: when a string is exactly a single placeholder and the variable's value is non-string (array, object, number, bool), the JSON node is replaced wholesale:
// Step body
{ "to": "{{approvers}}", "subject": "Re: {{taskName}}" }

// Context
{ "approvers": ["a@x.com", "b@y.com"], "taskName": "Export" }

// Outbound body
{ "to": ["a@x.com", "b@y.com"], "subject": "Re: Export" }

Same rules apply to queryParams, headers, url, path.

Output Mapping with Dot-Paths

In the step editor's Output mapping section, each row maps:

Left column Right column
Output path (in the action's response) Context variable name

Path syntax supports:

Path Result
body Entire response body
statusCode HTTP status code as integer
body.0.name body[0].name (dot-index form)
body.voices[0].id Same with bracket-index form
headers.Content-Type Header value (dash/underscore-safe)
* Whole completion JSON {statusCode, headers, body, elapsedMs}

For each row, the resolved value is written to context.Data[contextVariable]:

  • String JSON values are unwrapped (quotes stripped) so {{var}} substitutes the raw text.
  • Numbers, booleans, arrays, objects keep their JSON representation.

If the path doesn't resolve (missing field, out-of-range index, wrong kind), the variable is not set and a warning is logged:

Action step '<name>' OutputMapping path '<path>' did not match — context variable '<var>' not set

Tip: to expose the HTTP status of a call to downstream Condition / Switch steps, map statusCode → someVariable explicitly. (The lastActionError object — see Retry Policy — does not carry a statusCode field, so capture it via OutputMapping when you need to branch on the numeric status.)


Action Step — JavaScript Provider

Provider Capabilities

The connectionRequirement is None for the javascript/run action — it needs no Connection; it computes over the data you pass in.

{
  "providerId": "javascript",
  "displayName": "JavaScript",
  "iconName": "code",
  "capabilities": {
    "supportsSecrets": false,
    "supportsTesting": true
  },
  "connectionRequirement": "None"
}

The provider has one action: run. The script executes in a closed sandbox (QuickJS compiled to WebAssembly): no network, no filesystem, no external packages — only deterministic computation over the supplied data.

Script Contract

The script is the body of a function that reads a global input object and ends with return <a JSON value>:

return { doubled: Number(input.n) * 2 };

The returned value becomes the action output and is exposed to later steps via the step's OutputMapping (e.g. map doubled → result). Code and data stay separate: variables are never string-interpolated into the source — they arrive only as structured data on input.

Input Schema

Field Type Description
code string The script body (reads input, returns a JSON value). Capped at 64 KB.
input object Named bindings mapped from context variables — each entry is <name>: {{variable}} or a literal, read in-script as input.<name>.

The input object is populated from an explicit name-binding grid in the editor; the step's generic Input mapping is not used by this provider.

Context Files (input.files)

When the step has Use context files enabled and the conversation carries uploaded files, the server pre-parses them and injects input.files — an array of:

Field Type Description
name string File name
ext string Lowercase extension, no dot (e.g. xlsx)
mimeType string | null Content type when known
size integer Size in bytes
kind string "table", "text" or "binary"
sheets object kind: "table" only — one entry per sheet name, each { headers, rows } where rows are objects keyed by header
text string kind: "text" only — raw file text (use JSON.parse for JSON)
tooLarge boolean true when the file exceeded a limit and was passed as metadata only

Format mapping: Excel (.xlsx/.xls) and CSV/TSV → kind: "table"; .txt/.md/.xml/.html/.json → kind: "text"; anything else → kind: "binary". Excel cells keep their native types (numbers, booleans, ISO dates); CSV cells are always strings. File data is resolved at runtime, isolated per tenant, and never persisted in the workflow state.

Authoring Assistance

The step editor can generate the script for you. While the code field is empty the monospace editor is replaced by a call-to-action (Generate the script with AI / Write it manually); a dedicated button in the editor's title bar opens the same assistant regardless of whether code is present.

The assistant is a chat agent whose knowledge base holds the Action-step documentation, so its answers about input, input.files, return and the limits reflect this page rather than generic JavaScript knowledge. When it opens it is briefed with the step's context — the upstream context variables available, the input bindings already mapped and the current script — so the interview covers only what it cannot infer. Besides the code it advises on the surrounding configuration: bindings to create, OutputMapping rows to add, whether the step needs context files.

The finished script arrives behind a Use this code button that writes the code field exactly as manual editing would, asking for confirmation when code is already present; asking for a revision refreshes it. The assistant only writes into the editor — it never saves the step and never executes the script.

Output & Testing

The action output is the script's returned JSON value; pull its fields apart with OutputMapping like any other action. The editor's Run button executes the script against a sample input you provide, using the same engine as the runtime, and shows the output or error.

Limits

Limit Value
Script source 64 KB
Memory 128 MB
Wall-clock 5 s
Output 1 MB
Files per step 20
Total file bytes 8 MB
Bytes per file 10 MB
Rows per file 50,000
Cells per file 1,000,000

A script that exceeds memory/CPU/time is interrupted and the step fails; a file over its limits is passed with tooLarge: true (the step does not fail). Script errors are deterministic and are not retried.

Worked Example — count rows per group in an Excel

// input.files[0] is an .xlsx with an "Orders" sheet; count rows per Customer
const wb = input.files.find(f => f.ext === "xlsx");
const counts = {};
for (const r of wb.sheets["Orders"].rows) {
  const k = String(r.Customer ?? "(blank)");
  counts[k] = (counts[k] || 0) + 1;
}
return { perCustomer: counts, total: wb.sheets["Orders"].rows.length };

Map perCustomer → perCustomer and total → total in OutputMapping, then reference {{total}} in a later Send Message step. To collect the file mid-workflow, pause on a User question or Agent step with Allow file upload enabled (see Administrator-Guide).


Execution Flow

Orchestrator: dispatch an Action step
  ├─ Parse the step's action expression
  ├─ Validate (providerId, actionId)
  ├─ Render input (templating + rich substitution)
  ├─ Build the action dispatch message
  ├─ Dispatch → 'action-dispatch' queue
  └─ Suspend orchestration (waits for completion)

Background worker: handle the dispatch message
  ├─ Resolve handler for "webhook"
  ├─ Resolve Connection (cached, 30s TTL)
  ├─ Deserialize the webhook input
  ├─ Resolve target URI (baseUrl + path, or inline url)
  ├─ SSRF safety guard (block-list)
  ├─ Build the HTTP request (method, query, headers, body, auth)
  ├─ Add standard headers (X-XRCopilot-* + X-Idempotency-Key)
  ├─ Send the request (insecure variant if ignoreSslErrors)
  ├─ Parse response body (JSON or string, cap 1 MB)
  ├─ Classify status (in expectedStatusRange? transient? permanent?)
  ├─ If transient & retries available → schedule retry (15s / 30s / 60s)
  └─ Else → publish completion on 'action-completion'

Orchestrator: resume from completion
  ├─ Inject the completion into the suspended state
  ├─ Re-enter the dispatch loop at the suspended step
  ├─ Apply OutputMapping (dot-path resolution)
  ├─ On failure: populate context.Data["lastActionError"]
  └─ Continue to the next step

Standard Headers & Idempotency

Every outbound webhook automatically receives:

Header Value Purpose
X-XRCopilot-ExecutionId execution UUID Cross-reference with execution logs
X-XRCopilot-TaskId step ID (orchestrator) / task ID (agent task) Correlation per logical operation
X-XRCopilot-Attempt 1-based attempt counter Visibility into retries
X-Idempotency-Key {executionId}:{correlationId} Deterministic deduplication key for receivers that support it

Receivers that honor X-Idempotency-Key (most modern SaaS APIs) can safely treat retries from XRCopilot as no-ops on the second delivery.

Standard headers are emitted via a shared helper, used both by the orchestrator path and by the agent-task webhook adapter (see Webhooks-Agent-Tasks).


Retry Policy

Outcome Behavior
Status in expectedStatusRange Success → publish completion with Success=true
Status outside range, in 408 / 429 / 5xx Transient → Service Bus scheduled requeue with exponential backoff (15s, 30s, 60s), max 3 retries
Status outside range, 4xx (except 408/429) Permanent → publish completion with Success=false, no retry
HttpRequestException / timeout (OperationCanceledException) Transient → retry
SSRF block Permanent → no retry
Response too large (>1 MB) Permanent → no retry
Handler unexpected exception Permanent → publish completion with Success=false, code HandlerException

After a permanent failure (or retry exhaustion), the orchestrator's resume path populates context.Data["lastActionError"]:

{
  "code": "StatusOutOfRange",
  "message": "HTTP 404 not in expected range '200-299'.",
  "providerId": "webhook",
  "actionId": "request",
  "attemptCount": 1,
  "timestamp": "2026-05-25T10:14:36Z"
}

Downstream Condition / Switch steps can branch on {{lastActionError.code}} or on {{lastActionError.message}}.

Note: lastActionError does not include the numeric HTTP status. The status text is embedded in message (e.g. "HTTP 404 not in expected range…"). If you need to branch on the numeric status itself, add an Output mapping statusCode → someVariable on the action step and branch on {{someVariable}}.


SSL / TLS

By default the webhook handler enforces strict TLS validation. Two escape hatches exist (use sparingly):

Per-Connection (ignoreSslErrors on the Connection config)

Every call through this Connection skips certificate validation. Useful for:

  • Internal staging environments with self-signed certs
  • Partner endpoints with expired/broken chains the receiver can't fix overnight

Per-Step (ignoreSslErrors on the step input)

Per-call override, takes precedence over the Connection's setting. Useful when only one specific endpoint behind a shared Connection has cert issues.

Every request routed through the insecure HTTP client logs a warning naming the target host + execution/step IDs:

TLS certificate validation is DISABLED for webhook <host> (execution <exec> step <step>). Trust the endpoint owner.

SSRF Guard

Even with TLS bypass, the safety guard remains active. Blocked targets:

  • Loopback: 127.0.0.0/8, ::1
  • RFC1918: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
  • Link-local: 169.254.0.0/16 (incl. cloud instance-metadata 169.254.169.254)
  • IPv6 unique-local: fc00::/7
  • IPv6 link-local: fe80::/10
  • Reserved: 0.0.0.0/8
  • Known cloud metadata hostnames: metadata.google.internal, metadata.aws, metadata.azure.com

Outside development environments, only https:// is allowed.

If a hostname resolves to a blocked IP (DNS rebinding), the request is rejected before sending.


Security

Concern Mitigation
Secret leak in DB AES-256 GCM encryption. Plaintext never persisted.
Secret leak in transit secretValue encrypted in step config too; only decrypted just-in-time in the worker
Secret leak in logs Diagnostic logs print header names + secret length only, never values
Cross-tenant access Every SQL query filters by CompanyId; cache key includes CompanyId
SSRF Safety-guard block-list (see above) + no automatic redirect following
Response bomb Body cap of 1 MB → ResponseTooLarge permanent failure
Header injection CRLF stripped from outgoing values
Replay / duplicate side-effects Deterministic X-Idempotency-Key = {executionId}:{stepId}
Connection deletion → broken steps Delete blocked with 409 + reference count unless forced

Worked Examples

Example 1 — Simple GET against a backend API with header-key auth

Connection (/connections → New connection):

The secret value is set separately via the Set / update secret action in the UI and stored encrypted — it is not part of configJson.

{
  "providerId": "webhook",
  "connectionId": "internal-api",
  "displayName": "Internal API",
  "configJson": {
    "baseUrl": "https://your-server.example.com/api",
    "auth": { "type": "header", "headerName": "x-functions-key" }
  }
}

Action step:

Field Value
Provider HTTP Webhook
Action HTTP Request
Connection internal-api
Method GET
Path /common/voices
Expected Status Range 200-299 (default)

Output mapping:

Output path Context variable
body voicesJson
body.0.name firstVoiceName
statusCode voicesHttpStatus

Downstream SendMessage step:

La prima voce disponibile è: **{{firstVoiceName}}**
Status HTTP: {{voicesHttpStatus}}
Lista completa: {{voicesJson}}

Example 2 — POST with templated body to a partner webhook

Connection:

{
  "baseUrl": "https://partner.example.com/api/v1",
  "auth": { "type": "bearer" },
  "defaultHeaders": { "Accept": "application/json" }
}

(Secret: a long-lived API token.)

Action step:

Field Value
Method POST
Path /notifications
Content type application/json
Body { "to": "{{userEmail}}", "subject": "Welcome {{userName}}", "metadata": "{{userMetadata}}" }

When userMetadata in the context is a JSON object, the rich-substitution rule replaces the placeholder with the structured value (not a stringified version).

Example 3 — Branching on HTTP failure

Step 1 (Action — POST /tickets):

Field Value
Output mapping body.id → ticketId
Output mapping statusCode → ticketStatus

Step 2 (Condition):

  • Variable: lastActionError.code
  • Operator: equals
  • Value: StatusOutOfRange
  • True branch → SendMessage: Impossibile creare il ticket. Status: {{ticketStatus}}, dettaglio: {{lastActionError.message}}
  • False branch → SendMessage: Ticket creato con ID {{ticketId}}

Note the True branch uses {{ticketStatus}} (captured via the statusCode output mapping in Step 1) for the numeric status, and {{lastActionError.message}} for the human-readable detail. lastActionError itself has no statusCode field.

Example 4 — Inline URL (no Connection)

Useful for one-off calls or quick prototyping.

Action step:

Field Value
Provider HTTP Webhook
Connection (cleared via the x button)
Method POST
URL https://hooks.slack.com/services/T00/B00/XYZ (absolute)
Body { "text": "Build completed: {{buildResult}}" }

Without a Connection there's no centralized auth — credentials must be embedded in url (e.g., webhook token in the path) or in custom headers.


Troubleshooting

Symptom Likely cause Fix
Connection 'xxx' not found in worker logs ConnectionId in step doesn't match an existing Connection for the tenant, or it's been soft-deleted Verify in /connections; recreate if missing
Connection resolution failed for connection 'xxx' Secret decryption failed (encryption key changed, blob corrupted) Open the Connection in Edit, click Set / update secret, re-enter the secret, save
Outbound URL is missing the /api prefix baseUrl doesn't include /api; path doesn't either Either embed /api in baseUrl or in path
HTTP 403 from the backend Wrong key in Secret, or the endpoint needs a host-level key rather than a function-level one Use the correct key, or fetch the endpoint-specific key from the provider
HTTP 404 but the same URL works in Postman Method mismatch (e.g., step uses POST but endpoint accepts only GET) Change Method in the step editor
WebhookSafetyException: Loopback address blocked Step targets 127.0.0.1 / localhost Cannot be bypassed; use a publicly reachable endpoint or a tunnel
WebhookSafetyException: Only https:// is allowed Step targets http:// in a non-development environment Switch to HTTPS
ResponseTooLarge permanent failure Endpoint returns a body > 1 MB Pagination, server-side filtering, or store + return a URL instead of the payload
OutputMapping warning: path '<x>' did not match Typo in path, or response shape changed Inspect the raw response via a temp body → tempVar mapping; correct the path
Auth header sent but server returns 401/403 Stale key (cache 30s TTL) OR wrong key in Secret Wait 30s and retry; verify the key works with a direct curl
Cache shows stale Connection config Edited the Connection less than 30s ago TTL is 30 seconds; retry after the TTL elapses

Changelog

Version Date Changes
1.0 2026-05-25 Initial release — Connection entity, webhook provider (GET/POST/PUT/PATCH/DELETE), templated body, structured auth (none/bearer/basic/header), OutputMapping with dot-paths, SSRF guard, automatic idempotency key, retry with exponential backoff, per-Connection and per-step ignoreSslErrors overrides.
1.1 2026-07 Added the JavaScript provider (javascript/run): sandboxed deterministic script over context data, input.files for uploaded Excel/CSV/JSON/text, in-editor Run, fixed limits.
1.2 2026-07 Documented the in-editor authoring assistant that writes an action script from a short interview, briefed with the step's context, and hands it over through Use this code.

See Also

Clone this wiki locally