ads-mcp-for-snapchat 0.9.5 → 0.9.8

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 CHANGED
@@ -9,6 +9,8 @@ SNAP_AD_ACCOUNT_ID=
9
9
  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
+ # Optional: only read media and customer-list files from this folder (absolute path).
13
+ # SNAP_MEDIA_DIR=
12
14
  SNAP_MIN_DAILY_BUDGET=5
13
15
  SNAP_MAX_BID=50
14
16
  SNAP_MAX_BUDGET_INCREASE_PCT=100
@@ -23,7 +25,7 @@ SNAP_REPORT_UTC_OFFSET=+00:00
23
25
  # Optional: SNAP_BROKER_URL=https://login.example.com (the shared login service; a refresh token is sent there, so use only one you trust)
24
26
  # Optional: SNAP_HOME=/some/folder (where settings, the change log and exports live; default ~/.ads-mcp-for-snapchat for an npm install)
25
27
  # Optional: SNAP_PORTFOLIO_FILES=/abs/path/.env,/abs/path/.env.account2 (accounts shown side by side by snap_portfolio_summary)
26
- # Optional: SNAP_TOOLSETS=setup,reports,checks (show only these tool groups: setup, read, reports, checks, changes, create; default all)
28
+ # Optional: SNAP_TOOLSETS=setup,reports,checks (show only these tool groups: core, setup, read, reports, checks, changes, create; default all)
27
29
  # Optional: SNAP_MAX_LIFETIME_BUDGET, SNAP_MAX_ACTIVATION_DAILY_BUDGET, SNAP_MAX_ADDED_DAILY_BUDGET_24H, SNAP_ACCOUNT_CURRENCY=USD,
28
30
  # SNAP_READ_ONLY=1, SNAP_HUMAN_APPROVAL=elicit (see README "Safety settings")
29
31
  # Only needed once, by scripts/get-refresh-token.js (must match the redirect URL on your OAuth app)
package/ARCHITECTURE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Architecture and design notes
2
2
 
3
- For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API: 85 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: 78 tools, all tests mocked (`npm test`). Read `README.md` first for setup and the tool table.
4
4
 
5
5
  ## Architecture (src/)
6
6
  - `portfolio.js`: several accounts side by side, from the settings files the owner lists in SNAP_PORTFOLIO_FILES (read-only).
package/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.9.8 (2026-11-21)
6
+
7
+ - **Fix: the Claude Desktop extension did not start after upgrading to 0.9.7.** 0.9.7 added a required setting (Tool set); an upgraded install has no saved value for it, and Desktop then reports "No MCP config found" and never starts the server. The setting is now optional, the extension passes `SNAP_TOOLSETS_DEFAULT=core`, and the server uses it when the Tool set is empty or was never saved. Tests start the server in every state of the setting and keep new extension settings optional.
8
+
9
+ ## 0.9.7 (2026-11-21)
10
+
11
+ Three changes together: fewer tools (merged near-duplicates, a core tool set), interactive cards (MCP Apps), and the quality-audit fixes. Existing tool names keep working behind `SNAP_LEGACY_TOOLS=1`; see the entries below. The Claude Desktop extension now starts with the core tool set and changes allowed (see 0.9.5).
12
+
13
+ - **Interactive cards (MCP Apps).** New read-only tools `snap_dashboard` (spend, ROAS, purchases, pacing, 7/14/30-day switch) and `snap_campaign_board` (campaigns with Pause and Resume buttons), and a preview card for every tool that previews a change, with an Apply button. Cards are optional: apps without card support get the same answers as text and data. The buttons use the same previews, approval tokens, limits and read-only setting; the cards have no network access and show account names as plain text. 76 tools became 78, and both new tools are in the core set (now 46).
14
+
15
+ - **Core tool set.** `SNAP_TOOLSETS=core` shows 44 everyday tools (read, check, launch campaigns, undo, and every tool the playbooks use); it can be combined with groups (`core,reports`). The Claude Desktop extension now starts with `core`; type `all` in its Tool set field to see every tool.
16
+
17
+ - **Fewer tools (85 to 76).** Tools that did the same job are now one: `snap_set_status`, `snap_rename`, `snap_set_schedule`, `snap_exclude_segments` and `snap_set_daily_budget` take `id` for one item or `ids` (`adsquad_ids`) for up to 20, and `snap_report` takes `view` = table, daily, hourly, compare or audience. The old tools do the work as before (every limit, preview and approval is the same); only the names changed. The old names are hidden unless `SNAP_LEGACY_TOOLS=1`, and then work as deprecated aliases.
18
+
19
+ ## 0.9.6 (2026-11-21)
20
+
21
+ From the quality audit (see AUDIT-REPORT.md). No tool was renamed or removed.
22
+
23
+ - Dates: wherever a tool takes `start_time`, `end_time` or the compare-window times, a plain `YYYY-MM-DD` now works (it means 00:00 that day in `SNAP_REPORT_UTC_OFFSET`); ISO date-times on the hour still work.
24
+ - Long answers: new `SNAP_MAX_RESPONSE_CHARS` (default 100000). A longer answer is cut with a note saying how to ask for less.
25
+ - The list tools declare an `outputSchema` (`items`, `returned`, `total_matching`, `has_more`, `next_offset`, `notes`).
26
+
27
+ - Errors: Snap HTTP errors now end with a plain "Fix:" sentence (re-run setup, ask an Admin, get the id from a list tool, wait N seconds).
28
+ - Descriptions: every parameter of every tool now has a description (where its id comes from, units, examples); 22 tools got a "use this / not that" pointer. A test keeps it at 100%.
29
+ - Lists: `snap_list_*` tools take `offset` and `response_format` (concise or detailed) and report `has_more` and `next_offset`. `snap_list_pixels`, `snap_list_catalogs` and `snap_list_product_sets` gained `limit`.
30
+ - Results that are objects are also returned as `structuredContent` next to the text; list answers are `{ items, returned, total_matching, has_more, next_offset }`.
31
+ - Ten read-only evaluation questions with known answers (`test/eval/questions.json`), run by the tests. README: examples, permissions, rate limits.
32
+
33
+ - Safety: `snap_set_frequency_cap`, `snap_set_ad_schedule`, `snap_set_placement` and `snap_claim_ad_code` are now marked destructive (they overwrite settings or use up a single-use code). New optional `SNAP_MEDIA_DIR`: when set, media and customer-list files must be inside that folder (symbolic links resolved).
34
+
5
35
  ## 0.9.5 (2026-11-17)
