ads-mcp-for-snapchat 0.7.0 → 0.9.1

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 CHANGED
@@ -17,6 +17,10 @@ SNAP_DEFAULT_PHONE_CODE=
17
17
  SNAP_REPORT_UTC_OFFSET=+00:00
18
18
  # Optional: where the change/audit log goes (default: changes.log.jsonl, or <SNAP_ENV_FILE>.log.jsonl when that is set)
19
19
  # SNAP_LOG_FILE=
20
+ # Optional: SNAP_CAPI_TOKEN=... (a Conversions API token from Ads Manager, only for the Conversions API test tools if your normal login is not accepted there)
21
+ # Optional: SNAP_BROKER_URL=https://login.example.com (the shared login service; a refresh token is sent there, so use only one you trust)
22
+ # Optional: SNAP_HOME=/some/folder (where settings, the change log and exports live; default ~/.ads-mcp-for-snapchat for an npm install)
23
+ # Optional: SNAP_PORTFOLIO_FILES=/abs/path/.env,/abs/path/.env.account2 (accounts shown side by side by snap_portfolio_summary)
20
24
  # Optional: SNAP_TOOLSETS=setup,reports,checks (show only these tool groups: setup, read, reports, checks, changes, create; default all)
21
25
  # Optional: SNAP_MAX_LIFETIME_BUDGET, SNAP_MAX_ACTIVATION_DAILY_BUDGET, SNAP_MAX_ADDED_DAILY_BUDGET_24H, SNAP_ACCOUNT_CURRENCY=USD,
22
26
  # SNAP_READ_ONLY=1, SNAP_HUMAN_APPROVAL=elicit (see README "Safety settings")
package/ARCHITECTURE.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # Architecture and design notes
2
2
 
3
- For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API: 82 tools, all tests mocked (`npm test`). Read `README.md` first for setup and the tool table.
3
+ For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API: 85 tools, all tests mocked (`npm test`). Read `README.md` first for setup and the tool table.
4
4
 
5
5
  ## Architecture (src/)
6
+ - `portfolio.js`: several accounts side by side, from the settings files the owner lists in SNAP_PORTFOLIO_FILES (read-only).
6
7
  - `hygiene.js`: billing, unused media, audience health, funnel, catalog feed status (read-only). `toolsets.js`: tool groups for SNAP_TOOLSETS (a test fails when a new tool is not in a group).
7
8
  - `controls.js`: frequency cap and ad schedule planners. `advice.js`: hourly report, creative comparison and budget advice (read-only suggestions).
8
9
  - `intel.js`: Audience Insights, the public Ads Gallery, Conversions API test events (the token goes only to tr.snapchat.com; the real events endpoint is never called).
