ads-mcp-for-snapchat 0.9.1 → 0.9.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 0.9.3 (2026-11-16)
6
+
7
+ - **Shared login is live.** The login service is deployed and the package uses it by default (`npx -y ads-mcp-for-snapchat setup`, choose 1). Verified on a real Snapchat login: login, account list, saving the access, renewing it through the service, and `verify` (20 of 24 checks ran; the rest need optional settings). Snap has not yet been asked to confirm a shared app for other advertisers; own-app setup still works.
8
+ - `setup` checks the name given for the server in Claude (letters, numbers, - and _) instead of passing a pasted command to Claude Code.
9
+
10
+ - Login service: the browser cookie that ties a login to the browser that started it is now sent after Snapchat's redirect in every browser (SameSite=None instead of Lax), and the error page says whether the link expired or the browser did not start the login.
11
+
12
+ - A GitHub Action builds the Claude Desktop file and creates the GitHub Release when a version tag is pushed.
13
+
14
+ ## 0.9.2 (2026-11-15)
15
+
16
+ - README: the "Not built" list no longer names things that now exist (product sets, dynamic product creatives, other ad squad goals); "Verified live" now says what the real-account `verify` run covered and what is still only tested against a fake Snap; the shared login is marked as not available until a service is deployed.
17
+ - `snap_check_landing_pages`: a website that answers 401, 403 or 429 to the check (bot protection; found on a live shop) is listed apart as "could not check" and never counted as a broken link.
18
+ - `snap_audience_health`: audiences with nobody in them are flagged EMPTY (not TINY), counted by flag, and problems on audiences that an ACTIVE ad squad uses right now (for example a stale buyer list used for exclusion) are listed first.
19
+ - `verify`: a rate-limited public Ads Gallery is a skip, long upper-case error codes stay readable, percent-encoded link paths are decoded for display.
20
+ - `verify --details` lists the specifics behind each problem (broken links without their query strings, pixel issues, feed errors, audience problems, rejected ads' reasons, ad squad issue counts).
21
+
3
22
  ## 0.9.1 (2026-11-15)
4
23
 
5
24
  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.
package/README.md CHANGED
@@ -27,10 +27,14 @@ A local [MCP](https://modelcontextprotocol.io) server that lets an AI assistant
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
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.
30
+ `npx -y ads-mcp-for-snapchat verify` (or `node src/cli.js verify` in a git checkout; add `--details` to also list the specific problems it found: broken links, pixel issues, feed errors, audience problems, rejected ads) 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
31
 
32
32
  ## Easiest: log in with Snapchat (no OAuth app)
33
- When a login service is available (see `broker/README.md` and `PRIVACY.md`), you do not need to create a Snapchat OAuth app. Run `npx -y ads-mcp-for-snapchat setup` and choose **1. Shared login**, or install the Claude Desktop file, leave Client ID and secret empty, and ask Claude: "Connect my Snapchat ad account." You log in with Snapchat in your browser and pick your ad account. The service only passes your login along: it stores nothing, and your access is sealed so only your own computer can read it. Prefer to stay independent? Use your own app (next section), or run your own copy of the service.
33
+ 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. No OAuth app to create.
34
+
35
+ How it works: a small login service (`broker/`, code in this repository) passes your login along and stores nothing, and your access is sealed so only your own computer can read it. Read `PRIVACY.md` first. The tool itself still runs only on your computer.
36
+
37
+ **Status: new.** It works end to end on the maintainer's real login and ad accounts, but Snap has not yet been asked to confirm that one shared app may serve other advertisers. If the login is refused for you, or you prefer not to rely on a shared service, use your own Snapchat app (next section: about 5 minutes, and `setup` walks you through it) or run your own copy of the service (`broker/README.md`).
34
38
 
35
39
  ## Easy setup (about 5 minutes)
36
40
  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).
@@ -90,7 +94,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
90
94
  | `SNAP_ACCOUNT_CURRENCY` | not set | If set (e.g. `USD`), writes are refused unless the ad account uses that currency |
91
95
  | `SNAP_READ_ONLY` | 0 | `1` = previews and reads only |
92
96
  | `SNAP_CAPI_TOKEN` | (none) | Only for the Conversions API test tools (`snap_capi_*`): a Conversions API token made in Ads Manager (Events Manager > Conversions API > Generate token), used if Snap does not accept your normal login there. Sent only to `tr.snapchat.com`. |
93
- | `SNAP_BROKER_URL` | (none) | The shared login service: connect with a normal Snapchat login and no OAuth app. https only. A refresh token is sent there, so use only a service you trust (see `PRIVACY.md`, `broker/README.md`). `setup` saves it for you. |
97
+ | `SNAP_BROKER_URL` | the maintainer's login service (`off` turns the shared login off) | The shared login service: connect with a normal Snapchat login and no OAuth app. https only. A refresh token is sent there, so use only a service you trust (see `PRIVACY.md`, `broker/README.md`). `setup` saves it for you. |
94
98
  | `SNAP_HOME` | `~/.ads-mcp-for-snapchat` for an npm install, the project folder for a git checkout | Where the settings file, the change log and `exports/` live. Set it to keep them somewhere else. |
95
99
  | `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. |
96
100
  | `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. |
@@ -200,7 +204,7 @@ From an npm install, use `npx -y ads-mcp-for-snapchat check | weekly-report` ins
200
204
  ## Requirements
201
205
  Node 18+ and a Snapchat Ads account with permission to create an OAuth app. Install dependencies with `npm install`. Run the tests with `npm test` (all mocked, no credentials needed).
202
206
 
203
- Each user runs this server locally with their own OAuth app and their own ad account. Nothing is shared or hosted.
207
+ Each user runs this server locally with their own ad account, and (for now) their own OAuth app. Nothing about your ad account is hosted or shared; the optional login service (see above) only handles the Snapchat login.
204
208
 
205
209
  ## Setup (one time)
206
210
  1. In Snap Ads Manager open **Business Details > OAuth Apps** and create an app. Redirect URL must be https and not `localhost`, for example `https://127.0.0.1/callback`. **The client secret is shown once**: select it and copy it before leaving the page.
@@ -268,11 +272,17 @@ Verified on the maintainer's own ad account. Anything not listed here is covered
268
272
 
269
273
  **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).
