ads-mcp-for-snapchat 0.4.0 → 0.5.0

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/ARCHITECTURE.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # Architecture and design notes
2
2
 
3
- For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API: 58 tools, all tests mocked (`npm test`). Read `README.md` first for setup and the tool table.
3
+ For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API: 59 tools, all tests mocked (`npm test`). Read `README.md` first for setup and the tool table.
4
4
 
5
5
  ## Architecture (src/)
6
- - `cli.js`: npm command (`npx ads-mcp-for-snapchat`): no command starts the server; `init`, `where`, `save-secret`, `auth`, `check`, `weekly-report` run the setup scripts. `index.js`: MCP server entry. `tools.js`: all 58 tool definitions (zod schemas, handlers).
6
+ - `setup.js`: the guided `setup` command; `oauth.js`: authorization link, code exchange and ad-account list (used by `setup` and the `snap_connect` tool). `manifest.json` + `scripts/build-mcpb.js`: the Claude Desktop extension (`npm run pack:mcpb`).
7
+ - `cli.js`: npm command (`npx ads-mcp-for-snapchat`): no command starts the server; `setup`, `init`, `where`, `save-secret`, `auth`, `check`, `weekly-report` run the setup scripts. `index.js`: MCP server entry. `tools.js`: all 59 tool definitions (zod schemas, handlers).
7
8
  - `snap.js`: `SnapClient` (token refresh, retry), `ENTITIES` (campaign, adsquad, ad, creative, media, segment), sanitize-for-create/update helpers, `createEntity/updateEntity/getEntity/listChildren`, `upload`.
8
9
  - `env.js`: `.env` loading, `setEnvValue` (writes a value without printing it) and `dataDir` (the project folder for a git checkout; `~/.ads-mcp-for-snapchat` for a copy inside `node_modules`; `SNAP_HOME` overrides). The default change log and `exports/` live there too.
9
10
  - `changes.js`: plan functions (status, budget, exclusions, rename, bid, targeting, schedule), `applyChange` (logs before/after), `containsDeep`, `planUndo`.
