ads-mcp-for-snapchat 0.9.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 +1 -0
- package/CHANGELOG.md +15 -2
- package/README.md +5 -1
- package/broker/ASK-SNAP.md +26 -0
- package/broker/worker.js +1 -1
- package/package.json +4 -4
- package/src/advice.js +16 -4
- package/src/checks.js +56 -15
- package/src/cli.js +11 -0
- package/src/hygiene.js +21 -4
- package/src/index.js +1 -1
- package/src/intel.js +7 -1
- package/src/report.js +75 -6
- package/src/snap.js +17 -7
- package/src/verify.js +102 -0
package/.env.example
CHANGED
|
@@ -17,6 +17,7 @@ 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)
|
|
20
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)
|
|
21
22
|
# Optional: SNAP_HOME=/some/folder (where settings, the change log and exports live; default ~/.ads-mcp-for-snapchat for an npm install)
|
|
22
23
|
# Optional: SNAP_PORTFOLIO_FILES=/abs/path/.env,/abs/path/.env.account2 (accounts shown side by side by snap_portfolio_summary)
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
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
|
+
|
|
3
16
|
## 0.9.0 (2026-11-15)
|
|
4
17
|
|
|
5
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.
|
|
@@ -69,7 +82,7 @@ Everything below is built from Snap's documentation and mocked tests and is not
|
|
|
69
82
|
## 0.4.1 (2026-11-14)
|
|
70
83
|
|
|
71
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.
|
|
72
|
-
- Package and registry links point to the repository's real name, `Usame794/
|
|
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).
|
|
73
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`.
|
|
74
87
|
|
|
75
88
|
## 0.4.0 (2026-11-14)
|
|
@@ -77,7 +90,7 @@ Everything below is built from Snap's documentation and mocked tests and is not
|
|
|
77
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.
|
|
78
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.
|
|
79
92
|
- `server.json` for the official MCP Registry (`io.github.Usame794/ads-mcp-for-snapchat`).
|
|
80
|
-
- Repository links point to `Usame794/
|
|
93
|
+
- Repository links point to `Usame794/snapchat-ads-mcp`.
|
|
81
94
|
- Verified live on a real account: a COLLECTION ad (paused).
|
|
82
95
|
|
|
83
96
|
## 0.3.2 (2026-11-14)
|
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
|
+
## 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
|
+
|
|
29
32
|
## Easiest: log in with Snapchat (no OAuth app)
|
|
30
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.
|
|
31
34
|
|
|
@@ -33,7 +36,7 @@ When a login service is available (see `broker/README.md` and `PRIVACY.md`), you
|
|
|
33
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).
|
|
34
37
|
|
|
35
38
|
**Claude Desktop (no terminal):**
|
|
36
|
-
1. Download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/
|
|
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.
|
|
37
40
|
2. Enter the Client ID and Client Secret, your highest daily budget and (optional) your main country. Leave **Read-only** on for now.
|
|
38
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.
|
|
39
42
|
4. Quit and reopen Claude Desktop. Ask: "call snap_ping".
|
|
@@ -86,6 +89,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
86
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 |
|
|
87
90
|
| `SNAP_ACCOUNT_CURRENCY` | not set | If set (e.g. `USD`), writes are refused unless the ad account uses that currency |
|
|
88
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`. |
|
|
89
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. |
|
|
90
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. |
|
|
91
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. |
|
|
@@ -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]
|
package/broker/worker.js
CHANGED
|
@@ -128,7 +128,7 @@ async function refresh(request, env, fetchImpl) {
|
|
|
128
128
|
}
|
|
129
129
|
|
|
130
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/
|
|
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
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
133
|
|
|
134
134
|
const PRIVACY = `<h1>Privacy</h1>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ads-mcp-for-snapchat",
|
|
3
|
-
"version": "0.9.
|
|
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
6
|
"adsMcpBroker": "",
|
|
@@ -36,12 +36,12 @@
|
|
|
36
36
|
],
|
|
37
37
|
"repository": {
|
|
38
38
|
"type": "git",
|
|
39
|
-
"url": "git+https://github.com/Usame794/
|
|
39
|
+
"url": "git+https://github.com/Usame794/snapchat-ads-mcp.git"
|
|
40
40
|
},
|
|
41
41
|
"bugs": {
|
|
42
|
-
"url": "https://github.com/Usame794/
|
|
42
|
+
"url": "https://github.com/Usame794/snapchat-ads-mcp/issues"
|
|
43
43
|
},
|
|
44
|
-
"homepage": "https://github.com/Usame794/
|
|
44
|
+
"homepage": "https://github.com/Usame794/snapchat-ads-mcp#readme",
|
|
45
45
|
"files": [
|
|
46
46
|
"src",
|
|
47
47
|
"scripts/save-secret.js",
|
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
|
|
52
|
-
|
|
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)),
|
package/src/checks.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// reported revenue does the store confirm. None of them changes anything in the ad account.
|
|
3
3
|
import { lookup as dnsLookup } from "node:dns/promises";
|
|
4
4
|
import { isIP } from "node:net";
|
|
5
|
-
import { dailyReport } from "./report.js";
|
|
5
|
+
import { accountTotals, dailyReport, totalsOf } from "./report.js";
|
|
6
6
|
import { localClock } from "./insights.js";
|
|
7
7
|
import { shiftIso } from "./fatigue.js";
|
|
8
8
|
|
|
@@ -98,15 +98,43 @@ async function pool(items, size, fn) {
|
|
|
98
98
|
return out;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const
|
|
101
|
+
// Only what can deliver is read: ACTIVE campaigns, their ACTIVE ad squads and those squads' ACTIVE ads (reading every ad of a big
|
|
102
|
+
// account took minutes on a live account), then only the creatives those ads use. A time limit keeps the answer prompt; if it is
|
|
103
|
+
// reached the answer says how much was covered.
|
|
104
|
+
export async function landingPageReport(client, { adAccountId, requiredParams = [], maxUrls = 100, check = checkUrl, checkOptions = {}, timeBudgetMs = 40_000, now = () => Date.now() }) {
|
|
105
|
+
const started = now();
|
|
106
|
+
const timeUp = () => now() - started > timeBudgetMs;
|
|
107
|
+
const campaigns = await client.listPaged(`/adaccounts/${adAccountId}/campaigns`, "campaign");
|
|
108
|
+
const activeCampaigns = campaigns.items.filter((c) => c.status === "ACTIVE");
|
|
109
|
+
const squads = [];
|
|
110
|
+
await pool(activeCampaigns, 5, async (c) => {
|
|
111
|
+
if (timeUp()) return;
|
|
112
|
+
for (const s of await client.listChildren("campaign", c.id, "adsquad")) if (s.status === "ACTIVE") squads.push({ ...s, campaign_name: c.name });
|
|
113
|
+
});
|
|
114
|
+
const active = [];
|
|
115
|
+
await pool(squads, 5, async (sq) => {
|
|
116
|
+
if (timeUp()) return;
|
|
117
|
+
for (const ad of await client.listChildren("adsquad", sq.id, "ad")) if (ad.status === "ACTIVE") active.push(ad);
|
|
118
|
+
});
|
|
119
|
+
const creativeIds = [...new Set(active.map((a) => a.creative_id).filter(Boolean))];
|
|
120
|
+
const byCreative = new Map();
|
|
121
|
+
await pool(creativeIds, 8, async (id) => {
|
|
122
|
+
if (timeUp()) return;
|
|
123
|
+
try {
|
|
124
|
+
byCreative.set(id, await client.getEntity("creative", id));
|
|
125
|
+
} catch {
|
|
126
|
+
byCreative.set(id, null);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
106
129
|
const byUrl = new Map();
|
|
107
130
|
let withoutLink = 0;
|
|
131
|
+
let creativesUnread = 0;
|
|
108
132
|
for (const ad of active) {
|
|
109
|
-
|
|
133
|
+
if (ad.creative_id && !byCreative.has(ad.creative_id)) {
|
|
134
|
+
creativesUnread += 1;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const urls = urlsOfCreative(byCreative.get(ad.creative_id) ?? undefined);
|
|
110
138
|
if (!urls.length) withoutLink += 1;
|
|
111
139
|
for (const url of urls) {
|
|
112
140
|
if (!byUrl.has(url)) byUrl.set(url, []);
|
|
@@ -115,24 +143,31 @@ export async function landingPageReport(client, { adAccountId, requiredParams =
|
|
|
115
143
|
}
|
|
116
144
|
const all = [...byUrl.keys()];
|
|
117
145
|
const toCheck = all.slice(0, maxUrls);
|
|
118
|
-
const results =
|
|
146
|
+
const results = [];
|
|
147
|
+
await pool(toCheck, 5, async (u) => {
|
|
148
|
+
results.push(timeUp() ? { url: u, verdict: "NOT_CHECKED", detail: "Out of time" } : await check(u, checkOptions));
|
|
149
|
+
});
|
|
119
150
|
const rows = results.map((r) => {
|
|
120
151
|
const missing = requiredParams.filter((p) => { try { return !new URL(r.url).searchParams.has(p); } catch { return true; } });
|
|
121
152
|
return { ...r, ads: byUrl.get(r.url), ...(r.final_url && !sameHost(r.url, r.final_url) ? { lands_on_other_site: new URL(r.final_url).hostname } : {}), ...(missing.length ? { missing_params: missing } : {}) };
|
|
122
153
|
});
|
|
123
|
-
const problems = rows.filter((r) => !["OK"].includes(r.verdict) || r.missing_params || r.lands_on_other_site);
|
|
154
|
+
const problems = rows.filter((r) => !["OK", "NOT_CHECKED"].includes(r.verdict) || r.missing_params || r.lands_on_other_site);
|
|
124
155
|
const counts = {};
|
|
125
156
|
for (const r of rows) counts[r.verdict] = (counts[r.verdict] ?? 0) + 1;
|
|
157
|
+
const outOfTime = timeUp();
|
|
126
158
|
return {
|
|
159
|
+
active_campaigns: activeCampaigns.length,
|
|
160
|
+
active_squads: squads.length,
|
|
127
161
|
active_ads: active.length,
|
|
128
162
|
ads_without_a_web_link: withoutLink,
|
|
129
|
-
links_checked: rows.length,
|
|
130
|
-
...(all.length > toCheck.length ? { links_not_checked: all.length - toCheck.length, warning: `Only the first ${maxUrls} distinct links were
|
|
131
|
-
...(
|
|
163
|
+
links_checked: rows.filter((r) => r.verdict !== "NOT_CHECKED").length,
|
|
164
|
+
...(all.length > toCheck.length ? { links_not_checked: all.length - toCheck.length, warning: `Only the first ${maxUrls} distinct links were looked at.` } : {}),
|
|
165
|
+
...(outOfTime || creativesUnread || counts.NOT_CHECKED ? { partial: true, partial_reason: `Stopped after about ${Math.round(timeBudgetMs / 1000)} seconds: ${counts.NOT_CHECKED ?? 0} link(s) and ${creativesUnread} ad(s) were not looked at. Run it again, or lower max_links.` } : {}),
|
|
166
|
+
...(campaigns.complete ? {} : { warning_incomplete: "The campaign list was INCOMPLETE; some ads were not looked at." }),
|
|
132
167
|
by_verdict: counts,
|
|
133
168
|
problems,
|
|
134
|
-
all_links_ok: !problems.length,
|
|
135
|
-
not_checked: "Only whether the page opens is checked. A page that opens but shows 'out of stock' or an error message inside is not detected. Catalog, Story, Snap-only and app creatives have no web link to check.",
|
|
169
|
+
all_links_ok: !problems.length && !outOfTime,
|
|
170
|
+
not_checked: "Only whether the page opens is checked. A page that opens but shows 'out of stock' or an error message inside is not detected. Catalog, Story, Snap-only and app creatives have no web link to check. Only ACTIVE ads of ACTIVE ad squads are read.",
|
|
136
171
|
};
|
|
137
172
|
}
|
|
138
173
|
|
|
@@ -189,7 +224,13 @@ export async function anomalyCheck(client, { adAccountId, offset = "+00:00", bas
|
|
|
189
224
|
|
|
190
225
|
// ---------- Blended ROAS ----------
|
|
191
226
|
|
|
192
|
-
|
|
227
|
+
// Account totals for a window, in the same shape dailyReport gives (built from the campaign breakdown: see report.js).
|
|
228
|
+
async function accountReport(client, { id, start_time, end_time }) {
|
|
229
|
+
const { stats, incomplete } = await accountTotals(client, id, { start_time, end_time, fields: "spend,conversion_purchases,conversion_purchases_value" });
|
|
230
|
+
return { ...totalsOf([stats]), ...(incomplete ? { warning: "Snap returned more pages than were read; the totals are a lower bound." } : {}) };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export async function blendedRoas(client, { adAccountId, offset = "+00:00", storeRevenue, storeOrders, days = 7, startDate, endDate, now = new Date(), report = accountReport }) {
|
|
193
234
|
let start;
|
|
194
235
|
let end;
|
|
195
236
|
if (startDate || endDate) {
|
package/src/cli.js
CHANGED
|
@@ -26,6 +26,7 @@ Usage: npx ads-mcp-for-snapchat [command]
|
|
|
26
26
|
auth CODE exchange the authorization code for a refresh token
|
|
27
27
|
check test the connection and the ad account (read-only)
|
|
28
28
|
weekly-report write the weekly report to the exports folder
|
|
29
|
+
verify run every read-only tool on your account and show what works (changes nothing)
|
|
29
30
|
help show this text
|
|
30
31
|
|
|
31
32
|
Settings file: SNAP_ENV_FILE if set, otherwise .env in ~/.ads-mcp-for-snapchat (npm install) or the project folder (git clone).`;
|
|
@@ -37,6 +38,16 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
37
38
|
if (!command || command === "serve") return import("./index.js");
|
|
38
39
|
if (command === "help" || command === "--help" || command === "-h") return console.log(HELP);
|
|
39
40
|
if (command === "where") return console.log(envFile());
|
|
41
|
+
if (command === "verify") {
|
|
42
|
+
const { loadEnv } = await import("./env.js");
|
|
43
|
+
const { SnapClient } = await import("./snap.js");
|
|
44
|
+
const { runVerify } = await import("./verify.js");
|
|
45
|
+
loadEnv();
|
|
46
|
+
console.log("Checking every read-only tool on your ad account (nothing is changed)...\n");
|
|
47
|
+
const { failed } = await runVerify({ client: new SnapClient() });
|
|
48
|
+
process.exitCode = failed ? 1 : 0;
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
40
51
|
if (command === "setup") return (await import("./setup.js")).setupCommand(rest);
|
|
41
52
|
if (command === "init") {
|
|
42
53
|
const r = init();
|
package/src/hygiene.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Account hygiene, all read-only: billing, unused media, audience health, the conversion funnel, and catalog feed status.
|
|
2
2
|
// Nothing here changes the ad account.
|
|
3
3
|
import { localClock } from "./insights.js";
|
|
4
|
+
import { accountTotals } from "./report.js";
|
|
4
5
|
import { shiftIso } from "./fatigue.js";
|
|
5
6
|
|
|
6
7
|
const round = (n, d = 2) => Math.round(n * 10 ** d) / 10 ** d;
|
|
@@ -177,8 +178,13 @@ export async function funnelReport(client, { adAccountId, entity = "adaccount",
|
|
|
177
178
|
if (!Number.isInteger(days) || days < 1 || days > 31) throw new Error("days must be a whole number from 1 to 31");
|
|
178
179
|
const end = localClock(now, offset).todayStart;
|
|
179
180
|
const start = shiftIso(end, -days * DAY);
|
|
180
|
-
const
|
|
181
|
-
|
|
181
|
+
const fields = FUNNEL.map(([, f]) => f).join(",");
|
|
182
|
+
let stats;
|
|
183
|
+
if (entity === "adaccount") stats = (await accountTotals(client, adAccountId, { start_time: start, end_time: end, fields })).stats;
|
|
184
|
+
else {
|
|
185
|
+
const data = await client.request("GET", `/${base}/${id}/stats`, { query: { granularity: "TOTAL", start_time: start, end_time: end, fields, omit_empty: true } });
|
|
186
|
+
stats = data.total_stats?.[0]?.total_stat?.stats ?? {};
|
|
187
|
+
}
|
|
182
188
|
return {
|
|
183
189
|
window: { start_time: start, end_time: end, days },
|
|
184
190
|
...buildFunnel(stats),
|
|
@@ -188,6 +194,16 @@ export async function funnelReport(client, { adAccountId, entity = "adaccount",
|
|
|
188
194
|
|
|
189
195
|
// ---------- Catalog feed status ----------
|
|
190
196
|
|
|
197
|
+
// How many days apart uploads are expected, from the feed's schedule (unknown: null).
|
|
198
|
+
export function scheduleDays(schedule) {
|
|
199
|
+
if (!schedule) return null;
|
|
200
|
+
const n = Number(schedule.interval_count) || 1;
|
|
201
|
+
const unit = String(schedule.interval_type ?? "").toUpperCase();
|
|
202
|
+
return unit === "HOURLY" ? n / 24 : unit === "DAILY" ? n : unit === "WEEKLY" ? n * 7 : unit === "MONTHLY" ? n * 30 : null;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export const uploadErrorCount = (u) => Object.entries(u?.summary?.issues_summary ?? {}).filter(([k]) => /error/i.test(k)).reduce((n, [, counts]) => n + Object.values(counts ?? {}).reduce((a, b) => a + Number(b || 0), 0), 0);
|
|
206
|
+
|
|
191
207
|
export function judgeUpload(u) {
|
|
192
208
|
const issues = [];
|
|
193
209
|
const status = u.status;
|
|
@@ -215,7 +231,7 @@ export async function feedStatus(client, { organizationId, now = Date.now() }) {
|
|
|
215
231
|
const lastAge = last ? daysSince(last.updated_at ?? last.created_at, now) : null;
|
|
216
232
|
const problems = [];
|
|
217
233
|
if (!last) problems.push("No upload has completed yet.");
|
|
218
|
-
else if (lastAge > 2) problems.push(`The last completed upload was ${lastAge} days ago.`);
|
|
234
|
+
else if (lastAge > Math.max(2, 2 * (scheduleDays(feed.schedule) ?? 0))) problems.push(`The last completed upload was ${lastAge} days ago.`);
|
|
219
235
|
if (latest && latest.status && !["COMPLETE", "INITIALIZED", "IN_PROGRESS"].includes(latest.status)) problems.push(`The latest upload is ${latest.status}.`);
|
|
220
236
|
entry.feeds.push({
|
|
221
237
|
feed_id: feed.id,
|
|
@@ -225,6 +241,7 @@ export async function feedStatus(client, { organizationId, now = Date.now() }) {
|
|
|
225
241
|
last_completed_upload: last ? { at: last.updated_at ?? last.created_at, total_items: last.summary?.total_items ?? null, items_modified: last.summary?.items_modified ?? null, days_ago: lastAge } : null,
|
|
226
242
|
latest_upload_status: latest?.status ?? null,
|
|
227
243
|
upload_issues: latest ? judgeUpload(latest).slice(0, 10) : [],
|
|
244
|
+
upload_errors: latest ? uploadErrorCount(latest) : 0,
|
|
228
245
|
problems,
|
|
229
246
|
});
|
|
230
247
|
}
|
|
@@ -232,7 +249,7 @@ export async function feedStatus(client, { organizationId, now = Date.now() }) {
|
|
|
232
249
|
}
|
|
233
250
|
return {
|
|
234
251
|
catalogs: out.length,
|
|
235
|
-
feeds_with_problems: out.flatMap((c) => c.feeds).filter((f) => f.problems.length || f.
|
|
252
|
+
feeds_with_problems: out.flatMap((c) => c.feeds).filter((f) => f.problems.length || f.upload_errors > 0).length,
|
|
236
253
|
catalogs_detail: out,
|
|
237
254
|
note: "The feed's own URL and password are never shown. Recommendations (such as missing app links) are not counted as problems.",
|
|
238
255
|
};
|
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.9.
|
|
23
|
+
const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.9.1" });
|
|
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/intel.js
CHANGED
|
@@ -47,7 +47,13 @@ export async function audienceInsights(client, { adAccountId, targeting, base, c
|
|
|
47
47
|
const baseSpec = buildTargeting(base ?? { countries: targeting.countries });
|
|
48
48
|
if (category && !INSIGHT_CATEGORIES.includes(category)) throw new Error(`category must be one of ${INSIGHT_CATEGORIES.join(", ")}`);
|
|
49
49
|
const data = await client.request("POST", `/adaccounts/${adAccountId}/targeting_insights`, { query: { dimension_category: category }, body: { base_spec: baseSpec, targeting_spec: spec } });
|
|
50
|
-
|
|
50
|
+
const summary = summarizeInsights(data);
|
|
51
|
+
return {
|
|
52
|
+
...summary,
|
|
53
|
+
...(summary.groups.length ? {} : { note: "No group differs noticeably from the comparison audience. That is expected when your targeting is only the countries (the same as the comparison). Add ages, a gender, interests or a device to see differences." }),
|
|
54
|
+
targeting: spec,
|
|
55
|
+
base: baseSpec,
|
|
56
|
+
};
|
|
51
57
|
}
|
|
52
58
|
|
|
53
59
|
// ---------- Ads Gallery (public ads library, no login) ----------
|
package/src/report.js
CHANGED
|
@@ -123,20 +123,89 @@ export async function breakdownReport(client, { entity, id, start_time, end_time
|
|
|
123
123
|
export const DIMENSIONS = ["country", "gender", "age", "region", "dma", "make"];
|
|
124
124
|
const ENTITY_BASE = { adaccount: "adaccounts", campaign: "campaigns", adsquad: "adsquads", ad: "ads" };
|
|
125
125
|
|
|
126
|
+
// ---------- Account-level numbers ----------
|
|
127
|
+
// Snap's account-level stats endpoint only accepts the `spend` field when no breakdown is asked for ("Only field 'spend' should be
|
|
128
|
+
// used when querying AdAccount stats", found on a live account). Account totals are therefore built from the per-campaign
|
|
129
|
+
// breakdown, the query the weekly report already uses. Time series per hour or day are merged from the same breakdown; if Snap
|
|
130
|
+
// does not answer that, from the ACTIVE campaigns' own series. The result is checked against Snap's own spend total.
|
|
131
|
+
const NUMERIC = ["impressions", "spend", "swipes", "conversion_purchases", "conversion_purchases_value", "conversion_view_content", "conversion_add_cart", "conversion_start_checkout"];
|
|
132
|
+
const addStats = (into, s = {}) => {
|
|
133
|
+
for (const k of NUMERIC) if (s[k] != null) into[k] = (into[k] ?? 0) + Number(s[k]);
|
|
134
|
+
return into;
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
export async function accountTotals(client, adAccountId, { start_time, end_time, fields = FIELDS.join(",") }) {
|
|
138
|
+
checkWindow(start_time, end_time);
|
|
139
|
+
const rows = await collectBreakdown(client, `/adaccounts/${adAccountId}/stats`, { granularity: "TOTAL", breakdown: "campaign", start_time, end_time, fields, omit_empty: true, limit: 200 }, "campaign");
|
|
140
|
+
const stats = {};
|
|
141
|
+
for (const r of rows) addStats(stats, r.stats);
|
|
142
|
+
return { stats, campaigns: rows.length, incomplete: Boolean(rows.incomplete) };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function mergeSeries(into, timeseries = []) {
|
|
146
|
+
for (const t of timeseries) addStats((into[t.start_time] ??= { start_time: t.start_time, end_time: t.end_time, stats: {} }).stats, t.stats);
|
|
147
|
+
}
|
|
148
|
+
const sortedSeries = (m) => Object.values(m).sort((a, b) => Date.parse(a.start_time) - Date.parse(b.start_time));
|
|
149
|
+
|
|
150
|
+
export async function accountSeries(client, adAccountId, { granularity, start_time, end_time, fields = FIELDS.filter((f) => f !== "frequency").join(",") }) {
|
|
151
|
+
checkWindow(start_time, end_time);
|
|
152
|
+
const merged = {};
|
|
153
|
+
let source = "campaign breakdown";
|
|
154
|
+
try {
|
|
155
|
+
let cursor;
|
|
156
|
+
for (let page = 0; page < 40; page++) {
|
|
157
|
+
const data = await client.request("GET", `/adaccounts/${adAccountId}/stats`, { query: { granularity, breakdown: "campaign", start_time, end_time, fields, omit_empty: true, limit: 200, cursor } });
|
|
158
|
+
for (const ts of data.timeseries_stats ?? []) mergeSeries(merged, ts.timeseries_stat?.timeseries);
|
|
159
|
+
const next = data.paging?.next_link;
|
|
160
|
+
const nextCursor = next ? new URL(next).searchParams.get("cursor") : null;
|
|
161
|
+
if (!nextCursor || nextCursor === cursor) break;
|
|
162
|
+
cursor = nextCursor;
|
|
163
|
+
}
|
|
164
|
+
} catch (e) {
|
|
165
|
+
if (!/\(400\)|Unsupported/i.test(String(e.message))) throw e;
|
|
166
|
+
for (const k of Object.keys(merged)) delete merged[k];
|
|
167
|
+
}
|
|
168
|
+
// The check: the series must add up to the spend Snap reports for the account over the same window.
|
|
169
|
+
const accountSpend = await client.request("GET", `/adaccounts/${adAccountId}/stats`, { query: { granularity: "TOTAL", start_time, end_time, fields: "spend" } })
|
|
170
|
+
.then((d) => Number(d.total_stats?.[0]?.total_stat?.stats?.spend ?? 0))
|
|
171
|
+
.catch(() => null);
|
|
172
|
+
const seriesSpend = () => Object.values(merged).reduce((n, t) => n + (t.stats.spend ?? 0), 0);
|
|
173
|
+
if (accountSpend > 0 && seriesSpend() < accountSpend * 0.95) {
|
|
174
|
+
// Not the whole account (or an unexpected answer): rebuild from the ACTIVE campaigns' own series.
|
|
175
|
+
for (const k of Object.keys(merged)) delete merged[k];
|
|
176
|
+
source = "active campaigns only";
|
|
177
|
+
const campaigns = (await client.listPaged(`/adaccounts/${adAccountId}/campaigns`, "campaign")).items.filter((c) => c.status === "ACTIVE");
|
|
178
|
+
for (const c of campaigns) {
|
|
179
|
+
const d = await client.request("GET", `/campaigns/${c.id}/stats`, { query: { granularity, start_time, end_time, fields, omit_empty: true } });
|
|
180
|
+
mergeSeries(merged, d.timeseries_stats?.[0]?.timeseries_stat?.timeseries);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const covered = accountSpend > 0 ? Math.min(1, seriesSpend() / accountSpend) : 1;
|
|
184
|
+
return { series: sortedSeries(merged), source, coverage_pct: Math.round(covered * 100), ...(covered < 0.95 ? { warning: `These numbers cover about ${Math.round(covered * 100)}% of the account's spend (${source}); the rest could not be broken down.` } : {}) };
|
|
185
|
+
}
|
|
186
|
+
|
|
126
187
|
// One row per day (synchronous limit: 31 days).
|
|
127
188
|
export async function dailyReport(client, { entity, id, start_time, end_time, swipe_up_attribution_window, view_attribution_window }) {
|
|
128
|
-
if (!ENTITY_BASE[entity]) throw new Error("entity must be campaign, adsquad or ad");
|
|
189
|
+
if (!ENTITY_BASE[entity]) throw new Error("entity must be adaccount, campaign, adsquad or ad");
|
|
129
190
|
checkWindow(start_time, end_time);
|
|
130
191
|
const days = (new Date(end_time) - new Date(start_time)) / 86_400_000;
|
|
131
192
|
if (days > 31) throw new Error("Daily reports are limited to 31 days per request");
|
|
132
193
|
const attribution = attributionQuery({ swipe_up_attribution_window, view_attribution_window });
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
194
|
+
let series;
|
|
195
|
+
let accountNote = {};
|
|
196
|
+
if (entity === "adaccount") {
|
|
197
|
+
const acc = await accountSeries(client, id, { granularity: "DAY", start_time, end_time });
|
|
198
|
+
series = acc.series;
|
|
199
|
+
accountNote = { source: acc.source, coverage_pct: acc.coverage_pct, ...(acc.warning ? { warning: acc.warning } : {}) };
|
|
200
|
+
} else {
|
|
201
|
+
const data = await client.request("GET", `/${ENTITY_BASE[entity]}/${id}/stats`, {
|
|
202
|
+
query: { granularity: "DAY", start_time, end_time, fields: FIELDS.join(","), omit_empty: true, ...attribution },
|
|
203
|
+
});
|
|
204
|
+
series = data.timeseries_stats?.[0]?.timeseries_stat?.timeseries ?? [];
|
|
205
|
+
}
|
|
137
206
|
// The date is the local day in the requested offset, whether Snap answers in that offset or in UTC.
|
|
138
207
|
const rows = series.map((r) => ({ date: localDate(r.start_time, start_time), ...summarizeRow(null, null, r.stats) })).map(({ id: _i, name: _n, ...rest }) => rest);
|
|
139
|
-
return { window: { start_time, end_time }, days: rows.length, ...totalsOf(series.map((r) => r.stats)), basis: basisOf(attribution), rows };
|
|
208
|
+
return { window: { start_time, end_time }, days: rows.length, ...totalsOf(series.map((r) => r.stats)), basis: basisOf(attribution), ...accountNote, rows };
|
|
140
209
|
}
|
|
141
210
|
|
|
142
211
|
// Totals split by country, gender, age, region, dma or make.
|
package/src/snap.js
CHANGED
|
@@ -146,21 +146,31 @@ export class SnapClient {
|
|
|
146
146
|
this.tokenExpiry = 0;
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
// Calls to Snap's Conversions API host (test-event tools only).
|
|
150
|
-
//
|
|
149
|
+
// Calls to Snap's Conversions API host (test-event tools only). Snap's test tools take the token as an `access_token` parameter
|
|
150
|
+
// (an OAuth access token works, or a Conversions API token made in Ads Manager: set SNAP_CAPI_TOKEN to use that one). The token
|
|
151
|
+
// goes to this one fixed host. A 4xx on POST is returned with its body (Snap explains an INVALID test event there); a failed GET throws.
|
|
151
152
|
async requestTr(method, path, { body } = {}) {
|
|
152
|
-
const
|
|
153
|
+
const [pathname, search = ""] = String(path).split("?");
|
|
154
|
+
const url = new URL(TR + pathname);
|
|
153
155
|
if (url.hostname !== "tr.snapchat.com") throw new Error("refusing to send the token to another host");
|
|
154
|
-
|
|
155
|
-
|
|
156
|
+
url.search = search;
|
|
157
|
+
const own = this.env.SNAP_CAPI_TOKEN || null;
|
|
158
|
+
const send = async () => {
|
|
159
|
+
const token = own ?? (await this.accessToken());
|
|
160
|
+
url.searchParams.set("access_token", token);
|
|
161
|
+
return this.fetchRetry(url, { method, headers: { ...(own ? {} : { Authorization: `Bearer ${token}` }), "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined });
|
|
162
|
+
};
|
|
156
163
|
let res = await send();
|
|
157
|
-
if (res.status === 401) {
|
|
164
|
+
if (res.status === 401 && !own) {
|
|
158
165
|
this.token = null;
|
|
159
166
|
this.tokenExpiry = 0;
|
|
160
167
|
res = await send();
|
|
161
168
|
}
|
|
162
169
|
const data = await res.json().catch(() => ({}));
|
|
163
|
-
if (
|
|
170
|
+
if (res.status === 401 || res.status === 403) {
|
|
171
|
+
throw new Error(`Snap refused the token for the Conversions API test tools (${res.status}: ${String(data.reason ?? data.detail ?? "Invalid access token").slice(0, 120)}). ${own ? "Check SNAP_CAPI_TOKEN." : "Create a Conversions API token in Ads Manager (Events Manager > Conversions API > Generate token) and set SNAP_CAPI_TOKEN in your settings."}`);
|
|
172
|
+
}
|
|
173
|
+
if (method === "GET" && !res.ok) throw new Error(`Snap Conversions API ${method} ${pathname} failed (${res.status}): ${String(data.reason ?? data.debug_message ?? "").slice(0, 300)}`);
|
|
164
174
|
return { status: res.status, data };
|
|
165
175
|
}
|
|
166
176
|
|
package/src/verify.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// `verify`: runs the read-only tools on a real account, one by one, and prints a short pass/fail list. It exists so that one
|
|
2
|
+
// command (instead of asking an AI app about each tool) shows what works on your account, and what does not.
|
|
3
|
+
// It only calls tools that declare themselves read-only, and it forces read-only mode on top of that.
|
|
4
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
5
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
6
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
7
|
+
import { registerTools } from "./tools.js";
|
|
8
|
+
import { loadPolicy } from "./policy.js";
|
|
9
|
+
import { localClock } from "./insights.js";
|
|
10
|
+
import { shiftIso } from "./fatigue.js";
|
|
11
|
+
|
|
12
|
+
const count = (a) => (Array.isArray(a) ? `${a.length} item${a.length === 1 ? "" : "s"}` : null);
|
|
13
|
+
|
|
14
|
+
// Each check: the tool, its arguments, what it needs from the settings (else it is skipped), and a short summary of the answer.
|
|
15
|
+
export function checksFor({ start, end, hasPixel, hasCountry }) {
|
|
16
|
+
return [
|
|
17
|
+
{ tool: "snap_ping", args: {}, show: (d) => `authorized as ${d.me?.display_name ?? d.me?.email ?? "your login"}; account ${d.ad_account ? "set" : "NOT set"}` },
|
|
18
|
+
{ tool: "snap_list_campaigns", args: { limit: 5 }, show: (d) => count(d) },
|
|
19
|
+
{ tool: "snap_list_adsquads", args: { limit: 5 }, show: (d) => count(d) },
|
|
20
|
+
{ tool: "snap_list_media", args: { limit: 3 }, show: (d) => count(d) },
|
|
21
|
+
{ tool: "snap_list_segments", args: { limit: 3 }, show: (d) => count(d) },
|
|
22
|
+
{ tool: "snap_spend_pacing", args: {}, show: (d) => `${d.today?.active_squads ?? "?"} active ad squads; month so far ${d.month?.month_to_date_spend ?? "?"}` },
|
|
23
|
+
{ tool: "snap_anomaly_check", args: {}, show: (d) => `verdict ${d.verdict}${d.findings?.length ? ` (${d.findings.map((f) => f.code).join(", ")})` : ""}; ${d.days?.length ?? 0} days read` },
|
|
24
|
+
{ tool: "snap_funnel", args: { days: 7 }, show: (d) => `weakest step: ${d.weakest_step ?? "n/a"}${d.missing_steps?.length ? `; missing events: ${d.missing_steps.join(", ")}` : ""}` },
|
|
25
|
+
{ tool: "snap_report_hourly", args: { days: 7 }, show: (d) => `best hours ${JSON.stringify(d.best_hours ?? [])}${d.coverage_pct != null ? `; covers ${d.coverage_pct}% of spend (${d.source})` : ""}` },
|
|
26
|
+
{ tool: "snap_billing_check", args: {}, show: (d) => `verdict ${d.verdict}; ${d.funding_sources?.length ?? 0} funding source(s)` },
|
|
27
|
+
{ tool: "snap_audience_health", args: {}, show: (d) => `${d.audiences} audiences, ${d.with_problems} with problems` },
|
|
28
|
+
{ tool: "snap_unused_media", args: { limit: 5 }, show: (d) => `${d.unused_count} of ${d.media_total} files unused${d.warning ? " (list cut: partial)" : ""}` },
|
|
29
|
+
{ tool: "snap_budget_advice", args: {}, show: (d) => `${d.active_squads_with_a_daily_budget} squads read, ${d.squads_compared ?? "?"} compared; ${d.increases?.length ?? 0} raise, ${d.decreases?.length ?? 0} lower suggested` },
|
|
30
|
+
{ tool: "snap_check_landing_pages", args: { max_links: 20 }, show: (d) => `${d.active_ads} active ads, ${d.links_checked} link(s) checked, ${d.problems?.length ?? 0} problem(s)${d.partial ? " (partial: out of time)" : ""}` },
|
|
31
|
+
{ tool: "snap_health_check", args: { start_time: start, end_time: end }, show: (d) => `${d.active_squads_checked} active ad squads, ${d.squads_with_issues} with issues` },
|
|
32
|
+
{ tool: "snap_review_issues", args: {}, show: (d) => `${d.shown ?? d.items?.length ?? 0} ad(s) not approved` },
|
|
33
|
+
{ tool: "snap_list_dynamic_templates", args: { limit: 5 }, show: (d) => count(d) },
|
|
34
|
+
{ tool: "snap_catalog_feed_status", args: {}, show: (d) => `${d.catalogs} catalog(s), ${d.feeds_with_problems} feed(s) with problems${d.feeds_with_problems ? `; e.g. ${d.catalogs_detail.flatMap((c) => c.feeds).find((f) => f.problems.length || f.upload_errors)?.problems?.[0] ?? "upload errors"}` : ""}` },
|
|
35
|
+
{ tool: "snap_pixel_health", args: {}, needs: hasPixel, setting: "SNAP_PIXEL_ID", show: (d) => `${d.top_priority_issues?.length ?? 0} top-priority issue(s)` },
|
|
36
|
+
{ tool: "snap_capi_status", args: {}, needs: hasPixel, setting: "SNAP_PIXEL_ID", show: (d) => `${d.test_events?.event_count_past_hour ?? 0} test events in the last hour` },
|
|
37
|
+
{ tool: "snap_audience_size", args: {}, needs: hasCountry, setting: "SNAP_DEFAULT_COUNTRY", show: (d) => `${d.audience_size_min}-${d.audience_size_max} people (${d.verdict})` },
|
|
38
|
+
{ tool: "snap_audience_insights", args: { min_age: 18, max_age: 24, gender: "FEMALE" }, needs: hasCountry, setting: "SNAP_DEFAULT_COUNTRY", show: (d) => `${d.groups?.length ?? 0} insight group(s)${d.groups?.length ? "" : " (none: unexpected for a narrowed targeting)"}` },
|
|
39
|
+
{ tool: "snap_competitor_ads", args: { advertiser: "Nike", status: "ACTIVE" }, show: (d) => `${d.count} ad(s) returned by the public Ads Gallery` },
|
|
40
|
+
{ tool: "snap_portfolio_summary", args: {}, show: (d) => (d.configured === false ? "not configured (optional: SNAP_PORTFOLIO_FILES)" : `${d.accounts?.length ?? 0} account(s)`) },
|
|
41
|
+
];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Printed output never includes ids or tokens: ids are shortened, long secret-looking strings are hidden.
|
|
45
|
+
export const tidy = (s) => String(s).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, (m) => `${m.slice(0, 8)}…`).replace(/[A-Za-z0-9._-]{40,}/g, "[hidden]").replace(/\s+/g, " ").slice(0, 220);
|
|
46
|
+
|
|
47
|
+
export async function runVerify({ client, env = process.env, now = new Date(), log = console.log }) {
|
|
48
|
+
// Everything below runs with writes switched off, whatever the settings say.
|
|
49
|
+
const settings = { ...env, SNAP_READ_ONLY: "1", SNAP_TOOLSETS: "", SNAP_LOG_FILE: env.SNAP_LOG_FILE ?? "" };
|
|
50
|
+
const policy = loadPolicy(settings);
|
|
51
|
+
const server = new McpServer({ name: "verify", version: "1" });
|
|
52
|
+
registerTools(server, client, settings);
|
|
53
|
+
const mcp = new Client({ name: "verify", version: "1" });
|
|
54
|
+
const [a, b] = InMemoryTransport.createLinkedPair();
|
|
55
|
+
await Promise.all([server.connect(a), mcp.connect(b)]);
|
|
56
|
+
const tools = new Map((await mcp.listTools()).tools.map((t) => [t.name, t]));
|
|
57
|
+
const end = localClock(now, policy.reportUtcOffset).todayStart;
|
|
58
|
+
const start = shiftIso(end, -7 * 86_400_000);
|
|
59
|
+
const checks = checksFor({ start, end, hasPixel: Boolean(settings.SNAP_PIXEL_ID), hasCountry: Boolean(settings.SNAP_DEFAULT_COUNTRY) });
|
|
60
|
+
const results = [];
|
|
61
|
+
for (const c of checks) {
|
|
62
|
+
const tool = tools.get(c.tool);
|
|
63
|
+
let row;
|
|
64
|
+
if (!tool) row = { tool: c.tool, status: "SKIP", detail: "tool is not available" };
|
|
65
|
+
else if (tool.annotations?.readOnlyHint !== true) row = { tool: c.tool, status: "SKIP", detail: "not read-only; never called here" };
|
|
66
|
+
else if ("needs" in c && !c.needs) row = { tool: c.tool, status: "SKIP", detail: `needs ${c.setting} in your settings` };
|
|
67
|
+
else {
|
|
68
|
+
try {
|
|
69
|
+
const r = await mcp.callTool({ name: c.tool, arguments: c.args }, undefined, { timeout: 5 * 60_000 });
|
|
70
|
+
const text = r.content?.[0]?.text ?? "";
|
|
71
|
+
// Snap refusing the normal login for the Conversions API test tools is a missing setting, not a fault.
|
|
72
|
+
if (r.isError && c.tool.startsWith("snap_capi_") && /refused the token for the Conversions API/.test(text) && !settings.SNAP_CAPI_TOKEN) row = { tool: c.tool, status: "SKIP", detail: "needs SNAP_CAPI_TOKEN: a Conversions API token from Ads Manager (Events Manager > Conversions API > Generate token). Optional." };
|
|
73
|
+
else if (r.isError) row = { tool: c.tool, status: "FAIL", detail: tidy(text) };
|
|
74
|
+
else {
|
|
75
|
+
let data = null;
|
|
76
|
+
try {
|
|
77
|
+
data = JSON.parse(text);
|
|
78
|
+
} catch {
|
|
79
|
+
data = null;
|
|
80
|
+
}
|
|
81
|
+
let detail = "ok";
|
|
82
|
+
try {
|
|
83
|
+
detail = tidy(c.show(Array.isArray(data) ? data : data ?? {}) ?? "ok");
|
|
84
|
+
} catch {
|
|
85
|
+
detail = "ok";
|
|
86
|
+
}
|
|
87
|
+
row = { tool: c.tool, status: "OK", detail };
|
|
88
|
+
}
|
|
89
|
+
} catch (e) {
|
|
90
|
+
row = { tool: c.tool, status: "FAIL", detail: tidy(e.message) };
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
results.push(row);
|
|
94
|
+
log(` ${row.status === "OK" ? "✓" : row.status === "SKIP" ? "-" : "✗"} ${row.tool.padEnd(28)} ${row.detail}`);
|
|
95
|
+
}
|
|
96
|
+
await mcp.close();
|
|
97
|
+
const failed = results.filter((r) => r.status === "FAIL").length;
|
|
98
|
+
log("");
|
|
99
|
+
log(`${results.filter((r) => r.status === "OK").length} worked, ${failed} failed, ${results.filter((r) => r.status === "SKIP").length} skipped.`);
|
|
100
|
+
log(failed ? "Copy everything above (it contains no tokens and only short ids) and send it to whoever maintains this project." : "Everything read-only worked on this account.");
|
|
101
|
+
return { results, failed };
|
|
102
|
+
}
|