Skip to content

Webhooks Agent Tasks

Marcello Marchetti edited this page Nov 23, 2026 · 5 revisions

Agent Tasks — Webhook Integration Guide

This page describes how external systems can invoke XRCopilot AI agents via webhooks and receive execution results through outbound delivery. The same inbound pattern can also start a Business Process instance — see Starting a Process via Webhook.

For step-by-step low-code recipes (Power Automate, SharePoint, Logic Apps) see Integration-Templates. For invoking external HTTP endpoints from inside an orchestrator workflow, see Webhooks-Connections-Action-Steps.


Table of Contents


Overview

XRCopilot Agent Tasks allow external systems to trigger AI agent executions via HTTP webhooks. The integration works in two directions:

Direction Description
Inbound (Trigger) Your system sends an HTTP POST to invoke an agent task
Outbound (Delivery) XRCopilot sends execution results back to your system
┌──────────────────┐   POST {base-url}/hooks/{hookId}   ┌──────────────────────┐
│  Your System     │ ───────────────────────────────────>│  XRCopilot           │
│  (Power Automate,│                                     │                      │
│   Zapier, n8n,   │     POST {your-webhook-url}         │  Agent Task          │
│   custom app)    │ <───────────────────────────────────│  Execution + Delivery│
└──────────────────┘                                     └──────────────────────┘

Base URL and Environments

All API endpoints are exposed through Azure API Management (APIM). Do not call the backend Functions directly.

Environment Base URL
Production https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public

All requests require an APIM subscription key passed via the Ocp-Apim-Subscription-Key header (see Authentication under Inbound Webhook).


Quick Start

1. Obtain Credentials

When a webhook is configured for an Agent Task, you receive:

Field Description
hookId Webhook identifier (format: wh_ + alphanumeric), used in the URL path
apiKey Secret API key (shown once at creation — store it securely)

You also need an APIM subscription key, provided separately by your XRCopilot administrator.

2. Send Your First Request

curl -X POST "https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public/hooks/wh_a1b2c3d4e5f6" \
  -H "Ocp-Apim-Subscription-Key: <YOUR_API_KEY>" \
  -H "X-Api-Key: <YOUR_WEBHOOK_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{"customer_name": "Acme Corp", "question": "What is the project status?"}'

3. Receive the Response

The webhook returns 202 Accepted immediately. The agent executes asynchronously and delivers results via your configured output action (webhook, email, or in-app inbox).


Inbound Webhook (Trigger)

Endpoint

POST {base-url}/hooks/{hookId}

Full URL example (production):

https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public/hooks/wh_a1b2c3d4e5f6
Parameter Location Description
hookId URL path Unique webhook identifier (format: wh_ + alphanumeric string)

Authentication

Every request requires two authentication headers:

Header Description
Ocp-Apim-Subscription-Key APIM subscription key — provided by your XRCopilot administrator
X-Api-Key Webhook API key — generated when the webhook is created
POST /api/lab-public/hooks/wh_a1b2c3d4e5f6 HTTP/1.1
Host: apim-hipexr-prod-italynorth.azure-api.net
Ocp-Apim-Subscription-Key: <YOUR_API_KEY>
X-Api-Key: <YOUR_WEBHOOK_API_KEY>
Content-Type: application/json

APIM subscription key:

  • Provided by your XRCopilot administrator when onboarding your integration
  • Can also be passed as query parameter: ?subscription-key=YOUR_KEY
  • Identifies and authorizes your application at the API gateway level

Webhook API key (X-Api-Key):

  • Generated automatically when the webhook is created
  • Shown once at creation time — it cannot be retrieved later
  • Stored as a SHA-256 hash on the server (the plain text is never persisted)
  • Validated by hashing the incoming key and comparing with the stored hash

Important: If you lose the webhook API key, you must regenerate it. The previous key will be immediately invalidated.

IP Whitelisting

Optionally, the webhook can be configured with an IP whitelist. When configured, only requests from listed IP addresses are accepted.

The client IP is extracted from (in order of priority):

  1. X-Forwarded-For header (first IP in the chain)
  2. X-Client-IP header
  3. Direct connection IP

