# Meta Ads MCP Apps

This directory contains **11 premium MCP apps** that provide rich HTML UIs for Meta Ads management inside Claude Desktop and other MCP clients.

## 🎨 Design System

All apps follow a consistent dark theme design:
- **Background**: `#1a1a2e` (dark navy)
- **Cards**: `#16213e` (lighter navy)
- **Accents**: `#0f3460` (deep blue)
- **Highlights**: `#e94560` (vibrant pink/red)
- **Text**: `#eee` (light gray)

**Visual Style**: Premium analytics dashboard with:
- Self-contained inline CSS (no external dependencies)
- Smooth gradients, box-shadows, and rounded corners
- Color-coded performance indicators (green/yellow/red)
- Pure CSS visualizations (no canvas/SVG/JS)

---

## 📊 Apps Overview

### 1. **Campaign Dashboard** (`campaign-dashboard.ts`)
**Tool**: `campaign_dashboard`  
**Icon**: 📊  

**Purpose**: Executive overview of all campaigns with aggregate metrics and performance table.

**Features**:
- Summary cards: Total Spend, Impressions, Avg CTR, Avg CPC, Conversions, ROAS
- Campaign table with status badges (green=ACTIVE, yellow=PAUSED, red=ERROR)
- Budget pacing bars showing spend vs budget
- Sorted by spend (descending)

**Parameters**:
- `account_id` (required): Ad Account ID (format: `act_XXXXX`)
- `date_preset` (optional): Date range (default: `last_7d`)

---

### 2. **Ad Performance Grid** (`ad-performance-grid.ts`)
**Tool**: `ad_performance_grid`  
**Icon**: 🎯  

**Purpose**: Detailed ad-level performance with color-coded metrics.

**Features**:
- Comprehensive table with all ads
- Columns: Ad Name, Campaign, Ad Set, Status, Impressions, Clicks, CTR, Spend, CPC, Conversions, CPA, ROAS
- Color-coded cells: green (above avg), red (below avg)
- Summary row with totals/averages

**Parameters**:
- `account_id` (required)
- `campaign_id` (optional): Filter by campaign
- `date_preset` (optional): Date range (default: `last_7d`)

---

### 3. **Creative Preview** (`creative-preview.ts`)
**Tool**: `creative_preview`  
**Icon**: 🎨  

**Purpose**: Multi-placement preview of ad creative.

**Features**:
- Creative details (headline, body, CTA, link URL)
- Placement cards for:
  - Facebook Feed
  - Instagram Feed
  - Instagram Story
  - Facebook Right Column
  - Audience Network
- Image preview if available
- Truncated text for mobile previews

**Parameters**:
- `creative_id` (optional): Ad Creative ID
- `ad_id` (optional): Ad ID (will fetch associated creative)
- *(One of the two must be provided)*

---

### 4. **Audience Builder** (`audience-builder.ts`)
**Tool**: `audience_builder`  
**Icon**: 👥  

**Purpose**: Visualize targeting spec with demographics and reach estimate.

**Features**:
- Location list (countries, regions, cities)
- Age range visual bar (18-65+ scale with highlight)
- Gender split cards (Male/Female percentages)
- Interest tags
- Behavior tags
- Custom audience tags
- Estimated reach gauge with lower/upper bounds

**Parameters**:
- `account_id` (required)
- `targeting_spec` (required): JSON string of targeting specification

---

### 5. **Funnel Analyzer** (`funnel-analyzer.ts`)
**Tool**: `funnel_analyzer`  
**Icon**: 🔄  

**Purpose**: Conversion funnel visualization with drop-off rates.

**Features**:
- Funnel stages:
  1. Impressions
  2. Clicks
  3. Landing Page Views
  4. Leads/Add to Cart
  5. Purchases
- Narrowing bars showing volume at each stage
- Conversion rates and drop-off percentages
- Cost per stage cards (CPM, CPC, Cost/LPV, CPL, CPA)

**Parameters**:
- `account_id` (required)
- `campaign_id` (optional): Filter by campaign
- `date_preset` (optional): Date range (default: `last_7d`)

---

### 6. **Spend Tracker** (`spend-tracker.ts`)
**Tool**: `spend_tracker`  
**Icon**: 💰  

