ads-mcp-for-snapchat 0.9.4 → 0.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +5 -1
- package/ARCHITECTURE.md +1 -1
- package/CHANGELOG.md +34 -0
- package/README.md +46 -12
- package/package.json +1 -1
- package/src/apps/board.html +152 -0
- package/src/apps/bridge.js +99 -0
- package/src/apps/dashboard.html +173 -0
- package/src/apps/preview.html +100 -0
- package/src/apps.js +34 -0
- package/src/budget-warning.js +43 -0
- package/src/dashboard.js +87 -0
- package/src/index.js +1 -1
- package/src/media-dir.js +25 -0
- package/src/policy.js +16 -0
- package/src/prompts.js +2 -2
- package/src/snap-errors.js +12 -0
- package/src/snap.js +3 -2
- package/src/tool-docs.js +127 -0
- package/src/tools.js +222 -31
- package/src/toolsets.js +22 -7
- package/src/verify.js +1 -1
package/.env.example
CHANGED
|
@@ -7,6 +7,10 @@ SNAP_REFRESH_TOKEN=
|
|
|
7
7
|
SNAP_AD_ACCOUNT_ID=
|
|
8
8
|
# Safety limits (optional; plain numbers in account currency; an invalid value stops the server; restart to apply)
|
|
9
9
|
SNAP_MAX_DAILY_BUDGET=1000
|
|
10
|
+
# Optional: a warning (not a limit) in the preview when a change adds more daily budget than this.
|
|
11
|
+
# SNAP_WARN_DAILY_BUDGET=
|
|
12
|
+
# Optional: only read media and customer-list files from this folder (absolute path).
|
|
13
|
+
# SNAP_MEDIA_DIR=
|
|
10
14
|
SNAP_MIN_DAILY_BUDGET=5
|
|
11
15
|
SNAP_MAX_BID=50
|
|
12
16
|
SNAP_MAX_BUDGET_INCREASE_PCT=100
|
|
@@ -21,7 +25,7 @@ SNAP_REPORT_UTC_OFFSET=+00:00
|
|
|
21
25
|
# Optional: SNAP_BROKER_URL=https://login.example.com (the shared login service; a refresh token is sent there, so use only one you trust)
|
|
22
26
|
# Optional: SNAP_HOME=/some/folder (where settings, the change log and exports live; default ~/.ads-mcp-for-snapchat for an npm install)
|
|
23
27
|
# Optional: SNAP_PORTFOLIO_FILES=/abs/path/.env,/abs/path/.env.account2 (accounts shown side by side by snap_portfolio_summary)
|
|
24
|
-
# Optional: SNAP_TOOLSETS=setup,reports,checks (show only these tool groups: setup, read, reports, checks, changes, create; default all)
|
|
28
|
+
# Optional: SNAP_TOOLSETS=setup,reports,checks (show only these tool groups: core, setup, read, reports, checks, changes, create; default all)
|
|
25
29
|
# Optional: SNAP_MAX_LIFETIME_BUDGET, SNAP_MAX_ACTIVATION_DAILY_BUDGET, SNAP_MAX_ADDED_DAILY_BUDGET_24H, SNAP_ACCOUNT_CURRENCY=USD,
|
|
26
30
|
# SNAP_READ_ONLY=1, SNAP_HUMAN_APPROVAL=elicit (see README "Safety settings")
|
|
27
31
|
# Only needed once, by scripts/get-refresh-token.js (must match the redirect URL on your OAuth app)
|
package/ARCHITECTURE.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Architecture and design notes
|
|
2
2
|
|
|
3
|
-
For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API:
|
|
3
|
+
For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API: 78 tools, all tests mocked (`npm test`). Read `README.md` first for setup and the tool table.
|
|
4
4
|
|
|
5
5
|
## Architecture (src/)
|
|
6
6
|
- `portfolio.js`: several accounts side by side, from the settings files the owner lists in SNAP_PORTFOLIO_FILES (read-only).
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,40 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.9.7 (2026-11-21)
|
|
6
|
+
|
|
7
|
+
Three changes together: fewer tools (merged near-duplicates, a core tool set), interactive cards (MCP Apps), and the quality-audit fixes. Existing tool names keep working behind `SNAP_LEGACY_TOOLS=1`; see the entries below. The Claude Desktop extension now starts with the core tool set and changes allowed (see 0.9.5).
|
|
8
|
+
|
|
9
|
+
- **Interactive cards (MCP Apps).** New read-only tools `snap_dashboard` (spend, ROAS, purchases, pacing, 7/14/30-day switch) and `snap_campaign_board` (campaigns with Pause and Resume buttons), and a preview card for every tool that previews a change, with an Apply button. Cards are optional: apps without card support get the same answers as text and data. The buttons use the same previews, approval tokens, limits and read-only setting; the cards have no network access and show account names as plain text. 76 tools became 78, and both new tools are in the core set (now 46).
|
|
10
|
+
|
|
11
|
+
- **Core tool set.** `SNAP_TOOLSETS=core` shows 44 everyday tools (read, check, launch campaigns, undo, and every tool the playbooks use); it can be combined with groups (`core,reports`). The Claude Desktop extension now starts with `core`; type `all` in its Tool set field to see every tool.
|
|
12
|
+
|
|
13
|
+
- **Fewer tools (85 to 76).** Tools that did the same job are now one: `snap_set_status`, `snap_rename`, `snap_set_schedule`, `snap_exclude_segments` and `snap_set_daily_budget` take `id` for one item or `ids` (`adsquad_ids`) for up to 20, and `snap_report` takes `view` = table, daily, hourly, compare or audience. The old tools do the work as before (every limit, preview and approval is the same); only the names changed. The old names are hidden unless `SNAP_LEGACY_TOOLS=1`, and then work as deprecated aliases.
|
|
14
|
+
|
|
15
|
+
## 0.9.6 (2026-11-21)
|
|
16
|
+
|
|
17
|
+
From the quality audit (see AUDIT-REPORT.md). No tool was renamed or removed.
|
|
18
|
+
|
|
19
|
+
- Dates: wherever a tool takes `start_time`, `end_time` or the compare-window times, a plain `YYYY-MM-DD` now works (it means 00:00 that day in `SNAP_REPORT_UTC_OFFSET`); ISO date-times on the hour still work.
|
|
20
|
+
- Long answers: new `SNAP_MAX_RESPONSE_CHARS` (default 100000). A longer answer is cut with a note saying how to ask for less.
|
|
21
|
+
- The list tools declare an `outputSchema` (`items`, `returned`, `total_matching`, `has_more`, `next_offset`, `notes`).
|
|
22
|
+
|
|
23
|
+
- Errors: Snap HTTP errors now end with a plain "Fix:" sentence (re-run setup, ask an Admin, get the id from a list tool, wait N seconds).
|
|
24
|
+
- Descriptions: every parameter of every tool now has a description (where its id comes from, units, examples); 22 tools got a "use this / not that" pointer. A test keeps it at 100%.
|
|
25
|
+
- Lists: `snap_list_*` tools take `offset` and `response_format` (concise or detailed) and report `has_more` and `next_offset`. `snap_list_pixels`, `snap_list_catalogs` and `snap_list_product_sets` gained `limit`.
|
|
26
|
+
- Results that are objects are also returned as `structuredContent` next to the text; list answers are `{ items, returned, total_matching, has_more, next_offset }`.
|
|
27
|
+
- Ten read-only evaluation questions with known answers (`test/eval/questions.json`), run by the tests. README: examples, permissions, rate limits.
|
|
28
|
+
|
|
29
|
+
- Safety: `snap_set_frequency_cap`, `snap_set_ad_schedule`, `snap_set_placement` and `snap_claim_ad_code` are now marked destructive (they overwrite settings or use up a single-use code). New optional `SNAP_MEDIA_DIR`: when set, media and customer-list files must be inside that folder (symbolic links resolved).
|
|
30
|
+
|
|
31
|
+
## 0.9.5 (2026-11-17)
|
|
32
|
+
|
|
33
|
+
- **Claude Desktop extension starts with changes allowed** (Read-only is off by default) and a daily budget limit of 500. Every change is still previewed and needs approval, everything created starts paused, and the limit and the new budget warning apply. `npx ... setup` still starts read-only unless you choose otherwise.
|
|
34
|
+
|
|
35
|
+
- **Budget warning.** A preview that adds a daily budget unusually large for the account now shows a `budget_warning`: more than twice the largest running ad squad, more than half the limit when nothing is running, or above the optional `SNAP_WARN_DAILY_BUDGET`. It is a warning only; the limits still apply and nothing is blocked by it.
|
|
36
|
+
|
|
37
|
+
- README: a short section on how this project relates to Snap's own read-only Ads MCP server (use theirs to look, this one to launch and change campaigns, safely).
|
|
38
|
+
|
|
5
39
|
## 0.9.4 (2026-11-16)
|
|
6
40
|
|
|
7
41
|
- Claude Desktop extension: an icon, a link to the privacy page, and the corrected description (the shared login needs no OAuth app).
|
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ A local [MCP](https://modelcontextprotocol.io) server that lets an AI assistant
|
|
|
5
5
|
> **Unofficial.** Not affiliated with or endorsed by Snap Inc. This tool can change real ad campaigns that spend real money. You use it at your own risk (see LICENSE). Check Snap's developer terms for your own use. Review every preview before approving.
|
|
6
6
|
|
|
7
7
|
## Get started in 2 minutes
|
|
8
|
-
**Claude Desktop (no terminal):** download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snapchat-ads-mcp/releases/latest), open it, leave Client ID and secret empty, then ask Claude: "Connect my Snapchat ad account." Log in with Snapchat and pick the ad account.
|
|
8
|
+
**Claude Desktop (no terminal):** download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snapchat-ads-mcp/releases/latest), open it, leave Client ID and secret empty, then ask Claude: "Connect my Snapchat ad account." Log in with Snapchat and pick the ad account. In the Desktop extension, changes are **allowed from the start** (Read-only is off by default): each one is previewed and needs your approval, everything created starts paused, and the daily budget limit starts at 500 (change it in the extension's settings). Switch Read-only on there if you only want to look. It also starts with the **core** tool set (46 everyday tools); type `all` in its Tool set field to see all 78.
|
|
9
9
|
|
|
10
10
|
**Claude Code, Cursor, VS Code or a terminal:**
|
|
11
11
|
```bash
|
|
@@ -13,6 +13,15 @@ npx -y ads-mcp-for-snapchat setup
|
|
|
13
13
|
```
|
|
14
14
|
Choose **1. Shared login**, log in with Snapchat, pick the ad account, and press Enter at the safety question (it starts read-only; nothing can be changed until you allow it). Then check everything with `npx -y ads-mcp-for-snapchat verify`.
|
|
15
15
|
|
|
16
|
+
## How this relates to Snap's own Ads MCP server
|
|
17
|
+
Snap runs its own hosted **Ads MCP server** (see Snap's developer documentation). According to Snap's documentation it is **read-only**: an agent can read Snapchat Ads data but cannot create, update or delete anything, and it works with several AI apps without installing anything.
|
|
18
|
+
|
|
19
|
+
- **Only need to look at your numbers?** Snap's own server is the simplest way, and you don't have to install anything.
|
|
20
|
+
- **Want to launch and change campaigns?** That is what this project is for: you can create campaigns, ad squads, creatives and ads and change budgets, bids, schedules and placements, with a **preview and your approval for every change**, spend limits, undo and a change log, and everything created starts **paused**. Turn on changes with `SNAP_READ_ONLY=0` (the safe default starts read-only; it is a switch, not a limit).
|
|
21
|
+
- You can use both side by side.
|
|
22
|
+
|
|
23
|
+
This project is unofficial and is not made, endorsed or supported by Snap. It runs on your own computer; it is not the hosted service Snap provides.
|
|
24
|
+
|
|
16
25
|
## What it is, and what it is not
|
|
17
26
|
- **It runs on your machine, with your own ad account.** You connect with a normal Snapchat login (the shared login service) or with your own Snapchat OAuth app. The tool itself is not hosted, and no ad account data leaves your computer except to Snap's API.
|
|
18
27
|
- **It is a safety-first tool, not an autopilot.** Writes are previewed first, created things start paused, and there are hard limits on money. See "Safety rules" below, and read "What the approval token is not".
|
|
@@ -93,6 +102,10 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
93
102
|
| Setting | Default | Meaning |
|
|
94
103
|
|---|---|---|
|
|
95
104
|
| `SNAP_MAX_DAILY_BUDGET` | 1000 | Highest daily budget any single campaign or ad squad may be given or enabled with |
|
|
105
|
+
| `SNAP_MAX_RESPONSE_CHARS` | 100000 | Longest answer a tool returns; longer ones are cut with a note saying how to ask for less. |
|
|
106
|
+
| `SNAP_LEGACY_TOOLS` | off | Set to 1 to also show the old tool names that were merged into other tools (for example `snap_set_status_bulk`, `snap_bulk_set_budget`, `snap_report_daily`). They work as before and say which tool replaced them. Off by default, so the assistant sees fewer tools. |
|
|
107
|
+
| `SNAP_MEDIA_DIR` | (none) | Optional folder allow-list: when set, `snap_upload_media` and `snap_upload_customer_list` only read files inside this folder (symbolic links are resolved first). Recommended, so the server cannot be steered into reading other files on your computer. |
|
|
108
|
+
| `SNAP_WARN_DAILY_BUDGET` | (none) | Optional **warning** level, not a limit: a change that adds more than this daily budget shows a `budget_warning` in the preview. Without it, the preview still warns when a change adds more than twice your largest running ad squad (or, on an account with none running, more than half of `SNAP_MAX_DAILY_BUDGET`). |
|
|
96
109
|
| `SNAP_MIN_DAILY_BUDGET` | 5 | Lowest daily budget |
|
|
97
110
|
| `SNAP_MAX_BID` | 50 | Highest max bid |
|
|
98
111
|
| `SNAP_MAX_BUDGET_INCREASE_PCT` | 100 | Largest budget increase per step and per 24 hours |
|
|
@@ -106,7 +119,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
106
119
|
| `SNAP_BROKER_URL` | the maintainer's login service (`off` turns the shared login off) | The shared login service: connect with a normal Snapchat login and no OAuth app. https only. A refresh token is sent there, so use only a service you trust (see `PRIVACY.md`, `broker/README.md`). `setup` saves it for you. |
|
|
107
120
|
| `SNAP_HOME` | `~/.ads-mcp-for-snapchat` for an npm install, the project folder for a git checkout | Where the settings file, the change log and `exports/` live. Set it to keep them somewhere else. |
|
|
108
121
|
| `SNAP_PORTFOLIO_FILES` | (none) | Absolute paths of the settings files of the accounts for `snap_portfolio_summary`, comma-separated (up to 10). Only you can set it: the AI app cannot pick files. |
|
|
109
|
-
| `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `setup, read, reports, checks, changes, create` (comma-separated). Fewer tools make some apps faster and less error-prone, e.g. `setup,reports,checks` for an analyst. It only hides tools. |
|
|
122
|
+
| `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `core` (46 everyday tools: read, check and launch campaigns), or `setup, read, reports, checks, changes, create` (comma-separated, can be combined with core). The Claude Desktop extension starts with `core`; type `all` in its Tool set field to see every tool. Fewer tools make some apps faster and less error-prone, e.g. `setup,reports,checks` for an analyst. It only hides tools. |
|
|
110
123
|
| `SNAP_HUMAN_APPROVAL` | off | `elicit` = ask the user through the MCP client before every write |
|
|
111
124
|
| `SNAP_APPROVAL_TTL_SECONDS` | 600 | Lifetime of an approval token |
|
|
112
125
|
| `SNAP_REPEAT_WINDOW_SECONDS` | 600 | An identical create, copy, claim or upload is refused within this time |
|
|
@@ -146,7 +159,6 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
146
159
|
| `snap_capi_status`, `snap_capi_test_event` | Conversions API TEST events only: read the last test events and their errors; send one test event (previewed, email hashed). No tool sends real conversion events. |
|
|
147
160
|
| `snap_set_frequency_cap` | write (preview + approval): at most N impressions per person per N hours/days, or clear it |
|
|
148
161
|
| `snap_set_ad_schedule` | write (preview + approval): which hours of which days ads run; Snap allows it only on lifetime-budget ad squads |
|
|
149
|
-
| `snap_report_hourly` | read: spend, purchases and ROAS by local hour of the day (last 1-7 days), best and worst hours |
|
|
150
162
|
| `snap_creative_compare` | read: the ads of a campaign or ad squad ranked against the median ROAS (WINNER / LAGGING), grouped by call to action |
|
|
151
163
|
| `snap_budget_advice` | read: suggested daily-budget moves (lower the weak, raise the proven, funded by what is freed, inside your limits), each naming the tool that applies it |
|
|
152
164
|
| `snap_billing_check` | read: ad account status, funding sources (card expiry, daily limit vs budgets, credit left) and a verdict |
|
|
@@ -159,30 +171,27 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
159
171
|
| `snap_portfolio_summary` | read: all your ad accounts side by side (yesterday and last 7 days, what needs attention, totals per currency). Reads the settings files you list in `SNAP_PORTFOLIO_FILES`; the AI app cannot choose files. |
|
|
160
172
|
| `snap_connect` | connect an ad account from inside the chat (link, pasted address, account choice); saves access on this computer, changes no ads |
|
|
161
173
|
| `snap_list_campaigns`, `snap_list_adsquads`, `snap_list_ads`, `snap_list_creatives`, `snap_get_entity`, `snap_get_media`, `snap_get_stats` | read |
|
|
162
|
-
| `
|
|
163
|
-
| `
|
|
164
|
-
| `snap_report_audience` | read: performance by country, gender, age, region, dma or make |
|
|
174
|
+
| `snap_dashboard`, `snap_campaign_board` | read: interactive cards (see "Interactive cards" below): an account dashboard (spend, ROAS, purchases, pacing, 7/14/30 days) and a campaign list with Pause and Resume buttons. Without card support the same numbers come back as data |
|
|
175
|
+
| `snap_report` | read: performance reports. `view` = `table` (ROAS, CPA, swipe rate, frequency by ad squad or ad; the default), `daily` (day by day, up to 31 days), `hourly` (by local hour of the day, last 1-7 days, best and worst hours), `compare` (two time windows side by side) or `audience` (by country, gender, age, region, dma or make) |
|
|
165
176
|
| `snap_health_check` | read: audits every active squad for missing buyer exclusion, high frequency, low swipe rate, low ROAS, spend with no purchases, paused parents |
|
|
166
177
|
| `snap_review_issues` | read: rejected / pending ads with Snap's reasons |
|
|
167
178
|
| `snap_pixel_health` | read: pixel signal readiness and event-quality issues, top priority first |
|
|
168
179
|
| `snap_creative_fatigue` | read: which ads are tired (ROAS down 30%+ with higher frequency or lower swipe rate), which to replace first |
|
|
169
|
-
| `snap_report_compare` | read: two time windows side by side with the changes |
|
|
170
180
|
| `snap_report_async_start`, `snap_report_async_status`, `snap_report_async_download` | read: very large CSV reports saved to `exports/` |
|
|
171
181
|
| `snap_api_get` | read-only GET for anything else (allow-listed paths, never writes) |
|
|
172
182
|
| `snap_list_segments`, `snap_list_pixels`, `snap_list_catalogs`, `snap_list_product_sets`, `snap_targeting_options` | read: audiences, pixels, catalogs, product sets, interest/region/language ids |
|
|
173
183
|
| `snap_change_log` | read the local log |
|
|
174
|
-
| `snap_set_status
|
|
175
|
-
| `snap_set_daily_budget`, `snap_set_bid`, `snap_rename` | edit |
|
|
184
|
+
| `snap_set_status` | pause / enable one item (`id`) or up to 20 (`ids`; skips items already in that state, warns when a parent is paused) |
|
|
185
|
+
| `snap_set_daily_budget`, `snap_set_bid`, `snap_rename` | edit. `snap_set_daily_budget` also takes `adsquad_ids` with `mode` set or scale for up to 20 ad squads; `snap_rename` takes `ids` with `find` and `replace` for up to 20 items |
|
|
176
186
|
| `snap_set_targeting` | change countries, age, gender, interests, device OS, include segments, stop excluding segments; everything else is kept |
|
|
177
|
-
| `snap_set_schedule` | set start/end time on a campaign or ad squad |
|
|
178
|
-
| `snap_exclude_segments` | add buyer-exclusion audiences to an ad squad |
|
|
187
|
+
| `snap_set_schedule` | set start/end time on a campaign or ad squad (`id`), or on up to 20 (`ids`) |
|
|
188
|
+
| `snap_exclude_segments` | add buyer-exclusion audiences to an ad squad (`adsquad_id`), or to up to 20 (`adsquad_ids`) |
|
|
179
189
|
| `snap_copy_campaign` | copy a campaign (all or selected ad squads, with or without ads), paused |
|
|
180
190
|
| `snap_create_campaign` | create a new empty campaign, paused |
|
|
181
191
|
| `snap_create_adsquad` | create a new purchase-optimized web ad squad (max bid or auto-bid, interests, device OS, buyer exclusions), paused |
|
|
182
192
|
| `snap_create_lookalike` | create a lookalike audience from a customer-list seed |
|
|
183
193
|
| `snap_copy_adsquad` | copy one ad squad into a campaign, paused |
|
|
184
194
|
| `snap_clone_ad` | clone an ad into other ad squads, paused (skips duplicates and different product sets) |
|
|
185
|
-
| `snap_bulk_exclude_segments`, `snap_bulk_set_budget`, `snap_bulk_set_schedule`, `snap_bulk_rename` | edit up to 20 items at once with a per-item preview; stop at the first failure |
|
|
186
195
|
| `snap_undo` | revert a change from the log (refuses if the field changed again since) |
|
|
187
196
|
| `snap_clone_creative` | duplicate a creative with a new name/headline/link |
|
|
188
197
|
| `snap_create_pixel_audience` | audience of people who fired pixel events (e.g. ADD_CART) |
|
|
@@ -197,6 +206,31 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
197
206
|
| `snap_create_collection_creative` | Collection Ad: a main image or video with 4-20 product tiles, each opening its own page |
|
|
198
207
|
| `snap_influencer_ad` | the whole influencer flow in one step: claim, wait for media, creative, paused ad |
|
|
199
208
|
|
|
209
|
+
## Interactive cards (MCP Apps)
|
|
210
|
+
In AI apps that support [MCP Apps](https://modelcontextprotocol.io) (for example Claude), some tools show a small interactive card inside the chat instead of only text:
|
|
211
|
+
- **`snap_dashboard`**: spend, ROAS, purchases, cost per purchase and swipe rate for 7, 14 or 30 days (switch with the buttons), spend by day, and this month's pacing.
|
|
212
|
+
- **`snap_campaign_board`**: every campaign with its 7-day spend and ROAS. **Pause** and **Resume** buttons first show what would change, and nothing happens until you press **Confirm**.
|
|
213
|
+
- **Preview card**: every tool that previews a change (create, budget, status, schedule and so on) shows its preview as a card with an **Apply** button that uses the approval token of that exact preview.
|
|
214
|
+
|
|
215
|
+
How they stay safe: the buttons call the same tools with the same previews, approval tokens, spend limits and read-only setting as before; with `SNAP_READ_ONLY` on, Confirm and Apply stay disabled. The cards have no network access, show names from your account as plain text (never as code), and follow the app's light or dark theme. In apps without card support nothing changes: the same answers arrive as text and data.
|
|
216
|
+
|
|
217
|
+
## Examples, permissions and limits
|
|
218
|
+
**Things to ask your assistant** (each names the tool it will use):
|
|
219
|
+
- "Which campaigns are running?" (`snap_list_campaigns`, status ACTIVE)
|
|
220
|
+
- "How is spend pacing this month?" (`snap_spend_pacing`)
|
|
221
|
+
- "Which ad squads are wasting money?" (`snap_budget_advice`, `snap_health_check`)
|
|
222
|
+
- "Create a paused traffic campaign called Spring sale." (`snap_create_campaign`, previewed first)
|
|
223
|
+
- "Raise the daily budget of ad squad X to 40." (`snap_set_daily_budget`, previewed, with a warning if the amount is unusual)
|
|
224
|
+
- "Undo the last change." (`snap_undo`)
|
|
225
|
+
|
|
226
|
+
**Snapchat permissions.** The Snapchat login must have access to the ad account in Ads Manager. Reading and changing both go through the login's own rights: if the login can edit campaigns in Ads Manager, so can this server; if it can only view, changes fail. Check the roles in Ads Manager under Members. Asking Snap for an item your login cannot see returns a 403 with a hint.
|
|
227
|
+
|
|
228
|
+
**Rate limits.** Snap limits how many requests a login may send. The server retries reads on 429 and 5xx and honours Snap's `Retry-After`; writes are retried only on 429, never after a network failure (so a change is never applied twice). If Snap still refuses, the error says how long to wait.
|
|
229
|
+
|
|
230
|
+
**Long lists.** `snap_list_*` tools take `limit`, `offset` and `response_format` (`concise` = id, name, status; `detailed` = everything). Each answer says `has_more` and `next_offset`. Results also come back as structured data next to the text.
|
|
231
|
+
|
|
232
|
+
**Evaluation questions.** `test/eval/questions.json` holds ten read-only questions with known answers; `npm test` runs them against a fake Snap.
|
|
233
|
+
|
|
200
234
|
## Influencer ad-code flow
|
|
201
235
|
Creators share a code like `adcode_<uuid>`. `snap_influencer_ad` claims it into the ad account (`POST /adaccounts/{id}/claim_media_by_ad_code?ad_code=&profile_id=`, parameters go in the query string), waits for the media to be READY, creates a WEB_VIEW creative on the brand profile (`SNAP_BRAND_PROFILE_ID`) and creates a **paused** ad in the ad squad you choose.
|
|
202
236
|
Notes from live use:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ads-mcp-for-snapchat",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.7",
|
|
4
4
|
"description": "Unofficial local MCP server for the Snapchat Marketing API: reports, audits and safe, previewed changes to campaigns, ad squads and ads.",
|
|
5
5
|
"mcpName": "io.github.Usame794/ads-mcp-for-snapchat",
|
|
6
6
|
"adsMcpBroker": "https://ads-mcp-for-snapchat-login.ads-mcp.workers.dev",
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>Campaigns</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb}
|
|
9
|
+
@media (prefers-color-scheme:dark){:root{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff}}
|
|
10
|
+
:root[data-theme=light]{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb}
|
|
11
|
+
:root[data-theme=dark]{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff}
|
|
12
|
+
:root{--bg:var(--color-background-primary,var(--fb-bg));--bg2:var(--color-background-secondary,var(--fb-bg2));--text:var(--color-text-primary,var(--fb-text));--muted:var(--color-text-secondary,var(--fb-muted));--border:var(--color-border-primary,var(--fb-border));--good:var(--color-text-success,var(--fb-good));--bad:var(--color-text-danger,var(--fb-bad));--warn:var(--color-text-warning,var(--fb-warn))}
|
|
13
|
+
*{box-sizing:border-box}
|
|
14
|
+
body{margin:0;padding:16px;background:var(--bg);color:var(--text);font:14px/1.45 var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif)}
|
|
15
|
+
h1{font-size:18px;margin:0}
|
|
16
|
+
header{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between;margin-bottom:12px}
|
|
17
|
+
.sub{color:var(--muted);font-size:12px}
|
|
18
|
+
.seg{display:flex;border:1px solid var(--border);border-radius:10px;overflow:hidden}
|
|
19
|
+
.seg button{min-height:44px;min-width:56px;padding:0 14px;border:0;background:var(--bg);color:var(--text);font:inherit;cursor:pointer}
|
|
20
|
+
.seg button+button{border-left:1px solid var(--border)}
|
|
21
|
+
.seg button[aria-pressed=true]{background:var(--accent);color:#fff}
|
|
22
|
+
.row{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:12px;margin-bottom:10px}
|
|
23
|
+
.top{display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap}
|
|
24
|
+
.name{font-weight:650;overflow-wrap:anywhere}
|
|
25
|
+
.pill{display:inline-block;padding:1px 8px;border-radius:999px;font-size:11px;border:1px solid var(--border);margin-right:6px}
|
|
26
|
+
.pill.on{color:var(--good);border-color:var(--good)}
|
|
27
|
+
.meta{color:var(--muted);font-size:12px;margin-top:2px}
|
|
28
|
+
button.act{min-height:44px;min-width:96px;padding:0 16px;border-radius:10px;border:1px solid var(--border);background:var(--bg);color:var(--text);font:inherit;cursor:pointer}
|
|
29
|
+
button.act.primary{background:var(--accent);border-color:var(--accent);color:#fff}
|
|
30
|
+
button:disabled{opacity:.55;cursor:default}
|
|
31
|
+
button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
32
|
+
.panel{margin-top:10px;border-top:1px dashed var(--border);padding-top:10px}
|
|
33
|
+
.panel dl{margin:0 0 8px;display:grid;grid-template-columns:max-content 1fr;gap:2px 12px}
|
|
34
|
+
.panel dt{color:var(--muted)}.panel dd{margin:0;overflow-wrap:anywhere}
|
|
35
|
+
.btns{display:flex;gap:8px;flex-wrap:wrap}
|
|
36
|
+
.warn{color:var(--warn)}.err{color:var(--bad)}.ok{color:var(--good)}
|
|
37
|
+
.skeleton{background:linear-gradient(90deg,var(--bg2),var(--border),var(--bg2));background-size:200% 100%;animation:sk 1.2s linear infinite;border-radius:12px;min-height:72px;margin-bottom:10px}
|
|
38
|
+
@keyframes sk{to{background-position:-200% 0}}
|
|
39
|
+
@media (prefers-reduced-motion:reduce){.skeleton{animation:none}}
|
|
40
|
+
</style>
|
|
41
|
+
</head>
|
|
42
|
+
<body>
|
|
43
|
+
<main>
|
|
44
|
+
<header>
|
|
45
|
+
<div><h1>Campaigns</h1><div class="sub" id="sub">Loading...</div></div>
|
|
46
|
+
<div class="seg" role="group" aria-label="Show" id="seg"></div>
|
|
47
|
+
</header>
|
|
48
|
+
<section id="list" aria-live="polite"><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div></section>
|
|
49
|
+
<p class="sub warn" id="warn" hidden></p>
|
|
50
|
+
</main>
|
|
51
|
+
<!--BRIDGE-->
|
|
52
|
+
<script>
|
|
53
|
+
(function () {
|
|
54
|
+
const { el, num } = window.snapApp;
|
|
55
|
+
const $ = (id) => document.getElementById(id);
|
|
56
|
+
const state = { data: null, filter: "ALL", open: null };
|
|
57
|
+
|
|
58
|
+
function seg() {
|
|
59
|
+
const s = $("seg");
|
|
60
|
+
s.textContent = "";
|
|
61
|
+
for (const [key, label] of [["ALL", "All"], ["ACTIVE", "Active"], ["PAUSED", "Paused"]]) s.append(el("button", { type: "button", "aria-pressed": String(state.filter === key), onclick: () => { state.filter = key; state.open = null; render(); } }, label));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function render() {
|
|
65
|
+
const d = state.data;
|
|
66
|
+
seg();
|
|
67
|
+
const list = $("list");
|
|
68
|
+
list.textContent = "";
|
|
69
|
+
if (!d) return;
|
|
70
|
+
const cur = d.account && d.account.currency ? " " + d.account.currency : "";
|
|
71
|
+
$("sub").textContent = d.summary;
|
|
72
|
+
const rows = d.campaigns.filter((c) => state.filter === "ALL" || c.status === state.filter);
|
|
73
|
+
if (!rows.length) list.append(el("div", { class: "sub" }, "No campaigns to show."));
|
|
74
|
+
for (const c of rows) list.append(row(c, cur));
|
|
75
|
+
if (d.has_more) list.append(el("div", { class: "sub" }, "Showing " + d.campaigns.length + " of " + d.total_campaigns + ". Ask for the rest in the chat."));
|
|
76
|
+
const w = $("warn");
|
|
77
|
+
w.hidden = !(d.warnings && d.warnings.length);
|
|
78
|
+
w.textContent = (d.warnings || []).join(" ");
|
|
79
|
+
window.snapApp.resize();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function row(c, cur) {
|
|
83
|
+
const active = c.status === "ACTIVE";
|
|
84
|
+
const target = active ? "PAUSED" : "ACTIVE";
|
|
85
|
+
const box = el("div", { class: "row" });
|
|
86
|
+
box.append(el("div", { class: "top" },
|
|
87
|
+
el("div", null, el("div", { class: "name" }, c.name), el("div", { class: "meta" }, el("span", { class: "pill" + (active ? " on" : "") }, c.status), "7-day spend " + num(c.spend_7d) + cur + " | ROAS " + num(c.roas_7d) + (c.active_daily_budget != null ? " | active daily budgets " + num(c.active_daily_budget) + cur : ""))),
|
|
88
|
+
el("button", { class: "act", type: "button", onclick: () => ask(c, target, box) }, active ? "Pause" : "Resume")));
|
|
89
|
+
if (state.open === c.id && c._panel) box.append(c._panel);
|
|
90
|
+
return box;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function ask(c, status, box) {
|
|
94
|
+
state.open = c.id;
|
|
95
|
+
const panel = el("div", { class: "panel" }, el("div", { class: "sub" }, "Checking what would change..."));
|
|
96
|
+
c._panel = panel;
|
|
97
|
+
box.querySelector(".panel") && box.querySelector(".panel").remove();
|
|
98
|
+
box.append(panel);
|
|
99
|
+
try {
|
|
100
|
+
const r = await window.snapApp.call("snap_set_status", { entity: "campaign", id: c.id, status });
|
|
101
|
+
const text = window.snapApp.textOf(r);
|
|
102
|
+
if (r.isError) { panel.textContent = ""; panel.append(el("div", { class: "err" }, text)); return; }
|
|
103
|
+
const p = window.snapApp.dataOf(r) || {};
|
|
104
|
+
panel.textContent = "";
|
|
105
|
+
const pv = p.preview || {};
|
|
106
|
+
const rows = [["Change", c.name + ": " + c.status + " to " + status]];
|
|
107
|
+
if (pv.daily_budget_that_would_start_delivering !== undefined) rows.push(["Daily budget that would start spending", num(pv.daily_budget_that_would_start_delivering) + (p.ad_account ? "" : "")]);
|
|
108
|
+
if (pv.note) rows.push(["Note", pv.note]);
|
|
109
|
+
const dl = el("dl", null, rows.map(([k, v]) => [el("dt", null, k), el("dd", null, v)]));
|
|
110
|
+
panel.append(dl);
|
|
111
|
+
if (p.read_only) panel.append(el("div", { class: "warn" }, p.read_only));
|
|
112
|
+
if (p.budget_warning) panel.append(el("div", { class: "warn" }, p.budget_warning.message));
|
|
113
|
+
if (p.duplicate_warning) panel.append(el("div", { class: "warn" }, p.duplicate_warning));
|
|
114
|
+
const confirm = el("button", { class: "act primary", type: "button", disabled: !p.approval_token || !!p.read_only, onclick: () => apply(c, status, p.approval_token, panel, confirm, cancel) }, "Confirm " + (status === "PAUSED" ? "pause" : "resume"));
|
|
115
|
+
const cancel = el("button", { class: "act", type: "button", onclick: () => { state.open = null; c._panel = null; render(); } }, "Cancel");
|
|
116
|
+
panel.append(el("div", { class: "btns" }, confirm, cancel));
|
|
117
|
+
window.snapApp.resize();
|
|
118
|
+
} catch (e) {
|
|
119
|
+
panel.textContent = "";
|
|
120
|
+
panel.append(el("div", { class: "err" }, "Could not preview: " + e.message));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function apply(c, status, token, panel, confirm, cancel) {
|
|
125
|
+
confirm.disabled = true;
|
|
126
|
+
cancel.disabled = true;
|
|
127
|
+
try {
|
|
128
|
+
const r = await window.snapApp.call("snap_set_status", { entity: "campaign", id: c.id, status, confirm: true, approval_token: token });
|
|
129
|
+
if (r.isError) { panel.append(el("div", { class: "err" }, window.snapApp.textOf(r))); cancel.disabled = false; return; }
|
|
130
|
+
c.status = status;
|
|
131
|
+
state.open = null;
|
|
132
|
+
c._panel = null;
|
|
133
|
+
render();
|
|
134
|
+
} catch (e) {
|
|
135
|
+
panel.append(el("div", { class: "err" }, "Could not apply: " + e.message));
|
|
136
|
+
cancel.disabled = false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
seg();
|
|
141
|
+
window.snapApp.connect({
|
|
142
|
+
"ui/notifications/tool-result": (r) => {
|
|
143
|
+
if (r && r.isError) { $("sub").textContent = window.snapApp.textOf(r); return; }
|
|
144
|
+
state.data = window.snapApp.dataOf(r);
|
|
145
|
+
render();
|
|
146
|
+
},
|
|
147
|
+
error: (e) => { $("sub").textContent = "Not connected to the chat app: " + e.message; },
|
|
148
|
+
});
|
|
149
|
+
})();
|
|
150
|
+
</script>
|
|
151
|
+
</body>
|
|
152
|
+
</html>
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Shared by the three cards. Talks to the chat app over postMessage using the MCP Apps protocol (2026-01-26): it starts with
|
|
2
|
+
// ui/initialize, receives the tool's input and result as notifications, and can call this server's tools through the app.
|
|
3
|
+
// Everything shown is written as text nodes (never as markup), because names in an ad account are untrusted text.
|
|
4
|
+
(function () {
|
|
5
|
+
const pending = new Map();
|
|
6
|
+
const handlers = {};
|
|
7
|
+
const state = { ctx: {}, nextId: 1 };
|
|
8
|
+
const post = (msg) => window.parent.postMessage(Object.assign({ jsonrpc: "2.0" }, msg), "*");
|
|
9
|
+
const request = (method, params) =>
|
|
10
|
+
new Promise((resolve, reject) => {
|
|
11
|
+
const id = state.nextId++;
|
|
12
|
+
pending.set(id, { resolve, reject });
|
|
13
|
+
post({ id, method, params });
|
|
14
|
+
});
|
|
15
|
+
const notify = (method, params) => post({ method, params });
|
|
16
|
+
|
|
17
|
+
function applyContext(ctx) {
|
|
18
|
+
if (!ctx) return;
|
|
19
|
+
Object.assign(state.ctx, ctx);
|
|
20
|
+
const root = document.documentElement;
|
|
21
|
+
if (ctx.theme) root.setAttribute("data-theme", ctx.theme);
|
|
22
|
+
const vars = ctx.styles && ctx.styles.variables;
|
|
23
|
+
if (vars) for (const k in vars) if (vars[k]) root.style.setProperty(k, vars[k]);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
window.addEventListener("message", (event) => {
|
|
27
|
+
if (event.source !== window.parent) return;
|
|
28
|
+
const m = event.data;
|
|
29
|
+
if (!m || m.jsonrpc !== "2.0") return;
|
|
30
|
+
if (m.id !== undefined && m.method === undefined) {
|
|
31
|
+
const p = pending.get(m.id);
|
|
32
|
+
if (!p) return;
|
|
33
|
+
pending.delete(m.id);
|
|
34
|
+
if (m.error) p.reject(new Error(m.error.message || "Request failed"));
|
|
35
|
+
else p.resolve(m.result);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (!m.method) return;
|
|
39
|
+
if (m.method === "ui/notifications/host-context-changed") applyContext(m.params);
|
|
40
|
+
const handler = handlers[m.method];
|
|
41
|
+
try {
|
|
42
|
+
if (handler) handler(m.params);
|
|
43
|
+
} catch (e) {
|
|
44
|
+
console.error(e);
|
|
45
|
+
}
|
|
46
|
+
if (m.id !== undefined) post({ id: m.id, result: {} }); // the host asked something (ping, teardown): answer it
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
function resize() {
|
|
50
|
+
notify("ui/notifications/size-changed", { height: Math.ceil(document.documentElement.scrollHeight) });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function el(tag, attrs, ...children) {
|
|
54
|
+
const node = document.createElement(tag);
|
|
55
|
+
for (const k in attrs || {}) {
|
|
56
|
+
if (k === "class") node.className = attrs[k];
|
|
57
|
+
else if (k.startsWith("on")) node.addEventListener(k.slice(2), attrs[k]);
|
|
58
|
+
else if (attrs[k] !== undefined && attrs[k] !== null && attrs[k] !== false) node.setAttribute(k, attrs[k] === true ? "" : attrs[k]);
|
|
59
|
+
}
|
|
60
|
+
for (const c of children.flat(Infinity)) if (c !== undefined && c !== null && c !== false) node.append(c.nodeType ? c : document.createTextNode(String(c)));
|
|
61
|
+
return node;
|
|
62
|
+
}
|
|
63
|
+
const num = (n, d) => (n === null || n === undefined || Number.isNaN(Number(n)) ? "n/a" : Number(n).toLocaleString(undefined, { maximumFractionDigits: d === undefined ? 2 : d }));
|
|
64
|
+
const textOf = (r) => ((r && r.content) || []).filter((c) => c.type === "text").map((c) => c.text).join("\n");
|
|
65
|
+
// The data of a tool result: structuredContent when the app sent it, otherwise the JSON text.
|
|
66
|
+
const dataOf = (r) => {
|
|
67
|
+
if (r && r.structuredContent) return r.structuredContent;
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(textOf(r));
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
function connect(on) {
|
|
76
|
+
Object.assign(handlers, on || {});
|
|
77
|
+
request("ui/initialize", { protocolVersion: "2026-01-26", appInfo: { name: "Ads MCP for Snapchat", version: "1" }, appCapabilities: {} })
|
|
78
|
+
.then((res) => {
|
|
79
|
+
applyContext(res && res.hostContext);
|
|
80
|
+
notify("ui/notifications/initialized", {});
|
|
81
|
+
if (handlers.ready) handlers.ready(state.ctx);
|
|
82
|
+
})
|
|
83
|
+
.catch((e) => handlers.error && handlers.error(e));
|
|
84
|
+
if (window.ResizeObserver) new ResizeObserver(resize).observe(document.body);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
window.snapApp = {
|
|
88
|
+
connect,
|
|
89
|
+
el,
|
|
90
|
+
num,
|
|
91
|
+
textOf,
|
|
92
|
+
dataOf,
|
|
93
|
+
resize,
|
|
94
|
+
call: (name, args) => request("tools/call", { name, arguments: args || {} }),
|
|
95
|
+
get ctx() {
|
|
96
|
+
return state.ctx;
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
})();
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>Account dashboard</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb}
|
|
9
|
+
@media (prefers-color-scheme:dark){:root{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff}}
|
|
10
|
+
:root[data-theme=light]{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb}
|
|
11
|
+
:root[data-theme=dark]{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff}
|
|
12
|
+
:root{--bg:var(--color-background-primary,var(--fb-bg));--bg2:var(--color-background-secondary,var(--fb-bg2));--text:var(--color-text-primary,var(--fb-text));--muted:var(--color-text-secondary,var(--fb-muted));--border:var(--color-border-primary,var(--fb-border));--good:var(--color-text-success,var(--fb-good));--bad:var(--color-text-danger,var(--fb-bad));--warn:var(--color-text-warning,var(--fb-warn))}
|
|
13
|
+
*{box-sizing:border-box}
|
|
14
|
+
body{margin:0;padding:16px;background:var(--bg);color:var(--text);font:14px/1.45 var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif)}
|
|
15
|
+
h1{font-size:18px;margin:0}h2{font-size:14px;margin:0 0 8px;color:var(--muted);font-weight:600}
|
|
16
|
+
header{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between;margin-bottom:14px}
|
|
17
|
+
.sub{color:var(--muted);font-size:12px}
|
|
18
|
+
.seg{display:flex;border:1px solid var(--border);border-radius:10px;overflow:hidden}
|
|
19
|
+
.seg button{min-height:44px;min-width:56px;padding:0 14px;border:0;background:var(--bg);color:var(--text);font:inherit;cursor:pointer}
|
|
20
|
+
.seg button+button{border-left:1px solid var(--border)}
|
|
21
|
+
.seg button[aria-pressed=true]{background:var(--accent);color:#fff}
|
|
22
|
+
.seg button:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
|
|
23
|
+
.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px;margin-bottom:14px}
|
|
24
|
+
.tile,.card{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:12px}
|
|
25
|
+
.tile .label{color:var(--muted);font-size:12px}.tile .value{font-size:22px;font-weight:650;margin-top:2px}
|
|
26
|
+
.card{margin-bottom:12px}
|
|
27
|
+
.bar{fill:var(--accent)}.axis{fill:var(--muted);font-size:10px}
|
|
28
|
+
.track{height:12px;border-radius:6px;background:var(--border);overflow:hidden;position:relative}
|
|
29
|
+
.fill{height:100%;background:var(--accent)}
|
|
30
|
+
.legend{display:flex;flex-wrap:wrap;gap:12px;color:var(--muted);font-size:12px;margin-top:6px}
|
|
31
|
+
.warn{color:var(--warn);font-size:12px;margin:8px 0 0}
|
|
32
|
+
.skeleton{background:linear-gradient(90deg,var(--bg2),var(--border),var(--bg2));background-size:200% 100%;animation:sk 1.2s linear infinite;border-radius:8px;min-height:64px}
|
|
33
|
+
@keyframes sk{to{background-position:-200% 0}}
|
|
34
|
+
.err{color:var(--bad)}
|
|
35
|
+
@media (prefers-reduced-motion:reduce){.skeleton{animation:none}}
|
|
36
|
+
</style>
|
|
37
|
+
</head>
|
|
38
|
+
<body>
|
|
39
|
+
<main>
|
|
40
|
+
<header>
|
|
41
|
+
<div><h1>Account dashboard</h1><div class="sub" id="sub">Loading...</div></div>
|
|
42
|
+
<div class="seg" role="group" aria-label="Period" id="seg"></div>
|
|
43
|
+
</header>
|
|
44
|
+
<section class="tiles" id="kpis" aria-live="polite"><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div></section>
|
|
45
|
+
<section class="card"><h2>Spend by day</h2><div id="chart"><div class="skeleton"></div></div></section>
|
|
46
|
+
<section class="card" id="pacing" hidden><h2>This month</h2><div id="pacingBody"></div></section>
|
|
47
|
+
<p class="warn" id="warn" hidden></p>
|
|
48
|
+
</main>
|
|
49
|
+
<!--BRIDGE-->
|
|
50
|
+
<script>
|
|
51
|
+
(function () {
|
|
52
|
+
const { el, num } = window.snapApp;
|
|
53
|
+
const state = { days: 7, busy: false };
|
|
54
|
+
const $ = (id) => document.getElementById(id);
|
|
55
|
+
|
|
56
|
+
function buttons() {
|
|
57
|
+
const seg = $("seg");
|
|
58
|
+
seg.textContent = "";
|
|
59
|
+
for (const d of [7, 14, 30]) {
|
|
60
|
+
seg.append(el("button", { type: "button", "aria-pressed": String(state.days === d), onclick: () => load(d) }, d + " days"));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function tile(label, value, tone) {
|
|
65
|
+
const v = el("div", { class: "value" }, value);
|
|
66
|
+
if (tone) v.style.color = "var(--" + tone + ")";
|
|
67
|
+
return el("div", { class: "tile" }, el("div", { class: "label" }, label), v);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function chart(daily) {
|
|
71
|
+
const box = $("chart");
|
|
72
|
+
box.textContent = "";
|
|
73
|
+
if (!daily || !daily.length) { box.append(el("div", { class: "sub" }, "No daily data for this period.")); return; }
|
|
74
|
+
const W = 600, H = 150, padL = 4, padB = 18;
|
|
75
|
+
const max = Math.max.apply(null, daily.map((d) => d.spend)) || 1;
|
|
76
|
+
const bw = (W - padL) / daily.length;
|
|
77
|
+
const ns = "http://www.w3.org/2000/svg";
|
|
78
|
+
const svg = document.createElementNS(ns, "svg");
|
|
79
|
+
svg.setAttribute("viewBox", "0 0 " + W + " " + H);
|
|
80
|
+
svg.setAttribute("role", "img");
|
|
81
|
+
svg.setAttribute("aria-label", "Bar chart of daily spend");
|
|
82
|
+
svg.style.width = "100%";
|
|
83
|
+
svg.style.height = "auto";
|
|
84
|
+
daily.forEach((d, i) => {
|
|
85
|
+
const h = Math.max(1, ((H - padB) * d.spend) / max);
|
|
86
|
+
const r = document.createElementNS(ns, "rect");
|
|
87
|
+
r.setAttribute("class", "bar");
|
|
88
|
+
r.setAttribute("x", String(padL + i * bw + bw * 0.12));
|
|
89
|
+
r.setAttribute("y", String(H - padB - h));
|
|
90
|
+
r.setAttribute("width", String(bw * 0.76));
|
|
91
|
+
r.setAttribute("height", String(h));
|
|
92
|
+
r.setAttribute("rx", "2");
|
|
93
|
+
const t = document.createElementNS(ns, "title");
|
|
94
|
+
t.textContent = d.date + ": spend " + num(d.spend) + ", purchases " + num(d.purchases, 0) + ", ROAS " + num(d.roas);
|
|
95
|
+
r.append(t);
|
|
96
|
+
svg.append(r);
|
|
97
|
+
});
|
|
98
|
+
[0, daily.length - 1].forEach((i, k) => {
|
|
99
|
+
const tx = document.createElementNS(ns, "text");
|
|
100
|
+
tx.setAttribute("class", "axis");
|
|
101
|
+
tx.setAttribute("x", String(k === 0 ? padL : W));
|
|
102
|
+
tx.setAttribute("y", String(H - 4));
|
|
103
|
+
tx.setAttribute("text-anchor", k === 0 ? "start" : "end");
|
|
104
|
+
tx.textContent = daily[i].date;
|
|
105
|
+
svg.append(tx);
|
|
106
|
+
});
|
|
107
|
+
box.append(svg, el("div", { class: "legend" }, el("span", null, "Highest day: " + num(max)), el("span", null, "Hover or tap a bar for the day's numbers")));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function pacing(p, cur) {
|
|
111
|
+
const sec = $("pacing"), body = $("pacingBody");
|
|
112
|
+
body.textContent = "";
|
|
113
|
+
if (!p) { sec.hidden = true; return; }
|
|
114
|
+
sec.hidden = false;
|
|
115
|
+
const top = Math.max(p.most_it_could_spend_this_month, p.projected_month_spend, p.month_to_date_spend) || 1;
|
|
116
|
+
const bar = (label, value, tone) => {
|
|
117
|
+
const f = el("div", { class: "fill" });
|
|
118
|
+
f.style.width = Math.min(100, (value / top) * 100) + "%";
|
|
119
|
+
if (tone) f.style.background = "var(--" + tone + ")";
|
|
120
|
+
return el("div", { style: "margin-bottom:10px" }, el("div", { class: "sub" }, label + ": " + num(value) + cur), el("div", { class: "track" }, f));
|
|
121
|
+
};
|
|
122
|
+
body.append(
|
|
123
|
+
bar("Spent so far", p.month_to_date_spend),
|
|
124
|
+
bar("Projected for the month", p.projected_month_spend, "warn"),
|
|
125
|
+
bar("Most it could spend (every active ad squad at full budget)", p.most_it_could_spend_this_month, "bad"),
|
|
126
|
+
el("div", { class: "sub" }, "Today: " + num(p.spend_today) + cur + " across " + num(p.active_squads, 0) + " active ad squads, daily budgets total " + num(p.active_daily_budgets_total) + cur)
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function render(data) {
|
|
131
|
+
if (!data || !data.totals) { $("sub").textContent = "No data."; return; }
|
|
132
|
+
const cur = data.account && data.account.currency ? " " + data.account.currency : "";
|
|
133
|
+
state.days = data.range.days;
|
|
134
|
+
buttons();
|
|
135
|
+
$("sub").textContent = "Account " + data.account.id + " | last " + data.range.days + " days, ending today 00:00 (UTC" + data.range.utc_offset + ")";
|
|
136
|
+
const t = data.totals;
|
|
137
|
+
const k = $("kpis");
|
|
138
|
+
k.textContent = "";
|
|
139
|
+
k.append(tile("Spend" + cur, num(t.spend)), tile("ROAS", num(t.roas), t.roas === null ? "" : t.roas >= 1 ? "good" : "bad"), tile("Purchases", num(t.purchases, 0)), tile("Cost per purchase" + cur, num(t.cpa)), tile("Swipe rate", t.swipe_rate_pct === null ? "n/a" : num(t.swipe_rate_pct) + "%"));
|
|
140
|
+
chart(data.daily);
|
|
141
|
+
pacing(data.pacing, cur);
|
|
142
|
+
const w = $("warn");
|
|
143
|
+
w.hidden = !(data.warnings && data.warnings.length);
|
|
144
|
+
w.textContent = (data.warnings || []).join(" ");
|
|
145
|
+
window.snapApp.resize();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function load(days) {
|
|
149
|
+
if (state.busy) return;
|
|
150
|
+
state.busy = true;
|
|
151
|
+
state.days = days;
|
|
152
|
+
buttons();
|
|
153
|
+
try {
|
|
154
|
+
const r = await window.snapApp.call("snap_dashboard", { days });
|
|
155
|
+
if (r.isError) { $("sub").textContent = window.snapApp.textOf(r); $("sub").className = "sub err"; }
|
|
156
|
+
else { $("sub").className = "sub"; render(window.snapApp.dataOf(r)); }
|
|
157
|
+
} catch (e) {
|
|
158
|
+
$("sub").textContent = "Could not load: " + e.message;
|
|
159
|
+
$("sub").className = "sub err";
|
|
160
|
+
} finally {
|
|
161
|
+
state.busy = false;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
buttons();
|
|
166
|
+
window.snapApp.connect({
|
|
167
|
+
"ui/notifications/tool-result": (r) => { if (r && !r.isError) render(window.snapApp.dataOf(r)); else if (r) { $("sub").textContent = window.snapApp.textOf(r); $("sub").className = "sub err"; } },
|
|
168
|
+
error: (e) => { $("sub").textContent = "Not connected to the chat app: " + e.message; },
|
|
169
|
+
});
|
|
170
|
+
})();
|
|
171
|
+
</script>
|
|
172
|
+
</body>
|
|
173
|
+
</html>
|