ads-mcp-for-snapchat 0.9.9 → 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: 80 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,5 +1,25 @@
1
1
  # Changelog
2
2
 
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
+
3
23
  ## 0.9.9 (2026-11-21)
4
24
 
5
25
  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** 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 (48 everyday tools); type `all` in its Tool set field to see all 80.
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` (48 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 |
@@ -176,6 +190,7 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
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/` |
@@ -210,7 +225,7 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
210
225
  | `snap_influencer_ad` | the whole influencer flow in one step: claim, wait for media, creative, paused ad |
211
226
 
212
227
  ## Interactive cards (MCP Apps)
213
- 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.
214
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.
215
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.
216
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**.
@@ -219,7 +234,7 @@ In AI apps that support [MCP Apps](https://modelcontextprotocol.io) (for example
219
234
  - **`snap_setup_check`**: what is connected and what is missing, the money limits, and whether you are asked before every change.
220
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).
221
236
 
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.
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.
223
238
 
224
239
  ## Examples, permissions and limits
225
240
  **Things to ask your assistant** (each names the tool it will use):
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 (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
+
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.9.9",
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",
@@ -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
- const root = document.documentElement;
21
- if (ctx.theme) root.setAttribute("data-theme", ctx.theme);
22
- const vars = ctx.styles && ctx.styles.variables;
23
- if (vars) for (const k in vars) if (vars[k]) root.style.setProperty(k, vars[k]);
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) => {
@@ -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
- const rows = Object.entries(r).filter(([k, v]) => !HIDE.has(k) && v !== undefined && v !== null && !(Array.isArray(v) && !v.length));
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 = !!r.approval_token && !r.read_only && !!state.input && !!state.tool && state.secs !== 0;
127
- const apply = el("button", { id: "apply", class: "primary", type: "button", disabled: !can || state.phase === "applying", onclick: () => applyIt() }, state.phase === "applying" ? "Applying…" : "Apply");
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,7 +201,7 @@ 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 }); }
179
206
  else { state.phase = "preview"; state.message = { err: true, text: r.text }; }
180
207
  } catch (e) { state.phase = "preview"; state.message = { err: true, text: "Could not apply: " + e.message }; }
