@offerswap/mcp 1.0.0 → 1.1.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/src/tools.js ADDED
@@ -0,0 +1,1885 @@
1
+ /**
2
+ * The OfferSwap MCP tools: their list (TOOLS) and what each one calls on the
3
+ * API (callTool). Shared by the npm package (index.js, stdio, runs on the
4
+ * user's computer) and the hosted endpoint at https://app.offerswap.com/mcp
5
+ * (worker/src/api/mcp-http.js), so the two can never offer different tools.
6
+ *
7
+ * No Node or Worker specifics in here: the caller passes an `api` function,
8
+ * which sends the request with the user's key and returns the parsed body or
9
+ * throws, and optionally `readLocalFile(path)`, which only the local package
10
+ * has. The docs gate (scripts/lib/api-surface.mjs) reads the API calls here.
11
+ */
12
+
13
+ // Query string from the args that are set, skipping undefined, null and ''.
14
+ export function qsFrom(args, keys) {
15
+ const qs = new URLSearchParams();
16
+ for (const k of keys) {
17
+ const v = args?.[k];
18
+ if (v !== undefined && v !== null && v !== '') qs.set(k, String(v));
19
+ }
20
+ const q = qs.toString();
21
+ return q ? `?${q}` : '';
22
+ }
23
+
24
+ export const TOOLS = [
25
+ {
26
+ name: 'create_link',
27
+ description:
28
+ 'Create a new branded short link on offerswap.com. The link redirects to exactly the destination URL you provide. For Amazon links, include your own Associates tag in the URL (e.g. ?tag=yourtag-20); OfferSwap passes it through untouched and does not rewrite or geo-route Amazon URLs. By default, the link is created under the user\'s first active custom domain (if any); pass `domain_id` to pin it to a specific one. Returns the short URL and link metadata (including `short_domain`, the hostname the link will resolve at).',
29
+ inputSchema: {
30
+ type: 'object',
31
+ properties: {
32
+ destination_url: {
33
+ type: 'string',
34
+ description: 'The full URL the short link should redirect to. Must be http(s).',
35
+ },
36
+ title: {
37
+ type: 'string',
38
+ description: 'Optional human-readable title for the link.',
39
+ },
40
+ source_label: {
41
+ type: 'string',
42
+ description: 'Optional source label (campaign tag) for your own attribution.',
43
+ },
44
+ domain_id: {
45
+ type: 'number',
46
+ description: 'Optional id of one of the user\'s active custom domains (from list_domains). If omitted, defaults to the user\'s first active custom domain, or offerswap.com if they have none.',
47
+ },
48
+ phone_open: { type: ['string', 'null'], enum: ['app', 'browser', 'stay', null], description: 'On a phone, what a tap on this link does: "browser" leaves Facebook\'s, Instagram\'s or TikTok\'s own in-app browser for Safari or Chrome and loads the page; "stay" loads the website where they tapped and never opens an app; "app" or null is the default: a destination that belongs to an app (Amazon, YouTube, eBay, Instagram...) opens that app, or its website when it is not installed, going by way of Safari or Chrome when the tap was inside an in-app browser.' },
49
+ },
50
+ required: ['destination_url'],
51
+ },
52
+ },
53
+ {
54
+ name: 'update_link',
55
+ description:
56
+ 'Update an existing short link. Supports changing where it redirects (destination_url), renaming (title, which also renames the offer paired to this link\'s destination URL), changing the campaign source label, swapping the branded domain it resolves under (domain_id), setting a memorable custom alias (alias), archiving/unarchiving, and password-protecting the link. Pass `destination_url` to repoint the link at a new target. The short code, alias, and click history are preserved; only the redirect destination moves (the ASIN is re-extracted automatically for Amazon /dp/ URLs). Pass `alias` to give the link a memorable URL slug on its custom domain (e.g. alias="summer-sale" → https://click.example.com/summer-sale). Aliases require the link to be on a custom domain. Setting `alias` REPLACES any previous alias. The old alias stops resolving immediately and is freed for any other link to claim. The link\'s original random short code (link.code) keeps working forever regardless of alias changes. Pass alias="" or alias=null to remove the alias. Changing the link\'s `domain_id` clears the alias automatically. To set or change the password, pass `password` as a non-empty string. To remove password protection, pass an empty string for `password`. To move the link back to the platform default (offerswap.com), pass `domain_id: null`. Returns the updated link row including `short_domain`, `alias`, and `password_protected` (boolean; the plaintext is never returned).',
57
+ inputSchema: {
58
+ type: 'object',
59
+ properties: {
60
+ link_id: { type: 'number', description: 'The numeric id of the link (from list_links / create_link).' },
61
+ destination_url: { type: 'string', description: 'New destination URL the short link redirects to (must be http(s)). The short code, alias, and click history are preserved.' },
62
+ title: { type: 'string', description: 'New display title.' },
63
+ source_label: { type: 'string', description: 'New source label (campaign tag).' },
64
+ archived: { type: 'boolean', description: 'Set true to archive the link, false to unarchive.' },
65
+ password: { type: 'string', description: 'Password to protect the link with. Empty string clears any existing password. Max 200 chars.' },
66
+ domain_id: { type: ['number', 'null'], description: 'Id of one of the user\'s active custom domains, or null to move the link back to offerswap.com.' },
67
+ phone_open: { type: ['string', 'null'], enum: ['app', 'browser', 'stay', null], description: 'On a phone, what a tap on this link does: "browser" leaves Facebook\'s, Instagram\'s or TikTok\'s own in-app browser for Safari or Chrome and loads the page; "stay" loads the website where they tapped and never opens an app; "app" or null is the default: a destination that belongs to an app (Amazon, YouTube, eBay, Instagram...) opens that app, or its website when it is not installed, going by way of Safari or Chrome when the tap was inside an in-app browser.' },
68
+ alias: { type: ['string', 'null'], description: 'Custom path alias on the link\'s custom domain. 1–32 chars; letters, numbers, hyphens, underscores; must start with letter/number. Empty string or null removes the alias. Replacing an alias retires the old one immediately. Requires the link to be on a custom domain.' },
69
+ },
70
+ required: ['link_id'],
71
+ },
72
+ },
73
+ {
74
+ name: 'refresh_link_image',
75
+ description:
76
+ 'Get or refresh the thumbnail image for an existing short link or offer. Amazon /dp/ links get the Amazon product photo. Any other URL gets a screenshot of the page (1280x800, the first screen, taken in a headless browser with ad pixels and analytics blocked, so it never counts as a visit), falling back to the page\'s og:image or first image if the screenshot fails. The image is stored on OfferSwap storage. Takes about 5 to 10 seconds. Use this when a link has no image (the thumbnail shows a letter) or a stale one. Returns { found: true, link } with the updated `product_image_url` on success, or { found: false } if no image could be fetched this time (the existing image, if any, is left untouched; try again later).',
77
+ inputSchema: {
78
+ type: 'object',
79
+ properties: {
80
+ link_id: { type: 'number', description: 'The numeric id of the link (from list_links / create_link).' },
81
+ },
82
+ required: ['link_id'],
83
+ },
84
+ },
85
+ {
86
+ name: 'delete_link',
87
+ description:
88
+ 'Permanently delete a short link and its click history. The short URL and any alias stop resolving at once. This cannot be undone: to take a link out of use but keep its stats, use update_link with archived=true instead. Confirm with the user before calling this.',
89
+ inputSchema: {
90
+ type: 'object',
91
+ properties: {
92
+ link_id: { type: 'number', description: 'The numeric id of the link (from list_links).' },
93
+ },
94
+ required: ['link_id'],
95
+ },
96
+ },
97
+ {
98
+ name: 'get_link_pixels',
99
+ description:
100
+ 'Get which tracking pixels fire when a short link is clicked. Returns { pixel_ids, events, overridden }. The link fires only these pixels, and none when the list is empty (an active pixel on the account no longer fires on every link). `overridden` is kept for older clients and no longer changes what fires. `events` maps a pixel id to the event this link fires it as, when that differs from the pixel\'s default_event.',
101
+ inputSchema: {
102
+ type: 'object',
103
+ properties: { link_id: { type: 'number' } },
104
+ required: ['link_id'],
105
+ },
106
+ },
107
+ {
108
+ name: 'set_link_pixels',
109
+ description:
110
+ 'Choose which tracking pixels fire when a short link is clicked (ids from list_tracking_pixels). Replaces the link\'s whole selection. The link fires exactly these pixels; an empty list means none. A link with no pick fires no pixel. `events` optionally sets the event per pixel for this link, e.g. {"12": "ViewContent"}; it must be valid for that pixel\'s platform.',
111
+ inputSchema: {
112
+ type: 'object',
113
+ properties: {
114
+ link_id: { type: 'number' },
115
+ pixel_ids: { type: 'array', items: { type: 'number' } },
116
+ overridden: { type: 'boolean', description: 'Kept for older clients; no longer changes what fires.' },
117
+ events: { type: 'object', additionalProperties: { type: 'string' }, description: 'Per pixel event for this link, keyed by pixel id.' },
118
+ },
119
+ required: ['link_id', 'pixel_ids'],
120
+ },
121
+ },
122
+ {
123
+ name: 'set_link_collection',
124
+ description: 'Put a short link in a collection (from list_collections), or pass collection_id null to take it out. A link is in at most one collection.',
125
+ inputSchema: {
126
+ type: 'object',
127
+ properties: {
128
+ link_id: { type: 'number' },
129
+ collection_id: { type: ['number', 'null'] },
130
+ },
131
+ required: ['link_id', 'collection_id'],
132
+ },
133
+ },
134
+
135
+ // ─── Collections ────────────────────────────────────────────────────────
136
+ {
137
+ name: 'list_collections',
138
+ description:
139
+ 'List the user\'s collections (folders of short links) with each one\'s link and click counts, starred first. A collection can also be a ROTATOR: with rotator_enabled, https://offerswap.com/c/{rotator_alias} sends each visitor to a random link in the collection.',
140
+ inputSchema: { type: 'object', properties: {} },
141
+ },
142
+ {
143
+ name: 'get_collection',
144
+ description:
145
+ 'Get one collection with its links (each with its short_domain and clicks) and click analytics for the window: totals (links, clicks, unique_clicks, countries), by_day, by_country, by_device, by_browser, by_referrer, by_language and the 25 most recent clicks.',
146
+ inputSchema: {
147
+ type: 'object',
148
+ properties: {
149
+ collection_id: { type: 'number' },
150
+ days: { type: 'number', description: 'Window size in days (1 to 90). Defaults to 14.' },
151
+ },
152
+ required: ['collection_id'],
153
+ },
154
+ },
155
+ {
156
+ name: 'create_collection',
157
+ description:
158
+ 'Create a collection to group short links. Add links to it with set_link_collection. Set rotator_enabled to get a rotator URL (https://offerswap.com/c/{rotator_alias}) that sends each visitor to a random link in the collection; the alias is generated when not given.',
159
+ inputSchema: {
160
+ type: 'object',
161
+ properties: {
162
+ name: { type: 'string', description: 'Up to 80 characters.' },
163
+ description: { type: 'string', description: 'Optional, up to 280 characters.' },
164
+ color: { type: 'string', description: 'One of #ef4444 #f97316 #f59e0b #eab308 #84cc16 #22c55e #14b8a6 #3b82f6 #1d4ed8 #6d28d9 #8b5cf6 #ec4899 #be185d #92400e #0f766e #000000 #fb7185 #0d9488. Anything else becomes #ef4444.' },
165
+ starred: { type: 'boolean', description: 'Starred collections show in the app\'s Starred menu.' },
166
+ rotator_enabled: { type: 'boolean' },
167
+ rotator_alias: { type: 'string', description: 'Optional rotator path, 8 to 24 letters, numbers, dashes or underscores. 409 alias_taken when in use.' },
168
+ },
169
+ required: ['name'],
170
+ },
171
+ },
172
+ {
173
+ name: 'update_collection',
174
+ description: 'Rename a collection or change its description, color, star, or rotator. Turning the rotator off keeps its alias, so turning it back on restores the same URL.',
175
+ inputSchema: {
176
+ type: 'object',
177
+ properties: {
178
+ collection_id: { type: 'number' },
179
+ name: { type: 'string' },
180
+ description: { type: 'string' },
181
+ color: { type: 'string' },
182
+ starred: { type: 'boolean' },
183
+ rotator_enabled: { type: 'boolean' },
184
+ rotator_alias: { type: 'string', description: '8 to 24 letters, numbers, dashes or underscores.' },
185
+ },
186
+ required: ['collection_id'],
187
+ },
188
+ },
189
+ {
190
+ name: 'delete_collection',
191
+ description: 'Delete a collection. Its links are kept and simply leave the collection; its rotator URL stops working.',
192
+ inputSchema: { type: 'object', properties: { collection_id: { type: 'number' } }, required: ['collection_id'] },
193
+ },
194
+
195
+ // ─── Account ────────────────────────────────────────────────────────────
196
+ {
197
+ name: 'get_account',
198
+ description:
199
+ 'Get the signed-in account: email, plan and billing period, current_period_end and cancels_at, monthly usage (clicks_used_this_month against plan_click_limit, pageview_usage {used, limit, remaining, over, resets_at}), the report time zone (`timezone`, null means each browser uses its own), the dashboard\'s default range (tracker_range_days) and the universal postback_url.',
200
+ inputSchema: { type: 'object', properties: {} },
201
+ },
202
+ {
203
+ name: 'list_api_keys',
204
+ description: 'List the account\'s API keys: id, label, prefix (the first 8 characters after bgl_, to tell keys apart), last_used_at and created_at. The keys themselves are never returned.',
205
+ inputSchema: { type: 'object', properties: {} },
206
+ },
207
+ {
208
+ name: 'create_api_key',
209
+ description: 'Create a new API key. The full key (`token`, bgl_...) is returned ONCE and cannot be shown again, so hand it to the user straight away and tell them to store it.',
210
+ inputSchema: {
211
+ type: 'object',
212
+ properties: { label: { type: 'string', description: 'Name to tell the key apart, e.g. "Cursor on laptop".' } },
213
+ },
214
+ },
215
+ {
216
+ name: 'delete_api_key',
217
+ description: 'Revoke an API key at once. Anything using it starts getting 401s, including this MCP server if it is the key it runs on. Confirm with the user first.',
218
+ inputSchema: { type: 'object', properties: { api_key_id: { type: 'number' } }, required: ['api_key_id'] },
219
+ },
220
+ {
221
+ name: 'list_links',
222
+ description:
223
+ 'List all short links owned by the authenticated user, including per-link click counts. Returns links in newest-first order. Use include_archived=true to also include archived links.',
224
+ inputSchema: {
225
+ type: 'object',
226
+ properties: {
227
+ include_archived: {
228
+ type: 'boolean',
229
+ description: 'If true, include archived links. Defaults to false.',
230
+ },
231
+ },
232
+ },
233
+ },
234
+ {
235
+ name: 'get_link_stats',
236
+ description:
237
+ 'Get aggregated click analytics for a single short link: clicks by day, country, device, browser, referrer, hour-of-day, and weekday. Use the link id returned from list_links or create_link.',
238
+ inputSchema: {
239
+ type: 'object',
240
+ properties: {
241
+ link_id: {
242
+ type: 'number',
243
+ description: 'The numeric id of the link (from list_links / create_link).',
244
+ },
245
+ days: {
246
+ type: 'number',
247
+ description: 'Window size in days (1–90). Defaults to 14.',
248
+ },
249
+ },
250
+ required: ['link_id'],
251
+ },
252
+ },
253
+ {
254
+ name: 'get_links_report',
255
+ description:
256
+ 'Every short link with its clicks in a window: clicks, unique clicks (by IP), top country, top device and last click, sorted by clicks. Short links are counted apart from the campaign tracker, so get_tracker_overview does not include them. A link that was turned into a campaign is listed while it had clicks in the window, with `campaign` naming it.',
257
+ inputSchema: {
258
+ type: 'object',
259
+ properties: {
260
+ days: { type: 'number', description: 'Rolling window in days (1-90). Defaults to 30. Ignored when `from` is set.' },
261
+ from: { type: 'string', description: 'ISO start of a window (inclusive).' },
262
+ to: { type: 'string', description: 'ISO end of a window (exclusive). Omit to run to now.' },
263
+ },
264
+ },
265
+ },
266
+ {
267
+ name: 'convert_link_to_campaign',
268
+ description:
269
+ 'Turn a short link into a campaign on the SAME URL, for when a plain link needs campaign tracking (a landing page, split tests, sales by postback) without changing the URL already posted. The campaign takes the link\'s short code and domain, its flow sends traffic to an offer for the link\'s destination (an existing offer on that URL is reused; an Amazon URL gets the account\'s Associates tag), and the link\'s phone pick moves to the offer step. The link is archived and keeps its click history. It cannot be undone. Call with `preview: true` first to see what carries over: links with a custom alias or a password are refused, and click pixels on the link stop firing.',
270
+ inputSchema: {
271
+ type: 'object',
272
+ properties: {
273
+ link_id: { type: 'number', description: 'The numeric id of the link (from list_links).' },
274
+ preview: { type: 'boolean', description: 'true: only report what would happen (can_convert, blocked, campaign_name, offer, dropped). Nothing changes.' },
275
+ },
276
+ required: ['link_id'],
277
+ },
278
+ },
279
+ {
280
+ name: 'get_overview_stats',
281
+ description:
282
+ 'Get account-wide analytics for the user\'s branded short LINKS only: total link CLICKS, clicks by day, top countries, devices, browsers, referrers, peak hour and weekday. This covers the Links section ONLY. It does NOT include Tracker page views, site-property traffic, or campaign visits/conversions. For PAGE VIEWS (site properties) or campaign traffic use the Tracker tools instead: get_tracker_overview (clicks-vs-pageviews unified rollup), list_properties, or get_property_stats. If the user asks for "clicks AND page views" together, call BOTH this tool and get_tracker_overview and combine them, because they read from separate event streams. Use this for "how are my links doing" type questions.',
283
+ inputSchema: {
284
+ type: 'object',
285
+ properties: {
286
+ days: {
287
+ type: 'number',
288
+ description: 'Window size in days (1–90). Defaults to 14.',
289
+ },
290
+ },
291
+ },
292
+ },
293
+ {
294
+ name: 'list_domains',
295
+ description:
296
+ 'List the user\'s branded custom short-link domains (e.g. go.acme.com). Returns each domain with its provisioning status (pending DNS / active / failed), SSL status, and the CNAME target the user needs to point their hostname at. Also returns the plan tier and the number of domains the plan allows.',
297
+ inputSchema: { type: 'object', properties: {} },
298
+ },
299
+ {
300
+ name: 'create_domain',
301
+ description:
302
+ 'Register a new branded custom domain so short links can resolve at the user\'s own hostname instead of offerswap.com. After creation, the user must add a CNAME record at their DNS provider pointing the hostname at the returned cname_target. SSL is auto-issued by Cloudflare once DNS resolves. Free plan does not allow custom domains.',
303
+ inputSchema: {
304
+ type: 'object',
305
+ properties: {
306
+ hostname: {
307
+ type: 'string',
308
+ description: 'The hostname to register, e.g. "go.acme.com". Must be a valid public hostname; the offerswap.com apex and its subdomains are reserved.',
309
+ },
310
+ },
311
+ required: ['hostname'],
312
+ },
313
+ },
314
+ {
315
+ name: 'verify_domain',
316
+ description:
317
+ 'Force a re-check of a custom domain\'s status against Cloudflare. Use after the user has added the CNAME record to advance the domain from "pending" to "active". Returns the refreshed domain row.',
318
+ inputSchema: {
319
+ type: 'object',
320
+ properties: {
321
+ domain_id: { type: 'number', description: 'The numeric id of the domain (from list_domains / create_domain).' },
322
+ },
323
+ required: ['domain_id'],
324
+ },
325
+ },
326
+ {
327
+ name: 'check_domain_dns',
328
+ description:
329
+ 'Detect where a custom domain\'s DNS is hosted (Cloudflare, GoDaddy, Namecheap, Route 53, and others) from its public nameservers, and report the easiest way to point it at OfferSwap. `one_click.method` is `domain_connect` (send the user to `one_click.url` to approve the change at their provider), `cloudflare_oauth` (tell the user to open Properties in the app and click Connect Cloudflare on this domain, which needs a browser), or null (the user adds the CNAME by hand, at `dns_url` when known). On Cloudflare, `one_click.token_url` is also set, for connect_domain_cloudflare when the user prefers an agent to do it.',
330
+ inputSchema: {
331
+ type: 'object',
332
+ properties: {
333
+ domain_id: { type: 'number', description: 'The numeric id of the domain (from list_domains / create_domain).' },
334
+ },
335
+ required: ['domain_id'],
336
+ },
337
+ },
338
+ {
339
+ name: 'connect_domain_cloudflare',
340
+ description:
341
+ 'Add the required CNAME to the user\'s own Cloudflare zone without a browser, using an API token they created with Zone Read and DNS Edit (form at `one_click.token_url`). Prefer the Connect Cloudflare button in the app when the user can click it, since it needs no token. The token is used for this one request and is never stored. Returns `action`: `created`, or `already_set` when the record is already correct. Never overwrites an existing record: a different record on the hostname returns error `record_exists`. Other errors: `invalid_token`, `zone_not_found`, `token_missing_dns`. Call verify_domain afterward to watch status move to active.',
342
+ inputSchema: {
343
+ type: 'object',
344
+ properties: {
345
+ domain_id: { type: 'number', description: 'The numeric id of the domain.' },
346
+ api_token: { type: 'string', description: 'The user\'s Cloudflare API token.' },
347
+ },
348
+ required: ['domain_id', 'api_token'],
349
+ },
350
+ },
351
+ {
352
+ name: 'delete_domain',
353
+ description:
354
+ 'Remove a custom domain. Deletes the Cloudflare hostname binding and the local record. Short links served via this domain stop resolving immediately.',
355
+ inputSchema: {
356
+ type: 'object',
357
+ properties: {
358
+ domain_id: { type: 'number', description: 'The numeric id of the domain to remove.' },
359
+ },
360
+ required: ['domain_id'],
361
+ },
362
+ },
363
+
364
+ // ─── Tracker: affiliate networks ────────────────────────────────────────
365
+ {
366
+ name: 'get_universal_postback_url',
367
+ description:
368
+ 'Get the account\'s UNIVERSAL postback URL (Voluum-style): ONE URL that works for every campaign and every affiliate network. It matches the click by click_id alone and credits whichever campaign the click belongs to, so the user pastes it once into any network\'s S2S settings or their own webhook (n8n, Zapier, a store\'s order webhook) and never updates it again. Format: https://offerswap.com/postback/u/{token}?clickid={clickid}&payout={payout}&currency={currency}&txid={txid} where payout/currency/txid are optional; `cid` is accepted as an alias for `clickid`. It is the account\'s ONLY postback URL: campaigns and networks have no postback URL of their own. Conversions are deduped by txid: at most one conversion per (account, txid). A re-fired postback with the same txid is ignored, and a re-fire with a different payout updates the stored conversion\'s revenue instead of stacking a second one. With no `event` param the postback records a sale. Add `event=refund` or `event=chargeback` to subtract from revenue (matched by click, so the amount can be sent as 67 or -67, and leaving it out reverses everything booked on the click), or `event={slug}` for one of the user\'s custom events (see list_custom_events). An event that is blank or unknown gets a 400 and records nothing.',
369
+ inputSchema: { type: 'object', properties: {} },
370
+ },
371
+ {
372
+ name: 'set_account_timezone',
373
+ description:
374
+ 'Set the time zone the account\'s reports count days and hours in: Today and Yesterday on the dashboard, by_day, by_hour, and the day / weekday / hour report dimensions. It applies on every device and to every API call that does not pass its own `tz`. Pass an IANA name such as America/New_York, Europe/London or Asia/Tokyo, or null to go back to each browser using its own zone (API calls then count in UTC). Returns the saved value.',
375
+ inputSchema: {
376
+ type: 'object',
377
+ properties: {
378
+ timezone: { type: ['string', 'null'], description: 'IANA time zone name, or null to clear.' },
379
+ },
380
+ required: ['timezone'],
381
+ },
382
+ },
383
+ {
384
+ name: 'set_sale_alerts',
385
+ description:
386
+ 'Turn the "New sale" card on the Dashboard\'s Realtime map on or off. When on (the default), each sale or upsell that lands while the Dashboard is open shows a card with the amount, the offer and the buyer\'s city. Saved on the account, so it holds on every device. Returns the saved value. The same sales are in get_realtime\'s recent_sales whatever this says.',
387
+ inputSchema: {
388
+ type: 'object',
389
+ properties: {
390
+ enabled: { type: 'boolean', description: 'true shows the cards, false hides them.' },
391
+ },
392
+ required: ['enabled'],
393
+ },
394
+ },
395
+ {
396
+ name: 'list_affiliate_networks',
397
+ description:
398
+ 'List the user\'s affiliate networks (ClickBank, Digistore24, MaxWeb, etc). Their sales come back on the account\'s one postback URL (get_universal_postback_url); networks have no postback URL of their own. conversion_param is what the network calls the click id, and is appended to offer URLs that use the network.',
399
+ inputSchema: { type: 'object', properties: {} },
400
+ },
401
+ {
402
+ name: 'create_affiliate_network',
403
+ description:
404
+ 'Add a new affiliate network. Its sales come back on the account\'s one postback URL (get_universal_postback_url), not a URL of its own. Every offer using the network gets ?{conversion_param}={click_id} appended at click time unless the offer URL already has a {clickid} token. For Amazon Associates, set amazon_tag (e.g. "yourtagid-20"): every Amazon destination link the user adds is then auto-tagged with ?tag={amazon_tag} at click time (a tag already on the URL always wins).',
405
+ inputSchema: {
406
+ type: 'object',
407
+ properties: {
408
+ name: { type: 'string', description: 'Display name, e.g. "ClickBank".' },
409
+ conversion_param: { type: 'string', description: 'What the network calls the click id (default "clickid"). Appended to offer URLs that use this network.' },
410
+ amazon_tag: { type: 'string', description: 'Amazon Associates tracking tag (e.g. "yourtagid-20"). When set, Amazon links are auto-converted to affiliate links by appending ?tag={amazon_tag} on each click.' },
411
+ },
412
+ required: ['name'],
413
+ },
414
+ },
415
+ {
416
+ name: 'update_affiliate_network',
417
+ description: 'Update an affiliate network (rename, change the click id param, or set the Amazon Associates amazon_tag; pass an empty string to clear it). Pass archived=true to soft-archive.',
418
+ inputSchema: {
419
+ type: 'object',
420
+ properties: {
421
+ network_id: { type: 'number' },
422
+ name: { type: 'string' },
423
+ conversion_param: { type: 'string' },
424
+ amazon_tag: { type: 'string', description: 'Amazon Associates tracking tag (e.g. "yourtagid-20"); empty string clears it.' },
425
+ archived: { type: 'boolean' },
426
+ },
427
+ required: ['network_id'],
428
+ },
429
+ },
430
+ {
431
+ name: 'delete_affiliate_network',
432
+ description: 'Delete an affiliate network. Offers that referenced this network keep their URL but have affiliate_network_id set to NULL.',
433
+ inputSchema: {
434
+ type: 'object',
435
+ properties: { network_id: { type: 'number' } },
436
+ required: ['network_id'],
437
+ },
438
+ },
439
+
440
+ // ─── Tracker: offers ────────────────────────────────────────────────────
441
+ {
442
+ name: 'list_offers',
443
+ description: 'List all offers (destination URLs) owned by the user. Use these as the end-point of a campaign. Each offer carries `campaigns`: the live campaigns it is in, each with its `short_url`. An offer has no link of its own, so those are the links that reach it; when the list is empty, create_offer_link makes one. Archived offers (`archived_at` set) are left out unless include_archived is true.',
444
+ inputSchema: { type: 'object', properties: { include_archived: { type: 'boolean', description: 'Also list archived ones. Default false.' } } },
445
+ },
446
+ {
447
+ name: 'create_offer_link',
448
+ description: 'Get a shareable link for an offer. An offer has no short link of its own (the link is always a campaign\'s), so this makes the simplest campaign: named after the offer, on the account\'s default domain, every click going to the offer. Returns the campaign with its `short_url`. Each call makes a new campaign, so check list_offers `campaigns` first unless a separate link per placement is wanted.',
449
+ inputSchema: {
450
+ type: 'object',
451
+ properties: { offer_id: { type: 'number', description: 'The offer id (from list_offers or create_offer).' } },
452
+ required: ['offer_id'],
453
+ },
454
+ },
455
+ {
456
+ name: 'create_offer',
457
+ description:
458
+ 'Create an offer (a destination URL: affiliate landing page, product page, etc). The URL is used exactly as given when redirecting. Include any affiliate tag yourself. An offer gets no short link of its own: the link that goes in an ad comes from a campaign (create_campaign), which also sets the domain. Link the offer to an affiliate_network_id so the resolver knows which postback param name to use when redirecting (e.g. some networks expect ?aff_sub=… instead of ?clickid=…).',
459
+ inputSchema: {
460
+ type: 'object',
461
+ properties: {
462
+ name: { type: 'string' },
463
+ url: { type: 'string', description: 'Destination URL (http/https).' },
464
+ affiliate_network_id: { type: ['number', 'null'] },
465
+ payout: { type: ['number', 'null'], description: 'Default payout. A sale postback that arrives with no payout books this amount. Leave out or null for none.' },
466
+ payout_currency: { type: 'string', description: 'ISO 4217 currency, default USD.' },
467
+ country: { type: 'string', description: 'ISO2 country code (optional).' },
468
+ },
469
+ required: ['name', 'url'],
470
+ },
471
+ },
472
+ {
473
+ name: 'update_offer',
474
+ description: 'Update an offer\'s name, URL, payout, currency, country, or affiliate network. An offer has no short link of its own (the link for an ad comes from a campaign); renaming one also renames any older short link left on its URL, so the two keep one name. Pass archived=true to soft-archive.',
475
+ inputSchema: {
476
+ type: 'object',
477
+ properties: {
478
+ offer_id: { type: 'number' },
479
+ name: { type: 'string' },
480
+ url: { type: 'string' },
481
+ affiliate_network_id: { type: ['number', 'null'] },
482
+ payout: { type: ['number', 'null'], description: 'Default payout, booked on a sale postback that has none. null clears it.' },
483
+ payout_currency: { type: 'string' },
484
+ country: { type: 'string' },
485
+ archived: { type: 'boolean' },
486
+ },
487
+ required: ['offer_id'],
488
+ },
489
+ },
490
+ {
491
+ name: 'archive_offer',
492
+ description: 'Archive an offer. Offers are never deleted: an archived offer stays with its sales history, campaigns stop sending clicks to it, and list_offers leaves it out. Restore it with update_offer archived=false.',
493
+ inputSchema: { type: 'object', properties: { offer_id: { type: 'number' } }, required: ['offer_id'] },
494
+ },
495
+
496
+ // ─── Tracker: landers ───────────────────────────────────────────────────
497
+ {
498
+ name: 'list_landers',
499
+ description: 'List the user\'s landing pages. Landers are optional intermediate pages between the short link and the offer.',
500
+ inputSchema: { type: 'object', properties: {} },
501
+ },
502
+ {
503
+ name: 'create_lander',
504
+ description:
505
+ 'Create a lander (the user\'s own landing page that visitors hit between the short link and the offer). The URL may contain {clickid} tokens which the resolver expands. Install the campaign\'s pixel snippet on the lander to get impressions, time-on-page, scroll depth, and outbound click tracking.',
506
+ inputSchema: {
507
+ type: 'object',
508
+ properties: {
509
+ name: { type: 'string' },
510
+ url: { type: 'string', description: 'Lander URL. May contain {clickid} which the resolver will replace.' },
511
+ country: { type: 'string' },
512
+ },
513
+ required: ['name', 'url'],
514
+ },
515
+ },
516
+ {
517
+ name: 'update_lander',
518
+ description: 'Update a lander\'s name, URL, or country. Pass archived=true to soft-archive.',
519
+ inputSchema: {
520
+ type: 'object',
521
+ properties: {
522
+ lander_id: { type: 'number' },
523
+ name: { type: 'string' },
524
+ url: { type: 'string' },
525
+ country: { type: 'string' },
526
+ archived: { type: 'boolean' },
527
+ },
528
+ required: ['lander_id'],
529
+ },
530
+ },
531
+ {
532
+ name: 'delete_lander',
533
+ description: 'Delete a lander. Removes it from any campaigns it was attached to.',
534
+ inputSchema: { type: 'object', properties: { lander_id: { type: 'number' } }, required: ['lander_id'] },
535
+ },
536
+
537
+ // ─── Custom postback events ─────────────────────────────────────────────
538
+ {
539
+ name: 'list_custom_events',
540
+ description:
541
+ 'List the account\'s custom postback events. Sale, refund and chargeback are built in on every account (`built_in`); everything else (add to cart, upsell, lead, registration, anything) is defined by the user (`events`). Each event\'s `slug` is the value of `event=` on any postback URL. `presets` are common starting points that do not exist until created.',
542
+ inputSchema: { type: 'object', properties: {} },
543
+ },
544
+ {
545
+ name: 'create_custom_event',
546
+ description:
547
+ 'Add a custom postback event. Once created, `event={slug}` on any postback URL records it and it appears as its own column in campaign reports. The slug is derived from the label unless given, and cannot be changed later. Built-in names (purchase, sale, conversion, refund, chargeback) and tracker names (visit, offer_click, ...) are refused. With counts_revenue true, the event adds its payout to revenue and is deduped by txid like a sale (use for an upsell). With counts_revenue false, it is counted at most once per click and any payout is ignored (use for a cart or a lead).',
548
+ inputSchema: {
549
+ type: 'object',
550
+ properties: {
551
+ label: { type: 'string', description: 'Display name, e.g. "Add to cart".' },
552
+ slug: { type: 'string', description: 'Optional. The event= value, lower case letters, numbers, dashes and underscores, e.g. "add_to_cart". Defaults to the label, slugified.' },
553
+ counts_revenue: { type: 'boolean', description: 'Whether this event adds its payout to revenue. Default false.' },
554
+ },
555
+ required: ['label'],
556
+ },
557
+ },
558
+ {
559
+ name: 'update_custom_event',
560
+ description: 'Rename a custom postback event or change whether it counts revenue. The slug cannot be changed.',
561
+ inputSchema: {
562
+ type: 'object',
563
+ properties: {
564
+ custom_event_id: { type: 'number' },
565
+ label: { type: 'string' },
566
+ counts_revenue: { type: 'boolean' },
567
+ },
568
+ required: ['custom_event_id'],
569
+ },
570
+ },
571
+ {
572
+ name: 'delete_custom_event',
573
+ description: 'Delete a custom postback event. Recorded events stay and their revenue stays in totals, but postbacks using its slug get a 400 from then on. Adding the same slug back reconnects the history.',
574
+ inputSchema: { type: 'object', properties: { custom_event_id: { type: 'number' } }, required: ['custom_event_id'] },
575
+ },
576
+
577
+ // ─── Split tests ────────────────────────────────────────────────────────
578
+ {
579
+ name: 'list_split_tests',
580
+ description:
581
+ 'List on-page split tests with their arms and live results. A split test changes text, images or button colors on a landing page that has the account\'s property tag, swapping them per visitor, while a revenue bandit (Thompson sampling) moves traffic toward the arm making the most money per visitor. Arm `a` is always the page as it is. Each test\'s `results` has, per arm: views (people who saw it), clicks, buyers, sales, gross, net (after refunds), weight (its share of new visitors right now) and p_best. `burn_in` is true while the test has fewer counted visitors than burn_in_target (200): every arm then gets an even split. `missing` counts views where the tested element was no longer on the page.',
582
+ inputSchema: { type: 'object', properties: { include_archived: { type: 'boolean' } } },
583
+ },
584
+ {
585
+ name: 'get_split_test',
586
+ description: 'One split test with its arms and live results. See list_split_tests.',
587
+ inputSchema: { type: 'object', properties: { split_test_id: { type: 'number' } }, required: ['split_test_id'] },
588
+ },
589
+ {
590
+ name: 'scan_page_for_split_test',
591
+ description:
592
+ 'Open a landing page in a headless browser (a phone by default) and return what can be tested on its first six screens: every line of text (headline, subheadline, heading, text), every button (role cta) and images, each with an id, a CSS selector, its text or image src and its position. Also says whether the page carries this account\'s property tag (has_tag, property_id): a test cannot start without it. Takes about 15 seconds. Pass the elements you want to test to create_split_test. With browse: true the browser stays open for 5 minutes and `session` lets click_split_test_scan tap the page to reach a later step (a quiz\'s next screen).',
593
+ inputSchema: {
594
+ type: 'object',
595
+ properties: {
596
+ url: { type: 'string', description: 'The full page URL, https://...' },
597
+ device: { type: 'string', enum: ['mobile', 'desktop'], description: 'Default mobile. Most ad traffic is on phones.' },
598
+ browse: { type: 'boolean', description: 'Keep the browser open to tap through the page with click_split_test_scan. Default false here; close it with close_split_test_scan when done.' },
599
+ },
600
+ required: ['url'],
601
+ },
602
+ },
603
+ {
604
+ name: 'click_split_test_scan',
605
+ description:
606
+ 'Tap a scanned page that is still open (scan_page_for_split_test with browse: true) at x, y in the screenshot\'s CSS pixels, for example on a quiz\'s start button, and get the page after the tap: a new screenshot and that screen\'s elements, with ids of their own and later: true. A later element is changed by the tag whenever it appears, so it can be tested even though it is not on the first screen. navigated: true means a different page loaded, whose elements cannot go in this test. 410 scan_expired after 5 idle minutes.',
607
+ inputSchema: {
608
+ type: 'object',
609
+ properties: {
610
+ session: { type: 'string', description: 'The scan\'s session.' },
611
+ x: { type: 'number' }, y: { type: 'number' },
612
+ step: { type: 'number', description: 'Which tap this is, 1 for the first. Numbers the elements found.' },
613
+ device: { type: 'string', enum: ['mobile', 'desktop'] },
614
+ },
615
+ required: ['session', 'x', 'y'],
616
+ },
617
+ },
618
+ {
619
+ name: 'close_split_test_scan',
620
+ description: 'Close a scan\'s open browser (it is billed while open).',
621
+ inputSchema: { type: 'object', properties: { session: { type: 'string' } }, required: ['session'] },
622
+ },
623
+ {
624
+ name: 'create_split_test',
625
+ description:
626
+ 'Create a split test as a draft. `elements` are the scanned elements it changes (from scan_page_for_split_test, passed back whole). Arm a (the original) is added for you; `arms` are up to 3 variants, each a name and changes: [{element: "<element id>", text?, src?, color?, background?}]. In text, *words* in stars take the page\'s highlight style. Start it with update_split_test status "running".',
627
+ inputSchema: {
628
+ type: 'object',
629
+ properties: {
630
+ page_url: { type: 'string' },
631
+ name: { type: 'string' },
632
+ page_title: { type: 'string' },
633
+ device: { type: 'string', enum: ['mobile', 'desktop'] },
634
+ property_id: { type: 'number', description: 'The scan\'s property_id (the property whose tag is on the page).' },
635
+ screenshot_url: { type: 'string' },
636
+ screenshot_w: { type: 'number' },
637
+ screenshot_h: { type: 'number' },
638
+ elements: { type: 'array', items: { type: 'object' }, description: 'The elements to test, as the scan returned them.' },
639
+ candidates: { type: 'array', items: { type: 'object' }, description: 'Optional: every scanned element, so the draft can change what it tests later.' },
640
+ arms: {
641
+ type: 'array',
642
+ items: {
643
+ type: 'object',
644
+ properties: {
645
+ name: { type: 'string' },
646
+ source: { type: 'string', enum: ['manual', 'ai'] },
647
+ changes: { type: 'array', items: { type: 'object' } },
648
+ },
649
+ },
650
+ },
651
+ },
652
+ required: ['page_url', 'elements'],
653
+ },
654
+ },
655
+ {
656
+ name: 'update_split_test',
657
+ description:
658
+ 'Change a split test. status: "running" starts or resumes it (needs the property tag on the page and a variant with a change; one running test per page, else 409 page_has_running_test with test_id: add your variant to that test instead; and not on an element an ended test\'s winner still changes, else 409 page_has_winner), "paused" shows the page as it is, "ended" with winner_arm keeps showing that arm to everyone (no winner, or "a", shows the original). arms: [{key?, name?, changes?, active?}]: with a key it edits that arm (active false retires it, keeping its numbers); without one it adds a variant. Once a test has run, an arm\'s changes and the elements are locked: add a new arm instead. remove_arms deletes draft arms.',
659
+ inputSchema: {
660
+ type: 'object',
661
+ properties: {
662
+ split_test_id: { type: 'number' },
663
+ name: { type: 'string' },
664
+ status: { type: 'string', enum: ['running', 'paused', 'ended'] },
665
+ winner_arm: { type: 'string' },
666
+ elements: { type: 'array', items: { type: 'object' } },
667
+ arms: { type: 'array', items: { type: 'object' } },
668
+ remove_arms: { type: 'array', items: { type: 'string' } },
669
+ burn_in: { type: 'number', description: 'Counted visitors before the bandit adapts. Default 200.' },
670
+ floor: { type: 'number', description: 'Least share any active arm gets after burn-in, 0 to 0.3. Default 0.05.' },
671
+ reward_weight: { type: 'number', description: 'How many clicks one average sale is worth to the bandit. Default 20.' },
672
+ archived: { type: 'boolean', description: 'false restores an archived test.' },
673
+ },
674
+ required: ['split_test_id'],
675
+ },
676
+ },
677
+ {
678
+ name: 'archive_split_test',
679
+ description: 'Archive a split test. A running test is paused first, so the page goes back to its own copy. Nothing is deleted.',
680
+ inputSchema: { type: 'object', properties: { split_test_id: { type: 'number' } }, required: ['split_test_id'] },
681
+ },
682
+ {
683
+ name: 'write_split_test_copy',
684
+ description:
685
+ 'Have AI write split test variants. Uses one AI credit (Free 0, Small 20, Medium 50, Large 150 a month; 402 ai_credits_exhausted when out). mode "variants" rewrites the text elements you pass; mode "auto" picks the 1 to 3 that matter most from the elements you pass (send every scanned text element) and writes them. Returns arms ready for create_split_test or update_split_test, plus `picked` and `ai_credits`. The AI keeps the page\'s facts and never adds claims, prices or guarantees.',
686
+ inputSchema: {
687
+ type: 'object',
688
+ properties: {
689
+ mode: { type: 'string', enum: ['variants', 'auto'] },
690
+ count: { type: 'number', description: '1 to 3. Default 3.' },
691
+ page_url: { type: 'string' },
692
+ page_title: { type: 'string' },
693
+ elements: { type: 'array', items: { type: 'object' } },
694
+ context: { type: 'array', items: { type: 'string' }, description: 'Other text on the page, for context.' },
695
+ test_id: { type: 'number' },
696
+ },
697
+ required: ['elements'],
698
+ },
699
+ },
700
+ {
701
+ name: 'upload_split_test_image',
702
+ description: 'Upload an image for an image variant and get back its URL, to use as a change\'s src. Pass a local file_path (JPG, PNG, WebP or GIF, up to 5 MB) or an image_url to copy.',
703
+ inputSchema: {
704
+ type: 'object',
705
+ properties: { file_path: { type: 'string' }, image_url: { type: 'string' } },
706
+ },
707
+ },
708
+
709
+ // ─── Report views ───────────────────────────────────────────────────────
710
+ {
711
+ name: 'list_report_views',
712
+ description:
713
+ 'List the account\'s saved report views. A view is a name plus the report columns in the order the user wants them (Voluum-style), and `active` is the view every campaign report and the dashboard Overview open on: "fewer" (the short table), "all" (every column), or a view id as a string. Column ids: lander_views, unique_lander_views, visits, unique_visits, clicks, unique_clicks, ctr, unique_ctr, conversions (Sales), cr, refunds, chargebacks, epc, epv, unique_epv (all three gross revenue per click, visit or person, before refunds and chargebacks), aov (Net AOV, after refunds and chargebacks), gross_aov (Gross AOV, before them), gross_revenue (Gross Rev., before refunds and chargebacks), reversed (Reversed: the dollars refunds and chargebacks took back), revenue (Net Rev.), cost (Cost: ad spend only), plus custom:{slug} for a custom event\'s count and take:{slug} / unique_take:{slug} for the take rate of an event that counts revenue (see list_custom_events). Views only change which columns show; they never change the numbers.',
714
+ inputSchema: { type: 'object', properties: {} },
715
+ },
716
+ {
717
+ name: 'create_report_view',
718
+ description: 'Save a report view: a name and the columns, in order (left to right). By default it becomes the active view. Names are unique per account, case-insensitive (409 name_taken). Up to 50 views.',
719
+ inputSchema: {
720
+ type: 'object',
721
+ properties: {
722
+ name: { type: 'string', description: 'e.g. "Money first".' },
723
+ columns: { type: 'array', items: { type: 'string' }, description: 'Column ids in display order, e.g. ["revenue","conversions","epc","clicks"]. See list_report_views for the ids.' },
724
+ activate: { type: 'boolean', description: 'Make it the active view. Default true.' },
725
+ },
726
+ required: ['name', 'columns'],
727
+ },
728
+ },
729
+ {
730
+ name: 'update_report_view',
731
+ description: 'Rename a saved report view or replace its columns. `columns` replaces the whole list, in order.',
732
+ inputSchema: {
733
+ type: 'object',
734
+ properties: {
735
+ report_view_id: { type: 'number' },
736
+ name: { type: 'string' },
737
+ columns: { type: 'array', items: { type: 'string' } },
738
+ },
739
+ required: ['report_view_id'],
740
+ },
741
+ },
742
+ {
743
+ name: 'delete_report_view',
744
+ description: 'Delete a saved report view. If it was active, reports go back to "fewer".',
745
+ inputSchema: { type: 'object', properties: { report_view_id: { type: 'number' } }, required: ['report_view_id'] },
746
+ },
747
+ {
748
+ name: 'set_active_report_view',
749
+ description: 'Pick the view reports open on: "fewer", "all", or a saved view\'s id.',
750
+ inputSchema: {
751
+ type: 'object',
752
+ properties: { view: { type: 'string', description: '"fewer", "all", or a view id such as "12".' } },
753
+ required: ['view'],
754
+ },
755
+ },
756
+
757
+ // ─── Traffic sources ────────────────────────────────────────────────────
758
+ {
759
+ name: 'list_traffic_sources',
760
+ description:
761
+ 'List the user\'s traffic sources (the platforms they buy traffic from: Facebook, TikTok, Google, …). Each source has a `name`, an optional `platform` (pixel-platform key), and `token_params`: how the source\'s click macros map onto the Google UTM params the resolver captures (utm_source/medium/campaign/term/content), e.g. Facebook utm_campaign = `{{campaign.id}}`, utm_content = Ad ID `{{ad.id}}`. The response also includes a `presets` catalog of ready-made sources with standard macros. Campaigns reference a source via `traffic_source_id` (see create_campaign / update_campaign).',
762
+ inputSchema: { type: 'object', properties: { include_archived: { type: 'boolean', description: 'Also list archived ones. Default false.' } } },
763
+ },
764
+ {
765
+ name: 'create_traffic_source',
766
+ description:
767
+ 'Create a traffic source. `token_params` is an array of `{ slot, label, token }` where slot is one of utm_source/utm_medium/utm_campaign/utm_term/utm_content, label is a human name (e.g. "Campaign ID"), and token is the platform macro (e.g. "{{campaign.id}}"). Use `list_traffic_sources` first to copy a preset\'s token_params for the big platforms.',
768
+ inputSchema: {
769
+ type: 'object',
770
+ properties: {
771
+ name: { type: 'string', description: 'e.g. "Facebook".' },
772
+ platform: { type: ['string', 'null'], description: 'Optional pixel-platform key (facebook, google_ads, tiktok, bing, …) for the icon + conversion-pixel suggestion.' },
773
+ token_params: {
774
+ type: 'array',
775
+ items: {
776
+ type: 'object',
777
+ properties: {
778
+ slot: { type: 'string', enum: ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] },
779
+ label: { type: 'string' },
780
+ token: { type: 'string' },
781
+ },
782
+ required: ['slot'],
783
+ },
784
+ },
785
+ },
786
+ required: ['name'],
787
+ },
788
+ },
789
+ {
790
+ name: 'update_traffic_source',
791
+ description: 'Update a traffic source\'s name, platform, token_params, or archive state. token_params replaces the whole set.',
792
+ inputSchema: {
793
+ type: 'object',
794
+ properties: {
795
+ traffic_source_id: { type: 'number' },
796
+ name: { type: 'string' },
797
+ platform: { type: ['string', 'null'] },
798
+ token_params: { type: 'array', items: { type: 'object', properties: { slot: { type: 'string' }, label: { type: 'string' }, token: { type: 'string' } }, required: ['slot'] } },
799
+ archived: { type: 'boolean' },
800
+ },
801
+ required: ['traffic_source_id'],
802
+ },
803
+ },
804
+ {
805
+ name: 'delete_traffic_source',
806
+ description: 'Delete a traffic source. Campaigns using it keep their data but their `traffic_source_id` is cleared.',
807
+ inputSchema: { type: 'object', properties: { traffic_source_id: { type: 'number' } }, required: ['traffic_source_id'] },
808
+ },
809
+
810
+ // ─── Tracking pixels ────────────────────────────────────────────────────
811
+ {
812
+ name: 'list_tracking_pixels',
813
+ description:
814
+ 'List the user\'s tracking pixels (Facebook, Google Ads, TikTok, etc). Each pixel has a platform, pixel_id, a default_event it fires, an active flag, and has_capi_token (whether a server-side Conversions API token is set; the token itself is never returned). The response also includes a `platforms` catalog with each platform\'s valid `events`, its `defaultEvent`, and `capi` (whether server-side conversions are supported). A pixel never fires on its own: a short link fires it only when it was picked for that link (set_link_pixels), and a campaign sends only the events it picked in pixel_events. has_capi_token comes with capi_token_tail, the token\'s last four characters. Each pixel also reports test_event_code (test mode when set), last_sent_at / last_sent_event (the last server event the platform accepted) and last_error / last_error_at (the last refusal).',
815
+ inputSchema: { type: 'object', properties: {} },
816
+ },
817
+ {
818
+ name: 'create_tracking_pixel',
819
+ description:
820
+ 'Create a tracking pixel. `platform` is one of: facebook, google_ads, google_analytics, google_tag_manager, linkedin, twitter, tiktok, pinterest, snapchat, reddit, quora, bing, adroll. `default_event` must be a valid event for that platform (see the `platforms` catalog from list_tracking_pixels) and defaults to the platform default (e.g. Facebook "PageView"). For Facebook and TikTok you can pass a `capi_token` (server-side Conversions API access token) so campaign events fire server-to-server. For a Facebook pixel with a token the response carries meta_check {ok, name, error}: whether the token can send to that dataset, from an empty event batch so nothing is recorded (a wrong id, such as the Owner number Events Manager shows beside the Dataset ID, comes back ok: false; name is often null).',
821
+ inputSchema: {
822
+ type: 'object',
823
+ properties: {
824
+ platform: { type: 'string', description: 'Pixel platform key (facebook, google_ads, tiktok, …).' },
825
+ pixel_id: { type: 'string', description: 'The platform\'s pixel/dataset id.' },
826
+ label: { type: 'string', description: 'Optional friendly name.' },
827
+ default_event: { type: 'string', description: 'Event this pixel fires by default (must be valid for the platform).' },
828
+ capi_token: { type: 'string', description: 'Optional server-side Conversions API access token (Facebook/TikTok only).' },
829
+ test_event_code: { type: 'string', description: 'Optional Meta test event code (Events Manager, Test events). While set, every server event this pixel sends lands in Test events and never counts.' },
830
+ active: { type: 'boolean', description: 'Whether the pixel is active. Defaults to true.' },
831
+ },
832
+ required: ['platform', 'pixel_id'],
833
+ },
834
+ },
835
+ {
836
+ name: 'update_tracking_pixel',
837
+ description: 'Update a tracking pixel\'s pixel_id, label, default_event, active flag, CAPI token or test event code. Pass capi_token as an empty string or null to clear the stored token. Saving pixel_id or a new capi_token on a Facebook pixel returns meta_check {ok, name, error}, whether the token can send to that dataset (checked with an empty batch, nothing recorded).',
838
+ inputSchema: {
839
+ type: 'object',
840
+ properties: {
841
+ pixel_id_row: { type: 'number', description: 'The id of the tracking_pixels row to update (from list_tracking_pixels).' },
842
+ pixel_id: { type: 'string', description: 'New platform pixel id.' },
843
+ label: { type: 'string' },
844
+ default_event: { type: 'string', description: 'New default event (must be valid for the pixel\'s platform).' },
845
+ capi_token: { type: ['string', 'null'], description: 'New Conversions API token, or empty/null to clear.' },
846
+ test_event_code: { type: ['string', 'null'], description: 'Meta test event code, or empty/null to clear it and go live.' },
847
+ active: { type: 'boolean' },
848
+ },
849
+ required: ['pixel_id_row'],
850
+ },
851
+ },
852
+ {
853
+ name: 'test_tracking_pixel',
854
+ description: 'Send one test event (a $1 Purchase by default) server-side with the pixel\'s own token, to prove the pixel id and token work. Only runs when the pixel has a test_event_code, so the test lands in Meta\'s Test events and never counts. Returns ok, and the platform\'s error when it refused. The pixel\'s last_sent_at / last_error (list_tracking_pixels) record the result.',
855
+ inputSchema: {
856
+ type: 'object',
857
+ properties: {
858
+ pixel_id_row: { type: 'number', description: 'The id of the tracking_pixels row (from list_tracking_pixels).' },
859
+ event: { type: 'string', description: 'Optional event name, valid for the platform. Defaults to Purchase.' },
860
+ },
861
+ required: ['pixel_id_row'],
862
+ },
863
+ },
864
+ {
865
+ name: 'delete_tracking_pixel',
866
+ description: 'Delete a tracking pixel. It is removed from any per-link selections and any campaign that used it as its conversion pixel (the campaign\'s conversion_pixel_id is cleared).',
867
+ inputSchema: { type: 'object', properties: { pixel_id_row: { type: 'number' } }, required: ['pixel_id_row'] },
868
+ },
869
+
870
+ // ─── Tracker: campaigns ─────────────────────────────────────────────────
871
+ {
872
+ name: 'list_campaigns',
873
+ description:
874
+ 'List the user\'s campaigns with quick-look stats (visits / offer_clicks / conversions / revenue). Each campaign has a short_url to paste into traffic sources, and a pixel_snippet to install on landers.',
875
+ inputSchema: { type: 'object', properties: { include_archived: { type: 'boolean', description: 'Also list archived ones. Default false.' } } },
876
+ },
877
+ {
878
+ name: 'create_campaign',
879
+ description:
880
+ 'Create a campaign. A campaign mints one short link (campaign.code) that the user pastes into Facebook / TikTok / etc. The resolver mints a click_id per visit, optionally routes through a lander (weighted), then redirects to an offer (weighted). The response also includes a `click_url` (`…/click`): the single, campaign-agnostic DEFINED lander click URL the user pastes into their lander\'s CTA button. It\'s the same on every campaign, so one lander can be reused across many; the campaign is resolved at click time from the visitor\'s `bgl_clk_{code}` cookie (short-link traffic) or the ad\'s `?utm_campaign={direct_slug}` that the lander forwards onto the CTA (direct-link). It always resolves to an offer (chosen by the flow graph), never a lander, never a dead page. For DIRECT-LINK campaigns (ad points straight at the lander, no tracker hop), set `direct_slug`, put `?utm_campaign={direct_slug}` on the ad URL, and have the lander forward that utm_campaign onto the CTA. `/click` resolves the campaign from it and the property tag stitches the page view too. `fallback_url` guarantees the click never dead-ends. Conversions come back on the account\'s one postback URL (get_universal_postback_url), which credits each sale to the campaign its click came from. You can optionally attach offer_ids / lander_ids inline with matching offer_weights / lander_weights arrays for a one-call setup.',
881
+ inputSchema: {
882
+ type: 'object',
883
+ properties: {
884
+ name: { type: 'string' },
885
+ traffic_source_id: { type: ['number', 'null'], description: 'Id of one of the user\'s saved traffic sources (from list_traffic_sources) to attribute this campaign to. Preferred over the legacy `traffic_source` string. Mirrors the source name into the display label.' },
886
+ traffic_source: { type: 'string', description: 'Legacy structured traffic source key, one of: facebook, instagram, google, youtube, tiktok, microsoft, linkedin, twitter, pinterest, snapchat, reddit, native, email, organic, other. Prefer `traffic_source_id`.' },
887
+ traffic_source_label: { type: 'string', description: 'Free text display label.' },
888
+ country: { type: 'string', description: 'ISO2 default geo.' },
889
+ cost_model: { type: 'string', enum: ['not_tracked', 'cpc', 'cpm'] },
890
+ cost_value: { type: 'number' },
891
+ transition_mode: { type: 'string', enum: ['302', 'meta_refresh'] },
892
+ domain_id: { type: ['number', 'null'], description: 'Optional id of one of the user\'s active custom domains (from list_domains). The campaign\'s short link will resolve at that hostname. If omitted, defaults to the user\'s first active custom domain, or offerswap.com if they have none. Pass null to force the platform default.' },
893
+ conversion_pixel_id: { type: ['number', 'null'], description: 'Optional id of one of the user\'s tracking pixels (from list_tracking_pixels) to fire when this campaign converts (server-side via the pixel\'s CAPI token when set). Pass null for no conversion pixel.' },
894
+ conversion_event: { type: 'string', description: 'Event name to fire on conversion (e.g. "Purchase", "Lead", "CompletePayment"). Must be a valid event for the conversion pixel\'s platform; defaults to that pixel\'s default_event. Prefer pixel_events, which also covers upsells, checkouts and carts.' },
895
+ pixel_events: {
896
+ type: ['object', 'null'],
897
+ description: 'Which of this campaign\'s events reach its conversion pixel, and as what. Keys are "conversion" (a sale), a traffic event ("lander_view": the campaign\'s landing page shown, or a view of a direct lander from the property tag; "visit": the ad click reaching the campaign link; "offer_click": the tap that leaves for the offer) or one of the account\'s custom event slugs (list_custom_events), values {event, first_only?}. `event` must be valid for the pixel\'s platform (e.g. Facebook "Purchase", "InitiateCheckout", "AddToCart"); an empty event means "don\'t send". first_only: true sends only the click\'s first event of that kind (e.g. the first sale, not rebills). A missing key is not sent. Example: {"conversion":{"event":"Purchase","first_only":true},"upsell":{"event":"Purchase"},"initiate_checkout":{"event":"InitiateCheckout"}}. Null keeps the old rule (sales only, as conversion_event). Events are sent server-side the moment they happen; refunds, re-fired orders and bot traffic never are. Add &email= to the postback URL so the platform can match the buyer (hashed, never stored).',
898
+ },
899
+ report_value_mode: { type: 'string', enum: ['payout', 'fixed', 'adjusted'], description: 'What revenue VALUE to report back to the ad platform on a CAPI conversion. "payout" (default) = the real conversion payout; "fixed" = always report report_value_fixed (e.g. 1); "adjusted" = real payout minus report_value_adjust_pct % then minus report_value_adjust_flat (so the user\'s margin/cost is withheld from what the platform optimizes against). Floored at 0.' },
900
+ report_value_fixed: { type: ['number', 'null'], description: 'Used when report_value_mode = "fixed": the exact value (USD) reported on every conversion regardless of real payout.' },
901
+ report_value_adjust_pct: { type: ['number', 'null'], description: 'Used when report_value_mode = "adjusted": percentage (0–100) subtracted from the real payout first (e.g. 10 reports payout − 10%).' },
902
+ report_value_adjust_flat: { type: ['number', 'null'], description: 'Used when report_value_mode = "adjusted": flat amount (USD) subtracted after the percentage.' },
903
+ direct_slug: { type: ['string', 'null'], description: 'DEPRECATED single-tag form (still accepted). Prefer direct_slugs. Optional direct-link tag, unique per user (lowercased alnum + dashes, e.g. "bsu-fb-cold"). Returns 409 (direct_slug_taken) if another campaign already uses it. Pass null to clear.' },
904
+ direct_slugs: { type: 'array', description: 'Direct-link tags this campaign claims, for running traffic STRAIGHT to a lander with no tracker hop. A campaign can claim MANY utm_campaign values (an older campaign being migrated in, a lander turned into a campaign, etc.). Each routes through this campaign\'s flow. Put `?utm_campaign={slug}` on the ad URL; the lander forwards it onto the /click CTA and the property tag stitches the page view. Each item is either a string (used as both slug + label) or `{ slug, label }` where slug is sanitized (lowercased alnum+dashes, what gets matched) and label is the friendly display value (e.g. "ABO Testing Campaign"). Each slug is unique per user → 409 (direct_slug_taken) on collision. Pass [] to clear all tags.', items: { oneOf: [ { type: 'string' }, { type: 'object', properties: { slug: { type: 'string' }, label: { type: 'string' } }, required: ['slug'] } ] } },
905
+ fallback_url: { type: ['string', 'null'], description: 'Optional URL the click falls back to when the flow yields no live offer: the never-dead-end guarantee. Pass null to use the platform default.' },
906
+ open_in_browser: { type: 'boolean', description: 'Older all-offers default, kept for compatibility: true sends a phone\'s tap to any offer with no phone_open of its own out of Facebook\'s in-app browser to Safari or Chrome. Prefer setting phone_open on each node with set_campaign_flow, which wins over this.' },
907
+ offer_ids: { type: 'array', items: { type: 'number' } },
908
+ offer_weights: { type: 'array', items: { type: 'number' } },
909
+ lander_ids: { type: 'array', items: { type: 'number' } },
910
+ lander_weights: { type: 'array', items: { type: 'number' } },
911
+ },
912
+ required: ['name'],
913
+ },
914
+ },
915
+ {
916
+ name: 'get_campaign',
917
+ description: 'Get a single campaign with its attached offers, landers, short URL, and pixel snippet. `direct_lander` is true on a direct link campaign: its ads link straight to a lander, so `short_url` goes on that page\'s button and not in the ads.',
918
+ inputSchema: { type: 'object', properties: { campaign_id: { type: 'number' } }, required: ['campaign_id'] },
919
+ },
920
+ {
921
+ name: 'update_campaign',
922
+ description: 'Update a campaign\'s name, structured traffic source, country, cost model/value, transition mode, traffic source label, branded domain, conversion pixel/event, direct-link slug, fallback URL, or archive state. Use set_campaign_offers / set_campaign_landers (or set_campaign_flow) to change the destination wiring. Pass domain_id to move the campaign\'s short link to a different custom domain, or null to send it back to offerswap.com.',
923
+ inputSchema: {
924
+ type: 'object',
925
+ properties: {
926
+ campaign_id: { type: 'number' },
927
+ name: { type: 'string' },
928
+ traffic_source_id: { type: ['number', 'null'], description: 'Id of a saved traffic source (from list_traffic_sources), or null to clear. Preferred over `traffic_source`.' },
929
+ traffic_source: { type: ['string', 'null'], description: 'Legacy structured traffic source key or null to clear.' },
930
+ traffic_source_label: { type: 'string' },
931
+ country: { type: 'string' },
932
+ cost_model: { type: 'string', enum: ['not_tracked', 'cpc', 'cpm'] },
933
+ cost_value: { type: 'number' },
934
+ transition_mode: { type: 'string', enum: ['302', 'meta_refresh'] },
935
+ domain_id: { type: ['number', 'null'], description: 'Id of one of the user\'s active custom domains, or null to move the campaign back to offerswap.com.' },
936
+ conversion_pixel_id: { type: ['number', 'null'], description: 'Id of a tracking pixel to fire on conversion, or null to clear.' },
937
+ conversion_event: { type: 'string', description: 'Event a sale is sent as (must be valid for that pixel\'s platform). Moves the sale\'s pixel_events rule with it. Prefer pixel_events.' },
938
+ pixel_events: {
939
+ type: ['object', 'null'],
940
+ description: 'Which of this campaign\'s events reach its conversion pixel, and as what. Keys are "conversion" (a sale), a traffic event ("lander_view": the campaign\'s landing page shown, or a view of a direct lander from the property tag; "visit": the ad click reaching the campaign link; "offer_click": the tap that leaves for the offer) or one of the account\'s custom event slugs (list_custom_events), values {event, first_only?}. `event` must be valid for the pixel\'s platform (e.g. Facebook "Purchase", "InitiateCheckout", "AddToCart"); an empty event means "don\'t send". first_only: true sends only the click\'s first event of that kind (e.g. the first sale, not rebills). A missing key is not sent. Example: {"conversion":{"event":"Purchase","first_only":true},"upsell":{"event":"Purchase"},"initiate_checkout":{"event":"InitiateCheckout"}}. Null keeps the old rule (sales only, as conversion_event). Events are sent server-side the moment they happen; refunds, re-fired orders and bot traffic never are. Add &email= to the postback URL so the platform can match the buyer (hashed, never stored).',
941
+ },
942
+ report_value_mode: { type: 'string', enum: ['payout', 'fixed', 'adjusted'], description: 'What revenue value to report back to the ad platform on conversion: "payout" (real), "fixed" (report_value_fixed), or "adjusted" (real payout − report_value_adjust_pct% − report_value_adjust_flat, floored at 0).' },
943
+ report_value_fixed: { type: ['number', 'null'], description: 'Fixed value (USD) reported on every conversion when report_value_mode = "fixed". Null to clear.' },
944
+ report_value_adjust_pct: { type: ['number', 'null'], description: 'Percentage (0–100) subtracted from real payout when report_value_mode = "adjusted". Null to clear.' },
945
+ report_value_adjust_flat: { type: ['number', 'null'], description: 'Flat USD amount subtracted (after the %) when report_value_mode = "adjusted". Null to clear.' },
946
+ direct_slug: { type: ['string', 'null'], description: 'DEPRECATED single-tag form (still accepted). Prefer direct_slugs. Direct-link tag for utm_campaign-based stitching (unique per user), or null to clear. Returns 409 (direct_slug_taken) on collision.' },
947
+ direct_slugs: { type: 'array', description: 'Replace this campaign\'s direct-link tags. A campaign can claim MANY utm_campaign values, each routing through its flow. Each item is a string (slug+label) or `{ slug, label }`. Slugs are unique per user → 409 (direct_slug_taken) on collision. Pass [] to clear all.', items: { oneOf: [ { type: 'string' }, { type: 'object', properties: { slug: { type: 'string' }, label: { type: 'string' } }, required: ['slug'] } ] } },
948
+ fallback_url: { type: ['string', 'null'], description: 'Never-dead-end fallback URL when no live offer exists, or null to use the platform default.' },
949
+ open_in_browser: { type: 'boolean', description: 'Older all-offers default, kept for compatibility: true sends a phone\'s tap to any offer with no phone_open of its own out of Facebook\'s in-app browser to Safari or Chrome. Prefer setting phone_open on each node with set_campaign_flow, which wins over this.' },
950
+ dim_labels: { type: 'object', additionalProperties: { type: 'string' }, description: 'The user\'s names for this campaign\'s tokens, keyed by dimension: { "utm_medium": "Ad Name", "param:adset_name": "Ad Set" }. Replaces the whole set, so send the names to keep too. Only utm_* and param:<name> keys are kept, and a blank name removes that one. The report keeps showing the URL\'s name beside it.' },
951
+ archived: { type: 'boolean' },
952
+ },
953
+ required: ['campaign_id'],
954
+ },
955
+ },
956
+ {
957
+ name: 'archive_campaign',
958
+ description: 'Archive a campaign. Campaigns are never deleted: an archived campaign keeps its flow, reports and history, but its short link stops routing (it shows the not found page) and list_campaigns leaves it out. Restore it with update_campaign archived=false.',
959
+ inputSchema: { type: 'object', properties: { campaign_id: { type: 'number' } }, required: ['campaign_id'] },
960
+ },
961
+ {
962
+ name: 'duplicate_campaign',
963
+ description: 'Deep-copy a campaign: clones the campaign settings plus its full routing flow (source → landers → offers graph and split-test weights) and its offer/lander pools. The copy gets a fresh short link and a name like "COPY - {original}" (or "COPY (1) - {original}", "COPY (2) - …" when copying a copy). Stats are NOT copied; the direct-link slug is left blank (it must be unique). Returns the new campaign, including its short_url/click_url. Useful for spinning up a new geo/angle variant of a working campaign without rebuilding the flow.',
964
+ inputSchema: { type: 'object', properties: { campaign_id: { type: 'number' } }, required: ['campaign_id'] },
965
+ },
966
+ {
967
+ name: 'set_campaign_offers',
968
+ description: 'Replace the campaign\'s offer split with the supplied items. Each item is { offer_id, weight }. Weight is an integer; higher = more traffic. To direct all traffic to one offer use weight=100 for that offer and don\'t include the others.',
969
+ inputSchema: {
970
+ type: 'object',
971
+ properties: {
972
+ campaign_id: { type: 'number' },
973
+ items: {
974
+ type: 'array',
975
+ items: {
976
+ type: 'object',
977
+ properties: { offer_id: { type: 'number' }, weight: { type: 'number' } },
978
+ required: ['offer_id', 'weight'],
979
+ },
980
+ },
981
+ },
982
+ required: ['campaign_id', 'items'],
983
+ },
984
+ },
985
+ {
986
+ name: 'set_campaign_landers',
987
+ description: 'Replace the campaign\'s lander split. Pass empty items to remove all landers (clicks then go direct to offer). Each item is { lander_id, weight }.',
988
+ inputSchema: {
989
+ type: 'object',
990
+ properties: {
991
+ campaign_id: { type: 'number' },
992
+ items: {
993
+ type: 'array',
994
+ items: {
995
+ type: 'object',
996
+ properties: { lander_id: { type: 'number' }, weight: { type: 'number' } },
997
+ required: ['lander_id', 'weight'],
998
+ },
999
+ },
1000
+ },
1001
+ required: ['campaign_id', 'items'],
1002
+ },
1003
+ },
1004
+ {
1005
+ name: 'get_campaign_flow',
1006
+ description:
1007
+ 'Get the campaign\'s routing flow graph (n8n-style). Returns { flow: { nodes, edges }, offers, landers }. Nodes are { id, kind: "source"|"lander"|"offer"|"rule", ref_id, pos_x, pos_y, direct, offer?, lander? }, with exactly one "source" node (the traffic entry). A "rule" node also has name, conditions and priority (see set_campaign_flow). Edges are { id, from_node_id, to_node_id, weight } and only go source→lander, source→offer (direct), or lander→offer; weight is the split-test weight. This graph is what the resolver walks per click, letting a specific lander route to its own specific offers.',
1008
+ inputSchema: {
1009
+ type: 'object',
1010
+ properties: { campaign_id: { type: 'number' } },
1011
+ required: ['campaign_id'],
1012
+ },
1013
+ },
1014
+ {
1015
+ name: 'set_campaign_flow',
1016
+ description:
1017
+ 'Replace the campaign\'s routing flow graph. Body: { nodes: [{ tmp_id, kind, ref_id, pos_x, pos_y, direct? }], edges: [{ from, to, weight }] }. Set direct=true on a lander node when the ad links straight to that page and the campaign short link or `/click` sits on its button: the link then goes on to that lander\'s offers instead of sending the visitor to the page, and direct landers win over every other edge on the source. No ad URL has to change. tmp_id is any client-stable string key; edges reference nodes by tmp_id. Provide exactly one node with kind="source" (ref_id null) as the traffic entry; "lander" / "offer" nodes set ref_id to a lander/offer id you own. Edges must go source→lander, source→offer, or lander→offer. weight is an integer split-test weight (higher = more traffic). Saving also re-derives the flat offer/lander pools, so legacy reports stay consistent. Use this to add a second offer for a split test, divert a lander to a different offer, or insert a landing page before an offer. RULES (0.42.0): a node with kind "rule" takes { name, conditions, priority } and no ref_id. It hangs off the source (not on a direct link campaign, whose ad goes straight to its page) or off a lander, with exactly one edge into it, and its own edges are its branches: landers or offers after the source, offers after a lander. When a visitor reaches a step, the step\'s rules are checked in priority order (lowest first); the first whose conditions ALL match and that has a branch sends them down its branches (weighted as usual), and everyone else goes down the step\'s plain edges. A step with rules and no plain edge sends unmatched visitors to the campaign\'s fallback_url. A condition is { type, op: "is"|"is_not", values } with type one of country (ISO2), region, city, device (mobile|desktop), os (ios|android|mac|windows|linux|other), browser (chrome|safari|firefox|edge|opera|other), inapp (facebook|instagram|messenger|tiktok|twitter|linkedin|pinterest|snapchat|none), language (2 letter code), ip (addresses or CIDR ranges), isp (network name contains), referrer (domain, subdomains match), param ({ name, values }, empty values = present), time ({ from: "HH:MM", to: "HH:MM", tz }, to is exclusive, to < from wraps midnight) or weekday ({ values: ["mon"...], tz }). Values in a condition are ORed, conditions in a rule are ANDed. A bad condition or a rule in the wrong place is a 400 with a message.',
1018
+ inputSchema: {
1019
+ type: 'object',
1020
+ properties: {
1021
+ campaign_id: { type: 'number' },
1022
+ nodes: {
1023
+ type: 'array',
1024
+ items: {
1025
+ type: 'object',
1026
+ properties: {
1027
+ tmp_id: { type: 'string' },
1028
+ kind: { type: 'string', enum: ['source', 'lander', 'offer', 'rule'] },
1029
+ ref_id: { type: ['number', 'null'] },
1030
+ name: { type: 'string', description: 'Rules only. What the rule is called, like "Cell phones".' },
1031
+ priority: { type: 'number', description: 'Rules only. Order among the rules on the same step, lowest checked first.' },
1032
+ conditions: {
1033
+ type: 'array',
1034
+ description: 'Rules only. All must match. See the tool description for the types and their values.',
1035
+ items: {
1036
+ type: 'object',
1037
+ properties: {
1038
+ type: { type: 'string', enum: ['country', 'region', 'city', 'device', 'os', 'browser', 'inapp', 'language', 'ip', 'isp', 'referrer', 'param', 'time', 'weekday'] },
1039
+ op: { type: 'string', enum: ['is', 'is_not'] },
1040
+ values: { type: 'array', items: { type: 'string' } },
1041
+ name: { type: 'string', description: 'param only: the URL parameter, like utm_campaign.' },
1042
+ from: { type: 'string', description: 'time only: HH:MM.' },
1043
+ to: { type: 'string', description: 'time only: HH:MM, exclusive.' },
1044
+ tz: { type: 'string', description: 'time and weekday: IANA time zone, like America/New_York.' },
1045
+ },
1046
+ required: ['type'],
1047
+ },
1048
+ },
1049
+ pos_x: { type: 'number' },
1050
+ pos_y: { type: 'number' },
1051
+ direct: { type: 'boolean', description: 'Landers only. True when the ad links straight to this page, so the campaign link goes on to its offers instead of back to the page.' },
1052
+ phone_open: { type: ['string', 'null'], enum: ['app', 'browser', 'stay', null], description: 'Landers and offers. On a phone, what a tap TO this step does. "browser" leaves Facebook\'s, Instagram\'s or TikTok\'s own in-app browser for Safari or Chrome first (on a lander: the ad tap; on a direct lander the OfferSwap tracking tag on the page does the move; on an offer: the button tap). "stay" loads it where they tapped. "app" (offers only) opens the offer\'s app. Null is the default: an offer that belongs to an app (Amazon...) opens its app, anything else stays, unless the campaign\'s older open_in_browser is on. Leaving the in-app browser loses some people at the move and the browser holding Meta\'s cookies.' },
1053
+ },
1054
+ required: ['tmp_id', 'kind'],
1055
+ },
1056
+ },
1057
+ edges: {
1058
+ type: 'array',
1059
+ items: {
1060
+ type: 'object',
1061
+ properties: {
1062
+ from: { type: 'string' },
1063
+ to: { type: 'string' },
1064
+ weight: { type: 'number' },
1065
+ },
1066
+ required: ['from', 'to'],
1067
+ },
1068
+ },
1069
+ },
1070
+ required: ['campaign_id', 'nodes', 'edges'],
1071
+ },
1072
+ },
1073
+ {
1074
+ name: 'get_campaign_stats',
1075
+ description:
1076
+ 'Get a campaign\'s full report: totals (visits / unique_visits / lander_views / unique_lander_views / offer_clicks / unique_offer_clicks / conversions / refunds / chargebacks / revenue / gross_revenue / reversed_revenue / custom / cost / profit / CTR / CR / EPC / AOV / ROI). `conversions` counts sales. `aov` is average order value after refunds and chargebacks: net revenue per sale (0 with no sale). `gross_aov` is average order value before them: gross revenue per sale. `epc` (totals and every row) is GROSS revenue per offer click, before refunds and chargebacks. `revenue` is NET: sales and revenue-counting custom events, minus refunds and chargebacks. `custom` is keyed by event slug, each {count, revenue}, and `custom_events` lists the account\'s definitions with their labels. The rest of the report: by_day / by_country / by_device / by_browser / by_referrer / by_hour, per-offer and per-lander performance, the 50 most recent events, and `breakdowns`: Voluum-style grouped report rows for 10 dimensions (utm_campaign / utm_medium / utm_source / utm_content / utm_term / lander / offer / country / device / day), each row {key, visits, unique_visits, clicks, unique_clicks, lander_views, unique_lander_views, conversions, refunds, chargebacks, revenue, gross_revenue, reversed_revenue, cost, custom, ctr, cr, epc, aov, gross_aov}. `cost` (here and in `totals`) is the ad cost the campaign\'s cost model put on its visits (CPC), 0 without one. It never includes refunds or chargebacks, which are `reversed_revenue` (the app\'s Reversed column). UNIQUES count people, not rows: unique_visits and unique_clicks (unique_offer_clicks in totals) go by the IP and user agent of the visit that minted the click, unique_lander_views by the property tag\'s visitor cookie, then IP and device. A person who taps the button three times is 3 clicks and 1 unique click. `totals.unique_events` counts the people behind each sale and custom event, keyed `conversion` or the event slug (refunds and chargebacks are left out). Offer clicks and conversions are attributed to the utm values of the visit that minted their click_id (postback conversions landing after the visit included); the `offer` dimension attributes each visit to the offer its click routed to (keyed by offer NAME), so split-test rows read correctly; the `lander` dimension is the page the click came FROM (visit referrer normalized to host+path; full paths for landers running the property tag, ad-platform hosts like m.facebook.com for straight-from-ad clicks); traffic with no value groups under "(none)". DRILL-DOWN: pass any dimension as a filter (e.g. utm_campaign="Summer Sale", lander="promo.example.com/lander-a", or offer="My Offer") and the WHOLE report (totals, by_day, breakdowns) narrows to that traffic slice; combine filters to drill deeper (e.g. utm_campaign + group the result\'s `breakdowns.offer` to see which offer converts for that ad). Pass "(none)" to match events with no value. DIRECT LANDERS: when the flow has a direct lander, `direct_lander` is true, `totals.lander_views` and each row\'s `lander_views` count that page\'s property-tag page views, and `lander_ctr` is visits per lander view. Page views have no offer, so `lander_views` is 0 on the offer dimension and under an offer filter. A campaign with direct-link tags counts tagged traffic only. STACKED REPORT: pass `group` (up to 3 dimensions, e.g. ["utm_campaign", "utm_medium", "offer"]) and `report.rows` comes back as a Binom-style tree, each row carrying its slice\'s metrics and `children` for the next level. With no `group` the report groups by offer. `group` also accepts region / city / browser / language / weekday / hour (day, weekday and hour count in the account time zone, see `timezone` on the response) and custom tokens as `param:<name>`: every extra param on the inbound link (adset_name=..., sub3=..., utm_id=...) is kept on the visit, except click ids and personal fields. `passed_dims` lists what the URLs really carried in the window: the utm_* tokens that had a value, then the `param:<name>` ones. On a direct lander the ad\'s URL counts even if the page\'s button drops it: the visit fills in from that visitor\'s page view, and `lander_views` split by token too. `dim_labels` holds the names the user gave this campaign\'s tokens (e.g. utm_medium: "Ad Name"), set with update_campaign. Read those before describing a dimension to the user, and never assume what a slot holds: setups differ even between two campaigns on one offer, so with no name on a token, call it by its URL name.',
1077
+ inputSchema: {
1078
+ type: 'object',
1079
+ properties: {
1080
+ campaign_id: { type: 'number' },
1081
+ days: { type: 'number', description: 'Rolling window size in days (1–90). Defaults to 14. Ignored when `from` is set.' },
1082
+ tz: { type: 'string', description: 'IANA time zone (e.g. America/New_York) to count days, weekdays and hours in. Defaults to the account time zone (set_account_timezone), else UTC. The response echoes it as `timezone`.' },
1083
+ group: { type: 'array', items: { type: 'string' }, maxItems: 3, description: 'Up to 3 dimensions to stack into the `report.rows` tree, outermost first. Custom tokens are written param:<name>.' },
1084
+ breakdowns: { type: 'boolean', description: 'Default true. false skips the ten fixed `breakdowns` (returned empty) and keeps everything else, which makes a long window on a busy campaign several times faster. Use `group` for the dimensions you need.' },
1085
+ filters: { type: 'object', additionalProperties: { type: 'string' }, description: 'Extra drill-down filters by dimension, for anything without its own argument, e.g. {"param:adset_name": "Broad 35+", "browser": "safari"}.' },
1086
+ from: { type: 'string', description: 'ISO date/datetime: start of an explicit closed range (overrides days).' },
1087
+ to: { type: 'string', description: 'ISO date/datetime: end of the explicit range. Defaults to now when omitted.' },
1088
+ utm_campaign: { type: 'string', description: 'Drill-down filter: only traffic whose minting visit carried this utm_campaign.' },
1089
+ utm_medium: { type: 'string', description: 'Drill-down filter by utm_medium.' },
1090
+ utm_source: { type: 'string', description: 'Drill-down filter by utm_source.' },
1091
+ utm_content: { type: 'string', description: 'Drill-down filter by utm_content.' },
1092
+ utm_term: { type: 'string', description: 'Drill-down filter by utm_term.' },
1093
+ lander: { type: 'string', description: 'Drill-down filter by lander page (host+path, as returned in breakdowns.lander keys).' },
1094
+ offer: { type: 'string', description: 'Drill-down filter by offer NAME (as returned in breakdowns.offer keys).' },
1095
+ country: { type: 'string', description: 'Drill-down filter by ISO2 country of the minting visit.' },
1096
+ device: { type: 'string', description: 'Drill-down filter by device of the minting visit.' },
1097
+ day: { type: 'string', description: 'Drill-down filter by day (YYYY-MM-DD) of the minting visit, in the report time zone.' },
1098
+ },
1099
+ required: ['campaign_id'],
1100
+ },
1101
+ },
1102
+
1103
+ // ─── Tracker: properties (GTM/GA-style site containers) ─────────────────
1104
+ {
1105
+ name: 'list_properties',
1106
+ description:
1107
+ 'List the user\'s properties with quick-look stats (page_views / unique_visitors / conversions / revenue). Best one-call tool for "page views per property" / "page views for each site". A property is a whole-site container: the user installs ONE universal tag (returned as `snippet`) on every page of their site and every page auto-reports pageviews, time-on-page, scroll depth, outbound clicks, and conversions. Page events auto-attribute to a campaign when a visitor arrives carrying that campaign\'s click.',
1108
+ inputSchema: { type: 'object', properties: { include_archived: { type: 'boolean', description: 'Also list archived ones. Default false.' } } },
1109
+ },
1110
+ {
1111
+ name: 'create_property',
1112
+ description:
1113
+ 'Create a property (a GTM/GA-style site container). Returns the property with its public property_key, the `tracking_domain` it\'s bound to, and an install `snippet`: a single GA/Facebook-style inline <script> block (a self-invoking function that sets up a conversion-queue stub and injects the async tag) the user pastes into the <head> of every page of their site. REQUIRES an active custom domain: the tag is served from the user\'s own domain so it stays first-party to their site, which is required for tracking to work on iOS/Safari (a tag loaded cross-site from offerswap.com gets its visitor cookie partitioned/blocked). Defaults to the user\'s first active custom domain; pass `domain_id` (from list_domains) to pin a specific one. If the user has no active custom domain, returns error `domain_required`. Have them add one via create_domain first. To record conversions, the site sets window.bglConversion = true (optionally window.bglRevenue) on a thank-you page, or calls window.bglFireConversion(revenue). The queue stub makes that call safe even before the async tag finishes loading.',
1114
+ inputSchema: {
1115
+ type: 'object',
1116
+ properties: {
1117
+ name: { type: 'string' },
1118
+ site_url: { type: 'string', description: 'Optional primary site URL, informational.' },
1119
+ domain_id: { type: 'number', description: 'Optional id of one of the user\'s active custom domains (from list_domains) to serve the tag from. Defaults to the first active custom domain.' },
1120
+ },
1121
+ required: ['name'],
1122
+ },
1123
+ },
1124
+ {
1125
+ name: 'get_property',
1126
+ description: 'Get a single property with its install snippet and the campaigns linked to it.',
1127
+ inputSchema: { type: 'object', properties: { property_id: { type: 'number' } }, required: ['property_id'] },
1128
+ },
1129
+ {
1130
+ name: 'update_property',
1131
+ description: 'Update a property\'s name, site_url, tracking domain (domain_id), or archive state. Pass `domain_id` to re-bind the install snippet to a different active custom domain. It must be one of the user\'s active custom domains (a property can never fall back to offerswap.com, since that breaks iOS tracking). Returns the updated property with its `tracking_domain` and regenerated `snippet`.',
1132
+ inputSchema: {
1133
+ type: 'object',
1134
+ properties: {
1135
+ property_id: { type: 'number' },
1136
+ name: { type: 'string' },
1137
+ site_url: { type: ['string', 'null'] },
1138
+ domain_id: { type: 'number', description: 'Id of one of the user\'s active custom domains (from list_domains) to serve the tag from.' },
1139
+ archived: { type: 'boolean' },
1140
+ },
1141
+ required: ['property_id'],
1142
+ },
1143
+ },
1144
+ {
1145
+ name: 'archive_property',
1146
+ description: 'Archive a property. Properties are never deleted: an archived property keeps its page views and history, its tag stops counting, and list_properties leaves it out. Its custom domain stays connected. Restore it with update_property archived=false.',
1147
+ inputSchema: { type: 'object', properties: { property_id: { type: 'number' } }, required: ['property_id'] },
1148
+ },
1149
+ {
1150
+ name: 'set_property_campaigns',
1151
+ description: 'Replace the set of campaigns linked to a property (many-to-many, for organisation and the source split in reports). Each item is { campaign_id }. Pass empty items to unlink all. Stitching still happens automatically by click regardless of explicit links.',
1152
+ inputSchema: {
1153
+ type: 'object',
1154
+ properties: {
1155
+ property_id: { type: 'number' },
1156
+ items: {
1157
+ type: 'array',
1158
+ items: {
1159
+ type: 'object',
1160
+ properties: { campaign_id: { type: 'number' } },
1161
+ required: ['campaign_id'],
1162
+ },
1163
+ },
1164
+ },
1165
+ required: ['property_id', 'items'],
1166
+ },
1167
+ },
1168
+ {
1169
+ name: 'get_property_stats',
1170
+ description:
1171
+ 'Get a single property\'s GA-style PAGE VIEW report: totals (page_views / unique_visitors / outbound / conversions / revenue / avg_time_on_page_ms / avg_scroll_pct / CR), by_day, by_page (top paths with views+conversions+revenue), by_source (organic vs each stitched campaign), by_country / by_device / by_browser / by_referrer, and the 50 most recent events.',
1172
+ inputSchema: {
1173
+ type: 'object',
1174
+ properties: {
1175
+ property_id: { type: 'number' },
1176
+ days: { type: 'number', description: 'Window size in days (1–90). Defaults to 14.' },
1177
+ tz: { type: 'string', description: 'IANA time zone (e.g. America/New_York) to count days, weekdays and hours in. Defaults to the account time zone (set_account_timezone), else UTC. The response echoes it as `timezone`.' },
1178
+ },
1179
+ required: ['property_id'],
1180
+ },
1181
+ },
1182
+ {
1183
+ name: 'list_property_pages',
1184
+ description:
1185
+ 'List the distinct pages observed across ALL the user\'s properties (the pageview stream), most-viewed first. Each entry is `{ url, path, title, property_id, property_name, views }`. Any of these pages can be used as a campaign LANDER: pass its `url` to `create_lander` (the page title makes a good lander name) and then wire the resulting lander into a campaign flow via `set_campaign_flow`. Use this to turn a real page on the user\'s site into a lander without retyping its URL.',
1186
+ inputSchema: { type: 'object', properties: {} },
1187
+ },
1188
+ {
1189
+ name: 'list_observed_campaign_tags',
1190
+ description:
1191
+ 'List the distinct `utm_campaign` values that have actually been SEEN arriving on the user\'s properties/visits over the last 90 days, most-active first. Each entry is `{ utm_campaign, slug, events, utm_source, utm_medium, lander_url, claimed_by }` where `utm_campaign` is the raw value (for display, e.g. "ABO Testing Campaign"), `slug` is its sanitized form (what gets stored + matched), and `claimed_by` is `{ id, name }` of the BGL campaign that already owns that slug, or null if unclaimed. Use this to WIRE UP AN ALREADY-RUNNING DIRECT-LINK CAMPAIGN: when an ad on FB/Google points straight at a lander (no tracker hop) with `?utm_campaign={tag}`, that tag shows up here once the universal property tag reports a page view. Pick an unclaimed tag and add it to a campaign\'s `direct_slugs` (via `update_campaign`, passing `{ slug, label: utm_campaign }`) so BGL attributes that traffic, and its `/click` CTA, to the right campaign + offer. A campaign can claim several tags. Skip tags whose `claimed_by` is non-null (another campaign already owns them).',
1192
+ inputSchema: { type: 'object', properties: {} },
1193
+ },
1194
+ {
1195
+ name: 'get_tracker_overview',
1196
+ description:
1197
+ 'PAGE VIEWS live here. Get the unified Tracker dashboard rollup across BOTH event streams (site properties + campaigns) in one call. Returns totals (page_views / unique_visitors / visits / offer_clicks / conversions / revenue), a merged daily activity series (by_day), dimension breakdowns (by_country / by_device / by_browser), per-property and per-campaign rollups (the per-property rollup gives page_views for each site/property; each campaign row has visits, lander_views, offer_clicks, conversions, net revenue and direct_lander, and its EPV is revenue / lander_views when direct_lander is true, else revenue / visits, the same as the campaign Report), a per-UTM-campaign rollup (utm_campaigns: auto-detected Google utm_source/medium/campaign/content tags with events/conversions/revenue), a per-source rollup (utm_sources: one row per utm_source with events/conversions/net revenue, uncapped). In both, a sale is credited to the UTMs of the visit on its click, since a postback carries none, and events counts traffic only. and the 50 most recent events across both streams. This is the go-to tool for "page views", "page views per property", "campaign traffic", and "is everything running and getting traffic?". NOTE: page_views here is Tracker site traffic and is SEPARATE from branded short-link clicks (get_overview_stats). If the user asks for "clicks AND page views" together, call BOTH this tool and get_overview_stats and combine them.',
1198
+ inputSchema: {
1199
+ type: 'object',
1200
+ properties: {
1201
+ days: { type: 'number', description: 'Window size in days (1–90). Defaults to 14. Ignored when `from` is set.' },
1202
+ from: { type: 'string', description: 'ISO date/datetime: start of an explicit range (overrides days). For "today" pass local midnight; leave `to` out to stay open to now.' },
1203
+ to: { type: 'string', description: 'ISO date/datetime: end of the explicit range. Defaults to now.' },
1204
+ tz: { type: 'string', description: 'IANA time zone (e.g. America/New_York) to count days, weekdays and hours in. Defaults to the account time zone (set_account_timezone), else UTC. The response echoes it as `timezone`.' },
1205
+ offer_id: { type: 'number', description: 'Scope to one offer: its campaign traffic and the sales on its clicks. Drops the property stream.' },
1206
+ property_id: { type: 'number', description: 'Scope to one property\'s page views. Drops the campaign stream.' },
1207
+ },
1208
+ },
1209
+ },
1210
+ {
1211
+ name: 'get_realtime',
1212
+ description:
1213
+ 'Who is on the account\'s pages and campaigns RIGHT NOW: the last 30 minutes across every campaign and property, like Google Analytics Realtime. Returns active_30 and active_5 (people active in the last 30 and 5 minutes), per_minute (30 counts, oldest minute first), by_campaign (active people per campaign, `name: "Not from a campaign"` for people on a tagged page that no campaign claimed), by_page (page views and people per page, host+path, with its title), events (the funnel in order: page views, visits, offer clicks, custom events such as add to cart, sales, then upsells and refunds, each with `count` and `people`), and locations (people per city with lat/lon, for a map; `located` says how many could be placed). A person is IP + device + browser, so one visitor who viewed the lander, tapped through and bought counts once; a sale counts under its click\'s visitor. Bots are left out. Also returns revenue_today: GROSS revenue since midnight (sales and upsells, before refunds and chargebacks, which belong to sales from other days) and net_revenue_today (after them), in `timezone`, the `tz` given or the account\'s zone. And recent_sales: the newest sales and upsells of the last 30 minutes (up to 10, newest first), each with id, ts, label ("Sale" or the custom event\'s label), amount, currency, offer, campaign_id, campaign, and the buyer\'s city, region and country from the visit on their click. Use for "did we just get a sale", "where did that sale come from", "how many people are on right now", "is the ad live", "where are they dropping off right now", "how much have we made today".',
1214
+ inputSchema: {
1215
+ type: 'object',
1216
+ properties: {
1217
+ tz: { type: 'string', description: 'IANA time zone that today starts in for revenue_today, e.g. America/New_York. Defaults to the account time zone, then UTC.' },
1218
+ },
1219
+ },
1220
+ },
1221
+ {
1222
+ name: 'get_tracker_events',
1223
+ description:
1224
+ 'Query the unified Tracker event log across BOTH streams (site properties + campaigns), with full search / filter / sort over auto-detected Google UTM tags. Every event carries utm_source / utm_medium / utm_campaign / utm_term / utm_content. Use `q` for free-text search (matches any utm value, country, device, browser, referrer, source name, event type); `stream` to scope to all|property|campaign; `event` to filter by event_type; the utm_* params for exact-match filtering; `campaign_id` / `offer_id` / `property_id` / `link_id` to scope it; and `sort`+`dir` to order by any column. Rows from a campaign carry the location, IP and UTMs of the visit on their click, so a sale row shows where its buyer came from. Bot traffic (Meta ad reviewers, crawlers) is left out. Returns the matching page of events plus `facets` (distinct utm values present in the window) to drive filter pickers, and `total` for the full match count.',
1225
+ inputSchema: {
1226
+ type: 'object',
1227
+ properties: {
1228
+ days: { type: 'number', description: 'Window size in days (1–90). Defaults to 14. Ignored when `from` is set.' },
1229
+ from: { type: 'string', description: 'ISO date/datetime: start of an explicit range (overrides days).' },
1230
+ to: { type: 'string', description: 'ISO date/datetime: end of the explicit range. Defaults to now.' },
1231
+ q: { type: 'string', description: 'Free-text search across utm_*, country, city, device, browser, referrer, source name, event type.' },
1232
+ stream: { type: 'string', enum: ['all', 'property', 'campaign'], description: 'Scope to one stream. Defaults to all. Ignored when a campaign, offer, property or link scope is set.' },
1233
+ campaign_id: { type: 'number', description: 'Only this campaign\'s events (visits, offer clicks, sales, custom events, refunds).' },
1234
+ offer_id: { type: 'number', description: 'Only events on clicks that went to this offer.' },
1235
+ property_id: { type: 'number', description: 'Only this property\'s page events.' },
1236
+ link_id: { type: 'number', description: 'Only this plain short link\'s clicks (shown as event_type "click").' },
1237
+ event: { type: 'string', description: 'Exact event_type filter, e.g. page_view, outbound, conversion, visit, lander_view, offer_click.' },
1238
+ utm_source: { type: 'string', description: 'Exact utm_source filter.' },
1239
+ utm_medium: { type: 'string', description: 'Exact utm_medium filter.' },
1240
+ utm_campaign: { type: 'string', description: 'Exact utm_campaign filter.' },
1241
+ utm_term: { type: 'string', description: 'Exact utm_term filter.' },
1242
+ utm_content: { type: 'string', description: 'Exact utm_content filter.' },
1243
+ sort: { type: 'string', enum: ['ts', 'revenue', 'stream', 'source_name', 'event_type', 'country', 'region', 'city', 'ip', 'device', 'browser', 'referrer', 'page_path', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'], description: 'Sort field. Defaults to ts.' },
1244
+ dir: { type: 'string', enum: ['asc', 'desc'], description: 'Sort direction. Defaults to desc.' },
1245
+ limit: { type: 'number', description: 'Page size (1–500). Defaults to 200.' },
1246
+ offset: { type: 'number', description: 'Pagination offset. Defaults to 0.' },
1247
+ },
1248
+ },
1249
+ },
1250
+ ];
1251
+
1252
+ // Runs one tool and returns the API's answer. Throws on an unknown tool, bad
1253
+ // arguments or an API error; the caller turns that into an MCP error result.
1254
+ export async function callTool(name, args, { api, readLocalFile } = {}) {
1255
+ let result;
1256
+ switch (name) {
1257
+ case 'create_link': {
1258
+ const body = {
1259
+ destination_url: args.destination_url,
1260
+ title: args.title,
1261
+ source_label: args.source_label,
1262
+ };
1263
+ if (typeof args.domain_id === 'number') body.domain_id = args.domain_id;
1264
+ if ('phone_open' in args) body.phone_open = args.phone_open;
1265
+ result = await api('/api/links', {
1266
+ method: 'POST',
1267
+ body: JSON.stringify(body),
1268
+ });
1269
+ break;
1270
+ }
1271
+ case 'update_link': {
1272
+ const body = {};
1273
+ if (typeof args.destination_url === 'string') body.destination_url = args.destination_url;
1274
+ if (typeof args.title === 'string') body.title = args.title;
1275
+ if (typeof args.source_label === 'string') body.source_label = args.source_label;
1276
+ if (typeof args.archived === 'boolean') body.archived = args.archived;
1277
+ if (typeof args.password === 'string') body.password = args.password;
1278
+ if (args.domain_id === null || typeof args.domain_id === 'number') {
1279
+ body.domain_id = args.domain_id;
1280
+ }
1281
+ if (args.alias === null || typeof args.alias === 'string') {
1282
+ body.alias = args.alias;
1283
+ }
1284
+ if ('phone_open' in args) body.phone_open = args.phone_open;
1285
+ result = await api(`/api/links/${Number(args.link_id)}`, {
1286
+ method: 'PATCH',
1287
+ body: JSON.stringify(body),
1288
+ });
1289
+ break;
1290
+ }
1291
+ case 'refresh_link_image': {
1292
+ result = await api(`/api/links/${Number(args.link_id)}/refresh-image`, {
1293
+ method: 'POST',
1294
+ });
1295
+ break;
1296
+ }
1297
+ case 'delete_link': {
1298
+ result = await api(`/api/links/${Number(args.link_id)}`, { method: 'DELETE' });
1299
+ break;
1300
+ }
1301
+ case 'get_link_pixels': {
1302
+ result = await api(`/api/links/${Number(args.link_id)}/pixels`);
1303
+ break;
1304
+ }
1305
+ case 'set_link_pixels': {
1306
+ const body = { pixel_ids: (args.pixel_ids || []).map(Number) };
1307
+ if (typeof args.overridden === 'boolean') body.overridden = args.overridden;
1308
+ if (args.events && typeof args.events === 'object') body.events = args.events;
1309
+ result = await api(`/api/links/${Number(args.link_id)}/pixels`, { method: 'PUT', body: JSON.stringify(body) });
1310
+ break;
1311
+ }
1312
+ case 'set_link_collection': {
1313
+ const cid = args.collection_id == null ? null : Number(args.collection_id);
1314
+ result = await api(`/api/links/${Number(args.link_id)}/collection`, {
1315
+ method: 'POST', body: JSON.stringify({ collection_id: cid }),
1316
+ });
1317
+ break;
1318
+ }
1319
+
1320
+ // ── Collections ──
1321
+ case 'list_collections': {
1322
+ result = await api('/api/collections');
1323
+ break;
1324
+ }
1325
+ case 'get_collection': {
1326
+ result = await api(`/api/collections/${Number(args.collection_id)}${qsFrom(args, ['days'])}`);
1327
+ break;
1328
+ }
1329
+ case 'create_collection':
1330
+ case 'update_collection': {
1331
+ const body = {};
1332
+ for (const k of ['name', 'description', 'color', 'rotator_alias']) {
1333
+ if (typeof args[k] === 'string') body[k] = args[k];
1334
+ }
1335
+ for (const k of ['starred', 'rotator_enabled']) {
1336
+ if (typeof args[k] === 'boolean') body[k] = args[k];
1337
+ }
1338
+ result = name === 'create_collection'
1339
+ ? await api('/api/collections', { method: 'POST', body: JSON.stringify(body) })
1340
+ : await api(`/api/collections/${Number(args.collection_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1341
+ break;
1342
+ }
1343
+ case 'delete_collection': {
1344
+ result = await api(`/api/collections/${Number(args.collection_id)}`, { method: 'DELETE' });
1345
+ break;
1346
+ }
1347
+
1348
+ // ── Account ──
1349
+ case 'get_account': {
1350
+ result = await api('/api/me');
1351
+ break;
1352
+ }
1353
+ case 'list_api_keys': {
1354
+ result = await api('/api/api-keys');
1355
+ break;
1356
+ }
1357
+ case 'create_api_key': {
1358
+ const body = typeof args?.label === 'string' ? { label: args.label } : {};
1359
+ result = await api('/api/api-keys', { method: 'POST', body: JSON.stringify(body) });
1360
+ break;
1361
+ }
1362
+ case 'delete_api_key': {
1363
+ result = await api(`/api/api-keys/${Number(args.api_key_id)}`, { method: 'DELETE' });
1364
+ break;
1365
+ }
1366
+
1367
+ case 'list_links': {
1368
+ const qs = args?.include_archived ? '?include_archived=1' : '';
1369
+ result = await api(`/api/links${qs}`);
1370
+ break;
1371
+ }
1372
+ case 'get_links_report': {
1373
+ const q = new URLSearchParams();
1374
+ if (args?.from) q.set('from', String(args.from)); else q.set('days', String(Number(args?.days) || 30));
1375
+ if (args?.to) q.set('to', String(args.to));
1376
+ result = await api(`/api/stats/links?${q}`);
1377
+ break;
1378
+ }
1379
+ case 'convert_link_to_campaign': {
1380
+ const path = `/api/links/${Number(args.link_id)}/campaign`;
1381
+ result = args?.preview ? await api(path) : await api(path, { method: 'POST' });
1382
+ break;
1383
+ }
1384
+ case 'get_link_stats': {
1385
+ const days = args?.days ? `?days=${Number(args.days)}` : '';
1386
+ result = await api(`/api/stats/link/${Number(args.link_id)}${days}`);
1387
+ break;
1388
+ }
1389
+ case 'get_overview_stats': {
1390
+ const days = args?.days ? `?days=${Number(args.days)}` : '';
1391
+ result = await api(`/api/stats/overview${days}`);
1392
+ break;
1393
+ }
1394
+ case 'list_domains': {
1395
+ result = await api('/api/domains');
1396
+ break;
1397
+ }
1398
+ case 'create_domain': {
1399
+ result = await api('/api/domains', {
1400
+ method: 'POST',
1401
+ body: JSON.stringify({ hostname: args.hostname }),
1402
+ });
1403
+ break;
1404
+ }
1405
+ case 'verify_domain': {
1406
+ result = await api(`/api/domains/${Number(args.domain_id)}/verify`, { method: 'POST' });
1407
+ break;
1408
+ }
1409
+ case 'check_domain_dns': {
1410
+ result = await api(`/api/domains/${Number(args.domain_id)}/dns`);
1411
+ break;
1412
+ }
1413
+ case 'connect_domain_cloudflare': {
1414
+ result = await api(`/api/domains/${Number(args.domain_id)}/connect-cloudflare`, {
1415
+ method: 'POST',
1416
+ body: JSON.stringify({ api_token: args.api_token }),
1417
+ });
1418
+ break;
1419
+ }
1420
+ case 'delete_domain': {
1421
+ result = await api(`/api/domains/${Number(args.domain_id)}`, { method: 'DELETE' });
1422
+ break;
1423
+ }
1424
+
1425
+ // ── Tracker: networks ──
1426
+ case 'set_account_timezone': {
1427
+ const tz = args?.timezone === null || args?.timezone === '' ? null : String(args.timezone);
1428
+ await api('/api/me', { method: 'PATCH', body: JSON.stringify({ timezone: tz }) });
1429
+ result = { timezone: tz };
1430
+ break;
1431
+ }
1432
+ case 'set_sale_alerts': {
1433
+ const enabled = args?.enabled === true || args?.enabled === 'true';
1434
+ await api('/api/me', { method: 'PATCH', body: JSON.stringify({ sale_alerts: enabled }) });
1435
+ result = { sale_alerts: enabled };
1436
+ break;
1437
+ }
1438
+ case 'get_universal_postback_url': {
1439
+ const me = await api('/api/me');
1440
+ const base = me.user && me.user.postback_url;
1441
+ result = {
1442
+ postback_url: base,
1443
+ template: base ? `${base}?clickid=REPLACE&payout=OPTIONAL&currency=OPTIONAL&txid=OPTIONAL` : null,
1444
+ note: 'Universal: works for every campaign and every network. payout/currency/txid are optional; a sale sent with no payout books the payout of the offer its click went to, when the offer has one. cid is accepted as an alias for clickid.',
1445
+ };
1446
+ break;
1447
+ }
1448
+ case 'list_affiliate_networks': {
1449
+ result = await api('/api/affiliate-networks');
1450
+ break;
1451
+ }
1452
+ case 'create_affiliate_network': {
1453
+ const body = { name: args.name };
1454
+ if (typeof args.conversion_param === 'string') body.conversion_param = args.conversion_param;
1455
+ if (typeof args.amazon_tag === 'string') body.amazon_tag = args.amazon_tag;
1456
+ result = await api('/api/affiliate-networks', { method: 'POST', body: JSON.stringify(body) });
1457
+ break;
1458
+ }
1459
+ case 'update_affiliate_network': {
1460
+ const body = {};
1461
+ if (typeof args.name === 'string') body.name = args.name;
1462
+ if (typeof args.conversion_param === 'string') body.conversion_param = args.conversion_param;
1463
+ if (typeof args.amazon_tag === 'string') body.amazon_tag = args.amazon_tag;
1464
+ if (typeof args.archived === 'boolean') body.archived = args.archived;
1465
+ result = await api(`/api/affiliate-networks/${Number(args.network_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1466
+ break;
1467
+ }
1468
+ case 'delete_affiliate_network': {
1469
+ result = await api(`/api/affiliate-networks/${Number(args.network_id)}`, { method: 'DELETE' });
1470
+ break;
1471
+ }
1472
+
1473
+ // ── Tracker: offers ──
1474
+ case 'list_offers': {
1475
+ result = await api(`/api/offers${args?.include_archived ? '?include_archived=1' : ''}`);
1476
+ break;
1477
+ }
1478
+ case 'create_offer_link': {
1479
+ result = await api(`/api/offers/${Number(args.offer_id)}/campaign`, { method: 'POST' });
1480
+ break;
1481
+ }
1482
+ case 'create_offer': {
1483
+ const body = { name: args.name, url: args.url };
1484
+ if ('affiliate_network_id' in args) body.affiliate_network_id = args.affiliate_network_id;
1485
+ if ('payout' in args) body.payout = args.payout;
1486
+ if (typeof args.payout_currency === 'string') body.payout_currency = args.payout_currency;
1487
+ if (typeof args.country === 'string') body.country = args.country;
1488
+ result = await api('/api/offers', { method: 'POST', body: JSON.stringify(body) });
1489
+ break;
1490
+ }
1491
+ case 'update_offer': {
1492
+ const body = {};
1493
+ if (typeof args.name === 'string') body.name = args.name;
1494
+ if (typeof args.url === 'string') body.url = args.url;
1495
+ if ('affiliate_network_id' in args) body.affiliate_network_id = args.affiliate_network_id;
1496
+ if ('payout' in args) body.payout = args.payout;
1497
+ if (typeof args.payout_currency === 'string') body.payout_currency = args.payout_currency;
1498
+ if (typeof args.country === 'string') body.country = args.country;
1499
+ if (typeof args.archived === 'boolean') body.archived = args.archived;
1500
+ result = await api(`/api/offers/${Number(args.offer_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1501
+ break;
1502
+ }
1503
+ case 'archive_offer':
1504
+ case 'delete_offer': { // pre-0.39 name; DELETE archives
1505
+ result = await api(`/api/offers/${Number(args.offer_id)}`, { method: 'DELETE' });
1506
+ break;
1507
+ }
1508
+
1509
+ // ── Tracker: landers ──
1510
+ case 'list_landers': {
1511
+ result = await api('/api/landers');
1512
+ break;
1513
+ }
1514
+ case 'create_lander': {
1515
+ const body = { name: args.name, url: args.url };
1516
+ if (typeof args.country === 'string') body.country = args.country;
1517
+ result = await api('/api/landers', { method: 'POST', body: JSON.stringify(body) });
1518
+ break;
1519
+ }
1520
+ case 'update_lander': {
1521
+ const body = {};
1522
+ if (typeof args.name === 'string') body.name = args.name;
1523
+ if (typeof args.url === 'string') body.url = args.url;
1524
+ if (typeof args.country === 'string') body.country = args.country;
1525
+ if (typeof args.archived === 'boolean') body.archived = args.archived;
1526
+ result = await api(`/api/landers/${Number(args.lander_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1527
+ break;
1528
+ }
1529
+ case 'delete_lander': {
1530
+ result = await api(`/api/landers/${Number(args.lander_id)}`, { method: 'DELETE' });
1531
+ break;
1532
+ }
1533
+
1534
+ // ── Custom postback events ──
1535
+ case 'list_custom_events': {
1536
+ result = await api('/api/custom-events');
1537
+ break;
1538
+ }
1539
+ case 'create_custom_event': {
1540
+ const body = { label: args.label };
1541
+ if (typeof args.slug === 'string') body.slug = args.slug;
1542
+ if (typeof args.counts_revenue === 'boolean') body.counts_revenue = args.counts_revenue;
1543
+ result = await api('/api/custom-events', { method: 'POST', body: JSON.stringify(body) });
1544
+ break;
1545
+ }
1546
+ case 'update_custom_event': {
1547
+ const body = {};
1548
+ if (typeof args.label === 'string') body.label = args.label;
1549
+ if (typeof args.counts_revenue === 'boolean') body.counts_revenue = args.counts_revenue;
1550
+ result = await api(`/api/custom-events/${Number(args.custom_event_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1551
+ break;
1552
+ }
1553
+ case 'delete_custom_event': {
1554
+ result = await api(`/api/custom-events/${Number(args.custom_event_id)}`, { method: 'DELETE' });
1555
+ break;
1556
+ }
1557
+
1558
+ // ── Report views ──
1559
+ case 'list_split_tests': {
1560
+ result = await api(`/api/split-tests${args?.include_archived ? '?include_archived=1' : ''}`);
1561
+ break;
1562
+ }
1563
+ case 'get_split_test': {
1564
+ result = await api(`/api/split-tests/${encodeURIComponent(args.split_test_id)}`);
1565
+ break;
1566
+ }
1567
+ case 'scan_page_for_split_test': {
1568
+ result = await api('/api/split-tests/scan', { method: 'POST', body: JSON.stringify({ url: args.url, device: args.device, browse: args.browse === true }) });
1569
+ break;
1570
+ }
1571
+ case 'click_split_test_scan': {
1572
+ result = await api('/api/split-tests/scan/click', { method: 'POST', body: JSON.stringify(args) });
1573
+ break;
1574
+ }
1575
+ case 'close_split_test_scan': {
1576
+ result = await api('/api/split-tests/scan/close', { method: 'POST', body: JSON.stringify({ session: args.session }) });
1577
+ break;
1578
+ }
1579
+ case 'create_split_test': {
1580
+ result = await api('/api/split-tests', { method: 'POST', body: JSON.stringify(args) });
1581
+ break;
1582
+ }
1583
+ case 'update_split_test': {
1584
+ const { split_test_id, ...body } = args;
1585
+ result = await api(`/api/split-tests/${encodeURIComponent(split_test_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1586
+ break;
1587
+ }
1588
+ case 'archive_split_test': {
1589
+ result = await api(`/api/split-tests/${encodeURIComponent(args.split_test_id)}`, { method: 'DELETE' });
1590
+ break;
1591
+ }
1592
+ case 'write_split_test_copy': {
1593
+ result = await api('/api/split-tests/generate', { method: 'POST', body: JSON.stringify(args) });
1594
+ break;
1595
+ }
1596
+ case 'upload_split_test_image': {
1597
+ const TYPES = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', gif: 'image/gif' };
1598
+ let bytes, type;
1599
+ if (args.file_path) {
1600
+ // Only the local package can read the user's disk.
1601
+ if (!readLocalFile) throw new Error('file_path only works with the local package (npx @offerswap/mcp). Pass image_url instead.');
1602
+ bytes = await readLocalFile(args.file_path);
1603
+ type = TYPES[String(args.file_path).split('.').pop().toLowerCase()];
1604
+ } else if (args.image_url) {
1605
+ const r = await fetch(args.image_url);
1606
+ if (!r.ok) throw new Error(`could not download ${args.image_url}: ${r.status}`);
1607
+ bytes = new Uint8Array(await r.arrayBuffer());
1608
+ type = (r.headers.get('content-type') || '').split(';')[0];
1609
+ } else {
1610
+ throw new Error('Pass file_path or image_url.');
1611
+ }
1612
+ if (!Object.values(TYPES).includes(type)) throw new Error('Use a JPG, PNG, WebP or GIF image.');
1613
+ result = await api('/api/split-tests/images', { method: 'POST', body: bytes, headers: { 'Content-Type': type } });
1614
+ break;
1615
+ }
1616
+ case 'list_report_views': {
1617
+ result = await api('/api/report-views');
1618
+ break;
1619
+ }
1620
+ case 'create_report_view': {
1621
+ const body = { name: args.name, columns: args.columns };
1622
+ if (typeof args.activate === 'boolean') body.activate = args.activate;
1623
+ result = await api('/api/report-views', { method: 'POST', body: JSON.stringify(body) });
1624
+ break;
1625
+ }
1626
+ case 'update_report_view': {
1627
+ const body = {};
1628
+ if (typeof args.name === 'string') body.name = args.name;
1629
+ if (Array.isArray(args.columns)) body.columns = args.columns;
1630
+ result = await api(`/api/report-views/${Number(args.report_view_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1631
+ break;
1632
+ }
1633
+ case 'delete_report_view': {
1634
+ result = await api(`/api/report-views/${Number(args.report_view_id)}`, { method: 'DELETE' });
1635
+ break;
1636
+ }
1637
+ case 'set_active_report_view': {
1638
+ result = await api('/api/report-views/active', { method: 'PUT', body: JSON.stringify({ view: String(args.view) }) });
1639
+ break;
1640
+ }
1641
+
1642
+ // ── Traffic sources ──
1643
+ case 'list_traffic_sources': {
1644
+ result = await api(`/api/traffic-sources${args?.include_archived ? '?include_archived=1' : ''}`);
1645
+ break;
1646
+ }
1647
+ case 'create_traffic_source': {
1648
+ const body = { name: args.name };
1649
+ if ('platform' in args) body.platform = args.platform;
1650
+ if (Array.isArray(args.token_params)) body.token_params = args.token_params;
1651
+ result = await api('/api/traffic-sources', { method: 'POST', body: JSON.stringify(body) });
1652
+ break;
1653
+ }
1654
+ case 'update_traffic_source': {
1655
+ const body = {};
1656
+ if (typeof args.name === 'string') body.name = args.name;
1657
+ if ('platform' in args) body.platform = args.platform;
1658
+ if (Array.isArray(args.token_params)) body.token_params = args.token_params;
1659
+ if (typeof args.archived === 'boolean') body.archived = args.archived;
1660
+ result = await api(`/api/traffic-sources/${Number(args.traffic_source_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1661
+ break;
1662
+ }
1663
+ case 'delete_traffic_source': {
1664
+ result = await api(`/api/traffic-sources/${Number(args.traffic_source_id)}`, { method: 'DELETE' });
1665
+ break;
1666
+ }
1667
+
1668
+ // ── Tracking pixels ──
1669
+ case 'list_tracking_pixels': {
1670
+ result = await api('/api/tracking-pixels');
1671
+ break;
1672
+ }
1673
+ case 'create_tracking_pixel': {
1674
+ const body = { platform: args.platform, pixel_id: args.pixel_id };
1675
+ if (typeof args.label === 'string') body.label = args.label;
1676
+ if (typeof args.default_event === 'string') body.default_event = args.default_event;
1677
+ if (typeof args.capi_token === 'string') body.capi_token = args.capi_token;
1678
+ if (typeof args.test_event_code === 'string') body.test_event_code = args.test_event_code;
1679
+ if (typeof args.active === 'boolean') body.active = args.active;
1680
+ result = await api('/api/tracking-pixels', { method: 'POST', body: JSON.stringify(body) });
1681
+ break;
1682
+ }
1683
+ case 'update_tracking_pixel': {
1684
+ const body = {};
1685
+ if (typeof args.pixel_id === 'string') body.pixel_id = args.pixel_id;
1686
+ if (typeof args.label === 'string') body.label = args.label;
1687
+ if (typeof args.default_event === 'string') body.default_event = args.default_event;
1688
+ if ('capi_token' in args) body.capi_token = args.capi_token;
1689
+ if ('test_event_code' in args) body.test_event_code = args.test_event_code;
1690
+ if (typeof args.active === 'boolean') body.active = args.active;
1691
+ result = await api(`/api/tracking-pixels/${Number(args.pixel_id_row)}`, { method: 'PATCH', body: JSON.stringify(body) });
1692
+ break;
1693
+ }
1694
+ case 'test_tracking_pixel': {
1695
+ const body = typeof args.event === 'string' ? { event: args.event } : {};
1696
+ result = await api(`/api/tracking-pixels/${Number(args.pixel_id_row)}/test`, { method: 'POST', body: JSON.stringify(body) });
1697
+ break;
1698
+ }
1699
+ case 'delete_tracking_pixel': {
1700
+ result = await api(`/api/tracking-pixels/${Number(args.pixel_id_row)}`, { method: 'DELETE' });
1701
+ break;
1702
+ }
1703
+
1704
+ // ── Tracker: campaigns ──
1705
+ case 'list_campaigns': {
1706
+ result = await api(`/api/campaigns${args?.include_archived ? '?include_archived=1' : ''}`);
1707
+ break;
1708
+ }
1709
+ case 'create_campaign': {
1710
+ const body = { name: args.name };
1711
+ for (const k of ['traffic_source', 'traffic_source_label', 'country', 'cost_model', 'transition_mode', 'conversion_event']) {
1712
+ if (typeof args[k] === 'string') body[k] = args[k];
1713
+ }
1714
+ if (typeof args.cost_value === 'number') body.cost_value = args.cost_value;
1715
+ if ('domain_id' in args) body.domain_id = args.domain_id;
1716
+ if ('traffic_source_id' in args) body.traffic_source_id = args.traffic_source_id;
1717
+ if ('conversion_pixel_id' in args) body.conversion_pixel_id = args.conversion_pixel_id;
1718
+ if ('pixel_events' in args) body.pixel_events = args.pixel_events;
1719
+ if (typeof args.report_value_mode === 'string') body.report_value_mode = args.report_value_mode;
1720
+ if ('report_value_fixed' in args) body.report_value_fixed = args.report_value_fixed;
1721
+ if ('report_value_adjust_pct' in args) body.report_value_adjust_pct = args.report_value_adjust_pct;
1722
+ if ('report_value_adjust_flat' in args) body.report_value_adjust_flat = args.report_value_adjust_flat;
1723
+ if ('direct_slug' in args) body.direct_slug = args.direct_slug;
1724
+ if (Array.isArray(args.direct_slugs)) body.direct_slugs = args.direct_slugs;
1725
+ if ('fallback_url' in args) body.fallback_url = args.fallback_url;
1726
+ if ('open_in_browser' in args) body.open_in_browser = args.open_in_browser;
1727
+ if (Array.isArray(args.offer_ids)) body.offer_ids = args.offer_ids;
1728
+ if (Array.isArray(args.offer_weights)) body.offer_weights = args.offer_weights;
1729
+ if (Array.isArray(args.lander_ids)) body.lander_ids = args.lander_ids;
1730
+ if (Array.isArray(args.lander_weights)) body.lander_weights = args.lander_weights;
1731
+ result = await api('/api/campaigns', { method: 'POST', body: JSON.stringify(body) });
1732
+ break;
1733
+ }
1734
+ case 'get_campaign': {
1735
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}`);
1736
+ break;
1737
+ }
1738
+ case 'update_campaign': {
1739
+ const body = {};
1740
+ for (const k of ['name', 'traffic_source_label', 'country', 'cost_model', 'transition_mode', 'conversion_event']) {
1741
+ if (typeof args[k] === 'string') body[k] = args[k];
1742
+ }
1743
+ if ('traffic_source' in args) body.traffic_source = args.traffic_source;
1744
+ if ('traffic_source_id' in args) body.traffic_source_id = args.traffic_source_id;
1745
+ if (typeof args.cost_value === 'number') body.cost_value = args.cost_value;
1746
+ if ('domain_id' in args) body.domain_id = args.domain_id;
1747
+ if ('conversion_pixel_id' in args) body.conversion_pixel_id = args.conversion_pixel_id;
1748
+ if ('pixel_events' in args) body.pixel_events = args.pixel_events;
1749
+ if (typeof args.report_value_mode === 'string') body.report_value_mode = args.report_value_mode;
1750
+ if ('report_value_fixed' in args) body.report_value_fixed = args.report_value_fixed;
1751
+ if ('report_value_adjust_pct' in args) body.report_value_adjust_pct = args.report_value_adjust_pct;
1752
+ if ('report_value_adjust_flat' in args) body.report_value_adjust_flat = args.report_value_adjust_flat;
1753
+ if ('direct_slug' in args) body.direct_slug = args.direct_slug;
1754
+ if (Array.isArray(args.direct_slugs)) body.direct_slugs = args.direct_slugs;
1755
+ if ('fallback_url' in args) body.fallback_url = args.fallback_url;
1756
+ if ('open_in_browser' in args) body.open_in_browser = args.open_in_browser;
1757
+ if ('dim_labels' in args) body.dim_labels = args.dim_labels;
1758
+ if (typeof args.archived === 'boolean') body.archived = args.archived;
1759
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1760
+ break;
1761
+ }
1762
+ case 'archive_campaign':
1763
+ case 'delete_campaign': { // pre-0.39 name; DELETE archives
1764
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}`, { method: 'DELETE' });
1765
+ break;
1766
+ }
1767
+ case 'duplicate_campaign': {
1768
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}/duplicate`, { method: 'POST' });
1769
+ break;
1770
+ }
1771
+ case 'set_campaign_offers': {
1772
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}/offers`, {
1773
+ method: 'PUT', body: JSON.stringify({ items: args.items }),
1774
+ });
1775
+ break;
1776
+ }
1777
+ case 'set_campaign_landers': {
1778
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}/landers`, {
1779
+ method: 'PUT', body: JSON.stringify({ items: args.items }),
1780
+ });
1781
+ break;
1782
+ }
1783
+ case 'get_campaign_flow': {
1784
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}/flow`);
1785
+ break;
1786
+ }
1787
+ case 'set_campaign_flow': {
1788
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}/flow`, {
1789
+ method: 'PUT', body: JSON.stringify({ nodes: args.nodes, edges: args.edges }),
1790
+ });
1791
+ break;
1792
+ }
1793
+ case 'get_campaign_stats': {
1794
+ const qs = new URLSearchParams();
1795
+ if (args?.from) qs.set('from', String(args.from));
1796
+ if (args?.to) qs.set('to', String(args.to));
1797
+ if (args?.days && !args?.from) qs.set('days', String(Number(args.days)));
1798
+ if (args?.tz) qs.set('tz', String(args.tz));
1799
+ for (const dim of ['utm_campaign', 'utm_medium', 'utm_source', 'utm_content', 'utm_term', 'lander', 'offer', 'country', 'device', 'day']) {
1800
+ if (args?.[dim]) qs.set(dim, String(args[dim]));
1801
+ }
1802
+ for (const [dim, v] of Object.entries(args?.filters || {})) {
1803
+ if (v) qs.set(dim, String(v));
1804
+ }
1805
+ if (Array.isArray(args?.group) && args.group.length) qs.set('group', args.group.join(','));
1806
+ if (args?.breakdowns === false) qs.set('breakdowns', '0');
1807
+ const q = qs.toString();
1808
+ result = await api(`/api/campaigns/${Number(args.campaign_id)}/stats${q ? `?${q}` : ''}`);
1809
+ break;
1810
+ }
1811
+
1812
+ case 'list_properties': {
1813
+ result = await api(`/api/properties${args?.include_archived ? '?include_archived=1' : ''}`);
1814
+ break;
1815
+ }
1816
+ case 'create_property': {
1817
+ const body = { name: args.name };
1818
+ if (typeof args.site_url === 'string') body.site_url = args.site_url;
1819
+ if (typeof args.domain_id === 'number') body.domain_id = args.domain_id;
1820
+ result = await api('/api/properties', { method: 'POST', body: JSON.stringify(body) });
1821
+ break;
1822
+ }
1823
+ case 'get_property': {
1824
+ result = await api(`/api/properties/${Number(args.property_id)}`);
1825
+ break;
1826
+ }
1827
+ case 'update_property': {
1828
+ const body = {};
1829
+ if (typeof args.name === 'string') body.name = args.name;
1830
+ if ('site_url' in args) body.site_url = args.site_url;
1831
+ if (typeof args.domain_id === 'number') body.domain_id = args.domain_id;
1832
+ if (typeof args.archived === 'boolean') body.archived = args.archived;
1833
+ result = await api(`/api/properties/${Number(args.property_id)}`, { method: 'PATCH', body: JSON.stringify(body) });
1834
+ break;
1835
+ }
1836
+ case 'archive_property':
1837
+ case 'delete_property': { // pre-0.39 name; DELETE archives
1838
+ result = await api(`/api/properties/${Number(args.property_id)}`, { method: 'DELETE' });
1839
+ break;
1840
+ }
1841
+ case 'set_property_campaigns': {
1842
+ result = await api(`/api/properties/${Number(args.property_id)}/campaigns`, {
1843
+ method: 'PUT', body: JSON.stringify({ items: args.items }),
1844
+ });
1845
+ break;
1846
+ }
1847
+ case 'get_property_stats': {
1848
+ const qs = new URLSearchParams();
1849
+ if (args?.days) qs.set('days', String(Number(args.days)));
1850
+ if (args?.tz) qs.set('tz', String(args.tz));
1851
+ const q = qs.toString();
1852
+ result = await api(`/api/properties/${Number(args.property_id)}/stats${q ? `?${q}` : ''}`);
1853
+ break;
1854
+ }
1855
+ case 'list_property_pages': {
1856
+ result = await api('/api/property-pages');
1857
+ break;
1858
+ }
1859
+ case 'list_observed_campaign_tags': {
1860
+ result = await api('/api/observed-campaign-tags');
1861
+ break;
1862
+ }
1863
+
1864
+ case 'get_tracker_overview': {
1865
+ const a = { ...(args || {}) };
1866
+ if (a.from) delete a.days;
1867
+ result = await api(`/api/tracker/overview${qsFrom(a, ['days', 'from', 'to', 'tz', 'offer_id', 'property_id'])}`);
1868
+ break;
1869
+ }
1870
+ case 'get_realtime': {
1871
+ result = await api(`/api/tracker/realtime${qsFrom(args || {}, ['tz'])}`);
1872
+ break;
1873
+ }
1874
+ case 'get_tracker_events': {
1875
+ const a = { ...(args || {}) };
1876
+ if (a.from) delete a.days;
1877
+ result = await api(`/api/tracker/events${qsFrom(a, ['days', 'from', 'to', 'q', 'stream', 'event', 'campaign_id', 'offer_id', 'property_id', 'link_id', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'sort', 'dir', 'limit', 'offset'])}`);
1878
+ break;
1879
+ }
1880
+
1881
+ default:
1882
+ throw new Error(`unknown tool: ${name}`);
1883
+ }
1884
+ return result;
1885
+ }