**Purpose**: Daily spend visualization with budget pacing.

**Features**:
- Daily spend bar chart (CSS-only)
- Budget line overlay showing average daily target
- Budget pacing bar with status indicator:
  - ✅ On Track (90-110%)
  - 📉 Underspending (<90%)
  - ⚠️ Overspending (>110%)
- Stats cards: Total Spend, Avg Daily, Projected End, Day-over-Day %

**Parameters**:
- `account_id` (required)
- `date_preset` (optional): Date range (default: `last_30d`)

---

### 7. **A/B Test Results** (`ab-test-results.ts`)
**Tool**: `ab_test_results`  
**Icon**: 🧪  

**Purpose**: Compare A/B test variants with statistical significance.

**Features**:
- Side-by-side variant cards (Control vs Treatment)
- Metrics: Spend, Impressions, CTR, CPC, CPA, ROAS
- Confidence level bar (95% threshold)
- Lift percentage badges (↑/↓)
- Winner badge on winning variant
- Warning if not yet significant

**Parameters**:
- `experiment_id` (required): Experiment/Study ID

---

### 8. **Performance Heatmap** (`performance-heatmap.ts`)
**Tool**: `performance_heatmap`  
**Icon**: 🔥  

**Purpose**: Hourly performance visualization across days and hours.

**Features**:
- 7×24 grid (days × hours)
- Color intensity gradient (cool → hot)
- Metric options: CTR, CPC, CPM, Conversions, ROAS
- Color legend bar
- Best/worst time slot indicators
- Average metric value

**Parameters**:
- `account_id` (optional)
- `campaign_id` (optional)
- `date_preset` (optional): Date range (default: `last_7d`)
- `metric` (optional): Metric to visualize (default: `ctr`)

---

### 9. **Ad Library Browser** (`ad-library-browser.ts`)
**Tool**: `ad_library_browser`  
**Icon**: 📚  

**Purpose**: Search and browse competitor ads from Facebook Ad Library.

**Features**:
- Grid of competitor ad cards (2-3 per row)
- Each card shows:
  - Page name
  - Ad creative text (truncated to 200 chars)
  - Platform badges (FB, IG, etc.)
  - Start/end dates
  - Active/Inactive status
  - Estimated spend range (if available)
  - Estimated impression range (if available)

**Parameters**:
- `search_terms` (optional): Search terms for ad creative/text
- `page_id` (optional): Facebook Page ID to filter by
- `country` (optional): Country code (default: `US`)
- *(Either search_terms or page_id must be provided)*

---

### 10. **Campaign Builder** (`campaign-builder.ts`)
**Tool**: `campaign_builder`  
**Icon**: 🎯  

**Purpose**: Multi-step wizard for campaign creation.

**Features**:
- **5-step wizard**:
  1. **Objective**: 6 objective cards (Awareness, Traffic, Engagement, Leads, App, Sales)
  2. **Audience**: Summary of targeting spec (locations, age, gender, interests, etc.)
  3. **Budget & Schedule**: Budget type, amount, start/end dates, bid strategy
  4. **Creative**: Ad format, headline, body text, CTA, preview placeholder
  5. **Review & Confirm**: Full summary with "Ready to Launch" confirmation
- Progress bar at top
- Step indicators with completion status
- Navigation hints (Back/Next)

**Parameters**:
- `account_id` (required)
- `step` (required): Current wizard step (1-5)
- `wizard_data` (optional): JSON string of accumulated data from previous steps

---

### 11. **Account Health** (`account-health.ts`)
**Tool**: `account_health`  
**Icon**: 💚  

**Purpose**: Comprehensive account health assessment with sub-scores.

**Features**:
- **Overall health score (0-100)**:
  - Circular gauge with color-coded status
  - Green (>80): Excellent
  - Yellow (50-80): Good
  - Red (<50): Needs Attention
- **5 sub-scores** in card grid:
  1. **Budget Utilization** (spend vs cap)
  2. **Creative Freshness** (avg creative age, active count)
  3. **Audience Saturation** (frequency)
  4. **Conversion Efficiency** (CPA, ROAS)
  5. **Account Activity** (active campaigns %)
- Each sub-score has:
  - Score bar (colored)
  - Trend indicator (↑/↓/→)
  - Recommendation text