If your system connects through a proxy or load balancer, ensure the originating IP is included in the forwarded headers.

Request Payload

The request body must be valid JSON (or empty). The payload is passed to the agent as trigger data and can be used in input template variable resolution.

{
  "customer_id": "12345",
  "report_type": "weekly",
  "department": "sales"
}

Constraints:

  • Content-Type should be application/json
  • Body must be valid JSON (if not empty)
  • Empty body is accepted and treated as {}
  • No size limit enforced at the webhook level (subject to platform limits, typically 100 MB)

Response

Success:

HTTP/1.1 202 Accepted
{
  "accepted": true
}

Errors:

HTTP Status Meaning Description
202 Accepted Event received and queued for execution
400 Bad Request Request body is not valid JSON
401 Unauthorized Missing or invalid Ocp-Apim-Subscription-Key or X-Api-Key header
403 Forbidden Webhook is disabled, or client IP is not in whitelist
404 Not Found Unknown hookId
500 Internal Error Server-side processing error

Error responses carry a JSON body of the form { "error": "..." }.

Template Variables

The Agent Task has an input template with {{variable}} placeholders. When the webhook fires, variables are resolved from multiple sources in this priority order:

  1. Webhook payload — fields from the JSON body
  2. Static variables — pre-configured default values
  3. Built-in variables — {{date}}, {{time}}, {{taskName}}

Example:

Input template:

Generate a {{report_type}} report for customer {{customer_name}} in department {{department}}.

Webhook payload:

{
  "customer_name": "Acme Corp",
  "report_type": "monthly"
}

Static variables:

{
  "department": "sales"
}

Resolved input sent to the agent:

Generate a monthly report for customer Acme Corp in department sales.

Note: Webhook payload values take precedence over static variables with the same key.

The task input inside an orchestrator

When the Agent Task runs an orchestrator, the resolved input is also available to every step of the workflow as the {{input}} variable. A step can pass it on unchanged — for example to a skill that renders a long text into a document — without a first step where a model copies it into a variable. The variable exists only when the resolved input is not empty, and only in runs started by an Agent Task: orchestrations started from the chat are unchanged. See Orchestrators.

Event Batching

The webhook supports an optional batch accumulation window. When batchWindowSeconds > 0, multiple events received within the window are accumulated and executed together as a single agent invocation.

Configuration Behavior
batchWindowSeconds = 0 Each event triggers immediate, independent execution
batchWindowSeconds = 60 Events are accumulated for 60 seconds, then executed as a batch

Batching is useful when your system sends multiple related events in rapid succession and you want to process them together.


Starting a Process via Webhook

Besides triggering Agent Tasks, an inbound webhook can start a Business Process instance (see Administrator-Guide → Business Process Management). The pattern mirrors the Agent Task trigger above: an external system sends an HTTP POST to a per-process hook URL, and the request body becomes the process case data.

Endpoint

POST {base-url}/hooks/process/{hookId}

Full URL example (production):

https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public/hooks/process/wh_proc_a1b2c3d4e5f6
Parameter Location Description
hookId URL path Per-process webhook identifier (format: wh_proc_ + alphanumeric), returned when you enable the webhook on the process

Authentication

Identical to the Agent Task trigger — two headers:

Header Description
Ocp-Apim-Subscription-Key APIM subscription key — provided by your XRCopilot administrator
X-Api-Key Per-process webhook key — shown once when you create or regenerate it on the process. Stored as a SHA-256 hash; it cannot be retrieved later.

An optional IP whitelist can be configured on the webhook.

Request

The body must be a JSON object (or empty). Its properties become the initial case data of the new instance, available to start forms and gateway conditions.

curl -X POST "https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public/hooks/process/wh_proc_a1b2c3d4e5f6" \
  -H "Ocp-Apim-Subscription-Key: <YOUR_API_KEY>" \
  -H "X-Api-Key: <YOUR_WEBHOOK_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{"orderId": "ORD-12345", "priority": "high"}'

Response

On success the endpoint returns 202 Accepted with the new instance id:

{ "accepted": true, "instanceId": "3f2b1c4d-..." }
Status Meaning
202 Accepted — a new process instance was started
400 Body is not a valid JSON object
401 Missing or invalid X-Api-Key
403 Webhook disabled, or client IP not in the whitelist
404 Unknown hookId
409 The process has no published version

Notes

  • The webhook is managed per process (create / regenerate key / delete) from the process detail — the key is shown only once.
  • Starting via webhook bypasses the per-process start-permission roles: the API key itself is the authorization.
  • The target process must have a published version, otherwise the call returns 409.
  • The started instance behaves like any other and appears in instance monitoring — see Administrator-Guide.

Outbound Webhook (Delivery)

When the agent task completes, XRCopilot can deliver results to your webhook endpoint.

Payload Format

The body of the outbound webhook is a template rendered against the execution context. By default the template emits the legacy shape (preserved for backward compatibility — no migration required for existing webhooks):

{
  "executionId": "c34e88c5-b4a1-4f2e-9b3c-7d8e9f0a1b2c",
  "taskId": "2ff8971d-2ddf-4992-bab4-3f0dc4ecc301",
  "taskName": "Customer Support Q&A",
  "companyId": "acme-corp",
  "status": "Completed",
  "durationMs": 3700,
  "timestamp": "2026-03-20T15:06:10.000Z",
  "agentResponse": "The project is currently on track. Phase 3 was completed last week and Phase 4 is 60% done...",
  "files": [
    {
      "fileName": "report-2026-03-20.pdf",
      "url": "https://your-storage.example.com/report-2026-03-20.pdf?sv=...&sig=...",
      "contentType": "application/pdf"
    }
  ]
}

All property names are camelCase, exactly as shown. The status value is one of the PascalCase status names listed under Execution Statuses.

Custom body templates

You can override the default body by setting bodyTemplate in your webhook output configuration. Variables available in the template:

Variable Description
{{executionId}} Unique execution identifier
{{taskId}} Agent Task identifier
{{taskName}} Task name
{{companyId}} Tenant identifier
{{status}} Completed / Failed / Timeout
{{durationMs}} Execution duration (ms)
{{timestamp}} Delivery timestamp (ISO-8601, UTC)
{{agentResponse}} Agent's text response (only when includeFullResponse: true)
{{files}} Generated files array (object shape: {fileName, url, contentType})

Rich substitution: when a value in the template is exactly a single placeholder (e.g., "to": "{{files}}"), the entire JSON node is replaced with the structured value (array/object/number/bool). This lets you nest files differently than the default shape:

{
  "bodyTemplate": "{ \"taskId\": \"{{taskId}}\", \"attachments\": \"{{files}}\" }"
}

If bodyTemplate is empty/null, the default shape above is used.

Fields (default shape):

Field Type Always Present Description
executionId string (UUID) Yes Unique execution identifier
taskId string (UUID) Yes Agent Task identifier
taskName string Yes Human-readable task name
companyId string Yes Tenant identifier
status string Yes Execution status: Completed, Failed, Timeout
durationMs number Yes Execution duration in milliseconds
timestamp string (ISO 8601) Yes Delivery timestamp (UTC)
agentResponse string Conditional Agent's text response (included when includeFullResponse is true)
files array Conditional Generated files with download URLs (present when the agent produces files)

File object:

Field Type Description
fileName string Original file name
url string Pre-signed download URL (SAS URI, time-limited)
contentType string MIME type (e.g., application/pdf, image/png)

Standard Headers

Every outbound webhook delivery includes these headers:

Header Description Example
Content-Type Always JSON application/json
X-XRCopilot-ExecutionId Execution identifier for correlation c34e88c5-b4a1-...
X-XRCopilot-TaskId Task identifier 2ff8971d-2ddf-...
X-XRCopilot-Attempt Delivery attempt number (1-based) 1
X-Idempotency-Key Deterministic {executionId}:{taskId} key for safe retry deduplication c34e88c5...:2ff8971d...

Plus any custom headers configured in the webhook output action.

Retry Policy