6
36
 
7
37
  - **Claude Desktop extension starts with changes allowed** (Read-only is off by default) and a daily budget limit of 500. Every change is still previewed and needs approval, everything created starts paused, and the limit and the new budget warning apply. `npx ... setup` still starts read-only unless you choose otherwise.
package/README.md CHANGED
@@ -5,7 +5,7 @@ A local [MCP](https://modelcontextprotocol.io) server that lets an AI assistant
5
5
  > **Unofficial.** Not affiliated with or endorsed by Snap Inc. This tool can change real ad campaigns that spend real money. You use it at your own risk (see LICENSE). Check Snap's developer terms for your own use. Review every preview before approving.
6
6
 
7
7
  ## Get started in 2 minutes
8
- **Claude Desktop (no terminal):** download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snapchat-ads-mcp/releases/latest), open it, leave Client ID and secret empty, then ask Claude: "Connect my Snapchat ad account." Log in with Snapchat and pick the ad account. In the Desktop extension, changes are **allowed from the start** (Read-only is off by default): each one is previewed and needs your approval, everything created starts paused, and the daily budget limit starts at 500 (change it in the extension's settings). Switch Read-only on there if you only want to look.
8
+ **Claude Desktop (no terminal):** download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snapchat-ads-mcp/releases/latest), open it, leave Client ID and secret empty, then ask Claude: "Connect my Snapchat ad account." Log in with Snapchat and pick the ad account. In the Desktop extension, changes are **allowed from the start** (Read-only is off by default): each one is previewed and needs your approval, everything created starts paused, and the daily budget limit starts at 500 (change it in the extension's settings). Switch Read-only on there if you only want to look. It also starts with the **core** tool set (46 everyday tools); type `all` in its Tool set field to see all 78.
9
9
 
10
10
  **Claude Code, Cursor, VS Code or a terminal:**
11
11
  ```bash
@@ -102,6 +102,10 @@ With this setting the server asks **you**, through the MCP client's own dialog (
102
102
  | Setting | Default | Meaning |
103
103
  |---|---|---|
104
104
  | `SNAP_MAX_DAILY_BUDGET` | 1000 | Highest daily budget any single campaign or ad squad may be given or enabled with |
105
+ | `SNAP_MAX_RESPONSE_CHARS` | 100000 | Longest answer a tool returns; longer ones are cut with a note saying how to ask for less. |
106
+ | `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. |
107
+ | `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. |
108
+ | `SNAP_MEDIA_DIR` | (none) | Optional folder allow-list: when set, `snap_upload_media` and `snap_upload_customer_list` only read files inside this folder (symbolic links are resolved first). Recommended, so the server cannot be steered into reading other files on your computer. |
105
109
  | `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`). |
106
110
  | `SNAP_MIN_DAILY_BUDGET` | 5 | Lowest daily budget |
107
111
  | `SNAP_MAX_BID` | 50 | Highest max bid |
@@ -116,7 +120,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
116
120
  | `SNAP_BROKER_URL` | the maintainer's login service (`off` turns the shared login off) | The shared login service: connect with a normal Snapchat login and no OAuth app. https only. A refresh token is sent there, so use only a service you trust (see `PRIVACY.md`, `broker/README.md`). `setup` saves it for you. |
117
121
  | `SNAP_HOME` | `~/.ads-mcp-for-snapchat` for an npm install, the project folder for a git checkout | Where the settings file, the change log and `exports/` live. Set it to keep them somewhere else. |
118
122
  | `SNAP_PORTFOLIO_FILES` | (none) | Absolute paths of the settings files of the accounts for `snap_portfolio_summary`, comma-separated (up to 10). Only you can set it: the AI app cannot pick files. |
119
- | `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `setup, read, reports, checks, changes, create` (comma-separated). Fewer tools make some apps faster and less error-prone, e.g. `setup,reports,checks` for an analyst. It only hides tools. |
123
+ | `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `core` (46 everyday tools: read, check and launch campaigns), or `setup, read, reports, checks, changes, create` (comma-separated, can be combined with core). The Claude Desktop extension starts with `core`; type `all` in its Tool set field to see every tool. Fewer tools make some apps faster and less error-prone, e.g. `setup,reports,checks` for an analyst. It only hides tools. |
120
124
  | `SNAP_HUMAN_APPROVAL` | off | `elicit` = ask the user through the MCP client before every write |
121
125
  | `SNAP_APPROVAL_TTL_SECONDS` | 600 | Lifetime of an approval token |
122
126
  | `SNAP_REPEAT_WINDOW_SECONDS` | 600 | An identical create, copy, claim or upload is refused within this time |
@@ -156,7 +160,6 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
156
160
  | `snap_capi_status`, `snap_capi_test_event` | Conversions API TEST events only: read the last test events and their errors; send one test event (previewed, email hashed). No tool sends real conversion events. |
157
161
  | `snap_set_frequency_cap` | write (preview + approval): at most N impressions per person per N hours/days, or clear it |
158
162
  | `snap_set_ad_schedule` | write (preview + approval): which hours of which days ads run; Snap allows it only on lifetime-budget ad squads |
159
- | `snap_report_hourly` | read: spend, purchases and ROAS by local hour of the day (last 1-7 days), best and worst hours |
160
163
  | `snap_creative_compare` | read: the ads of a campaign or ad squad ranked against the median ROAS (WINNER / LAGGING), grouped by call to action |
161
164
  | `snap_budget_advice` | read: suggested daily-budget moves (lower the weak, raise the proven, funded by what is freed, inside your limits), each naming the tool that applies it |
162
165
  | `snap_billing_check` | read: ad account status, funding sources (card expiry, daily limit vs budgets, credit left) and a verdict |
@@ -169,30 +172,27 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
169
172
  | `snap_portfolio_summary` | read: all your ad accounts side by side (yesterday and last 7 days, what needs attention, totals per currency). Reads the settings files you list in `SNAP_PORTFOLIO_FILES`; the AI app cannot choose files. |
170
173
  | `snap_connect` | connect an ad account from inside the chat (link, pasted address, account choice); saves access on this computer, changes no ads |
171
174
  | `snap_list_campaigns`, `snap_list_adsquads`, `snap_list_ads`, `snap_list_creatives`, `snap_get_entity`, `snap_get_media`, `snap_get_stats` | read |
172
- | `snap_report` | read: ROAS, CPA, swipe rate, frequency by ad squad or ad |
173
- | `snap_report_daily` | read: day-by-day performance (up to 31 days) |
174
- | `snap_report_audience` | read: performance by country, gender, age, region, dma or make |
175
+ | `snap_dashboard`, `snap_campaign_board` | read: interactive cards (see "Interactive cards" below): an account dashboard (spend, ROAS, purchases, pacing, 7/14/30 days) and a campaign list with Pause and Resume buttons. Without card support the same numbers come back as data |
176
+ | `snap_report` | read: performance reports. `view` = `table` (ROAS, CPA, swipe rate, frequency by ad squad or ad; the default), `daily` (day by day, up to 31 days), `hourly` (by local hour of the day, last 1-7 days, best and worst hours), `compare` (two time windows side by side) or `audience` (by country, gender, age, region, dma or make) |
175
177
  | `snap_health_check` | read: audits every active squad for missing buyer exclusion, high frequency, low swipe rate, low ROAS, spend with no purchases, paused parents |
176
178
  | `snap_review_issues` | read: rejected / pending ads with Snap's reasons |
177
179
  | `snap_pixel_health` | read: pixel signal readiness and event-quality issues, top priority first |
178
180
  | `snap_creative_fatigue` | read: which ads are tired (ROAS down 30%+ with higher frequency or lower swipe rate), which to replace first |
179
- | `snap_report_compare` | read: two time windows side by side with the changes |
180
181
  | `snap_report_async_start`, `snap_report_async_status`, `snap_report_async_download` | read: very large CSV reports saved to `exports/` |
181
182
  | `snap_api_get` | read-only GET for anything else (allow-listed paths, never writes) |
182
183
  | `snap_list_segments`, `snap_list_pixels`, `snap_list_catalogs`, `snap_list_product_sets`, `snap_targeting_options` | read: audiences, pixels, catalogs, product sets, interest/region/language ids |
183
184
  | `snap_change_log` | read the local log |
184
- | `snap_set_status`, `snap_set_status_bulk` | pause / enable (bulk up to 20, warns when a parent is paused) |
185
- | `snap_set_daily_budget`, `snap_set_bid`, `snap_rename` | edit |
185
+ | `snap_set_status` | pause / enable one item (`id`) or up to 20 (`ids`; skips items already in that state, warns when a parent is paused) |
186
+ | `snap_set_daily_budget`, `snap_set_bid`, `snap_rename` | edit. `snap_set_daily_budget` also takes `adsquad_ids` with `mode` set or scale for up to 20 ad squads; `snap_rename` takes `ids` with `find` and `replace` for up to 20 items |
186
187
  | `snap_set_targeting` | change countries, age, gender, interests, device OS, include segments, stop excluding segments; everything else is kept |
187
- | `snap_set_schedule` | set start/end time on a campaign or ad squad |
188
- | `snap_exclude_segments` | add buyer-exclusion audiences to an ad squad |
188
+ | `snap_set_schedule` | set start/end time on a campaign or ad squad (`id`), or on up to 20 (`ids`) |
189
+ | `snap_exclude_segments` | add buyer-exclusion audiences to an ad squad (`adsquad_id`), or to up to 20 (`adsquad_ids`) |
189
190
  | `snap_copy_campaign` | copy a campaign (all or selected ad squads, with or without ads), paused |
190
191
  | `snap_create_campaign` | create a new empty campaign, paused |
191
192
  | `snap_create_adsquad` | create a new purchase-optimized web ad squad (max bid or auto-bid, interests, device OS, buyer exclusions), paused |
192
193
  | `snap_create_lookalike` | create a lookalike audience from a customer-list seed |
193
194
  | `snap_copy_adsquad` | copy one ad squad into a campaign, paused |
194
195
  | `snap_clone_ad` | clone an ad into other ad squads, paused (skips duplicates and different product sets) |
195
- | `snap_bulk_exclude_segments`, `snap_bulk_set_budget`, `snap_bulk_set_schedule`, `snap_bulk_rename` | edit up to 20 items at once with a per-item preview; stop at the first failure |
196
196
  | `snap_undo` | revert a change from the log (refuses if the field changed again since) |
197
197
  | `snap_clone_creative` | duplicate a creative with a new name/headline/link |
198
198
  | `snap_create_pixel_audience` | audience of people who fired pixel events (e.g. ADD_CART) |
@@ -207,6 +207,31 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
207
207
  | `snap_create_collection_creative` | Collection Ad: a main image or video with 4-20 product tiles, each opening its own page |
208
208
  | `snap_influencer_ad` | the whole influencer flow in one step: claim, wait for media, creative, paused ad |
209
209
 
210
+ ## Interactive cards (MCP Apps)
211
+ In AI apps that support [MCP Apps](https://modelcontextprotocol.io) (for example Claude), some tools show a small interactive card inside the chat instead of only text:
212
+ - **`snap_dashboard`**: spend, ROAS, purchases, cost per purchase and swipe rate for 7, 14 or 30 days (switch with the buttons), spend by day, and this month's pacing.
213
+ - **`snap_campaign_board`**: every campaign with its 7-day spend and ROAS. **Pause** and **Resume** buttons first show what would change, and nothing happens until you press **Confirm**.
214
+ - **Preview card**: every tool that previews a change (create, budget, status, schedule and so on) shows its preview as a card with an **Apply** button that uses the approval token of that exact preview.
215
+
216
+ How they stay safe: the buttons call the same tools with the same previews, approval tokens, spend limits and read-only setting as before; with `SNAP_READ_ONLY` on, Confirm and Apply stay disabled. The cards have no network access, show names from your account as plain text (never as code), and follow the app's light or dark theme. In apps without card support nothing changes: the same answers arrive as text and data.
217
+
218
+ ## Examples, permissions and limits
219
+ **Things to ask your assistant** (each names the tool it will use):
220
+ - "Which campaigns are running?" (`snap_list_campaigns`, status ACTIVE)
221
+ - "How is spend pacing this month?" (`snap_spend_pacing`)
222
+ - "Which ad squads are wasting money?" (`snap_budget_advice`, `snap_health_check`)
223
+ - "Create a paused traffic campaign called Spring sale." (`snap_create_campaign`, previewed first)
224
+ - "Raise the daily budget of ad squad X to 40." (`snap_set_daily_budget`, previewed, with a warning if the amount is unusual)
225
+ - "Undo the last change." (`snap_undo`)
226
+
227
+ **Snapchat permissions.** The Snapchat login must have access to the ad account in Ads Manager. Reading and changing both go through the login's own rights: if the login can edit campaigns in Ads Manager, so can this server; if it can only view, changes fail. Check the roles in Ads Manager under Members. Asking Snap for an item your login cannot see returns a 403 with a hint.
228
+
229
+ **Rate limits.** Snap limits how many requests a login may send. The server retries reads on 429 and 5xx and honours Snap's `Retry-After`; writes are retried only on 429, never after a network failure (so a change is never applied twice). If Snap still refuses, the error says how long to wait.
230
+
231
+ **Long lists.** `snap_list_*` tools take `limit`, `offset` and `response_format` (`concise` = id, name, status; `detailed` = everything). Each answer says `has_more` and `next_offset`. Results also come back as structured data next to the text.
232
+
233
+ **Evaluation questions.** `test/eval/questions.json` holds ten read-only questions with known answers; `npm test` runs them against a fake Snap.
234
+
210
235
  ## Influencer ad-code flow
211
236
  Creators share a code like `adcode_<uuid>`. `snap_influencer_ad` claims it into the ad account (`POST /adaccounts/{id}/claim_media_by_ad_code?ad_code=&profile_id=`, parameters go in the query string), waits for the media to be READY, creates a WEB_VIEW creative on the brand profile (`SNAP_BRAND_PROFILE_ID`) and creates a **paused** ad in the ad squad you choose.
212
237
  Notes from live use:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ads-mcp-for-snapchat",
3
- "version": "0.9.5",
3
+ "version": "0.9.8",
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",
@@ -0,0 +1,152 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Campaigns</title>
7
+ <style>
8
+ :root{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb}
9
+ @media (prefers-color-scheme:dark){:root{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff}}
10
+ :root[data-theme=light]{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb}
11
+ :root[data-theme=dark]{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff}
12
+ :root{--bg:var(--color-background-primary,var(--fb-bg));--bg2:var(--color-background-secondary,var(--fb-bg2));--text:var(--color-text-primary,var(--fb-text));--muted:var(--color-text-secondary,var(--fb-muted));--border:var(--color-border-primary,var(--fb-border));--good:var(--color-text-success,var(--fb-good));--bad:var(--color-text-danger,var(--fb-bad));--warn:var(--color-text-warning,var(--fb-warn))}
13
+ *{box-sizing:border-box}
14
+ body{margin:0;padding:16px;background:var(--bg);color:var(--text);font:14px/1.45 var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif)}
15
+ h1{font-size:18px;margin:0}
16
+ header{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between;margin-bottom:12px}
17
+ .sub{color:var(--muted);font-size:12px}
18
+ .seg{display:flex;border:1px solid var(--border);border-radius:10px;overflow:hidden}
19
+ .seg button{min-height:44px;min-width:56px;padding:0 14px;border:0;background:var(--bg);color:var(--text);font:inherit;cursor:pointer}
20
+ .seg button+button{border-left:1px solid var(--border)}
21
+ .seg button[aria-pressed=true]{background:var(--accent);color:#fff}
22
+ .row{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:12px;margin-bottom:10px}
23
+ .top{display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap}
24
+ .name{font-weight:650;overflow-wrap:anywhere}
25
+ .pill{display:inline-block;padding:1px 8px;border-radius:999px;font-size:11px;border:1px solid var(--border);margin-right:6px}
26
+ .pill.on{color:var(--good);border-color:var(--good)}
27
+ .meta{color:var(--muted);font-size:12px;margin-top:2px}
28
+ button.act{min-height:44px;min-width:96px;padding:0 16px;border-radius:10px;border:1px solid var(--border);background:var(--bg);color:var(--text);font:inherit;cursor:pointer}
29
+ button.act.primary{background:var(--accent);border-color:var(--accent);color:#fff}
30
+ button:disabled{opacity:.55;cursor:default}
31
+ button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
32
+ .panel{margin-top:10px;border-top:1px dashed var(--border);padding-top:10px}
33
+ .panel dl{margin:0 0 8px;display:grid;grid-template-columns:max-content 1fr;gap:2px 12px}
34
+ .panel dt{color:var(--muted)}.panel dd{margin:0;overflow-wrap:anywhere}
35
+ .btns{display:flex;gap:8px;flex-wrap:wrap}
36
+ .warn{color:var(--warn)}.err{color:var(--bad)}.ok{color:var(--good)}
37
+ .skeleton{background:linear-gradient(90deg,var(--bg2),var(--border),var(--bg2));background-size:200% 100%;animation:sk 1.2s linear infinite;border-radius:12px;min-height:72px;margin-bottom:10px}
38
+ @keyframes sk{to{background-position:-200% 0}}
39
+ @media (prefers-reduced-motion:reduce){.skeleton{animation:none}}
40
+ </style>
41
+ </head>
42
+ <body>
43
+ <main>
44
+ <header>
45
+ <div><h1>Campaigns</h1><div class="sub" id="sub">Loading...</div></div>
46
+ <div class="seg" role="group" aria-label="Show" id="seg"></div>
47
+ </header>
48
+ <section id="list" aria-live="polite"><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div></section>
49
+ <p class="sub warn" id="warn" hidden></p>
50
+ </main>
51
+ <!--BRIDGE-->
52
+ <script>
53
+ (function () {
54
+ const { el, num } = window.snapApp;
55
+ const $ = (id) => document.getElementById(id);
56
+ const state = { data: null, filter: "ALL", open: null };
57
+
58
+ function seg() {
59
+ const s = $("seg");
60
+ s.textContent = "";
61
+ for (const [key, label] of [["ALL", "All"], ["ACTIVE", "Active"], ["PAUSED", "Paused"]]) s.append(el("button", { type: "button", "aria-pressed": String(state.filter === key), onclick: () => { state.filter = key; state.open = null; render(); } }, label));
62
+ }
63
+
64
+ function render() {
65
+ const d = state.data;
66
+ seg();
67
+ const list = $("list");
68
+ list.textContent = "";
69
+ if (!d) return;
70
+ const cur = d.account && d.account.currency ? " " + d.account.currency : "";
71
+ $("sub").textContent = d.summary;
72
+ const rows = d.campaigns.filter((c) => state.filter === "ALL" || c.status === state.filter);
73
+ if (!rows.length) list.append(el("div", { class: "sub" }, "No campaigns to show."));
74
+ for (const c of rows) list.append(row(c, cur));
75
+ if (d.has_more) list.append(el("div", { class: "sub" }, "Showing " + d.campaigns.length + " of " + d.total_campaigns + ". Ask for the rest in the chat."));
76
+ const w = $("warn");
77
+ w.hidden = !(d.warnings && d.warnings.length);
78
+ w.textContent = (d.warnings || []).join(" ");
79
+ window.snapApp.resize();
80
+ }
81
+
82
+ function row(c, cur) {
83
+ const active = c.status === "ACTIVE";
84
+ const target = active ? "PAUSED" : "ACTIVE";
85
+ const box = el("div", { class: "row" });
86
+ box.append(el("div", { class: "top" },
87
+ el("div", null, el("div", { class: "name" }, c.name), el("div", { class: "meta" }, el("span", { class: "pill" + (active ? " on" : "") }, c.status), "7-day spend " + num(c.spend_7d) + cur + " | ROAS " + num(c.roas_7d) + (c.active_daily_budget != null ? " | active daily budgets " + num(c.active_daily_budget) + cur : ""))),
88
+ el("button", { class: "act", type: "button", onclick: () => ask(c, target, box) }, active ? "Pause" : "Resume")));
89
+ if (state.open === c.id && c._panel) box.append(c._panel);
90
+ return box;
91
+ }
92
+
93
+ async function ask(c, status, box) {
94
+ state.open = c.id;
95
+ const panel = el("div", { class: "panel" }, el("div", { class: "sub" }, "Checking what would change..."));
96
+ c._panel = panel;
97
+ box.querySelector(".panel") && box.querySelector(".panel").remove();
98
+ box.append(panel);
99
+ try {
100
+ const r = await window.snapApp.call("snap_set_status", { entity: "campaign", id: c.id, status });
101
+ const text = window.snapApp.textOf(r);
102
+ if (r.isError) { panel.textContent = ""; panel.append(el("div", { class: "err" }, text)); return; }
103
+ const p = window.snapApp.dataOf(r) || {};
104
+ panel.textContent = "";
105
+ const pv = p.preview || {};
106
+ const rows = [["Change", c.name + ": " + c.status + " to " + status]];
107
+ if (pv.daily_budget_that_would_start_delivering !== undefined) rows.push(["Daily budget that would start spending", num(pv.daily_budget_that_would_start_delivering) + (p.ad_account ? "" : "")]);
108
+ if (pv.note) rows.push(["Note", pv.note]);
109
+ const dl = el("dl", null, rows.map(([k, v]) => [el("dt", null, k), el("dd", null, v)]));
110
+ panel.append(dl);
111
+ if (p.read_only) panel.append(el("div", { class: "warn" }, p.read_only));
112
+ if (p.budget_warning) panel.append(el("div", { class: "warn" }, p.budget_warning.message));
113
+ if (p.duplicate_warning) panel.append(el("div", { class: "warn" }, p.duplicate_warning));
114
+ const confirm = el("button", { class: "act primary", type: "button", disabled: !p.approval_token || !!p.read_only, onclick: () => apply(c, status, p.approval_token, panel, confirm, cancel) }, "Confirm " + (status === "PAUSED" ? "pause" : "resume"));
115
+ const cancel = el("button", { class: "act", type: "button", onclick: () => { state.open = null; c._panel = null; render(); } }, "Cancel");
116
+ panel.append(el("div", { class: "btns" }, confirm, cancel));
117
+ window.snapApp.resize();
118
+ } catch (e) {
119
+ panel.textContent = "";
120
+ panel.append(el("div", { class: "err" }, "Could not preview: " + e.message));
121
+ }
122
+ }
123
+
124
+ async function apply(c, status, token, panel, confirm, cancel) {
125
+ confirm.disabled = true;
126
+ cancel.disabled = true;
127
+ try {
128
+ const r = await window.snapApp.call("snap_set_status", { entity: "campaign", id: c.id, status, confirm: true, approval_token: token });
129
+ if (r.isError) { panel.append(el("div", { class: "err" }, window.snapApp.textOf(r))); cancel.disabled = false; return; }
130
+ c.status = status;
131
+ state.open = null;
132
+ c._panel = null;
133
+ render();
134
+ } catch (e) {
135
+ panel.append(el("div", { class: "err" }, "Could not apply: " + e.message));
136
+ cancel.disabled = false;
137
+ }
138
+ }
139
+
140
+ seg();
141
+ window.snapApp.connect({
142
+ "ui/notifications/tool-result": (r) => {
143
+ if (r && r.isError) { $("sub").textContent = window.snapApp.textOf(r); return; }
144
+ state.data = window.snapApp.dataOf(r);
145
+ render();
146
+ },
147
+ error: (e) => { $("sub").textContent = "Not connected to the chat app: " + e.message; },
148
+ });
149
+ })();
150
+ </script>
151
+ </body>
152
+ </html>
@@ -0,0 +1,99 @@
1
+ // Shared by the three cards. Talks to the chat app over postMessage using the MCP Apps protocol (2026-01-26): it starts with
2
+ // ui/initialize, receives the tool's input and result as notifications, and can call this server's tools through the app.
3
+ // Everything shown is written as text nodes (never as markup), because names in an ad account are untrusted text.
4
+ (function () {
5
+ const pending = new Map();
6
+ const handlers = {};
7
+ const state = { ctx: {}, nextId: 1 };
8
+ const post = (msg) => window.parent.postMessage(Object.assign({ jsonrpc: "2.0" }, msg), "*");
9
+ const request = (method, params) =>
10
+ new Promise((resolve, reject) => {
11
+ const id = state.nextId++;
12
+ pending.set(id, { resolve, reject });
13
+ post({ id, method, params });
14
+ });
15
+ const notify = (method, params) => post({ method, params });
16
+
17
+ function applyContext(ctx) {
18
+ if (!ctx) return;
19
+ Object.assign(state.ctx, ctx);
20
+ const root = document.documentElement;
21
+ if (ctx.theme) root.setAttribute("data-theme", ctx.theme);
22
+ const vars = ctx.styles && ctx.styles.variables;
23
+ if (vars) for (const k in vars) if (vars[k]) root.style.setProperty(k, vars[k]);
24
+ }
25
+
26
+ window.addEventListener("message", (event) => {
27
+ if (event.source !== window.parent) return;
28
+ const m = event.data;
29
+ if (!m || m.jsonrpc !== "2.0") return;
30
+ if (m.id !== undefined && m.method === undefined) {
31
+ const p = pending.get(m.id);
32
+ if (!p) return;
33
+ pending.delete(m.id);
34
+ if (m.error) p.reject(new Error(m.error.message || "Request failed"));
35
+ else p.resolve(m.result);
36
+ return;
37
+ }
38
+ if (!m.method) return;
39
+ if (m.method === "ui/notifications/host-context-changed") applyContext(m.params);
40
+ const handler = handlers[m.method];
41
+ try {
42
+ if (handler) handler(m.params);
43
+ } catch (e) {
44
+ console.error(e);
45
+ }
46
+ if (m.id !== undefined) post({ id: m.id, result: {} }); // the host asked something (ping, teardown): answer it
47
+ });
48
+
49
+ function resize() {
50
+ notify("ui/notifications/size-changed", { height: Math.ceil(document.documentElement.scrollHeight) });
51
+ }
52
+
53
+ function el(tag, attrs, ...children) {
54
+ const node = document.createElement(tag);
55
+ for (const k in attrs || {}) {
56
+ if (k === "class") node.className = attrs[k];
57
+ else if (k.startsWith("on")) node.addEventListener(k.slice(2), attrs[k]);
58
+ else if (attrs[k] !== undefined && attrs[k] !== null && attrs[k] !== false) node.setAttribute(k, attrs[k] === true ? "" : attrs[k]);
59
+ }
60
+ for (const c of children.flat(Infinity)) if (c !== undefined && c !== null && c !== false) node.append(c.nodeType ? c : document.createTextNode(String(c)));
61
+ return node;
62
+ }
63
+ const num = (n, d) => (n === null || n === undefined || Number.isNaN(Number(n)) ? "n/a" : Number(n).toLocaleString(undefined, { maximumFractionDigits: d === undefined ? 2 : d }));
64
+ const textOf = (r) => ((r && r.content) || []).filter((c) => c.type === "text").map((c) => c.text).join("\n");
65
+ // The data of a tool result: structuredContent when the app sent it, otherwise the JSON text.
66
+ const dataOf = (r) => {
67
+ if (r && r.structuredContent) return r.structuredContent;
68
+ try {
69
+ return JSON.parse(textOf(r));
70
+ } catch {
71
+ return null;
72
+ }
73
+ };
74
+
75
+ function connect(on) {
76
+ Object.assign(handlers, on || {});
77
+ request("ui/initialize", { protocolVersion: "2026-01-26", appInfo: { name: "Ads MCP for Snapchat", version: "1" }, appCapabilities: {} })
78
+ .then((res) => {
79
+ applyContext(res && res.hostContext);
80
+ notify("ui/notifications/initialized", {});
81
+ if (handlers.ready) handlers.ready(state.ctx);
82
+ })
83
+ .catch((e) => handlers.error && handlers.error(e));
84
+ if (window.ResizeObserver) new ResizeObserver(resize).observe(document.body);
85
+ }
86
+
87
+ window.snapApp = {
88
+ connect,
89
+ el,
90
+ num,
91
+ textOf,
92
+ dataOf,
93
+ resize,
94
+ call: (name, args) => request("tools/call", { name, arguments: args || {} }),
95
+ get ctx() {
96
+ return state.ctx;
97
+ },
98
+ };
99
+ })();
@@ -0,0 +1,173 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Account dashboard</title>
7
+ <style>
8
+ :root{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb}
9
+ @media (prefers-color-scheme:dark){:root{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff}}
10
+ :root[data-theme=light]{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb}
11
+ :root[data-theme=dark]{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff}
12
+ :root{--bg:var(--color-background-primary,var(--fb-bg));--bg2:var(--color-background-secondary,var(--fb-bg2));--text:var(--color-text-primary,var(--fb-text));--muted:var(--color-text-secondary,var(--fb-muted));--border:var(--color-border-primary,var(--fb-border));--good:var(--color-text-success,var(--fb-good));--bad:var(--color-text-danger,var(--fb-bad));--warn:var(--color-text-warning,var(--fb-warn))}
13
+ *{box-sizing:border-box}
14
+ body{margin:0;padding:16px;background:var(--bg);color:var(--text);font:14px/1.45 var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif)}
15
+ h1{font-size:18px;margin:0}h2{font-size:14px;margin:0 0 8px;color:var(--muted);font-weight:600}
16
+ header{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between;margin-bottom:14px}
17
+ .sub{color:var(--muted);font-size:12px}
18
+ .seg{display:flex;border:1px solid var(--border);border-radius:10px;overflow:hidden}
19
+ .seg button{min-height:44px;min-width:56px;padding:0 14px;border:0;background:var(--bg);color:var(--text);font:inherit;cursor:pointer}
20
+ .seg button+button{border-left:1px solid var(--border)}
21
+ .seg button[aria-pressed=true]{background:var(--accent);color:#fff}
22
+ .seg button:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
23
+ .tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px;margin-bottom:14px}
24
+ .tile,.card{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:12px}
25
+ .tile .label{color:var(--muted);font-size:12px}.tile .value{font-size:22px;font-weight:650;margin-top:2px}
26
+ .card{margin-bottom:12px}
27
+ .bar{fill:var(--accent)}.axis{fill:var(--muted);font-size:10px}
28
+ .track{height:12px;border-radius:6px;background:var(--border);overflow:hidden;position:relative}
29
+ .fill{height:100%;background:var(--accent)}
30
+ .legend{display:flex;flex-wrap:wrap;gap:12px;color:var(--muted);font-size:12px;margin-top:6px}
31
+ .warn{color:var(--warn);font-size:12px;margin:8px 0 0}
32
+ .skeleton{background:linear-gradient(90deg,var(--bg2),var(--border),var(--bg2));background-size:200% 100%;animation:sk 1.2s linear infinite;border-radius:8px;min-height:64px}
33
+ @keyframes sk{to{background-position:-200% 0}}
34
+ .err{color:var(--bad)}
35
+ @media (prefers-reduced-motion:reduce){.skeleton{animation:none}}
36
+ </style>
37
+ </head>
38
+ <body>
39
+ <main>
40
+ <header>
41
+ <div><h1>Account dashboard</h1><div class="sub" id="sub">Loading...</div></div>
42
+ <div class="seg" role="group" aria-label="Period" id="seg"></div>
43
+ </header>
44
+ <section class="tiles" id="kpis" aria-live="polite"><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div></section>
45
+ <section class="card"><h2>Spend by day</h2><div id="chart"><div class="skeleton"></div></div></section>
46
+ <section class="card" id="pacing" hidden><h2>This month</h2><div id="pacingBody"></div></section>
47
+ <p class="warn" id="warn" hidden></p>
48
+ </main>
49
+ <!--BRIDGE-->
50
+ <script>
51
+ (function () {
52
+ const { el, num } = window.snapApp;
53
+ const state = { days: 7, busy: false };
54
+ const $ = (id) => document.getElementById(id);
55
+
56
+ function buttons() {
57
+ const seg = $("seg");
58
+ seg.textContent = "";
59
+ for (const d of [7, 14, 30]) {
60
+ seg.append(el("button", { type: "button", "aria-pressed": String(state.days === d), onclick: () => load(d) }, d + " days"));
61
+ }
62
+ }
63
+
64
+ function tile(label, value, tone) {
65
+ const v = el("div", { class: "value" }, value);
66
+ if (tone) v.style.color = "var(--" + tone + ")";
67
+ return el("div", { class: "tile" }, el("div", { class: "label" }, label), v);
68
+ }
69
+
70
+ function chart(daily) {
71
+ const box = $("chart");
72
+ box.textContent = "";
73
+ if (!daily || !daily.length) { box.append(el("div", { class: "sub" }, "No daily data for this period.")); return; }
74
+ const W = 600, H = 150, padL = 4, padB = 18;
75
+ const max = Math.max.apply(null, daily.map((d) => d.spend)) || 1;
76
+ const bw = (W - padL) / daily.length;
77
+ const ns = "http://www.w3.org/2000/svg";
78
+ const svg = document.createElementNS(ns, "svg");
79
+ svg.setAttribute("viewBox", "0 0 " + W + " " + H);
80
+ svg.setAttribute("role", "img");
81
+ svg.setAttribute("aria-label", "Bar chart of daily spend");
82
+ svg.style.width = "100%";
83
+ svg.style.height = "auto";
84
+ daily.forEach((d, i) => {
85
+ const h = Math.max(1, ((H - padB) * d.spend) / max);
86
+ const r = document.createElementNS(ns, "rect");
87
+ r.setAttribute("class", "bar");
88
+ r.setAttribute("x", String(padL + i * bw + bw * 0.12));
89
+ r.setAttribute("y", String(H - padB - h));
90
+ r.setAttribute("width", String(bw * 0.76));
91
+ r.setAttribute("height", String(h));
92
+ r.setAttribute("rx", "2");
93
+ const t = document.createElementNS(ns, "title");
94
+ t.textContent = d.date + ": spend " + num(d.spend) + ", purchases " + num(d.purchases, 0) + ", ROAS " + num(d.roas);
95
+ r.append(t);
96
+ svg.append(r);
97
+ });
98
+ [0, daily.length - 1].forEach((i, k) => {
99
+ const tx = document.createElementNS(ns, "text");
100
+ tx.setAttribute("class", "axis");
101
+ tx.setAttribute("x", String(k === 0 ? padL : W));
102
+ tx.setAttribute("y", String(H - 4));
103
+ tx.setAttribute("text-anchor", k === 0 ? "start" : "end");
104
+ tx.textContent = daily[i].date;
105
+ svg.append(tx);
106
+ });
107
+ box.append(svg, el("div", { class: "legend" }, el("span", null, "Highest day: " + num(max)), el("span", null, "Hover or tap a bar for the day's numbers")));
108
+ }
109
+
110
+ function pacing(p, cur) {
111
+ const sec = $("pacing"), body = $("pacingBody");
112
+ body.textContent = "";
113
+ if (!p) { sec.hidden = true; return; }
114
+ sec.hidden = false;
115
+ const top = Math.max(p.most_it_could_spend_this_month, p.projected_month_spend, p.month_to_date_spend) || 1;
116
+ const bar = (label, value, tone) => {
117
+ const f = el("div", { class: "fill" });
118
+ f.style.width = Math.min(100, (value / top) * 100) + "%";
119
+ if (tone) f.style.background = "var(--" + tone + ")";
120
+ return el("div", { style: "margin-bottom:10px" }, el("div", { class: "sub" }, label + ": " + num(value) + cur), el("div", { class: "track" }, f));
121
+ };
122
+ body.append(
123
+ bar("Spent so far", p.month_to_date_spend),
124
+ bar("Projected for the month", p.projected_month_spend, "warn"),
125
+ bar("Most it could spend (every active ad squad at full budget)", p.most_it_could_spend_this_month, "bad"),
126
+ el("div", { class: "sub" }, "Today: " + num(p.spend_today) + cur + " across " + num(p.active_squads, 0) + " active ad squads, daily budgets total " + num(p.active_daily_budgets_total) + cur)
127
+ );
128
+ }
129
+
130
+ function render(data) {
131
+ if (!data || !data.totals) { $("sub").textContent = "No data."; return; }
132
+ const cur = data.account && data.account.currency ? " " + data.account.currency : "";
133
+ state.days = data.range.days;
134
+ buttons();
135
+ $("sub").textContent = "Account " + data.account.id + " | last " + data.range.days + " days, ending today 00:00 (UTC" + data.range.utc_offset + ")";
136
+ const t = data.totals;
137
+ const k = $("kpis");
138
+ k.textContent = "";
139
+ k.append(tile("Spend" + cur, num(t.spend)), tile("ROAS", num(t.roas), t.roas === null ? "" : t.roas >= 1 ? "good" : "bad"), tile("Purchases", num(t.purchases, 0)), tile("Cost per purchase" + cur, num(t.cpa)), tile("Swipe rate", t.swipe_rate_pct === null ? "n/a" : num(t.swipe_rate_pct) + "%"));
140
+ chart(data.daily);
141
+ pacing(data.pacing, cur);
142
+ const w = $("warn");
143
+ w.hidden = !(data.warnings && data.warnings.length);
144
+ w.textContent = (data.warnings || []).join(" ");
145
+ window.snapApp.resize();
146
+ }
147
+
148
+ async function load(days) {
149
+ if (state.busy) return;
150
+ state.busy = true;
151
+ state.days = days;
152
+ buttons();
153
+ try {
154
+ const r = await window.snapApp.call("snap_dashboard", { days });
155
+ if (r.isError) { $("sub").textContent = window.snapApp.textOf(r); $("sub").className = "sub err"; }
156
+ else { $("sub").className = "sub"; render(window.snapApp.dataOf(r)); }
157
+ } catch (e) {
158
+ $("sub").textContent = "Could not load: " + e.message;
159
+ $("sub").className = "sub err";
160
+ } finally {
161
+ state.busy = false;
162
+ }
163
+ }
164
+
165
+ buttons();
166
+ window.snapApp.connect({
167
+ "ui/notifications/tool-result": (r) => { if (r && !r.isError) render(window.snapApp.dataOf(r)); else if (r) { $("sub").textContent = window.snapApp.textOf(r); $("sub").className = "sub err"; } },
168
+ error: (e) => { $("sub").textContent = "Not connected to the chat app: " + e.message; },
169
+ });
170
+ })();
171
+ </script>
172
+ </body>
173
+ </html>