@trimstats/mcp 0.0.0-stage → 0.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/dist/tools.js ADDED
@@ -0,0 +1,825 @@
1
+ const READ_ONLY_ANNOTATIONS = {
2
+ readOnlyHint: true,
3
+ destructiveHint: false,
4
+ idempotentHint: true,
5
+ openWorldHint: false,
6
+ };
7
+ const UUID_PATTERN = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$';
8
+ const ISO_DATE_PATTERN = '^\\d{4}-\\d{2}-\\d{2}$';
9
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
11
+ const DEVICES = new Set(['desktop', 'mobile', 'tablet']);
12
+ const ATTRIBUTIONS = new Set(['first_touch', 'last_touch']);
13
+ const CRAWLER_CATEGORIES = new Set(['ai_answers', 'indexing', 'training']);
14
+ const FUNNEL_STEP_TYPES = new Set(['pageview', 'event']);
15
+ const SITE_ID_PROP = {
16
+ type: 'string',
17
+ pattern: UUID_PATTERN,
18
+ description: 'TrimStats site UUID (obtain from list_sites).',
19
+ };
20
+ const SEGMENT_FILTER_PROPS = {
21
+ from: {
22
+ type: 'string',
23
+ pattern: ISO_DATE_PATTERN,
24
+ description: 'Inclusive UTC start date in YYYY-MM-DD format.',
25
+ },
26
+ to: {
27
+ type: 'string',
28
+ pattern: ISO_DATE_PATTERN,
29
+ description: 'Inclusive UTC end date in YYYY-MM-DD format.',
30
+ },
31
+ country: {
32
+ type: 'string',
33
+ minLength: 2,
34
+ maxLength: 2,
35
+ description: 'Two-letter ISO 3166-1 alpha-2 country code (e.g. US, DE, GB).',
36
+ },
37
+ device: {
38
+ type: 'string',
39
+ enum: ['desktop', 'mobile', 'tablet'],
40
+ description: 'Filter by visitor device category.',
41
+ },
42
+ browser: {
43
+ type: 'string',
44
+ maxLength: 64,
45
+ description: 'Exact browser name (e.g. Chrome, Safari, Firefox).',
46
+ },
47
+ os: {
48
+ type: 'string',
49
+ maxLength: 64,
50
+ description: 'Exact operating system name (e.g. macOS, Windows, iOS, Android).',
51
+ },
52
+ pathname: {
53
+ type: 'string',
54
+ maxLength: 512,
55
+ description: 'Exact page pathname starting with / (e.g. /pricing).',
56
+ },
57
+ referrer: {
58
+ type: 'string',
59
+ maxLength: 256,
60
+ description: 'Referrer hostname (e.g. google.com), or empty string "" for direct traffic.',
61
+ },
62
+ utmSource: {
63
+ type: 'string',
64
+ maxLength: 128,
65
+ description: 'Filter by utm_source parameter.',
66
+ },
67
+ utmMedium: {
68
+ type: 'string',
69
+ maxLength: 128,
70
+ description: 'Filter by utm_medium parameter.',
71
+ },
72
+ utmCampaign: {
73
+ type: 'string',
74
+ maxLength: 128,
75
+ description: 'Filter by utm_campaign parameter.',
76
+ },
77
+ utmTerm: {
78
+ type: 'string',
79
+ maxLength: 128,
80
+ description: 'Filter by utm_term parameter.',
81
+ },
82
+ utmContent: {
83
+ type: 'string',
84
+ maxLength: 128,
85
+ description: 'Filter by utm_content parameter.',
86
+ },
87
+ };
88
+ export const TRIMSTATS_MCP_TOOLS = [
89
+ {
90
+ name: 'list_sites',
91
+ description: 'List websites accessible to the authenticated TrimStats API key. Call this first whenever you need a siteId UUID before calling any site-scoped analytics tool.',
92
+ inputSchema: {
93
+ type: 'object',
94
+ properties: {},
95
+ additionalProperties: false,
96
+ },
97
+ annotations: READ_ONLY_ANNOTATIONS,
98
+ },
99
+ {
100
+ name: 'get_site_overview',
101
+ description: 'Get site traffic KPIs (visitors, pageviews, sessions, bounce rate, average active visit duration in ms, views/session), prior-period comparison, daily timeseries, top pages/entry/exit pages, referrers, UTM breakdowns, countries, devices, browsers, OS, custom events, and goal conversions. Defaults to the last 7 UTC days. Do not use if you only need the current live visitor count (use get_live_visitors).',
102
+ inputSchema: {
103
+ type: 'object',
104
+ properties: {
105
+ siteId: SITE_ID_PROP,
106
+ ...SEGMENT_FILTER_PROPS,
107
+ compare: {
108
+ type: 'boolean',
109
+ default: true,
110
+ description: 'Include previous equal-length period totals and timeseries.',
111
+ },
112
+ },
113
+ required: ['siteId'],
114
+ additionalProperties: false,
115
+ },
116
+ annotations: READ_ONLY_ANNOTATIONS,
117
+ },
118
+ {
119
+ name: 'get_live_visitors',
120
+ description: 'Get the real-time count of unique visitors active on a site during the last 5 minutes. Use for current active traffic checks instead of get_site_overview.',
121
+ inputSchema: {
122
+ type: 'object',
123
+ properties: {
124
+ siteId: SITE_ID_PROP,
125
+ },
126
+ required: ['siteId'],
127
+ additionalProperties: false,
128
+ },
129
+ annotations: READ_ONLY_ANNOTATIONS,
130
+ },
131
+ {
132
+ name: 'get_event_properties',
133
+ description: 'Break down a custom event by its attached JSON property keys and top property values (for example plan, billing_interval, or cta). Use after seeing a custom event name in get_site_overview.',
134
+ inputSchema: {
135
+ type: 'object',
136
+ properties: {
137
+ siteId: SITE_ID_PROP,
138
+ eventName: {
139
+ type: 'string',
140
+ minLength: 1,
141
+ maxLength: 120,
142
+ description: 'Exact custom event name to inspect (e.g. signup_click).',
143
+ },
144
+ ...SEGMENT_FILTER_PROPS,
145
+ },
146
+ required: ['siteId', 'eventName'],
147
+ additionalProperties: false,
148
+ },
149
+ annotations: READ_ONLY_ANNOTATIONS,
150
+ },
151
+ {
152
+ name: 'get_revenue_report',
153
+ description: 'Get attributed revenue totals (all currency amounts in USD cents), order count, paying customers, average order value, revenue per visitor, conversion rate, daily revenue series, and breakdowns by referrer, UTM parameters, landing page, and country. Defaults to the last 30 UTC days.',
154
+ inputSchema: {
155
+ type: 'object',
156
+ properties: {
157
+ siteId: SITE_ID_PROP,
158
+ from: SEGMENT_FILTER_PROPS.from,
159
+ to: SEGMENT_FILTER_PROPS.to,
160
+ attribution: {
161
+ type: 'string',
162
+ enum: ['first_touch', 'last_touch'],
163
+ default: 'first_touch',
164
+ description: 'Attribution model: first_touch (initial landing) or last_touch (most recent visit).',
165
+ },
166
+ },
167
+ required: ['siteId'],
168
+ additionalProperties: false,
169
+ },
170
+ annotations: READ_ONLY_ANNOTATIONS,
171
+ },
172
+ {
173
+ name: 'get_anomaly_insights',
174
+ description: 'Get automated rolling 7-day anomaly insights (traffic_drop, traffic_spike, conversion_dip, friction_spike) comparing the last 7 completed UTC days against the prior 7 days. Set includeDetails=true to include 14-day daily trends, top contributing drivers, and 30-day history.',
175
+ inputSchema: {
176
+ type: 'object',
177
+ properties: {
178
+ siteId: SITE_ID_PROP,
179
+ includeDetails: {
180
+ type: 'boolean',
181
+ default: false,
182
+ description: 'Include 14-day daily trend arrays, contributing drivers, and 30-day anomaly history.',
183
+ },
184
+ },
185
+ required: ['siteId'],
186
+ additionalProperties: false,
187
+ },
188
+ annotations: READ_ONLY_ANNOTATIONS,
189
+ },
190
+ {
191
+ name: 'get_ui_friction',
192
+ description: 'Get UI click friction analytics for a site: rage clicks, dead clicks, affected visitors, 90% scroll reach rate, top friction pages, and top CSS element selectors causing friction. Defaults to the last 30 UTC days.',
193
+ inputSchema: {
194
+ type: 'object',
195
+ properties: {
196
+ siteId: SITE_ID_PROP,
197
+ from: SEGMENT_FILTER_PROPS.from,
198
+ to: SEGMENT_FILTER_PROPS.to,
199
+ },
200
+ required: ['siteId'],
201
+ additionalProperties: false,
202
+ },
203
+ annotations: READ_ONLY_ANNOTATIONS,
204
+ },
205
+ {
206
+ name: 'list_funnels',
207
+ description: 'List saved multi-step conversion funnels configured for a site, returning each funnel ID, name, and ordered step definitions. Call this before evaluate_funnel when querying a saved funnel.',
208
+ inputSchema: {
209
+ type: 'object',
210
+ properties: {
211
+ siteId: SITE_ID_PROP,
212
+ },
213
+ required: ['siteId'],
214
+ additionalProperties: false,
215
+ },
216
+ annotations: READ_ONLY_ANNOTATIONS,
217
+ },
218
+ {
219
+ name: 'evaluate_funnel',
220
+ description: 'Evaluate ordered multi-step conversion and drop-off rates using ClickHouse windowFunnel(). Provide EITHER funnelId (from list_funnels) OR an ad-hoc steps array (2 to 8 steps), not both. Defaults to the last 30 UTC days (max 90-day span) and an 86400-second (24h) conversion window.',
221
+ inputSchema: {
222
+ type: 'object',
223
+ properties: {
224
+ siteId: SITE_ID_PROP,
225
+ funnelId: {
226
+ type: 'string',
227
+ pattern: UUID_PATTERN,
228
+ description: 'Saved funnel UUID from list_funnels. Mutually exclusive with steps.',
229
+ },
230
+ steps: {
231
+ type: 'array',
232
+ minItems: 2,
233
+ maxItems: 8,
234
+ description: 'Ad-hoc ordered funnel steps (2 to 8). Mutually exclusive with funnelId.',
235
+ items: {
236
+ type: 'object',
237
+ properties: {
238
+ label: {
239
+ type: 'string',
240
+ minLength: 1,
241
+ maxLength: 80,
242
+ description: 'Human-readable step label.',
243
+ },
244
+ type: {
245
+ type: 'string',
246
+ enum: ['pageview', 'event'],
247
+ description: 'Whether this step matches a pageview pathname or custom event name.',
248
+ },
249
+ matchRule: {
250
+ type: 'string',
251
+ minLength: 1,
252
+ maxLength: 256,
253
+ description: 'Exact pathname (or trailing * prefix for pageview) or custom event name.',
254
+ },
255
+ },
256
+ required: ['label', 'type', 'matchRule'],
257
+ additionalProperties: false,
258
+ },
259
+ },
260
+ from: SEGMENT_FILTER_PROPS.from,
261
+ to: SEGMENT_FILTER_PROPS.to,
262
+ windowSeconds: {
263
+ type: 'integer',
264
+ minimum: 60,
265
+ maximum: 2_592_000,
266
+ default: 86_400,
267
+ description: 'Maximum conversion window in seconds from Step 1 to final step (60 to 2592000).',
268
+ },
269
+ },
270
+ required: ['siteId'],
271
+ additionalProperties: false,
272
+ },
273
+ annotations: READ_ONLY_ANNOTATIONS,
274
+ },
275
+ {
276
+ name: 'get_retention_cohorts',
277
+ description: 'Get weekly visitor retention cohorts (Week 0 through Week +N) for persistent visitors in first-party or identified mode, along with persistent vs cookie-less visitor counts.',
278
+ inputSchema: {
279
+ type: 'object',
280
+ properties: {
281
+ siteId: SITE_ID_PROP,
282
+ weeks: {
283
+ type: 'integer',
284
+ minimum: 2,
285
+ maximum: 12,
286
+ default: 8,
287
+ description: 'Number of cohort weeks to include (2 to 12, default 8).',
288
+ },
289
+ },
290
+ required: ['siteId'],
291
+ additionalProperties: false,
292
+ },
293
+ annotations: READ_ONLY_ANNOTATIONS,
294
+ },
295
+ {
296
+ name: 'get_ai_crawlers',
297
+ description: 'Get AI bot and crawler fetch analytics (ChatGPT-User, ClaudeBot, PerplexityBot, GPTBot, etc.) grouped by category (ai_answers, indexing, training), top crawlers, top crawled pages, and daily series. Defaults to the last 30 UTC days.',
298
+ inputSchema: {
299
+ type: 'object',
300
+ properties: {
301
+ siteId: SITE_ID_PROP,
302
+ from: SEGMENT_FILTER_PROPS.from,
303
+ to: SEGMENT_FILTER_PROPS.to,
304
+ category: {
305
+ type: 'string',
306
+ enum: ['ai_answers', 'indexing', 'training'],
307
+ default: 'ai_answers',
308
+ description: 'Crawler intent category: ai_answers (live user prompts), indexing (search/citation), or training.',
309
+ },
310
+ crawler: {
311
+ type: 'string',
312
+ maxLength: 64,
313
+ description: 'Optional crawler family ID filter (e.g. chatgpt, claude, perplexity).',
314
+ },
315
+ pathname: SEGMENT_FILTER_PROPS.pathname,
316
+ },
317
+ required: ['siteId'],
318
+ additionalProperties: false,
319
+ },
320
+ annotations: READ_ONLY_ANNOTATIONS,
321
+ },
322
+ {
323
+ name: 'get_ai_referrals',
324
+ description: 'Get human referral traffic, attributed revenue (USD cents), goal conversions, and #:~:text= cited passages arriving from AI assistants (ChatGPT, Perplexity, Claude, Gemini, etc.). Defaults to the last 30 UTC days.',
325
+ inputSchema: {
326
+ type: 'object',
327
+ properties: {
328
+ siteId: SITE_ID_PROP,
329
+ from: SEGMENT_FILTER_PROPS.from,
330
+ to: SEGMENT_FILTER_PROPS.to,
331
+ provider: {
332
+ type: 'string',
333
+ maxLength: 64,
334
+ description: 'Optional AI provider filter (e.g. chatgpt, perplexity, claude, gemini).',
335
+ },
336
+ pathname: SEGMENT_FILTER_PROPS.pathname,
337
+ },
338
+ required: ['siteId'],
339
+ additionalProperties: false,
340
+ },
341
+ annotations: READ_ONLY_ANNOTATIONS,
342
+ },
343
+ ];
344
+ function isPlainObject(val) {
345
+ return typeof val === 'object' && val !== null && !Array.isArray(val);
346
+ }
347
+ function assertAllowedKeys(obj, allowed) {
348
+ for (const key of Object.keys(obj)) {
349
+ if (!allowed.has(key)) {
350
+ return `Unknown argument: "${key}".`;
351
+ }
352
+ }
353
+ return null;
354
+ }
355
+ function parseIsoDateMs(dateStr) {
356
+ if (!ISO_DATE_RE.test(dateStr))
357
+ return null;
358
+ const [yStr, mStr, dStr] = dateStr.split('-');
359
+ const y = Number(yStr);
360
+ const m = Number(mStr);
361
+ const d = Number(dStr);
362
+ if (y < 2020 || y > 2100 || m < 1 || m > 12 || d < 1 || d > 31)
363
+ return null;
364
+ const ms = Date.UTC(y, m - 1, d);
365
+ const check = new Date(ms);
366
+ if (check.getUTCFullYear() !== y ||
367
+ check.getUTCMonth() !== m - 1 ||
368
+ check.getUTCDate() !== d) {
369
+ return null;
370
+ }
371
+ return ms;
372
+ }
373
+ function validateDateBounds(from, to, maxDays) {
374
+ if (from !== undefined && (typeof from !== 'string' || parseIsoDateMs(from) === null)) {
375
+ return { ok: false, error: '"from" must be a valid YYYY-MM-DD UTC date.' };
376
+ }
377
+ if (to !== undefined && (typeof to !== 'string' || parseIsoDateMs(to) === null)) {
378
+ return { ok: false, error: '"to" must be a valid YYYY-MM-DD UTC date.' };
379
+ }
380
+ if (typeof from === 'string' && typeof to === 'string') {
381
+ const fMs = parseIsoDateMs(from);
382
+ const tMs = parseIsoDateMs(to);
383
+ if (fMs > tMs) {
384
+ return { ok: false, error: '"from" must be on or before "to".' };
385
+ }
386
+ const spanDays = Math.floor((tMs - fMs) / 86_400_000) + 1;
387
+ if (spanDays > maxDays) {
388
+ return { ok: false, error: `Date range cannot exceed ${maxDays} days.` };
389
+ }
390
+ }
391
+ return {
392
+ ok: true,
393
+ ...(typeof from === 'string' ? { from } : {}),
394
+ ...(typeof to === 'string' ? { to } : {}),
395
+ };
396
+ }
397
+ function validateRequiredSiteId(obj) {
398
+ if (typeof obj.siteId !== 'string' || !UUID_RE.test(obj.siteId)) {
399
+ return null;
400
+ }
401
+ return obj.siteId;
402
+ }
403
+ function validateOptionalString(obj, key, maxLen, exactLen) {
404
+ const val = obj[key];
405
+ if (val === undefined)
406
+ return { ok: true };
407
+ if (typeof val !== 'string') {
408
+ return { ok: false, error: `"${key}" must be a string.` };
409
+ }
410
+ if (exactLen !== undefined && val.length !== exactLen) {
411
+ return { ok: false, error: `"${key}" must be exactly ${exactLen} characters.` };
412
+ }
413
+ if (val.length > maxLen) {
414
+ return { ok: false, error: `"${key}" cannot exceed ${maxLen} characters.` };
415
+ }
416
+ return { ok: true, value: val };
417
+ }
418
+ function validateSegmentFilters(obj, maxDays) {
419
+ const dates = validateDateBounds(obj.from, obj.to, maxDays);
420
+ if (!dates.ok)
421
+ return dates;
422
+ const filters = {
423
+ ...(dates.from ? { from: dates.from } : {}),
424
+ ...(dates.to ? { to: dates.to } : {}),
425
+ };
426
+ const country = validateOptionalString(obj, 'country', 2, 2);
427
+ if (!country.ok)
428
+ return country;
429
+ if (country.value !== undefined)
430
+ filters.country = country.value.toUpperCase();
431
+ if (obj.device !== undefined) {
432
+ if (typeof obj.device !== 'string' || !DEVICES.has(obj.device)) {
433
+ return { ok: false, error: '"device" must be one of desktop, mobile, or tablet.' };
434
+ }
435
+ filters.device = obj.device;
436
+ }
437
+ for (const [k, maxLen] of [
438
+ ['browser', 64],
439
+ ['os', 64],
440
+ ['pathname', 512],
441
+ ['referrer', 256],
442
+ ['utmSource', 128],
443
+ ['utmMedium', 128],
444
+ ['utmCampaign', 128],
445
+ ['utmTerm', 128],
446
+ ['utmContent', 128],
447
+ ]) {
448
+ const check = validateOptionalString(obj, k, maxLen);
449
+ if (!check.ok)
450
+ return check;
451
+ if (check.value !== undefined) {
452
+ filters[k] = check.value;
453
+ }
454
+ }
455
+ return { ok: true, filters };
456
+ }
457
+ const OVERVIEW_KEYS = new Set([
458
+ 'siteId',
459
+ 'from',
460
+ 'to',
461
+ 'compare',
462
+ 'country',
463
+ 'device',
464
+ 'browser',
465
+ 'os',
466
+ 'pathname',
467
+ 'referrer',
468
+ 'utmSource',
469
+ 'utmMedium',
470
+ 'utmCampaign',
471
+ 'utmTerm',
472
+ 'utmContent',
473
+ ]);
474
+ const EVENT_PROPS_KEYS = new Set([
475
+ 'siteId',
476
+ 'eventName',
477
+ 'from',
478
+ 'to',
479
+ 'country',
480
+ 'device',
481
+ 'browser',
482
+ 'os',
483
+ 'pathname',
484
+ 'referrer',
485
+ 'utmSource',
486
+ 'utmMedium',
487
+ 'utmCampaign',
488
+ 'utmTerm',
489
+ 'utmContent',
490
+ ]);
491
+ export function validateToolCall(name, rawArgs) {
492
+ if (typeof name !== 'string') {
493
+ return { ok: false, error: 'Tool name must be a string.' };
494
+ }
495
+ const args = rawArgs === undefined ? {} : rawArgs;
496
+ if (!isPlainObject(args)) {
497
+ return { ok: false, error: 'Tool arguments must be a JSON object.' };
498
+ }
499
+ switch (name) {
500
+ case 'list_sites': {
501
+ const unknown = assertAllowedKeys(args, new Set());
502
+ if (unknown)
503
+ return { ok: false, error: unknown };
504
+ return { ok: true, call: { name: 'list_sites', args: {} } };
505
+ }
506
+ case 'get_live_visitors':
507
+ case 'list_funnels': {
508
+ const unknown = assertAllowedKeys(args, new Set(['siteId']));
509
+ if (unknown)
510
+ return { ok: false, error: unknown };
511
+ const siteId = validateRequiredSiteId(args);
512
+ if (!siteId)
513
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
514
+ return { ok: true, call: { name, args: { siteId } } };
515
+ }
516
+ case 'get_site_overview': {
517
+ const unknown = assertAllowedKeys(args, OVERVIEW_KEYS);
518
+ if (unknown)
519
+ return { ok: false, error: unknown };
520
+ const siteId = validateRequiredSiteId(args);
521
+ if (!siteId)
522
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
523
+ if (args.compare !== undefined && typeof args.compare !== 'boolean') {
524
+ return { ok: false, error: '"compare" must be a boolean.' };
525
+ }
526
+ const seg = validateSegmentFilters(args, 366);
527
+ if (!seg.ok)
528
+ return seg;
529
+ return {
530
+ ok: true,
531
+ call: {
532
+ name: 'get_site_overview',
533
+ args: {
534
+ siteId,
535
+ ...seg.filters,
536
+ ...(typeof args.compare === 'boolean' ? { compare: args.compare } : {}),
537
+ },
538
+ },
539
+ };
540
+ }
541
+ case 'get_event_properties': {
542
+ const unknown = assertAllowedKeys(args, EVENT_PROPS_KEYS);
543
+ if (unknown)
544
+ return { ok: false, error: unknown };
545
+ const siteId = validateRequiredSiteId(args);
546
+ if (!siteId)
547
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
548
+ if (typeof args.eventName !== 'string' ||
549
+ args.eventName.trim().length === 0 ||
550
+ args.eventName.length > 120) {
551
+ return { ok: false, error: '"eventName" is required (1 to 120 characters).' };
552
+ }
553
+ const seg = validateSegmentFilters(args, 366);
554
+ if (!seg.ok)
555
+ return seg;
556
+ return {
557
+ ok: true,
558
+ call: {
559
+ name: 'get_event_properties',
560
+ args: {
561
+ siteId,
562
+ eventName: args.eventName.trim(),
563
+ ...seg.filters,
564
+ },
565
+ },
566
+ };
567
+ }
568
+ case 'get_revenue_report': {
569
+ const unknown = assertAllowedKeys(args, new Set(['siteId', 'from', 'to', 'attribution']));
570
+ if (unknown)
571
+ return { ok: false, error: unknown };
572
+ const siteId = validateRequiredSiteId(args);
573
+ if (!siteId)
574
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
575
+ const dates = validateDateBounds(args.from, args.to, 366);
576
+ if (!dates.ok)
577
+ return dates;
578
+ if (args.attribution !== undefined) {
579
+ if (typeof args.attribution !== 'string' || !ATTRIBUTIONS.has(args.attribution)) {
580
+ return { ok: false, error: '"attribution" must be "first_touch" or "last_touch".' };
581
+ }
582
+ }
583
+ return {
584
+ ok: true,
585
+ call: {
586
+ name: 'get_revenue_report',
587
+ args: {
588
+ siteId,
589
+ ...(dates.from ? { from: dates.from } : {}),
590
+ ...(dates.to ? { to: dates.to } : {}),
591
+ ...(typeof args.attribution === 'string'
592
+ ? { attribution: args.attribution }
593
+ : {}),
594
+ },
595
+ },
596
+ };
597
+ }
598
+ case 'get_anomaly_insights': {
599
+ const unknown = assertAllowedKeys(args, new Set(['siteId', 'includeDetails']));
600
+ if (unknown)
601
+ return { ok: false, error: unknown };
602
+ const siteId = validateRequiredSiteId(args);
603
+ if (!siteId)
604
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
605
+ if (args.includeDetails !== undefined && typeof args.includeDetails !== 'boolean') {
606
+ return { ok: false, error: '"includeDetails" must be a boolean.' };
607
+ }
608
+ return {
609
+ ok: true,
610
+ call: {
611
+ name: 'get_anomaly_insights',
612
+ args: {
613
+ siteId,
614
+ ...(typeof args.includeDetails === 'boolean'
615
+ ? { includeDetails: args.includeDetails }
616
+ : {}),
617
+ },
618
+ },
619
+ };
620
+ }
621
+ case 'get_ui_friction': {
622
+ const unknown = assertAllowedKeys(args, new Set(['siteId', 'from', 'to']));
623
+ if (unknown)
624
+ return { ok: false, error: unknown };
625
+ const siteId = validateRequiredSiteId(args);
626
+ if (!siteId)
627
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
628
+ const dates = validateDateBounds(args.from, args.to, 366);
629
+ if (!dates.ok)
630
+ return dates;
631
+ return {
632
+ ok: true,
633
+ call: {
634
+ name: 'get_ui_friction',
635
+ args: {
636
+ siteId,
637
+ ...(dates.from ? { from: dates.from } : {}),
638
+ ...(dates.to ? { to: dates.to } : {}),
639
+ },
640
+ },
641
+ };
642
+ }
643
+ case 'evaluate_funnel': {
644
+ const unknown = assertAllowedKeys(args, new Set(['siteId', 'funnelId', 'steps', 'from', 'to', 'windowSeconds']));
645
+ if (unknown)
646
+ return { ok: false, error: unknown };
647
+ const siteId = validateRequiredSiteId(args);
648
+ if (!siteId)
649
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
650
+ const hasFunnelId = args.funnelId !== undefined;
651
+ const hasSteps = args.steps !== undefined;
652
+ if (hasFunnelId === hasSteps) {
653
+ return {
654
+ ok: false,
655
+ error: 'Provide either "funnelId" or "steps" (mutually exclusive).',
656
+ };
657
+ }
658
+ let funnelId;
659
+ let steps;
660
+ if (hasFunnelId) {
661
+ if (typeof args.funnelId !== 'string' || !UUID_RE.test(args.funnelId)) {
662
+ return { ok: false, error: '"funnelId" must be a valid UUID.' };
663
+ }
664
+ funnelId = args.funnelId;
665
+ }
666
+ else {
667
+ if (!Array.isArray(args.steps) || args.steps.length < 2 || args.steps.length > 8) {
668
+ return { ok: false, error: '"steps" must be an array of 2 to 8 funnel steps.' };
669
+ }
670
+ steps = [];
671
+ for (let i = 0; i < args.steps.length; i++) {
672
+ const item = args.steps[i];
673
+ if (!isPlainObject(item)) {
674
+ return { ok: false, error: `steps[${i}] must be an object.` };
675
+ }
676
+ const stepUnknown = assertAllowedKeys(item, new Set(['label', 'type', 'matchRule']));
677
+ if (stepUnknown)
678
+ return { ok: false, error: `steps[${i}]: ${stepUnknown}` };
679
+ const label = typeof item.label === 'string' ? item.label.trim() : '';
680
+ const type = typeof item.type === 'string' ? item.type : '';
681
+ const matchRule = typeof item.matchRule === 'string' ? item.matchRule.trim() : '';
682
+ if (!label || label.length > 80) {
683
+ return { ok: false, error: `steps[${i}].label must be 1 to 80 characters.` };
684
+ }
685
+ if (!FUNNEL_STEP_TYPES.has(type)) {
686
+ return { ok: false, error: `steps[${i}].type must be "pageview" or "event".` };
687
+ }
688
+ if (!matchRule || matchRule.length > 256) {
689
+ return { ok: false, error: `steps[${i}].matchRule must be 1 to 256 characters.` };
690
+ }
691
+ steps.push({ label, type: type, matchRule });
692
+ }
693
+ }
694
+ const dates = validateDateBounds(args.from, args.to, 90);
695
+ if (!dates.ok)
696
+ return dates;
697
+ let windowSeconds;
698
+ if (args.windowSeconds !== undefined) {
699
+ if (typeof args.windowSeconds !== 'number' ||
700
+ !Number.isInteger(args.windowSeconds) ||
701
+ args.windowSeconds < 60 ||
702
+ args.windowSeconds > 2_592_000) {
703
+ return {
704
+ ok: false,
705
+ error: '"windowSeconds" must be an integer between 60 and 2592000.',
706
+ };
707
+ }
708
+ windowSeconds = args.windowSeconds;
709
+ }
710
+ return {
711
+ ok: true,
712
+ call: {
713
+ name: 'evaluate_funnel',
714
+ args: {
715
+ siteId,
716
+ ...(funnelId ? { funnelId } : {}),
717
+ ...(steps ? { steps } : {}),
718
+ ...(dates.from ? { from: dates.from } : {}),
719
+ ...(dates.to ? { to: dates.to } : {}),
720
+ ...(windowSeconds !== undefined ? { windowSeconds } : {}),
721
+ },
722
+ },
723
+ };
724
+ }
725
+ case 'get_retention_cohorts': {
726
+ const unknown = assertAllowedKeys(args, new Set(['siteId', 'weeks']));
727
+ if (unknown)
728
+ return { ok: false, error: unknown };
729
+ const siteId = validateRequiredSiteId(args);
730
+ if (!siteId)
731
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
732
+ if (args.weeks !== undefined) {
733
+ if (typeof args.weeks !== 'number' ||
734
+ !Number.isInteger(args.weeks) ||
735
+ args.weeks < 2 ||
736
+ args.weeks > 12) {
737
+ return { ok: false, error: '"weeks" must be an integer between 2 and 12.' };
738
+ }
739
+ }
740
+ return {
741
+ ok: true,
742
+ call: {
743
+ name: 'get_retention_cohorts',
744
+ args: {
745
+ siteId,
746
+ ...(typeof args.weeks === 'number' ? { weeks: args.weeks } : {}),
747
+ },
748
+ },
749
+ };
750
+ }
751
+ case 'get_ai_crawlers': {
752
+ const unknown = assertAllowedKeys(args, new Set(['siteId', 'from', 'to', 'category', 'crawler', 'pathname']));
753
+ if (unknown)
754
+ return { ok: false, error: unknown };
755
+ const siteId = validateRequiredSiteId(args);
756
+ if (!siteId)
757
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
758
+ const dates = validateDateBounds(args.from, args.to, 366);
759
+ if (!dates.ok)
760
+ return dates;
761
+ if (args.category !== undefined) {
762
+ if (typeof args.category !== 'string' || !CRAWLER_CATEGORIES.has(args.category)) {
763
+ return {
764
+ ok: false,
765
+ error: '"category" must be one of ai_answers, indexing, or training.',
766
+ };
767
+ }
768
+ }
769
+ const crawler = validateOptionalString(args, 'crawler', 64);
770
+ if (!crawler.ok)
771
+ return crawler;
772
+ const pathname = validateOptionalString(args, 'pathname', 512);
773
+ if (!pathname.ok)
774
+ return pathname;
775
+ return {
776
+ ok: true,
777
+ call: {
778
+ name: 'get_ai_crawlers',
779
+ args: {
780
+ siteId,
781
+ ...(dates.from ? { from: dates.from } : {}),
782
+ ...(dates.to ? { to: dates.to } : {}),
783
+ ...(typeof args.category === 'string'
784
+ ? { category: args.category }
785
+ : {}),
786
+ ...(crawler.value !== undefined ? { crawler: crawler.value } : {}),
787
+ ...(pathname.value !== undefined ? { pathname: pathname.value } : {}),
788
+ },
789
+ },
790
+ };
791
+ }
792
+ case 'get_ai_referrals': {
793
+ const unknown = assertAllowedKeys(args, new Set(['siteId', 'from', 'to', 'provider', 'pathname']));
794
+ if (unknown)
795
+ return { ok: false, error: unknown };
796
+ const siteId = validateRequiredSiteId(args);
797
+ if (!siteId)
798
+ return { ok: false, error: '"siteId" must be a valid UUID.' };
799
+ const dates = validateDateBounds(args.from, args.to, 366);
800
+ if (!dates.ok)
801
+ return dates;
802
+ const provider = validateOptionalString(args, 'provider', 64);
803
+ if (!provider.ok)
804
+ return provider;
805
+ const pathname = validateOptionalString(args, 'pathname', 512);
806
+ if (!pathname.ok)
807
+ return pathname;
808
+ return {
809
+ ok: true,
810
+ call: {
811
+ name: 'get_ai_referrals',
812
+ args: {
813
+ siteId,
814
+ ...(dates.from ? { from: dates.from } : {}),
815
+ ...(dates.to ? { to: dates.to } : {}),
816
+ ...(provider.value !== undefined ? { provider: provider.value } : {}),
817
+ ...(pathname.value !== undefined ? { pathname: pathname.value } : {}),
818
+ },
819
+ },
820
+ };
821
+ }
822
+ default:
823
+ return { ok: false, error: `Unknown tool: "${name}".` };
824
+ }
825
+ }