package/CHANGELOG.md CHANGED
@@ -1,11 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0 (2026-11-14)
4
+
5
+ - Easy setup: `npx -y ads-mcp-for-snapchat setup` goes from nothing to a working server in one command. It asks for the Client ID and secret (the secret is hidden), opens the approval page, reads the code from the pasted address (checking it belongs to this attempt), lists the login's ad accounts to choose from, asks for the highest daily budget, main country and read-only mode, and adds the server to Claude Code (or prints the exact settings for other apps). Switching a file to another account clears the old account's pixel and brand profile.
6
+ - Claude Desktop extension (`.mcpb`, attached to each GitHub release): install with a double-click, enter the Client ID and secret in Claude Desktop's own settings screen, then connect from the chat.
7
+ - New tool `snap_connect`: connect an ad account from inside the chat (link, pasted address, account choice). The Client ID and secret come from the app's settings, never from the chat; the refresh token is saved to the settings file and never returned. It changes no ads, so it also works in read-only mode. A new account takes effect after restarting the app, as before.
8
+ - An optional Claude Desktop setting left empty is ignored instead of stopping the server.
9
+
10
+ ## 0.4.1 (2026-11-14)
11
+
12
+ - 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.
13
+ - Package and registry links point to the repository's real name, `Usame794/snap-ads-mcp` (0.4.0 linked to a name that does not exist).
14
+ - 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`.
15
+
3
16
  ## 0.4.0 (2026-11-14)
4
17
 
5
18
  - 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.
6
19
  - 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.
7
20
  - `server.json` for the official MCP Registry (`io.github.Usame794/ads-mcp-for-snapchat`).
8
- - The repository is now `Usame794/ads-mcp-for-snapchat`. Old links redirect.
21
+ - Repository links point to `Usame794/snap-ads-mcp`.
9
22
  - Verified live on a real account: a COLLECTION ad (paused).
10
23
 
11
24
  ## 0.3.2 (2026-11-14)
package/README.md CHANGED
@@ -24,17 +24,24 @@ A local [MCP](https://modelcontextprotocol.io) server that lets an AI assistant
24
24
 
25
25
  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.
26
26
 
27
- ## Install from npm (no download needed)
28
- Needs Node 18 or newer. Your settings live in `~/.ads-mcp-for-snapchat/.env`, outside the package, so updates never touch them.
27
+ ## Easy setup (about 5 minutes)
28
+ 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).
29
29
 
30
- 1. `npx -y ads-mcp-for-snapchat init` creates the settings file (private to you). `npx -y ads-mcp-for-snapchat where` prints its path.
31
- 2. Open it, fill in `SNAP_CLIENT_ID`, `SNAP_AD_ACCOUNT_ID`, your limits and market settings, then follow **Setup (one time)** below using these commands instead of `node scripts/...`:
32
- - `npx -y ads-mcp-for-snapchat save-secret` (client secret from the clipboard; `--stdin` to paste it instead)
33
- - `npx -y ads-mcp-for-snapchat auth THE_CODE` (refresh token)
34
- - `npx -y ads-mcp-for-snapchat check` (read-only test)
35
- 3. Register it: `claude mcp add --scope user snapchat-ads -- npx -y ads-mcp-for-snapchat`, then restart Claude Code. For Claude Desktop use `"command": "npx", "args": ["-y", "ads-mcp-for-snapchat"]`.
30
+ **Claude Desktop (no terminal):**
31
+ 1. Download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snap-ads-mcp/releases/latest) and double-click it. Claude Desktop shows an install screen.
32
+ 2. Enter the Client ID and Client Secret, your highest daily budget and (optional) your main country. Leave **Read-only** on for now.
33
+ 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.
34
+ 4. Quit and reopen Claude Desktop. Ask: "call snap_ping".
36
35
 
37
- `npx -y ads-mcp-for-snapchat help` lists every command. For a second ad account, put `SNAP_ENV_FILE=/path/to/.env.account2` in front of any command, and add `-e SNAP_ENV_FILE=/path/to/.env.account2` when registering it (see "Several ad accounts"). It is also listed in the official MCP Registry as `io.github.Usame794/ads-mcp-for-snapchat`.
36
+ **Claude Code, Cursor, VS Code (one command, needs Node 18+):**
37
+
38
+ ```
39
+ npx -y ads-mcp-for-snapchat setup
40
+ ```
41
+
42
+ It asks for the Client ID and secret (hidden), opens the approval page, lists your ad accounts to choose from, asks for your first safety settings, and adds the server to Claude Code. For Cursor, VS Code or Claude Desktop it prints the exact settings to paste. Another ad account: `npx -y ads-mcp-for-snapchat setup --file ~/.ads-mcp-for-snapchat/.env.account2`.
43
+
44
+ Settings, the change log and exports live in `~/.ads-mcp-for-snapchat/`, outside the package, so updates never touch them. `npx -y ads-mcp-for-snapchat help` lists the other commands (`check`, `where`, `weekly-report`, and the step-by-step `init`, `save-secret`, `auth`). It is also listed in the official MCP Registry as `io.github.Usame794/ads-mcp-for-snapchat`.
38
45
 
39
46
  ## Quick start (from source)
40
47
  1. `git clone` this repository, then `npm ci`, then `npm test` (all tests are mocked and need no account).
@@ -90,6 +97,7 @@ Existing items above a limit can still be read, lowered and paused, but not rais
90
97
  | Tool | Type |
91
98
  |---|---|
92
99
  | `snap_ping` | check credentials |
100
+ | `snap_connect` | connect an ad account from inside the chat (link, pasted address, account choice); saves access on this computer, changes no ads |
93
101
  | `snap_list_campaigns`, `snap_list_adsquads`, `snap_list_ads`, `snap_list_creatives`, `snap_get_entity`, `snap_get_media`, `snap_get_stats` | read |
94
102
  | `snap_report` | read: ROAS, CPA, swipe rate, frequency by ad squad or ad |
95
103
  | `snap_report_daily` | read: day-by-day performance (up to 31 days) |
@@ -183,8 +191,9 @@ Run one server per ad account, each with its own settings file. Each server only
183
191
  1. Copy your settings: `cp .env .env.account2`. In `.env.account2`, set that account's `SNAP_AD_ACCOUNT_ID`, `SNAP_PIXEL_ID`, `SNAP_BRAND_PROFILE_ID` and its own limits. Every `.env*` file except `.env.example` is git-ignored.
184
192
  2. If that account belongs to another Snapchat login, authorize it into its own file (same steps as "Setup", with the variable in front): `SNAP_ENV_FILE=.env.account2 node scripts/get-refresh-token.js`, then `SNAP_ENV_FILE=.env.account2 node scripts/check.js`. If the same login can see both accounts, the copied credentials already work.
185
193
  3. Register a second server with an absolute path to the file:
186
- `claude mcp add --scope user -e SNAP_ENV_FILE="/ABSOLUTE/PATH/TO/ads-mcp-for-snapchat/.env.account2" snapchat-ads-2 -- node "/ABSOLUTE/PATH/TO/ads-mcp-for-snapchat/src/index.js"`
187
- 4. Start with `SNAP_READ_ONLY=1` in the new file and check `snap_ping` shows the right account.
194
+ `claude mcp add --scope user snapchat-ads-2 -e SNAP_ENV_FILE="/ABSOLUTE/PATH/TO/ads-mcp-for-snapchat/.env.account2" -e SNAP_READ_ONLY=1 -- node "/ABSOLUTE/PATH/TO/ads-mcp-for-snapchat/src/index.js"`
195
+ The server name must come before `-e` (`-e` takes every value after it). `-e SNAP_READ_ONLY=1` starts the new account read-only, whatever its file says; remove it (`claude mcp remove snapchat-ads-2`, then add it again without it) when you are ready.
196
+ 4. Restart, then check that `snap_ping` shows the new account's id (not the first account's) and `readOnly: true`.
188
197
 
189
198
  Scripts work the same way: put `SNAP_ENV_FILE=.env.account2` in front of any `node scripts/...` command.
190
199
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ads-mcp-for-snapchat",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
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
  "type": "module",
@@ -12,7 +12,8 @@
12
12
  "start": "node src/index.js",
13
13
  "test": "node --test test/*.test.js",
14
14
  "smoke": "node scripts/smoke.js",
15
- "weekly-report": "node scripts/weekly-report.js"
15
+ "weekly-report": "node scripts/weekly-report.js",
16
+ "pack:mcpb": "node scripts/build-mcpb.js"
16
17
  },
17
18
  "dependencies": {
18
19
  "@modelcontextprotocol/sdk": "^1.0.0",
@@ -34,12 +35,12 @@
34
35
  ],
35
36
  "repository": {
36
37
  "type": "git",
37
- "url": "git+https://github.com/Usame794/ads-mcp-for-snapchat.git"
38
+ "url": "git+https://github.com/Usame794/snap-ads-mcp.git"
38
39
  },
39
40
  "bugs": {
40
- "url": "https://github.com/Usame794/ads-mcp-for-snapchat/issues"
41
+ "url": "https://github.com/Usame794/snap-ads-mcp/issues"
41
42
  },
42
- "homepage": "https://github.com/Usame794/ads-mcp-for-snapchat#readme",
43
+ "homepage": "https://github.com/Usame794/snap-ads-mcp#readme",
43
44
  "files": [
44
45
  "src",
45
46
  "scripts/save-secret.js",
package/src/cli.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  // Command-line entry for the npm package: `npx ads-mcp-for-snapchat <command>`. With no command it starts the MCP server,
3
3
  // which is what an MCP client runs. The other commands are the one-time setup helpers from scripts/.
4
- import { chmodSync, copyFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
5
- import { dirname, join } from "node:path";
4
+ import { realpathSync } from "node:fs";
5
+ import { join } from "node:path";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
7
7
  import { envFile, ROOT } from "./env.js";
8
+ import { init } from "./init.js";
8
9
 
9
10
  const SCRIPTS = {
10
11
  "save-secret": "save-secret.js",
@@ -18,6 +19,7 @@ export const HELP = `Ads MCP for Snapchat
18
19
  Usage: npx ads-mcp-for-snapchat [command]