If your endpoint returns an error (non-2xx HTTP status), XRCopilot retries the delivery:

Setting Default Description
Max retries 3 Maximum number of retry attempts
Retry strategy Exponential backoff Via Service Bus scheduled requeue
Timeout 30 seconds Per-request timeout

Expected response: Return any 2xx status code to acknowledge successful delivery. A 200 OK with an empty body is sufficient.


Execution Lifecycle

1. Your System            POST {base-url}/hooks/{hookId}
       |                  (Ocp-Apim-Subscription-Key + X-Api-Key)
       |                                   |
       |                          2. APIM validates subscription key
       |                          3. Validate webhook API key, IP
       |                                   |
       |                          4. 202 Accepted (immediate)
       |<----------------------------------+
       |
       |                          5. Resolve template variables
       |                          6. Check daily execution quota
       |                          7. Execute AI agent (async)
       |                          8. Save execution log
       |                          9. Dispatch output actions
       |
       |                         10. POST {your-webhook-url}
       |<----------------------------------+
       |                                   |
       |         200 OK                    |
       |---------------------------------->|
       |                         11. Save delivery log

Execution Statuses

Status Description
Pending Queued, waiting for execution slot
Running Agent is currently processing
Completed Execution finished successfully
Failed Agent encountered an error
Timeout Execution exceeded the configured timeout
QuotaExceeded Daily execution limit reached

Error Handling

Quota Exceeded

Each Agent Task has a daily execution limit (default: 100). When exceeded, the task is not executed and the status is set to QuotaExceeded. The inbound webhook still returns 202 Accepted, but no agent execution occurs.

Execution Timeout

If the agent does not complete within the configured timeout (default: 300 seconds), the execution is terminated and marked as Timeout.

Delivery Failures

If the outbound webhook delivery fails after all retries, the delivery log records the failure. The execution result is still available in the execution logs and in-app inbox.


Configuration Reference

Execution Policy

Controls resource limits for the Agent Task.

Setting Default Description
timeoutSeconds 300 Max execution time before timeout (seconds)
maxRetries 0 Automatic execution retries on failure
maxDailyExecutions 100 Maximum executions per calendar day (UTC)
retryDelaySeconds 30 Delay between execution retry attempts

Webhook Output Configuration

Configuration for outbound result delivery to your system.

{
  "url": "https://your-server.example.com/api/xrcopilot-results",
  "httpMethod": "POST",
  "headers": {
    "Authorization": "Bearer your-token",
    "X-Custom-Header": "custom-value"
  },
  "maxRetries": 3,
  "includeFullResponse": true
}
Field Type Required Default Description
url string Yes — Destination URL (HTTPS recommended)
httpMethod string No POST HTTP method: GET, POST, PUT, PATCH, DELETE
headers object No null Custom HTTP headers (values encrypted at rest)
maxRetries number No 3 Max delivery retry attempts
includeFullResponse boolean No true Include agent's full text response in payload
bodyTemplate string No (default shape) Custom JSON body template; {{var}} placeholders rendered against the context
queryParams object No null Key/value query string pairs (also templated)
auth object No null Structured authentication: { type: "none"|"bearer"|"basic"|"header", secretValue, username?, headerName? }. Secrets encrypted at rest.
expectedStatusRange string No "200-299" Allowed status codes; failures outside this range trigger retry
skipWhen object No null Skip this delivery when the agent's answer matches: { "equals": "..." } (whole answer, trimmed) or { "contains": "..." }, case-insensitive. A skipped delivery is not retried and is logged as skipped

Email Output Configuration

Alternative output delivery via email.

{
  "recipients": ["user@example.com", "team@example.com"],
  "subject": "Task {{taskName}} - {{status}} ({{date}})",
  "includeFiles": true,
  "bodyFormat": "html"
}
Field Type Required Default Description
recipients string[] Yes — Email addresses
subject string No Auto-generated Subject line (supports {{taskName}}, {{status}}, {{date}} placeholders)
includeFiles boolean No true Include generated files as download links
bodyFormat string No html Body format: html or text
skipWhen object No null Skip this email when the agent's answer matches: { "equals": "..." } or { "contains": "..." }, as for webhooks

