ads-mcp-for-snapchat 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.11.1 (2026-11-26)
4
+ Fixes from the release audit (read tools that did not match Snapchat's published API).
5
+
6
+ - **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.
7
+ - **Transactions**: amounts (`total_amount`) are kept instead of dropped.
8
+ - **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.
9
+ - **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).
10
+ - Lists ask Snapchat for at least 50 rows, its minimum page size.
11
+
3
12
  ## 0.11.0 (2026-11-26)
4
13
  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
14
 
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
@@ -204,7 +216,7 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
204
216
  | `snap_billing_check` | read: ad account status, funding sources (card expiry, daily limit vs budgets, credit left) and a verdict |
205
217
  | `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
218
  | `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, a lead count, mobile apps, event details, interaction zones, offer disclaimers, phone numbers (masked), sponsored content, organizations, organization pixels, media stats, catalog products; contact details masked, and if Snapchat does not answer it says which paths were tried |
219
+ | `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
220
  | `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
221
  | `snap_unused_media` | read: uploaded images and videos no creative uses (never deletes) |
210
222
  | `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.0",
3
+ "version": "0.11.1",
4
4
  "description": "Unofficial local MCP server for the Snapchat Marketing API: reports, audits and safe, previewed changes to campaigns, ad squads and ads.",
5
5
  "mcpName": "io.github.Usame794/ads-mcp-for-snapchat",
6
6
  "adsMcpBroker": "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, sponsored content, organizations, organization pixels, media stats and catalog
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
- if (typeof v === "object" && !Array.isArray(v)) continue;
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, org, billing }) => [`/adaccounts/${acc}/invoices`, `/organizations/${org}/invoices`, ...billing.map((b) => `/billingcenters/${b}/invoices`)] },
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 ?? [], billing: [] };
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, 1), 200) } });
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
- const amount = Number(first(r, ["total", "total_amount", "amount_due", "amount", "balance"]));
55
- const row = { number: first(r, ["invoice_number", "number", "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 };
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 belong to the billing center, so they can cover other ad accounts too. Not being able to read them is not a problem here.
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 belong to the billing center and can cover several ad accounts, not only this one." };
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
@@ -25,7 +25,7 @@ try {
25
25
  }
26
26
  // Snapshot of the non-secret settings taken at startup. Later edits to .env do not change limits or the target account.
27
27
  const settings = { ...process.env };
28
- const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.11.0", ...BRAND }, { instructions: INSTRUCTIONS });
28
+ const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.11.1", ...BRAND }, { instructions: INSTRUCTIONS });
29
29
  // Only the OAuth credentials are re-read from .env when a token is needed, so replacing them does not require a restart.
30
30
  const client = new SnapClient({ beforeToken: () => loadEnv(undefined, { override: true }), onNewRefreshToken: (t) => setEnvValue("SNAP_REFRESH_TOKEN", t), timeoutMs: policy.httpTimeoutMs });
31
31
  registerTools(server, client, settings);
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 function authorizeUrl({ clientId, redirectUri = DEFAULT_REDIRECT, state }) {
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: "snapchat-marketing-api", state }).toString();
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/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
- for (const path of paths) {
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, "profile");
15
- const rows = items.map(pick).filter((p) => p && p.id).map((p) => ({ id: p.id, name: p.display_name ?? p.name ?? p.snapchat_user_name ?? p.username ?? null, ...(p.snapchat_user_name || p.username ? { username: p.snapchat_user_name ?? p.username } : {}), ...(p.status ? { status: p.status } : {}) }));
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(`${path}: ${reason(e)}`);
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 (Snapchat offers no profile list to this login)", failures };
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",
@@ -259,8 +261,9 @@ export class SnapClient {
259
261
  return this.token;
260
262
  }
261
263
 
262
- async request(method, path, { query, body } = {}) {
263
- const url = new URL(API + path);
264
+ async request(method, path, { query, body, business = false } = {}) {
265
+ if (business && method !== "GET") throw new Error("The business API host is read-only here.");
266
+ const url = new URL((business ? BUSINESS : API) + path);
264
267
  for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
265
268
  const send = async () =>
266
269
  this.fetchRetry(url, {
@@ -336,11 +339,11 @@ export class SnapClient {
336
339
 
337
340
  // Reads a list endpoint page by page. Returns { items, complete }. `complete` is false when the page limit was reached or a
338
341
  // 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 } = {}) {
342
+ async listPaged(path, entity, { query = {}, maxPages = MAX_LIST_PAGES, business = false } = {}) {
340
343
  const items = [];
341
344
  let cursor;
342
345
  for (let page = 0; page < maxPages; page++) {
343
- const data = await this.request("GET", path, { query: { limit: 500, ...query, cursor } });
346
+ const data = await this.request("GET", path, { query: { limit: 500, ...query, cursor }, business });
344
347
  items.push(...SnapClient.unwrap(data, entity));
345
348
  const next = data.paging?.next_link;
346
349
  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
  }