@@ -10,7 +11,7 @@ For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat
10
11
  - `catalog-ads.js`: product set filter rules, dynamic template / creative builders and DPA audiences (Snap's Dynamic Product Ads guide).
11
12
  - `insights.js`: audience size, spend pacing, ad preview (read-only). `prompts.js`: the playbooks (MCP prompts).
12
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`).
13
- - `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 82 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 85 tool definitions (zod schemas, handlers).
14
15
  - `snap.js`: `SnapClient` (token refresh, retry), `ENTITIES` (campaign, adsquad, ad, creative, media, segment), sanitize-for-create/update helpers, `createEntity/updateEntity/getEntity/listChildren`, `upload`.
15
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.
16
17
  - `changes.js`: plan functions (status, budget, exclusions, rename, bid, targeting, schedule), `applyChange` (logs before/after), `containsDeep`, `planUndo`.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.1 (2026-11-15)
4
+
5
+ Fixes from the first run of `verify` on a real ad account (19 of 24 checks passed; these are the other five and some rough edges). Mocked tests could not have found them.
6
+
7
+ - **Account-level numbers** (`snap_anomaly_check`, `snap_funnel`, `snap_report_hourly`, `snap_blended_roas`, `snap_portfolio_summary`): Snap's account-level stats only accept the `spend` field ("Only field 'spend' should be used when querying AdAccount stats"). Totals are now built from the per-campaign breakdown, the query the weekly report already used. Time series are merged from the same breakdown, then checked against Snap's own spend total; if the answer is not the whole account they are rebuilt from the active campaigns, and the answer states its coverage instead of showing silent zeros.
8
+ - **`snap_check_landing_pages`** timed out on a big account because it read every ad. It now reads only ACTIVE campaigns, their ACTIVE ad squads and those squads' ACTIVE ads, fetches only the creatives those ads use, and stops after about 40 seconds with a clear "partial" note rather than claiming everything is fine.
9
+ - `verify` reports the Conversions API test tools as skipped (needs `SNAP_CAPI_TOKEN`) when Snap does not accept the normal login there, instead of as a failure.
10
+ - **Conversions API test tools** (`snap_capi_*`): the token is now sent as Snap documents it (an `access_token` parameter). New optional setting `SNAP_CAPI_TOKEN` for a Conversions API token made in Ads Manager, used only for `tr.snapchat.com`. A refusal now says exactly what to do.
11
+ - `snap_audience_insights` explains an empty answer (targeting equal to the comparison). `snap_budget_advice` says how many ad squads were compared and why nothing is suggested. `snap_catalog_feed_status` judges staleness against each feed's own schedule and counts only real upload errors, not warnings. `verify` shows more detail, no longer times out on slow tools, and uses a narrowed targeting for the insights check.
12
+ - The GitHub repository is now `Usame794/snapchat-ads-mcp`; links in the package, the registry entry, the README and the login service pages use the new name.
13
+ - `verify` command: runs every read-only tool on your real account and prints what worked, what failed (with a short, tidy reason) and what was skipped. It only calls tools that declare themselves read-only and forces read-only mode; a test checks it sends nothing but GETs and the two read-only POSTs (audience size and insights).
14
+ - `broker/ASK-SNAP.md`: the message to send to Snap before announcing the shared login.
15
+
16
+ ## 0.9.0 (2026-11-15)
17
+
18
+ - **Shared login (log in with Snapchat, no OAuth app).** `setup` offers it first; in Claude Desktop leave the Client ID and secret empty and ask Claude to connect: the browser finishes the login by itself, nothing is pasted. A small stateless login service (`broker/`, a Cloudflare Worker) holds one shared app's secret and nothing else. It stores no tokens, accounts or logs: at login it seals the refresh token to a key made on the person's own computer and redirects only to `http://127.0.0.1:<port>` (checked), and later it only swaps a refresh token for a 30-minute access token. Using your own Snapchat app still works exactly as before and always wins when its secret is present.
19
+ - The login is protected by a signed state (no storage), a cookie that ties it to the browser that started it, an expiry, a loopback-only redirect, a nonce-bound sealed token, and a listener on the computer that checks the Host header and accepts one callback only.
20
+ - New: `PRIVACY.md`, `broker/README.md` (how to deploy and what to check before announcing it), `SNAP_BROKER_URL`, `adsMcpBroker` in `package.json` (the default service address, empty until one is deployed).
21
+ - Not yet run against the real Snapchat login: the service is tested against a fake one. Follow `broker/README.md` step 5 before announcing it. ChatGPT support is not part of this: ChatGPT needs a hosted MCP server.
22
+
23
+ ## Unreleased
24
+
25
+ - Docs: `SECURITY.md` now lists every outside address the server contacts and what is sent. New tests fail when a tool or a `SNAP_` setting is missing from the README, or when the code starts contacting an address that `SECURITY.md` does not list. `SNAP_HOME` was missing from the README and is now documented.
26
+
27
+ ## 0.8.0 (2026-11-15)
28
+
29
+ Not yet verified on a live account (built from Snap's documentation and mocked tests).
30
+
31
+ - `snap_set_bid_strategy`: switch an ad squad between max bid and target cost with the bid for the new strategy, under the same bid limits as `snap_set_bid`. An ad squad on auto-bid can be given a cap this way. Switching TO auto-bid is deliberately not offered, and an undo can never restore auto-bid, because that would remove the bid cap.
32
+ - `snap_set_placement`: automatic, or custom positions (PUBLIC_STORIES_INSTREAM, INTERSTITIAL_CONTENT, INTERSTITIAL_SPOTLIGHT, INTERSTITIAL_USER, FEED, CAMERA, CHAT_FEED with Snap's CHAT_FEED rule). Refused on ad squads that use content inclusion or exclusion lists. Undo works when a placement was set before.
33
+ - `snap_portfolio_summary`: all your ad accounts side by side. The accounts are the settings files you list in `SNAP_PORTFOLIO_FILES`; the tool takes no arguments, so the AI app cannot choose files. Each account is read with its own credentials, only account-level numbers are returned, and currencies are never added together.
34
+ - Undo now validates the new editable fields (placement, caps, schedules, bid strategy) the same way it validates the old ones.
35
+ - This release also contains everything in 0.7.0, which is already on npm.
36
+
3
37
  ## 0.7.0 (2026-11-15)
4
38
 
5
39
  Everything below is built from Snap's documentation and mocked tests and is not yet verified on a live account. New write tools are previewed, need approval, are audited and create things PAUSED; all other new tools only read.
@@ -48,7 +82,7 @@ Everything below is built from Snap's documentation and mocked tests and is not
48
82
  ## 0.4.1 (2026-11-14)
49
83
 
50
84
  - Settings files: when a key appears twice, the last line now wins (as in dotenv), so a line added at the end, such as `SNAP_READ_ONLY=1`, takes effect. Saving a secret or token replaces every copy of that key, so an older duplicate can never win.
51
- - Package and registry links point to the repository's real name, `Usame794/snap-ads-mcp` (0.4.0 linked to a name that does not exist).
85
+ - Package and registry links point to the repository's real name, `Usame794/snapchat-ads-mcp` (0.4.0 linked to a name that does not exist).
52
86
  - README: the second-account `claude mcp add` command had the server name after `-e`, which Claude Code rejects. Fixed, and it now starts the second account read-only with `-e SNAP_READ_ONLY=1`.
53
87
 
54
88
  ## 0.4.0 (2026-11-14)
@@ -56,7 +90,7 @@ Everything below is built from Snap's documentation and mocked tests and is not
56
90
  - Install from npm: `npx -y ads-mcp-for-snapchat` starts the server. `init`, `where`, `save-secret`, `auth`, `check` and `weekly-report` replace `node scripts/...` for installed copies; `help` lists them.
57
91
  - An installed copy keeps its settings, change log and exports in `~/.ads-mcp-for-snapchat` (or `SNAP_HOME`), never inside `node_modules`, so an update cannot erase them. A git checkout works exactly as before.
58
92
  - `server.json` for the official MCP Registry (`io.github.Usame794/ads-mcp-for-snapchat`).
59
- - Repository links point to `Usame794/snap-ads-mcp`.
93
+ - Repository links point to `Usame794/snapchat-ads-mcp`.
60
94
  - Verified live on a real account: a COLLECTION ad (paused).
61
95
 
62
96
  ## 0.3.2 (2026-11-14)
package/PRIVACY.md ADDED
@@ -0,0 +1,28 @@
1
+ # Privacy
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.
4
+
5
+ ## The tool (on your computer)
6
+ - Your settings, the change log and exports stay on your computer. Nothing is sent to the maintainer.
7
+ - It talks to Snapchat's servers with your login to read and change your own ad account, as you ask. It also contacts the addresses listed in `SECURITY.md`.
8
+ - Your AI app (for example Claude) sees the data the tool returns, under that app's own terms.
9
+
10
+ ## The shared login service (optional)
11
+ The service lets you log in with Snapchat without creating your own Snapchat app. It is a small, stateless program (`broker/worker.js`, running on Cloudflare Workers).
12
+
13
+ **What it does**
14
+ - At login, Snapchat sends it a one-time code. It exchanges that code, using the shared app's secret, for your refresh token.
15
+ - It immediately **seals** that token to a key that only your computer holds, and sends it to your own computer (an address starting with `http://127.0.0.1`, which is your machine). After that it cannot read it again.
16
+ - Later, your computer sends its refresh token to the service to get a short-lived access token, because that step needs the app's secret.
17
+
18
+ **What it does not do**
19
+ - It stores **no** tokens, no ad account data, no names, emails or IP addresses. It has no database and writes no logs of its own (a test checks the code uses no storage and no logging).
20
+ - It cannot read your ad account: your computer talks to Snapchat directly.
21
+ - It does not sell, share or analyze anything.
22
+
23
+ **Good to know**
24
+ - While a request is being handled the service holds your refresh token in memory, as it must. Its hosting provider (Cloudflare) may keep standard request metadata under its own terms.
25
+ - 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`).
26
+ - To stop access: revoke the app in Snapchat Business Manager and delete your settings file.
27
+
28
+ This is an unofficial project and is not affiliated with or endorsed by Snap Inc.
package/README.md CHANGED
@@ -26,11 +26,17 @@ A local [MCP](https://modelcontextprotocol.io) server that lets an AI assistant
26
26
 
27
27
  In every case `snap_create_ad` picks the matching ad type (REMOTE_WEBPAGE, SNAP_AD, STORY or COLLECTION) and the ad starts PAUSED. Creatives never deliver on their own. Find media already in the account with `snap_list_media`, or upload with `snap_upload_media` and wait until `snap_get_media` says READY.
28
28
 
29
+ ## Check that everything works on your account
30
+ `npx -y ads-mcp-for-snapchat verify` (or `node src/cli.js verify` in a git checkout) runs every read-only tool on your real account, one by one, and prints a short list: what worked, what failed and why, what was skipped (and which setting it needs). It changes nothing: it only calls tools that declare themselves read-only and forces read-only mode. The output contains no tokens and only shortened ids, so it is safe to paste into an issue.
31
+
32
+ ## Easiest: log in with Snapchat (no OAuth app)
33
+ When a login service is available (see `broker/README.md` and `PRIVACY.md`), you do not need to create a Snapchat OAuth app. Run `npx -y ads-mcp-for-snapchat setup` and choose **1. Shared login**, or install the Claude Desktop file, leave Client ID and secret empty, and ask Claude: "Connect my Snapchat ad account." You log in with Snapchat in your browser and pick your ad account. The service only passes your login along: it stores nothing, and your access is sealed so only your own computer can read it. Prefer to stay independent? Use your own app (next section), or run your own copy of the service.
34
+
29
35
  ## Easy setup (about 5 minutes)
30
36
  First, once: in [Snap Business Manager](https://business.snapchat.com) open **Business Details > OAuth Apps > + OAuth App**, use the Redirect URI `https://127.0.0.1/callback`, and copy the **Client ID** and **Client Secret** (the secret is shown only once).
31
37
 
32
38
  **Claude Desktop (no terminal):**
33
- 1. Download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snap-ads-mcp/releases/latest) and double-click it. Claude Desktop shows an install screen.
39
+ 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.
34
40
  2. Enter the Client ID and Client Secret, your highest daily budget and (optional) your main country. Leave **Read-only** on for now.
35
41
  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.
36
42
  4. Quit and reopen Claude Desktop. Ask: "call snap_ping".
@@ -83,6 +89,10 @@ With this setting the server asks **you**, through the MCP client's own dialog (
83
89
  | `SNAP_MAX_ADDED_DAILY_BUDGET_24H` | 2 x the line above | Most daily budget this server may add to the account in any 24 hours, all tools together: budgets it starts plus budget increases |
84
90
  | `SNAP_ACCOUNT_CURRENCY` | not set | If set (e.g. `USD`), writes are refused unless the ad account uses that currency |
85
91
  | `SNAP_READ_ONLY` | 0 | `1` = previews and reads only |
92
+ | `SNAP_CAPI_TOKEN` | (none) | Only for the Conversions API test tools (`snap_capi_*`): a Conversions API token made in Ads Manager (Events Manager > Conversions API > Generate token), used if Snap does not accept your normal login there. Sent only to `tr.snapchat.com`. |
93
+ | `SNAP_BROKER_URL` | (none) | 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. |
94
+ | `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. |
95
+ | `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. |
86
96
  | `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `setup, read, reports, checks, changes, create` (comma-separated). Fewer tools make some apps faster and less error-prone, e.g. `setup,reports,checks` for an analyst. It only hides tools. |
87
97
  | `SNAP_HUMAN_APPROVAL` | off | `elicit` = ask the user through the MCP client before every write |
88
98
  | `SNAP_APPROVAL_TTL_SECONDS` | 600 | Lifetime of an approval token |
@@ -131,6 +141,9 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
131
141
  | `snap_audience_health` | read: audiences that are not targetable, tiny, stale, or unused by active ad squads |
132
142
  | `snap_funnel` | read: impressions → swipes → views → add to cart → checkout → purchases with the rate at each step and the weakest step |
133
143
  | `snap_catalog_feed_status` | read: for each catalog feed, the last completed upload, the latest upload's status and issues |
144
+ | `snap_set_bid_strategy` | write (preview + approval): switch an ad squad between max bid and target cost with a new bid, inside the bid limits. Switching TO auto-bid is not offered (it removes the bid cap). |
145
+ | `snap_set_placement` | write (preview + approval): automatic, or custom positions (Discover feed, Camera, Spotlight, Stories...). Undo works when a placement was set before. |
146
+ | `snap_portfolio_summary` | read: all your ad accounts side by side (yesterday and last 7 days, what needs attention, totals per currency). Reads the settings files you list in `SNAP_PORTFOLIO_FILES`; the AI app cannot choose files. |
134
147
  | `snap_connect` | connect an ad account from inside the chat (link, pasted address, account choice); saves access on this computer, changes no ads |
135
148
  | `snap_list_campaigns`, `snap_list_adsquads`, `snap_list_ads`, `snap_list_creatives`, `snap_get_entity`, `snap_get_media`, `snap_get_stats` | read |
136
149
  | `snap_report` | read: ROAS, CPA, swipe rate, frequency by ad squad or ad |
@@ -255,7 +268,7 @@ Verified on the maintainer's own ad account. Anything not listed here is covered
255
268
 
256
269
  **Before the safety layer (earlier tests, on throwaway paused objects):** pause/enable (single and bulk), budget, bid, targeting, schedule, bulk edits, campaign / ad squad copy, ad and creative clone, create campaign and ad squad, lookalike and pixel audiences, customer-list audience (with fake data), influencer flow and batch, media upload (simple and chunked), async reports, health check, review issues, pixel health, and the guarded delete (on a throwaway campaign).
257
270
 
258
- **Not verified live:** everything added in 0.6.0 and 0.7.0 (`snap_audience_size`, `snap_spend_pacing`, `snap_ad_preview`; catalog ads; the landing page, anomaly, blended ROAS, audience insights, competitor ads, Conversions API test, hourly, creative comparison, budget advice, billing, unused media, audience health, funnel and feed tools; frequency cap and ad schedule; the new ad squad goals), all built from Snap's documentation and mocked tests, 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.
271
+ **Not verified live:** everything added in 0.6.0 and 0.7.0 (`snap_audience_size`, `snap_spend_pacing`, `snap_ad_preview`; catalog ads; bid-strategy switching, placement and the portfolio summary; the landing page, anomaly, blended ROAS, audience insights, competitor ads, Conversions API test, hourly, creative comparison, budget advice, billing, unused media, audience health, funnel and feed tools; frequency cap and ad schedule; the new ad squad goals), all built from Snap's documentation and mocked tests, 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.
259
272
 
260
273
  ## Not built
261
274
  - A hosted multi-user version (this server runs on your own machine with your own credentials).
package/SECURITY.md CHANGED
@@ -13,5 +13,18 @@ Supported version: the latest release on `main`. This is a small, unofficial pro
13
13
  - Rotate the client secret whenever it may have been seen outside your machine (pasted in a chat, a screenshot, a shared terminal): create a new secret in Snap Ads Manager, run `node scripts/save-secret.js`, then authorize again with `scripts/get-refresh-token.js`. The old secret and refresh token stop working.
14
14
  - Anything that can read `.env` holds the full API credentials and bypasses every guard in this server. Deny your AI client's file tools access to `.env` and `changes.log.jsonl`.
15
15
 
16
+ ## What this server connects to
17
+ Everything runs on your computer. These are the only outside addresses it contacts:
18
+
19
+ | Address | What for | What is sent |
20
+ |---|---|---|
21
+ | `adsapi.snapchat.com`, `accounts.snapchat.com` | The Snapchat Marketing API and login | Your requests, with your access token |
22
+ | `tr.snapchat.com` | Conversions API **test** events and their status (`snap_capi_*`) | Your access token and one test event; an email is hashed first. Real conversion events are never sent. |
23
+ | `adsapi.snapchat.com/v1/ads_library/...` | Competitor ads (`snap_competitor_ads`) | The advertiser name you search for. **No token**, nothing about your account. |
24
+ | The links of your own active ads | `snap_check_landing_pages` opens each link once | A plain request. Only `https`, never private, loopback or link-local addresses, and every redirect is checked again. No credentials. |
25
+ | The shared login service (`SNAP_BROKER_URL`), only if you chose the shared login | Logging in, and renewing the 30-minute access token | Your refresh token (it must, to renew). It stores nothing; see `PRIVACY.md`. Only use a service you trust. |
26
+
27
+ Text that comes back from outside (competitors' ads, page contents, ad review reasons) is untrusted data: it is cut, marked as such in the answer, and must not be followed as instructions. `SNAP_PORTFOLIO_FILES` can only be set by you in your own settings; the AI app cannot choose which files are read. The audit log removes credentials, emails and phone numbers from logged arguments.
28
+
16
29
  ## Safety design
17
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.
@@ -0,0 +1,26 @@
1
+ # Message to Snap (before announcing the shared login)
2
+
3
+ Send this through Snap's developer or Business support. Replace the placeholders. Attach the privacy page address of the deployed service.
4
+
5
+ **Subject:** Question about a shared OAuth app for an open-source Marketing API tool
6
+
7
+ Hello,
8
+
9
+ I maintain an open-source, unofficial tool called "Ads MCP for Snapchat" (https://github.com/Usame794/snapchat-ads-mcp). It runs on each advertiser's own computer and lets an AI assistant read reports and make previewed, approved changes to the advertiser's **own** ad account through the Marketing API. It is not affiliated with Snap Inc.
10
+
11
+ Today each advertiser creates their own OAuth app. To make setup easier I built an optional login service (code in the `broker` folder of the repository, privacy page: [PRIVACY PAGE ADDRESS]) that uses **one shared OAuth app**:
12
+
13
+ - An advertiser logs in with Snapchat and approves the app, as with any OAuth app.
14
+ - The service exchanges the code for a refresh token using the app's secret, and immediately **seals the token to a key that exists only on the advertiser's own computer**, then redirects to that computer (127.0.0.1). It stores no tokens, no ad account data and no logs.
15
+ - Later the advertiser's computer sends its refresh token to the service to get a short-lived access token (that step needs the secret).
16
+ - All Marketing API calls are made directly from the advertiser's computer to Snap. The service never reads ad account data.
17
+
18
+ My questions:
19
+ 1. May an OAuth app owned by me be used by advertisers outside my own organization in this way? Does the app need review, approval or allowlisting before other advertisers can authorize it?
20
+ 2. Are there requirements for such an app (privacy policy, data retention, security measures, a terms acknowledgement) beyond the Developer Terms and Business Tools Terms that I should meet?
21
+ 3. Are there restrictions on open-source tools that let an AI assistant make changes to ad accounts, beyond the existing API terms? The tool shows a preview and needs the advertiser's approval for every change, enforces spend limits the advertiser sets, and creates everything paused.
22
+ 4. Is the shared-app design acceptable, or would you prefer that each advertiser registers their own app?
23
+
24
+ Thank you,
25
+ [YOUR NAME]
26
+ [YOUR BUSINESS / CONTACT]
@@ -0,0 +1,43 @@
1
+ # Login service (optional)
2
+
3
+ A small, **stateless** Cloudflare Worker that lets people connect their Snapchat ad account with a normal "log in with Snapchat" click, without creating their own Snapchat OAuth app. It holds one shared app's secret and nothing else: no tokens, no accounts, no logs. See `../PRIVACY.md`.
4
+
5
+ You only need this folder if you want to **run the login service** (the maintainer does this once, for everyone). Normal users never touch it.
6
+
7
+ ## How it works
8
+ 1. `npx ads-mcp-for-snapchat setup` (or the Claude Desktop extension) makes a one-time key pair on the user's computer and opens `https://<service>/login?port=...&pk=<public key>&nonce=...`.
9
+ 2. The service sends the browser to Snapchat's login with a **signed** state (no storage needed) and a cookie that ties the login to that browser.
10
+ 3. Snapchat sends the browser back to `/callback`. The service checks the signature, expiry and cookie, exchanges the code (using the secret) for a refresh token, **seals it to the user's public key**, and redirects the browser to `http://127.0.0.1:<port>/callback` on the user's own machine. The service keeps nothing.
11
+ 4. Later the computer sends its refresh token to `POST /v1/refresh` to get a 30-minute access token, because that needs the secret.
12
+
13
+ ## Deploy (about 20 minutes)
14
+ You need a free Cloudflare account and a Snapchat Business Manager login.
15
+
16
+ 1. Install the tool and sign in: `npm install -g wrangler`, then `wrangler login`.
17
+ 2. Deploy once to learn the address: `cd broker && wrangler deploy`. It prints something like `https://ads-mcp-for-snapchat-login.<you>.workers.dev`. (Or attach your own domain in the Cloudflare dashboard.)
18
+ 3. In Snap Business Manager open **Business Details > OAuth Apps > + OAuth App**. Name it "Ads MCP for Snapchat". Set the **Redirect URI** to `https://<your address>/callback` exactly. Copy the Client ID and Client Secret.
19
+ 4. Store the three secrets (they are never put in files):
20
+ ```
21
+ wrangler secret put SNAP_CLIENT_ID
22
+ wrangler secret put SNAP_CLIENT_SECRET
23
+ wrangler secret put STATE_KEY
24
+ ```
25
+ For `STATE_KEY` paste any random text of 32+ characters, for example the output of `openssl rand -base64 48`.
26
+ 5. Check it: open `https://<your address>/` (a short home page) and `/privacy`. Then on your own computer run:
27
+ ```
28
+ SNAP_BROKER_URL=https://<your address> npx -y ads-mcp-for-snapchat setup
29
+ ```
30
+ Choose option 1 (shared login). It should open Snapchat's login, then say Connected.
31
+ 6. Make it the default for everyone: put the address in `package.json` as `"adsMcpBroker": "https://<your address>"`, then release a new version.
32
+
33
+ ## Before you tell other people about it
34
+ - **Ask Snap** whether an OAuth app may connect advertisers other than your own company, and whether the app needs review. Snap's rules decide this, not this code. Give them the privacy page address.
35
+ - **Add rate limits** in the Cloudflare dashboard (Security > WAF > Rate limiting): for example 30 requests per minute per IP for `/login` and `/v1/refresh`.
36
+ - **Know what you are running.** The service briefly holds each user's refresh token in memory while it handles a request. If its secrets leak, an attacker could use the shared app, so keep them in Cloudflare secrets only and rotate them if in doubt.
37
+ - If the service is down, shared-login users cannot renew their 30-minute access tokens until it is back. People with their own app are unaffected.
38
+
39
+ ## Run your own copy
40
+ The same code works with your own Snapchat app: deploy it as above and give your users `SNAP_BROKER_URL=https://<your address>`. Only point `SNAP_BROKER_URL` at a service you trust: a refresh token is sent there.
41
+
42
+ ## What is tested
43
+ `npm test` runs the real Worker code against a fake Snapchat: the state signature (tampered, expired, other key, other browser), the loopback-only redirect, sealing (only the user's key opens it), that no plaintext token or secret is ever in a redirect or an error, that nothing is logged or stored, and the whole login end to end. The Worker was also run in Cloudflare's own local runtime (`wrangler dev`): a token sealed there opens on a computer running Node, and forged or invalid requests are refused. It has **not** been run against the real Snapchat login: do step 5 above before announcing it.
@@ -0,0 +1,171 @@
1
+ // Login service for "Ads MCP for Snapchat": a small, STATELESS Cloudflare Worker. It lets people connect their Snapchat ad
2
+ // account with a normal "log in with Snapchat" click, without making their own Snapchat OAuth app. It holds the shared app's
3
+ // secret and nothing else: it stores no tokens, no accounts and no logs. See broker/README.md and PRIVACY.md.
4
+ //
5
+ // GET /login?port=&pk=&nonce= the person's computer starts a login (loopback port, a public key made for this login)
6
+ // GET /callback?code=&state= Snapchat sends the person back here; the refresh token is sealed to their key and handed to
7
+ // their own computer (http://127.0.0.1:<port>/callback). Nothing is kept.
8
+ // POST /v1/refresh their computer swaps its refresh token for a short-lived access token (needs the secret)
9
+ //
10
+ // Settings (Worker secrets and variables): SNAP_CLIENT_ID, SNAP_CLIENT_SECRET, STATE_KEY (random text, 32+ characters).
11
+ import { checkPublicKey, fromB64u, seal, toB64u } from "../src/hybrid.js";
12
+
13
+ const AUTHORIZE = "https://accounts.snapchat.com/login/oauth2/authorize";
14
+ const TOKEN = "https://accounts.snapchat.com/login/oauth2/access_token";
15
+ const STATE_MINUTES = 10;
16
+ const COOKIE = "ads_mcp_login";
17
+ const MAX_BODY = 8 * 1024;
18
+ const enc = new TextEncoder();
19
+
20
+ const SECURITY_HEADERS = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" };
21
+
22
+ const page = (title, body, status = 200, extra = {}) =>
23
+ new Response(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:40rem;margin:3rem auto;padding:0 1rem;color:#1a1a1a}code{background:#f2f2f2;padding:.1rem .3rem;border-radius:4px}</style><body>${body}</body></html>`, { status, headers: { "Content-Type": "text/html; charset=utf-8", ...SECURITY_HEADERS, ...extra } });
24
+
25
+ const json = (obj, status = 200) => new Response(JSON.stringify(obj), { status, headers: { "Content-Type": "application/json", ...SECURITY_HEADERS } });
26
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
27
+
28
+ // ---------- state: signed, so the service needs no storage ----------
29
+
30
+ async function hmacKey(env) {
31
+ if (!env.STATE_KEY || String(env.STATE_KEY).length < 32) throw new Error("STATE_KEY is missing or too short");
32
+ return crypto.subtle.importKey("raw", enc.encode(env.STATE_KEY), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
33
+ }
34
+
35
+ export async function signState(env, payload) {
36
+ const body = toB64u(enc.encode(JSON.stringify(payload)));
37
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await hmacKey(env), enc.encode(body)));
38
+ return `${body}.${toB64u(sig)}`;
39
+ }
40
+
41
+ export async function readState(env, text, now = Date.now()) {
42
+ const [body, sig, extra] = String(text ?? "").split(".");
43
+ if (!body || !sig || extra !== undefined) return null;
44
+ let sigBytes;
45
+ try {
46
+ sigBytes = fromB64u(sig);
47
+ } catch {
48
+ return null;
49
+ }
50
+ if (!(await crypto.subtle.verify("HMAC", await hmacKey(env), sigBytes, enc.encode(body)))) return null;
51
+ let payload;
52
+ try {
53
+ payload = JSON.parse(new TextDecoder().decode(fromB64u(body)));
54
+ } catch {
55
+ return null;
56
+ }
57
+ if (!payload || typeof payload.e !== "number" || payload.e < now) return null;
58
+ return payload;
59
+ }
60
+
61
+ const validPort = (p) => /^\d{4,5}$/.test(p) && Number(p) >= 1024 && Number(p) <= 65535;
62
+ const validNonce = (n) => /^[A-Za-z0-9_-]{16,64}$/.test(n ?? "");
63
+ const origin = (request, env) => (env.PUBLIC_URL ? String(env.PUBLIC_URL).replace(/\/+$/, "") : new URL(request.url).origin);
64
+ const getCookie = (request, name) => (request.headers.get("Cookie") ?? "").split(";").map((c) => c.trim().split("=")).find(([k]) => k === name)?.[1];
65
+
66
+ function need(env, ...keys) {
67
+ for (const k of keys) if (!env[k]) throw new Error(`${k} is not set`);
68
+ }
69
+
70
+ // ---------- routes ----------
71
+
72
+ async function login(request, env) {
73
+ need(env, "SNAP_CLIENT_ID", "SNAP_CLIENT_SECRET", "STATE_KEY");
74
+ const u = new URL(request.url);
75
+ const port = u.searchParams.get("port");
76
+ const pk = u.searchParams.get("pk");
77
+ const nonce = u.searchParams.get("nonce");
78
+ if (!validPort(port) || !checkPublicKey(pk) || !validNonce(nonce)) return page("Cannot start", "<h1>Cannot start the login</h1><p>The link is not valid. Start again from the setup command or the Claude Desktop extension.</p>", 400);
79
+ const state = await signState(env, { p: Number(port), k: pk, n: nonce, e: Date.now() + STATE_MINUTES * 60_000 });
80
+ const auth = new URL(AUTHORIZE);
81
+ auth.search = new URLSearchParams({ response_type: "code", client_id: env.SNAP_CLIENT_ID, redirect_uri: `${origin(request, env)}/callback`, scope: "snapchat-marketing-api", state }).toString();
82
+ return new Response(null, { status: 302, headers: { Location: auth.toString(), "Set-Cookie": `${COOKIE}=${nonce}; Path=/callback; Max-Age=${STATE_MINUTES * 60}; HttpOnly; Secure; SameSite=Lax`, ...SECURITY_HEADERS } });
83
+ }
84
+
85
+ async function callback(request, env, fetchImpl) {
86
+ need(env, "SNAP_CLIENT_ID", "SNAP_CLIENT_SECRET", "STATE_KEY");
87
+ const u = new URL(request.url);
88
+ const clear = { "Set-Cookie": `${COOKIE}=; Path=/callback; Max-Age=0; HttpOnly; Secure; SameSite=Lax` };
89
+ const state = await readState(env, u.searchParams.get("state"));
90
+ if (!state || !state.k || !validPort(String(state.p)) || !validNonce(state.n) || getCookie(request, COOKIE) !== state.n) {
91
+ return page("Login expired", "<h1>This login link is not valid any more</h1><p>It may have expired, or it was opened in a different browser. Start again from the setup command.</p>", 400, clear);
92
+ }
93
+ if (u.searchParams.get("error")) return page("Login cancelled", "<h1>Snapchat did not approve the login</h1><p>Nothing was saved. You can close this tab and start again.</p>", 400, clear);
94
+ const code = u.searchParams.get("code");
95
+ if (!code || code.length > 2048) return page("Login failed", "<h1>No code came back from Snapchat</h1><p>Start again.</p>", 400, clear);
96
+ const res = await fetchImpl(TOKEN, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: `${origin(request, env)}/callback`, client_id: env.SNAP_CLIENT_ID, client_secret: env.SNAP_CLIENT_SECRET }) });
97
+ const data = await res.json().catch(() => ({}));
98
+ if (!res.ok || !data.refresh_token) return page("Login failed", "<h1>Snapchat did not accept the login</h1><p>The code may have expired. Start again.</p>", 502, clear);
99
+ // The refresh token leaves here sealed to the key the person's own computer made for this login. It is not stored.
100
+ const sealed = await seal(state.k, data.refresh_token, state.n);
101
+ const back = new URL(`http://127.0.0.1:${state.p}/callback`);
102
+ back.search = new URLSearchParams({ nonce: state.n, epk: sealed.epk, salt: sealed.salt, iv: sealed.iv, ct: sealed.ct }).toString();
103
+ return new Response(null, { status: 302, headers: { Location: back.toString(), ...SECURITY_HEADERS, ...clear } });
104
+ }
105
+
106
+ async function refresh(request, env, fetchImpl) {
107
+ need(env, "SNAP_CLIENT_ID", "SNAP_CLIENT_SECRET");
108
+ if (request.method !== "POST") return json({ error: "use POST" }, 405);
109
+ if (!/^application\/json\b/i.test(request.headers.get("Content-Type") ?? "")) return json({ error: "send JSON" }, 415);
110
+ const text = await request.text();
111
+ if (text.length > MAX_BODY) return json({ error: "request too large" }, 413);
112
+ let body;
113
+ try {
114
+ body = JSON.parse(text);
115
+ } catch {
116
+ return json({ error: "invalid JSON" }, 400);
117
+ }
118
+ const token = body?.refresh_token;
119
+ if (typeof token !== "string" || token.length < 10 || token.length > 4096 || /\s/.test(token)) return json({ error: "refresh_token is missing or invalid" }, 400);
120
+ const res = await fetchImpl(TOKEN, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: token, client_id: env.SNAP_CLIENT_ID, client_secret: env.SNAP_CLIENT_SECRET }) });
121
+ const data = await res.json().catch(() => ({}));
122
+ if (!res.ok || !data.access_token) {
123
+ // Only Snap's short reason goes back; never the secret or anything we sent.
124
+ const reason = String(data.error_description ?? data.error ?? "refused").slice(0, 200);
125
+ return json({ error: "snapchat_refused", reason }, res.status === 400 || res.status === 401 ? 401 : 502);
126
+ }
127
+ return json({ access_token: data.access_token, expires_in: data.expires_in ?? 1800, ...(data.refresh_token && data.refresh_token !== token ? { refresh_token: data.refresh_token } : {}) });
128
+ }
129
+
130
+ const HOME = `<h1>Ads MCP for Snapchat: login service</h1>
131
+ <p>This small service lets you connect your own Snapchat ad account to the open-source tool <a href="https://github.com/Usame794/snapchat-ads-mcp">Ads MCP for Snapchat</a> with a normal "log in with Snapchat" button, so you do not have to create your own Snapchat app.</p>
132
+ <p><strong>It stores nothing.</strong> Your access is sealed so that only your own computer can read it. See the <a href="/privacy">privacy page</a>. This is an unofficial project and is not affiliated with Snap Inc.</p>`;
133
+
134
+ const PRIVACY = `<h1>Privacy</h1>
135
+ <p>This login service is part of the open-source tool Ads MCP for Snapchat. The tool itself runs on your computer.</p>
136
+ <h2>What this service does</h2>
137
+ <ul>
138
+ <li>When you log in, it receives a one-time code from Snapchat and exchanges it, using the shared app's secret, for your refresh token.</li>
139
+ <li>It immediately <strong>seals</strong> that token to a key that only your computer holds, and sends it to your computer (an address that starts with <code>http://127.0.0.1</code>, which is your own machine).</li>
140
+ <li>Later, your computer sends its refresh token to this service to get a short-lived access token, because that step needs the app's secret.</li>
141
+ </ul>
142
+ <h2>What it does not do</h2>
143
+ <ul>
144
+ <li>It does <strong>not store</strong> tokens, ad account data, names, emails or IP addresses, and it keeps no database and no logs of its own.</li>
145
+ <li>It cannot read your ad account data: your computer talks to Snapchat directly.</li>
146
+ <li>It does not sell, share or analyze anything.</li>
147
+ </ul>
148
+ <h2>Good to know</h2>
149
+ <ul>
150
+ <li>While a request is being handled the service briefly holds your refresh token in memory, as it must. The hosting provider (Cloudflare) may keep standard request metadata under its own terms.</li>
151
+ <li>You can revoke access at any time in Snapchat (Business Manager &gt; Business Details &gt; OAuth Apps / connected apps) and by deleting your settings file.</li>
152
+ <li>You can run your own copy of this service with your own Snapchat app: the code is in the <code>broker</code> folder of the repository.</li>
153
+ </ul>`;
154
+
155
+ export default {
156
+ async fetch(request, env, _ctx, fetchImpl = fetch) {
157
+ try {
158
+ const { pathname } = new URL(request.url);
159
+ if (pathname === "/" && request.method === "GET") return page("Ads MCP for Snapchat", HOME);
160
+ if (pathname === "/privacy" && request.method === "GET") return page("Privacy", PRIVACY);
161
+ if (pathname === "/login" && request.method === "GET") return await login(request, env);
162
+ if (pathname === "/callback" && request.method === "GET") return await callback(request, env, fetchImpl);
163
+ if (pathname === "/v1/refresh") return await refresh(request, env, fetchImpl);
164
+ return page("Not found", "<h1>Not found</h1>", 404);
165
+ } catch (e) {
166
+ // A generic answer: the reason may name a setting, never a value, and nothing about the request is logged.
167
+ const setting = /^(\w+) is (missing|not set)/.exec(e?.message ?? "")?.[1];
168
+ return page("Not available", `<h1>The login service is not set up correctly</h1>${setting ? `<p>Missing setting: <code>${esc(setting)}</code></p>` : ""}`, 503);
169
+ }
170
+ },
171
+ };
@@ -0,0 +1,10 @@
1
+ # Cloudflare Worker settings for the login service. See broker/README.md.
2
+ name = "ads-mcp-for-snapchat-login"
3
+ main = "worker.js"
4
+ compatibility_date = "2025-01-01"
5
+
6
+ # Set these as secrets, never in this file:
7
+ # wrangler secret put SNAP_CLIENT_ID
8
+ # wrangler secret put SNAP_CLIENT_SECRET
9
+ # wrangler secret put STATE_KEY (any random text of 32+ characters)
10
+ # Optional: PUBLIC_URL, if the address people reach is not the Worker's own origin.
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "ads-mcp-for-snapchat",
3
- "version": "0.7.0",
3
+ "version": "0.9.1",
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
+ "adsMcpBroker": "",
6
7
  "type": "module",