**Parameters**:
- `account_id` (required)
- `date_preset` (optional): Date range (default: `last_30d`)

---

## 🔌 Integration

### Registering Apps

```typescript
import { registerAllApps } from "./apps/index.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { MetaApiClient } from "./client.js";

const server = new McpServer({
  name: "meta-ads",
  version: "1.0.0"
});

const client = new MetaApiClient(config);

// Register all 11 apps at once
registerAllApps(server, client);
```

### Individual Registration

```typescript
import * as campaignDashboard from "./apps/campaign-dashboard.js";

campaignDashboard.register(server, client);
```

---

## 🎯 Usage Examples

### Claude Desktop

Once the server is running, use natural language:

```
"Show me the campaign dashboard for account act_123456789"
→ Invokes campaign_dashboard tool with structured HTML UI

"Preview creative 23847828383"
→ Invokes creative_preview with multi-placement preview

"Give me the account health score"
→ Invokes account_health with circular gauge and sub-scores
```

### API Response Format

Each app returns:

```typescript
{
  structuredContent: {
    type: "resource",
    resource: {
      uri: "meta-ads://app/<app-name>",
      mimeType: "text/html",
      text: "<html>...</html>" // Full self-contained HTML
    }
  },
  content: [
    {
      type: "text",
      text: "Fallback text summary for non-HTML clients"
    }
  ]
}
```

---

## 🛠️ Technical Details

### Data Flow

1. **User request** via MCP client (Claude Desktop)
2. **Tool invocation** with parameters
3. **Meta API fetch** via `MetaApiClient`
4. **Data processing** and calculations
5. **HTML generation** with inline CSS
6. **Structured content response** with text fallback

### Error Handling

All apps include:
- Try-catch wrapper
- Error HTML UI with styled error message
- Text fallback in content field

### CSS Architecture

- **Base styles**: Shared dark theme variables
- **Component styles**: Cards, tables, charts, badges
- **Responsive**: Percentage widths, max-width containers
- **Pure CSS charts**: Bars, gradients, grid layouts (no JS)

### Performance Considerations

- Inline CSS (no external requests)
- Efficient DOM structure
- CSS-only animations (transitions)
- No JavaScript dependencies
- Optimized for Claude Desktop rendering

---

## 📦 File Structure

```
src/apps/
├── campaign-dashboard.ts      # 1. Campaign Dashboard
├── ad-performance-grid.ts     # 2. Ad Performance Grid
├── creative-preview.ts        # 3. Creative Preview
├── audience-builder.ts        # 4. Audience Builder
├── funnel-analyzer.ts         # 5. Funnel Analyzer
├── spend-tracker.ts           # 6. Spend Tracker
├── ab-test-results.ts         # 7. A/B Test Results
├── performance-heatmap.ts     # 8. Performance Heatmap
├── ad-library-browser.ts      # 9. Ad Library Browser
├── campaign-builder.ts        # 10. Campaign Builder
├── account-health.ts          # 11. Account Health
├── index.ts                   # Export and registration
└── README.md                  # This file
```

---

## 🎨 Color Palette

```css
--background:    #1a1a2e  /* Dark navy background */
--card:          #16213e  /* Card background */
--accent:        #0f3460  /* Deep blue accent */
--highlight:     #e94560  /* Vibrant pink/red */
--text:          #eee     /* Light gray text */
--text-muted:    #999     /* Muted text */
--success:       #27ae60  /* Green */
--warning:       #f39c12  /* Orange/yellow */
--error:         #e74c3c  /* Red */
```

---

## 🚀 Future Enhancements

Potential improvements:
- Interactive filters (requires JS bridge)
- Export to PDF/CSV
- Real-time data streaming
- Advanced chart types (if MCP supports canvas)
- Accessibility improvements (ARIA labels, keyboard nav)
- Localization support

---

## 📝 Notes

- All apps are **read-only** (`readOnlyHint: true`)
- No external dependencies (pure HTML/CSS)
- Self-contained for offline rendering
- Optimized for Claude Desktop viewport
- Responsive down to ~320px width
- Cross-browser compatible (modern browsers)

---

Built with ❤️ for the Meta Ads MCP Server
