ads-mcp-for-snapchat 0.9.0 → 0.9.2
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 +25 -2
- package/README.md +18 -6
- 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 +60 -15
- package/src/cli.js +11 -0
- package/src/hygiene.js +29 -5
- 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 +141 -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,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.9.2 (2026-11-15)
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
- `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.
|
|
9
|
+
- `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.
|
|
10
|
+
- `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.
|
|
11
|
+
- `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).
|
|
12
|
+
|
|
13
|
+
## 0.9.1 (2026-11-15)
|
|
14
|
+
|
|
15
|
+
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.
|
|
16
|
+
|
|
17
|
+
- **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.
|
|
18
|
+
- **`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.
|
|
19
|
+
- `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.
|
|
20
|
+
- **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.
|
|
21
|
+
- `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.
|
|
22
|
+
- 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.
|
|
23
|
+
- `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).
|
|
24
|
+
- `broker/ASK-SNAP.md`: the message to send to Snap before announcing the shared login.
|
|
25
|
+
|
|
3
26
|
## 0.9.0 (2026-11-15)
|
|
4
27
|
|
|
5
28
|
- **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 +92,7 @@ Everything below is built from Snap's documentation and mocked tests and is not
|
|
|
69
92
|
## 0.4.1 (2026-11-14)
|
|
70
93
|
|
|
71
94
|
- 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/
|
|
95
|
+
- 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
96
|
- 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
97
|
|
|
75
98
|
## 0.4.0 (2026-11-14)
|
|
@@ -77,7 +100,7 @@ Everything below is built from Snap's documentation and mocked tests and is not
|
|
|
77
100
|
- 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
101
|
- 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
102
|
- `server.json` for the official MCP Registry (`io.github.Usame794/ads-mcp-for-snapchat`).
|
|
80
|
-
- Repository links point to `Usame794/
|
|
103
|
+
- Repository links point to `Usame794/snapchat-ads-mcp`.
|
|
81
104
|
- Verified live on a real account: a COLLECTION ad (paused).
|
|
82
105
|
|
|
83
106
|
## 0.3.2 (2026-11-14)
|
package/README.md
CHANGED
|
@@ -26,14 +26,19 @@ 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; 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
|
+
|
|
29
32
|
## Easiest: log in with Snapchat (no OAuth app)
|
|
30
|
-
|
|
33
|
+
**Not available yet.** The code is built and tested, but no shared login service has been deployed and Snap has not yet been asked whether a shared app may serve other advertisers. Until then, connect with your own Snapchat app (next section: about 5 minutes, and `setup` walks you through it).
|
|
34
|
+
|
|
35
|
+
Once a service exists (see `broker/README.md` and `PRIVACY.md`; you can also run your own), you will not need an 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.
|
|
31
36
|
|
|
32
37
|
## Easy setup (about 5 minutes)
|
|
33
38
|
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
39
|
|
|
35
40
|
**Claude Desktop (no terminal):**
|
|
36
|
-
1. Download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/
|
|
41
|
+
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
42
|
2. Enter the Client ID and Client Secret, your highest daily budget and (optional) your main country. Leave **Read-only** on for now.
|
|
38
43
|
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
44
|
4. Quit and reopen Claude Desktop. Ask: "call snap_ping".
|
|
@@ -86,6 +91,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
86
91
|
| `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
92
|
| `SNAP_ACCOUNT_CURRENCY` | not set | If set (e.g. `USD`), writes are refused unless the ad account uses that currency |
|
|
88
93
|
| `SNAP_READ_ONLY` | 0 | `1` = previews and reads only |
|
|
94
|
+
| `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
95
|
| `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
96
|
| `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
97
|
| `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. |
|
|
@@ -196,7 +202,7 @@ From an npm install, use `npx -y ads-mcp-for-snapchat check | weekly-report` ins
|
|
|
196
202
|
## Requirements
|
|
197
203
|
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).
|
|
198
204
|
|
|
199
|
-
Each user runs this server locally with their own
|
|
205
|
+
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.
|
|
200
206
|
|
|
201
207
|
## Setup (one time)
|
|
202
208
|
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.
|
|
@@ -264,11 +270,17 @@ Verified on the maintainer's own ad account. Anything not listed here is covered
|
|
|
264
270
|
|
|
265
271
|
**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).
|
|
266
272
|
|
|
267
|
-
**
|
|
273
|
+
**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.
|
|
274
|
+
|
|
275
|
+
**Not verified live:**
|
|
276
|
+
- 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.
|
|
277
|
+
- 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.
|
|
278
|
+
- The shared login service against the real Snapchat login (it is tested against a fake one; deploy it and follow `broker/README.md` step 5).
|
|
279
|
+
- 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.
|
|
268
280
|
|
|
269
281
|
## Not built
|
|
270
|
-
- A hosted multi-user
|
|
271
|
-
- Lens, App Install, Deep Link
|
|
282
|
+
- 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.
|
|
283
|
+
- 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).
|
|
272
284
|
- Anything that spends money without a separate, explicit enable step.
|
|
273
285
|
|
|
274
286
|
## Development
|
|
@@ -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.2",
|
|
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,35 @@ 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
|
-
|
|
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);
|
|
124
158
|
const counts = {};
|
|
125
159
|
for (const r of rows) counts[r.verdict] = (counts[r.verdict] ?? 0) + 1;
|
|
160
|
+
const outOfTime = timeUp();
|
|
126
161
|
return {
|
|
162
|
+
active_campaigns: activeCampaigns.length,
|
|
163
|
+
active_squads: squads.length,
|
|
127
164
|
active_ads: active.length,
|
|
128
165
|
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
|
-
...(
|
|
166
|
+
links_checked: rows.filter((r) => r.verdict !== "NOT_CHECKED").length,
|
|
167
|
+
...(all.length > toCheck.length ? { links_not_checked: all.length - toCheck.length, warning: `Only the first ${maxUrls} distinct links were looked at.` } : {}),
|
|
168
|
+
...(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.` } : {}),
|
|
169
|
+
...(campaigns.complete ? {} : { warning_incomplete: "The campaign list was INCOMPLETE; some ads were not looked at." }),
|
|
132
170
|
by_verdict: counts,
|
|
133
171
|
problems,
|
|
134
|
-
|
|
135
|
-
|
|
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,
|
|
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.",
|
|
136
175
|
};
|
|
137
176
|
}
|
|
138
177
|
|
|
@@ -189,7 +228,13 @@ export async function anomalyCheck(client, { adAccountId, offset = "+00:00", bas
|
|
|
189
228
|
|
|
190
229
|
// ---------- Blended ROAS ----------
|
|
191
230
|
|
|
192
|
-
|
|
231
|
+
// Account totals for a window, in the same shape dailyReport gives (built from the campaign breakdown: see report.js).
|
|
232
|
+
async function accountReport(client, { id, start_time, end_time }) {
|
|
233
|
+
const { stats, incomplete } = await accountTotals(client, id, { start_time, end_time, fields: "spend,conversion_purchases,conversion_purchases_value" });
|
|
234
|
+
return { ...totalsOf([stats]), ...(incomplete ? { warning: "Snap returned more pages than were read; the totals are a lower bound." } : {}) };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export async function blendedRoas(client, { adAccountId, offset = "+00:00", storeRevenue, storeOrders, days = 7, startDate, endDate, now = new Date(), report = accountReport }) {
|
|
193
238
|
let start;
|
|
194
239
|
let end;
|
|
195
240
|
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); add --details for the specifics behind each problem
|
|
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(), details: rest.includes("--details") });
|
|
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;
|
|
@@ -124,15 +125,22 @@ export async function audienceHealth(client, { adAccountId, now = Date.now(), st
|
|
|
124
125
|
const age = daysSince(s.updated_at ?? s.created_at, now);
|
|
125
126
|
const flags = [];
|
|
126
127
|
if (status && status !== "READY") flags.push({ code: "NOT_TARGETABLE", detail: `Status ${status}: it cannot be used in targeting yet.` });
|
|
127
|
-
if (size
|
|
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.` });
|
|
128
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.` });
|
|
129
131
|
const uses = usedBy.get(s.id) ?? 0;
|
|
130
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 } : {}) };
|
|
131
133
|
});
|
|
132
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);
|
|
133
139
|
return {
|
|
134
140
|
audiences: rows.length,
|
|
135
141
|
with_problems: problems.length,
|
|
142
|
+
by_flag: byFlag,
|
|
143
|
+
important_used_by_active_squads: important.slice(0, 20),
|
|
136
144
|
used_by_active_squads: rows.filter((r) => r.used_by_active_squads > 0).length,
|
|
137
145
|
unused_audiences: rows.filter((r) => r.unused).length,
|
|
138
146
|
active_squads_read: squadsRead,
|
|
@@ -177,8 +185,13 @@ export async function funnelReport(client, { adAccountId, entity = "adaccount",
|
|
|
177
185
|
if (!Number.isInteger(days) || days < 1 || days > 31) throw new Error("days must be a whole number from 1 to 31");
|
|
178
186
|
const end = localClock(now, offset).todayStart;
|
|
179
187
|
const start = shiftIso(end, -days * DAY);
|
|
180
|
-
const
|
|
181
|
-
|
|
188
|
+
const fields = FUNNEL.map(([, f]) => f).join(",");
|
|
189
|
+
let stats;
|
|
190
|
+
if (entity === "adaccount") stats = (await accountTotals(client, adAccountId, { start_time: start, end_time: end, fields })).stats;
|
|
191
|
+
else {
|
|
192
|
+
const data = await client.request("GET", `/${base}/${id}/stats`, { query: { granularity: "TOTAL", start_time: start, end_time: end, fields, omit_empty: true } });
|
|
193
|
+
stats = data.total_stats?.[0]?.total_stat?.stats ?? {};
|
|
194
|
+
}
|
|
182
195
|
return {
|
|
183
196
|
window: { start_time: start, end_time: end, days },
|
|
184
197
|
...buildFunnel(stats),
|
|
@@ -188,6 +201,16 @@ export async function funnelReport(client, { adAccountId, entity = "adaccount",
|
|
|
188
201
|
|
|
189
202
|
// ---------- Catalog feed status ----------
|
|
190
203
|
|
|
204
|
+
// How many days apart uploads are expected, from the feed's schedule (unknown: null).
|
|
205
|
+
export function scheduleDays(schedule) {
|
|
206
|
+
if (!schedule) return null;
|
|
207
|
+
const n = Number(schedule.interval_count) || 1;
|
|
208
|
+
const unit = String(schedule.interval_type ?? "").toUpperCase();
|
|
209
|
+
return unit === "HOURLY" ? n / 24 : unit === "DAILY" ? n : unit === "WEEKLY" ? n * 7 : unit === "MONTHLY" ? n * 30 : null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
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);
|
|
213
|
+
|
|
191
214
|
export function judgeUpload(u) {
|
|
192
215
|
const issues = [];
|
|
193
216
|
const status = u.status;
|
|
@@ -215,7 +238,7 @@ export async function feedStatus(client, { organizationId, now = Date.now() }) {
|
|
|
215
238
|
const lastAge = last ? daysSince(last.updated_at ?? last.created_at, now) : null;
|
|
216
239
|
const problems = [];
|
|
217
240
|
if (!last) problems.push("No upload has completed yet.");
|
|
218
|
-
else if (lastAge > 2) problems.push(`The last completed upload was ${lastAge} days ago.`);
|
|
241
|
+
else if (lastAge > Math.max(2, 2 * (scheduleDays(feed.schedule) ?? 0))) problems.push(`The last completed upload was ${lastAge} days ago.`);
|
|
219
242
|
if (latest && latest.status && !["COMPLETE", "INITIALIZED", "IN_PROGRESS"].includes(latest.status)) problems.push(`The latest upload is ${latest.status}.`);
|
|
220
243
|
entry.feeds.push({
|
|
221
244
|
feed_id: feed.id,
|
|
@@ -225,6 +248,7 @@ export async function feedStatus(client, { organizationId, now = Date.now() }) {
|
|
|
225
248
|
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
249
|
latest_upload_status: latest?.status ?? null,
|
|
227
250
|
upload_issues: latest ? judgeUpload(latest).slice(0, 10) : [],
|
|
251
|
+
upload_errors: latest ? uploadErrorCount(latest) : 0,
|
|
228
252
|
problems,
|
|
229
253
|
});
|
|
230
254
|
}
|
|
@@ -232,7 +256,7 @@ export async function feedStatus(client, { organizationId, now = Date.now() }) {
|
|
|
232
256
|
}
|
|
233
257
|
return {
|
|
234
258
|
catalogs: out.length,
|
|
235
|
-
feeds_with_problems: out.flatMap((c) => c.feeds).filter((f) => f.problems.length || f.
|
|
259
|
+
feeds_with_problems: out.flatMap((c) => c.feeds).filter((f) => f.problems.length || f.upload_errors > 0).length,
|
|
236
260
|
catalogs_detail: out,
|
|
237
261
|
note: "The feed's own URL and password are never shown. Recommendations (such as missing app links) are not counted as problems.",
|
|
238
262
|
};
|
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.2" });
|
|
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,141 @@
|
|
|
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
|
+
// 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
|
+
|
|
42
|
+
// Each check: the tool, its arguments, what it needs from the settings (else it is skipped), and a short summary of the answer.
|
|
43
|
+
export function checksFor({ start, end, hasPixel, hasCountry }) {
|
|
44
|
+
return [
|
|
45
|
+
{ tool: "snap_ping", args: {}, show: (d) => `authorized as ${d.me?.display_name ?? d.me?.email ?? "your login"}; account ${d.ad_account ? "set" : "NOT set"}` },
|
|
46
|
+
{ tool: "snap_list_campaigns", args: { limit: 5 }, show: (d) => count(d) },
|
|
47
|
+
{ tool: "snap_list_adsquads", args: { limit: 5 }, show: (d) => count(d) },
|
|
48
|
+
{ tool: "snap_list_media", args: { limit: 3 }, show: (d) => count(d) },
|
|
49
|
+
{ tool: "snap_list_segments", args: { limit: 3 }, show: (d) => count(d) },
|
|
50
|
+
{ tool: "snap_spend_pacing", args: {}, show: (d) => `${d.today?.active_squads ?? "?"} active ad squads; month so far ${d.month?.month_to_date_spend ?? "?"}` },
|
|
51
|
+
{ 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` },
|
|
52
|
+
{ 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(", ")}` : ""}` },
|
|
53
|
+
{ 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})` : ""}` },
|
|
54
|
+
{ tool: "snap_billing_check", args: {}, show: (d) => `verdict ${d.verdict}; ${d.funding_sources?.length ?? 0} funding source(s)` },
|
|
55
|
+
{ tool: "snap_audience_health", args: {}, show: (d) => `${d.audiences} audiences, ${d.with_problems} with problems` },
|
|
56
|
+
{ tool: "snap_unused_media", args: { limit: 5 }, show: (d) => `${d.unused_count} of ${d.media_total} files unused${d.warning ? " (list cut: partial)" : ""}` },
|
|
57
|
+
{ 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` },
|
|
58
|
+
{ 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)" : ""}` },
|
|
59
|
+
{ 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` },
|
|
60
|
+
{ tool: "snap_review_issues", args: {}, show: (d) => `${d.shown ?? d.items?.length ?? 0} ad(s) not approved` },
|
|
61
|
+
{ tool: "snap_list_dynamic_templates", args: { limit: 5 }, show: (d) => count(d) },
|
|
62
|
+
{ 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"}` : ""}` },
|
|
63
|
+
{ tool: "snap_pixel_health", args: {}, needs: hasPixel, setting: "SNAP_PIXEL_ID", show: (d) => `${d.top_priority_issues?.length ?? 0} top-priority issue(s)` },
|
|
64
|
+
{ 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` },
|
|
65
|
+
{ tool: "snap_audience_size", args: {}, needs: hasCountry, setting: "SNAP_DEFAULT_COUNTRY", show: (d) => `${d.audience_size_min}-${d.audience_size_max} people (${d.verdict})` },
|
|
66
|
+
{ 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)"}` },
|
|
67
|
+
{ tool: "snap_competitor_ads", args: { advertiser: "Nike", status: "ACTIVE" }, show: (d) => `${d.count} ad(s) returned by the public Ads Gallery` },
|
|
68
|
+
{ tool: "snap_portfolio_summary", args: {}, show: (d) => (d.configured === false ? "not configured (optional: SNAP_PORTFOLIO_FILES)" : `${d.accounts?.length ?? 0} account(s)`) },
|
|
69
|
+
];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Printed output never includes ids or tokens: ids are shortened, long secret-looking strings are hidden.
|
|
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);
|
|
74
|
+
|
|
75
|
+
export async function runVerify({ client, env = process.env, now = new Date(), log = console.log, details = false }) {
|
|
76
|
+
// Everything below runs with writes switched off, whatever the settings say.
|
|
77
|
+
const settings = { ...env, SNAP_READ_ONLY: "1", SNAP_TOOLSETS: "", SNAP_LOG_FILE: env.SNAP_LOG_FILE ?? "" };
|
|
78
|
+
const policy = loadPolicy(settings);
|
|
79
|
+
const server = new McpServer({ name: "verify", version: "1" });
|
|
80
|
+
registerTools(server, client, settings);
|
|
81
|
+
const mcp = new Client({ name: "verify", version: "1" });
|
|
82
|
+
const [a, b] = InMemoryTransport.createLinkedPair();
|
|
83
|
+
await Promise.all([server.connect(a), mcp.connect(b)]);
|
|
84
|
+
const tools = new Map((await mcp.listTools()).tools.map((t) => [t.name, t]));
|
|
85
|
+
const end = localClock(now, policy.reportUtcOffset).todayStart;
|
|
86
|
+
const start = shiftIso(end, -7 * 86_400_000);
|
|
87
|
+
const checks = checksFor({ start, end, hasPixel: Boolean(settings.SNAP_PIXEL_ID), hasCountry: Boolean(settings.SNAP_DEFAULT_COUNTRY) });
|
|
88
|
+
const results = [];
|
|
89
|
+
for (const c of checks) {
|
|
90
|
+
const tool = tools.get(c.tool);
|
|
91
|
+
let row;
|
|
92
|
+
if (!tool) row = { tool: c.tool, status: "SKIP", detail: "tool is not available" };
|
|
93
|
+
else if (tool.annotations?.readOnlyHint !== true) row = { tool: c.tool, status: "SKIP", detail: "not read-only; never called here" };
|
|
94
|
+
else if ("needs" in c && !c.needs) row = { tool: c.tool, status: "SKIP", detail: `needs ${c.setting} in your settings` };
|
|
95
|
+
else {
|
|
96
|
+
try {
|
|
97
|
+
const r = await mcp.callTool({ name: c.tool, arguments: c.args }, undefined, { timeout: 5 * 60_000 });
|
|
98
|
+
const text = r.content?.[0]?.text ?? "";
|
|
99
|
+
// Snap refusing the normal login for the Conversions API test tools is a missing setting, not a fault.
|
|
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." };
|
|
102
|
+
else if (r.isError) row = { tool: c.tool, status: "FAIL", detail: tidy(text) };
|
|
103
|
+
else {
|
|
104
|
+
let data = null;
|
|
105
|
+
try {
|
|
106
|
+
data = JSON.parse(text);
|
|
107
|
+
} catch {
|
|
108
|
+
data = null;
|
|
109
|
+
}
|
|
110
|
+
let detail = "ok";
|
|
111
|
+
try {
|
|
112
|
+
detail = tidy(c.show(Array.isArray(data) ? data : data ?? {}) ?? "ok");
|
|
113
|
+
} catch {
|
|
114
|
+
detail = "ok";
|
|
115
|
+
}
|
|
116
|
+
row = { tool: c.tool, status: "OK", detail, ...(details && DETAILS[c.tool] ? { lines: (() => { try { return DETAILS[c.tool](data ?? {}).map(tidy); } catch { return []; } })() } : {}) };
|
|
117
|
+
}
|
|
118
|
+
} catch (e) {
|
|
119
|
+
row = { tool: c.tool, status: "FAIL", detail: tidy(e.message) };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
results.push(row);
|
|
123
|
+
log(` ${row.status === "OK" ? "✓" : row.status === "SKIP" ? "-" : "✗"} ${row.tool.padEnd(28)} ${row.detail}`);
|
|
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
|
+
}
|
|
135
|
+
await mcp.close();
|
|
136
|
+
const failed = results.filter((r) => r.status === "FAIL").length;
|
|
137
|
+
log("");
|
|
138
|
+
log(`${results.filter((r) => r.status === "OK").length} worked, ${failed} failed, ${results.filter((r) => r.status === "SKIP").length} skipped.`);
|
|
139
|
+
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.");
|
|
140
|
+
return { results, failed };
|
|
141
|
+
}
|