Use skipWhen for agents that check a source at intervals and have nothing to report on most runs: for example, an agent instructed to answer exactly NOTHING when it finds nothing, with "skipWhen": { "equals": "NOTHING" } on its email and webhook actions. Test deliveries sent from the Agent Task page always go out, without the rule.


Monitoring

Execution Logs

Every execution is logged with a 90-day TTL. Each log entry contains:

Field Description
executionId Unique execution identifier
status Final status (Completed, Failed, Timeout, QuotaExceeded)
triggerType How the task was triggered (Manual, Scheduled, Webhook)
input Resolved input text sent to the agent
output Agent's text response
durationMs Execution time in milliseconds
tokenUsage Token consumption (promptTokens, completionTokens, totalTokens)
files Generated files with download URLs
triggerData Original webhook payload (for Webhook triggers)
error Error details (for failed executions)
startedAt Execution start timestamp (UTC)
completedAt Execution end timestamp (UTC)

Delivery Logs

Each output action delivery (email, webhook) is tracked:

Field Description
executionId Cross-reference with execution log
actionType Email or Webhook
status delivered, failed, retrying, skipped (the skipWhen rule matched)
attemptNumber Delivery attempt number (1-based)
error Error details (for failed deliveries)
deliveredAt Successful delivery timestamp

Statistics

Aggregated statistics are available per task:

Metric Description
Status counts Number of executions by status
Average duration Mean execution time (ms)
Total tokens Cumulative token usage
Daily quota Current usage vs. configured limit
Daily breakdown Execution counts per day
Delivery counts Delivered vs. failed output actions

Security Best Practices

  1. Store credentials securely. Use a secrets manager (Azure Key Vault, AWS Secrets Manager, etc.) for both the APIM subscription key and the webhook API key — never hardcode them in source code.

  2. Use HTTPS. Both for the inbound webhook URL and your outbound delivery URL.

  3. Configure IP whitelisting. If your system has static IPs, restrict access to only those addresses.

  4. Rotate API keys periodically. Regenerate the webhook API key and update your integration.

  5. Validate outbound deliveries. Use the X-XRCopilot-ExecutionId header (or X-Idempotency-Key) to correlate and deduplicate deliveries.

  6. Monitor delivery logs. Regularly check for failed deliveries to detect connectivity issues early.

  7. Set appropriate quotas. Configure maxDailyExecutions to prevent runaway costs from misconfigured automations.


Integration Examples

cURL

# Invoke agent task
curl -X POST "https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public/hooks/wh_a1b2c3d4e5f6" \
  -H "Ocp-Apim-Subscription-Key: <YOUR_API_KEY>" \
  -H "X-Api-Key: <YOUR_WEBHOOK_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "customer_name": "Acme Corp",
    "question": "Generate the weekly sales report"
  }'

# Expected: HTTP 202 {"accepted": true}

Power Automate

  1. Add an HTTP action with:

    • Method: POST
    • URI: https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public/hooks/wh_YOUR_HOOK_ID
    • Headers:
      • Ocp-Apim-Subscription-Key: Your APIM subscription key
      • X-Api-Key: Your webhook API key
      • Content-Type: application/json
    • Body: Your dynamic content as JSON
  2. To receive results, add a When an HTTP request is received trigger and configure its URL as the outbound webhook delivery URL in XRCopilot.

See Integration-Templates for fully worked Power Automate, SharePoint, and Logic Apps recipes.

Python

import requests

BASE_URL = "https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public"
HOOK_ID = "wh_a1b2c3d4e5f6"
APIM_KEY = "<YOUR_API_KEY>"
API_KEY = "<YOUR_WEBHOOK_API_KEY>"

# Trigger agent task
response = requests.post(
    f"{BASE_URL}/hooks/{HOOK_ID}",
    headers={
        "Ocp-Apim-Subscription-Key": APIM_KEY,
        "X-Api-Key": API_KEY,
        "Content-Type": "application/json"
    },
    json={
        "customer_name": "Acme Corp",
        "question": "Generate the weekly sales report"
    }
)

