ads-mcp-for-snapchat 0.9.8 → 0.10.0

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/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: 78 tools, all tests mocked (`npm test`). Read `README.md` first for setup and the tool table.
3
+ For contributors. Unofficial MCP server (Node ESM) for the Snapchat Marketing API: 81 tools (55 in the default core set), all tests mocked (`npm test`). It runs locally over stdio, and the same tool code also runs as a private-test hosted Worker (`remote/`, see below). 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).
@@ -11,11 +11,12 @@ For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat
11
11
  - `catalog-ads.js`: product set filter rules, dynamic template / creative builders and DPA audiences (Snap's Dynamic Product Ads guide).
12
12
  - `insights.js`: audience size, spend pacing, ad preview (read-only). `prompts.js`: the playbooks (MCP prompts).
13
13
  - `setup.js`: the guided `setup` command; `oauth.js`: authorization link, code exchange and ad-account list (used by `setup` and the `snap_connect` tool). `manifest.json` + `scripts/build-mcpb.js`: the Claude Desktop extension (`npm run pack:mcpb`).
14
- - `cli.js`: npm command (`npx ads-mcp-for-snapchat`): no command starts the server; `setup`, `init`, `where`, `save-secret`, `auth`, `check`, `weekly-report` run the setup scripts. `index.js`: MCP server entry. `tools.js`: all 85 tool definitions (zod schemas, handlers).
14
+ - `cli.js`: npm command (`npx ads-mcp-for-snapchat`): no command starts the server; `setup`, `init`, `where`, `save-secret`, `auth`, `check`, `weekly-report` run the setup scripts. `index.js`: MCP server entry. `tools.js`: all 80 tool definitions (zod schemas, handlers).
15
15
  - `snap.js`: `SnapClient` (token refresh, retry), `ENTITIES` (campaign, adsquad, ad, creative, media, segment), sanitize-for-create/update helpers, `createEntity/updateEntity/getEntity/listChildren`, `upload`.
16
16
  - `env.js`: `.env` loading, `setEnvValue` (writes a value without printing it) and `dataDir` (the project folder for a git checkout; `~/.ads-mcp-for-snapchat` for a copy inside `node_modules`; `SNAP_HOME` overrides). The default change log and `exports/` live there too.
17
17
  - `changes.js`: plan functions (status, budget, exclusions, rename, bid, targeting, schedule), `applyChange` (logs before/after), `containsDeep`, `planUndo`.
18
18
  - Feature modules: `formats.js` (SNAP_AD, Story and Collection builders, ad type per creative type, CTA list), `copy.js`, `clone-ad.js`, `bulk.js`, `bulk-edit.js`, `influencer.js`, `influencer-batch.js`, `create.js`, `creative-tools.js`, `readers.js`, `report.js`, `async-report.js`, `audit.js`, `fatigue.js`, `customer-list.js`, `delete.js`.
19
+ - `storage.js`: where the change log and audit log live. Files by default; a hosted build plugs in a database with the same three calls (`append`, `read`, `stamp`). `brand.js`: the server's title, description, website and icon (kept equal to `assets/logo.svg` by a test). `apps.js` + `apps/`: the interactive cards (`theme.css` is the shared look; raise `CARD_REVISION` whenever a card changes, because chat apps keep a card page by its address).
19
20
  - `policy.js` (limits and market settings, validated at startup), `approval.js`, `ownership.js`, `activation.js`, `audit-log.js` (see "Safety design").
20
21
  - `scripts/`: `check.js`, `get-refresh-token.js`, `save-secret.js` (clipboard or `--stdin`, via `src/clipboard.js`), `smoke.js` (9 live read checks), `live-create-creative.js`, `weekly-report.js`.
21
22
 
@@ -35,8 +36,11 @@ For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat
35
36
  - Chunked media upload: INIT/ADD/FINALIZE, 30 MiB chunks, up to 1 GB.
36
37
  - Snap's default attribution (1-day view) overstates results vs last-click store data. Use Snap numbers to compare trends, not as revenue.
37
38
 
39
+ ## Hosted version (`remote/`, private test)
40
+ A Cloudflare Worker that serves the same `registerTools` over HTTP. `worker.js` wraps Cloudflare's OAuth provider; `auth.js` is the consent page, the Snapchat redirect and the allowlist (`ALLOWED_MEMBERS`); `user-session.js` is one Durable Object per user that builds the tools for that user only; `store.js` and `approvals.js` keep the change log, audit log and approval codes in that user's own SQLite database (the server is rebuilt for every request, so nothing may live in memory); `crypto.js` derives the user id and encrypts the Snapchat refresh token. `remote/e2e.mjs` runs the whole flow against a fake Snapchat in the local Workers runtime (not part of `npm test`). Details and known gaps: `remote/README.md`, `remote/DESIGN.md`.
41
+
38
42
  ## Not built
39
- - Hosted multi-user version (needs per-user OAuth, encrypted token storage, abuse protection). Not planned in this repository.
43
+ - A public hosted service: the hosted version is an invitation-only test (no rate limits, no independent review, operator can decrypt stored tokens). It needs those and Snap's confirmation that a shared app may serve other advertisers before it is opened up.
40
44
  - Non-WEB_VIEW creatives (Collection, Story, video formats), product set creation, position-level reports, lifetime / reach-and-frequency budgets, custom location targeting.
41
45
  - Not run live on their own: `snap_create_creative`, `snap_create_ad` (ran inside the influencer flow), campaign-level `snap_set_daily_budget`, a successful `snap_delete` of an ad squad / ad / audience, real-data customer-list upload.
42
46
 
package/CHANGELOG.md CHANGED
@@ -1,6 +1,40 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.10.0 (2026-11-25)
4
+ The biggest release so far. It also contains 0.9.10, which was never published on its own.
5
+
6
+ **New**
7
+ - **Hosted version** (`remote/`, not part of the npm package): the same tools as a connector you add by address in an AI app that supports remote MCP servers, running on Cloudflare. Sign in with Snapchat, read-only unless you allow changes, the same previews, approval codes and spending limits, one private database per person, `snap_disconnect` to delete your data. The operator can open or restrict sign-in (`ALLOWED_MEMBERS`, `*` for everyone), block a person (`BLOCKED_MEMBERS`) and switch changes off for everyone (`HOSTED_READ_ONLY=1`). It has rate limits and log trimming, and serves `/terms`, `/privacy` and `/support`. It is unofficial, has not had an independent security review, and was tested with Claude only.
8
+ - **`snap_delivery_check`** (read-only, core set): why is an active ad squad not spending? Checks the campaign, schedule, ads and their review, budget, pixel and ad account, and says whether each squad is delivering, blocked (with the reason) or has no clear cause. It never guesses: a cut-off ads list is confirmed per squad, and blocked squads cost no extra Snapchat requests.
9
+ - **Catalog (dynamic product) ads** are reachable from the default tool set: the six catalog tools (list catalogs, product sets and templates, create a product set and a layout, feed status) joined the core set, which is now 55 tools.
10
+ - **Cards:** a shared dark and light theme and a cleaner look on all six cards, a Light mode / Dark mode button on each, a clear delete card (names what goes, says it is permanent, asks you to type the name), and a revision number in every card address so a redesign is never served from a chat app's saved copy.
11
+ - **Name, description, website and icon** for the server (`assets/logo.svg`).
12
+
13
+ **Safer**
14
+ - **Privacy:** `snap_ping` and the setup check no longer return the signed-in person's email, username or internal ids, only a masked label and the member status.
15
+ - The undo preview now says where the item ends up ("back to daily budget 5").
16
+ - Change log and audit log storage moved behind a small storage layer (files by default; no change for the local server).
17
+
18
+ **Docs:** README, ARCHITECTURE, PRIVACY, SECURITY and CONTRIBUTING describe the hosted version honestly, including what it lacks.
19
+
20
+ ## 0.9.10 (2026-11-21)
21
+ - The server now writes one line to the app's log saying which app connected and whether that app says it can show cards. It contains no account data. Use it to find out why a card does not appear.
22
+
23
+ ## 0.9.9 (2026-11-21)
24
+
25
+ Fixes from an independent security audit of 0.9.6 (every finding was reproduced with a test first):
26
+ - **Forged login values (F2, high).** The local login listener accepts only a value shaped like a token, and writing a settings value with a line break or control character is refused, so a sealed value can no longer add lines such as `SNAP_HUMAN_APPROVAL=off` to the settings file.
27
+ - **Stale updates (F1, high).** After you answer the "ask before every change" question, the item is read again and nothing is sent if it changed meanwhile; an update is also refused when the item changed since the preview, so a rename can no longer re-enable a campaign you paused.
28
+ - **Campaign-level daily budgets (F3).** Enabling a campaign that has its own daily budget counts and limits that budget (against `SNAP_MAX_DAILY_BUDGET`, the per-call and the 24-hour limits). The first ad squad to deliver under such a campaign counts it too.
29
+ - **`snap_api_get` (F5):** `%2e%2e` and other encoded paths are refused. **Undo (F8):** a forced undo can no longer restore a daily budget above the ceiling when the item has no daily budget now. **Dynamic templates (F9):** one without an ad account is refused. **Ad schedule (F15):** naming only some days works, as documented.
30
+ - **`snap_connect` (F6):** marked destructive; once an ad account is set, read-only mode refuses to switch the account or login, and with human approval on the person is asked first.
31
+ - **Desktop extension (F7):** new optional setting "Ask me before every change"; the wording no longer says a person approves every change when that is off.
32
+ - **Link checker (F11):** connects to the address it checked (no second DNS lookup), still verifying the certificate for the real name; NAT64 addresses count as private. **Customer lists (F12):** an error about a missing column no longer repeats the file's header text. **Approval question (F14):** names are shown on one line, so a name cannot add fake lines.
33
+ - **Ids (F10):** pixel and audience ids given as arguments must belong to the ad account. **Dates (F16):** a plain end date includes that whole day; a refresh token that Snap rotates is saved.
34
+ - **Smaller:** report downloads are not saved when they redirect or exceed 200 MB; auto-strip never drops a field you chose (link, headline, budget, media); the approval store keeps 2000 previews; copying into an existing campaign shows the ad squads already in it.
35
+ - **Documented, not fixed:** the shared login's renew endpoint has no rate limit and the refresh token is a bearer secret; the 24-hour limit lives in one log file; see SECURITY.md "Known limits".
36
+
37
+ - **More interactive tools** (from an independent patch, reviewed and tested here). New read-only tools `snap_change_history` (a filterable timeline of changes with before and after values and Undo buttons) and `snap_setup_check` (a checklist of the login, account, pixel, profile, country, change log and safety settings, with how to fix each). `snap_campaign_board` takes `level` (campaigns or ad squads, with -20% and +20% budget buttons) and `days` (1-30). The budget advice shows as a card where you tick suggestions and apply them together; each one is previewed and uses its own approval token, and a warning in any preview stops the batch instead of applying it. Every preview now starts with `impact_line`, one sentence about the spending effect. Names are shown with `dir="auto"` so Arabic names read correctly; amounts use the account currency (three decimals for KWD, BHD, OMR, JOD). 78 tools became 80; the core set is 48.
4
38
 
5
39
  ## 0.9.8 (2026-11-21)
6
40
 
package/PRIVACY.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Privacy
2
2
 
3
- Ads MCP for Snapchat is open-source software that runs **on your own computer**. This page covers the optional **shared login service** and the tool itself.
3
+ Ads MCP for Snapchat is open-source software that runs **on your own computer**. This page covers the optional **shared login service**, the tool itself, and the separate **hosted private test**.
4
4
 
5
5
  ## The tool (on your computer)
6
6
  - Your settings, the change log and exports stay on your computer. Nothing is sent to the maintainer.
@@ -27,4 +27,19 @@ The service lets you log in with Snapchat without creating your own Snapchat app
27
27
  - If you prefer, skip the shared login and use your own Snapchat OAuth app (see the README). You can also run your own copy of the service (`broker/README.md`).
28
28
  - To stop access: revoke the app in Snapchat Business Manager and delete your settings file.
29
29
 
30
+ ## The hosted version (private test, invitation only)
31
+ This is separate from the local tool. It runs on the maintainer's Cloudflare account. The operator may limit who can sign in. If you use it:
32
+
33
+ **What is stored for you** (in a private database that only your own connection reads)
34
+ - Your Snapchat **refresh token, encrypted**, so the service can act on your ad account for you.
35
+ - A one-way code made from your Snapchat member id (your member id itself is not stored with your data), the names and ids of the ad accounts you can reach (to offer the choice), your chosen ad account and its currency, and your settings.
36
+ - Separately, the operator may keep a **list of approved or blocked Snapchat member ids** as a service setting, to decide who may sign in.
37
+ - A **change log**: what was changed through the service and when, with before and after values and item names and ids, plus short-lived approval codes. It is used for spending limits and undo.
38
+
39
+ **What is not stored:** your campaign data, reports and performance numbers are fetched from Snapchat when you ask and are not kept. The service writes no log of your requests; Cloudflare may keep standard request metadata under its own terms.
40
+
41
+ **Who can read it:** the operator of the service holds the keys that protect the stored token and **could decrypt it**. Sign in only if you trust the operator. Your AI app sees what the tools return, under that app's own terms.
42
+
43
+ **Control:** the consent page asks separately for permission to make changes (off by default). `snap_disconnect` deletes everything stored about you. Also revoke the app in Snapchat Business Manager.
44
+
30
45
  This is an unofficial project and is not affiliated with or endorsed by Snap Inc.
package/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # Ads MCP for Snapchat
2
2
 
3
- A local [MCP](https://modelcontextprotocol.io) server that lets an AI assistant (Claude Code, Claude Desktop and other MCP clients) work with **your own** Snapchat ad account: read performance, audit campaigns, and make careful, reviewable changes. It also turns creators' **ad codes** into paused ads.
3
+ An [MCP](https://modelcontextprotocol.io) server that runs on your own computer, and lets an AI assistant (Claude Code, Claude Desktop and other MCP clients) work with **your own** Snapchat ad account: read performance, audit campaigns, and make careful, reviewable changes. It also turns creators' **ad codes** into paused ads. There is also a **hosted private test** that needs no install (see [Hosted version](#hosted-version-private-test)).
4
4
 
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. 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.
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 (55 everyday tools); type `all` in its Tool set field to see all 81.
9
9
 
10
10
  **Claude Code, Cursor, VS Code or a terminal:**
11
11
  ```bash
@@ -23,9 +23,9 @@ Snap runs its own hosted **Ads MCP server** (see Snap's developer documentation)
23
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
24
 
25
25
  ## What it is, and what it is not
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.
26
+ - **The local version 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. No ad account data leaves your computer except to Snap's API.
27
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".
28
- - **It is not a hosted service.** Services that only accept remote MCP servers (for example ChatGPT connectors) cannot use it as it is. Do not expose it on the internet.
28
+ - **The local version is not a public service.** Do not expose it on the internet. For apps that only accept remote MCP servers there is the separate, invitation-only [hosted test](#hosted-version-private-test); ChatGPT is not tested yet.
29
29
  - **Money limits are in your account's currency.** Defaults (`SNAP_MAX_DAILY_BUDGET=1000`, `SNAP_MAX_BID=50`) are deliberately conservative; set your own in `.env`.
30
30
 
31
31
  ## Snap's terms and data
@@ -59,7 +59,7 @@ First, once: in [Snap Business Manager](https://business.snapchat.com) open **Bu
59
59
 
60
60
  **Claude Desktop (no terminal):**
61
61
  1. Download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snapchat-ads-mcp/releases/latest) and double-click it. Claude Desktop shows an install screen.
62
- 2. Enter the Client ID and Client Secret, your highest daily budget and (optional) your main country. Leave **Read-only** on for now.
62
+ 2. Enter the Client ID and Client Secret, your highest daily budget and (optional) your main country. **Read-only** is off by default, so changes are allowed: each one is previewed and needs your approval, and everything created starts paused. Switch it on if you only want to look.
63
63
  3. In a chat, ask: **"Connect my Snapchat ad account."** Claude gives you a link; approve in the browser, paste back the address it lands on, and pick your ad account from the list.
64
64
  4. Quit and reopen Claude Desktop. Ask: "call snap_ping".
65
65
 
@@ -80,6 +80,20 @@ Settings, the change log and exports live in `~/.ads-mcp-for-snapchat/`, outside
80
80
  4. Start with `SNAP_READ_ONLY=1`: connect your MCP client, try `snap_ping`, a report, and a few previews, and compare the numbers with Ads Manager. Remove the setting when you are comfortable.
81
81
  5. Keep your client's permission prompt **on** for write tools.
82
82
 
83
+ ## Hosted version
84
+ A second way to use the same tools with **nothing to install**: a connector you add in an AI app by address, running on Cloudflare, at `https://ads-mcp-remote.ads-mcp.workers.dev/mcp`. **Be aware of its status:** it is run by one independent maintainer on a free plan, it is **unofficial**, it has **not had an independent security review**, and Snap has **not confirmed** that one shared app may serve other advertisers (if Snap objects, it can stop working for everyone; the local version with your own Snapchat app always works). Read the service's `/terms` and `/privacy` pages before signing in. The operator can restrict who signs in, can block a person, and can switch changes off for everyone at once.
85
+
86
+ What it does:
87
+ - You add the connector, sign in with Snapchat, and choose which ad account to use (`snap_connect`).
88
+ - **Read-only unless you tick "allow changes" on the consent page.** With changes allowed you get the same safety rules as the local version: everything created is paused, every change is previewed first with an approval code that works once for exactly that request, spending limits apply, and the change log lives in your own private database.
89
+ - Each person gets a separate private database. `snap_disconnect` deletes everything stored about you; also revoke the app in Snapchat Business Manager.
90
+ - Interactive cards (below) are shown in Claude with this version.
91
+ - **Works with apps that support remote MCP servers with sign-in** (OAuth with dynamic registration, which is what this server offers). It has been **tested with Claude only**. ChatGPT's custom connectors use the same standard, but it has **not been tested there**, and what ChatGPT allows depends on your plan.
92
+
93
+ What is stored, honestly: your Snapchat refresh token (encrypted) so the service can act for you, a change log, and your settings. **The operator of the service holds the keys and could decrypt the token**, so sign in only if you trust the operator. The page `/privacy` of the service says the same.
94
+
95
+ Limits that exist: sign-in endpoints are rate-limited per IP address, a person's tool calls are limited to 120 a minute, and each person's logs keep 90 days (at most 20,000 lines per log). Known gaps: not independently reviewed, the free Cloudflare plan's own limits cap how many people it can serve, and a few local-only tools (folder uploads, clipboard, customer-list files) do not work there. Code and design: [`remote/README.md`](remote/README.md) and [`remote/DESIGN.md`](remote/DESIGN.md). It is not part of the npm package.
96
+
83
97
  ## Safety rules (built in)
84
98
  - Every write tool works in **two steps**. `confirm=false` (the default) returns a preview and a single-use `approval_token`. To apply, the same arguments are sent again with `confirm=true` and that token. The token is bound to the tool, the ad account, the arguments and the state of the items at preview time: if anything changed, or the token is reused, expired or from another request, nothing is sent.
85
99
  - Everything that creates something (copies, clones, new ads, new creatives) is created **PAUSED**. Enabling is a separate step, and its preview shows the daily budget that would really start delivering (for a campaign: the budgets of its ACTIVE ad squads).
@@ -120,7 +134,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
120
134
  | `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. |
121
135
  | `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. |
122
136
  | `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. |
123
- | `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. |
137
+ | `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `core` (55 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. |
124
138
  | `SNAP_HUMAN_APPROVAL` | off | `elicit` = ask the user through the MCP client before every write |
125
139
  | `SNAP_APPROVAL_TTL_SECONDS` | 600 | Lifetime of an approval token |
126
140
  | `SNAP_REPEAT_WINDOW_SECONDS` | 600 | An identical create, copy, claim or upload is refused within this time |
@@ -172,16 +186,19 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
172
186
  | `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. |
173
187
  | `snap_connect` | connect an ad account from inside the chat (link, pasted address, account choice); saves access on this computer, changes no ads |
174
188
  | `snap_list_campaigns`, `snap_list_adsquads`, `snap_list_ads`, `snap_list_creatives`, `snap_get_entity`, `snap_get_media`, `snap_get_stats` | read |
175
- | `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 |
189
+ | `snap_dashboard`, `snap_campaign_board` | read: interactive cards (see "Interactive cards" below): an account dashboard (spend, ROAS, purchases, pacing, alerts, 7/14/30 days) and a campaign or ad squad board with Pause, Resume and budget buttons. Without card support the same numbers come back as data |
176
190
  | `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) |
177
191
  | `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 |
178
192
  | `snap_review_issues` | read: rejected / pending ads with Snap's reasons |
193
+ | `snap_delivery_check` | read: why an active ad squad is not spending: paused campaign, schedule not started or ended, no ads or none approved, no budget, missing pixel, inactive account; passes Snap's own delivery status through |
179
194
  | `snap_pixel_health` | read: pixel signal readiness and event-quality issues, top priority first |
180
195
  | `snap_creative_fatigue` | read: which ads are tired (ROAS down 30%+ with higher frequency or lower swipe rate), which to replace first |
181
196
  | `snap_report_async_start`, `snap_report_async_status`, `snap_report_async_download` | read: very large CSV reports saved to `exports/` |
182
197
  | `snap_api_get` | read-only GET for anything else (allow-listed paths, never writes) |
183
198
  | `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 |
184
199
  | `snap_change_log` | read the local log |
200
+ | `snap_change_history` | read: the changes made through this server, newest first, with before and after values and an Undo button for each one that can be reverted (interactive card) |
201
+ | `snap_setup_check` | read: a checklist of the login, ad account, pixel, brand profile, main country, change log and human approval, plus the money limits in use (interactive card) |
185
202
  | `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) |
186
203
  | `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 |
187
204
  | `snap_set_targeting` | change countries, age, gender, interests, device OS, include segments, stop excluding segments; everything else is kept |
@@ -208,12 +225,16 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
208
225
  | `snap_influencer_ad` | the whole influencer flow in one step: claim, wait for media, creative, paused ad |
209
226
 
210
227
  ## Interactive cards (MCP Apps)
211
- 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:
228
+ In AI apps that support [MCP Apps](https://modelcontextprotocol.io), some tools show a small interactive card inside the chat instead of only text. **Where they appear:** Claude Desktop shows them with the [hosted version](#hosted-version-private-test); with the local Claude Desktop extension it shows the plain data instead, and other apps may do either, because card support is up to each app and is still new. Nothing depends on them: every answer also arrives as text and data.
212
229
  - **`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.
213
- - **`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**.
214
- - **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.
215
-
216
- 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.
230
+ - **`snap_dashboard`** also lists alerts from the same days (a spend spike or drop, missing purchases, ROAS or cost per purchase moving sharply), each one dismissible.
231
+ - **`snap_campaign_board`**: campaigns or ad squads (switch with the buttons) with spend, ROAS and purchases for 7, 14 or 30 days, sorting and a "needs a look" filter. **Pause**, **Resume** and, on ad squads, **−20% / +20%** budget buttons first show the change and its spending effect (the daily budget that would start delivering, and the 24-hour total), and nothing happens until you press **Confirm**.
232
+ - **`snap_budget_advice`**: the suggested budget moves as a list to tick; the net change updates as you tick, and **Apply** previews and applies each selected move with its own approval token, one by one, stopping at the first refusal.
233
+ - **`snap_change_history`**: a filterable timeline of changes with before and after values and an **Undo** button that previews the undo first.
234
+ - **`snap_setup_check`**: what is connected and what is missing, the money limits, and whether you are asked before every change.
235
+ - **Preview card**: every tool that previews a change shows its preview as a card that leads with the spending effect in one line, then what changes, a countdown until the approval expires, **Apply** and **Cancel**, and after a single-item edit an **Undo** button (which previews the undo first).
236
+
237
+ 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 (each card also has a **Light mode / Dark mode** button). In apps without card support nothing changes: the same answers arrive as text and data.
217
238
 
218
239
  ## Examples, permissions and limits
219
240
  **Things to ask your assistant** (each names the tool it will use):
package/SECURITY.md CHANGED
@@ -28,3 +28,15 @@ Text that comes back from outside (competitors' ads, page contents, ad review re
28
28
 
29
29
  ## Safety design
30
30
  Write tools need the approval token of a preview of the exact same request, create objects paused, enforce absolute and relative money limits that fail closed, only touch the configured ad account, and record every write in an audit log. The approval token is not a human signature: keep your MCP client's permission prompt on for write tools (see README, "What the approval token is not"). This tool edits real campaigns: review each preview before approving.
31
+
32
+ ## Hosted version (private test)
33
+ The hosted version in `remote/` may be open to anyone with a Snapchat login and has **not** had an independent security review. The operator can restrict sign-in (`ALLOWED_MEMBERS`), block a person (`BLOCKED_MEMBERS`) and switch changes off for everyone (`HOSTED_READ_ONLY=1`). What it does for safety: sign-in through Cloudflare's OAuth library, an allowlist of approved Snapchat members, read-only unless the person opts in to changes, one private database per user, the stored Snapchat token encrypted with a key derived per user, approval codes kept per user, and the same previews, limits and paused-by-default creation as the local version. Rate limits: sign-in endpoints per IP address (registrations 10 an hour, other sign-in paths 60 a minute) and 120 tool calls a minute per person; logs are trimmed to 90 days and 20,000 lines. What it does **not** have yet: independent review, and the operator can decrypt stored tokens. `DEV_FAKE_SNAP_URL` exists for the local test only and must never be set on a deployed Worker. Report problems with it the same way as for the local tool (below).
34
+
35
+ ## Known limits (from the independent audit of 0.9.6)
36
+ These are real and not fixed in code. Know them before you rely on the guards.
37
+ - **Shared login: your refresh token is a bearer secret.** In shared-login mode the login service swaps any refresh token issued to the shared app for an access token, without needing a secret from your computer. Anyone who copies the token out of your settings file can use it until you revoke the app in Snapchat Business Manager. The service has **no rate limit yet**, so heavy use of its renew endpoint could get the shared app limited for everyone. A per-address and per-token limit (a Cloudflare Workers rate limit) is the fix and has to be set up in the deployed service. If this matters to you, use your own Snapchat OAuth app.
38
+ - **The 24-hour spending limit is kept in one change log file.** Two server processes for the same account with different log files each get a full allowance, deleting the log (or pointing `SNAP_LOG_FILE` at `/dev/null`) resets it, and entries dated more than a minute in the future are ignored, so setting the clock back also resets it. The limit protects against mistakes and a misled assistant, not against someone who can edit files on your computer.
39
+ - **Asking you is optional.** `SNAP_HUMAN_APPROVAL` (the Desktop extension's "Ask me before every change") is off by default, because an app that cannot show the question would refuse every change. With it off, the assistant previews and applies changes itself, inside your limits. Turn it on if you want to be asked.
40
+ - **Card pages talk to the chat app with `postMessage(..., "*")`.** Incoming messages are accepted only from the window that embeds the card, so this is safe while the chat app is the only parent; the target origin cannot be narrowed because the app's origin is not known to the card.
41
+ - **Settings in your environment win over the settings file for limits** that the Desktop extension sets itself, and a person or program that can edit your settings file can change limits after a restart.
42
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ads-mcp-for-snapchat",
3
- "version": "0.9.8",
3
+ "version": "0.10.0",
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",
package/src/activation.js CHANGED
@@ -39,6 +39,7 @@ export function scheduleOpensDelivery(current, patch, now = Date.now()) {
39
39
  export async function activationImpact(client, entity, items, policy, { now = Date.now() } = {}) {
40
40
  const line = (squad, why) => squadLine(squad, why, now);
41
41
  const started = new Map(); // squad id -> line
42
+ const squadCampaign = new Map(); // squad id -> campaign id
42
43
  const later = [];
43
44
  const campaignCaps = [];
44
45
  const campaigns = new Map();
@@ -50,12 +51,18 @@ export async function activationImpact(client, entity, items, policy, { now = Da
50
51
  if (entity === "campaign") {
51
52
  campaigns.set(obj.id, obj);
52
53
  const squads = (await client.listChildren("campaign", obj.id, "adsquad")).filter((s) => s.status === "ACTIVE");
53
- for (const s of squads) started.set(s.id, line(s, `ACTIVE ad squad of campaign "${obj.name}"`));
54
+ for (const s of squads) {
55
+ started.set(s.id, line(s, `ACTIVE ad squad of campaign "${obj.name}"`));
56
+ squadCampaign.set(s.id, obj.id);
57
+ }
54
58
  if (obj.daily_budget_micro != null) campaignCaps.push({ campaign_id: obj.id, name: obj.name, campaign_daily_budget: money(obj.daily_budget_micro) });
55
59
  if (obj.lifetime_spend_cap_micro != null) campaignCaps.push({ campaign_id: obj.id, name: obj.name, campaign_lifetime_spend_cap: money(obj.lifetime_spend_cap_micro) });
56
60
  } else if (entity === "adsquad") {
57
61
  const parent = await campaign(obj.campaign_id);
58
- if (parent.status === "ACTIVE") started.set(obj.id, line(obj, "its campaign is ACTIVE"));
62
+ if (parent.status === "ACTIVE") {
63
+ started.set(obj.id, line(obj, "its campaign is ACTIVE"));
64
+ squadCampaign.set(obj.id, obj.campaign_id);
65
+ }
59
66
  else later.push({ ...line(obj, `campaign "${parent.name}" is ${parent.status}`), starts: "when the campaign is enabled" });
60
67
  } else if (entity === "ad") {
61
68
  const squad = await client.getEntity("adsquad", obj.ad_squad_id);
@@ -63,14 +70,45 @@ export async function activationImpact(client, entity, items, policy, { now = Da
63
70
  if (squad.status === "ACTIVE" && parent.status === "ACTIVE") {
64
71
  const siblings = await client.listChildren("adsquad", squad.id, "ad");
65
72
  const alreadyDelivering = siblings.some((a) => a.id !== obj.id && a.status === "ACTIVE");
66
- if (!alreadyDelivering) started.set(squad.id, line(squad, `ad "${obj.name}" would be its first ACTIVE ad`));
73
+ if (!alreadyDelivering) {
74
+ started.set(squad.id, line(squad, `ad "${obj.name}" would be its first ACTIVE ad`));
75
+ squadCampaign.set(squad.id, squad.campaign_id);
76
+ }
67
77
  } else {
68
78
  later.push({ ...line(squad, `ad squad is ${squad.status}, campaign is ${parent.status}`), starts: "when its ad squad and campaign are enabled" });
69
79
  }
70
80
  }
71
81
  }
72
82
  const lines = [...started.values()];
73
- const total = round2(lines.reduce((n, l) => n + (l.counted_per_day ?? l.daily_budget), 0));
83
+ const counted = (l) => l.counted_per_day ?? l.daily_budget;
84
+ // Campaign-level daily budgets (the campaign has one budget and its ad squads have none). They start spending too, so they are
85
+ // counted and limited like an ad squad's: a campaign being enabled counts max(its squads' budgets, its own budget); an ad squad or
86
+ // ad that would be the first to deliver under an ACTIVE campaign with its own budget and no budget of its own counts that budget.
87
+ const campaignLines = [];
88
+ if (entity === "campaign") {
89
+ for (const obj of items) {
90
+ const cb = obj.daily_budget_micro > 0 ? money(obj.daily_budget_micro) : 0;
91
+ if (!cb) continue;
92
+ const squadsSum = lines.filter((l) => squadCampaign.get(l.adsquad_id) === obj.id).reduce((n, l) => n + counted(l), 0);
93
+ campaignLines.push({ campaign_id: obj.id, name: obj.name, campaign_daily_budget: cb, counted: round2(Math.max(0, cb - squadsSum)) });
94
+ }
95
+ } else {
96
+ const done = new Set();
97
+ for (const l of lines) {
98
+ const cid = squadCampaign.get(l.adsquad_id);
99
+ const camp = campaigns.get(cid);
100
+ const cb = camp?.daily_budget_micro > 0 ? money(camp.daily_budget_micro) : 0;
101
+ if (!cb || counted(l) > 0 || done.has(cid) || camp.status !== "ACTIVE") continue;
102
+ done.add(cid);
103
+ const others = (await client.listChildren("campaign", cid, "adsquad")).some((s) => s.status === "ACTIVE" && s.id !== l.adsquad_id);
104
+ campaignLines.push({ campaign_id: cid, name: camp.name, campaign_daily_budget: cb, counted: others ? 0 : cb });
105
+ }
106
+ }
107
+ const overCampaign = campaignLines.filter((c) => c.campaign_daily_budget > policy.maxDailyBudget && (entity === "campaign" || c.counted > 0));
108
+ if (overCampaign.length) {
109
+ throw new Error(`Refusing to enable: ${overCampaign.map((c) => `campaign "${c.name}" has a daily budget of ${c.campaign_daily_budget}`).join("; ")}, above the absolute limit of ${policy.maxDailyBudget} (SNAP_MAX_DAILY_BUDGET). Only the account owner can raise that limit, in .env, followed by a restart.`);
110
+ }
111
+ const total = round2(lines.reduce((n, l) => n + counted(l), 0) + campaignLines.reduce((n, c) => n + c.counted, 0));
74
112
  const lifetime = round2(lines.reduce((n, l) => n + (l.lifetime_budget ?? 0), 0));
75
113
  const over = lines.filter((l) => l.daily_budget > policy.maxDailyBudget);
76
114
  if (over.length) {
@@ -89,6 +127,7 @@ export async function activationImpact(client, entity, items, policy, { now = Da
89
127
  ad_squads_that_start_delivering: lines,
90
128
  starts_later: later.length ? later : undefined,
91
129
  campaign_level_budgets: campaignCaps.length ? campaignCaps : undefined,
130
+ campaign_budgets_counted: campaignLines.some((c) => c.counted > 0) ? campaignLines : undefined,
92
131
  limit_per_call: policy.maxActivationDailyBudget,
93
132
  note: "Amounts are in account currency. Ad squads that are already delivering are not counted. A squad with only a lifetime budget is counted at its pace per day (counted_per_day).",
94
133
  };
package/src/approval.js CHANGED
@@ -58,7 +58,7 @@ export function explainChange(before, after) {
58
58
  }
59
59
 
60
60
  export class ApprovalStore {
61
- constructor({ ttlMs = 600_000, repeatWindowMs = 600_000, now = Date.now, max = 500 } = {}) {
61
+ constructor({ ttlMs = 600_000, repeatWindowMs = 600_000, now = Date.now, max = 2000 } = {}) {
62
62
  this.ttlMs = ttlMs;
63
63
  this.repeatWindowMs = repeatWindowMs;
64
64
  this.now = now;
@@ -0,0 +1,140 @@
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>Budget suggestions</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;--fb-warnbg:#fff7e8;--fb-warnline:#f0d9ad}
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;--fb-warnbg:#3a2f1c;--fb-warnline:#6b5527}}
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;--fb-warnbg:#fff7e8;--fb-warnline:#f0d9ad}
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;--fb-warnbg:#3a2f1c;--fb-warnline:#6b5527}
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));--warnbg:var(--fb-warnbg);--warnline:var(--fb-warnline)}
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:17px;margin:0}.sub{color:var(--muted);font-size:12px}
16
+ .card{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:14px}
17
+ .badge{display:inline-block;padding:1px 10px;border-radius:999px;font-size:11px;border:1px solid var(--warn);color:var(--warn)}
18
+ .badge.done{border-color:var(--good);color:var(--good)}.badge.off{border-color:var(--border);color:var(--muted)}
19
+ .pill{display:inline-block;padding:1px 8px;border-radius:999px;font-size:11px;border:1px solid var(--border);margin-right:6px}
20
+ .pill.on{color:var(--good);border-color:var(--good)}.pill.flag{border-color:var(--warn);color:var(--warn)}
21
+ .impact{background:var(--warnbg);border:1px solid var(--warnline);border-radius:10px;padding:10px 12px;font-weight:600;margin:10px 0}
22
+ .impact.calm{background:var(--bg);border-color:var(--border);font-weight:500}
23
+ dl{margin:10px 0;display:grid;grid-template-columns:max-content 1fr;gap:4px 14px}
24
+ dt{color:var(--muted)}dd{margin:0;overflow-wrap:anywhere}
25
+ pre{margin:6px 0 0;white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.4 ui-monospace,Menlo,monospace;background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:8px}
26
+ .track{height:10px;background:var(--border);border-radius:999px;overflow:hidden;display:flex}
27
+ .track span{display:block;height:100%}
28
+ .warn{color:var(--warn);margin:6px 0}.err{color:var(--bad);margin:6px 0}.ok{color:var(--good);margin:6px 0}
29
+ .btns{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px;align-items:center}
30
+ button{min-height:44px;min-width:44px;padding:0 16px;border-radius:10px;border:1px solid var(--border);background:var(--bg);color:var(--text);font:inherit;cursor:pointer}
31
+ button.primary{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
32
+ button.link{border:0;background:none;color:var(--accent);padding:0;min-height:32px}
33
+ button.chip{min-height:36px;border-radius:999px;padding:0 12px}
34
+ button[aria-pressed=true]{background:var(--accent);border-color:var(--accent);color:#fff}
35
+ button:disabled{opacity:.55;cursor:default}
36
+ button:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
37
+ .row{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:12px;margin-bottom:10px}
38
+ .row.open{border-color:var(--accent)}
39
+ .top{display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap}
40
+ .name{font-weight:650;overflow-wrap:anywhere}.meta{color:var(--muted);font-size:12px;margin-top:2px}
41
+ .panel{margin-top:10px;border-top:1px dashed var(--border);padding-top:10px}
42
+ .bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;margin-bottom:12px}
43
+ .seg{display:flex;gap:6px;flex-wrap:wrap}
44
+ .stepper{display:flex;align-items:center;border:1px solid var(--border);border-radius:10px;background:var(--bg)}
45
+ .stepper button{border:0;background:none;font-size:18px}
46
+ .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}
47
+ @keyframes sk{to{background-position:-200% 0}}
48
+ @media (prefers-reduced-motion:reduce){.skeleton{animation:none}}
49
+
50
+ </style>
51
+ </head>
52
+ <body>
53
+ <main id="app"><div class="skeleton"></div><div class="skeleton"></div></main>
54
+ <!--BRIDGE-->
55
+ <script>
56
+ (function () {
57
+ const { el, num } = window.snapApp;
58
+ const $ = (id) => document.getElementById(id);
59
+ const state = { items: [], on: {}, status: {}, running: false, note: null, base: null };
60
+
61
+ function load(d) {
62
+ state.base = d;
63
+ state.items = [...(d.decreases || []), ...(d.increases || [])].map((x) => Object.assign({}, x, { diff: Math.round((x.to - x.from) * 100) / 100 }));
64
+ state.on = Object.fromEntries(state.items.map((x) => [x.adsquad_id, true]));
65
+ state.status = {};
66
+ render();
67
+ }
68
+
69
+ function render() {
70
+ const root = $("app"); root.textContent = "";
71
+ const d = state.base;
72
+ if (!d) return;
73
+ if (!state.items.length) { root.append(el("div", { class: "card" }, el("h1", null, "Budget suggestions"), el("div", { class: "sub" }, d.note || "Nothing to move right now."))); window.snapApp.resize(); return; }
74
+ const sel = state.items.filter((x) => state.on[x.adsquad_id]);
75
+ const net = sel.reduce((n, x) => n + x.diff, 0);
76
+ const adds = sel.reduce((n, x) => n + Math.max(0, x.diff), 0);
77
+ const card = el("div", { class: "card" });
78
+ card.append(el("h1", null, "Budget suggestions"), el("div", { class: "sub" }, "Median ROAS " + num(d.median_roas) + " over " + (d.window ? d.window.days : "?") + " days · " + d.squads_compared + " ad squads compared"));
79
+ card.append(el("div", { class: "impact" + (adds > 0 ? "" : " calm") }, sel.length + " of " + state.items.length + " selected · net " + (net > 0 ? "+" : "") + num(net) + " per day" + (adds > 0 ? " · adds " + num(adds) + " per day before cuts" : "")));
80
+ const quick = el("div", { class: "seg", style: "margin-bottom:8px" },
81
+ el("button", { type: "button", class: "chip", disabled: state.running, onclick: () => setAll(() => true) }, "Select all"),
82
+ el("button", { type: "button", class: "chip", disabled: state.running, onclick: () => setAll((x) => x.diff < 0) }, "Only cuts"),
83
+ el("button", { type: "button", class: "chip", disabled: state.running, onclick: () => setAll(() => false) }, "None"));
84
+ card.append(quick);
85
+ for (const x of state.items) {
86
+ const id = "s-" + x.adsquad_id;
87
+ const st = state.status[x.adsquad_id];
88
+ const box = el("input", { type: "checkbox", id, disabled: state.running || !!(st && st.ok) , onchange: () => { state.on[x.adsquad_id] = !state.on[x.adsquad_id]; render(); } });
89
+ box.checked = !!state.on[x.adsquad_id];
90
+ box.style.cssText = "width:20px;height:20px;accent-color:var(--accent)";
91
+ const diff = el("div", { style: "font-weight:650" }, (x.diff > 0 ? "+" : "") + num(x.diff) + "/day");
92
+ diff.style.color = x.diff > 0 ? "var(--warn)" : "var(--good)";
93
+ card.append(el("label", { for: id, style: "display:grid;grid-template-columns:28px minmax(0,1fr) auto;gap:10px;align-items:center;padding:10px 0;border-top:1px solid var(--border);cursor:pointer" }, box,
94
+ el("div", { style: "min-width:0" }, el("div", { class: "name", dir: "auto" }, x.adsquad), el("div", { class: "sub" }, x.why), st ? el("div", { class: st.ok ? "ok" : st.err ? "err" : "sub" }, st.text) : null),
95
+ el("div", { style: "text-align:right;white-space:nowrap" }, el("div", { style: "font-size:13px" }, num(x.from) + " → " + num(x.to)), diff)));
96
+ }
97
+ if (state.note) card.append(el("div", { class: state.note.err ? "err" : "ok" }, state.note.text));
98
+ card.append(el("div", { class: "btns" }, el("button", { type: "button", class: "primary", disabled: state.running || !sel.some((x) => !(state.status[x.adsquad_id] || {}).ok), onclick: () => applyAll() }, state.running ? "Applying…" : "Apply " + sel.length + " change" + (sel.length === 1 ? "" : "s"))));
99
+ card.append(el("div", { class: "sub" }, "Each one is previewed and applied with its own approval token, one after another, stopping at the first refusal. Changing a budget can restart Snap's learning."));
100
+ root.append(card);
101
+ window.snapApp.resize();
102
+ }
103
+
104
+ function setAll(fn) { if (state.running) return; state.on = Object.fromEntries(state.items.map((x) => [x.adsquad_id, fn(x)])); render(); }
105
+
106
+ async function applyAll() {
107
+ const todo = state.items.filter((x) => state.on[x.adsquad_id] && !(state.status[x.adsquad_id] || {}).ok);
108
+ state.running = true; state.note = null; render();
109
+ let done = 0;
110
+ for (const x of todo) {
111
+ const args = { entity: "adsquad", id: x.adsquad_id, daily_budget: x.to };
112
+ state.status[x.adsquad_id] = { text: "Previewing…" }; render();
113
+ try {
114
+ const p = await window.snapApp.run("snap_set_daily_budget", args);
115
+ if (!p.ok || !p.data || !p.data.approval_token) { state.status[x.adsquad_id] = { err: true, text: p.text || "No approval token in the preview." }; break; }
116
+ // A warning in the preview (an unusual amount, a repeat of a recent change, read-only) is never applied unseen: stop and say so.
117
+ const warning = (p.data.budget_warning && p.data.budget_warning.message) || p.data.duplicate_warning || p.data.read_only;
118
+ if (warning) { state.status[x.adsquad_id] = { err: true, text: "Not applied: " + warning + " Change this one from its own preview in the chat." }; break; }
119
+ state.status[x.adsquad_id] = { text: "Applying…" }; render();
120
+ const r = await window.snapApp.run("snap_set_daily_budget", Object.assign({}, args, { confirm: true, approval_token: p.data.approval_token }));
121
+ if (!r.ok) { state.status[x.adsquad_id] = { err: true, text: r.text }; break; }
122
+ state.status[x.adsquad_id] = { ok: true, text: "Applied." };
123
+ done++;
124
+ } catch (e) { state.status[x.adsquad_id] = { err: true, text: e.message }; break; }
125
+ render();
126
+ }
127
+ state.running = false;
128
+ state.note = done === todo.length ? { text: done + " budget" + (done === 1 ? "" : "s") + " changed. Undo any of them from the change history." } : { err: true, text: "Stopped after " + done + " of " + todo.length + ". The rest were not sent." };
129
+ render();
130
+ }
131
+
132
+ window.snapApp.connect({
133
+ "ui/notifications/tool-result": (r) => { if (r && r.isError) { $("app").textContent = window.snapApp.textOf(r); return; } load(window.snapApp.dataOf(r) || {}); },
134
+ error: (e) => { $("app").textContent = "Not connected to the chat app: " + e.message; },
135
+ });
136
+ })();
137
+
138
+ </script>
139
+ </body>
140
+ </html>