19
20
 
20
21
  (no command) start the MCP server (this is what Claude runs)
22
+ setup guided setup: connect your account and add it to Claude (--file PATH for another account)
21
23
  init create the settings file from the template
22
24
  where print the settings file in use
23
25
  save-secret save the client secret from the clipboard (--stdin to paste it instead)
@@ -28,24 +30,14 @@ Usage: npx ads-mcp-for-snapchat [command]
28
30
 
29
31
  Settings file: SNAP_ENV_FILE if set, otherwise .env in ~/.ads-mcp-for-snapchat (npm install) or the project folder (git clone).`;
30
32
 
31
- // Creates the settings file from .env.example, private to the user. Never overwrites an existing file.
32
- export function init(file = envFile()) {
33
- if (existsSync(file)) return { created: false, file };
34
- mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
35
- copyFileSync(join(ROOT, ".env.example"), file);
36
- try {
37
- chmodSync(file, 0o600);
38
- } catch {
39
- // not fatal (e.g. Windows)
40
- }
41
- return { created: true, file };
42
- }
33
+ export { init } from "./init.js";
43
34
 
44
35
  export async function main(argv = process.argv.slice(2)) {
45
36
  const [command, ...rest] = argv;
46
37
  if (!command || command === "serve") return import("./index.js");
47
38
  if (command === "help" || command === "--help" || command === "-h") return console.log(HELP);
48
39
  if (command === "where") return console.log(envFile());
40
+ if (command === "setup") return (await import("./setup.js")).setupCommand(rest);
49
41
  if (command === "init") {
50
42
  const r = init();
51
43
  console.log(r.created ? `Created ${r.file}. Fill in SNAP_CLIENT_ID and SNAP_AD_ACCOUNT_ID, then run save-secret.` : `${r.file} already exists; nothing changed.`);
package/src/env.js CHANGED
@@ -19,14 +19,22 @@ export const envFile = () => process.env.SNAP_ENV_FILE || join(dataDir(), ".env"
19
19
 
20
20
  // Minimal .env loader so the server needs no extra dependency.
21
21
  export function loadEnv(file = envFile(), { override = false } = {}) {
22
+ let text;
22
23
  try {
23
- for (const line of readFileSync(file, "utf8").split("\n")) {
24
- const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
25
- if (!m || line.trim().startsWith("#")) continue;
26
- if (override || process.env[m[1]] === undefined) process.env[m[1]] = m[2].replace(/^["']|["']$/g, "");
27
- }
24
+ text = readFileSync(file, "utf8");
28
25
  } catch {
29
- // .env is optional; real environment variables also work.
26
+ return; // .env is optional; real environment variables also work.
27
+ }
28
+ // When a key appears twice in the file, the LAST line wins (as in dotenv), so a line appended at the end, such as
29
+ // SNAP_READ_ONLY=1, really takes effect. A real environment variable still wins over the file unless override is set.
30
+ const values = {};
31
+ for (const line of text.split("\n")) {
32
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
33
+ if (!m || line.trim().startsWith("#")) continue;
34
+ values[m[1]] = m[2].replace(/^["']|["']$/g, "");
35
+ }
36
+ for (const [key, value] of Object.entries(values)) {
37
+ if (override || process.env[key] === undefined) process.env[key] = value;
30
38
  }
31
39
  }
32
40
 
@@ -39,8 +47,19 @@ export function setEnvValue(key, value, file = envFile()) {
39
47
  } catch {
40
48
  // create the file if missing
41
49
  }
42
- const re = new RegExp(`^${key}=.*$`, "m");
43
- text = re.test(text) ? text.replace(re, () => `${key}=${value}`) : text.replace(/\n?$/, "\n") + `${key}=${value}\n`;
50
+ // Every line of this key is replaced: the first keeps its place, later duplicates are removed. Otherwise a duplicate further
51
+ // down would win when the file is read (see loadEnv) and the new value would be silently ignored.
52
+ const re = new RegExp(`^${key}=.*(?:\n|$)`, "gm");
53
+ let seen = false;
54
+ if (re.test(text)) {
55
+ text = text.replace(re, (line) => {
56
+ if (seen) return "";
57
+ seen = true;
58
+ return `${key}=${value}${line.endsWith("\n") ? "\n" : ""}`;
59
+ });
60
+ } else {
61
+ text = text.replace(/\n?$/, "\n") + `${key}=${value}\n`;
62
+ }
44
63
  mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
45
64
  writeFileSync(file, text, { mode: 0o600 });
46
65
  // `mode` only applies when the file is created; an existing .env keeps its old permissions unless tightened here.
package/src/index.js CHANGED
@@ -6,6 +6,9 @@ import { loadPolicy } from "./policy.js";
6
6
  import { SnapClient } from "./snap.js";
7
7
  import { registerTools } from "./tools.js";
8
8
 
9
+ // A Claude Desktop extension passes optional settings the person left empty as unreplaced "${user_config.x}" text on some
10
+ // versions. Treat those as unset, so an empty optional setting can never stop the server or become a real value.
11
+ for (const [k, v] of Object.entries(process.env)) if (k.startsWith("SNAP_") && /^\$\{user_config\.[a-z_]+\}$/.test(v ?? "")) delete process.env[k];
9
12
  loadEnv();
10
13
  let policy;
11
14
  try {
@@ -17,7 +20,7 @@ try {
17
20
  }
18
21
  // Snapshot of the non-secret settings taken at startup. Later edits to .env do not change limits or the target account.
19
22
  const settings = { ...process.env };
20
- const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.4.0" });
23
+ const server = new McpServer({ name: "ads-mcp-for-snapchat", version: "0.5.0" });
21
24
  // Only the OAuth credentials are re-read from .env when a token is needed, so replacing them does not require a restart.
22
25
  const client = new SnapClient({ beforeToken: () => loadEnv(undefined, { override: true }), timeoutMs: policy.httpTimeoutMs });
23
26
  registerTools(server, client, settings);
package/src/init.js ADDED
@@ -0,0 +1,16 @@
1
+ import { chmodSync, copyFileSync, existsSync, mkdirSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { envFile, ROOT } from "./env.js";
4
+
5
+ // Creates the settings file from .env.example, private to the user. Never overwrites an existing file.
6
+ export function init(file = envFile()) {
7
+ if (existsSync(file)) return { created: false, file };
8
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
9
+ copyFileSync(join(ROOT, ".env.example"), file);
10
+ try {
11
+ chmodSync(file, 0o600);
12
+ } catch {
13
+ // not fatal (e.g. Windows)
14
+ }
15
+ return { created: true, file };
16
+ }
package/src/oauth.js ADDED
@@ -0,0 +1,63 @@
1
+ // Connecting an ad account: the authorization link, reading the code back, exchanging it for a refresh token, and listing the
2
+ // ad accounts the login can see. Shared by the `setup` command and the in-chat snap_connect tools.
3
+ import { randomBytes } from "node:crypto";
4
+
5
+ export const AUTHORIZE_URL = "https://accounts.snapchat.com/login/oauth2/authorize";
6
+ export const TOKEN_URL = "https://accounts.snapchat.com/login/oauth2/access_token";
7
+ export const DEFAULT_REDIRECT = "https://127.0.0.1/callback";
8
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
+
10
+ export const newState = () => `ads-mcp-${randomBytes(9).toString("base64url")}`;
11
+ export const looksLikeClientId = (text) => UUID.test(String(text).trim());
12
+
13
+ export function authorizeUrl({ clientId, redirectUri = DEFAULT_REDIRECT, state }) {
14
+ if (!looksLikeClientId(clientId)) throw new Error("The Client ID should look like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (from Business Details > OAuth Apps).");
15
+ const u = new URL(AUTHORIZE_URL);
16
+ u.search = new URLSearchParams({ response_type: "code", client_id: clientId.trim(), redirect_uri: redirectUri, scope: "snapchat-marketing-api", state }).toString();
17
+ return u.toString();
18
+ }
19
+
20
+ // Accepts the whole address the browser landed on (preferred: the state is checked) or just the code.
21
+ export function extractCode(input, expectedState) {
22
+ const text = String(input ?? "").trim();
23
+ if (!text) throw new Error("Nothing was pasted. Paste the whole address from the browser's address bar after approving.");
24
+ if (/^https?:\/\//i.test(text)) {
25
+ const url = new URL(text);
26
+ const error = url.searchParams.get("error");
27
+ if (error) throw new Error(`Snap refused the authorization: ${url.searchParams.get("error_description") || error}.`);
28
+ const code = url.searchParams.get("code");
29
+ if (!code) throw new Error("That address has no code in it. Approve in the browser first, then copy the address it lands on.");
30
+ const state = url.searchParams.get("state");
31
+ if (expectedState && state !== expectedState) throw new Error("That address belongs to a different authorization attempt. Use the newest link.");
32
+ return code;
33
+ }
34
+ if (!/^[A-Za-z0-9._~+\/=-]{10,}$/.test(text)) throw new Error("That does not look like a code. Paste the whole address from the browser instead.");
35
+ return text;
36
+ }
37
+
38
+ export async function exchangeCode({ clientId, clientSecret, redirectUri = DEFAULT_REDIRECT, code, fetchImpl = fetch }) {
39
+ const res = await fetchImpl(TOKEN_URL, {
40
+ method: "POST",
41
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
42
+ body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, client_id: clientId, client_secret: clientSecret }),
43
+ signal: AbortSignal.timeout(30_000),
44
+ });
45
+ const data = await res.json().catch(() => ({}));
46
+ if (!res.ok || !data.refresh_token) {
47
+ const why = data.error_description || data.error || "no detail";
48
+ const hint = /client/i.test(why) ? " Check that the Client ID and secret come from the same OAuth app." : " The code is single-use and expires after a few minutes: open the link again and paste the new address.";
49
+ throw new Error(`Snap did not accept the code (${res.status}: ${why}).${hint}`);
50
+ }
51
+ return data.refresh_token;
52
+ }
53
+
54
+ // Every ad account the authorized login can see, across its organizations.
55
+ export async function listAdAccounts(client) {
56
+ const data = await client.request("GET", "/me/organizations", { query: { with_ad_accounts: "true" } });
57
+ const rows = [];
58
+ for (const wrap of data.organizations ?? []) {
59
+ const org = wrap.organization ?? wrap;
60
+ for (const a of org.ad_accounts ?? []) rows.push({ id: a.id, name: a.name, status: a.status, currency: a.currency, organization: org.name });
61
+ }
62
+ return rows.sort((x, y) => String(x.organization).localeCompare(String(y.organization)) || String(x.name).localeCompare(String(y.name)));
63
+ }
package/src/setup.js ADDED
@@ -0,0 +1,235 @@
1
+ // `npx ads-mcp-for-snapchat setup`: one guided command from nothing to a working, registered server.
2
+ // Asks for the OAuth app's Client ID and secret (hidden), opens the approval page, takes the address the browser lands on,
3
+ // saves the refresh token, lets the person pick an ad account from a list, sets the first safety settings and registers the
4
+ // server in Claude Code. Every input and side effect goes through `io`/`deps`, so it is tested without a terminal or network.
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
+ import { readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { createInterface } from "node:readline";
9
+ import { envFile, ROOT, setEnvValue, dataDir } from "./env.js";
10
+ import { secretProblems } from "./clipboard.js";
11
+ import { authorizeUrl, DEFAULT_REDIRECT, exchangeCode, extractCode, listAdAccounts, looksLikeClientId, newState } from "./oauth.js";
12
+ import { SnapClient } from "./snap.js";
13
+ import { init } from "./init.js";
14
+
15
+ const readSettings = (file) => {
16
+ const out = {};
17
+ try {
18
+ for (const line of readFileSync(file, "utf8").split("\n")) {
19
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
20
+ if (m && !line.trim().startsWith("#")) out[m[1]] = m[2].replace(/^["']|["']$/g, "");
21
+ }
22
+ } catch {
23
+ // no file yet
24
+ }
25
+ return out;
26
+ };
27
+
28
+ // Terminal input. Lines are queued as they arrive, so answers typed ahead or piped in are never lost between questions.
29
+ // The secret prompt echoes nothing.
30
+ export function terminalIO({ input = process.stdin, output = process.stdout } = {}) {
31
+ const rl = createInterface({ input, output, terminal: Boolean(input.isTTY && output.isTTY) });
32
+ let muted = false;
33
+ const write = rl._writeToOutput?.bind(rl);
34
+ if (write) rl._writeToOutput = (s) => (muted ? undefined : write(s));
35
+ const lines = [];
36
+ const waiting = [];
37
+ let closed = false;
38
+ rl.on("line", (line) => (waiting.length ? waiting.shift()(line) : lines.push(line)));
39
+ rl.on("close", () => {
40
+ closed = true;
41
+ while (waiting.length) waiting.shift()(null);
42
+ });
43
+ const ask = async (q) => {
44
+ output.write(q);
45
+ const line = lines.length ? lines.shift() : closed ? null : await new Promise((resolve) => waiting.push(resolve));
46
+ if (line === null) throw new Error("Input ended before setup finished.");
47
+ return line.trim();
48
+ };
49
+ return {
50
+ print: (s = "") => output.write(`${s}\n`),
51
+ ask,
52
+ askSecret: async (q) => {
53
+ muted = true;
54
+ try {
55
+ output.write(q);
56
+ const line = lines.length ? lines.shift() : closed ? null : await new Promise((resolve) => waiting.push(resolve));
57
+ if (line === null) throw new Error("Input ended before setup finished.");
58
+ return line.trim();
59
+ } finally {
60
+ muted = false;
61
+ output.write("\n");
62
+ }
63
+ },
64
+ close: () => rl.close(),
65
+ };
66
+ }
67
+
68
+ export function openInBrowser(url, { platform = process.platform, spawn = spawnSync } = {}) {
69
+ const [cmd, args] = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
70
+ try {
71
+ return spawn(cmd, args, { stdio: "ignore", timeout: 10_000 }).status === 0;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ const hasClaude = (exec = execFileSync) => {
78
+ try {
79
+ exec("claude", ["--version"], { stdio: "ignore" });
80
+ return true;
81
+ } catch {
82
+ return false;
83
+ }
84
+ };
85
+
86
+ // How an MCP client should start this server: the npm package for an installed copy, the file itself for a git checkout.
87
+ export function launchCommand(root = ROOT) {
88
+ return root.split(/[\\/]/).includes("node_modules") ? { command: "npx", args: ["-y", "ads-mcp-for-snapchat"] } : { command: "node", args: [join(root, "src", "index.js")] };
89
+ }
90
+
91
+ async function askUntil(io, question, check) {
92
+ for (let i = 0; i < 5; i++) {
93
+ const answer = await io.ask(question);
94
+ const problem = check(answer);
95
+ if (!problem) return answer;
96
+ io.print(` ${problem}`);
97
+ }
98
+ throw new Error("Too many invalid answers. Run setup again when you have the details.");
99
+ }
100
+
101
+ export async function runSetup({ io, file = envFile(), fetchImpl = fetch, open = openInBrowser, exec = execFileSync, claudeAvailable = hasClaude, root = ROOT } = {}) {
102
+ const say = io.print;
103
+ const created = init(file).created;
104
+ let cur = readSettings(file);
105
+ say("");
106
+ say("Ads MCP for Snapchat: setup");
107
+ say(`Settings file: ${file}${created ? " (new)" : ""}`);
108
+ say("Nothing here can change your ads. It only connects the account and saves settings on this computer.");
109
+ say("");
110
+
111
+ // 1. OAuth app
112
+ say("STEP 1 of 5: your Snapchat OAuth app (one time, about 3 minutes)");
113
+ say(" 1. Open https://business.snapchat.com and go to Business Details > OAuth Apps > + OAuth App.");
114
+ say(` 2. Any app name. Redirect URI: ${DEFAULT_REDIRECT}`);
115
+ say(" 3. Create it. Copy the Client ID, and the Client Secret (shown only once).");
116
+ say("");
117
+ const keepId = looksLikeClientId(cur.SNAP_CLIENT_ID ?? "");
118
+ const idAnswer = await askUntil(io, keepId ? "Client ID (Enter keeps the saved one): " : "Client ID: ", (a) => (keepId && !a) || looksLikeClientId(a) ? null : "That is not a Client ID. It looks like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.");
119
+ const clientId = idAnswer || cur.SNAP_CLIENT_ID;
120
+ if (clientId !== cur.SNAP_CLIENT_ID) setEnvValue("SNAP_CLIENT_ID", clientId, file);
121
+
122
+ const keepSecret = Boolean(cur.SNAP_CLIENT_SECRET) && !secretProblems(cur.SNAP_CLIENT_SECRET).length && clientId === cur.SNAP_CLIENT_ID;
123
+ let secret = null;
124
+ for (let i = 0; i < 5 && secret === null; i++) {
125
+ const a = await io.askSecret(keepSecret ? "Client Secret (hidden; Enter keeps the saved one): " : "Client Secret (hidden while you type or paste): ");
126
+ if (!a && keepSecret) secret = cur.SNAP_CLIENT_SECRET;
127
+ else if (secretProblems(a).length) say(` That does not look like a secret: ${secretProblems(a).join(", ")}. Copy it again.`);
128
+ else secret = a;
129
+ }
130
+ if (secret === null) throw new Error("No valid secret was entered.");
131
+ if (secret !== cur.SNAP_CLIENT_SECRET) setEnvValue("SNAP_CLIENT_SECRET", secret, file);
132
+ const redirectUri = cur.SNAP_REDIRECT_URI || DEFAULT_REDIRECT;
133
+ if (!cur.SNAP_REDIRECT_URI) setEnvValue("SNAP_REDIRECT_URI", redirectUri, file);
134
+ say(" Saved.");
135
+ say("");
136
+
137
+ // 2. Authorize
138
+ say("STEP 2 of 5: approve access in the browser");
139
+ let token = null;
140
+ for (let i = 0; i < 3 && !token; i++) {
141
+ const state = newState();
142
+ const url = authorizeUrl({ clientId, redirectUri, state });
143
+ const opened = open(url);
144
+ say(opened ? " Your browser opened. Log in to Snapchat and click Continue." : " Open this link, log in to Snapchat and click Continue:");
145
+ if (!opened) say(` ${url}`);
146
+ say(" The browser then shows an error page ('can't connect' is normal). Copy the whole address from its address bar.");
147
+ const pasted = await io.ask("Paste that address here: ");
148
+ try {
149
+ token = await exchangeCode({ clientId, clientSecret: secret, redirectUri, code: extractCode(pasted, state), fetchImpl });
150
+ } catch (e) {
151
+ say(` ${e.message}`);
152
+ }
153
+ }
154
+ if (!token) throw new Error("Could not connect. Check the Redirect URI on the OAuth app is exactly " + redirectUri + ", then run setup again.");
155
+ setEnvValue("SNAP_REFRESH_TOKEN", token, file);
156
+ say(" Connected. Access saved on this computer only.");
157
+ say("");
158
+
159
+ // 3. Ad account
160
+ say("STEP 3 of 5: choose the ad account");
161
+ const client = new SnapClient({ env: { SNAP_CLIENT_ID: clientId, SNAP_CLIENT_SECRET: secret, SNAP_REFRESH_TOKEN: token }, fetchImpl });
162
+ const me = (await client.request("GET", "/me")).me ?? {};
163
+ say(` Logged in as ${me.display_name ?? me.email ?? "your Snapchat login"}.`);
164
+ const accounts = await listAdAccounts(client);
165
+ if (!accounts.length) throw new Error("This login cannot see any ad account. Ask the account's admin to add you, then run setup again.");
166
+ accounts.forEach((a, i) => say(` ${String(i + 1).padStart(2)}. ${a.name} (${a.organization}, ${a.status}, ${a.currency})`));
167
+ const pick = await askUntil(io, `Number of the ad account (1-${accounts.length}): `, (a) => (Number.isInteger(Number(a)) && Number(a) >= 1 && Number(a) <= accounts.length ? null : `Type a number from 1 to ${accounts.length}.`));
168
+ const chosen = accounts[Number(pick) - 1];
169
+ if (chosen.id !== cur.SNAP_AD_ACCOUNT_ID) {
170
+ setEnvValue("SNAP_AD_ACCOUNT_ID", chosen.id, file);
171
+ // A pixel or brand profile from another account must never be used on this one.
172
+ if (cur.SNAP_AD_ACCOUNT_ID && cur.SNAP_PIXEL_ID) setEnvValue("SNAP_PIXEL_ID", "", file);
173
+ if (cur.SNAP_AD_ACCOUNT_ID && cur.SNAP_BRAND_PROFILE_ID) setEnvValue("SNAP_BRAND_PROFILE_ID", "", file);
174
+ }
175
+ if (chosen.currency && /^[A-Z]{3}$/.test(chosen.currency)) setEnvValue("SNAP_ACCOUNT_CURRENCY", chosen.currency, file);
176
+ say(` Using ${chosen.name}.`);
177
+ say("");
178
+
179
+ // 4. Safety
180
+ cur = readSettings(file);
181
+ say("STEP 4 of 5: safety settings (Enter keeps the value in brackets)");
182
+ const budget = await askUntil(io, ` Highest daily budget the AI may set, in ${chosen.currency ?? "account currency"} [${cur.SNAP_MAX_DAILY_BUDGET || 1000}]: `, (a) => (!a || (/^\d+(\.\d+)?$/.test(a) && Number(a) > 0) ? null : "A plain number, such as 300."));
183
+ if (budget) setEnvValue("SNAP_MAX_DAILY_BUDGET", budget, file);
184
+ const country = await askUntil(io, ` Main country, 2 letters such as us, sa, ae (Enter to skip) [${cur.SNAP_DEFAULT_COUNTRY || ""}]: `, (a) => (!a || /^[a-z]{2}$/i.test(a) ? null : "Two letters, such as us."));
185
+ if (country) setEnvValue("SNAP_DEFAULT_COUNTRY", country.toLowerCase(), file);
186
+ const ro = await io.ask(" Start in read-only mode, so nothing can be changed until you are ready? [Y/n]: ");
187
+ setEnvValue("SNAP_READ_ONLY", /^n/i.test(ro) ? "0" : "1", file);
188
+ say(" Saved.");
189
+ say("");
190
+
191
+ // 5. Register
192
+ say("STEP 5 of 5: add it to your AI app");
193
+ const launch = launchCommand(root);
194
+ const defaultFile = join(dataDir({ root }), ".env");
195
+ const envArgs = file === defaultFile ? [] : ["-e", `SNAP_ENV_FILE=${file}`];
196
+ const name = (await io.ask(" Name for this server in Claude [snapchat-ads]: ")) || "snapchat-ads";
197
+ let registered = false;
198
+ if (claudeAvailable(exec)) {
199
+ try {
200
+ // The server name must come before -e: -e takes every value after it.
201
+ exec("claude", ["mcp", "add", "--scope", "user", name, ...envArgs, "--", launch.command, ...launch.args], { stdio: "ignore" });
202
+ registered = true;
203
+ say(` Added to Claude Code as "${name}". Restart Claude Code, then ask: "call ${name} snap_ping".`);
204
+ } catch {
205
+ say(` Claude Code did not accept it (maybe "${name}" exists already: claude mcp remove ${name}).`);
206
+ }
207
+ }
208
+ if (!registered) {
209
+ const quoted = (s) => (/[\s"]/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s);
210
+ say(" Claude Code, run:");
211
+ say(` claude mcp add --scope user ${name} ${envArgs.map(quoted).join(" ")} -- ${[launch.command, ...launch.args].map(quoted).join(" ")}`.replace(/ +/g, " "));
212
+ }
213
+ const desktop = { mcpServers: { [name]: { command: launch.command, args: launch.args, ...(envArgs.length ? { env: { SNAP_ENV_FILE: file } } : {}) } } };
214
+ say(" Claude Desktop, Cursor or VS Code: add this to the MCP settings:");
215
+ say(JSON.stringify(desktop, null, 2).split("\n").map((l) => ` ${l}`).join("\n"));
216
+ say("");
217
+ say(`Done. ${/^n/i.test(ro) ? "Changes are allowed; every change still needs your approval." : "Read-only for now: set SNAP_READ_ONLY=0 in the settings file when you want changes."}`);
218
+ say("For another ad account: npx -y ads-mcp-for-snapchat setup --file ~/.ads-mcp-for-snapchat/.env.account2");
219
+ return { file, account: chosen, registered, name };
220
+ }
221
+
222
+ // For the CLI: `setup [--file PATH]`.
223
+ export async function setupCommand(args) {
224
+ const i = args.indexOf("--file");
225
+ const file = i >= 0 && args[i + 1] ? args[i + 1].replace(/^~(?=$|[\\/])/, process.env.HOME ?? "~") : envFile();
226
+ const io = terminalIO();
227
+ try {
228
+ await runSetup({ io, file });
229
+ } catch (e) {
230
+ io.print(`\nSetup stopped: ${e.message}`);
231
+ process.exitCode = 1;
232
+ } finally {
233
+ io.close();
234
+ }
235
+ }
package/src/tools.js CHANGED
@@ -2,6 +2,8 @@ import { statSync } from "node:fs";
2
2
  import { randomInt } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { SnapClient } from "./snap.js";
5
+ import { envFile, setEnvValue } from "./env.js";
6
+ import { authorizeUrl, DEFAULT_REDIRECT, exchangeCode, extractCode, listAdAccounts, newState } from "./oauth.js";
5
7
  import { executeChange, LOG_FILE, planBid, planBudget, planExcludeSegments, planRename, planSchedule, planStatus, planTargeting, planUndo, prepareChange, previewOf, readLog, undoableEntries } from "./changes.js";
6
8
  import { executeBulkEdit, plans, prepareBulkEdit } from "./bulk-edit.js";
7
9
  import { runBatch, checkBatch } from "./influencer-batch.js";
@@ -268,6 +270,57 @@ export function registerTools(server, client, env = process.env) {
268
270
  return { ok: true, me: me.me ?? me, ad_account: cfg.account ?? null, safety_limits: describePolicy(policy) };
269
271
  });
270
272
 
273
+ // Connecting from inside the chat (Claude Desktop extension, no terminal). The Client ID and secret come from the app's
274
+ // settings, never from the chat. The authorization code that passes through the chat is single-use, expires in minutes and
275
+ // is useless without the secret. The refresh token is saved to the settings file and never returned.
276
+ let pendingState = null;
277
+ server.registerTool(
278
+ "snap_connect",
279
+ {
280
+ description:
281
+ "Connect this server to a Snapchat ad account, from inside the chat. Step 1: call with no arguments; it returns a link for the person to open and approve. Step 2: the person pastes the address the browser landed on; call with redirected_url, and it saves access on this computer and lists the ad accounts. Step 3: call with ad_account_id to choose one, then the app must be restarted. Changes no ads.",
282
+ inputSchema: z.object({ redirected_url: z.string().max(4000).optional(), ad_account_id: id().optional() }).strict(),
283
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
284
+ },
285
+ async ({ redirected_url, ad_account_id }) => {
286
+ try {
287
+ const e = client.env;
288
+ if (!e.SNAP_CLIENT_ID || !e.SNAP_CLIENT_SECRET) {
289
+ throw new Error("The Client ID and Client Secret are not set. Enter them in the extension's settings (Claude Desktop: Settings > Extensions > Ads MCP for Snapchat), or run: npx -y ads-mcp-for-snapchat setup");
290
+ }
291
+ const redirectUri = e.SNAP_REDIRECT_URI || DEFAULT_REDIRECT;
292
+ const file = envFile();
293
+ if (ad_account_id) {
294
+ const accounts = await listAdAccounts(client);
295
+ const chosen = accounts.find((a) => a.id === ad_account_id);
296
+ if (!chosen) throw new Error("That ad account is not one this login can see. Call snap_connect with redirected_url again to list them.");
297
+ setEnvValue("SNAP_AD_ACCOUNT_ID", chosen.id, file);
298
+ if (/^[A-Z]{3}$/.test(chosen.currency ?? "")) setEnvValue("SNAP_ACCOUNT_CURRENCY", chosen.currency, file);
299
+ return asResult({ ok: true, account: chosen, saved_to: file, next: "Quit and reopen the app (Claude Desktop: fully quit, then open it again), then call snap_ping. The account is fixed when the server starts, so a running server keeps its old account." });
300
+ }
301
+ if (!redirected_url) {
302
+ pendingState = newState();
303
+ return asResult({
304
+ step: 1,
305
+ link: authorizeUrl({ clientId: e.SNAP_CLIENT_ID, redirectUri, state: pendingState }),
306
+ 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.",
307
+ });
308
+ }
309
+ if (!pendingState) throw new Error("Start with snap_connect without arguments to get a fresh link.");
310
+ const token = await exchangeCode({ clientId: e.SNAP_CLIENT_ID, clientSecret: e.SNAP_CLIENT_SECRET, redirectUri, code: extractCode(redirected_url, pendingState), fetchImpl: client.fetch });
311
+ pendingState = null;
312
+ setEnvValue("SNAP_REFRESH_TOKEN", token, file);
313
+ e.SNAP_REFRESH_TOKEN = token;
314
+ client.token = null;
315
+ client.tokenExpiry = 0;
316
+ const accounts = await listAdAccounts(client);
317
+ return asResult({ step: 2, connected: true, saved_to: file, ad_accounts: accounts, next: accounts.length ? "Ask the person which ad account to use, then call snap_connect with its ad_account_id." : "This login sees no ad account. The account admin must add it first." });
318
+ } catch (err) {
319
+ return fail(err);
320
+ }
321
+ },
322
+ );
323
+
271
324
  // Lists read every page, apply the status filter to ALL rows, and only then cut to `limit`. If anything was left out, say so.
272
325
  const nameFilter = z.string().min(1).max(100).optional().describe("Only items whose name contains this text (case-insensitive). Use it to find one item in a big account.");
273
326
  const listRows = async (path, entity, { status, limit, nameContains }) => {