# 7. Integrations

## External Service Dependencies

### 1. Anthropic Claude API (Critical)

**Purpose:** Core AI engine powering all chat, analysis, and automation features.

| Property | Value |
|----------|-------|
| **API endpoint** | `https://api.anthropic.com/v1/messages` |
| **Auth method** | API key via `ANTHROPIC_API_KEY` |
| **Transport** | HTTPS (direct API) and Claude CLI process |
| **Used by** | Chat sessions, skill execution, meeting analysis, onboarding research, commit message generation |
| **Rate limits** | Anthropic tier-based (varies by plan) |
| **Failure handling** | Error surfaced to user in chat, no automatic retry |
| **Cost tracking** | `usage_events` table records tokens and calculated cost per exchange |

**System prompt injection pipeline:**
1. Base persona context (if persona active)
2. Guide context (if guides applied)
3. Plan mode ExitPlanMode instruction
4. AskUserQuestion instruction (always)
5. Bedrock passthrough (if Bedrock active)
6. Content reader file-based prompts

**Extended context (1M tokens):**
- Enabled via Bedrock configuration or Anthropic beta headers
- Requires acknowledgment audit (`bedrock_context_audit` table)
- Custom headers: `ANTHROPIC_CUSTOM_HEADERS`, `ANTHROPIC_BETAS`

### 2. AWS Bedrock (Optional)

**Purpose:** Alternative AI provider for organizations requiring AWS-managed Claude access.

| Property | Value |
|----------|-------|
| **SDK** | `@aws-sdk/client-bedrock`, `@aws-sdk/client-bedrock-runtime` |
| **Auth method** | AWS access key + secret key, or bearer token |
| **Env vars** | `AWS_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_BEARER_TOKEN_BEDROCK` |
| **Config storage** | `bedrock_config` table (single row, encrypted) |
| **Model discovery** | `discoverAccessibleModels()` tests hardcoded model list |
| **Service file** | `server/services/bedrockService.js` |

**Model configuration locations (4 hardcoded files):**
1. `bedrockService.js` → `modelConfigs` getter (pricing, limits)
2. `bedrockService.js` → `supportsExtendedContext()` (1M check)
3. `server/claude-cli.js` → `BEDROCK_MODEL_ID_TO_ALIAS` (CLI mapping)
4. `server/routes/admin.js` → `MODEL_OPTIONS.bedrock` (UI dropdown)

### 3. Postmark (Email)

**Purpose:** Transactional email delivery for password resets and welcome messages.

