> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloudshipai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Event-Triggered Execution

> Trigger agent execution from external systems via HTTP webhooks

# Event-Triggered Execution

Trigger agent execution from external systems via HTTP webhook. Perfect for integrating with CI/CD pipelines, alerting systems, or any automation that can make HTTP requests.

## Endpoint

```
POST http://localhost:8587/execute
```

Port 8587 is the Dynamic Agent MCP server, which also serves the webhook endpoint.

## Request Format

```bash theme={null}
# Trigger by agent name
curl -X POST http://localhost:8587/execute \
  -H "Content-Type: application/json" \
  -d '{"agent_name": "incident_coordinator", "task": "Investigate the API timeout alert"}'

# Trigger by agent ID
curl -X POST http://localhost:8587/execute \
  -H "Content-Type: application/json" \
  -d '{"agent_id": 21, "task": "Check system health"}'
```

### Request Parameters

| Field        | Type    | Required       | Description                      |
| ------------ | ------- | -------------- | -------------------------------- |
| `agent_name` | string  | One of name/id | Agent name to execute            |
| `agent_id`   | integer | One of name/id | Agent ID to execute              |
| `task`       | string  | Yes            | Task/prompt for the agent        |
| `variables`  | object  | No             | Variables for template rendering |

### With Variables

```bash theme={null}
curl -X POST http://localhost:8587/execute \
  -H "Content-Type: application/json" \
  -d '{
    "agent_name": "cost_analyzer",
    "task": "Analyze costs for project",
    "variables": {"project_id": "prod-123", "region": "us-east-1"}
  }'
```

## Response

### Success (202 Accepted)

```json theme={null}
{
  "run_id": 120,
  "agent_id": 21,
  "agent_name": "incident_coordinator",
  "status": "running",
  "message": "Agent execution started"
}
```

### Error (400/401/404)

```json theme={null}
{
  "error": "agent not found",
  "message": "No agent with name 'unknown_agent'"
}
```

## Authentication

### Local Mode (Default)

No authentication required when running locally.

### Production

Set a static API key:

```bash theme={null}
export STN_WEBHOOK_API_KEY="your-secret-key"
```

Include in requests:

```bash theme={null}
curl -X POST http://localhost:8587/execute \
  -H "Authorization: Bearer your-secret-key" \
  -H "Content-Type: application/json" \
  -d '{"agent_name": "my-agent", "task": "Do something"}'
```

### CloudShip OAuth

When CloudShip OAuth is enabled, webhook requests use the same OAuth flow as MCP clients.

## Integration Examples

### PagerDuty

Auto-investigate when alerts fire:

```bash theme={null}
curl -X POST https://your-station:8587/execute \
  -H "Authorization: Bearer $STN_WEBHOOK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_name": "incident_coordinator",
    "task": "PagerDuty alert: High CPU usage on payment-service"
  }'
```

### GitHub Actions

Trigger analysis on deployment:

```yaml theme={null}
# .github/workflows/deploy.yml
- name: Run deployment analyzer
  run: |
    curl -X POST ${{ secrets.STATION_URL }}/execute \
      -H "Authorization: Bearer ${{ secrets.STATION_API_KEY }}" \
      -H "Content-Type: application/json" \
      -d '{
        "agent_name": "deployment_analyzer",
        "task": "Analyze deployment ${{ github.sha }}",
        "variables": {
          "commit": "${{ github.sha }}",
          "branch": "${{ github.ref_name }}"
        }
      }'
```

### Datadog Monitor

Trigger from Datadog webhook:

```json theme={null}
{
  "agent_name": "metrics_investigator",
  "task": "Investigate alert: {{alertTitle}} - {{alertScope}}",
  "variables": {
    "alert_id": "{{alertId}}",
    "severity": "{{alertPriority}}"
  }
}
```

### Slack Slash Command

Create a Slack app that posts to your Station:

```bash theme={null}
# Slack sends: /investigate high memory on api-gateway

curl -X POST https://your-station:8587/execute \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "agent_name": "incident_coordinator",
    "task": "high memory on api-gateway"
  }'
```

### Prometheus Alertmanager

Configure alertmanager webhook:

```yaml theme={null}
# alertmanager.yml
receivers:
  - name: 'station'
    webhook_configs:
      - url: 'https://your-station:8587/execute'
        http_config:
          bearer_token: 'your-api-key'
        send_resolved: true
```

## Configuration

### Enable/Disable

```bash theme={null}
# Enable webhook (default: true)
export STN_WEBHOOK_ENABLED=true

# Disable webhook
export STN_WEBHOOK_ENABLED=false
```

### API Key

```bash theme={null}
# Set static API key for authentication
export STN_WEBHOOK_API_KEY="your-secret-key"
```

### In config.yaml

```yaml theme={null}
# config.yaml
webhook:
  enabled: true
  api_key: "{{ .STN_WEBHOOK_API_KEY }}"
```

## Checking Run Status

After triggering, use the `run_id` to check status:

```bash theme={null}
# Via API
curl http://localhost:8585/api/v1/runs/120

# Via CLI
stn runs inspect 120

# Via MCP tool
"Inspect run 120"
```

## Async Execution

Webhook triggers are **asynchronous** - the response returns immediately with a `run_id`. The agent executes in the background.

To wait for completion, poll the run status:

```bash theme={null}
# Poll until complete
while true; do
  status=$(curl -s http://localhost:8585/api/v1/runs/120 | jq -r '.status')
  if [ "$status" = "completed" ] || [ "$status" = "error" ]; then
    break
  fi
  sleep 2
done
```

## Security Considerations

1. **Always use API keys in production** - Never expose unauthenticated webhooks
2. **Use HTTPS** - Encrypt webhook traffic
3. **Validate sources** - Consider IP allowlisting for known sources
4. **Rate limiting** - Station doesn't rate limit by default; use a reverse proxy
5. **Audit logs** - All webhook executions are logged with source info

## Troubleshooting

### Connection Refused

```
Error: connection refused
```

**Check:**

1. Station is running: `stn status`
2. Port 8587 is accessible
3. Firewall allows inbound connections

### 401 Unauthorized

```
Error: 401 Unauthorized
```

**Check:**

1. `STN_WEBHOOK_API_KEY` is set on Station
2. Request includes `Authorization: Bearer <key>` header
3. Key matches exactly

### Agent Not Found

```
Error: agent not found
```

**Check:**

1. Agent name is correct (case-sensitive)
2. Agent exists: `stn agent list`
3. Agent is enabled

### Run Fails

Check run details:

```bash theme={null}
stn runs inspect <run_id>
```

Common issues:

* Agent prompt errors
* MCP tool failures
* Timeout exceeded

## Comparison: Webhooks vs Notify

| Feature   | Webhooks (this page)             | Notify Tool             |
| --------- | -------------------------------- | ----------------------- |
| Direction | External → Station               | Station → External      |
| Purpose   | Trigger agents                   | Send notifications      |
| Endpoint  | `POST /execute`                  | Configured webhook URL  |
| Example   | PagerDuty triggers investigation | Agent sends Slack alert |

See [Notifications](/station/notifications) for outbound notifications.

## Next Steps

* [Notifications](/station/notifications) - Outbound notifications from agents
* [Scheduling](/station/scheduling) - Cron-based execution
* [Observability](/station/observability) - Monitor webhook executions
