> ## Documentation Index
> Fetch the complete documentation index at: https://kapso-1adbad2d.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent webhooks

> Two-way communication between your systems and Kapso agents

Webhooks allow two-way communication: your systems can trigger Kapso agents, and Kapso agents can notify your systems.

## Incoming webhooks (triggering agents)

Use incoming webhooks to start an agent's execution flow from your application (e.g., backend, CRM).

**Endpoint:** Each agent has a unique webhook URL.

```
POST https://app.kapso.ai/api/v1/agents/{AGENT_ID}/executions
```

**Authentication:** Include your Project API Key in the `X-API-Key` request header.

```
X-API-Key: your-project-api-key
```

**Request body (optional):** Send initial data in the JSON payload.

```json theme={null}
{
  "message": "Optional initial message for the agent",
  "phone_number": "1234567890" // Optional identifier
}
```

**Example (Node.js):**

```javascript theme={null}
const agentWebhookUrl = 'https://app.kapso.ai/api/v1/agents/YOUR_AGENT_ID/executions';
const apiKey = 'YOUR_PROJECT_API_KEY';

const payload = JSON.stringify({
  message: 'Hello agent!',
  phone_number: '1987654321'
});

fetch(agentWebhookUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': apiKey
  },
  body: payload
})
.then(response => response.json())
.then(data => console.log('Agent execution started:', data))
.catch(error => console.error('Error triggering agent:', error));
```

## Outbound webhooks (agent notifications)

Configure your agents to send real-time notifications to your systems when important events occur during execution.

### Configuration

1. Navigate to your agent's "API & Webhooks" settings
2. Add webhook endpoints for the events you want to monitor
3. Configure a **Secret Key** for request verification
4. Select which events to subscribe to

### Supported events

<CardGroup cols={2}>
  <Card title="Execution started" icon="play">
    `agent_execution_started`

    Fired when an agent begins processing
  </Card>

  <Card title="Execution ended" icon="check">
    `agent_execution_ended`

    Fired when an agent completes successfully
  </Card>

  <Card title="Execution failed" icon="xmark">
    `agent_execution_failed`

    Fired when an agent encounters an error
  </Card>

  <Card title="Handoff required" icon="hand">
    `agent_execution_handoff`

    Fired when human intervention is needed
  </Card>
</CardGroup>

### Security & verification

Every webhook request includes an `X-Webhook-Signature` header containing an HMAC SHA-256 signature of the request body. Verify this signature using your configured Secret Key to ensure authenticity.

<CodeGroup>
  ```javascript Node.js theme={null}
  const crypto = require('crypto');

  function verifyWebhookSignature(body, signature, secret) {
    const expectedSignature = crypto
      .createHmac('sha256', secret)
      .update(body, 'utf8')
      .digest('hex');

    return signature === expectedSignature;
  }
  ```

  ```python Python theme={null}
  import hmac
  import hashlib

  def verify_webhook_signature(body, signature, secret):
      expected_signature = hmac.new(
          secret.encode('utf-8'),
          body.encode('utf-8'),
          hashlib.sha256
      ).hexdigest()

      return signature == expected_signature
  ```
</CodeGroup>

### Webhook payloads

All webhook payloads include base execution data plus event-specific information:

#### Base payload structure

```json theme={null}
{
  "event": "event_type",
  "agent_execution": {
    "id": "exec_123abc",
    "started_at": "2024-01-01T12:00:00Z",
    "ended_at": "2024-01-01T12:05:00Z", // null if still running
    "status": "completed", // started, completed, failed, handoff
    "agent_id": "agent_456def"
  },
  "agent": {
    "id": "agent_456def",
    "name": "Customer Support Agent"
  }
}
```

#### Event-specific data

**Handoff event** includes handoff details:

```json theme={null}
{
  "event": "agent_execution_handoff",
  // ... base payload ...
  "handoff": {
    "node_name": "Escalate to Human",
    "handoff_datetime": "2024-01-01T12:04:30Z",
    "handoff_reason": "Customer requested to speak with a human"
  }
}
```

**Failed event** includes error information:

```json theme={null}
{
  "event": "agent_execution_failed",
  // ... base payload ...
  "failure": {
    "error": {
      "message": "Failed to connect to external API",
      "type": "ConnectionError"
    },
    "failed_at": "2024-01-01T12:03:15Z"
  }
}
```

### Best practices

<Note>
  **Important considerations:**

  * Respond quickly (within 5 seconds) with a 2xx status code
  * Process webhook data asynchronously if needed
  * Store the webhook secret securely
  * Always verify webhook signatures
  * Implement idempotency handling using the provided idempotency key
</Note>