270
274
 
271
- **Not verified live:** everything added in 0.6.0 and 0.7.0 (`snap_audience_size`, `snap_spend_pacing`, `snap_ad_preview`; catalog ads; bid-strategy switching, placement and the portfolio summary; the landing page, anomaly, blended ROAS, audience insights, competitor ads, Conversions API test, hourly, creative comparison, budget advice, billing, unused media, audience health, funnel and feed tools; frequency cap and ad schedule; the new ad squad goals), all built from Snap's documentation and mocked tests, the 24-hour spend limit and absolute limits on real writes (mocked tests only), `SNAP_HUMAN_APPROVAL=elicit` in Claude Code, `snap_create_creative` with a WEB_VIEW link, a campaign-level `snap_set_daily_budget`, a successful `snap_delete` of an ad squad, ad or audience, a customer-list upload of real data, and Node 18 / 20 outside CI.
275
+ **Read-only run of `verify` on the maintainer's real ad account (November 2026, 23 of 24 tools worked):** `snap_ping`; the campaign, ad squad, media and audience lists; spend pacing; anomaly check; funnel; hourly report; billing check; audience health; unused media; budget advice; landing page check; health check; review issues; dynamic template list; catalog feed status; pixel health; audience size; audience insights; and the public Ads Gallery lookup. That run found real bugs that mocked tests could not (Snap's account-level stats accept only the `spend` field; the landing page check read too much; a shop's bot protection answered 403), all fixed in 0.9.1 and after.
276
+
277
+ **Not verified live:**
278
+ - Everything that **writes** and was added in 0.7.0 or later: catalog ad creation (product sets, templates, campaign, ad squad, creative, ad), frequency cap, ad schedule, placement, bid-strategy switching, and the new ad squad goals. Built from Snap's documentation and mocked tests.
279
+ - The Conversions API test tools (they need a Conversions API token: `SNAP_CAPI_TOKEN`), the portfolio summary (needs a second settings file), blended ROAS (needs your store's revenue), creative comparison, ad preview, and the playbooks.
280
+ - The shared login for people **outside** the maintainer's organization, and the Claude Desktop extension's login. (Setup's shared login, the account list and renewing the login through the service were run live on the maintainer's account.)
281
+ - 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.
272
282
 
273
283
  ## Not built
274
- - A hosted multi-user version (this server runs on your own machine with your own credentials).
275
- - Lens, App Install, Deep Link, lead-form and dynamic product creatives, product set creation, ad squad types other than purchase-optimized web squads, custom location/radius targeting, lifetime or reach-and-frequency budgets, and position-level reports.
284
+ - A hosted multi-user MCP server, which ChatGPT would need. The optional shared login service (`broker/`) only passes Snapchat logins along; the tool itself always runs on your own computer.
285
+ - Lens, App Install, Deep Link and lead-form creatives; ad squad goals for app installs and lead generation; custom location and radius targeting; reach-and-frequency budgets; position-level reports; custom placement on ad squads that use content inclusion or exclusion lists; switching an ad squad to auto-bid (it would remove the bid cap).
276
286
  - Anything that spends money without a separate, explicit enable step.
277
287
 
278
288
  ## Development
package/broker/worker.js CHANGED
@@ -79,16 +79,19 @@ async function login(request, env) {
79
79
  const state = await signState(env, { p: Number(port), k: pk, n: nonce, e: Date.now() + STATE_MINUTES * 60_000 });
80
80
  const auth = new URL(AUTHORIZE);
81
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 } });
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=None`, ...SECURITY_HEADERS } });
83
83
  }
84
84
 
85
85
  async function callback(request, env, fetchImpl) {
86
86
  need(env, "SNAP_CLIENT_ID", "SNAP_CLIENT_SECRET", "STATE_KEY");
87
87
  const u = new URL(request.url);
88
- const clear = { "Set-Cookie": `${COOKIE}=; Path=/callback; Max-Age=0; HttpOnly; Secure; SameSite=Lax` };
88
+ const clear = { "Set-Cookie": `${COOKIE}=; Path=/callback; Max-Age=0; HttpOnly; Secure; SameSite=None` };
89
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);
90
+ if (!state || !state.k || !validPort(String(state.p)) || !validNonce(state.n)) {
91
+ return page("Login expired", "<h1>This login link is not valid any more</h1><p>It has expired or was changed. Start again from the setup command.</p>", 400, clear);
92
+ }
93
+ if (getCookie(request, COOKIE) !== state.n) {
94
+ return page("Login expired", "<h1>This browser did not start the login</h1><p>The login must finish in the same browser window it started in, and the address must not be reloaded or opened a second time. Allow cookies for this site, then start again from the setup command.</p>", 400, clear);
92
95
  }
93
96
  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
97
  const code = u.searchParams.get("code");
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "ads-mcp-for-snapchat",
3
- "version": "0.9.1",
3
+ "version": "0.9.3",
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
+ "adsMcpBroker": "https://ads-mcp-for-snapchat-login.ads-mcp.workers.dev",
7
7
  "type": "module",
8
8
  "main": "src/index.js",
9
9
  "bin": {
package/src/broker.js CHANGED
@@ -22,7 +22,7 @@ function packageDefault() {
22
22
  // sent to this address, so a plain http address to anything else is refused.
23
23
  export function brokerUrlFrom(env = process.env, fallback = packageDefault()) {
24
24
  const raw = String(env.SNAP_BROKER_URL ?? "").trim() || String(fallback ?? "").trim();
25
- if (!raw) return null;
25
+ if (!raw || /^(off|none|no)$/i.test(raw)) return null; // SNAP_BROKER_URL=off turns the shared login off
26
26
  let u;
27
27
  try {
28
28
  u = new URL(raw);
package/src/checks.js CHANGED
@@ -151,7 +151,10 @@ export async function landingPageReport(client, { adAccountId, requiredParams =
151
151
  const missing = requiredParams.filter((p) => { try { return !new URL(r.url).searchParams.has(p); } catch { return true; } });
152
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 } : {}) };
153
153
  });
154
- const problems = rows.filter((r) => !["OK", "NOT_CHECKED"].includes(r.verdict) || r.missing_params || r.lands_on_other_site);
154
+ // A site answering 401, 403 or 429 to an automatic check usually blocks bots (found on a live shop): that says nothing about the
155
+ // link, so it is listed separately and never counted as a broken link.
156
+ const blocked = rows.filter((r) => r.verdict === "UNCHECKED");
157
+ const problems = rows.filter((r) => !["OK", "NOT_CHECKED", "UNCHECKED"].includes(r.verdict) || r.missing_params || r.lands_on_other_site);
155
158
  const counts = {};
156
159
  for (const r of rows) counts[r.verdict] = (counts[r.verdict] ?? 0) + 1;
157
160
  const outOfTime = timeUp();
@@ -166,7 +169,8 @@ export async function landingPageReport(client, { adAccountId, requiredParams =
166
169
  ...(campaigns.complete ? {} : { warning_incomplete: "The campaign list was INCOMPLETE; some ads were not looked at." }),
167
170
  by_verdict: counts,
168
171
  problems,
169
- all_links_ok: !problems.length && !outOfTime,
172
+ ...(blocked.length ? { could_not_check: blocked.map((r) => ({ url: r.url, status: r.status, ads: r.ads })), could_not_check_note: `${blocked.length} link(s) were answered with ${[...new Set(blocked.map((r) => r.status))].join("/")} by the website itself, which usually means it blocks automatic checks (bot protection). The links may work fine for people: open one yourself. They are not counted as broken.` } : {}),
173
+ all_links_ok: !problems.length && !outOfTime && !blocked.length,
170
174
  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.",
171
175
  };
172
176
  }
package/src/cli.js CHANGED
@@ -26,7 +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
+ verify run every read-only tool on your account and show what works (changes nothing); add --details for the specifics behind each problem
30
30
  help show this text
31
31
 
32
32
  Settings file: SNAP_ENV_FILE if set, otherwise .env in ~/.ads-mcp-for-snapchat (npm install) or the project folder (git clone).`;