7
8
  "main": "src/index.js",
8
9
  "bin": {
@@ -35,12 +36,12 @@
35
36
  ],
36
37
  "repository": {
37
38
  "type": "git",
38
- "url": "git+https://github.com/Usame794/snap-ads-mcp.git"
39
+ "url": "git+https://github.com/Usame794/snapchat-ads-mcp.git"
39
40
  },
40
41
  "bugs": {
41
- "url": "https://github.com/Usame794/snap-ads-mcp/issues"
42
+ "url": "https://github.com/Usame794/snapchat-ads-mcp/issues"
42
43
  },
43
- "homepage": "https://github.com/Usame794/snap-ads-mcp#readme",
44
+ "homepage": "https://github.com/Usame794/snapchat-ads-mcp#readme",
44
45
  "files": [
45
46
  "src",
46
47
  "scripts/save-secret.js",
@@ -52,6 +53,8 @@
52
53
  "SECURITY.md",
53
54
  "LICENSE",
54
55
  ".env.example",
55
- "CHANGELOG.md"
56
+ "CHANGELOG.md",
57
+ "broker",
58
+ "PRIVACY.md"
56
59
  ]
57
60
  }
package/src/advice.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Read-only advice: which hours work, which creatives win, and where budget could move. They only read and suggest. Every
2
2
  // suggestion names the tool that would apply it, and that tool still previews and waits for approval.