| Property | Value |
|----------|-------|
| **API endpoint** | `https://api.postmarkapp.com` |
| **Auth method** | Server token via `POSTMARK_SERVER_TOKEN` |
| **Templates** | Password reset (`POSTMARK_RESET_TEMPLATE_ALIAS`), Welcome (`POSTMARK_WELCOME_TEMPLATE_ALIAS`) |
| **Service file** | `server/services/emailService.js` |
| **Failure handling** | Logged but non-blocking (email failure doesn't block reset flow) |

**Env vars:**
- `POSTMARK_SERVER_TOKEN` -- API authentication
- `POSTMARK_FROM_EMAIL` -- Sender address
- `POSTMARK_FROM_NAME` -- Sender display name
- `POSTMARK_MESSAGE_STREAM` -- Message stream ID
- `POSTMARK_SUPPORT_URL` -- Support link in emails

### 4. rclone (Cloud Drive VFS)

**Purpose:** Virtual filesystem for mounting Google Drive, OneDrive, SharePoint.

| Property | Value |
|----------|-------|
| **Communication** | HTTP RC API at `127.0.0.1:5760` |
| **Auth method** | Basic auth (`RCLONE_RC_USER`, `RCLONE_RC_PASS`) |
| **Service file** | `server/services/rcloneService.js`, `virtualFsService.js` |
| **Cache** | VFS caching with configurable TTLs |
| **Mount dir** | `CLOUD_MOUNT_ROOT` env var |

**Env vars:**
- `RCLONE_RC_ADDR` -- RC API address (default `127.0.0.1:5760`)
- `RCLONE_RC_BIND_ADDR` -- Bind address
- `RCLONE_RC_USER`, `RCLONE_RC_PASS` -- Auth credentials
- `RCLONE_RC_TIMEOUT_MS` -- Request timeout (default 60s)
- `VFS_CACHE_DIR_TTL_MS` -- Directory cache TTL (default 15s)

### 5. PostHog (Analytics)

**Purpose:** Product analytics and event tracking (client-side).

| Property | Value |
|----------|-------|
| **SDK** | `posthog-js` |
| **Config** | `VITE_POSTHOG_KEY`, `VITE_POSTHOG_HOST` (default `eu.i.posthog.com`) |
| **Context** | `PostHogContext.jsx` |

### 6. Claude CLI

**Purpose:** Core execution engine -- Claude Code CLI installed in Docker container.

| Property | Value |
|----------|-------|
| **Version** | v2.1.81 (installed in Dockerfile) |
| **Spawn method** | `node-pty` for PTY emulation |
| **Communication** | stdin/stdout via PTY |
| **Configuration** | `CLAUDE_HOME` directory |
| **Permissions** | Default `bypassPermissions` |

## MCP Integration Framework

21 Model Context Protocol (MCP) services, each following a common pattern.

### Common MCP Architecture

Each MCP integration has:
- **Route file:** `server/routes/mcp-<service>.js` -- HTTP endpoints for configure/test/register
- **Service file:** `server/services/<service>McpService.js` -- Business logic
- **Config directory:** `<SERVICE>_MCP_CONFIG_DIR` env var -- Persistent config storage
- **Registration:** `POST /api/mcp/:service/register` adds to Claude CLI's MCP config

### MCP Service Inventory

| # | Service | Purpose | Config Env Var |
|---|---------|---------|---------------|
| 1 | bubble | Bubble.io database integration | `BUBBLE_MCP_CONFIG_DIR` |
| 2 | activecampaign | CRM integration | `ACTIVECAMPAIGN_MCP_CONFIG_DIR` |
| 3 | aws-cloudwatch | CloudWatch metrics/logs | `AWS_CLOUDWATCH_MCP_CONFIG_DIR` |
| 4 | aws-cost | AWS cost analysis | `AWS_COST_MCP_CONFIG_DIR` |
| 5 | companies-house | UK company data lookup | `COMPANIES_HOUSE_MCP_CONFIG_DIR` |
| 6 | cybersolstice-bubble | Bubble variant | `CYBERSOLSTICE_BUBBLE_MCP_CONFIG_DIR` |
| 7 | docbuilder | Document generation | `DOCBUILDER_MCP_CONFIG_DIR` |
| 8 | docsidecar | Document processing sidecar | `DOCSIDECAR_MCP_CONFIG_DIR` |
| 9 | drive | Google Drive access | `DRIVE_MCP_CONFIG_DIR` |
| 10 | google-analytics | GA4 data access | `GOOGLE_ANALYTICS_MCP_CONFIG_DIR` |
| 11 | google-search-console | GSC data access | `GOOGLE_SEARCH_CONSOLE_MCP_CONFIG_DIR` |
| 12 | openai-vector-store | Vector embeddings | `OPENAI_VECTOR_STORE_MCP_CONFIG_DIR` |
| 13 | planb-admin | Plan B admin tools | `PLANB_ADMIN_MCP_CONFIG_DIR` |
| 14 | postmark | Email delivery via MCP | `POSTMARK_MCP_CONFIG_DIR` |
| 15 | quickbase | QuickBase database | `QUICKBASE_MCP_CONFIG_DIR` |
| 16 | secretstore | Secret management | `SECRETSTORE_MCP_CONFIG_DIR` |
| 17 | stripe | Payment processing | `STRIPE_MCP_CONFIG_DIR` |
| 18 | tldv | Meeting/video integration | `TLDV_MCP_CONFIG_DIR` |
| 19 | whisper-transcription | Audio transcription | `WHISPER_MCP_CONFIG_DIR` |
| 20 | secondopinion | Second opinion service | -- |
| 21 | claude-historian | Session history access | -- |

### MCP API Pattern

Each service exposes:

```
GET  /api/mcp/:service/status    → { configured: bool, registered: bool }
POST /api/mcp/:service/configure → Store service credentials/config
POST /api/mcp/:service/register  → Add to Claude CLI MCP config
DELETE /api/mcp/:service/register → Remove from Claude CLI
POST /api/mcp/:service/test      → Validate connectivity
```

### MCP CLI Integration

`GET /api/mcp/cli/list` (localhost only) returns all registered MCP servers for the Claude CLI to discover. This endpoint is called by the CLI process during initialization.

## Cloud Drive OAuth Providers

| Provider | Type | OAuth Flow |
|----------|------|-----------|
| Google Drive | `gdrive` | Google OAuth 2.0 |
| OneDrive | `onedrive` | Microsoft OAuth 2.0 |
| SharePoint | `sharepoint` | Microsoft OAuth 2.0 (with tenant) |

**OAuth flow:**
1. GET `/api/auth/:provider/start` → redirect to provider auth page
2. User authorizes → provider redirects to callback
3. GET `/api/auth/:provider/callback` → exchange code for tokens
4. Tokens encrypted and stored in `cloud_credentials`

**Service files:**
- `server/services/cloudOAuthService.js` -- OAuth flow management
- `server/services/cloudOAuthProviders.js` -- Provider definitions
- `server/services/cloudDriveManager.js` -- Connection management

## Document Processing Pipeline

| Library | Purpose | Input → Output |
|---------|---------|---------------|
| `mammoth` | Word conversion | .docx → HTML |
| `turndown` | HTML conversion | HTML → Markdown |
| `marked` | Markdown rendering | Markdown → HTML |
| `html-pdf-node` | PDF generation | HTML → PDF |
| `html-to-docx` | DOCX generation | HTML → .docx |
| `@knowcode/doc-builder` | Doc-builder | Markdown → styled HTML |
| `@knowcode/convert-to-markdown` | Conversion | Various → Markdown |

## External API Contracts

### Projects API (`/api/v1/projects`)

**Auth:** API key (`X-API-Key` header)

```
GET /api/v1/projects
→ 200: { projects: [{ id, name, path, created_at }] }

GET /api/v1/projects/:projectId/meetings
→ 200: { meetings: [{ id, title, started_at, status }] }
```

### Meetings API (`/api/v1/meetings`)

**Auth:** API key

```
POST /api/v1/meetings/start
← { meetingId: string }
→ 200: { status: "started", meetingId }

POST /api/v1/meetings/stop
← { meetingId: string }
→ 200: { status: "stopped", transcript }

GET /api/v1/meetings/status
→ 200: { active: bool, meetingId, duration }

GET /api/v1/meetings/:meetingId/transcript
→ 200: { transcript, segments }
```

### Tasks API (`/api/v1/tasks`)

**Auth:** API key or localhost

```
GET /api/v1/tasks
→ 200: { tasks: [{ name, cron_expression, enabled, last_status }] }

POST /api/v1/tasks
← { name, prompt_name, cron_expression, timezone }
→ 201: { task }

POST /api/v1/tasks/:name/run
→ 200: { execution_id, status }

GET /api/v1/tasks/:name/history
→ 200: { executions: [...] }
```

### Callback Delivery

When API keys have a `callback_url` configured, meeting events are delivered via POST with HMAC signature verification using the key's `signing_secret`.