@@ -44,7 +44,7 @@ export async function main(argv = process.argv.slice(2)) {
44
44
  const { runVerify } = await import("./verify.js");
45
45
  loadEnv();
46
46
  console.log("Checking every read-only tool on your ad account (nothing is changed)...\n");
47
- const { failed } = await runVerify({ client: new SnapClient() });
47
+ const { failed } = await runVerify({ client: new SnapClient(), details: rest.includes("--details") });
48
48
  process.exitCode = failed ? 1 : 0;
49
49
  return;
50
50
  }
package/src/hygiene.js CHANGED
@@ -125,15 +125,22 @@ export async function audienceHealth(client, { adAccountId, now = Date.now(), st
125
125
  const age = daysSince(s.updated_at ?? s.created_at, now);
126
126
  const flags = [];
127
127
  if (status && status !== "READY") flags.push({ code: "NOT_TARGETABLE", detail: `Status ${status}: it cannot be used in targeting yet.` });
128
- if (size < minSize) flags.push({ code: "TINY", detail: `About ${size} people: too small to deliver reliably.` });
128
+ if (size === 0) flags.push({ code: "EMPTY", detail: "No people in it (an old, expired or never-filled audience)." });
129
+ else if (size < minSize) flags.push({ code: "TINY", detail: `About ${size} people: too small to deliver reliably.` });
129
130
  if (s.source_type === "FIRST_PARTY" && age != null && age > staleDays) flags.push({ code: "STALE", detail: `A customer list not updated for ${age} days. Old lists miss recent buyers.` });
130
131
  const uses = usedBy.get(s.id) ?? 0;
131
132
  return { id: s.id, name: s.name, source_type: s.source_type, status, size, age_days: age, used_by_active_squads: uses, flags, ...(uses === 0 ? { unused: true } : {}) };
132
133
  });
