ads-mcp-for-snapchat 0.11.0 → 0.11.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 -1
- package/CHANGELOG.md +16 -0
- package/README.md +16 -3
- package/SECURITY.md +1 -0
- package/broker/worker.js +1 -1
- package/package.json +1 -1
- package/src/details.js +10 -10
- package/src/hygiene.js +6 -4
- package/src/index.js +11 -1
- package/src/media-dir.js +3 -3
- package/src/oauth.js +8 -2
- package/src/policy.js +3 -2
- package/src/profiles.js +11 -10
- package/src/setup.js +2 -2
- package/src/snap.js +18 -7
- package/src/tools.js +2 -2
package/.env.example
CHANGED
|
@@ -10,7 +10,7 @@ SNAP_MAX_DAILY_BUDGET=1000
|
|
|
10
10
|
# Optional: a warning (not a limit) in the preview when a change adds more daily budget than this.
|
|
11
11
|
# SNAP_WARN_DAILY_BUDGET=
|
|
12
12
|
# Optional: only read media and customer-list files from this folder (absolute path).
|
|
13
|
-
# SNAP_MEDIA_DIR=
|
|
13
|
+
# SNAP_MEDIA_DIR= (default: ~/SnapAds; an absolute folder path, or "any" to allow files from anywhere)
|
|
14
14
|
SNAP_MIN_DAILY_BUDGET=5
|
|
15
15
|
SNAP_MAX_BID=50
|
|
16
16
|
SNAP_MAX_BUDGET_INCREASE_PCT=100
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.11.2 (2026-11-26)
|
|
4
|
+
More fixes from the release audit.
|
|
5
|
+
|
|
6
|
+
- **Token refresh**: requests that run at the same time now share one refresh instead of each making their own (Snap may rotate the refresh token on every refresh, so parallel refreshes could leave an old one saved and force a reconnect). Retrying on server errors is now decided by the caller, not by whether the address contains `access_token`, so Conversions API test events are no longer repeated.
|
|
7
|
+
- **Local files are only read from one folder**: `~/SnapAds` by default (created if missing; the Desktop extension has a setting for it). Set `SNAP_MEDIA_DIR` to another folder, or to `any` to allow files from anywhere. If you uploaded from other folders before, move the files or set `SNAP_MEDIA_DIR`.
|
|
8
|
+
- **Hosted connector**: the consent page and README now say plainly that the approval code is not a human approval and that your AI app's permission prompt is the real one. (The connector already starts read-only; changes need a tick on the consent page.)
|
|
9
|
+
|
|
10
|
+
## 0.11.1 (2026-11-26)
|
|
11
|
+
Fixes from the release audit (read tools that did not match Snapchat's published API).
|
|
12
|
+
|
|
13
|
+
- **Invoices**: amounts (`amount_cent`, in cents), document numbers and statuses are now read, so an overdue invoice shows its amount and the unpaid total is right. Invoices are listed per ad account; the old note saying they belong to the billing center was wrong. The invoice PDF is no longer included in answers.
|
|
14
|
+
- **Transactions**: amounts (`total_amount`) are kept instead of dropped.
|
|
15
|
+
- **Public profiles**: the list is now requested from Snapchat's business API host, where it lives. It needs the `snapchat-profile-api` permission, which is off by default so a login can never fail for an app without it. To turn it on, set `SNAP_PROFILE_SCOPE=1` and connect again. Without it, profile ids are still read from existing creatives.
|
|
16
|
+
- **Removed** the lead count and sponsored content options of `snap_account_details`: Snapchat documents no such endpoints (use lead forms, and `snap_competitor_ads` for ads from the Ads Library).
|
|
17
|
+
- Lists ask Snapchat for at least 50 rows, its minimum page size.
|
|
18
|
+
|
|
3
19
|
## 0.11.0 (2026-11-26)
|
|
4
20
|
The hosted version grew up and the local one gets everything it learned: shorter answers, a first-run guide, more tools, and fixes found by real accounts.
|
|
5
21
|
|
package/README.md
CHANGED
|
@@ -17,6 +17,18 @@ An [MCP](https://modelcontextprotocol.io) server, available as a **hosted connec
|
|
|
17
17
|
|
|
18
18
|
This is **unofficial** and run by one independent maintainer. Before you sign in, read [what the hosted version stores](#hosted-version) (your Snapchat login token is kept, encrypted, so the service can act for you; you can delete everything with `snap_disconnect` and revoke the app in Snapchat at any time).
|
|
19
19
|
|
|
20
|
+
#### Using the hosted connector in ChatGPT (not tested yet)
|
|
21
|
+
ChatGPT can add a remote MCP server by its address. The menu names change from version to version, so look for the closest match. You need a ChatGPT plan that allows custom connectors (the paid plans; an organization admin may have to allow it on Business and Enterprise).
|
|
22
|
+
1. Open **Settings**, then **Apps** (called **Connectors** in some versions), then **Advanced settings**, and turn on **Developer mode**.
|
|
23
|
+
2. Choose **Create** (or **Add a custom app / connector**), and fill in:
|
|
24
|
+
- **Name:** `Ads MCP for Snapchat`
|
|
25
|
+
- **MCP server URL:** `https://ads-mcp-remote.ads-mcp.workers.dev/mcp`
|
|
26
|
+
- **Authentication:** **OAuth** (it registers itself automatically; leave any client ID and secret empty)
|
|
27
|
+
3. Tick the box that says you trust the application, and press **Create**. ChatGPT sends you to the sign-in page: sign in with Snapchat and finish within a few minutes, in one tab. Changes stay off unless you tick "allow changes" there.
|
|
28
|
+
4. In a **new chat**, open the **+** menu, choose **Developer mode** (or **More**), and switch on **Ads MCP for Snapchat**. Then ask: "Use snap_start_here".
|
|
29
|
+
|
|
30
|
+
This server works with ChatGPT's standard sign-in as far as we can check (the discovery and registration pages are tested), but **nobody has run it in ChatGPT yet**. If a step fails, please open an issue with the exact words ChatGPT shows. Cards may not appear in ChatGPT; every answer also arrives as text.
|
|
31
|
+
|
|
20
32
|
### Option 2: on your own computer (private, no third-party server)
|
|
21
33
|
Pick this if you do not want any server run by someone else to hold your Snapchat login.
|
|
22
34
|
|
|
@@ -33,7 +45,7 @@ Choose **1. Shared login**, log in with Snapchat, pick the ad account, and press
|
|
|
33
45
|
| Install | none | one file or one command |
|
|
34
46
|
| Where your login token lives | encrypted on the maintainer's Cloudflare account | only on your computer |
|
|
35
47
|
| Interactive cards in Claude | yes | not in the Claude Desktop extension |
|
|
36
|
-
| Works with ChatGPT and other remote-only apps | designed for it, not tested yet | no |
|
|
48
|
+
| Works with ChatGPT and other remote-only apps | designed for it, [setup steps](#using-the-hosted-connector-in-chatgpt-not-tested-yet), not tested yet | no |
|
|
37
49
|
| Folder uploads and customer-list files | no | yes |
|
|
38
50
|
|
|
39
51
|
## How this relates to Snap's own Ads MCP server
|
|
@@ -109,6 +121,7 @@ A second way to use the same tools with **nothing to install**: a connector you
|
|
|
109
121
|
What it does:
|
|
110
122
|
- You add the connector, sign in with Snapchat, and choose which ad account to use (`snap_connect`).
|
|
111
123
|
- **Read-only unless you tick "allow changes" on the consent page.** With changes allowed you get the same safety rules as the local version: everything created is paused, every change is previewed first with an approval code that works once for exactly that request, spending limits apply, and the change log lives in your own private database.
|
|
124
|
+
- **Who approves a change:** the approval code only proves the change was previewed and has not moved. It does not prove that you looked at it, because your AI app receives the code. On the hosted connector the real approval is **your AI app's permission prompt**, so ticking "allow changes" is only safe if you keep that prompt on for the tools that change things.
|
|
112
125
|
- Each person gets a separate private database. `snap_disconnect` deletes everything stored about you; also revoke the app in Snapchat Business Manager.
|
|
113
126
|
- Interactive cards (below) are shown in Claude with this version.
|
|
114
127
|
- **Works with apps that support remote MCP servers with sign-in** (OAuth with dynamic registration, which is what this server offers). It has been **tested with Claude only**. ChatGPT's custom connectors use the same standard, but it has **not been tested there**, and what ChatGPT allows depends on your plan.
|
|
@@ -142,7 +155,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
142
155
|
| `SNAP_MAX_RESPONSE_CHARS` | 100000 | Longest answer a tool returns; longer ones are cut with a note saying how to ask for less. |
|
|
143
156
|
| `SNAP_LEGACY_TOOLS` | off | Set to 1 to also show the old tool names that were merged into other tools (for example `snap_set_status_bulk`, `snap_bulk_set_budget`, `snap_report_daily`). They work as before and say which tool replaced them. Off by default, so the assistant sees fewer tools. |
|
|
144
157
|
| `SNAP_TOOLSETS_DEFAULT` | (none) | Set by the Claude Desktop extension to `core`: used only when `SNAP_TOOLSETS` is empty or was never saved, so upgraded installs start with the core tool set. A real `SNAP_TOOLSETS` value always wins. |
|
|
145
|
-
| `SNAP_MEDIA_DIR` |
|
|
158
|
+
| `SNAP_MEDIA_DIR` | `~/SnapAds` | The one folder `snap_upload_media` and `snap_upload_customer_list` may read files from (symbolic links are resolved first), so the server cannot be steered into reading other files on your computer. Created if missing. Set another absolute folder to change it, or `any` to allow files from anywhere. |
|
|
146
159
|
| `SNAP_WARN_DAILY_BUDGET` | (none) | Optional **warning** level, not a limit: a change that adds more than this daily budget shows a `budget_warning` in the preview. Without it, the preview still warns when a change adds more than twice your largest running ad squad (or, on an account with none running, more than half of `SNAP_MAX_DAILY_BUDGET`). |
|
|
147
160
|
| `SNAP_MIN_DAILY_BUDGET` | 5 | Lowest daily budget |
|
|
148
161
|
| `SNAP_MAX_BID` | 50 | Highest max bid |
|
|
@@ -204,7 +217,7 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
204
217
|
| `snap_billing_check` | read: ad account status, funding sources (card expiry, daily limit vs budgets, credit left) and a verdict |
|
|
205
218
|
| `snap_account_admin` | read: the ad account's settings (status, currency, time zone, billing type, spend cap), the organization's billing centers, and how many people have access with which role (emails masked); never changes anything |
|
|
206
219
|
| `snap_list_profiles` | read: the public profiles (brand identities) this login can use for creatives, with their ids; with only one, new creatives use it automatically |
|
|
207
|
-
| `snap_account_details` | read: pick one list with `what`: invoices, transactions, lead forms,
|
|
220
|
+
| `snap_account_details` | read: pick one list with `what`: invoices, transactions, lead forms, mobile apps, event details, interaction zones, offer disclaimers, phone numbers (masked), organizations, organization pixels, media stats, catalog products; contact details masked, and if Snapchat does not answer it says which paths were tried |
|
|
208
221
|
| `snap_upload_media_from_url` | write: upload a JPEG, PNG, MP4 or MOV (up to 32 MB) from a public https link, for the hosted version; previews first, and only public https addresses are fetched |
|
|
209
222
|
| `snap_unused_media` | read: uploaded images and videos no creative uses (never deletes) |
|
|
210
223
|
| `snap_audience_health` | read: audiences that are not targetable, tiny, stale, or unused by active ad squads |
|
package/SECURITY.md
CHANGED
|
@@ -19,6 +19,7 @@ Everything runs on your computer. These are the only outside addresses it contac
|
|
|
19
19
|
| Address | What for | What is sent |
|
|
20
20
|
|---|---|---|
|
|
21
21
|
| `adsapi.snapchat.com`, `accounts.snapchat.com` | The Snapchat Marketing API and login | Your requests, with your access token |
|
|
22
|
+
| `businessapi.snapchat.com` | Snapchat's Public Profile API (read-only list of public profiles) | The organization id, with your access token |
|
|
22
23
|
| `tr.snapchat.com` | Conversions API **test** events and their status (`snap_capi_*`) | Your access token and one test event; an email is hashed first. Real conversion events are never sent. |
|
|
23
24
|
| `adsapi.snapchat.com/v1/ads_library/...` | Competitor ads (`snap_competitor_ads`) | The advertiser name you search for. **No token**, nothing about your account. |
|
|
24
25
|
| The links of your own active ads | `snap_check_landing_pages` opens each link once | A plain request. Only `https`, never private, loopback or link-local addresses, and every redirect is checked again. No credentials. |
|
package/broker/worker.js
CHANGED
|
@@ -78,7 +78,7 @@ async function login(request, env) {
|
|
|
78
78
|
if (!validPort(port) || !checkPublicKey(pk) || !validNonce(nonce)) return page("Cannot start", "<h1>Cannot start the login</h1><p>The link is not valid. Start again from the setup command or the Claude Desktop extension.</p>", 400);
|
|
79
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
|
-
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();
|
|
81
|
+
auth.search = new URLSearchParams({ response_type: "code", client_id: env.SNAP_CLIENT_ID, redirect_uri: `${origin(request, env)}/callback`, scope: String(env.SNAP_PROFILE_SCOPE ?? "") === "1" ? "snapchat-marketing-api snapchat-profile-api" : "snapchat-marketing-api", state }).toString();
|
|
82
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
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ads-mcp-for-snapchat",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.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": "https://ads-mcp-for-snapchat-login.ads-mcp.workers.dev",
|
package/src/details.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// More read-only lists in one tool, so the AI's tool list stays short: invoices, transactions, lead forms, mobile apps, event details,
|
|
2
|
-
// interaction zones, offer disclaimers, phone numbers,
|
|
2
|
+
// interaction zones, offer disclaimers, phone numbers, organizations, organization pixels, media stats and catalog
|
|
3
3
|
// products. For each, Snapchat's path is tried in a few likely spellings; the first that answers wins, and if none does the answer says
|
|
4
4
|
// which were tried instead of failing. Nothing here writes. Contact details are masked: the answer lands in a chat history.
|
|
5
5
|
|
|
@@ -20,7 +20,12 @@ export function tidyRow(obj) {
|
|
|
20
20
|
const row = {};
|
|
21
21
|
for (const [k, v] of Object.entries(obj ?? {})) {
|
|
22
22
|
if (v === null || v === undefined) continue;
|
|
23
|
-
|
|
23
|
+
// Snap sends money as { amount, currency_type } (transactions). Keep it; every other nested object is dropped.
|
|
24
|
+
if (typeof v === "object" && !Array.isArray(v)) {
|
|
25
|
+
if (typeof v.amount === "number" && typeof v.currency_type === "string") { row[k] = v.amount; row.currency = v.currency_type; }
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (k === "invoice_content") continue; // a base64 PDF: far too large for a chat answer
|
|
24
29
|
if (Array.isArray(v)) {
|
|
25
30
|
if (v.length && v.every((x) => ["string", "number", "boolean"].includes(typeof x))) row[k] = SENSITIVE_KEY.test(k) ? v.slice(0, 5).map((x) => maskValue(k, x)) : v.slice(0, 8);
|
|
26
31
|
continue;
|
|
@@ -47,16 +52,14 @@ export function rowsOf(data) {
|
|
|
47
52
|
}
|
|
48
53
|
|
|
49
54
|
export const WHAT = {
|
|
50
|
-
invoices: { about: "invoices (billing history)", paths: ({ acc
|
|
55
|
+
invoices: { about: "invoices (billing history)", paths: ({ acc }) => [`/adaccounts/${acc}/invoices`] },
|
|
51
56
|
transactions: { about: "payments and charges", paths: ({ acc, org, funding }) => [`/adaccounts/${acc}/transactions`, `/organizations/${org}/transactions`, ...funding.map((f) => `/fundingsources/${f}/transactions`)] },
|
|
52
57
|
lead_forms: { about: "lead generation forms", paths: ({ acc }) => [`/adaccounts/${acc}/lead_generation_forms`, `/adaccounts/${acc}/leadgenforms`] },
|
|
53
|
-
leads_summary: { about: "how many leads came in (no contact details)", countOnly: true, paths: ({ acc }) => [`/adaccounts/${acc}/leads_report`, `/adaccounts/${acc}/leads`] },
|
|
54
58
|
mobile_apps: { about: "the organization's mobile apps", paths: ({ org, acc }) => [`/organizations/${org}/mobile_apps`, `/organizations/${org}/apps`, `/adaccounts/${acc}/mobile_apps`] },
|
|
55
59
|
event_details: { about: "event details (for event ads)", paths: ({ acc }) => [`/adaccounts/${acc}/event_details`] },
|
|
56
60
|
interaction_zones: { about: "interaction zones", paths: ({ acc }) => [`/adaccounts/${acc}/interaction_zones`] },
|
|
57
61
|
offer_disclaimers: { about: "offer disclaimers", paths: ({ acc }) => [`/adaccounts/${acc}/offer_disclaimers`] },
|
|
58
62
|
phone_numbers: { about: "phone numbers (for click-to-call ads), masked", paths: ({ org, acc }) => [`/organizations/${org}/phone_numbers`, `/adaccounts/${acc}/phone_numbers`] },
|
|
59
|
-
sponsored_content: { about: "sponsored content", paths: ({ acc, org }) => [`/adaccounts/${acc}/sponsored_content`, `/organizations/${org}/sponsored_content`] },
|
|
60
63
|
organizations: { about: "the organizations this login belongs to", paths: () => ["/me/organizations"] },
|
|
61
64
|
organization_pixels: { about: "pixels across the whole organization", paths: ({ org }) => [`/organizations/${org}/pixels`] },
|
|
62
65
|
media_stats: { about: "performance of one media file (pass id)", needsId: true, paths: ({ id }) => [`/media/${id}/stats`] },
|
|
@@ -69,17 +72,14 @@ export async function accountDetails(client, { adAccountId, what, id, limit = 50
|
|
|
69
72
|
if (spec.needsId && !id) throw new Error(`id is required for ${what} (${spec.about})`);
|
|
70
73
|
const acct = (await client.request("GET", `/adaccounts/${adAccountId}`)).adaccounts?.[0]?.adaccount ?? {};
|
|
71
74
|
const org = acct.organization_id;
|
|
72
|
-
const ctx = { acc: adAccountId, org, id, funding: acct.funding_source_ids ?? []
|
|
75
|
+
const ctx = { acc: adAccountId, org, id, funding: acct.funding_source_ids ?? [] };
|
|
73
76
|
if (!org && spec.paths({ ...ctx, org: "x" }).some((p) => p.includes("/organizations/x/")) && !spec.paths({ ...ctx, org: "x" }).some((p) => !p.includes("/organizations/x/"))) {
|
|
74
77
|
return { what, could_not_read: ["This ad account did not say which organization it belongs to."] };
|
|
75
78
|
}
|
|
76
|
-
if (what === "invoices" && org) {
|
|
77
|
-
try { ctx.billing = (await client.listPaged(`/organizations/${org}/billingcenters`, "billingcenter")).items.map((b) => b?.id).filter(Boolean).slice(0, 5); } catch { ctx.billing = []; }
|
|
78
|
-
}
|
|
79
79
|
const tried = [];
|
|
80
80
|
for (const path of spec.paths(ctx).filter((p) => !p.includes("/undefined/") && !p.includes("/organizations/undefined"))) {
|
|
81
81
|
try {
|
|
82
|
-
const data = await client.request("GET", path, { query: { limit: Math.min(Math.max(limit,
|
|
82
|
+
const data = await client.request("GET", path, { query: { limit: Math.min(Math.max(limit, 50), 200) } });
|
|
83
83
|
const rows = rowsOf(data);
|
|
84
84
|
return {
|
|
85
85
|
what,
|
package/src/hygiene.js
CHANGED
|
@@ -51,8 +51,10 @@ export function judgeInvoices(rows, now = Date.now()) {
|
|
|
51
51
|
if (!status || PAID.has(status)) continue;
|
|
52
52
|
const dueRaw = first(r, ["due_date", "payment_due_date", "due_at", "due", "due_time"]);
|
|
53
53
|
const due = dueRaw ? Date.parse(String(dueRaw)) : NaN;
|
|
54
|
-
|
|
55
|
-
const
|
|
54
|
+
// Snap's invoices carry amount_cent (cents); other shapes are read as whole currency units.
|
|
55
|
+
const cents = first(r, ["amount_cent"]);
|
|
56
|
+
const amount = cents !== undefined ? Number(cents) / 100 : Number(first(r, ["total", "total_amount", "amount_due", "amount", "balance"]));
|
|
57
|
+
const row = { number: first(r, ["document_number", "invoice_number", "number", "invoice_id", "id"]) ?? null, status, due: Number.isNaN(due) ? null : new Date(due).toISOString().slice(0, 10), amount: Number.isFinite(amount) ? amount : null, currency: first(r, ["currency"]) ?? null };
|
|
56
58
|
unpaid.push(row);
|
|
57
59
|
if (!Number.isNaN(due) && due < now) {
|
|
58
60
|
const days = Math.floor((now - due) / 86_400_000);
|
|
@@ -93,14 +95,14 @@ export async function billingCheck(client, { adAccountId, now = Date.now() }) {
|
|
|
93
95
|
}));
|
|
94
96
|
for (const r of rows) findings.push(...r.findings.map((x) => ({ ...x, funding_source: r.name ?? r.id })));
|
|
95
97
|
if (!rows.length && !sourcesError) findings.push({ severity: "WARN", code: "NO_FUNDING_SOURCE_READ", detail: "No funding source was found for this ad account (or this login may not be allowed to see them)." });
|
|
96
|
-
// Invoices
|
|
98
|
+
// Invoices are listed per ad account. Not being able to read them is not a problem here.
|
|
97
99
|
let invoices = null;
|
|
98
100
|
try {
|
|
99
101
|
const got = await accountDetails(client, { adAccountId, what: "invoices", limit: 100 });
|
|
100
102
|
if (got.items) {
|
|
101
103
|
const j = judgeInvoices(got.items, now);
|
|
102
104
|
findings.push(...j.findings);
|
|
103
|
-
invoices = { read: got.items.length, not_yet_collected: j.unpaid.length, not_yet_collected_total: j.unpaid_total, unpaid: j.unpaid.slice(0, 10), note: "Invoices
|
|
105
|
+
invoices = { read: got.items.length, not_yet_collected: j.unpaid.length, not_yet_collected_total: j.unpaid_total, unpaid: j.unpaid.slice(0, 10), note: "Invoices are listed per ad account (Snapchat creates them; only some login roles can read them)." };
|
|
104
106
|
}
|
|
105
107
|
} catch {
|
|
106
108
|
invoices = null;
|
package/src/index.js
CHANGED
|
@@ -7,6 +7,9 @@ import { loadPolicy } from "./policy.js";
|
|
|
7
7
|
import { SnapClient } from "./snap.js";
|
|
8
8
|
import { registerTools } from "./tools.js";
|
|
9
9
|
import { INSTRUCTIONS } from "./instructions.js";
|
|
10
|
+
import { mkdirSync } from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
10
13
|
|
|
11
14
|
// A Claude Desktop extension passes optional settings the person left empty as unreplaced "${user_config.x}" text on some
|
|
12
15
|
// versions. Treat those as unset, so an empty optional setting can never stop the server or become a real value.
|
|
@@ -15,6 +18,13 @@ loadEnv();
|
|
|
15
18
|
// The Desktop extension offers "core" when its Tool set setting is empty or was never saved (an upgraded install has no value for a
|
|
16
19
|
// setting added later). A real value, including "all", always wins.
|
|
17
20
|
if (!process.env.SNAP_TOOLSETS && process.env.SNAP_TOOLSETS_DEFAULT) process.env.SNAP_TOOLSETS = process.env.SNAP_TOOLSETS_DEFAULT;
|
|
21
|
+
// Local files are only read from one folder (~/SnapAds by default), so an instruction hidden in an ad name or a web page cannot make
|
|
22
|
+
// the server read some other file. SNAP_MEDIA_DIR=any switches this off; any other absolute path replaces the folder.
|
|
23
|
+
if (!String(process.env.SNAP_MEDIA_DIR ?? "").trim()) {
|
|
24
|
+
const dir = join(homedir(), "SnapAds");
|
|
25
|
+
try { mkdirSync(dir, { recursive: true }); } catch { /* the upload tools say so if it cannot be used */ }
|
|
26
|
+
process.env.SNAP_MEDIA_DIR = dir;
|
|
27
|
+
}
|
|
18
28
|
let policy;
|
|
19
29
|
try {
|
|
20
30
|
// Safety settings are validated before anything else. An invalid value stops the server instead of disabling a limit.
|
|
@@ -25,7 +35,7 @@ try {
|
|
|
25
35
|
}
|
|
26
36
|
// Snapshot of the non-secret settings taken at startup. Later edits to .env do not change limits or the target account.
|
|
27
37
|
const settings = { ...process.env };
|
|
28
|
-
const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.11.
|
|
38
|
+
const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.11.2", ...BRAND }, { instructions: INSTRUCTIONS });
|
|
29
39
|
// Only the OAuth credentials are re-read from .env when a token is needed, so replacing them does not require a restart.
|
|
30
40
|
const client = new SnapClient({ beforeToken: () => loadEnv(undefined, { override: true }), onNewRefreshToken: (t) => setEnvValue("SNAP_REFRESH_TOKEN", t), timeoutMs: policy.httpTimeoutMs });
|
|
31
41
|
registerTools(server, client, settings);
|
package/src/media-dir.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Folder allow-list for local files this server reads and uploads (media and customer lists), ~/SnapAds unless SNAP_MEDIA_DIR says otherwise. A file must be inside it after symbolic links are resolved,
|
|
2
2
|
// a file must be inside that folder after symbolic links are resolved, so an instruction hidden in an ad name or a web page
|
|
3
3
|
// cannot make the server read some other file on the computer.
|
|
4
4
|
import { realpathSync } from "node:fs";
|
|
@@ -11,7 +11,7 @@ export function assertFileAllowed(filePath, mediaDir) {
|
|
|
11
11
|
try {
|
|
12
12
|
root = realpathSync(mediaDir);
|
|
13
13
|
} catch {
|
|
14
|
-
throw new Error(`
|
|
14
|
+
throw new Error(`The upload folder (${mediaDir}) does not exist or cannot be read. Create it, or set SNAP_MEDIA_DIR to another folder.`);
|
|
15
15
|
}
|
|
16
16
|
try {
|
|
17
17
|
real = realpathSync(resolve(String(filePath)));
|
|
@@ -20,6 +20,6 @@ export function assertFileAllowed(filePath, mediaDir) {
|
|
|
20
20
|
}
|
|
21
21
|
const rel = relative(root, real);
|
|
22
22
|
if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
23
|
-
throw new Error(`That file is outside the folder
|
|
23
|
+
throw new Error(`That file is outside the upload folder (${mediaDir}). Put the file inside that folder and try again (SNAP_MEDIA_DIR changes the folder; SNAP_MEDIA_DIR=any allows files from anywhere).`);
|
|
24
24
|
}
|
|
25
25
|
}
|
package/src/oauth.js
CHANGED
|
@@ -11,10 +11,16 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
|
11
11
|
export const newState = () => `ads-mcp-${randomBytes(9).toString("base64url")}`;
|
|
12
12
|
export const looksLikeClientId = (text) => UUID.test(String(text).trim());
|
|
13
13
|
|
|
14
|
-
export
|
|
14
|
+
export const MARKETING_SCOPE = "snapchat-marketing-api";
|
|
15
|
+
export const PROFILE_SCOPE = "snapchat-profile-api";
|
|
16
|
+
// The Public Profile API needs its own scope. It is opt-in (SNAP_PROFILE_SCOPE=1) because Snap only grants it to OAuth apps that were
|
|
17
|
+
// approved for it; asking for it from an app that was not would make the whole login fail.
|
|
18
|
+
export const scopeFor = (env = {}) => (String(env.SNAP_PROFILE_SCOPE ?? "") === "1" ? `${MARKETING_SCOPE} ${PROFILE_SCOPE}` : MARKETING_SCOPE);
|
|
19
|
+
|
|
20
|
+
export function authorizeUrl({ clientId, redirectUri = DEFAULT_REDIRECT, state, scope = MARKETING_SCOPE }) {
|
|
15
21
|
if (!looksLikeClientId(clientId)) throw new Error("The Client ID should look like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (from Business Details > OAuth Apps).");
|
|
16
22
|
const u = new URL(AUTHORIZE_URL);
|
|
17
|
-
u.search = new URLSearchParams({ response_type: "code", client_id: clientId.trim(), redirect_uri: redirectUri, scope
|
|
23
|
+
u.search = new URLSearchParams({ response_type: "code", client_id: clientId.trim(), redirect_uri: redirectUri, scope, state }).toString();
|
|
18
24
|
return u.toString();
|
|
19
25
|
}
|
|
20
26
|
|
package/src/policy.js
CHANGED
|
@@ -70,8 +70,9 @@ export function loadPolicy(env = process.env) {
|
|
|
70
70
|
let mediaDir = null;
|
|
71
71
|
if (env.SNAP_MEDIA_DIR !== undefined && String(env.SNAP_MEDIA_DIR).trim() !== "") {
|
|
72
72
|
const d = String(env.SNAP_MEDIA_DIR).trim();
|
|
73
|
-
if (
|
|
74
|
-
else
|
|
73
|
+
if (d.toLowerCase() === "any") mediaDir = null; // the owner chose to allow files from anywhere
|
|
74
|
+
else if (/^(\/|[A-Za-z]:[\\/])/.test(d)) mediaDir = d;
|
|
75
|
+
else errors.push("SNAP_MEDIA_DIR must be an absolute folder path (media and customer-list files must be inside it), or \"any\" to allow files from anywhere.");
|
|
75
76
|
}
|
|
76
77
|
let warnDailyBudget = null;
|
|
77
78
|
if (env.SNAP_WARN_DAILY_BUDGET !== undefined && String(env.SNAP_WARN_DAILY_BUDGET).trim() !== "") {
|
package/src/profiles.js
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
// Public profiles (the brand identity an ad shows). A creative needs one. People do not know the profile id, so this lists them and,
|
|
2
2
|
// when the organization has exactly one, uses it without asking. Read-only.
|
|
3
3
|
const reason = (e) => String(e?.message ?? e).replace(/\s+/g, " ").slice(0, 140);
|
|
4
|
-
const pick = (row) => (row && typeof row === "object" && row.profile && typeof row.profile === "object" ? row.profile : row);
|
|
5
4
|
|
|
6
5
|
export async function listProfiles(client, { adAccountId }) {
|
|
7
6
|
const acct = (await client.request("GET", `/adaccounts/${adAccountId}`)).adaccounts?.[0]?.adaccount ?? {};
|
|
8
|
-
const paths = [];
|
|
9
|
-
if (acct.organization_id) paths.push(`/organizations/${acct.organization_id}/public_profiles`, `/organizations/${acct.organization_id}/profiles`);
|
|
10
|
-
paths.push(`/adaccounts/${adAccountId}/public_profiles`, `/adaccounts/${adAccountId}/profiles`);
|
|
11
7
|
const failures = [];
|
|
12
|
-
|
|
8
|
+
// Snap documents the public profile list on its business API host (GET /v1/organizations/{id}/public_profiles). It needs the
|
|
9
|
+
// snapchat-profile-api scope, so a login made without it is refused and the creatives below are used instead.
|
|
10
|
+
if (acct.organization_id) {
|
|
11
|
+
const path = `/organizations/${acct.organization_id}/public_profiles`;
|
|
13
12
|
try {
|
|
14
|
-
const { items } = await client.listPaged(path, "
|
|
15
|
-
const rows = items.
|
|
16
|
-
return { profiles: rows, source: path };
|
|
13
|
+
const { items } = await client.listPaged(path, "public_profile", { business: true, query: { limit: 50 } });
|
|
14
|
+
const rows = items.filter((p) => p && p.id).map((p) => ({ id: p.id, name: p.display_name ?? null, ...(p.snap_user_name ? { username: p.snap_user_name } : {}), ...(p.profile_type ? { type: p.profile_type } : {}) }));
|
|
15
|
+
return { profiles: rows, source: `businessapi.snapchat.com${path}` };
|
|
17
16
|
} catch (e) {
|
|
18
|
-
failures.push(
|
|
17
|
+
failures.push(`businessapi${path}: ${reason(e)}`);
|
|
19
18
|
}
|
|
19
|
+
} else {
|
|
20
|
+
failures.push("This ad account did not say which organization it belongs to.");
|
|
20
21
|
}
|
|
21
22
|
// No list was offered. Every creative already made in this ad account names the public profile it shows (profile_properties.profile_id),
|
|
22
23
|
// so the profiles in use can be read from the creatives. Only ids are known this way, not names.
|
|
@@ -29,7 +30,7 @@ export async function listProfiles(client, { adAccountId }) {
|
|
|
29
30
|
}
|
|
30
31
|
if (counts.size) {
|
|
31
32
|
const rows = [...counts].sort((a, b) => b[1] - a[1]).map(([id, n]) => ({ id, name: null, used_by_creatives: n }));
|
|
32
|
-
return { profiles: rows, source: "read from this ad account's existing creatives (
|
|
33
|
+
return { profiles: rows, source: "read from this ad account's existing creatives (the profile list was not available to this login: it needs the profile permission, see the README, so only ids are shown)", failures };
|
|
33
34
|
}
|
|
34
35
|
} catch (e) {
|
|
35
36
|
failures.push(`creatives: ${reason(e)}`);
|
package/src/setup.js
CHANGED
|
@@ -8,7 +8,7 @@ import { join } from "node:path";
|
|
|
8
8
|
import { createInterface } from "node:readline";
|
|
9
9
|
import { envFile, ROOT, setEnvValue, dataDir } from "./env.js";
|
|
10
10
|
import { secretProblems } from "./clipboard.js";
|
|
11
|
-
import { authorizeUrl, DEFAULT_REDIRECT, exchangeCode, extractCode, listAdAccounts, looksLikeClientId, newState } from "./oauth.js";
|
|
11
|
+
import { authorizeUrl, DEFAULT_REDIRECT, exchangeCode, extractCode, listAdAccounts, looksLikeClientId, newState, scopeFor } from "./oauth.js";
|
|
12
12
|
import { SnapClient } from "./snap.js";
|
|
13
13
|
import { brokerUrlFrom, startBrokerLogin } from "./broker.js";
|
|
14
14
|
import { init } from "./init.js";
|
|
@@ -168,7 +168,7 @@ export async function runSetup({ io, file = envFile(), fetchImpl = fetch, open =
|
|
|
168
168
|
token = null;
|
|
169
169
|
for (let i = 0; i < 3 && !token; i++) {
|
|
170
170
|
const state = newState();
|
|
171
|
-
const url = authorizeUrl({ clientId, redirectUri, state });
|
|
171
|
+
const url = authorizeUrl({ clientId, redirectUri, state, scope: scopeFor(process.env) });
|
|
172
172
|
const opened = open(url);
|
|
173
173
|
say(opened ? " Your browser opened. Log in to Snapchat and click Continue." : " Open this link, log in to Snapchat and click Continue:");
|
|
174
174
|
if (!opened) say(` ${url}`);
|
package/src/snap.js
CHANGED
|
@@ -4,6 +4,7 @@ import { fixFor } from "./snap-errors.js";
|
|
|
4
4
|
const API = "https://adsapi.snapchat.com/v1";
|
|
5
5
|
const TOKEN_URL = "https://accounts.snapchat.com/login/oauth2/access_token";
|
|
6
6
|
const TR = "https://tr.snapchat.com"; // Conversions API test-event tools
|
|
7
|
+
const BUSINESS = "https://businessapi.snapchat.com/v1"; // Public Profile API (read-only)
|
|
7
8
|
|
|
8
9
|
// Fields the API returns but rejects (or ignores) on update.
|
|
9
10
|
const READ_ONLY = [
|
|
@@ -77,6 +78,7 @@ export const ENTITIES = {
|
|
|
77
78
|
member: { plural: "members", singular: "member", getPath: (id) => `/members/${id}` },
|
|
78
79
|
role: { plural: "roles", singular: "role", getPath: (id) => `/roles/${id}` },
|
|
79
80
|
profile: { plural: "profiles", singular: "profile", getPath: (id) => `/profiles/${id}` },
|
|
81
|
+
public_profile: { plural: "public_profiles", singular: "public_profile", getPath: (id) => `/public_profiles/${id}` },
|
|
80
82
|
catalog: {
|
|
81
83
|
plural: "catalogs",
|
|
82
84
|
singular: "catalog",
|
|
@@ -183,9 +185,10 @@ export class SnapClient {
|
|
|
183
185
|
|
|
184
186
|
// Reads (and the token call) retry on 429/5xx and network errors. Writes retry ONLY on 429, which Snap sends before
|
|
185
187
|
// processing, so a create/claim is never repeated by accident.
|
|
186
|
-
async fetchRetry(url, opts = {}, { timeoutMs = this.timeoutMs } = {}) {
|
|
188
|
+
async fetchRetry(url, opts = {}, { timeoutMs = this.timeoutMs, idempotent = false } = {}) {
|
|
187
189
|
const method = (opts.method ?? "GET").toUpperCase();
|
|
188
|
-
|
|
190
|
+
// Only reads, and calls the caller says are repeatable (the token refresh), are retried on 5xx and network errors. Never decided from the URL.
|
|
191
|
+
const safe = method === "GET" || idempotent;
|
|
189
192
|
let last;
|
|
190
193
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
191
194
|
try {
|
|
@@ -221,8 +224,15 @@ export class SnapClient {
|
|
|
221
224
|
}
|
|
222
225
|
}
|
|
223
226
|
|
|
227
|
+
// One refresh at a time: requests that run in parallel (dashboards fan out) share it. Snap may rotate the refresh token on each
|
|
228
|
+
// refresh, so several refreshes at once could leave a stale one saved.
|
|
224
229
|
async accessToken() {
|
|
225
230
|
if (this.token && Date.now() < this.tokenExpiry - 60_000) return this.token;
|
|
231
|
+
this.refreshing ??= this.refreshAccessToken().finally(() => { this.refreshing = null; });
|
|
232
|
+
return this.refreshing;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async refreshAccessToken() {
|
|
226
236
|
this.beforeToken?.();
|
|
227
237
|
const { SNAP_CLIENT_ID, SNAP_CLIENT_SECRET, SNAP_REFRESH_TOKEN } = this.env;
|
|
228
238
|
// Shared login: no app secret on this computer; the login service holds it and swaps the refresh token.
|
|
@@ -248,7 +258,7 @@ export class SnapClient {
|
|
|
248
258
|
client_secret: SNAP_CLIENT_SECRET,
|
|
249
259
|
refresh_token: SNAP_REFRESH_TOKEN,
|
|
250
260
|
}),
|
|
251
|
-
});
|
|
261
|
+
}, { idempotent: true });
|
|
252
262
|
const data = await res.json().catch(() => ({}));
|
|
253
263
|
if (!res.ok || !data.access_token) {
|
|
254
264
|
throw new Error(`Snap token refresh failed (${res.status}): ${data.error_description || data.error || "no detail"}`);
|
|
@@ -259,8 +269,9 @@ export class SnapClient {
|
|
|
259
269
|
return this.token;
|
|
260
270
|
}
|
|
261
271
|
|
|
262
|
-
async request(method, path, { query, body } = {}) {
|
|
263
|
-
|
|
272
|
+
async request(method, path, { query, body, business = false } = {}) {
|
|
273
|
+
if (business && method !== "GET") throw new Error("The business API host is read-only here.");
|
|
274
|
+
const url = new URL((business ? BUSINESS : API) + path);
|
|
264
275
|
for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
|
|
265
276
|
const send = async () =>
|
|
266
277
|
this.fetchRetry(url, {
|
|
@@ -336,11 +347,11 @@ export class SnapClient {
|
|
|
336
347
|
|
|
337
348
|
// Reads a list endpoint page by page. Returns { items, complete }. `complete` is false when the page limit was reached or a
|
|
338
349
|
// next-page link could not be followed; callers that need the whole list (safety checks) must treat that as an error.
|
|
339
|
-
async listPaged(path, entity, { query = {}, maxPages = MAX_LIST_PAGES } = {}) {
|
|
350
|
+
async listPaged(path, entity, { query = {}, maxPages = MAX_LIST_PAGES, business = false } = {}) {
|
|
340
351
|
const items = [];
|
|
341
352
|
let cursor;
|
|
342
353
|
for (let page = 0; page < maxPages; page++) {
|
|
343
|
-
const data = await this.request("GET", path, { query: { limit: 500, ...query, cursor } });
|
|
354
|
+
const data = await this.request("GET", path, { query: { limit: 500, ...query, cursor }, business });
|
|
344
355
|
items.push(...SnapClient.unwrap(data, entity));
|
|
345
356
|
const next = data.paging?.next_link;
|
|
346
357
|
if (!next) return { items, complete: true };
|
package/src/tools.js
CHANGED
|
@@ -3,7 +3,7 @@ import { randomInt } from "node:crypto";
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { SnapClient } from "./snap.js";
|
|
5
5
|
import { envFile, setEnvValue } from "./env.js";
|
|
6
|
-
import { authorizeUrl, DEFAULT_REDIRECT, exchangeCode, extractCode, listAdAccounts, newState, pickAccount } from "./oauth.js";
|
|
6
|
+
import { authorizeUrl, DEFAULT_REDIRECT, exchangeCode, extractCode, listAdAccounts, newState, pickAccount, scopeFor } from "./oauth.js";
|
|
7
7
|
import { executeChange, LOG_FILE, BID_STRATEGIES, planBid, planBidStrategy, planBudget, planExcludeSegments, planRename, planSchedule, planStatus, planTargeting, planUndo, prepareChange, previewOf, readLog, undoableEntries } from "./changes.js";
|
|
8
8
|
import { executeBulkEdit, plans, prepareBulkEdit } from "./bulk-edit.js";
|
|
9
9
|
import { runBatch, checkBatch } from "./influencer-batch.js";
|
|
@@ -600,7 +600,7 @@ export function registerTools(server, client, env = process.env, { approvals: in
|
|
|
600
600
|
pendingState = newState();
|
|
601
601
|
return asResult({
|
|
602
602
|
step: 1,
|
|
603
|
-
link: authorizeUrl({ clientId: e.SNAP_CLIENT_ID, redirectUri, state: pendingState }),
|
|
603
|
+
link: authorizeUrl({ clientId: e.SNAP_CLIENT_ID, redirectUri, state: pendingState, scope: scopeFor(e) }),
|
|
604
604
|
tell_the_person: "Open this link, log in to Snapchat and click Continue. The browser then shows an error page (that is normal). Copy the whole address from the address bar and paste it here.",
|
|
605
605
|
});
|
|
606
606
|
}
|