ads-mcp-for-snapchat 0.9.9 → 0.11.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/.env.example +2 -1
- package/ARCHITECTURE.md +7 -3
- package/CHANGELOG.md +45 -0
- package/PRIVACY.md +16 -1
- package/README.md +56 -10
- package/SECURITY.md +3 -0
- package/package.json +1 -1
- package/src/admin.js +65 -0
- package/src/apps/bridge.js +29 -4
- package/src/apps/preview.html +37 -8
- package/src/apps/start.html +138 -0
- package/src/apps/theme.css +58 -0
- package/src/apps.js +40 -11
- package/src/audit-log.js +9 -9
- package/src/audit.js +171 -0
- package/src/brand.js +16 -0
- package/src/changes.js +8 -5
- package/src/details.js +97 -0
- package/src/env.js +4 -2
- package/src/fatigue.js +21 -0
- package/src/find.js +69 -0
- package/src/hygiene.js +38 -0
- package/src/identity.js +15 -0
- package/src/index.js +10 -1
- package/src/insights.js +13 -4
- package/src/instructions.js +10 -0
- package/src/interactive.js +2 -1
- package/src/media-url.js +96 -0
- package/src/oauth.js +18 -0
- package/src/profiles.js +55 -0
- package/src/readers.js +9 -0
- package/src/snap.js +5 -0
- package/src/start.js +71 -0
- package/src/storage.js +36 -0
- package/src/tools.js +174 -37
- package/src/toolsets.js +26 -12
- package/src/tz.js +15 -0
- package/src/zone.js +25 -0
package/.env.example
CHANGED
|
@@ -25,7 +25,8 @@ SNAP_REPORT_UTC_OFFSET=+00:00
|
|
|
25
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)
|
|
26
26
|
# Optional: SNAP_HOME=/some/folder (where settings, the change log and exports live; default ~/.ads-mcp-for-snapchat for an npm install)
|
|
27
27
|
# Optional: SNAP_PORTFOLIO_FILES=/abs/path/.env,/abs/path/.env.account2 (accounts shown side by side by snap_portfolio_summary)
|
|
28
|
-
# Optional: SNAP_TOOLSETS=
|
|
28
|
+
# Optional: SNAP_TOOLSETS=lite (24 everyday tools, short descriptions) or SNAP_COMPACT=1 (short descriptions for any tool set)
|
|
29
|
+
# Optional: SNAP_TOOLSETS=setup,reports,checks (show only these tool groups: core, lite, setup, read, reports, checks, changes, create; default all)
|
|
29
30
|
# Optional: SNAP_MAX_LIFETIME_BUDGET, SNAP_MAX_ACTIVATION_DAILY_BUDGET, SNAP_MAX_ADDED_DAILY_BUDGET_24H, SNAP_ACCOUNT_CURRENCY=USD,
|
|
30
31
|
# SNAP_READ_ONLY=1, SNAP_HUMAN_APPROVAL=elicit (see README "Safety settings")
|
|
31
32
|
# 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
|
|
3
|
+
For contributors. Unofficial MCP server (Node ESM) for the Snapchat Marketing API: 87 tools (62 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
|
|
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/`)
|
|
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
|
-
-
|
|
43
|
+
- Independent review and Snap's confirmation: the hosted version is open to anyone with a Snapchat login and has per-IP and per-person rate limits, but it has had no independent security review, the operator can decrypt stored tokens, and Snap has not confirmed that one shared app may serve other advertisers.
|
|
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,5 +1,50 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.11.0 (2026-11-26)
|
|
4
|
+
The hosted version grew up and the local one gets everything it learned: shorter answers, a first-run guide, more tools, and fixes found by real accounts.
|
|
5
|
+
|
|
6
|
+
**New**
|
|
7
|
+
- **`snap_start_here`**: a first-run guide (who is connected, read-only or not, limits, ad account or a list to pick from, a snapshot, warnings, eight things to say next). In apps that draw cards it shows a start card with a progress bar and one-tap first wins.
|
|
8
|
+
- **`snap_find`**: find campaigns, ad squads or ads by name (Arabic spellings are treated alike). `snap_connect` takes an ad account name as well as an id.
|
|
9
|
+
- **`snap_account_details`**: one tool for many read-only lists: invoices, transactions, lead forms, a lead count (no lead details), mobile apps, event details, interaction zones, offer disclaimers, phone numbers (masked), sponsored content, organizations, organization pixels, media stats, catalog products.
|
|
10
|
+
- **`snap_account_admin`** (settings, billing centers, who has access with which role, emails masked) and **`snap_list_profiles`** (public profiles; if Snapchat offers no list, read from the account's own creatives). Creatives now pick the only public profile automatically.
|
|
11
|
+
- **`snap_upload_media_from_url`**: upload a JPEG, PNG, MP4 or MOV (up to 32 MB) from a public https link, for the hosted version. https only, public domain names, redirects checked.
|
|
12
|
+
- **More targeting lookups**: genders, advanced demographics, carriers, connection types, iOS and Android versions, device models, postal codes.
|
|
13
|
+
- **Lite tool set** (`SNAP_TOOLSETS=lite`: 24 tools, about 7,800 tokens instead of about 25,500) and `SNAP_COMPACT=1` for short descriptions in any set.
|
|
14
|
+
- **Overdue invoice warning** in `snap_billing_check`.
|
|
15
|
+
- **Short answers**: the server tells the AI to answer with the finding first, a few bullets and one next step. `snap_spend_pacing` lists only the ad squads that need attention (`show_all` for everything).
|
|
16
|
+
- **Cards**: a start card; the preview card shows "Already applied" instead of an error plus Apply when an approval was already used.
|
|
17
|
+
- **Hosted**: one switch (`PAID_PLAN = "1"`) raises the request and rate limits after subscribing to Cloudflare's paid plan; sign-in errors explain what to do.
|
|
18
|
+
|
|
19
|
+
**Fixed**
|
|
20
|
+
- Daily reports start at midnight in the ad account's own time zone, including across clock changes (daylight saving). Without this the hosted dashboard failed for any account outside UTC.
|
|
21
|
+
- `snap_delivery_check`, `snap_spend_pacing` and the dashboard no longer fail on accounts with thousands of campaigns (fewer requests per call, scoped reads).
|
|
22
|
+
- `snap_account_admin` and `snap_list_profiles` crashed on unregistered list types; found on a real account and now guarded by tests.
|
|
23
|
+
|
|
24
|
+
**Tests**: a sweep runs every tool through the real client on empty and filled lists and fails on any crash inside our own code; another check makes sure every list type the code asks for is registered; the hosted end-to-end check runs the recent read tools in the real Worker runtime.
|
|
25
|
+
|
|
26
|
+
**Counts**: 87 tools in all, 62 in the default core set.
|
|
27
|
+
|
|
28
|
+
## 0.10.0 (2026-11-25)
|
|
29
|
+
The biggest release so far. It also contains 0.9.10, which was never published on its own.
|
|
30
|
+
|
|
31
|
+
**New**
|
|
32
|
+
- **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.
|
|
33
|
+
- **`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.
|
|
34
|
+
- **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.
|
|
35
|
+
- **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.
|
|
36
|
+
- **Name, description, website and icon** for the server (`assets/logo.svg`).
|
|
37
|
+
|
|
38
|
+
**Safer**
|
|
39
|
+
- **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.
|
|
40
|
+
- The undo preview now says where the item ends up ("back to daily budget 5").
|
|
41
|
+
- Change log and audit log storage moved behind a small storage layer (files by default; no change for the local server).
|
|
42
|
+
|
|
43
|
+
**Docs:** README, ARCHITECTURE, PRIVACY, SECURITY and CONTRIBUTING describe the hosted version honestly, including what it lacks.
|
|
44
|
+
|
|
45
|
+
## 0.9.10 (2026-11-21)
|
|
46
|
+
- 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.
|
|
47
|
+
|
|
3
48
|
## 0.9.9 (2026-11-21)
|
|
4
49
|
|
|
5
50
|
Fixes from an independent security audit of 0.9.6 (every finding was reproduced with a test first):
|
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
|
|
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 version**.
|
|
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
|
|
31
|
+
This is separate from the local tool. It runs on the maintainer's Cloudflare account and is open to anyone with a Snapchat login; the operator may block a person or switch changes off for everyone. 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,26 @@
|
|
|
1
1
|
# Ads MCP for Snapchat
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An [MCP](https://modelcontextprotocol.io) server, available as a **hosted connector (nothing to install)** or **on your own computer**, 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.
|
|
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
|
-
|
|
8
|
+
|
|
9
|
+
### Option 1 (easiest): the hosted connector, nothing to install
|
|
10
|
+
1. In your AI app, add this address as a **custom connector**:
|
|
11
|
+
```
|
|
12
|
+
https://ads-mcp-remote.ads-mcp.workers.dev/mcp
|
|
13
|
+
```
|
|
14
|
+
In Claude: **Settings, Connectors, Add custom connector**, name it `Ads MCP for Snapchat`, and paste the address. Other apps that support remote MCP servers with sign-in use the same address (only Claude has been tested so far).
|
|
15
|
+
2. Press **Connect** and sign in with the same Snapchat login you use for Ads Manager. It is **read-only** unless you tick "allow changes" on the page. Finish it in one tab within a few minutes.
|
|
16
|
+
3. In a new chat say: **"Use snap_start_here"**. Pick your ad account by name, then ask in plain words: "How is my account doing this week?", "Which active ad squads are not spending, and why?", "Show my campaigns".
|
|
17
|
+
|
|
18
|
+
This is **unofficial** and run by one independent maintainer. Before you sign in, read [what the hosted version stores](#hosted-version) (your Snapchat login token is kept, encrypted, so the service can act for you; you can delete everything with `snap_disconnect` and revoke the app in Snapchat at any time).
|
|
19
|
+
|
|
20
|
+
### Option 2: on your own computer (private, no third-party server)
|
|
21
|
+
Pick this if you do not want any server run by someone else to hold your Snapchat login.
|
|
22
|
+
|
|
23
|
+
**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." You log in with Snapchat in your browser and pick your ad account.
|
|
9
24
|
|
|
10
25
|
**Claude Code, Cursor, VS Code or a terminal:**
|
|
11
26
|
```bash
|
|
@@ -13,6 +28,14 @@ npx -y ads-mcp-for-snapchat setup
|
|
|
13
28
|
```
|
|
14
29
|
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
30
|
|
|
31
|
+
| | Hosted (Option 1) | On your computer (Option 2) |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| Install | none | one file or one command |
|
|
34
|
+
| Where your login token lives | encrypted on the maintainer's Cloudflare account | only on your computer |
|
|
35
|
+
| Interactive cards in Claude | yes | not in the Claude Desktop extension |
|
|
36
|
+
| Works with ChatGPT and other remote-only apps | designed for it, not tested yet | no |
|
|
37
|
+
| Folder uploads and customer-list files | no | yes |
|
|
38
|
+
|
|
16
39
|
## How this relates to Snap's own Ads MCP server
|
|
17
40
|
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
41
|
|
|
@@ -23,9 +46,9 @@ Snap runs its own hosted **Ads MCP server** (see Snap's developer documentation)
|
|
|
23
46
|
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
47
|
|
|
25
48
|
## What it is, and what it is not
|
|
26
|
-
- **
|
|
49
|
+
- **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
50
|
- **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
|
-
- **
|
|
51
|
+
- **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 [hosted version](#hosted-version), open to anyone with a Snapchat login; ChatGPT is not tested yet.
|
|
29
52
|
- **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
53
|
|
|
31
54
|
## Snap's terms and data
|
|
@@ -59,7 +82,7 @@ First, once: in [Snap Business Manager](https://business.snapchat.com) open **Bu
|
|
|
59
82
|
|
|
60
83
|
**Claude Desktop (no terminal):**
|
|
61
84
|
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.
|
|
85
|
+
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
86
|
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
87
|
4. Quit and reopen Claude Desktop. Ask: "call snap_ping".
|
|
65
88
|
|
|
@@ -80,6 +103,20 @@ Settings, the change log and exports live in `~/.ads-mcp-for-snapchat/`, outside
|
|
|
80
103
|
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
104
|
5. Keep your client's permission prompt **on** for write tools.
|
|
82
105
|
|
|
106
|
+
## Hosted version
|
|
107
|
+
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.
|
|
108
|
+
|
|
109
|
+
What it does:
|
|
110
|
+
- You add the connector, sign in with Snapchat, and choose which ad account to use (`snap_connect`).
|
|
111
|
+
- **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.
|
|
112
|
+
- Each person gets a separate private database. `snap_disconnect` deletes everything stored about you; also revoke the app in Snapchat Business Manager.
|
|
113
|
+
- Interactive cards (below) are shown in Claude with this version.
|
|
114
|
+
- **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.
|
|
115
|
+
|
|
116
|
+
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.
|
|
117
|
+
|
|
118
|
+
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.
|
|
119
|
+
|
|
83
120
|
## Safety rules (built in)
|
|
84
121
|
- 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
122
|
- 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 +157,9 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
120
157
|
| `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
158
|
| `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
159
|
| `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
|
-
| `
|
|
160
|
+
| `SNAP_REQUEST_BUDGET` | 44 | The most requests to Snapchat one run of `snap_delivery_check` makes. The hosted version sets it from its plan (see `remote/README.md`); on your own computer you can raise it. |
|
|
161
|
+
| `SNAP_COMPACT` | (off) | `1` shortens every tool and parameter description to its first sentence, so the tool list costs the AI fewer tokens (the hosted version uses it). The `lite` tool set turns it on by itself. |
|
|
162
|
+
| `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `lite` (24 tools with short descriptions, about a third of the context cost: look, find, check delivery, pause, change budgets and bids, undo, start a campaign), `core` (62 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
163
|
| `SNAP_HUMAN_APPROVAL` | off | `elicit` = ask the user through the MCP client before every write |
|
|
125
164
|
| `SNAP_APPROVAL_TTL_SECONDS` | 600 | Lifetime of an approval token |
|
|
126
165
|
| `SNAP_REPEAT_WINDOW_SECONDS` | 600 | An identical create, copy, claim or upload is refused within this time |
|
|
@@ -163,6 +202,10 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
163
202
|
| `snap_creative_compare` | read: the ads of a campaign or ad squad ranked against the median ROAS (WINNER / LAGGING), grouped by call to action |
|
|
164
203
|
| `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 |
|
|
165
204
|
| `snap_billing_check` | read: ad account status, funding sources (card expiry, daily limit vs budgets, credit left) and a verdict |
|
|
205
|
+
| `snap_account_admin` | read: the ad account's settings (status, currency, time zone, billing type, spend cap), the organization's billing centers, and how many people have access with which role (emails masked); never changes anything |
|
|
206
|
+
| `snap_list_profiles` | read: the public profiles (brand identities) this login can use for creatives, with their ids; with only one, new creatives use it automatically |
|
|
207
|
+
| `snap_account_details` | read: pick one list with `what`: invoices, transactions, lead forms, a lead count, mobile apps, event details, interaction zones, offer disclaimers, phone numbers (masked), sponsored content, organizations, organization pixels, media stats, catalog products; contact details masked, and if Snapchat does not answer it says which paths were tried |
|
|
208
|
+
| `snap_upload_media_from_url` | write: upload a JPEG, PNG, MP4 or MOV (up to 32 MB) from a public https link, for the hosted version; previews first, and only public https addresses are fetched |
|
|
166
209
|
| `snap_unused_media` | read: uploaded images and videos no creative uses (never deletes) |
|
|
167
210
|
| `snap_audience_health` | read: audiences that are not targetable, tiny, stale, or unused by active ad squads |
|
|
168
211
|
| `snap_funnel` | read: impressions → swipes → views → add to cart → checkout → purchases with the rate at each step and the weakest step |
|
|
@@ -176,6 +219,9 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
176
219
|
| `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
220
|
| `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
221
|
| `snap_review_issues` | read: rejected / pending ads with Snap's reasons |
|
|
222
|
+
| `snap_start_here` | read: the first-run guide: who is connected (masked), whether changes are allowed, the limits, the active ad account (or the list to choose from), a snapshot of campaigns and ad squads, a warning about active ad squads under paused campaigns, and what to say next |
|
|
223
|
+
| `snap_find` | read: find campaigns, ad squads or ads by (part of) their name and get their ids, with parent names and ad squad budgets; accents and Arabic letter variants are ignored |
|
|
224
|
+
| `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
225
|
| `snap_pixel_health` | read: pixel signal readiness and event-quality issues, top priority first |
|
|
180
226
|
| `snap_creative_fatigue` | read: which ads are tired (ROAS down 30%+ with higher frequency or lower swipe rate), which to replace first |
|
|
181
227
|
| `snap_report_async_start`, `snap_report_async_status`, `snap_report_async_download` | read: very large CSV reports saved to `exports/` |
|
|
@@ -210,7 +256,7 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
210
256
|
| `snap_influencer_ad` | the whole influencer flow in one step: claim, wait for media, creative, paused ad |
|
|
211
257
|
|
|
212
258
|
## Interactive cards (MCP Apps)
|
|
213
|
-
In AI apps that support [MCP Apps](https://modelcontextprotocol.io)
|
|
259
|
+
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); 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.
|
|
214
260
|
- **`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.
|
|
215
261
|
- **`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.
|
|
216
262
|
- **`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**.
|
|
@@ -219,7 +265,7 @@ In AI apps that support [MCP Apps](https://modelcontextprotocol.io) (for example
|
|
|
219
265
|
- **`snap_setup_check`**: what is connected and what is missing, the money limits, and whether you are asked before every change.
|
|
220
266
|
- **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).
|
|
221
267
|
|
|
222
|
-
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.
|
|
268
|
+
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.
|
|
223
269
|
|
|
224
270
|
## Examples, permissions and limits
|
|
225
271
|
**Things to ask your assistant** (each names the tool it will use):
|
|
@@ -284,7 +330,7 @@ This is a local MCP server (stdio). Credentials stay in your `.env`; the AI app
|
|
|
284
330
|
```
|
|
285
331
|
Use the absolute path to `node` as `command` if the app cannot find it. The server reads `.env` from its own folder (an npm install reads `~/.ads-mcp-for-snapchat/.env`), so no secrets go in this file.
|
|
286
332
|
|
|
287
|
-
**ChatGPT**: ChatGPT connects to *remote* MCP servers (an https URL) through its connectors / developer mode, not to local stdio programs.
|
|
333
|
+
**ChatGPT**: ChatGPT connects to *remote* MCP servers (an https URL) through its connectors / developer mode, not to local stdio programs. Use the [hosted version](#hosted-version) for that (untested in ChatGPT so far; if it fails, please open an issue with the exact error). Do not expose the local server publicly: it can change real ad campaigns. Other desktop MCP clients that launch local stdio servers (Cursor, VS Code, Cline) work with the same `command` and `args` as above.
|
|
288
334
|
|
|
289
335
|
## Several ad accounts
|
|
290
336
|
Run one server per ad account, each with its own settings file. Each server only touches its own account, and keeps its own change log (`<settings file>.log.jsonl`), so limits, undo and the audit trail never mix.
|
|
@@ -331,7 +377,7 @@ Verified on the maintainer's own ad account. Anything not listed here is covered
|
|
|
331
377
|
- The 24-hour spend limit and absolute limits on real writes (mocked tests only), `SNAP_HUMAN_APPROVAL=elicit` in Claude Code, `snap_create_creative` with a WEB_VIEW link, a campaign-level `snap_set_daily_budget`, a successful `snap_delete` of an ad squad, ad or audience, a customer-list upload of real data, and Node 18 / 20 outside CI.
|
|
332
378
|
|
|
333
379
|
## Not built
|
|
334
|
-
-
|
|
380
|
+
- An independent security review of the hosted version, and Snap's confirmation that one shared app may serve other advertisers (see "Hosted version"). The optional shared login service (`broker/`) only passes Snapchat logins along; the local tool always runs on your own computer.
|
|
335
381
|
- Lens, App Install, Deep Link and lead-form creatives; ad squad goals for app installs and lead generation; custom location and radius targeting; reach-and-frequency budgets; position-level reports; custom placement on ad squads that use content inclusion or exclusion lists; switching an ad squad to auto-bid (it would remove the bid cap).
|
|
336
382
|
- Anything that spends money without a separate, explicit enable step.
|
|
337
383
|
|
package/SECURITY.md
CHANGED
|
@@ -29,6 +29,9 @@ Text that comes back from outside (competitors' ads, page contents, ad review re
|
|
|
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
31
|
|
|
32
|
+
## Hosted version (unofficial, open to anyone with a Snapchat login)
|
|
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
|
+
|
|
32
35
|
## Known limits (from the independent audit of 0.9.6)
|
|
33
36
|
These are real and not fixed in code. Know them before you rely on the guards.
|
|
34
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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ads-mcp-for-snapchat",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.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/admin.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Account and billing admin, read-only: the ad account's settings, its billing centers and who has access with which role. It never
|
|
2
|
+
// changes anything. Names, emails and addresses are masked or left out: the answer lands in a chat history. Each part is read on
|
|
3
|
+
// its own, because a login may be allowed to see some of them and not others; a part that cannot be read says why.
|
|
4
|
+
import { maskLogin } from "./identity.js";
|
|
5
|
+
|
|
6
|
+
const one = (row, key) => (row && typeof row === "object" && row[key] && typeof row[key] === "object" ? row[key] : row);
|
|
7
|
+
const reason = (e) => String(e?.message ?? e).replace(/\s+/g, " ").slice(0, 160);
|
|
8
|
+
const money = (micro) => (micro == null ? null : Number(micro) / 1e6);
|
|
9
|
+
|
|
10
|
+
async function section(fn) {
|
|
11
|
+
try {
|
|
12
|
+
return { ok: true, value: await fn() };
|
|
13
|
+
} catch (e) {
|
|
14
|
+
return { ok: false, why: reason(e) };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function accountAdmin(client, { adAccountId, maxPeople = 40 }) {
|
|
19
|
+
const acct = (await client.request("GET", `/adaccounts/${adAccountId}`)).adaccounts?.[0]?.adaccount ?? {};
|
|
20
|
+
const org = acct.organization_id ?? null;
|
|
21
|
+
const out = {
|
|
22
|
+
ad_account: {
|
|
23
|
+
name: acct.name ?? null,
|
|
24
|
+
status: acct.status ?? null,
|
|
25
|
+
currency: acct.currency ?? null,
|
|
26
|
+
timezone: acct.timezone ?? null,
|
|
27
|
+
billing_type: acct.billing_type ?? null,
|
|
28
|
+
type: acct.type ?? null,
|
|
29
|
+
lifetime_spend_cap: money(acct.lifetime_spend_cap_micro),
|
|
30
|
+
funding_sources: (acct.funding_source_ids ?? []).length,
|
|
31
|
+
created_at: acct.created_at ?? null,
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
const unavailable = {};
|
|
35
|
+
|
|
36
|
+
if (org) {
|
|
37
|
+
const bc = await section(async () => (await client.listPaged(`/organizations/${org}/billingcenters`, "billingcenter")).items.map((b) => one(b, "billingcenter")));
|
|
38
|
+
if (bc.ok) out.billing_centers = bc.value.map((b) => ({ id: b.id, name: b.name ?? null, currency: b.currency ?? null, country: b.country ?? null }));
|
|
39
|
+
else unavailable.billing_centers = bc.why;
|
|
40
|
+
|
|
41
|
+
const members = await section(async () => (await client.listPaged(`/organizations/${org}/members`, "member")).items.map((m) => one(m, "member")));
|
|
42
|
+
const roles = await section(async () => (await client.listPaged(`/adaccounts/${adAccountId}/roles`, "role")).items.map((r) => one(r, "role")));
|
|
43
|
+
if (members.ok || roles.ok) {
|
|
44
|
+
const byId = new Map((members.ok ? members.value : []).map((m) => [m.id, m]));
|
|
45
|
+
const rows = [];
|
|
46
|
+
if (roles.ok) {
|
|
47
|
+
for (const r of roles.value) {
|
|
48
|
+
const m = byId.get(r.member_id) ?? {};
|
|
49
|
+
rows.push({ person: maskLogin(m) ?? "(a member, details not visible to this login)", role: r.type ?? r.role ?? null, status: m.member_status ?? null });
|
|
50
|
+
}
|
|
51
|
+
} else {
|
|
52
|
+
for (const m of byId.values()) rows.push({ person: maskLogin(m), role: null, status: m.member_status ?? null });
|
|
53
|
+
}
|
|
54
|
+
const count = {};
|
|
55
|
+
for (const r of rows) count[r.role ?? "unknown"] = (count[r.role ?? "unknown"] ?? 0) + 1;
|
|
56
|
+
out.access = { people: rows.length, by_role: count, list: rows.slice(0, maxPeople), ...(rows.length > maxPeople ? { note: `${rows.length} people; the first ${maxPeople} are shown.` } : {}), ...(roles.ok ? {} : { note: "Roles could not be read, so only the organization's members are listed." }) };
|
|
57
|
+
}
|
|
58
|
+
if (!members.ok && !roles.ok) unavailable.access = `${members.why}${roles.why !== members.why ? ` / ${roles.why}` : ""}`;
|
|
59
|
+
} else {
|
|
60
|
+
unavailable.organization = "This ad account did not say which organization it belongs to, so billing centers and access could not be looked up.";
|
|
61
|
+
}
|
|
62
|
+
if (Object.keys(unavailable).length) out.could_not_read = unavailable;
|
|
63
|
+
out.note = "Read-only. Emails and addresses are masked or left out. Funding sources, card expiry and credit: use snap_billing_check. Invoices and payments are managed in Ads Manager.";
|
|
64
|
+
return out;
|
|
65
|
+
}
|
package/src/apps/bridge.js
CHANGED
|
@@ -14,13 +14,38 @@
|
|
|
14
14
|
});
|
|
15
15
|
const notify = (method, params) => post({ method, params });
|
|
16
16
|
|
|
17
|
+
// The theme: what the person picked with the Light/Dark button, else what the chat app says, else the system setting.
|
|
18
|
+
// Cards keep no storage on purpose, so the choice lasts while this card is open.
|
|
19
|
+
let chosen = null;
|
|
20
|
+
const setTheme = (t) => document.documentElement.setAttribute("data-theme", t);
|
|
21
|
+
const currentTheme = () => document.documentElement.getAttribute("data-theme") || (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
|
|
22
|
+
|
|
23
|
+
function addThemeButton() {
|
|
24
|
+
if (document.getElementById("snap-theme")) return;
|
|
25
|
+
const btn = document.createElement("button");
|
|
26
|
+
btn.id = "snap-theme";
|
|
27
|
+
btn.type = "button";
|
|
28
|
+
const label = () => (currentTheme() === "dark" ? "Light mode" : "Dark mode");
|
|
29
|
+
btn.textContent = label();
|
|
30
|
+
btn.addEventListener("click", () => {
|
|
31
|
+
chosen = currentTheme() === "dark" ? "light" : "dark";
|
|
32
|
+
setTheme(chosen);
|
|
33
|
+
btn.textContent = label();
|
|
34
|
+
});
|
|
35
|
+
document.body.append(btn);
|
|
36
|
+
}
|
|
37
|
+
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", addThemeButton);
|
|
38
|
+
else addThemeButton();
|
|
39
|
+
|
|
17
40
|
function applyContext(ctx) {
|
|
18
41
|
if (!ctx) return;
|
|
19
42
|
Object.assign(state.ctx, ctx);
|
|
20
|
-
|
|
21
|
-
if (ctx.theme
|
|
22
|
-
|
|
23
|
-
|
|
43
|
+
// The chat app's own colors are not used (they can be light inside a dark chat); only its light/dark choice is.
|
|
44
|
+
if ((ctx.theme === "light" || ctx.theme === "dark") && !chosen) {
|
|
45
|
+
setTheme(ctx.theme);
|
|
46
|
+
const b = document.getElementById("snap-theme");
|
|
47
|
+
if (b) b.textContent = ctx.theme === "dark" ? "Light mode" : "Dark mode";
|
|
48
|
+
}
|
|
24
49
|
}
|
|
25
50
|
|
|
26
51
|
window.addEventListener("message", (event) => {
|
package/src/apps/preview.html
CHANGED
|
@@ -59,7 +59,7 @@ button:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline
|
|
|
59
59
|
// Single-item edits that snap_undo can revert right after they are applied.
|
|
60
60
|
const UNDOABLE = new Set(["snap_set_status", "snap_set_daily_budget", "snap_set_bid", "snap_set_targeting", "snap_set_schedule", "snap_rename", "snap_exclude_segments", "snap_set_frequency_cap", "snap_set_ad_schedule", "snap_set_bid_strategy", "snap_set_placement"]);
|
|
61
61
|
const HIDE = new Set(["approval_token", "approval_expires_in_seconds", "applied", "dry_run", "ad_account", "read_only", "budget_warning", "duplicate_warning", "spend_impact", "impact_line", "note", "activation", "audit_event_id"]);
|
|
62
|
-
const state = { input: null, tool: null, result: null, phase: "preview", secs: null, message: null, details: false, undo: null };
|
|
62
|
+
const state = { input: null, tool: null, result: null, phase: "preview", secs: null, message: null, details: false, undo: null, typed: "" };
|
|
63
63
|
let timer = null;
|
|
64
64
|
const show = (v) => (v !== null && typeof v === "object" ? JSON.stringify(v, null, 1) : String(v));
|
|
65
65
|
const mmss = (n) => Math.floor(n / 60) + ":" + String(n % 60).padStart(2, "0");
|
|
@@ -98,18 +98,45 @@ button:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline
|
|
|
98
98
|
return out;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
// A delete cannot be undone, so its card says what goes, shows the facts up front, and asks the person to type the item's name.
|
|
102
|
+
const ENTITY_LABEL = { campaign: "campaign", adsquad: "ad squad", ad: "ad", segment: "audience" };
|
|
103
|
+
const isDelete = () => state.tool === "snap_delete" && state.result && state.result.preview && typeof state.result.preview === "object";
|
|
104
|
+
const blockersOf = () => (isDelete() && Array.isArray(state.result.preview.blocked_because) ? state.result.preview.blocked_because : []);
|
|
105
|
+
const nameMatches = () => isDelete() && state.typed === state.result.preview.name;
|
|
106
|
+
function deleteBlock(p) {
|
|
107
|
+
const label = ENTITY_LABEL[p.entity] || p.entity || "item";
|
|
108
|
+
const also = p.will_also_remove && typeof p.will_also_remove === "object" ? Object.entries(p.will_also_remove).filter(([, n]) => n).map(([k, n]) => n + " " + (n === 1 ? k.replace(/s$/, "") : k)).join(", ") : "";
|
|
109
|
+
const box = el("div", { class: "impact" });
|
|
110
|
+
box.append(el("div", { class: "name", dir: "auto" }, "Delete " + label + " \u201c" + (p.name || p.id) + "\u201d"));
|
|
111
|
+
box.append(el("div", { class: "sub" }, "Status " + (p.status || "unknown") + " \u00b7 spent " + num(p.spend_last_30_days) + " in the last 30 days" + (also ? " \u00b7 also removes " + also : " \u00b7 nothing else is removed")));
|
|
112
|
+
for (const b of blockersOf()) box.append(el("div", { class: "err" }, "Blocked: " + (typeof b === "string" ? b : JSON.stringify(b))));
|
|
113
|
+
if (!blockersOf().length) {
|
|
114
|
+
const input = el("input", { type: "text", id: "confirmName", dir: "auto", autocomplete: "off", spellcheck: "false", "aria-label": "Type the exact name to confirm", placeholder: p.name || "", style: "width:100%;margin-top:8px;min-height:44px;padding:0 12px;border-radius:10px;border:1px solid var(--border);background:var(--bg);color:var(--text);font:inherit" });
|
|
115
|
+
input.value = state.typed;
|
|
116
|
+
input.addEventListener("input", () => { state.typed = input.value; const b = document.getElementById("apply"); if (b) b.disabled = !canApply(); });
|
|
117
|
+
box.append(el("div", { class: "sub", style: "margin-top:8px" }, "Type the exact name to confirm. This cannot be undone."), input);
|
|
118
|
+
}
|
|
119
|
+
return box;
|
|
120
|
+
}
|
|
121
|
+
function canApply() {
|
|
122
|
+
const r = state.result;
|
|
123
|
+
const base = !!r.approval_token && !r.read_only && !!state.input && !!state.tool && state.secs !== 0 && state.phase !== "applying";
|
|
124
|
+
return isDelete() ? base && !blockersOf().length && nameMatches() : base;
|
|
125
|
+
}
|
|
126
|
+
|
|
101
127
|
function render() {
|
|
102
128
|
app.textContent = "";
|
|
103
129
|
const r = state.result;
|
|
104
130
|
if (!r) return;
|
|
105
|
-
const name = (state.tool || "change").replace(/^snap_/, "").replace(/_/g, " ");
|
|
131
|
+
const name = isDelete() ? "Delete " + (ENTITY_LABEL[state.result.preview.entity] || "item") : (state.tool || "change").replace(/^snap_/, "").replace(/_/g, " ");
|
|
106
132
|
const done = r.applied === true || state.phase === "applied";
|
|
107
133
|
const card = el("div", { class: "card" });
|
|
108
|
-
const badge = state.phase === "cancelled" ? el("span", { class: "badge off" }, "Cancelled") : done ? el("span", { class: "badge done" }, "Applied") : el("span", { class: "badge" }, "Preview: nothing has changed yet");
|
|
134
|
+
const badge = state.phase === "cancelled" ? el("span", { class: "badge off" }, "Cancelled") : done ? el("span", { class: "badge done" }, "Applied") : el("span", { class: "badge" + (isDelete() ? " perm" : "") }, isDelete() ? "Permanent: cannot be undone. Nothing deleted yet" : "Preview: nothing has changed yet");
|
|
109
135
|
card.append(el("div", { style: "display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap;align-items:center" }, el("h1", null, name), badge));
|
|
110
136
|
if (r.ad_account) card.append(el("div", { class: "sub" }, "Ad account " + r.ad_account));
|
|
111
137
|
if (!done) card.append(...moneyBlock(r));
|
|
112
|
-
|
|
138
|
+
if (!done && isDelete()) card.append(deleteBlock(r.preview));
|
|
139
|
+
const rows = Object.entries(r).filter(([k, v]) => !HIDE.has(k) && !(isDelete() && k === "preview") && v !== undefined && v !== null && !(Array.isArray(v) && !v.length));
|
|
113
140
|
// A list of {name, change} (what happens to each item) reads best as lines; other objects go under "Show details".
|
|
114
141
|
const lines = (v) => Array.isArray(v) && v.every((x) => x && typeof x === "object" && typeof x.change === "string");
|
|
115
142
|
const simple = rows.filter(([, v]) => typeof v !== "object" || lines(v));
|
|
@@ -123,11 +150,11 @@ button:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline
|
|
|
123
150
|
}
|
|
124
151
|
if (state.message) card.append(el("div", { class: state.message.err ? "err" : "ok" }, state.message.text));
|
|
125
152
|
if (!done && state.phase !== "cancelled") {
|
|
126
|
-
const can =
|
|
127
|
-
const apply = el("button", { id: "apply", class: "primary", type: "button", disabled: !
|
|
153
|
+
const can = canApply();
|
|
154
|
+
const apply = el("button", { id: "apply", class: "primary" + (isDelete() ? " danger" : ""), type: "button", disabled: !canApply(), onclick: () => applyIt() }, state.phase === "applying" ? (isDelete() ? "Deleting…" : "Applying…") : isDelete() ? "Delete permanently" : "Apply");
|
|
128
155
|
const cancel = el("button", { type: "button", disabled: state.phase === "applying", onclick: () => { state.phase = "cancelled"; state.message = { text: "Nothing was sent." }; render(); } }, "Cancel");
|
|
129
156
|
card.append(el("div", { class: "btns" }, apply, cancel, el("span", { id: "timer", class: "sub" }, state.secs ? "Approval expires in " + mmss(state.secs) : "")));
|
|
130
|
-
if (!can && state.phase === "preview") card.append(el("div", { class: "sub" }, r.read_only ? "Read-only is on in the settings, so this cannot be applied." : !r.approval_token ? "This preview cannot be applied (see above)." : "To apply this, ask in the chat."));
|
|
157
|
+
if (!can && state.phase === "preview" && !isDelete()) card.append(el("div", { class: "sub" }, r.read_only ? "Read-only is on in the settings, so this cannot be applied." : !r.approval_token ? "This preview cannot be applied (see above)." : "To apply this, ask in the chat."));
|
|
131
158
|
}
|
|
132
159
|
if (done && UNDOABLE.has(state.tool)) card.append(undoBlock());
|
|
133
160
|
app.append(card);
|
|
@@ -174,8 +201,10 @@ button:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline
|
|
|
174
201
|
async function applyIt() {
|
|
175
202
|
state.phase = "applying"; render();
|
|
176
203
|
try {
|
|
177
|
-
const r = await window.snapApp.run(state.tool, Object.assign({}, state.input, { confirm: true, approval_token: state.result.approval_token }));
|
|
204
|
+
const r = await window.snapApp.run(state.tool, Object.assign({}, state.input, { confirm: true, approval_token: state.result.approval_token }, isDelete() ? { confirm_name: state.typed } : {}));
|
|
178
205
|
if (r.ok) { state.phase = "applied"; state.message = { text: "Applied" + (r.data && r.data.verified === false ? ", but Snap did not show the new value yet. Check it." : " and checked back with Snap.") }; if (r.data) state.result = Object.assign({}, state.result, r.data, { applied: true }); }
|
|
206
|
+
// The same approval was already used (the chat applied it, or it was clicked twice). Nothing was repeated; do not offer Apply again.
|
|
207
|
+
else if (/already used/i.test(r.text || "")) { state.phase = "applied"; state.message = { text: "Already applied: this approval was used before (from the chat or an earlier click). Nothing was repeated. Ask in the chat to check the result." }; }
|
|
179
208
|
else { state.phase = "preview"; state.message = { err: true, text: r.text }; }
|
|
180
209
|
} catch (e) { state.phase = "preview"; state.message = { err: true, text: "Could not apply: " + e.message }; }
|
|
181
210
|
render();
|