@@ -0,0 +1,58 @@
1
+ /* Shared look of every card. Our own palette on purpose: the chat app's colors are not always the ones the chat is shown in
2
+ (a light card on a dark chat). The card follows the theme the app reports; the Light/Dark button on the card overrides it. */
3
+ :root{color-scheme:light;--bg:#ffffff;--bg2:#f5f6f9;--text:#161a22;--muted:#5d6878;--border:#e1e5ec;--good:#157f56;--bad:#c42f3a;--warn:#9a5a00;--accent:#3d5afe;--warnbg:#fff6e4;--warnline:#efd5a0;--shadow:0 1px 2px rgba(16,24,40,.06),0 2px 6px rgba(16,24,40,.06)}
4
+ @media (prefers-color-scheme:dark){:root{color-scheme:dark;--bg:#14161b;--bg2:#1c1f26;--text:#eceff5;--muted:#98a2b3;--border:#2b303a;--good:#4fd69c;--bad:#ff7d87;--warn:#f6bd5c;--accent:#8ba3ff;--warnbg:#2e2616;--warnline:#5e4a22;--shadow:0 1px 2px rgba(0,0,0,.4),0 2px 8px rgba(0,0,0,.3)}}
5
+ :root[data-theme=light]{color-scheme:light;--bg:#ffffff;--bg2:#f5f6f9;--text:#161a22;--muted:#5d6878;--border:#e1e5ec;--good:#157f56;--bad:#c42f3a;--warn:#9a5a00;--accent:#3d5afe;--warnbg:#fff6e4;--warnline:#efd5a0;--shadow:0 1px 2px rgba(16,24,40,.06),0 2px 6px rgba(16,24,40,.06)}
6
+ :root[data-theme=dark]{color-scheme:dark;--bg:#14161b;--bg2:#1c1f26;--text:#eceff5;--muted:#98a2b3;--border:#2b303a;--good:#4fd69c;--bad:#ff7d87;--warn:#f6bd5c;--accent:#8ba3ff;--warnbg:#2e2616;--warnline:#5e4a22;--shadow:0 1px 2px rgba(0,0,0,.4),0 2px 8px rgba(0,0,0,.3)}
7
+
8
+ body{background:var(--bg);color:var(--text);padding:18px;line-height:1.5;-webkit-font-smoothing:antialiased}
9
+ h1{font-size:20px;font-weight:700;letter-spacing:-.015em}
10
+ h2{font-size:12px;font-weight:650;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
11
+ .sub{color:var(--muted)}
12
+ .card,.tile,.row{background:var(--bg2);border:1px solid var(--border);border-radius:14px;box-shadow:var(--shadow)}
13
+ .tile{padding:14px}
14
+ .tile .label{font-size:11px;font-weight:600;letter-spacing:.03em;text-transform:uppercase;color:var(--muted)}
15
+ .tile .value{font-size:26px;font-weight:700;letter-spacing:-.02em;margin-top:4px;font-variant-numeric:tabular-nums}
16
+ .row{padding:14px;transition:border-color .12s}
17
+ .row:hover{border-color:var(--accent)}
18
+ .name{font-weight:650}
19
+
20
+ button{border-radius:12px;border:1px solid var(--border);background:var(--bg);color:var(--text);font-weight:550;transition:background .12s,border-color .12s,transform .05s}
21
+ button:hover:not(:disabled){border-color:var(--accent)}
22
+ button:active:not(:disabled){transform:translateY(1px)}
23
+ button:disabled{opacity:.55;cursor:default}
24
+ button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
25
+ button.primary{background:var(--accent);border-color:var(--accent);color:#fff}
26
+ :root[data-theme=dark] button.primary{color:#0b0d12}
27
+ @media (prefers-color-scheme:dark){:root:not([data-theme=light]) button.primary{color:#0b0d12}}
28
+ button.primary:hover:not(:disabled){filter:brightness(1.08)}
29
+ .seg{border-radius:12px;border:1px solid var(--border);background:var(--bg2);overflow:hidden}
30
+ .seg button{border:0;border-radius:0;background:transparent;font-weight:550;box-shadow:none}
31
+ .seg button+button{border-left:1px solid var(--border)}
32
+ .seg button[aria-pressed=true]{background:var(--accent);color:#fff}
33
+ :root[data-theme=dark] .seg button[aria-pressed=true]{color:#0b0d12}
34
+ @media (prefers-color-scheme:dark){:root:not([data-theme=light]) .seg button[aria-pressed=true]{color:#0b0d12}}
35
+
36
+ .badge,.pill{font-weight:650;letter-spacing:.02em;border-width:1px}
37
+ .badge{background:color-mix(in srgb,var(--warn) 14%,transparent)}
38
+ .badge.done{background:color-mix(in srgb,var(--good) 14%,transparent)}
39
+ .badge.off{background:transparent}
40
+ .badge.perm{border-color:var(--bad);color:var(--bad);background:color-mix(in srgb,var(--bad) 14%,transparent)}
41
+ button.danger{background:var(--bad);border-color:var(--bad);color:#fff}
42
+ :root[data-theme=dark] button.danger{color:#14161b}
43
+ @media (prefers-color-scheme:dark){:root:not([data-theme=light]) button.danger{color:#14161b}}
44
+ .pill.on{background:color-mix(in srgb,var(--good) 14%,transparent)}
45
+ .pill.flag{background:color-mix(in srgb,var(--warn) 14%,transparent)}
46
+ .impact{background:var(--warnbg);border-color:var(--warnline);border-radius:12px}
47
+ .impact.calm{background:var(--bg);border-color:var(--border)}
48
+ .alert{border-radius:12px;background:color-mix(in srgb,var(--warn) 10%,transparent)}
49
+ .alert.critical{background:color-mix(in srgb,var(--bad) 10%,transparent)}
50
+ .track{background:color-mix(in srgb,var(--muted) 22%,transparent);border-radius:999px}
51
+ .fill{border-radius:999px}
52
+ .err{color:var(--bad)}.ok{color:var(--good)}
53
+ pre{background:var(--bg);border-color:var(--border);border-radius:10px}
54
+ .stepper{border-radius:12px}
55
+
56
+ #snap-theme{display:block;margin:16px 0 0 auto;min-height:32px;min-width:0;padding:0 14px;border-radius:999px;font-size:12px;font-weight:550;color:var(--muted);background:var(--bg2);box-shadow:var(--shadow)}
57
+ #snap-theme:hover:not(:disabled){color:var(--text)}
58
+ @media (prefers-reduced-motion:reduce){button{transition:none}}
package/src/apps.js CHANGED
@@ -5,20 +5,47 @@
5
5
  import { readFileSync } from "node:fs";
6
6
 
7
7
  export const UI_MIME = "text/html;profile=mcp-app";
8
+ // Chat apps keep a card page by its address, so a card that was redesigned but kept its address can go on showing the old page. Raise
9
+ // CARD_REVISION whenever a card page, the shared theme or the bridge changes, and every card gets a new address.
10
+ export const CARD_REVISION = 3;
11
+ const uri = (name) => `ui://snap-ads/${name}-r${CARD_REVISION}`;
8
12
  export const APP_URIS = {
9
- dashboard: "ui://snap-ads/dashboard",
10
- board: "ui://snap-ads/board",
11
- preview: "ui://snap-ads/preview",
12
- history: "ui://snap-ads/history",
13
- setup: "ui://snap-ads/setup",
14
- advice: "ui://snap-ads/advice",
13
+ dashboard: uri("dashboard"),
14
+ board: uri("board"),
15
+ preview: uri("preview"),
16
+ history: uri("history"),
17
+ setup: uri("setup"),
18
+ advice: uri("advice"),
15
19
  };
16
20
  // Which tool shows which card. Every tool that previews a change (it has `confirm`) shows the preview card.
17
21
  export const APP_TOOLS = { snap_dashboard: APP_URIS.dashboard, snap_campaign_board: APP_URIS.board, snap_change_history: APP_URIS.history, snap_setup_check: APP_URIS.setup, snap_budget_advice: APP_URIS.advice };
18
22
 
19
- const read = (name) => readFileSync(new URL(`./apps/${name}`, import.meta.url), "utf8");
20
- const BRIDGE = read("bridge.js");
21
- export const pageFor = (file) => read(file).replace("<!--BRIDGE-->", () => `<script>\n${BRIDGE}\n</script>`);
23
+ // The card pages come from the apps/ folder. A hosted build has no folder: it hands the same pages over as text with useAssets().
24
+ let assets = null;
25
+ export function useAssets(map) {
26
+ assets = map;
27
+ bridge = null;
28
+ theme = null;
29
+ }
30
+ const read = (name) => {
31
+ if (assets) {
32
+ if (typeof assets[name] !== "string") throw new Error(`Card page missing: ${name}`);
33
+ return assets[name];
34
+ }
35
+ return readFileSync(new URL(`./apps/${name}`, import.meta.url), "utf8");
36
+ };
37
+ let bridge = null;
38
+ // Claude shows a card from a stable sandbox address that depends on the server's own web address (hosted servers only). A hosted build
39
+ // computes it once and hands it over here; the local build never sets it.
40
+ let appDomain = null;
41
+ export const useAppDomain = (domain) => { appDomain = domain || null; };
42
+ let theme = null;
43
+ export const pageFor = (file) => {
44
+ bridge ??= read("bridge.js");
45
+ theme ??= read("theme.css");
46
+ // The shared look goes last in the page so it wins over each card's own defaults.
47
+ return read(file).replace("</head>", () => `<style>\n${theme}\n</style>\n</head>`).replace("<!--BRIDGE-->", () => `<script>\n${bridge}\n</script>`);
48
+ };
22
49
 
23
50
  export function uiMeta(uri) {
24
51
  // `ui/resourceUri` is the older spelling, kept so older hosts still find the card.
@@ -35,6 +62,6 @@ export function registerApps(server) {
35
62
  ["snap-ads-advice", APP_URIS.advice, "advice.html", "Budget suggestions to tick and apply together; each still previews and uses its approval token."],
36
63
  ];
37
64
  for (const [name, uri, file, description] of pages) {
38
- server.registerResource(name, uri, { description, mimeType: UI_MIME }, async () => ({ contents: [{ uri, mimeType: UI_MIME, text: pageFor(file), _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } } }] }));
65
+ server.registerResource(name, uri, { description, mimeType: UI_MIME }, async () => ({ contents: [{ uri, mimeType: UI_MIME, text: pageFor(file), _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] }, ...(appDomain ? { domain: appDomain } : {}) } } }] }));
39
66
  }
40
67
  }
package/src/audit-log.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Structured audit trail for every mutating tool call, written to the same JSON-lines file as the change log.
2
2
  // An "intent" record is written BEFORE anything is sent; if that write fails, the operation does not run.
3
- import { appendFileSync, readFileSync, statSync } from "node:fs";
3
+ import { storage } from "./storage.js";
4
4
  import { randomUUID } from "node:crypto";
5
5
 
6
6
  const SECRET_KEY = /secret|token|password|authorization|cookie|credential|e-?mail|phone/i;
@@ -41,7 +41,7 @@ const keyOf = (e) => `${e.at}|${e.event_id ?? e.id ?? ""}|${e.phase ?? ""}|${e.c
41
41
 
42
42
  function append(file, record) {
43
43
  remember(file, record);
44
- appendFileSync(file, JSON.stringify(record) + "\n", { mode: 0o600 });
44
+ storage().append(file, JSON.stringify(record) + "\n");
45
45
  }
46
46
 
47
47
  // Throws when the record cannot be written: the caller must then NOT perform the operation.
@@ -70,11 +70,11 @@ export function auditResult(file, { event_id, tool, account, targets = [], ok, r
70
70
  export function readLogStrict(file) {
71
71
  let text;
72
72
  try {
73
- text = readFileSync(file, "utf8");
73
+ text = storage().read(file);
74
74
  } catch (e) {
75
- if (e.code === "ENOENT") return [];
76
75
  throw new Error(`Change log cannot be read (${e.code ?? e.message}); refusing changes that depend on it.`);
77
76
  }
77
+ if (text === null) return [];
78
78
  return text.split("\n").filter((l) => l.trim()).map((l, i) => {
79
79
  try {
80
80
  return JSON.parse(l);
@@ -91,14 +91,14 @@ const PARSED = new Map();
91
91
  function readLogCached(file) {
92
92
  let st;
93
93
  try {
94
- st = statSync(file);
94
+ st = storage().stamp(file);
95
95
  } catch (e) {
96
- if (e.code === "ENOENT") {
97
- PARSED.delete(file);
98
- return [];
99
- }
100
96
  throw new Error(`Change log cannot be read (${e.code ?? e.message}); refusing changes that depend on it.`);
101
97
  }
98
+ if (!st) {
99
+ PARSED.delete(file);
100
+ return [];
101
+ }
102
102
  const hit = PARSED.get(file);
103
103
  if (hit && hit.size === st.size && hit.mtimeMs === st.mtimeMs) return hit.entries;
104
104
  const entries = readLogStrict(file);
package/src/audit.js CHANGED
@@ -11,6 +11,7 @@ async function pages(client, path, entity, { limit = 200, maxPages = 12 } = {})
11
11
  if (!next) break;
12
12
  cursor = new URL(next).searchParams.get("cursor");
13
13
  if (!cursor) break;
14
+ if (i === maxPages - 1) out.incomplete = true; // more pages exist than this read was allowed to take
14
15
  }
15
16
  return out;
16
17
  }
@@ -148,3 +149,125 @@ export async function compareReport(client, { entity, id, breakdown, current, pr
148
149
  rows.sort((x, y) => y.spend.now - x.spend.now);
149
150
  return { current, previous, rows };
150
151
  }
152
+
153
+ // ---------- Why is it not delivering? ----------
154
+ // For each ACTIVE ad squad (or one chosen squad): did it show anything in the last days, and if not, what stops it? Read-only.
155
+ // A finding is `blocking` when it alone explains zero delivery. Snap's own words (delivery_status, targeting_reach_status) are passed
156
+ // through untouched under `snap_says`, because Snap's list of reasons is theirs to define.
157
+ const BLOCKING = new Set(["ACCOUNT_NOT_ACTIVE", "PARENT_NOT_ACTIVE", "PARENT_NOT_STARTED", "PARENT_ENDED", "NOT_STARTED", "ENDED", "NO_ADS", "NO_ACTIVE_ADS", "ADS_NOT_APPROVED", "NO_BUDGET", "NO_PIXEL"]);
158
+
159
+ export function judgeDelivery({ squad, campaign, ads, now, impressions, spend }) {
160
+ const f = [];
161
+ const add = (code, detail) => f.push({ code, blocking: BLOCKING.has(code), detail });
162
+ const t = (v) => (v ? Date.parse(v) : null);
163
+ const at = now.getTime();
164
+ if (!campaign) add("PARENT_NOT_ACTIVE", "the campaign could not be read");
165
+ else {
166
+ if (campaign.status !== "ACTIVE") add("PARENT_NOT_ACTIVE", `the campaign "${campaign.name}" is ${campaign.status}; its ad squads cannot deliver`);
167
+ if (t(campaign.start_time) && t(campaign.start_time) > at) add("PARENT_NOT_STARTED", `the campaign starts ${campaign.start_time}`);
168
+ if (t(campaign.end_time) && t(campaign.end_time) < at) add("PARENT_ENDED", `the campaign ended ${campaign.end_time}`);
169
+ }
170
+ if (t(squad.start_time) && t(squad.start_time) > at) add("NOT_STARTED", `this ad squad starts ${squad.start_time}`);
171
+ if (t(squad.end_time) && t(squad.end_time) < at) add("ENDED", `this ad squad ended ${squad.end_time}`);
172
+ if (!squad.daily_budget_micro && !squad.lifetime_budget_micro) add("NO_BUDGET", "no daily or lifetime budget is set");
173
+ if (/^PIXEL_/.test(squad.optimization_goal ?? "") && !squad.pixel_id) add("NO_PIXEL", `the goal is ${squad.optimization_goal} but no pixel is attached`);
174
+ if (!ads.length) add("NO_ADS", "this ad squad has no ads");
175
+ else {
176
+ const active = ads.filter((a) => a.status === "ACTIVE");
177
+ if (!active.length) add("NO_ACTIVE_ADS", `none of its ${ads.length} ad(s) is ACTIVE (they are ${[...new Set(ads.map((a) => a.status))].join(", ")})`);
178
+ else {
179
+ const approved = active.filter((a) => !a.review_status || a.review_status === "APPROVED");
180
+ if (!approved.length) {
181
+ const reasons = [...new Set(active.flatMap((a) => (a.review_status_reasons ?? []).map(String)))].slice(0, 4);
182
+ add("ADS_NOT_APPROVED", `${active.length} active ad(s), none approved (${[...new Set(active.map((a) => a.review_status))].join(", ")})${reasons.length ? `. Snap's reasons: ${reasons.join("; ")}` : ""}`);
183
+ } else if (approved.length < active.length) add("SOME_ADS_NOT_APPROVED", `${active.length - approved.length} of ${active.length} active ad(s) are not approved`);
184
+ }
185
+ }
186
+ const says = {};
187
+ if (squad.delivery_status !== undefined && squad.delivery_status !== null) says.delivery_status = squad.delivery_status;
188
+ if (squad.targeting_reach_status !== undefined && squad.targeting_reach_status !== null) says.targeting_reach_status = squad.targeting_reach_status;
189
+ const blocking = f.filter((x) => x.blocking);
190
+ // The verdict is about the state now. Something that blocks delivery wins even if it delivered a day ago; the numbers only decide
191
+ // between the other cases, and a squad whose numbers could not be read is not called "no delivery".
192
+ let verdict;
193
+ if (blocking.length) verdict = "BLOCKED";
194
+ else if (impressions === null || impressions === undefined) verdict = "UNKNOWN_DELIVERY";
195
+ else verdict = impressions > 0 ? "DELIVERING" : "NO_DELIVERY_NO_CLEAR_CAUSE";
196
+ const next = [];
197
+ if (verdict === "NO_DELIVERY_NO_CLEAR_CAUSE") {
198
+ next.push("Nothing structural stops it. Common causes are a bid or budget too low to win auctions, an audience that is too small, or a squad that started in the last day and is still ramping up.");
199
+ if (Object.keys(says).length) next.push("Compare with Snap's own status under snap_says.");
200
+ }
201
+ return { verdict, impressions, spend, findings: f, ...(Object.keys(says).length ? { snap_says: says } : {}), ...(next.length ? { next_checks: next } : {}) };
202
+ }
203
+
204
+ export async function deliveryCheck(client, { adAccountId, adsquadId, campaignId, days = 3, now = new Date(), maxSquads = 25, maxStatsCalls = 12 }) {
205
+ const end = new Date(Math.floor(now.getTime() / 3_600_000) * 3_600_000);
206
+ const start = new Date(end.getTime() - days * 86_400_000);
207
+ const iso = (d) => d.toISOString().replace(/\.\d+Z$/, "+00:00");
208
+ const account = (await client.request("GET", `/adaccounts/${adAccountId}`)).adaccounts?.[0]?.adaccount ?? {};
209
+ const campaigns = Object.fromEntries((await pages(client, `/adaccounts/${adAccountId}/campaigns`, "campaigns")).map((c) => [c.id, c]));
210
+ let squads = await pages(client, `/adaccounts/${adAccountId}/adsquads`, "adsquads");
211
+ if (adsquadId) squads = squads.filter((s) => s.id === adsquadId);
212
+ else squads = squads.filter((s) => s.status === "ACTIVE" && (!campaignId || s.campaign_id === campaignId));
213
+ if (adsquadId && !squads.length) throw new Error("That ad squad is not in this ad account.");
214
+ const truncated = squads.length > maxSquads;
215
+ squads = squads.slice(0, maxSquads);
216
+
217
+ // One list of the account's ads is cheapest, but a large account can have more ads than one list reads. When it was cut short, a squad
218
+ // that shows no ads is asked about directly, and if even that cannot be confirmed it is NOT called "no ads".
219
+ const adList = await pages(client, `/adaccounts/${adAccountId}/ads`, "ads", { maxPages: 40 });
220
+ const adsIncomplete = adList.incomplete === true;
221
+ const bySquad = new Map();
222
+ for (const a of adList) bySquad.set(a.ad_squad_id, [...(bySquad.get(a.ad_squad_id) ?? []), a]);
223
+ let directLeft = 10;
224
+ const adsOf = async (squad) => {
225
+ const known = bySquad.get(squad.id);
226
+ if (known?.length || !adsIncomplete) return { ads: known ?? [], verified: true };
227
+ if (directLeft-- <= 0) return { ads: [], verified: false };
228
+ try {
229
+ const data = await client.request("GET", `/adsquads/${squad.id}/ads`, { query: { limit: 200 } });
230
+ return { ads: (data.ads ?? []).map((r) => r.ad ?? r), verified: true };
231
+ } catch {
232
+ return { ads: [], verified: false };
233
+ }
234
+ };
235
+
236
+ const accountIssues = account.status && account.status !== "ACTIVE" ? [{ code: "ACCOUNT_NOT_ACTIVE", blocking: true, detail: `the ad account is ${account.status}` }] : [];
237
+ const out = [];
238
+ let statsLeft = maxStatsCalls;
239
+ for (const squad of squads) {
240
+ const { ads, verified } = await adsOf(squad);
241
+ // First without numbers: if something already blocks it, its recent numbers are not needed (and cost a request each).
242
+ let j = judgeDelivery({ squad, campaign: campaigns[squad.campaign_id], ads: verified ? ads : [{ status: "ACTIVE", review_status: "APPROVED", unverified: true }], now, impressions: null, spend: null });
243
+ if (!verified) j.findings.push({ code: "ADS_NOT_VERIFIED", blocking: false, detail: "this account has more ads than could be listed, so whether this squad has ads could not be confirmed" });
244
+ if (accountIssues.length) {
245
+ j.findings.unshift(...accountIssues);
246
+ j.verdict = "BLOCKED";
247
+ }
248
+ if (j.verdict !== "BLOCKED") {
249
+ if (statsLeft-- > 0) {
250
+ try {
251
+ const data = await client.request("GET", `/adsquads/${squad.id}/stats`, { query: { granularity: "TOTAL", start_time: iso(start), end_time: iso(end), fields: "impressions,spend" } });
252
+ const st = data.total_stats?.[0]?.total_stat?.stats ?? {};
253
+ j = { ...j, ...judgeDelivery({ squad, campaign: campaigns[squad.campaign_id], ads: verified ? ads : [{ status: "ACTIVE", review_status: "APPROVED", unverified: true }], now, impressions: Number(st.impressions ?? 0), spend: Number(st.spend ?? 0) / 1e6 }), findings: j.findings };
254
+ } catch (e) {
255
+ j.stats_note = `could not read delivery numbers (${String(e.message).slice(0, 100)})`;
256
+ }
257
+ } else j.stats_note = "delivery numbers were not read for this squad (too many squads in one check); run it for this squad alone";
258
+ } else {
259
+ j.recent_delivery = "not read: it is blocked right now, so recent numbers are not needed";
260
+ }
261
+ out.push({ adsquad_id: squad.id, name: squad.name, campaign: campaigns[squad.campaign_id]?.name ?? squad.campaign_id, daily_budget: squad.daily_budget_micro ? squad.daily_budget_micro / 1e6 : null, ...j });
262
+ }
263
+ const count = (v) => out.filter((r) => r.verdict === v).length;
264
+ return {
265
+ window: { start_time: iso(start), end_time: iso(end), days },
266
+ ad_account_status: account.status ?? null,
267
+ checked: out.length,
268
+ summary: { delivering: count("DELIVERING"), blocked: count("BLOCKED"), no_clear_cause: count("NO_DELIVERY_NO_CLEAR_CAUSE"), unknown: count("UNKNOWN_DELIVERY") },
269
+ ...(adsIncomplete ? { ads_list_note: "This account has more ads than one list reads; squads that showed no ads were checked directly (up to 10)." } : {}),
270
+ ...(truncated ? { note: `Only the first ${maxSquads} active ad squads were checked. Pass adsquad_id or campaign_id to look at others.` } : {}),
271
+ adsquads: out,
272
+ };
273
+ }
package/src/brand.js ADDED
@@ -0,0 +1,16 @@
1
+ // How this server presents itself: name, description, website and icon. Chat apps may show these in their connector lists.
2
+ // The icon is assets/logo.svg (a test keeps the two in step) so the same picture works on every surface.
3
+ export const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-label="Ads MCP for Snapchat">
4
+ <rect width="512" height="512" rx="112" fill="#232f78"/>
5
+ <g fill="#fff"><rect x="106" y="280" width="60" height="100" rx="14"/><rect x="196" y="210" width="60" height="170" rx="14"/><rect x="286" y="140" width="60" height="240" rx="14"/></g>
6
+ <circle cx="351" cy="166" r="76" fill="#4cc68c"/>
7
+ <path d="M314 168l28 28 46-54" fill="none" stroke="#fff" stroke-width="22" stroke-linecap="round" stroke-linejoin="round"/>
8
+ </svg>`;
9
+ export const LOGO_DATA_URI = `data:image/svg+xml;base64,${typeof Buffer !== "undefined" ? Buffer.from(LOGO_SVG).toString("base64") : btoa(LOGO_SVG)}`;
10
+ export const WEBSITE = "https://github.com/Usame794/snapchat-ads-mcp";
11
+ export const BRAND = {
12
+ title: "Ads MCP for Snapchat",
13
+ description: "Run and review Snapchat ad campaigns with an AI assistant. Everything created starts paused; every change is previewed, checked against your spending limits, and needs approval.",
14
+ websiteUrl: WEBSITE,
15
+ icons: [{ src: LOGO_DATA_URI, mimeType: "image/svg+xml", sizes: ["any"] }],
16
+ };
package/src/changes.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Planning, guarding and logging of write operations.
2
- import { appendFileSync, readFileSync } from "node:fs";
2
+ import { storage } from "./storage.js";
3
3
  import { join } from "node:path";
4
4
  import { DATA_DIR } from "./env.js";
5
5
  import { checkBid, checkDailyBudget, loadPolicy } from "./policy.js";
@@ -193,18 +193,18 @@ export function planSchedule(current, { startTime, endTime }, now = new Date())
193
193
  export function logChange(entry, file = LOG_FILE) {
194
194
  const record = { at: new Date().toISOString(), ...entry };
195
195
  remember(file, record); // kept in memory too, so the 24-hour limits survive a lost or failed log write
196
- appendFileSync(file, JSON.stringify(record) + "\n", { mode: 0o600 });
196
+ storage().append(file, JSON.stringify(record) + "\n");
197
197
  }
198
198
 
199
199
  // For display: the last `limit` records. A missing log is empty; damaged lines are skipped AND reported, never hidden.
200
200
  export function readLog(limit = 20, file = LOG_FILE) {
201
201
  let text;
202
202
  try {
203
- text = readFileSync(file, "utf8");
203
+ text = storage().read(file);
204
204
  } catch (e) {
205
- if (e.code === "ENOENT") return [];
206
205
  throw new Error(`Change log cannot be read (${e.code ?? e.message})`);
207
206
  }
207
+ if (text === null) return [];
208
208
  const out = [];
209
209
  let damaged = 0;
210
210
  for (const line of text.split("\n").filter((l) => l.trim())) {
@@ -336,5 +336,8 @@ export function planUndo(entry, current, { force = false, env = process.env, his
336
336
  if (typeof patch.bid_micro === "number") {
337
337
  checkBid(policy, { before: current.bid_micro != null ? unmicro(current.bid_micro) : null, value: unmicro(patch.bid_micro), windowStart: windowStart(history, current, "bid_micro"), restoring: true, what: "Max bid (undo)" });
338
338
  }
339
- return { patch, summary: `undo: ${entry.change}` };
339
+ // Say plainly where the item ends up, so the preview is not mistaken for repeating the original change.
340
+ const value = (k, v) => (typeof v === "number" ? (k.endsWith("_micro") ? unmicro(v) : v) : typeof v === "string" && v.length < 40 ? v : null);
341
+ const back = keys.map((k) => (value(k, patch[k]) === null ? null : `${k.replace(/_micro$/, "").replace(/_/g, " ")} ${value(k, patch[k])}`)).filter(Boolean).join(", ");
342
+ return { patch, summary: `undo: ${entry.change}${back ? `, back to ${back}` : ""}` };
340
343
  }
package/src/env.js CHANGED
@@ -3,12 +3,14 @@ import { homedir } from "node:os";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { dirname, join, sep } from "node:path";
5
5
 
6
- export const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
6
+ // Where the package sits on disk. A hosted build has no disk (and no file URL), so it gets "/".
7
+ export const ROOT = import.meta.url ? join(dirname(fileURLToPath(import.meta.url)), "..") : "/";
7
8
 
8
9
  // Where settings, the change log and exports live. A git checkout keeps them in the project folder, as before. A copy installed
9
10
  // from npm (inside node_modules, including the npx cache) must not: that folder is replaced on every update, so it uses
10
11
  // ~/.ads-mcp-for-snapchat instead. SNAP_HOME overrides both.
11
- export function dataDir({ root = ROOT, env = process.env, home = homedir() } = {}) {
12
+ const homeDir = () => { try { return homedir(); } catch { return "/"; } };
13
+ export function dataDir({ root = ROOT, env = process.env, home = homeDir() } = {}) {
12
14
  if (env.SNAP_HOME) return env.SNAP_HOME;
13
15
  return root.split(sep).includes("node_modules") ? join(home, ".ads-mcp-for-snapchat") : root;
14
16
  }
@@ -0,0 +1,15 @@
1
+ // What the tools may say about the signed-in person. Snapchat's /me returns the email, username and several internal ids; none of
2
+ // that is needed to use the tools, and it would land in the person's chat history. The tools get a masked label (enough to tell
3
+ // two logins apart) and the member status, nothing else.
4
+ export function maskLogin(me) {
5
+ const raw = String((me && (me.email || me.display_name || me.snapchat_username)) || "").trim();
6
+ if (!raw) return null;
7
+ const at = raw.indexOf("@");
8
+ if (at > 0) return `${raw[0]}***@${raw.slice(at + 1)}`;
9
+ return `${raw.slice(0, 1)}***`;
10
+ }
11
+
12
+ export function publicMe(me) {
13
+ const m = (me && typeof me === "object") ? me : {};
14
+ return { signed_in: true, signed_in_as: maskLogin(m), member_status: m.member_status ?? null };
15
+ }
package/src/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { BRAND } from "./brand.js";
3
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
5
  import { loadEnv, setEnvValue } from "./env.js";
5
6
  import { loadPolicy } from "./policy.js";
@@ -23,8 +24,15 @@ try {
23
24
  }
24
25
  // Snapshot of the non-secret settings taken at startup. Later edits to .env do not change limits or the target account.
25
26
  const settings = { ...process.env };
26
- const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.9.9" });
27
+ const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.10.0", ...BRAND });
27
28
  // Only the OAuth credentials are re-read from .env when a token is needed, so replacing them does not require a restart.
28
29
  const client = new SnapClient({ beforeToken: () => loadEnv(undefined, { override: true }), onNewRefreshToken: (t) => setEnvValue("SNAP_REFRESH_TOKEN", t), timeoutMs: policy.httpTimeoutMs });
29
30
  registerTools(server, client, settings);
31
+ // One line in the app's log: which app connected and whether it says it can show cards. This is how we find out why a card does not appear.
32
+ server.server.oninitialized = () => {
33
+ const info = server.server.getClientVersion() ?? {};
34
+ const ext = server.server.getClientCapabilities()?.extensions ?? {};
35
+ const ui = ext["io.modelcontextprotocol/ui"];
36
+ console.error(`[ads-mcp-for-snapchat] client=${info.name ?? "?"} ${info.version ?? ""} cards=${ui ? `yes (${(ui.mimeTypes ?? []).join(",")})` : "no"} extensions=${Object.keys(ext).join(",") || "none"}`);
37
+ };
30
38
  await server.connect(new StdioServerTransport());
@@ -1,3 +1,4 @@
1
+ import { maskLogin } from "./identity.js";
1
2
  // Data for the interactive cards that are not reports: the change history (with what can be undone) and the connection and
2
3
  // safety check. Both only read. Their cards change things only through snap_undo, with its own preview and approval.
3
4
  import { accessSync, constants } from "node:fs";
@@ -68,7 +69,7 @@ export async function setupCheck(client, { cfg, policy, logFile }) {
68
69
  try {
69
70
  const r = await client.request("GET", "/me");
70
71
  me = r.me ?? r;
71
- add("login", "Snapchat login", "ok", `Connected${me.display_name ? ` as ${me.display_name}` : ""}.`);
72
+ add("login", "Snapchat login", "ok", `Connected${maskLogin(me) ? ` as ${maskLogin(me)}` : ""}.`);
72
73
  } catch (e) {
73
74
  add("login", "Snapchat login", "error", `Not connected (${String(e.message).slice(0, 140)}).`, "Ask: connect my Snapchat ad account (snap_connect).");
74
75
  }
package/src/storage.js ADDED
@@ -0,0 +1,36 @@
1
+ // Where the change log and the audit log live. On your computer they are files (this file). A hosted version plugs in a database
2
+ // with the same three calls, so the safety rules (24-hour limits, undo, audit) run unchanged on top of either one.
3
+ // append(name, line) adds one line at the end. Throws if it cannot be written.
4
+ // read(name) the whole text, or null when nothing was ever written. Throws on any other problem.
5
+ // stamp(name) { size, mtimeMs } of what is stored, or null when nothing is stored. Used to skip re-reading an unchanged log.
6
+ import { appendFileSync, readFileSync, statSync } from "node:fs";
7
+
8
+ export const fileStorage = {
9
+ append(name, line) {
10
+ appendFileSync(name, line, { mode: 0o600 });
11
+ },
12
+ read(name) {
13
+ try {
14
+ return readFileSync(name, "utf8");
15
+ } catch (e) {
16
+ if (e.code === "ENOENT") return null;
17
+ throw e;
18
+ }
19
+ },
20
+ stamp(name) {
21
+ try {
22
+ const st = statSync(name);
23
+ return { size: st.size, mtimeMs: st.mtimeMs };
24
+ } catch (e) {
25
+ if (e.code === "ENOENT") return null;
26
+ throw e;
27
+ }
28
+ },
29
+ };
30
+
31
+ let current = fileStorage;
32
+ export const storage = () => current;
33
+ export function useStorage(next) {
34
+ for (const k of ["append", "read", "stamp"]) if (typeof next?.[k] !== "function") throw new Error(`Storage needs a ${k}() function`);
35
+ current = next;
36
+ }
package/src/tools.js CHANGED
@@ -12,7 +12,7 @@ import { buildCustomerSegment, readIdentifiers, uploadCustomerList } from "./cus
12
12
  import { asyncReportStatus, downloadAsyncReport, startAsyncReport } from "./async-report.js";
13
13
  import { executeDelete, planDelete } from "./delete.js";
14
14
  import { breakdownReport, dailyReport, dimensionReport, DIMENSIONS, SWIPE_WINDOWS, VIEW_WINDOWS } from "./report.js";
15
- import { compareReport, healthCheck, pixelHealth, reviewIssues } from "./audit.js";
15
+ import { compareReport, deliveryCheck, healthCheck, pixelHealth, reviewIssues } from "./audit.js";
16
16
  import { fatigueReport } from "./fatigue.js";
17
17
  import { buildDynamicCreative, buildDynamicTemplate, buildProductSet, creativeProductSet, describeFilter, squadProductSet, TEMPLATE_LAYOUTS, TEMPLATE_TEXT_FIELDS } from "./catalog-ads.js";
18
18
  import { brokerUrlFrom, startBrokerLogin } from "./broker.js";
@@ -39,6 +39,7 @@ import { executeCloneAd, loadTargets, planCloneAd } from "./clone-ad.js";
39
39
  import { executeBulkStatus, loadBulkItems, planBulkStatus } from "./bulk.js";
40
40
  import { buildAd, buildCreative, claimAdCode, getMedia, runInfluencerFlow, validateAdCode } from "./influencer.js";
41
41
  import { describePolicy, loadPolicy } from "./policy.js";
42
+ import { publicMe } from "./identity.js";
42
43
  import { ApprovalStore, digest, fingerprintOf, stabilizeState } from "./approval.js";
43
44
  import { addedDailyBudgetInWindow, auditIntent, auditResult, redact, windowStartMicro } from "./audit-log.js";
44
45
  import { Ownership } from "./ownership.js";
@@ -105,7 +106,7 @@ const brief = (o) => ({
105
106
  const id = () => z.string().regex(/^[A-Za-z0-9_-]{1,64}$/, "must be an id (letters, digits, '-' or '_')");
106
107
  const TWO_STEP = " Two steps: confirm=false returns a preview and an approval_token; to apply, repeat the same arguments with confirm=true and that approval_token.";
107
108
 
108
- export function registerTools(server, client, env = process.env) {
109
+ export function registerTools(server, client, env = process.env, { approvals: injectedApprovals } = {}) {
109
110
  // Safety settings are parsed once, here. Invalid settings throw, so the server does not start with a limit switched off.
110
111
  const policy = loadPolicy(env);
111
112
  // SNAP_TOOLSETS hides whole groups of tools (see toolsets.js). Prompts and settings are not affected.
@@ -244,7 +245,8 @@ export function registerTools(server, client, env = process.env) {
244
245
  // One change log per settings file: with SNAP_ENV_FILE (one file per ad account) the log sits next to it, so 24-hour limits,
245
246
  // undo and the audit trail of two accounts never mix. SNAP_LOG_FILE overrides; without either, changes.log.jsonl.
246
247
  const logFile = env.SNAP_LOG_FILE || (env.SNAP_ENV_FILE ? `${env.SNAP_ENV_FILE}.log.jsonl` : LOG_FILE);
247
- const approvals = new ApprovalStore({ ttlMs: policy.approvalTtlSeconds * 1000, repeatWindowMs: policy.repeatWindowSeconds * 1000 });
248
+ // A hosted build builds the server again for every request, so it hands in a store that keeps its codes between requests.
249
+ const approvals = injectedApprovals ?? new ApprovalStore({ ttlMs: policy.approvalTtlSeconds * 1000, repeatWindowMs: policy.repeatWindowSeconds * 1000 });
248
250
  const ownership = new Ownership(client);
249
251
  // Pixel and audience ids given as arguments must belong to the configured ad account. (A pixel set in the settings file is the
250
252
  // owner's own choice and is not re-checked.) Snap may refuse a foreign id itself, but this server does not rely on that.
@@ -472,7 +474,7 @@ export function registerTools(server, client, env = process.env) {
472
474
 
473
475
  read("snap_ping", { description: "Check the Snap credentials work, show who is authorized, and show the safety limits this server is running with." }, async () => {
474
476
  const me = await client.request("GET", "/me");
475
- return { ok: true, me: me.me ?? me, ad_account: cfg.account ?? null, safety_limits: describePolicy(policy) };
477
+ return { ok: true, me: publicMe(me.me ?? me), ad_account: cfg.account ?? null, safety_limits: describePolicy(policy) };
476
478
  });
477
479
 
478
480
  // Connecting from inside the chat (Claude Desktop extension, no terminal). The Client ID and secret come from the app's
@@ -1072,6 +1074,15 @@ export function registerTools(server, client, env = process.env) {
1072
1074
  ({ only_active }) => reviewIssues(client, { adAccountId: account(), onlyActive: only_active }),
1073
1075
  );
1074
1076
 
1077
+ read(
1078
+ "snap_delivery_check",
1079
+ {
1080
+ description: "Why is an ad squad not spending? (read-only) For each ACTIVE ad squad (or the one you name): did it show anything in the last days, and if not, what stops it: a paused campaign, a schedule that has not started or has ended, no ads or none approved, no budget, a missing pixel, an account that is not active. Snap's own delivery status is passed through. Use when the dashboard shows active ad squads but zero spend.",
1081
+ shape: { adsquad_id: id().optional(), campaign_id: id().optional(), days: z.number().int().min(1).max(14).default(3) },
1082
+ },
1083
+ ({ adsquad_id, campaign_id, days }) => deliveryCheck(client, { adAccountId: account(), adsquadId: adsquad_id, campaignId: campaign_id, days }),
1084
+ );
1085
+
1075
1086
  read(
1076
1087
  "snap_pixel_health",
1077
1088
  { description: "Pixel signal readiness and event-quality recommendations, highest priority first (read-only). Pixel defaults to SNAP_PIXEL_ID.", shape: { pixel_id: id().optional() } },
package/src/toolsets.js CHANGED
@@ -5,7 +5,7 @@ export const TOOLSETS = {
5
5
  setup: ["snap_ping", "snap_connect", "snap_change_log", "snap_setup_check", "snap_change_history"],
6
6
  read: ["snap_campaign_board", "snap_list_campaigns", "snap_list_adsquads", "snap_list_ads", "snap_list_creatives", "snap_list_media", "snap_list_segments", "snap_list_pixels", "snap_list_catalogs", "snap_list_product_sets", "snap_list_dynamic_templates", "snap_get_entity", "snap_get_media", "snap_targeting_options", "snap_api_get"],
7
7
  reports: ["snap_dashboard", "snap_get_stats", "snap_report", "snap_report_async_start", "snap_report_async_status", "snap_report_async_download", "snap_funnel", "snap_blended_roas", "snap_spend_pacing", "snap_creative_compare", "snap_portfolio_summary"],
8
- checks: ["snap_health_check", "snap_review_issues", "snap_pixel_health", "snap_creative_fatigue", "snap_anomaly_check", "snap_check_landing_pages", "snap_billing_check", "snap_unused_media", "snap_audience_health", "snap_catalog_feed_status", "snap_capi_status", "snap_budget_advice", "snap_audience_size", "snap_audience_insights", "snap_competitor_ads", "snap_ad_preview"],
8
+ checks: ["snap_health_check", "snap_review_issues", "snap_delivery_check", "snap_pixel_health", "snap_creative_fatigue", "snap_anomaly_check", "snap_check_landing_pages", "snap_billing_check", "snap_unused_media", "snap_audience_health", "snap_catalog_feed_status", "snap_capi_status", "snap_budget_advice", "snap_audience_size", "snap_audience_insights", "snap_competitor_ads", "snap_ad_preview"],
9
9
  changes: ["snap_set_status", "snap_set_daily_budget", "snap_set_bid", "snap_set_targeting", "snap_set_schedule", "snap_set_frequency_cap", "snap_set_ad_schedule", "snap_set_bid_strategy", "snap_set_placement", "snap_exclude_segments", "snap_rename", "snap_undo", "snap_delete"],
10
10
  create: ["snap_create_campaign", "snap_create_adsquad", "snap_create_creative", "snap_create_ad", "snap_create_story_creative", "snap_create_collection_creative", "snap_create_product_set", "snap_create_dynamic_template", "snap_create_lookalike", "snap_create_pixel_audience", "snap_upload_media", "snap_upload_customer_list", "snap_copy_campaign", "snap_copy_adsquad", "snap_clone_ad", "snap_clone_creative", "snap_claim_ad_code", "snap_influencer_ad", "snap_influencer_batch", "snap_capi_test_event"],
11
11
  };
@@ -15,14 +15,16 @@ const OF = new Map(Object.entries(TOOLSETS).flatMap(([group, names]) => names.ma
15
15
  export const LEGACY_ALIASES = { snap_set_status_bulk: "snap_set_status", snap_bulk_rename: "snap_rename", snap_bulk_set_schedule: "snap_set_schedule", snap_bulk_exclude_segments: "snap_exclude_segments", snap_bulk_set_budget: "snap_set_daily_budget", snap_report_daily: "snap_report", snap_report_hourly: "snap_report", snap_report_compare: "snap_report", snap_report_audience: "snap_report" };
16
16
  export const toolsetOf = (name) => OF.get(name) ?? OF.get(LEGACY_ALIASES[name]) ?? null;
17
17
 
18
- // "core": the everyday tools for reading, checking and launching campaigns (about 40), for apps that do better with fewer tools.
18
+ // "core": the everyday tools for reading, checking and launching campaigns (about 55), for apps that do better with fewer tools.
19
19
  // Everything else stays available: SNAP_TOOLSETS=core,reports adds a group, and the default (all) shows every tool.
20
20
  export const CORE_TOOLS = [
21
21
  "snap_ping", "snap_connect", "snap_list_campaigns", "snap_list_adsquads", "snap_list_ads", "snap_list_creatives", "snap_list_media", "snap_list_segments", "snap_get_entity",
22
- "snap_dashboard", "snap_campaign_board", "snap_report", "snap_get_stats", "snap_spend_pacing", "snap_health_check", "snap_review_issues", "snap_anomaly_check", "snap_budget_advice", "snap_creative_fatigue",
22
+ "snap_dashboard", "snap_campaign_board", "snap_report", "snap_get_stats", "snap_spend_pacing", "snap_health_check", "snap_review_issues", "snap_delivery_check", "snap_anomaly_check", "snap_budget_advice", "snap_creative_fatigue",
23
23
  "snap_set_status", "snap_set_daily_budget", "snap_set_bid", "snap_set_targeting", "snap_set_schedule", "snap_rename", "snap_exclude_segments", "snap_undo", "snap_change_log", "snap_change_history", "snap_setup_check",
24
24
  "snap_create_campaign", "snap_create_adsquad", "snap_create_creative", "snap_create_ad", "snap_upload_media", "snap_copy_campaign", "snap_copy_adsquad", "snap_clone_ad",
25
25
  "snap_targeting_options", "snap_ad_preview", "snap_delete",
26
+ // catalog (dynamic product) ads: find the catalog and its product sets, make a product set and a layout, check the feed
27
+ "snap_list_catalogs", "snap_list_product_sets", "snap_list_dynamic_templates", "snap_create_product_set", "snap_create_dynamic_template", "snap_catalog_feed_status",
26
28
  // used by the playbooks, so every playbook can run with only the core tools
27
29
  "snap_check_landing_pages", "snap_audience_size", "snap_pixel_health", "snap_blended_roas", "snap_capi_status", "snap_competitor_ads", "snap_clone_creative",
28
30
  ];