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

# n8n Integration Guide for Encore Health OS

> Version: 1.0.0 Last Updated: 2025-11-25 Core: FW (Forms & Workflow) Related Specs: FW-03 Automation Engine

**Version:** 1.0.0\
**Last Updated:** 2025-11-25\
**Core:** FW (Forms & Workflow)\
**Related Specs:** [FW-03 Automation Engine](../../specs/fw/archive/FW-03-automation-engine.md)

***

## Table of Contents

1. [Introduction & Overview](#introduction--overview)
2. [Architecture & Data Flow](#architecture--data-flow)
3. [n8n Setup Guide](#n8n-setup-guide)
4. [Encore Health OS Configuration](#encore-health-os-configuration)
5. [Data Mapping Reference](#data-mapping-reference)
6. [Security Best Practices](#security-best-practices)
7. [Common Integration Patterns](#common-integration-patterns)
8. [Troubleshooting Guide](#troubleshooting-guide)
9. [Advanced: MCP Integration](#advanced-mcp-integration)

***

## Introduction & Overview

### Purpose

This guide documents how to connect Encore Health OS's automation engine (FW-03) to n8n workflows via webhooks, enabling advanced external integrations and multi-step orchestration.

### Hybrid Approach

Encore Health OS and n8n complement each other:

* **Encore Health OS (FW-03 Engine)**: Internal workflows, tenant-scoped automations, database operations
* **n8n**: External integrations, visual workflow design, complex branching logic, 400+ pre-built connectors

### When to Use n8n

Use n8n for workflows that require:

* ✅ **External SaaS integrations** (Salesforce, HubSpot, Slack, Google Workspace)
* ✅ **Complex branching logic** (if/else, switch, loops)
* ✅ **Multi-step orchestration** (approval chains, escalation workflows)
* ✅ **Visual workflow design** (drag-and-drop, no-code)
* ✅ **Error handling & retries** (advanced fault tolerance)
* ✅ **Data transformation** (JSON manipulation, aggregation)

### When to Use Encore Health OS (FW-03)

Use Encore Health OS's built-in engine for:

* ✅ **Tenant-scoped automations** (org/site-specific rules)
* ✅ **Database operations** (create/update records with RLS)
* ✅ **Internal notifications** (via Platform Notifications)
* ✅ **Simple webhooks** (one-off API calls)
* ✅ **Form validations** (immediate feedback)

***

## Architecture & Data Flow

### High-Level Flow

```
┌─────────────────────────────────────────────────────────────────────┐
│                        Encore Health OS Platform                          │
│                                                                     │
│  ┌──────────────┐     ┌─────────────────┐     ┌─────────────────┐ │
│  │ Form Submit  │────▶│ FW-03 Automation│────▶│ Call Webhook    │ │
│  │  (Trigger)   │     │ Rules Engine    │     │    Action       │ │
│  └──────────────┘     └─────────────────┘     └────────┬────────┘ │
│                                                         │          │
└─────────────────────────────────────────────────────────┼──────────┘
                                                          │
                                        HTTPS POST        │
                                        (JSON payload)    │
                                                          ▼
┌─────────────────────────────────────────────────────────────────────┐
│                            n8n Workflow                             │
│                                                                     │
│  ┌──────────────┐     ┌─────────────────┐     ┌─────────────────┐ │
│  │   Webhook    │────▶│  Process Data   │────▶│  External API   │ │
│  │   Trigger    │     │ (Transform/Map) │     │ (Slack, CRM...)  │ │
│  └──────────────┘     └─────────────────┘     └─────────────────┘ │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

### Data Format

Encore Health OS sends webhook payloads in this format:

```json theme={null}
{
  "trigger_type": "form_submission",
  "trigger_data": {
    "submission_id": "uuid",
    "form_id": "uuid",
    "form_name": "Employee Onboarding Form",
    "submission_data": {
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "start_date": "2025-12-01"
    },
    "submitted_by": "uuid",
    "submitted_at": "2025-11-25T10:30:00Z",
    "organization_id": "uuid",
    "site_id": "uuid"
  },
  "rule_id": "uuid",
  "rule_name": "New Hire Notification",
  "timestamp": "2025-11-25T10:30:05Z"
}
```

***

## n8n Setup Guide

### Step 1: Create a New Workflow

1. Log into your n8n instance
2. Click **"New Workflow"**
3. Give it a descriptive name (e.g., "Encore Health OS Form to Slack")

### Step 2: Add Webhook Trigger

1. Click **"Add first step"**
2. Search for **"Webhook"** and select it
3. Configure webhook settings:
   * **HTTP Method**: `POST`
   * **Path**: Leave default or customize (e.g., `/encore-health-os/form-submission`)
   * **Authentication**: Choose based on security needs (see [Security](#security-best-practices))
   * **Response Mode**: `Last Node` (if n8n needs to return data)

### Step 3: Get Webhook URL

1. Click **"Listen for Test Event"** or **"Listen for Production Event"**
2. Copy the webhook URL (e.g., `https://your-n8n-instance.com/webhook/abc123`)
3. **Important**: Use the **Production URL** for live automations

### Step 4: Test Webhook

1. Keep n8n in "Listen" mode
2. Send a test POST request:
   ```bash theme={null}
   curl -X POST https://your-n8n-instance.com/webhook/abc123 \
     -H "Content-Type: application/json" \
     -d '{"test": "data"}'
   ```
3. Verify n8n receives the payload

### Step 5: Build Workflow Logic

Example: Send Slack notification

1. Add **"Slack"** node
2. Select **"Send Message"** operation
3. Map webhook data:
   * **Channel**: `#new-hires`
   * **Message**:
     ```
     New employee starting: {{$json.trigger_data.submission_data.first_name}} {{$json.trigger_data.submission_data.last_name}}
     Start Date: {{$json.trigger_data.submission_data.start_date}}
     ```

### Step 6: Activate Workflow

1. Click **"Save"** in the top right
2. Toggle **"Active"** to enable the workflow
3. The webhook is now live and ready to receive data from Encore Health OS

***

## Encore Health OS Configuration

### Step 1: Create Automation Rule

1. Navigate to **Forms & Workflow → Automations**
2. Click **"Create Automation"**
3. Configure trigger:
   * **Trigger Type**: `Form Submission`
   * **Form**: Select target form (e.g., "Employee Onboarding Form")

### Step 2: Add Conditions (Optional)

Add conditions to filter when the automation runs:

```
Field: "employment_type"
Operator: "equals"
Value: "Full-Time"
```

### Step 3: Add "Call Webhook" Action

1. Click **"Add Action"**
2. Select **"Call Webhook"**
3. Configure webhook action:
   * **URL**: Paste your n8n webhook URL
   * **Method**: `POST`
   * **Headers**:
     ```json theme={null}
     {
       "Content-Type": "application/json",
       "Authorization": "Bearer YOUR_SECRET_TOKEN"
     }
     ```
   * **Body Template**: Use dynamic values (see [Data Mapping](#data-mapping-reference))

### Step 4: Configure Body Template

Example body template with dynamic values:

```json theme={null}
{
  "employee": {
    "first_name": "{{submission_data.first_name}}",
    "last_name": "{{submission_data.last_name}}",
    "email": "{{submission_data.email}}",
    "start_date": "{{submission_data.start_date}}"
  },
  "metadata": {
    "form_id": "{{form_id}}",
    "form_name": "{{form_name}}",
    "submitted_at": "{{submitted_at}}",
    "organization_id": "{{organization_id}}"
  }
}
```

### Step 5: Test with Dry Run

1. Click **"Test Automation"**
2. Select **"Dry Run"** mode
3. Submit a test form or use sample data
4. Check n8n workflow execution logs
5. Verify data mapping is correct

### Step 6: Activate Automation

1. Set **Status**: `Active`
2. Set **Requires Approval**: `false` (for trusted workflows)
3. Click **"Save"**

***

## Data Mapping Reference

### Available Trigger Data Fields

When an automation is triggered by a form submission, the following fields are available for dynamic mapping:

| Field Path          | Type     | Description          | Example                  |
| ------------------- | -------- | -------------------- | ------------------------ |
| `submission_id`     | UUID     | Unique submission ID | `"a1b2c3d4-..."`         |
| `form_id`           | UUID     | Form ID              | `"e5f6g7h8-..."`         |
| `form_name`         | String   | Form name            | `"Employee Onboarding"`  |
| `submission_data.*` | Object   | Form field values    | See below                |
| `submitted_by`      | UUID     | User who submitted   | `"i9j0k1l2-..."`         |
| `submitted_at`      | ISO 8601 | Submission timestamp | `"2025-11-25T10:30:00Z"` |
| `organization_id`   | UUID     | Tenant organization  | `"m3n4o5p6-..."`         |
| `site_id`           | UUID     | Site (if scoped)     | `"q7r8s9t0-..."`         |

### Dynamic Value Syntax

Use `{{path.to.field}}` syntax to reference trigger data:

#### Simple Field Access

```json theme={null}
{
  "email": "{{submission_data.email}}",
  "phone": "{{submission_data.phone}}"
}
```

#### Nested Field Access

```json theme={null}
{
  "contact": {
    "first_name": "{{submission_data.contact.first_name}}",
    "last_name": "{{submission_data.contact.last_name}}"
  }
}
```

#### Metadata Fields

```json theme={null}
{
  "source": "Encore Health OS",
  "form_name": "{{form_name}}",
  "timestamp": "{{submitted_at}}"
}
```

### Example Mappings

#### Slack Notification

```json theme={null}
{
  "channel": "#new-hires",
  "text": "New employee {{submission_data.first_name}} {{submission_data.last_name}} starting on {{submission_data.start_date}}",
  "metadata": {
    "form_id": "{{form_id}}",
    "submitted_at": "{{submitted_at}}"
  }
}
```

#### CRM Update (Salesforce, HubSpot)

```json theme={null}
{
  "contact": {
    "email": "{{submission_data.email}}",
    "firstName": "{{submission_data.first_name}}",
    "lastName": "{{submission_data.last_name}}",
    "phone": "{{submission_data.phone}}",
    "company": "{{organization_id}}",
    "properties": {
      "start_date": "{{submission_data.start_date}}",
      "employment_type": "{{submission_data.employment_type}}"
    }
  }
}
```

#### Google Sheets Row

```json theme={null}
{
  "values": [
    "{{submission_data.first_name}}",
    "{{submission_data.last_name}}",
    "{{submission_data.email}}",
    "{{submission_data.start_date}}",
    "{{submitted_at}}"
  ]
}
```

***

## Security Best Practices

### 1. Always Use HTTPS

❌ **Never use HTTP webhooks**:

```
http://your-n8n-instance.com/webhook/abc123  # ❌ Insecure
```

✅ **Always use HTTPS**:

```
https://your-n8n-instance.com/webhook/abc123  # ✅ Secure
```

### 2. Implement Authentication

n8n supports multiple authentication methods:

#### Option A: Header Authentication (Recommended)

```json theme={null}
{
  "Authorization": "Bearer YOUR_SECRET_TOKEN"
}
```

Configure in n8n:

* Webhook settings → **Authentication** → **Header Auth**
* **Header Name**: `Authorization`
* **Header Value**: `Bearer YOUR_SECRET_TOKEN`

#### Option B: Basic Authentication

```json theme={null}
{
  "Authorization": "Basic base64(username:password)"
}
```

#### Option C: Query Parameter (Less Secure)

```
https://your-n8n-instance.com/webhook/abc123?token=YOUR_SECRET
```

### 3. Protect Sensitive Data

* **Never log PHI/PII** in webhook bodies or n8n logs
* Use **encrypted storage** in n8n for credentials
* Implement **field-level encryption** for sensitive submission data

### 4. Rate Limiting & Circuit Breaker

Encore Health OS's FW-03 engine includes:

* **Circuit breaker**: Trips after 5 consecutive failures
* **Timeout**: 30-second webhook timeout
* **Retry logic**: 3 retries with exponential backoff

Configure n8n to handle:

* **Rate limits** on external APIs
* **Error responses** (return 4xx/5xx appropriately)

### 5. IP Whitelisting (Optional)

If n8n is self-hosted:

1. Get Encore Health OS's outbound IP addresses
2. Configure firewall rules to allow only those IPs
3. Blocks unauthorized webhook calls

### 6. Audit Logging

* Enable **automation logs** in Encore Health OS (automatic)
* Enable **execution logs** in n8n
* Review logs regularly for anomalies

***

## Common Integration Patterns

### Pattern 1: Form → n8n → Slack Notification

**Use Case**: Notify team when a new form is submitted

**Encore Health OS Setup**:

1. Trigger: Form submission on "Contact Form"
2. Action: Call webhook to n8n

**n8n Workflow**:

1. **Webhook** (receive form data)
2. **Slack** → Send message to `#inquiries`
   * Message: `New inquiry from {{submission_data.name}} ({{submission_data.email}})`

**Webhook Body**:

```json theme={null}
{
  "name": "{{submission_data.name}}",
  "email": "{{submission_data.email}}",
  "message": "{{submission_data.message}}"
}
```

***

### Pattern 2: Form → n8n → Google Sheets

**Use Case**: Log form submissions to a Google Sheet for analysis

**Encore Health OS Setup**:

1. Trigger: Form submission on "Event Registration"
2. Action: Call webhook to n8n

**n8n Workflow**:

1. **Webhook** (receive form data)
2. **Google Sheets** → Append row
   * Sheet ID: `your-sheet-id`
   * Values: `[name, email, event_date, submitted_at]`

**Webhook Body**:

```json theme={null}
{
  "name": "{{submission_data.name}}",
  "email": "{{submission_data.email}}",
  "event_date": "{{submission_data.event_date}}",
  "submitted_at": "{{submitted_at}}"
}
```

***

### Pattern 3: Form → n8n → CRM Update (Salesforce/HubSpot)

**Use Case**: Create or update contact in CRM when form is submitted

**Encore Health OS Setup**:

1. Trigger: Form submission on "Lead Capture Form"
2. Action: Call webhook to n8n

**n8n Workflow**:

1. **Webhook** (receive form data)
2. **HubSpot** → Create or Update Contact
   * Email: `{{submission_data.email}}`
   * First Name: `{{submission_data.first_name}}`
   * Last Name: `{{submission_data.last_name}}`
   * Properties: Map additional fields

**Webhook Body**:

```json theme={null}
{
  "contact": {
    "email": "{{submission_data.email}}",
    "first_name": "{{submission_data.first_name}}",
    "last_name": "{{submission_data.last_name}}",
    "company": "{{submission_data.company}}",
    "phone": "{{submission_data.phone}}"
  }
}
```

***

### Pattern 4: Form → n8n → Multi-Step Approval

**Use Case**: Form submission triggers approval workflow with escalation

**Encore Health OS Setup**:

1. Trigger: Form submission on "Expense Request"
2. Condition: Amount > \$1000
3. Action: Call webhook to n8n

**n8n Workflow**:

1. **Webhook** (receive expense data)
2. **Slack** → Send approval request to manager
3. **Wait for Webhook** (manager response)
4. **IF** approved:
   * **Email** → Notify requester (approved)
   * **Database** → Update expense status
5. **IF** denied:
   * **Email** → Notify requester (denied with reason)

**Webhook Body**:

```json theme={null}
{
  "expense": {
    "amount": "{{submission_data.amount}}",
    "description": "{{submission_data.description}}",
    "category": "{{submission_data.category}}",
    "requested_by": "{{submitted_by}}",
    "submitted_at": "{{submitted_at}}"
  },
  "approver": "{{submission_data.manager_email}}"
}
```

***

### Pattern 5: Scheduled Trigger → n8n → Report Generation

**Use Case**: Generate weekly compliance report

**Encore Health OS Setup**:

1. Trigger: Scheduled (every Monday at 9 AM)
2. Action: Call webhook to n8n

**n8n Workflow**:

1. **Webhook** (receive trigger)
2. **Encore Health OS API** → Fetch compliance data (via custom function)
3. **Google Sheets** → Create new sheet with data
4. **Email** → Send report link to compliance team

***

## Troubleshooting Guide

### Issue 1: Webhook Not Triggering

**Symptoms**: n8n workflow doesn't execute when automation runs

**Diagnostic Steps**:

1. Check **Encore Health OS automation logs**:
   * Navigate to **Automations → \[Your Rule] → Logs**
   * Look for `execution_status: "failed"` or timeout errors
2. Verify **webhook URL** is correct (copy from n8n production URL)
3. Check **n8n workflow** is **Active** (not paused)
4. Test webhook manually:
   ```bash theme={null}
   curl -X POST https://your-n8n-instance.com/webhook/abc123 \
     -H "Content-Type: application/json" \
     -d '{"test": "manual_trigger"}'
   ```

**Common Fixes**:

* ✅ Ensure URL uses HTTPS
* ✅ Check firewall rules allow outbound connections
* ✅ Verify n8n instance is reachable from Encore Health OS

***

### Issue 2: Authentication Errors (401/403)

**Symptoms**: Webhook returns `401 Unauthorized` or `403 Forbidden`

**Diagnostic Steps**:

1. Check **Encore Health OS automation logs** for HTTP status code
2. Verify **authentication headers** match n8n webhook configuration
3. Test authentication with curl:
   ```bash theme={null}
   curl -X POST https://your-n8n-instance.com/webhook/abc123 \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"test": "auth_test"}'
   ```

**Common Fixes**:

* ✅ Re-generate authentication token in n8n
* ✅ Update token in Encore Health OS webhook headers
* ✅ Check header name matches (e.g., `Authorization` vs `X-API-Key`)

***

### Issue 3: Data Mapping Errors

**Symptoms**: n8n receives payload but fields are `null` or incorrect

**Diagnostic Steps**:

1. Use **Encore Health OS dry-run mode**:
   * Test automation with sample data
   * Check execution logs for payload sent
2. Check **n8n execution logs**:
   * View received payload in webhook node output
   * Verify field paths match expected structure
3. Compare **expected vs actual** payload structure

**Common Fixes**:

* ✅ Use correct field paths: `{{submission_data.field_name}}`
* ✅ Check for nested fields: `{{submission_data.nested.field}}`
* ✅ Verify form field keys match (case-sensitive)

**Example Debug**:

```json theme={null}
// Expected
{"email": "{{submission_data.email}}"}

// Actual (if null)
{"email": null}

// Fix: Check form field key
// Is it "email" or "Email" or "email_address"?
```

***

### Issue 4: Timeout Errors

**Symptoms**: Automation logs show `execution_status: "timeout"`

**Diagnostic Steps**:

1. Check **n8n execution time** in workflow logs
2. Identify **slow nodes** (external API calls, large data processing)
3. Test n8n workflow execution time manually

**Common Fixes**:

* ✅ Optimize n8n workflow (reduce API calls, use caching)
* ✅ Increase timeout in Encore Health OS (30s default, max 60s)
* ✅ Split complex workflows into multiple steps

***

### Issue 5: Circuit Breaker Tripped

**Symptoms**: Automation stops executing after multiple failures

**Diagnostic Steps**:

1. Check **automation status** in Encore Health OS:
   * Look for `circuit_breaker_tripped: true`
   * Review `consecutive_failures` count
2. Check **n8n error logs** for failure reasons

**Common Fixes**:

* ✅ Fix underlying n8n workflow issue
* ✅ Reset circuit breaker in Encore Health OS:
  * Edit automation rule
  * Save (resets circuit breaker)
* ✅ Monitor for recurring failures

***

### Debugging Checklist

* [ ] Webhook URL is correct and uses HTTPS
* [ ] n8n workflow is **Active**
* [ ] Authentication headers are correct
* [ ] Data mapping uses correct field paths
* [ ] n8n workflow completes within timeout (30s)
* [ ] Encore Health OS automation status is **Active**
* [ ] Circuit breaker is not tripped
* [ ] Firewall allows outbound HTTPS connections
* [ ] n8n instance is reachable from Encore Health OS

***

## Advanced: MCP Integration

### What is n8n MCP?

The **n8n MCP (Model Context Protocol) server** allows Encore Health OS's AI agent to:

* **Execute n8n workflows** during app building
* **Query workflow definitions** for documentation
* **Create bidirectional integrations** (Encore Health OS ↔ n8n)

### When to Use MCP vs Webhooks

| Capability                             | Webhooks             | n8n MCP               |
| -------------------------------------- | -------------------- | --------------------- |
| **Trigger workflows from automations** | ✅ Primary            | ⚡ Alternative         |
| **Return data to Encore Health OS**    | ⚡ Limited (200 char) | ✅ Full response       |
| **AI agent workflow execution**        | ❌ N/A                | ✅ Primary             |
| **Bidirectional workflows**            | ⚡ Complex            | ✅ Native              |
| **Setup complexity**                   | ✅ Simple             | ⚡ Requires MCP config |

### Setting Up n8n MCP

See the n8n official documentation for MCP integration setup instructions.

**Prerequisites**:

1. Enable **MCP access** in n8n (Settings → MCP access)
2. Enable **"Available in MCP"** for each workflow (workflow settings)
3. Connect n8n MCP server in Encore Health OS (Project Settings → Integrations)

### MCP Use Case: Bidirectional Workflow

**Scenario**: Form submission triggers n8n workflow, n8n updates Encore Health OS database

**Encore Health OS Setup**:

1. Form submission triggers automation
2. Automation calls n8n webhook
3. n8n workflow processes data
4. n8n calls **Encore Health OS Edge Function** (via MCP) to update database

**n8n Workflow**:

1. Webhook (receive form data)
2. External API (e.g., validate address via Google Maps)
3. HTTP Request → Encore Health OS Edge Function (update database with validated address)

**Benefits**:

* ✅ Complex external processing in n8n
* ✅ Database updates maintain RLS policies
* ✅ Full error handling and logging

***

## Summary

### Quick Start Checklist

1. ✅ Create webhook trigger in n8n
2. ✅ Copy production webhook URL
3. ✅ Create automation rule in Encore Health OS
4. ✅ Add "Call Webhook" action with URL and auth
5. ✅ Map trigger data using `{{field}}` syntax
6. ✅ Test with dry-run mode
7. ✅ Activate automation and n8n workflow
8. ✅ Monitor logs for successful executions

### Best Practices

* ✅ Always use HTTPS webhooks
* ✅ Implement authentication (Bearer token recommended)
* ✅ Test with dry-run mode before activating
* ✅ Monitor automation and n8n execution logs
* ✅ Document complex workflows
* ✅ Use circuit breakers for fault tolerance
* ✅ Never log sensitive data (PHI/PII)

### Resources

* [FW-03 Automation Engine Spec](../../specs/fw/archive/FW-03-automation-engine.md)
* [Automation Security Guide](../security/AUTOMATION_SECURITY.md)
* [Integration Documentation](../architecture/integrations/index.md)
* [n8n Official Documentation](https://docs.n8n.io/)

***

**Questions or Issues?** Contact the platform team or review automation logs in **Forms & Workflow → Automations → \[Your Rule] → Logs**.