133
134
  const problems = rows.filter((r) => r.flags.length);
135
+ const byFlag = {};
136
+ for (const r of problems) for (const f of r.flags) byFlag[f.code] = (byFlag[f.code] ?? 0) + 1;
137
+ // What matters most: a problem on an audience an ACTIVE ad squad uses right now (for example a stale buyer list used to exclude buyers).
138
+ const important = problems.filter((r) => r.used_by_active_squads > 0);
134
139
  return {
135
140
  audiences: rows.length,
136
141
  with_problems: problems.length,
142
+ by_flag: byFlag,
143
+ important_used_by_active_squads: important.slice(0, 20),
137
144
  used_by_active_squads: rows.filter((r) => r.used_by_active_squads > 0).length,
138
145
  unused_audiences: rows.filter((r) => r.unused).length,
139
146
  active_squads_read: squadsRead,
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.1" });
23
+ const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.9.3" });
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/setup.js CHANGED
@@ -224,7 +224,15 @@ export async function runSetup({ io, file = envFile(), fetchImpl = fetch, open =
224
224
  const launch = launchCommand(root);
225
225
  const defaultFile = join(dataDir({ root }), ".env");
226
226
  const envArgs = file === defaultFile ? [] : ["-e", `SNAP_ENV_FILE=${file}`];
227
- const name = (await io.ask(" Name for this server in Claude [snapchat-ads]: ")) || "snapchat-ads";
227
+ let name = "snapchat-ads";
228
+ for (let tries = 0; tries < 3; tries++) {
229
+ const answer = ((await io.ask(" Name for this server in Claude [snapchat-ads]: ")) || "snapchat-ads").trim();
230
+ if (/^[A-Za-z0-9_-]{1,64}$/.test(answer)) {
231
+ name = answer;
232
+ break;
233
+ }
234
+ say(" Use only letters, numbers, - and _ (for example snapchat-ads).");
235
+ }
228
236
  let registered = false;
229
237
  if (claudeAvailable(exec)) {
230
238
  try {
package/src/verify.js CHANGED
@@ -11,6 +11,34 @@ import { shiftIso } from "./fatigue.js";
11
11
 
12
12
  const count = (a) => (Array.isArray(a) ? `${a.length} item${a.length === 1 ? "" : "s"}` : null);
13
13
 
14
+ // For `verify --details`: the specifics behind a summary line. Links are shown without their query string (it can carry
15
+ // tracking ids); everything goes through tidy() before it is printed.
16
+ const where = (u) => {
17
+ try {
18
+ const x = new URL(u);
19
+ let path = x.pathname;
20
+ try {
21
+ path = decodeURIComponent(path);
22
+ } catch {
23
+ // keep the encoded form
24
+ }
25
+ return `${x.hostname}${path.length > 70 ? `${path.slice(0, 70)}...` : path}`;
26
+ } catch {
27
+ return String(u).split("?")[0];
28
+ }
29
+ };
30
+ export const DETAILS = {
31
+ snap_check_landing_pages: (d) => [...(d.problems ?? []).slice(0, 10), ...(d.could_not_check ?? []).slice(0, 5).map((p) => ({ ...p, verdict: "BLOCKED", detail: "the website answered with a block (it probably refuses automatic checks); open it yourself" }))].map((p) => `${p.verdict}${p.status ? ` ${p.status}` : ""} ${where(p.url)}: ${p.detail ?? ""}${p.missing_params ? ` (missing ${p.missing_params.join(", ")})` : ""}${p.lands_on_other_site ? ` (ends on ${p.lands_on_other_site})` : ""} [${p.ads?.length ?? 0} ad(s), e.g. ${p.ads?.[0]?.ad ?? "?"}]`),
32
+ snap_pixel_health: (d) => (d.top_priority_issues ?? []).slice(0, 10).map((i) => (typeof i === "string" ? i : JSON.stringify(i))),
33
+ snap_catalog_feed_status: (d) => (d.catalogs_detail ?? []).flatMap((c) => c.feeds.filter((f) => f.problems.length || f.upload_errors).map((f) => `${c.catalog} / ${f.name}: ${[...f.problems, ...(f.upload_issues ?? [])].slice(0, 4).join("; ")}`)).slice(0, 10),
34
+ snap_audience_health: (d) => [
35
+ ...(d.important_used_by_active_squads ?? []).slice(0, 10).map((p) => `USED NOW by ${p.used_by_active_squads} active ad squad(s): ${p.name} (${p.source_type}, ${p.size} people): ${p.flags.map((f) => f.code).join(", ")}`),
36
+ ...Object.entries(d.by_flag ?? {}).map(([k, n]) => `${k}: ${n} audience(s)`),
37
+ ],
38
+ snap_review_issues: (d) => (d.items ?? []).slice(0, 10).map((i) => `${i.name}: ${String(i.reasons?.[0] ?? i.review_status ?? "").slice(0, 120)}`),
39
+ snap_health_check: (d) => Object.entries(d.issue_counts ?? {}).map(([k, n]) => `${k}: ${n} ad squad(s)`),
40
+ };
41
+
14
42
  // Each check: the tool, its arguments, what it needs from the settings (else it is skipped), and a short summary of the answer.
15
43
  export function checksFor({ start, end, hasPixel, hasCountry }) {
16
44
  return [
@@ -42,9 +70,9 @@ export function checksFor({ start, end, hasPixel, hasCountry }) {
42
70
  }
43
71
 
44
72
  // 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);
73
+ 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, (m) => (/^[A-Z][A-Z0-9]*(_[A-Z0-9]+)+$/.test(m) ? m : "[hidden]")).replace(/\s+/g, " ").slice(0, 220);
46
74
 
47
- export async function runVerify({ client, env = process.env, now = new Date(), log = console.log }) {
75
+ export async function runVerify({ client, env = process.env, now = new Date(), log = console.log, details = false }) {
48
76
  // Everything below runs with writes switched off, whatever the settings say.
49
77
  const settings = { ...env, SNAP_READ_ONLY: "1", SNAP_TOOLSETS: "", SNAP_LOG_FILE: env.SNAP_LOG_FILE ?? "" };
50
78
  const policy = loadPolicy(settings);
@@ -69,7 +97,8 @@ export async function runVerify({ client, env = process.env, now = new Date(), l
69
97
  const r = await mcp.callTool({ name: c.tool, arguments: c.args }, undefined, { timeout: 5 * 60_000 });
70
98
  const text = r.content?.[0]?.text ?? "";
71
99
  // 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." };
100
+ if (r.isError && c.tool === "snap_competitor_ads" && /429|too many requests/i.test(text)) row = { tool: c.tool, status: "SKIP", detail: "Snap's public Ads Gallery is rate-limited right now; try again in a few minutes" };
101
+ else 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
102
  else if (r.isError) row = { tool: c.tool, status: "FAIL", detail: tidy(text) };
74
103
  else {
75
104
  let data = null;
@@ -84,7 +113,7 @@ export async function runVerify({ client, env = process.env, now = new Date(), l
84
113
  } catch {
85
114
  detail = "ok";
86
115
  }
87
- row = { tool: c.tool, status: "OK", detail };
116
+ row = { tool: c.tool, status: "OK", detail, ...(details && DETAILS[c.tool] ? { lines: (() => { try { return DETAILS[c.tool](data ?? {}).map(tidy); } catch { return []; } })() } : {}) };
88
117
  }
89
118
  } catch (e) {
90
119
  row = { tool: c.tool, status: "FAIL", detail: tidy(e.message) };
@@ -93,6 +122,16 @@ export async function runVerify({ client, env = process.env, now = new Date(), l
93
122
  results.push(row);
94
123
  log(` ${row.status === "OK" ? "✓" : row.status === "SKIP" ? "-" : "✗"} ${row.tool.padEnd(28)} ${row.detail}`);
95
124
  }
125
+ if (details) {
126
+ const withLines = results.filter((r) => r.lines?.length);
127
+ log("");
128
+ log("Details");
129
+ if (!withLines.length) log(" (nothing to show)");
130
+ for (const r of withLines) {
131
+ log(` ${r.tool}`);
132
+ for (const l of r.lines) log(` - ${l}`);
133
+ }
134
+ }
96
135
  await mcp.close();
97
136
  const failed = results.filter((r) => r.status === "FAIL").length;
98
137
  log("");