print(f"Status: {response.status_code}")  # 202
print(f"Body: {response.json()}")          # {"accepted": true}

Receive results (Flask):

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/xrcopilot-results", methods=["POST"])
def receive_results():
    data = request.json
    execution_id = request.headers.get("X-XRCopilot-ExecutionId")

    print(f"Execution {execution_id}: {data['status']}")
    print(f"Agent response: {data.get('agentResponse', 'N/A')}")

    # Process files if present
    for file in data.get("files", []):
        print(f"  File: {file['fileName']} -> {file['url']}")

    return jsonify({"received": True}), 200

Node.js

const BASE_URL = "https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public";
const HOOK_ID = "wh_a1b2c3d4e5f6";

// Trigger agent task
const response = await fetch(
  `${BASE_URL}/hooks/${HOOK_ID}`,
  {
    method: "POST",
    headers: {
      "Ocp-Apim-Subscription-Key": "<YOUR_API_KEY>",
      "X-Api-Key": "<YOUR_WEBHOOK_API_KEY>",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      customer_name: "Acme Corp",
      question: "Generate the weekly sales report"
    })
  }
);

console.log(`Status: ${response.status}`); // 202
console.log(await response.json());         // { accepted: true }

Receive results (Express):

const express = require("express");
const app = express();
app.use(express.json());

app.post("/xrcopilot-results", (req, res) => {
  const executionId = req.headers["x-xrcopilot-executionid"];
  const { status, agentResponse, files } = req.body;

  console.log(`Execution ${executionId}: ${status}`);
  console.log(`Response: ${agentResponse}`);

  if (files?.length) {
    files.forEach(f => console.log(`  File: ${f.fileName} -> ${f.url}`));
  }

  res.status(200).json({ received: true });
});

app.listen(3000);

C# (.NET)

using System.Net.Http.Json;

var httpClient = new HttpClient();
var baseUrl = "https://apim-hipexr-prod-italynorth.azure-api.net/api/lab-public";
var hookId = "wh_a1b2c3d4e5f6";

// Trigger agent task
var request = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}/hooks/{hookId}");
request.Headers.Add("Ocp-Apim-Subscription-Key", "<YOUR_API_KEY>");
request.Headers.Add("X-Api-Key", "<YOUR_WEBHOOK_API_KEY>");
request.Content = JsonContent.Create(new
{
    customer_name = "Acme Corp",
    question = "Generate the weekly sales report"
});

var response = await httpClient.SendAsync(request);
Console.WriteLine($"Status: {response.StatusCode}"); // 202 Accepted

Receive results (ASP.NET Minimal API):

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapPost("/xrcopilot-results", (HttpRequest req, WebhookPayload payload) =>
{
    var executionId = req.Headers["X-XRCopilot-ExecutionId"].FirstOrDefault();
    Console.WriteLine($"Execution {executionId}: {payload.Status}");
    Console.WriteLine($"Response: {payload.AgentResponse}");
    return Results.Ok(new { received = true });
});

app.Run();

record WebhookPayload(
    string ExecutionId,
    string TaskId,
    string TaskName,
    string Status,
    long DurationMs,
    string? AgentResponse,
    List<FileInfo>? Files);

record FileInfo(string FileName, string Url, string ContentType);

Rate Limits and Quotas

Limit Default Configurable
Daily executions per task 100 Yes (maxDailyExecutions)
Execution timeout 300s Yes (timeoutSeconds)
Outbound webhook timeout 30s No (platform setting)
Outbound delivery retries 3 Yes (maxRetries)
Inbound payload size ~100 MB No (platform limit)

Changelog

Version Date Changes
1.2 2026-05-22 Templated body + structured auth + query params + idempotency key. Default body preserves legacy shape (no migration required). GET/DELETE now supported.
1.1 2026-03-20 Updated URLs to APIM gateway, added APIM subscription key authentication
1.0 2026-03-20 Initial release — webhook trigger, email/webhook output delivery, monitoring

See Also

Clone this wiki locally