ads-mcp-for-snapchat 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +3 -0
- package/ARCHITECTURE.md +3 -2
- package/CHANGELOG.md +21 -0
- package/PRIVACY.md +28 -0
- package/README.md +10 -1
- package/SECURITY.md +13 -0
- package/broker/README.md +43 -0
- package/broker/worker.js +171 -0
- package/broker/wrangler.toml +10 -0
- package/package.json +5 -2
- package/src/broker.js +109 -0
- package/src/changes.js +26 -1
- package/src/controls.js +27 -0
- package/src/env.js +11 -0
- package/src/hybrid.js +70 -0
- package/src/index.js +1 -1
- package/src/portfolio.js +82 -0
- package/src/setup.js +75 -44
- package/src/snap.js +12 -1
- package/src/tools.js +68 -4
- package/src/toolsets.js +2 -2
package/.env.example
CHANGED
|
@@ -17,6 +17,9 @@ 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_BROKER_URL=https://login.example.com (the shared login service; a refresh token is sent there, so use only one you trust)
|
|
21
|
+
# Optional: SNAP_HOME=/some/folder (where settings, the change log and exports live; default ~/.ads-mcp-for-snapchat for an npm install)
|
|
22
|
+
# Optional: SNAP_PORTFOLIO_FILES=/abs/path/.env,/abs/path/.env.account2 (accounts shown side by side by snap_portfolio_summary)
|
|
20
23
|
# Optional: SNAP_TOOLSETS=setup,reports,checks (show only these tool groups: setup, read, reports, checks, changes, create; default all)
|
|
21
24
|
# Optional: SNAP_MAX_LIFETIME_BUDGET, SNAP_MAX_ACTIVATION_DAILY_BUDGET, SNAP_MAX_ADDED_DAILY_BUDGET_24H, SNAP_ACCOUNT_CURRENCY=USD,
|
|
22
25
|
# 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:
|
|
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
|
|
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,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.0 (2026-11-15)
|
|
4
|
+
|
|
5
|
+
- **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.
|
|
6
|
+
- 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.
|
|
7
|
+
- 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).
|
|
8
|
+
- 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.
|
|
9
|
+
|
|
10
|
+
## Unreleased
|
|
11
|
+
|
|
12
|
+
- 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.
|
|
13
|
+
|
|
14
|
+
## 0.8.0 (2026-11-15)
|
|
15
|
+
|
|
16
|
+
Not yet verified on a live account (built from Snap's documentation and mocked tests).
|
|
17
|
+
|
|
18
|
+
- `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.
|
|
19
|
+
- `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.
|
|
20
|
+
- `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.
|
|
21
|
+
- Undo now validates the new editable fields (placement, caps, schedules, bid strategy) the same way it validates the old ones.
|
|
22
|
+
- This release also contains everything in 0.7.0, which is already on npm.
|
|
23
|
+
|
|
3
24
|
## 0.7.0 (2026-11-15)
|
|
4
25
|
|
|
5
26
|
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.
|
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,6 +26,9 @@ 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
|
+
## Easiest: log in with Snapchat (no OAuth app)
|
|
30
|
+
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.
|
|
31
|
+
|
|
29
32
|
## Easy setup (about 5 minutes)
|
|
30
33
|
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
34
|
|
|
@@ -83,6 +86,9 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
83
86
|
| `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
87
|
| `SNAP_ACCOUNT_CURRENCY` | not set | If set (e.g. `USD`), writes are refused unless the ad account uses that currency |
|
|
85
88
|
| `SNAP_READ_ONLY` | 0 | `1` = previews and reads only |
|
|
89
|
+
| `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. |
|
|
90
|
+
| `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. |
|
|
91
|
+
| `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
92
|
| `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
93
|
| `SNAP_HUMAN_APPROVAL` | off | `elicit` = ask the user through the MCP client before every write |
|
|
88
94
|
| `SNAP_APPROVAL_TTL_SECONDS` | 600 | Lifetime of an approval token |
|
|
@@ -131,6 +137,9 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
131
137
|
| `snap_audience_health` | read: audiences that are not targetable, tiny, stale, or unused by active ad squads |
|
|
132
138
|
| `snap_funnel` | read: impressions → swipes → views → add to cart → checkout → purchases with the rate at each step and the weakest step |
|
|
133
139
|
| `snap_catalog_feed_status` | read: for each catalog feed, the last completed upload, the latest upload's status and issues |
|
|
140
|
+
| `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). |
|
|
141
|
+
| `snap_set_placement` | write (preview + approval): automatic, or custom positions (Discover feed, Camera, Spotlight, Stories...). Undo works when a placement was set before. |
|
|
142
|
+
| `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
143
|
| `snap_connect` | connect an ad account from inside the chat (link, pasted address, account choice); saves access on this computer, changes no ads |
|
|
135
144
|
| `snap_list_campaigns`, `snap_list_adsquads`, `snap_list_ads`, `snap_list_creatives`, `snap_get_entity`, `snap_get_media`, `snap_get_stats` | read |
|
|
136
145
|
| `snap_report` | read: ROAS, CPA, swipe rate, frequency by ad squad or ad |
|
|
@@ -255,7 +264,7 @@ Verified on the maintainer's own ad account. Anything not listed here is covered
|
|
|
255
264
|
|
|
256
265
|
**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
266
|
|
|
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.
|
|
267
|
+
**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
268
|
|
|
260
269
|
## Not built
|
|
261
270
|
- 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.
|
package/broker/README.md
ADDED
|
@@ -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.
|
package/broker/worker.js
ADDED
|
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[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/snap-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 > Business Details > 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.
|
|
3
|
+
"version": "0.9.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
|
+
"adsMcpBroker": "",
|
|
6
7
|
"type": "module",
|
|
7
8
|
"main": "src/index.js",
|
|
8
9
|
"bin": {
|
|
@@ -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/broker.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// The computer's side of the shared login: where the login service is, how to start a login (a tiny listener on this computer
|
|
2
|
+
// only), and how to swap a refresh token for an access token through the service. The refresh token never travels in the clear
|
|
3
|
+
// after the login: the service seals it to a key made here, for this one login.
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { randomBytes, webcrypto } from "node:crypto";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { ROOT } from "./env.js";
|
|
9
|
+
import { generateKeyPair, open, toB64u } from "./hybrid.js";
|
|
10
|
+
|
|
11
|
+
// The address of the login service people use by default. Empty until the maintainer deploys one and sets "adsMcpBroker" in
|
|
12
|
+
// package.json. SNAP_BROKER_URL overrides it (for example to run your own copy of the service).
|
|
13
|
+
function packageDefault() {
|
|
14
|
+
try {
|
|
15
|
+
return String(JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).adsMcpBroker ?? "");
|
|
16
|
+
} catch {
|
|
17
|
+
return "";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Returns the service's origin, or null when none is set. Only https, or a loopback address for local testing. A refresh token is
|
|
22
|
+
// sent to this address, so a plain http address to anything else is refused.
|
|
23
|
+
export function brokerUrlFrom(env = process.env, fallback = packageDefault()) {
|
|
24
|
+
const raw = String(env.SNAP_BROKER_URL ?? "").trim() || String(fallback ?? "").trim();
|
|
25
|
+
if (!raw) return null;
|
|
26
|
+
let u;
|
|
27
|
+
try {
|
|
28
|
+
u = new URL(raw);
|
|
29
|
+
} catch {
|
|
30
|
+
throw new Error("SNAP_BROKER_URL is not a valid address");
|
|
31
|
+
}
|
|
32
|
+
const loopback = u.protocol === "http:" && (u.hostname === "127.0.0.1" || u.hostname === "localhost");
|
|
33
|
+
if (u.protocol !== "https:" && !loopback) throw new Error("SNAP_BROKER_URL must start with https:// (a refresh token is sent there)");
|
|
34
|
+
if (u.username || u.password || u.search || u.hash || (u.pathname !== "/" && u.pathname !== "")) throw new Error("SNAP_BROKER_URL must be just the address, like https://login.example.com");
|
|
35
|
+
return u.origin;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const DONE_PAGE = (ok) =>
|
|
39
|
+
`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Ads MCP for Snapchat</title><body style="font:16px/1.5 system-ui,sans-serif;max-width:36rem;margin:3rem auto;padding:0 1rem">${
|
|
40
|
+
ok ? "<h1>Connected</h1><p>Your Snapchat login was received by Ads MCP for Snapchat. You can close this tab and go back to the terminal or to Claude.</p>" : "<h1>Could not finish</h1><p>This link did not work. Go back and start the login again.</p>"
|
|
41
|
+
}</body></html>`;
|
|
42
|
+
|
|
43
|
+
// Starts a login. Returns { url, done, close }: open `url` in a browser; `done` resolves with the refresh token.
|
|
44
|
+
// The listener accepts only this login's one callback, only for the loopback address, and closes itself afterwards.
|
|
45
|
+
export async function startBrokerLogin({ brokerUrl, timeoutMs = 5 * 60_000, crypto = webcrypto } = {}) {
|
|
46
|
+
if (!brokerUrl) throw new Error("No login service address is set");
|
|
47
|
+
const keys = await generateKeyPair(crypto);
|
|
48
|
+
const nonce = toB64u(randomBytes(18));
|
|
49
|
+
let finish;
|
|
50
|
+
let fail;
|
|
51
|
+
const done = new Promise((resolve, reject) => {
|
|
52
|
+
finish = resolve;
|
|
53
|
+
fail = reject;
|
|
54
|
+
});
|
|
55
|
+
let settled = false;
|
|
56
|
+
const server = createServer(async (req, res) => {
|
|
57
|
+
const reply = (status, ok) => {
|
|
58
|
+
res.writeHead(status, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'" });
|
|
59
|
+
res.end(DONE_PAGE(ok));
|
|
60
|
+
};
|
|
61
|
+
try {
|
|
62
|
+
const u = new URL(req.url, "http://127.0.0.1");
|
|
63
|
+
// Host check: a web page cannot reach this listener through a name that points at 127.0.0.1 (DNS rebinding).
|
|
64
|
+
if (req.method !== "GET" || u.pathname !== "/callback" || req.headers.host !== `127.0.0.1:${server.address().port}`) return reply(404, false);
|
|
65
|
+
const q = u.searchParams;
|
|
66
|
+
if (settled || q.get("nonce") !== nonce) return reply(400, false);
|
|
67
|
+
const token = await open(keys.privateKey, { v: 1, epk: q.get("epk"), salt: q.get("salt"), iv: q.get("iv"), ct: q.get("ct") }, nonce, crypto);
|
|
68
|
+
if (typeof token !== "string" || token.length < 10) return reply(400, false);
|
|
69
|
+
settled = true;
|
|
70
|
+
reply(200, true);
|
|
71
|
+
clear();
|
|
72
|
+
finish(token);
|
|
73
|
+
} catch {
|
|
74
|
+
reply(400, false);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
const timer = setTimeout(() => {
|
|
78
|
+
if (!settled) {
|
|
79
|
+
settled = true;
|
|
80
|
+
clear();
|
|
81
|
+
fail(new Error("The login was not completed in time. Start again."));
|
|
82
|
+
}
|
|
83
|
+
}, timeoutMs);
|
|
84
|
+
timer.unref?.();
|
|
85
|
+
const clear = () => {
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
server.close();
|
|
88
|
+
server.closeAllConnections?.();
|
|
89
|
+
};
|
|
90
|
+
await new Promise((resolve, reject) => {
|
|
91
|
+
server.once("error", reject);
|
|
92
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
93
|
+
});
|
|
94
|
+
const port = server.address().port;
|
|
95
|
+
const url = new URL(`${brokerUrl}/login`);
|
|
96
|
+
url.search = new URLSearchParams({ port: String(port), pk: keys.publicKey, nonce }).toString();
|
|
97
|
+
return { url: url.toString(), port, done, close: () => { if (!settled) { settled = true; clear(); fail(new Error("cancelled")); } } };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Swaps the refresh token for an access token through the login service (which holds the app's secret).
|
|
101
|
+
export async function refreshViaBroker(brokerUrl, refreshToken, fetchImpl = fetch, timeoutMs = 30_000) {
|
|
102
|
+
const res = await fetchImpl(`${brokerUrl}/v1/refresh`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ refresh_token: refreshToken }), signal: AbortSignal.timeout(timeoutMs) });
|
|
103
|
+
const data = await res.json().catch(() => ({}));
|
|
104
|
+
if (!res.ok || !data.access_token) {
|
|
105
|
+
const why = data.reason || data.error || `status ${res.status}`;
|
|
106
|
+
throw new Error(`Snap login service refused the token refresh (${res.status}: ${String(why).slice(0, 200)})${res.status === 401 ? ". The login may have been revoked or expired: run setup again." : ""}`);
|
|
107
|
+
}
|
|
108
|
+
return data;
|
|
109
|
+
}
|
package/src/changes.js
CHANGED
|
@@ -57,6 +57,24 @@ export function planExcludeSegments(current, segmentIds) {
|
|
|
57
57
|
return { patch: { targeting }, summary: `exclude segments ${toAdd.join(", ")}` };
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
// Switch between the two strategies that carry a bid: max bid and target cost. Switching TO one of them from auto-bid is allowed
|
|
61
|
+
// (it adds a cap). Switching to auto-bid is not offered: it would remove the bid cap, which this server never does.
|
|
62
|
+
export const BID_STRATEGIES = ["LOWEST_COST_WITH_MAX_BID", "TARGET_COST"];
|
|
63
|
+
export function planBidStrategy(current, { strategy, bid }, env = process.env, { history } = {}) {
|
|
64
|
+
const policy = loadPolicy(env);
|
|
65
|
+
if (!BID_STRATEGIES.includes(strategy)) throw new Error(`strategy must be ${BID_STRATEGIES.join(" or ")}. Switching to auto-bid removes the bid cap, so it is not offered here; do it in Ads Manager.`);
|
|
66
|
+
if (!(bid > 0)) throw new Error("bid is required (account currency): the max bid, or the target cost");
|
|
67
|
+
const nowStrategy = current.bid_strategy ?? (current.auto_bid ? "AUTO_BID" : "LOWEST_COST_WITH_MAX_BID");
|
|
68
|
+
const before = current.bid_micro != null ? unmicro(current.bid_micro) : null;
|
|
69
|
+
if (nowStrategy === strategy && before === bid) throw new Error("The bid strategy and bid are already those values");
|
|
70
|
+
checkBid(policy, { before, value: bid, windowStart: before == null ? null : windowStart(history, current, "bid_micro"), what: strategy === "TARGET_COST" ? "Target cost" : "Max bid" });
|
|
71
|
+
const patch = { bid_strategy: strategy, bid_micro: micro(bid) };
|
|
72
|
+
// Older fields Snap still returns on the same ad squad; kept consistent with the strategy when present.
|
|
73
|
+
if ("auto_bid" in current) patch.auto_bid = false;
|
|
74
|
+
if ("target_bid" in current) patch.target_bid = strategy === "TARGET_COST";
|
|
75
|
+
return { patch, summary: `bid strategy ${nowStrategy}${before != null ? ` (${before})` : ""} -> ${strategy} (${bid})`, note: strategy === "TARGET_COST" ? "With target cost Snap aims for the average cost you give instead of capping each bid, so delivery and spend can behave differently. The daily budget limit still applies." : undefined };
|
|
76
|
+
}
|
|
77
|
+
|
|
60
78
|
export function planRename(current, newName) {
|
|
61
79
|
const n = String(newName ?? "").trim();
|
|
62
80
|
if (n.length < 3) throw new Error("New name must be at least 3 characters");
|
|
@@ -267,13 +285,20 @@ export function undoableEntries(file = LOG_FILE) {
|
|
|
267
285
|
}
|
|
268
286
|
|
|
269
287
|
// The only fields this server ever edits. An undo restores nothing else, whatever a log entry claims.
|
|
270
|
-
const UNDOABLE_FIELDS = ["status", "daily_budget_micro", "bid_micro", "targeting", "start_time", "end_time", "name", "cap_and_exclusion_config", "ad_scheduling_config"];
|
|
288
|
+
const UNDOABLE_FIELDS = ["status", "daily_budget_micro", "bid_micro", "targeting", "start_time", "end_time", "name", "cap_and_exclusion_config", "ad_scheduling_config", "placement_v2", "bid_strategy", "auto_bid", "target_bid"];
|
|
271
289
|
|
|
272
290
|
export function planUndo(entry, current, { force = false, env = process.env, history } = {}) {
|
|
273
291
|
const keys = Object.keys(entry.patch ?? {});
|
|
274
292
|
if (!keys.length || !entry.before || typeof entry.before !== "object") throw new Error("That log entry has nothing that can be undone");
|
|
275
293
|
const foreign = keys.filter((k) => !UNDOABLE_FIELDS.includes(k));
|
|
276
294
|
if (foreign.length) throw new Error(`That log entry touches ${foreign.join(", ")}, which this server never edits; refusing to restore it.`);
|
|
295
|
+
// An undo never restores auto-bid (that would remove the bid cap), whatever a log entry claims.
|
|
296
|
+
if (keys.includes("bid_strategy") && !BID_STRATEGIES.includes(entry.before.bid_strategy)) throw new Error("That log entry would restore a bid strategy other than max bid or target cost (which would remove the bid cap); refusing.");
|
|
297
|
+
if (keys.includes("bid_strategy") && !(typeof entry.before.bid_micro === "number" && entry.before.bid_micro > 0)) throw new Error("That log entry has no valid earlier bid for the bid strategy; refusing.");
|
|
298
|
+
for (const k of ["cap_and_exclusion_config", "ad_scheduling_config", "placement_v2"]) {
|
|
299
|
+
if (keys.includes(k) && entry.before[k] != null && (typeof entry.before[k] !== "object" || Array.isArray(entry.before[k]))) throw new Error(`That log entry has no valid earlier ${k}; refusing.`);
|
|
300
|
+
}
|
|
301
|
+
if (keys.includes("placement_v2") && entry.before.placement_v2 && !["AUTOMATIC", "CUSTOM"].includes(entry.before.placement_v2.config)) throw new Error("That log entry would restore an unknown placement; refusing.");
|
|
277
302
|
if (keys.includes("status") && !["ACTIVE", "PAUSED"].includes(entry.before.status)) throw new Error("That log entry would restore a status other than ACTIVE or PAUSED; refusing.");
|
|
278
303
|
for (const k of ["daily_budget_micro", "bid_micro"]) {
|
|
279
304
|
if (keys.includes(k) && entry.before[k] != null && !(typeof entry.before[k] === "number" && Number.isFinite(entry.before[k]) && entry.before[k] > 0)) throw new Error(`That log entry has no valid earlier ${k}; refusing.`);
|
package/src/controls.js
CHANGED
|
@@ -72,3 +72,30 @@ export function planAdSchedule(current, { schedule, always = false }) {
|
|
|
72
72
|
note: "Hours are each viewer's local time. The schedule cannot conflict with the ad squad's start and end dates. Ads outside these hours do not run, so a narrow schedule lowers delivery.",
|
|
73
73
|
};
|
|
74
74
|
}
|
|
75
|
+
|
|
76
|
+
// ---------- Placement ----------
|
|
77
|
+
|
|
78
|
+
// Where on Snapchat the ads may appear. INSTREAM is left out: it belongs to commercials and needs content bundles.
|
|
79
|
+
export const PLACEMENT_POSITIONS = ["PUBLIC_STORIES_INSTREAM", "INTERSTITIAL_CONTENT", "INTERSTITIAL_SPOTLIGHT", "INTERSTITIAL_USER", "FEED", "CAMERA", "CHAT_FEED"];
|
|
80
|
+
|
|
81
|
+
export function planPlacement(current, { mode, positions }) {
|
|
82
|
+
const now = current.placement_v2 ?? null;
|
|
83
|
+
const describe = (p) => (!p ? "automatic" : p.config === "AUTOMATIC" ? "automatic (everywhere)" : `custom: ${(p.snapchat_positions ?? []).join(", ")}`);
|
|
84
|
+
if (now && (now.inclusion || now.exclusion)) throw new Error("This ad squad has content inclusion or exclusion lists in its placement. Change its placement in Ads Manager so those are not lost.");
|
|
85
|
+
let next;
|
|
86
|
+
if (mode === "automatic") {
|
|
87
|
+
if (positions?.length) throw new Error("Do not give positions with mode automatic");
|
|
88
|
+
next = { config: "AUTOMATIC" };
|
|
89
|
+
} else if (mode === "custom") {
|
|
90
|
+
if (!Array.isArray(positions) || !positions.length) throw new Error(`positions is required for custom placement: ${PLACEMENT_POSITIONS.join(", ")}`);
|
|
91
|
+
const bad = positions.filter((p) => !PLACEMENT_POSITIONS.includes(p));
|
|
92
|
+
if (bad.length) throw new Error(`Unknown or unsupported position ${bad.join(", ")}. Allowed: ${PLACEMENT_POSITIONS.join(", ")}`);
|
|
93
|
+
const set = [...new Set(positions)].sort();
|
|
94
|
+
if (set.includes("CHAT_FEED") && !set.includes("INTERSTITIAL_CONTENT") && !set.includes("INTERSTITIAL_USER")) throw new Error("CHAT_FEED must be combined with INTERSTITIAL_CONTENT or INTERSTITIAL_USER (Snap's rule)");
|
|
95
|
+
next = { config: "CUSTOM", platforms: ["SNAPCHAT"], snapchat_positions: set };
|
|
96
|
+
} else {
|
|
97
|
+
throw new Error("mode must be automatic or custom");
|
|
98
|
+
}
|
|
99
|
+
if (JSON.stringify(now) === JSON.stringify(next)) throw new Error("The placement is already that value");
|
|
100
|
+
return { patch: { placement_v2: next }, summary: `placement ${describe(now)} -> ${describe(next)}`, note: "Fewer placements usually mean less reach and a higher cost. Undo works when a placement was set before." };
|
|
101
|
+
}
|
package/src/env.js
CHANGED
|
@@ -17,6 +17,17 @@ export const DATA_DIR = dataDir();
|
|
|
17
17
|
// The settings file in use: SNAP_ENV_FILE when set (one file per ad account), otherwise .env in the data folder.
|
|
18
18
|
export const envFile = () => process.env.SNAP_ENV_FILE || join(dataDir(), ".env");
|
|
19
19
|
|
|
20
|
+
// The settings in a file, as an object, without touching process.env. When a key appears twice the last line wins.
|
|
21
|
+
export function readEnvFile(file) {
|
|
22
|
+
const values = {};
|
|
23
|
+
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
24
|
+
const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
|
|
25
|
+
if (!m || line.trim().startsWith("#")) continue;
|
|
26
|
+
values[m[1]] = m[2].replace(/^["']|["']$/g, "");
|
|
27
|
+
}
|
|
28
|
+
return values;
|
|
29
|
+
}
|
|
30
|
+
|
|
20
31
|
// Minimal .env loader so the server needs no extra dependency.
|
|
21
32
|
export function loadEnv(file = envFile(), { override = false } = {}) {
|
|
22
33
|
let text;
|
package/src/hybrid.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Sealing a secret so that only one computer can open it: ECDH (P-256) with an ephemeral key, HKDF-SHA256, AES-256-GCM.
|
|
2
|
+
// Pure Web Crypto with no Node imports, so the same file runs in the login service (a Cloudflare Worker) and on the user's
|
|
3
|
+
// computer. The login service seals a refresh token to the public key the user's computer made for this one login; after that
|
|
4
|
+
// nothing the service keeps can open it, and a copy of the sealed text is useless to anyone else.
|
|
5
|
+
|
|
6
|
+
const enc = new TextEncoder();
|
|
7
|
+
const dec = new TextDecoder();
|
|
8
|
+
const INFO = enc.encode("ads-mcp-for-snapchat sealed-token v1");
|
|
9
|
+
|
|
10
|
+
export const toB64u = (bytes) => {
|
|
11
|
+
let s = "";
|
|
12
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
13
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const fromB64u = (text) => {
|
|
17
|
+
if (typeof text !== "string" || !/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
|
|
18
|
+
const s = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4));
|
|
19
|
+
return Uint8Array.from(s, (c) => c.charCodeAt(0));
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const ECDH = { name: "ECDH", namedCurve: "P-256" };
|
|
23
|
+
|
|
24
|
+
// A public key as the 65 bytes of an uncompressed P-256 point, base64url (87 characters).
|
|
25
|
+
export const PUBLIC_KEY_LENGTH = 65;
|
|
26
|
+
|
|
27
|
+
export async function generateKeyPair(crypto = globalThis.crypto) {
|
|
28
|
+
const pair = await crypto.subtle.generateKey(ECDH, true, ["deriveBits"]);
|
|
29
|
+
return { privateKey: pair.privateKey, publicKey: toB64u(new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey))) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function checkPublicKey(text) {
|
|
33
|
+
let raw;
|
|
34
|
+
try {
|
|
35
|
+
raw = fromB64u(text);
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
return raw.length === PUBLIC_KEY_LENGTH && raw[0] === 4;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function deriveKey(crypto, privateKey, peerPublicRaw, salt) {
|
|
43
|
+
const peer = await crypto.subtle.importKey("raw", peerPublicRaw, ECDH, false, []);
|
|
44
|
+
const bits = await crypto.subtle.deriveBits({ name: "ECDH", public: peer }, privateKey, 256);
|
|
45
|
+
const base = await crypto.subtle.importKey("raw", bits, "HKDF", false, ["deriveKey"]);
|
|
46
|
+
return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt, info: INFO }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// `aad` is extra text the sealed value is bound to (the login's nonce), so it cannot be replayed into another login.
|
|
50
|
+
export async function seal(publicKey, plaintext, aad, crypto = globalThis.crypto) {
|
|
51
|
+
if (!checkPublicKey(publicKey)) throw new Error("invalid public key");
|
|
52
|
+
const ephemeral = await crypto.subtle.generateKey(ECDH, true, ["deriveBits"]);
|
|
53
|
+
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
54
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
55
|
+
const key = await deriveKey(crypto, ephemeral.privateKey, fromB64u(publicKey), salt);
|
|
56
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(String(aad)) }, key, enc.encode(plaintext)));
|
|
57
|
+
return { v: 1, epk: toB64u(new Uint8Array(await crypto.subtle.exportKey("raw", ephemeral.publicKey))), salt: toB64u(salt), iv: toB64u(iv), ct: toB64u(ct) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function open(privateKey, sealed, aad, crypto = globalThis.crypto) {
|
|
61
|
+
if (!sealed || sealed.v !== 1) throw new Error("unknown format");
|
|
62
|
+
const epk = fromB64u(sealed.epk);
|
|
63
|
+
if (epk.length !== PUBLIC_KEY_LENGTH || epk[0] !== 4) throw new Error("invalid key");
|
|
64
|
+
const key = await deriveKey(crypto, privateKey, epk, fromB64u(sealed.salt));
|
|
65
|
+
try {
|
|
66
|
+
return dec.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromB64u(sealed.iv), additionalData: enc.encode(String(aad)) }, key, fromB64u(sealed.ct)));
|
|
67
|
+
} catch {
|
|
68
|
+
throw new Error("could not open the sealed value (wrong key, changed data, or a different login)");
|
|
69
|
+
}
|
|
70
|
+
}
|
package/src/index.js
CHANGED
|
@@ -20,7 +20,7 @@ try {
|
|
|
20
20
|
}
|
|
21
21
|
// Snapshot of the non-secret settings taken at startup. Later edits to .env do not change limits or the target account.
|
|
22
22
|
const settings = { ...process.env };
|
|
23
|
-
const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.
|
|
23
|
+
const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.9.0" });
|
|
24
24
|
// Only the OAuth credentials are re-read from .env when a token is needed, so replacing them does not require a restart.
|
|
25
25
|
const client = new SnapClient({ beforeToken: () => loadEnv(undefined, { override: true }), timeoutMs: policy.httpTimeoutMs });
|
|
26
26
|
registerTools(server, client, settings);
|
package/src/portfolio.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Several ad accounts in one answer (read-only). The server's owner lists the settings files of the accounts in
|
|
2
|
+
// SNAP_PORTFOLIO_FILES; the AI app cannot choose files, so it cannot point this at anything else. Each account is read with its
|
|
3
|
+
// own credentials and only account-level numbers are returned: no secrets, no tokens, no changes.
|
|
4
|
+
import { isAbsolute, basename } from "node:path";
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import { readEnvFile } from "./env.js";
|
|
7
|
+
import { dailyReport } from "./report.js";
|
|
8
|
+
import { judgeDays } from "./checks.js";
|
|
9
|
+
import { localClock } from "./insights.js";
|
|
10
|
+
import { shiftIso } from "./fatigue.js";
|
|
11
|
+
import { SnapClient } from "./snap.js";
|
|
12
|
+
|
|
13
|
+
const round = (n, d = 2) => Math.round(n * 10 ** d) / 10 ** d;
|
|
14
|
+
|
|
15
|
+
export function parsePortfolioFiles(raw) {
|
|
16
|
+
const files = String(raw ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
17
|
+
if (!files.length) return [];
|
|
18
|
+
if (files.length > 10) throw new Error("SNAP_PORTFOLIO_FILES lists more than 10 files");
|
|
19
|
+
for (const f of files) if (!isAbsolute(f)) throw new Error(`SNAP_PORTFOLIO_FILES needs absolute paths; "${f}" is not`);
|
|
20
|
+
return [...new Set(files)];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const sum = (rows, k) => rows.reduce((n, r) => n + (r[k] ?? 0), 0);
|
|
24
|
+
|
|
25
|
+
export async function portfolioSummary({ files, defaultOffset = "+00:00", now = new Date(), makeClient = (env) => new SnapClient({ env }), report = dailyReport, exists = existsSync, readFile = readEnvFile }) {
|
|
26
|
+
const accounts = [];
|
|
27
|
+
for (const file of files) {
|
|
28
|
+
const label = basename(file);
|
|
29
|
+
try {
|
|
30
|
+
if (!exists(file)) throw new Error("settings file not found");
|
|
31
|
+
const env = readFile(file);
|
|
32
|
+
const missing = ["SNAP_CLIENT_ID", "SNAP_CLIENT_SECRET", "SNAP_REFRESH_TOKEN", "SNAP_AD_ACCOUNT_ID"].filter((k) => !env[k]);
|
|
33
|
+
if (missing.length) throw new Error(`missing ${missing.join(", ")}`);
|
|
34
|
+
const offset = env.SNAP_REPORT_UTC_OFFSET || defaultOffset;
|
|
35
|
+
const client = makeClient(env);
|
|
36
|
+
const acct = (await client.request("GET", `/adaccounts/${env.SNAP_AD_ACCOUNT_ID}`)).adaccounts?.[0]?.adaccount ?? {};
|
|
37
|
+
const end = localClock(now, offset).todayStart;
|
|
38
|
+
const start = shiftIso(end, -9 * 86_400_000);
|
|
39
|
+
const rep = await report(client, { entity: "adaccount", id: env.SNAP_AD_ACCOUNT_ID, start_time: start, end_time: end });
|
|
40
|
+
const rows = rep.rows.slice(-9);
|
|
41
|
+
const yesterday = rows.at(-1) ?? null;
|
|
42
|
+
const week = rows.slice(-7);
|
|
43
|
+
const spend = sum(week, "spend");
|
|
44
|
+
const value = sum(week, "purchase_value");
|
|
45
|
+
const purchases = sum(week, "purchases");
|
|
46
|
+
const judged = judgeDays(rows, { minSpend: 20 });
|
|
47
|
+
accounts.push({
|
|
48
|
+
settings_file: label,
|
|
49
|
+
account: acct.name ?? null,
|
|
50
|
+
status: acct.status ?? null,
|
|
51
|
+
currency: acct.currency ?? null,
|
|
52
|
+
read_only_server_setting: ["1", "true", "yes", "on"].includes(String(env.SNAP_READ_ONLY ?? "").toLowerCase()),
|
|
53
|
+
yesterday: yesterday ? { date: yesterday.date, spend: yesterday.spend, purchases: yesterday.purchases, roas: yesterday.roas } : null,
|
|
54
|
+
last_7_days: { spend: round(spend), purchases, purchase_value: round(value), roas: spend ? round(value / spend) : null, cpa: purchases ? round(spend / purchases) : null },
|
|
55
|
+
attention: judged.verdict === "NORMAL" || judged.verdict === "NOT_ENOUGH_DATA" || judged.verdict === "TOO_LITTLE_SPEND" ? null : { verdict: judged.verdict, findings: judged.findings.map((f) => `${f.code}: ${f.detail}`) },
|
|
56
|
+
...(acct.status && acct.status !== "ACTIVE" ? { attention_status: `Ad account status ${acct.status}` } : {}),
|
|
57
|
+
});
|
|
58
|
+
} catch (e) {
|
|
59
|
+
accounts.push({ settings_file: label, error: String(e.message).slice(0, 200) });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// Money is only added up within one currency.
|
|
63
|
+
const totals = {};
|
|
64
|
+
for (const a of accounts.filter((x) => x.currency && x.last_7_days)) {
|
|
65
|
+
const t = (totals[a.currency] ??= { accounts: 0, spend: 0, purchase_value: 0, purchases: 0 });
|
|
66
|
+
t.accounts += 1;
|
|
67
|
+
t.spend += a.last_7_days.spend;
|
|
68
|
+
t.purchase_value += a.last_7_days.purchase_value;
|
|
69
|
+
t.purchases += a.last_7_days.purchases;
|
|
70
|
+
}
|
|
71
|
+
for (const t of Object.values(totals)) {
|
|
72
|
+
t.spend = round(t.spend);
|
|
73
|
+
t.purchase_value = round(t.purchase_value);
|
|
74
|
+
t.roas = t.spend ? round(t.purchase_value / t.spend) : null;
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
accounts,
|
|
78
|
+
last_7_days_totals_by_currency: totals,
|
|
79
|
+
needs_attention: accounts.filter((a) => a.attention || a.error || a.attention_status).map((a) => a.account ?? a.settings_file),
|
|
80
|
+
note: "Last 7 full local days per account, Snap-attributed purchases. Currencies are never mixed. Each account was read with its own credentials; nothing was changed.",
|
|
81
|
+
};
|
|
82
|
+
}
|
package/src/setup.js
CHANGED
|
@@ -10,6 +10,7 @@ import { envFile, ROOT, setEnvValue, dataDir } from "./env.js";
|
|
|
10
10
|
import { secretProblems } from "./clipboard.js";
|
|
11
11
|
import { authorizeUrl, DEFAULT_REDIRECT, exchangeCode, extractCode, listAdAccounts, looksLikeClientId, newState } from "./oauth.js";
|
|
12
12
|
import { SnapClient } from "./snap.js";
|
|
13
|
+
import { brokerUrlFrom, startBrokerLogin } from "./broker.js";
|
|
13
14
|
import { init } from "./init.js";
|
|
14
15
|
|
|
15
16
|
const readSettings = (file) => {
|
|
@@ -98,7 +99,7 @@ async function askUntil(io, question, check) {
|
|
|
98
99
|
throw new Error("Too many invalid answers. Run setup again when you have the details.");
|
|
99
100
|
}
|
|
100
101
|
|
|
101
|
-
export async function runSetup({ io, file = envFile(), fetchImpl = fetch, open = openInBrowser, exec = execFileSync, claudeAvailable = hasClaude, root = ROOT } = {}) {
|
|
102
|
+
export async function runSetup({ io, file = envFile(), fetchImpl = fetch, open = openInBrowser, exec = execFileSync, claudeAvailable = hasClaude, root = ROOT, broker, startLogin = startBrokerLogin } = {}) {
|
|
102
103
|
const say = io.print;
|
|
103
104
|
const created = init(file).created;
|
|
104
105
|
let cur = readSettings(file);
|
|
@@ -108,57 +109,87 @@ export async function runSetup({ io, file = envFile(), fetchImpl = fetch, open =
|
|
|
108
109
|
say("Nothing here can change your ads. It only connects the account and saves settings on this computer.");
|
|
109
110
|
say("");
|
|
110
111
|
|
|
111
|
-
//
|
|
112
|
-
|
|
113
|
-
say(" 1. Open https://business.snapchat.com and go to Business Details > OAuth Apps > + OAuth App.");
|
|
114
|
-
say(` 2. Any app name. Redirect URI: ${DEFAULT_REDIRECT}`);
|
|
115
|
-
say(" 3. Create it. Copy the Client ID, and the Client Secret (shown only once).");
|
|
116
|
-
say("");
|
|
117
|
-
const keepId = looksLikeClientId(cur.SNAP_CLIENT_ID ?? "");
|
|
118
|
-
const idAnswer = await askUntil(io, keepId ? "Client ID (Enter keeps the saved one): " : "Client ID: ", (a) => (keepId && !a) || looksLikeClientId(a) ? null : "That is not a Client ID. It looks like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.");
|
|
119
|
-
const clientId = idAnswer || cur.SNAP_CLIENT_ID;
|
|
120
|
-
if (clientId !== cur.SNAP_CLIENT_ID) setEnvValue("SNAP_CLIENT_ID", clientId, file);
|
|
121
|
-
|
|
122
|
-
const keepSecret = Boolean(cur.SNAP_CLIENT_SECRET) && !secretProblems(cur.SNAP_CLIENT_SECRET).length && clientId === cur.SNAP_CLIENT_ID;
|
|
112
|
+
// The shared login: no OAuth app to create. Offered only on a fresh settings file (own app credentials are never replaced here).
|
|
113
|
+
let clientId = null;
|
|
123
114
|
let secret = null;
|
|
124
|
-
for (let i = 0; i < 5 && secret === null; i++) {
|
|
125
|
-
const a = await io.askSecret(keepSecret ? "Client Secret (hidden; Enter keeps the saved one): " : "Client Secret (hidden while you type or paste): ");
|
|
126
|
-
if (!a && keepSecret) secret = cur.SNAP_CLIENT_SECRET;
|
|
127
|
-
else if (secretProblems(a).length) say(` That does not look like a secret: ${secretProblems(a).join(", ")}. Copy it again.`);
|
|
128
|
-
else secret = a;
|
|
129
|
-
}
|
|
130
|
-
if (secret === null) throw new Error("No valid secret was entered.");
|
|
131
|
-
if (secret !== cur.SNAP_CLIENT_SECRET) setEnvValue("SNAP_CLIENT_SECRET", secret, file);
|
|
132
|
-
const redirectUri = cur.SNAP_REDIRECT_URI || DEFAULT_REDIRECT;
|
|
133
|
-
if (!cur.SNAP_REDIRECT_URI) setEnvValue("SNAP_REDIRECT_URI", redirectUri, file);
|
|
134
|
-
say(" Saved.");
|
|
135
|
-
say("");
|
|
136
|
-
|
|
137
|
-
// 2. Authorize
|
|
138
|
-
say("STEP 2 of 5: approve access in the browser");
|
|
139
115
|
let token = null;
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
116
|
+
let shared = false;
|
|
117
|
+
const brokerUrl = broker === undefined ? brokerUrlFrom(process.env) : broker;
|
|
118
|
+
if (brokerUrl && !cur.SNAP_CLIENT_SECRET) {
|
|
119
|
+
say("There are two ways to connect:");
|
|
120
|
+
say(" 1. Shared login (easiest): just log in with Snapchat. No OAuth app to create.");
|
|
121
|
+
say(" 2. Your own Snapchat OAuth app (about 5 minutes).");
|
|
122
|
+
say(` The shared login uses ${brokerUrl}, which only passes your login along and stores nothing. See PRIVACY.md.`);
|
|
123
|
+
const choice = await askUntil(io, "Choose 1 or 2 [1]: ", (a) => (!a || a === "1" || a === "2" ? null : "Type 1 or 2."));
|
|
124
|
+
shared = choice !== "2";
|
|
125
|
+
}
|
|
126
|
+
if (shared) {
|
|
127
|
+
say("");
|
|
128
|
+
say("STEPS 1 and 2 of 5: log in with Snapchat (no OAuth app needed)");
|
|
129
|
+
const login = await startLogin({ brokerUrl });
|
|
130
|
+
const opened = open(login.url);
|
|
144
131
|
say(opened ? " Your browser opened. Log in to Snapchat and click Continue." : " Open this link, log in to Snapchat and click Continue:");
|
|
145
|
-
if (!opened) say(` ${url}`);
|
|
146
|
-
say("
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
132
|
+
if (!opened) say(` ${login.url}`);
|
|
133
|
+
say(" Waiting for you to finish in the browser (up to 5 minutes)...");
|
|
134
|
+
token = await login.done;
|
|
135
|
+
setEnvValue("SNAP_BROKER_URL", brokerUrl, file);
|
|
136
|
+
setEnvValue("SNAP_REFRESH_TOKEN", token, file);
|
|
137
|
+
say(" Connected. Access saved on this computer only.");
|
|
138
|
+
say("");
|
|
139
|
+
} else {
|
|
140
|
+
// 1. OAuth app
|
|
141
|
+
say("STEP 1 of 5: your Snapchat OAuth app (one time, about 3 minutes)");
|
|
142
|
+
say(" 1. Open https://business.snapchat.com and go to Business Details > OAuth Apps > + OAuth App.");
|
|
143
|
+
say(` 2. Any app name. Redirect URI: ${DEFAULT_REDIRECT}`);
|
|
144
|
+
say(" 3. Create it. Copy the Client ID, and the Client Secret (shown only once).");
|
|
145
|
+
say("");
|
|
146
|
+
const keepId = looksLikeClientId(cur.SNAP_CLIENT_ID ?? "");
|
|
147
|
+
const idAnswer = await askUntil(io, keepId ? "Client ID (Enter keeps the saved one): " : "Client ID: ", (a) => (keepId && !a) || looksLikeClientId(a) ? null : "That is not a Client ID. It looks like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.");
|
|
148
|
+
clientId = idAnswer || cur.SNAP_CLIENT_ID;
|
|
149
|
+
if (clientId !== cur.SNAP_CLIENT_ID) setEnvValue("SNAP_CLIENT_ID", clientId, file);
|
|
150
|
+
|
|
151
|
+
const keepSecret = Boolean(cur.SNAP_CLIENT_SECRET) && !secretProblems(cur.SNAP_CLIENT_SECRET).length && clientId === cur.SNAP_CLIENT_ID;
|
|
152
|
+
secret = null;
|
|
153
|
+
for (let i = 0; i < 5 && secret === null; i++) {
|
|
154
|
+
const a = await io.askSecret(keepSecret ? "Client Secret (hidden; Enter keeps the saved one): " : "Client Secret (hidden while you type or paste): ");
|
|
155
|
+
if (!a && keepSecret) secret = cur.SNAP_CLIENT_SECRET;
|
|
156
|
+
else if (secretProblems(a).length) say(` That does not look like a secret: ${secretProblems(a).join(", ")}. Copy it again.`);
|
|
157
|
+
else secret = a;
|
|
152
158
|
}
|
|
159
|
+
if (secret === null) throw new Error("No valid secret was entered.");
|
|
160
|
+
if (secret !== cur.SNAP_CLIENT_SECRET) setEnvValue("SNAP_CLIENT_SECRET", secret, file);
|
|
161
|
+
const redirectUri = cur.SNAP_REDIRECT_URI || DEFAULT_REDIRECT;
|
|
162
|
+
if (!cur.SNAP_REDIRECT_URI) setEnvValue("SNAP_REDIRECT_URI", redirectUri, file);
|
|
163
|
+
say(" Saved.");
|
|
164
|
+
say("");
|
|
165
|
+
|
|
166
|
+
// 2. Authorize
|
|
167
|
+
say("STEP 2 of 5: approve access in the browser");
|
|
168
|
+
token = null;
|
|
169
|
+
for (let i = 0; i < 3 && !token; i++) {
|
|
170
|
+
const state = newState();
|
|
171
|
+
const url = authorizeUrl({ clientId, redirectUri, state });
|
|
172
|
+
const opened = open(url);
|
|
173
|
+
say(opened ? " Your browser opened. Log in to Snapchat and click Continue." : " Open this link, log in to Snapchat and click Continue:");
|
|
174
|
+
if (!opened) say(` ${url}`);
|
|
175
|
+
say(" The browser then shows an error page ('can't connect' is normal). Copy the whole address from its address bar.");
|
|
176
|
+
const pasted = await io.ask("Paste that address here: ");
|
|
177
|
+
try {
|
|
178
|
+
token = await exchangeCode({ clientId, clientSecret: secret, redirectUri, code: extractCode(pasted, state), fetchImpl });
|
|
179
|
+
} catch (e) {
|
|
180
|
+
say(` ${e.message}`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (!token) throw new Error("Could not connect. Check the Redirect URI on the OAuth app is exactly " + redirectUri + ", then run setup again.");
|
|
184
|
+
setEnvValue("SNAP_REFRESH_TOKEN", token, file);
|
|
185
|
+
say(" Connected. Access saved on this computer only.");
|
|
186
|
+
say("");
|
|
187
|
+
|
|
153
188
|
}
|
|
154
|
-
if (!token) throw new Error("Could not connect. Check the Redirect URI on the OAuth app is exactly " + redirectUri + ", then run setup again.");
|
|
155
|
-
setEnvValue("SNAP_REFRESH_TOKEN", token, file);
|
|
156
|
-
say(" Connected. Access saved on this computer only.");
|
|
157
|
-
say("");
|
|
158
189
|
|
|
159
190
|
// 3. Ad account
|
|
160
191
|
say("STEP 3 of 5: choose the ad account");
|
|
161
|
-
const client = new SnapClient({ env: { SNAP_CLIENT_ID: clientId, SNAP_CLIENT_SECRET: secret, SNAP_REFRESH_TOKEN: token }, fetchImpl });
|
|
192
|
+
const client = new SnapClient({ env: shared ? { SNAP_REFRESH_TOKEN: token, SNAP_BROKER_URL: brokerUrl } : { SNAP_CLIENT_ID: clientId, SNAP_CLIENT_SECRET: secret, SNAP_REFRESH_TOKEN: token }, fetchImpl });
|
|
162
193
|
const me = (await client.request("GET", "/me")).me ?? {};
|
|
163
194
|
say(` Logged in as ${me.display_name ?? me.email ?? "your Snapchat login"}.`);
|
|
164
195
|
const accounts = await listAdAccounts(client);
|
package/src/snap.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Thin client for the Snapchat Marketing API (https://adsapi.snapchat.com/v1).
|
|
2
|
+
import { brokerUrlFrom, refreshViaBroker } from "./broker.js";
|
|
2
3
|
const API = "https://adsapi.snapchat.com/v1";
|
|
3
4
|
const TOKEN_URL = "https://accounts.snapchat.com/login/oauth2/access_token";
|
|
4
5
|
const TR = "https://tr.snapchat.com"; // Conversions API test-event tools
|
|
@@ -195,8 +196,18 @@ export class SnapClient {
|
|
|
195
196
|
if (this.token && Date.now() < this.tokenExpiry - 60_000) return this.token;
|
|
196
197
|
this.beforeToken?.();
|
|
197
198
|
const { SNAP_CLIENT_ID, SNAP_CLIENT_SECRET, SNAP_REFRESH_TOKEN } = this.env;
|
|
199
|
+
// Shared login: no app secret on this computer; the login service holds it and swaps the refresh token.
|
|
200
|
+
if (SNAP_REFRESH_TOKEN && !SNAP_CLIENT_SECRET) {
|
|
201
|
+
const broker = brokerUrlFrom(this.env);
|
|
202
|
+
if (broker) {
|
|
203
|
+
const data = await refreshViaBroker(broker, SNAP_REFRESH_TOKEN, this.fetch);
|
|
204
|
+
this.token = data.access_token;
|
|
205
|
+
this.tokenExpiry = Date.now() + (data.expires_in ?? 1800) * 1000;
|
|
206
|
+
return this.token;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
198
209
|
if (!SNAP_CLIENT_ID || !SNAP_CLIENT_SECRET || !SNAP_REFRESH_TOKEN) {
|
|
199
|
-
throw new Error("Missing SNAP_CLIENT_ID, SNAP_CLIENT_SECRET or SNAP_REFRESH_TOKEN.
|
|
210
|
+
throw new Error("Missing SNAP_CLIENT_ID, SNAP_CLIENT_SECRET or SNAP_REFRESH_TOKEN. Run `npx -y ads-mcp-for-snapchat setup` (see .env.example).");
|
|
200
211
|
}
|
|
201
212
|
const res = await this.fetchRetry(TOKEN_URL, {
|
|
202
213
|
method: "POST",
|
package/src/tools.js
CHANGED
|
@@ -4,7 +4,7 @@ import { z } from "zod";
|
|
|
4
4
|
import { SnapClient } from "./snap.js";
|
|
5
5
|
import { envFile, setEnvValue } from "./env.js";
|
|
6
6
|
import { authorizeUrl, DEFAULT_REDIRECT, exchangeCode, extractCode, listAdAccounts, newState } from "./oauth.js";
|
|
7
|
-
import { executeChange, LOG_FILE, planBid, planBudget, planExcludeSegments, planRename, planSchedule, planStatus, planTargeting, planUndo, prepareChange, previewOf, readLog, undoableEntries } from "./changes.js";
|
|
7
|
+
import { executeChange, LOG_FILE, BID_STRATEGIES, planBid, planBidStrategy, planBudget, planExcludeSegments, planRename, planSchedule, planStatus, planTargeting, planUndo, prepareChange, previewOf, readLog, undoableEntries } from "./changes.js";
|
|
8
8
|
import { executeBulkEdit, plans, prepareBulkEdit } from "./bulk-edit.js";
|
|
9
9
|
import { runBatch, checkBatch } from "./influencer-batch.js";
|
|
10
10
|
import { createWithAutoStrip, planCloneCreative } from "./creative-tools.js";
|
|
@@ -15,12 +15,14 @@ import { breakdownReport, dailyReport, dimensionReport, DIMENSIONS, SWIPE_WINDOW
|
|
|
15
15
|
import { compareReport, 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
|
+
import { brokerUrlFrom, startBrokerLogin } from "./broker.js";
|
|
18
19
|
import { audienceInsights, buildTestEvent, capiStatus, capiTest, CAPI_TEST_EVENTS, competitorAds, GALLERY_COUNTRIES, INSIGHT_CATEGORIES } from "./intel.js";
|
|
19
20
|
import { anomalyCheck, blendedRoas, landingPageReport } from "./checks.js";
|
|
20
21
|
import { toolAllowed } from "./toolsets.js";
|
|
22
|
+
import { parsePortfolioFiles, portfolioSummary } from "./portfolio.js";
|
|
21
23
|
import { audienceHealth, billingCheck, feedStatus, funnelReport, unusedMedia } from "./hygiene.js";
|
|
22
24
|
import { budgetAdvice, creativeCompare, hourlyReport } from "./advice.js";
|
|
23
|
-
import { CAP_UNITS, planAdSchedule, planFrequencyCap } from "./controls.js";
|
|
25
|
+
import { CAP_UNITS, PLACEMENT_POSITIONS, planAdSchedule, planFrequencyCap, planPlacement } from "./controls.js";
|
|
24
26
|
import { adPreview, audienceSizeForSquad, audienceSizeForTargeting, pacingReport } from "./insights.js";
|
|
25
27
|
import { registerPrompts } from "./prompts.js";
|
|
26
28
|
import { buildLookalike, buildPixelAudience, PIXEL_EVENTS, listCatalogs, listPixels, listProductSets, listSegments, rawGet, targetingOptions, TARGETING_KINDS } from "./readers.js";
|
|
@@ -286,6 +288,7 @@ export function registerTools(server, client, env = process.env) {
|
|
|
286
288
|
// settings, never from the chat. The authorization code that passes through the chat is single-use, expires in minutes and
|
|
287
289
|
// is useless without the secret. The refresh token is saved to the settings file and never returned.
|
|
288
290
|
let pendingState = null;
|
|
291
|
+
let pendingShared = null; // a shared login in progress: { link, token, error }
|
|
289
292
|
server.registerTool(
|
|
290
293
|
"snap_connect",
|
|
291
294
|
{
|
|
@@ -297,11 +300,40 @@ export function registerTools(server, client, env = process.env) {
|
|
|
297
300
|
async ({ redirected_url, ad_account_id }) => {
|
|
298
301
|
try {
|
|
299
302
|
const e = client.env;
|
|
300
|
-
|
|
303
|
+
const file = envFile();
|
|
304
|
+
// The shared login: no Client ID or secret on this computer. The browser sends the sealed token to a listener this
|
|
305
|
+
// server opens on 127.0.0.1, so nothing has to be pasted into the chat.
|
|
306
|
+
const shared = !e.SNAP_CLIENT_SECRET ? brokerUrlFrom(e) : null;
|
|
307
|
+
if (shared && !ad_account_id) {
|
|
308
|
+
if (redirected_url) throw new Error("This connection uses the shared login: no address needs to be pasted. Open the link, log in, then call snap_connect again with no arguments.");
|
|
309
|
+
if (pendingShared?.token) {
|
|
310
|
+
const token = pendingShared.token;
|
|
311
|
+
pendingShared = null;
|
|
312
|
+
setEnvValue("SNAP_BROKER_URL", shared, file);
|
|
313
|
+
setEnvValue("SNAP_REFRESH_TOKEN", token, file);
|
|
314
|
+
e.SNAP_BROKER_URL = shared;
|
|
315
|
+
e.SNAP_REFRESH_TOKEN = token;
|
|
316
|
+
client.token = null;
|
|
317
|
+
client.tokenExpiry = 0;
|
|
318
|
+
const accounts = await listAdAccounts(client);
|
|
319
|
+
return asResult({ step: 2, connected: true, saved_to: file, ad_accounts: accounts, next: accounts.length ? "Ask the person which ad account to use, then call snap_connect with its ad_account_id." : "This login sees no ad account. The account admin must add it first." });
|
|
320
|
+
}
|
|
321
|
+
if (pendingShared?.error) {
|
|
322
|
+
const why = pendingShared.error;
|
|
323
|
+
pendingShared = null;
|
|
324
|
+
throw new Error(`The login did not finish: ${why}. Call snap_connect again to get a new link.`);
|
|
325
|
+
}
|
|
326
|
+
if (pendingShared) return asResult({ step: 1, waiting: true, link: pendingShared.link, tell_the_person: "Still waiting. Open the link, log in to Snapchat and click Continue. Then say so and call snap_connect again." });
|
|
327
|
+
const login = await startBrokerLogin({ brokerUrl: shared });
|
|
328
|
+
const entry = { link: login.url, token: null, error: null };
|
|
329
|
+
pendingShared = entry;
|
|
330
|
+
login.done.then((t) => (entry.token = t), (err) => (entry.error = String(err?.message ?? err)));
|
|
331
|
+
return asResult({ step: 1, link: login.url, tell_the_person: "Open this link, log in to Snapchat and click Continue. The browser then says Connected. Tell me when that is done and I will call snap_connect again." });
|
|
332
|
+
}
|
|
333
|
+
if (!shared && (!e.SNAP_CLIENT_ID || !e.SNAP_CLIENT_SECRET)) {
|
|
301
334
|
throw new Error("The Client ID and Client Secret are not set. Enter them in the extension's settings (Claude Desktop: Settings > Extensions > Ads MCP for Snapchat), or run: npx -y ads-mcp-for-snapchat setup");
|
|
302
335
|
}
|
|
303
336
|
const redirectUri = e.SNAP_REDIRECT_URI || DEFAULT_REDIRECT;
|
|
304
|
-
const file = envFile();
|
|
305
337
|
if (ad_account_id) {
|
|
306
338
|
const accounts = await listAdAccounts(client);
|
|
307
339
|
const chosen = accounts.find((a) => a.id === ad_account_id);
|
|
@@ -811,6 +843,19 @@ export function registerTools(server, client, env = process.env) {
|
|
|
811
843
|
async ({ organization_id }) => feedStatus(client, { organizationId: organization_id ?? (await accountOrg()) }),
|
|
812
844
|
);
|
|
813
845
|
|
|
846
|
+
read(
|
|
847
|
+
"snap_portfolio_summary",
|
|
848
|
+
{
|
|
849
|
+
description: "All your ad accounts side by side (read-only): for each account yesterday and the last 7 days (spend, purchases, ROAS, cost per purchase), what needs attention, and totals per currency. It reads the accounts whose settings files the server's owner listed in SNAP_PORTFOLIO_FILES; the AI app cannot choose files. Only account-level numbers are returned.",
|
|
850
|
+
shape: {},
|
|
851
|
+
},
|
|
852
|
+
async () => {
|
|
853
|
+
const files = parsePortfolioFiles(env.SNAP_PORTFOLIO_FILES);
|
|
854
|
+
if (!files.length) return { configured: false, how_to: "Set SNAP_PORTFOLIO_FILES in this server's settings to the absolute paths of the settings files of your accounts, separated by commas (for example /Users/me/ads/.env,/Users/me/ads/.env.account2), then restart. This server's own file may be included." };
|
|
855
|
+
return portfolioSummary({ files, defaultOffset: policy.reportUtcOffset });
|
|
856
|
+
},
|
|
857
|
+
);
|
|
858
|
+
|
|
814
859
|
registerPrompts(server);
|
|
815
860
|
|
|
816
861
|
read(
|
|
@@ -1276,6 +1321,25 @@ export function registerTools(server, client, env = process.env) {
|
|
|
1276
1321
|
({ adsquad_id, schedule, always }) => change("adsquad", adsquad_id, (cur) => planAdSchedule(cur, { schedule, always })),
|
|
1277
1322
|
);
|
|
1278
1323
|
|
|
1324
|
+
write(
|
|
1325
|
+
"snap_set_bid_strategy",
|
|
1326
|
+
{
|
|
1327
|
+
description: "Switch an ad squad between max bid (LOWEST_COST_WITH_MAX_BID) and target cost (TARGET_COST), with the bid for the new strategy. An ad squad on auto-bid may be switched to one of these (it adds a bid cap). Switching TO auto-bid is not offered because it would remove the bid cap. The bid follows the same limits as snap_set_bid (absolute SNAP_MAX_BID, +50% per step and per 24 hours). Previews unless confirm=true.",
|
|
1328
|
+
shape: { adsquad_id: id(), strategy: z.enum(BID_STRATEGIES), bid: z.number().positive().describe("Account currency: the max bid, or the target cost") },
|
|
1329
|
+
destructive: true,
|
|
1330
|
+
},
|
|
1331
|
+
({ adsquad_id, strategy, bid }) => change("adsquad", adsquad_id, (cur) => planBidStrategy(cur, { strategy, bid }, policy, { history })),
|
|
1332
|
+
);
|
|
1333
|
+
|
|
1334
|
+
write(
|
|
1335
|
+
"snap_set_placement",
|
|
1336
|
+
{
|
|
1337
|
+
description: `Choose where on Snapchat an ad squad's ads may appear: automatic (everywhere) or custom positions (${PLACEMENT_POSITIONS.join(", ")}; CHAT_FEED must come with INTERSTITIAL_CONTENT or INTERSTITIAL_USER). Fewer placements usually mean less reach and a higher cost. Refused on ad squads that use content inclusion or exclusion lists. Undo works when a placement was set before. Previews unless confirm=true.`,
|
|
1338
|
+
shape: { adsquad_id: id(), mode: z.enum(["automatic", "custom"]), positions: z.array(z.enum(PLACEMENT_POSITIONS)).max(7).optional() },
|
|
1339
|
+
},
|
|
1340
|
+
({ adsquad_id, mode, positions }) => change("adsquad", adsquad_id, (cur) => planPlacement(cur, { mode, positions })),
|
|
1341
|
+
);
|
|
1342
|
+
|
|
1279
1343
|
write(
|
|
1280
1344
|
"snap_copy_adsquad",
|
|
1281
1345
|
{
|
package/src/toolsets.js
CHANGED
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
export const TOOLSETS = {
|
|
5
5
|
setup: ["snap_ping", "snap_connect", "snap_change_log"],
|
|
6
6
|
read: ["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
|
-
reports: ["snap_get_stats", "snap_report", "snap_report_daily", "snap_report_audience", "snap_report_compare", "snap_report_hourly", "snap_report_async_start", "snap_report_async_status", "snap_report_async_download", "snap_funnel", "snap_blended_roas", "snap_spend_pacing", "snap_creative_compare"],
|
|
7
|
+
reports: ["snap_get_stats", "snap_report", "snap_report_daily", "snap_report_audience", "snap_report_compare", "snap_report_hourly", "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
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"],
|
|
9
|
-
changes: ["snap_set_status", "snap_set_status_bulk", "snap_set_daily_budget", "snap_set_bid", "snap_set_targeting", "snap_set_schedule", "snap_set_frequency_cap", "snap_set_ad_schedule", "snap_exclude_segments", "snap_rename", "snap_bulk_exclude_segments", "snap_bulk_set_budget", "snap_bulk_set_schedule", "snap_bulk_rename", "snap_undo", "snap_delete"],
|
|
9
|
+
changes: ["snap_set_status", "snap_set_status_bulk", "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_bulk_exclude_segments", "snap_bulk_set_budget", "snap_bulk_set_schedule", "snap_bulk_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
|
};
|
|
12
12
|
|