3
- import { breakdownReport } from "./report.js";
3
+ import { accountSeries, breakdownReport } from "./report.js";
4
4
  import { localClock } from "./insights.js";
5
5
  import { shiftIso } from "./fatigue.js";
6
6
 
@@ -48,13 +48,23 @@ export async function hourlyReport(client, { entity = "adaccount", id, offset =
48
48
  if (!Number.isInteger(days) || days < 1 || days > 7) throw new Error("days must be a whole number from 1 to 7 (Snap's hourly limit)");
49
49
  const end = localClock(now, offset).todayStart;
50
50
  const start = shiftIso(end, -days * 86_400_000);
51
- const data = await client.request("GET", `/${ENTITY_BASE[entity]}/${id}/stats`, { query: { granularity: "HOUR", start_time: start, end_time: end, fields: "spend,impressions,conversion_purchases,conversion_purchases_value", omit_empty: true } });
52
- const series = data.timeseries_stats?.[0]?.timeseries_stat?.timeseries ?? [];
51
+ const fields = "spend,impressions,conversion_purchases,conversion_purchases_value";
52
+ let series;
53
+ let accountNote = {};
54
+ if (entity === "adaccount") {
55
+ const acc = await accountSeries(client, id, { granularity: "HOUR", start_time: start, end_time: end, fields });
56
+ series = acc.series;
57
+ accountNote = { source: acc.source, coverage_pct: acc.coverage_pct, ...(acc.warning ? { warning: acc.warning } : {}) };
58
+ } else {
59
+ const data = await client.request("GET", `/${ENTITY_BASE[entity]}/${id}/stats`, { query: { granularity: "HOUR", start_time: start, end_time: end, fields, omit_empty: true } });
60
+ series = data.timeseries_stats?.[0]?.timeseries_stat?.timeseries ?? [];
61
+ }
53
62
  const out = summarizeHours(series, start);
54
63
  return {
55
64
  window: { start_time: start, end_time: end, days },
56
65
  ...out,
57
66
  note: "Hours are local to SNAP_REPORT_UTC_OFFSET, summed over the days. Purchases are Snap-attributed and arrive late, so the most recent hours can look worse than they are. Seven days is a small sample: use it as a hint. To act on it, snap_set_ad_schedule needs a lifetime-budget ad squad.",
67
+ ...accountNote,
58
68
  ...(series.length ? {} : { warning: "Snap returned no hourly data for this window." }),
59
69
  };
60
70
  }
@@ -117,7 +127,7 @@ export async function creativeCompare(client, { adAccountId, entity, id, start_t
117
127
  export function suggestMoves(squads, { policy, minSpend = 50, shiftUpPct = 20, shiftDownPct = 25, extraBudget = 0 }) {
118
128
  const judged = squads.filter((s) => s.spend >= minSpend && s.roas != null && s.daily_budget > 0);
119
129
  const med = median(judged.map((s) => s.roas));
120
- if (med == null || judged.length < 3) return { median_roas: med == null ? null : round(med), decreases: [], increases: [], note: "Fewer than 3 ad squads have enough spend to compare, so no moves are suggested." };
130
+ if (med == null || judged.length < 3) return { median_roas: med == null ? null : round(med), squads_compared: judged.length, decreases: [], increases: [], note: "Fewer than 3 ad squads have enough spend to compare, so no moves are suggested." };
121
131
  const decreases = [];
122
132
  for (const s of judged.filter((x) => x.roas <= med * 0.6 || x.purchases === 0)) {
123
133
  const to = Math.max(policy.minDailyBudget, round(s.daily_budget * (1 - shiftDownPct / 100)));
@@ -139,6 +149,8 @@ export function suggestMoves(squads, { policy, minSpend = 50, shiftUpPct = 20, s
139
149
  const strip = (x) => ({ adsquad: x.name, adsquad_id: x.id, campaign: x.campaign, spend: x.spend, roas: x.roas, purchases: x.purchases, from: x.daily_budget, to: x.to, why: x.why, apply_with: `snap_set_daily_budget entity=adsquad id=${x.id} daily_budget=${x.to}` });
140
150
  return {
141
151
  median_roas: round(med),
152
+ squads_compared: judged.length,
153
+ ...(decreases.length || increases.length ? {} : { note: `${judged.length} ad squads had enough spend to compare and none is far enough from the median ROAS to suggest a move.` }),
142
154
  decreases: decreases.map(strip),
143
155
  increases: increases.map(strip),
144
156
  net_daily_budget_change: round(increases.reduce((n, x) => n + x.added, 0) - decreases.reduce((n, x) => n + x.freed, 0)),