@datadive-tools/mcp 0.5.0 → 0.7.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/README.md CHANGED
@@ -15,6 +15,12 @@ except as the `x-api-key` header on requests to `api.datadive.tools`.
15
15
  - "What's my ranking juice for niche X — where can I improve?"
16
16
  - "Show me my rank radars."
17
17
  - "Plot the organic ranking trend for rank radar Y from 2024-03-01 to 2024-04-01."
18
+ - "Run a niche dive on ASIN B08N5WRWNW in the US marketplace with 5 competitors."
19
+ - "Is my dive done yet?"
20
+ - "Start a rank radar tracking 10 keywords for ASIN B08N5WRWNW in niche X."
21
+ - "Which Amazon seller accounts are connected?"
22
+ - "Search my catalog for active 'widget' products in the US."
23
+ - "What price or content changes happened on my listings last week?"
18
24
 
19
25
  ## 1. Get a DataDive API key
20
26
 
@@ -96,17 +102,43 @@ niches, plus pagination metadata. If you don't, see Troubleshooting below.
96
102
  | `get_ranking_juice` | DataDive proprietary ranking-juice metric per competitor (current vs optimized listing). |
97
103
  | `list_rank_radars` | Paginated list of rank radars. Filter by `nicheId` or `status`. |
98
104
  | `get_rank_radar_data` | Historical keyword rankings for a rank radar within a `startDate`/`endDate` range. |
99
- | `get_asin_inventory_distribution` | Per-fulfillment-center sellable inventory for an ASIN. Requires `sellerId` from your Connections page. |
105
+ | `create_niche_dive` | **Spends dive tokens.** Starts new niche research from a seed ASIN. Async — returns a `diveId` to poll with `get_dive_status`. Requires `confirm: true`. |
106
+ | `get_dive_status` | Poll a dive started by `create_niche_dive`: `in_progress`, `success` (carries the new `nicheId`), or `error`. |
107
+ | `create_rank_radar` | **Spends Search Term tokens.** Starts tracking keyword rankings for an ASIN in a niche. Returns a `rankRadarId`. Requires `confirm: true`. |
108
+ | `list_seller_profiles` | Paginated list of connected Amazon seller accounts. Discovery step — returns the `sellerId` + `marketplace` the seller-scoped tools below (and the alert tools) need. |
109
+ | `get_seller_catalog` | Paginated catalog of a seller's own ASINs. Filter by `search`, `brand`, and `status` (Active by default). |
110
+ | `get_seller_listing_changes` | Paginated price/content/image changes on a seller's listings. Filter by `types`, `asin`, `brand`, `search`, and a date range; optionally include ranking/conversion `correlation`. |
111
+ | `get_asin_inventory_distribution` | Per-fulfillment-center sellable inventory for an ASIN. Requires `sellerId` from `list_seller_profiles` or your Connections page. |
100
112
  | `list_indexing_issue_alerts` | Paginated list of indexing-issue alerts — ASINs no longer indexed for their tracked keywords. Filter by `sellerId`, `marketplace`, `status`, or `updatedSince`. |
101
113
  | `list_blind_spend_alerts` | Paginated list of blind-spend alerts — ad spend on search terms with little or no sales, with per-term spend/clicks/CVR. Same filters as above. |
102
114
  | `get_quota` | Current quota usage and capacity per billable feature, plus the next refresh date. No arguments. |
103
115
  | `list_usage` | Paginated billable usage logs (token-consumption events). Filter by `type`, `search` (user), and `startDate`/`endDate`. |
104
116
 
105
- Read-only. All data is scoped to the organization that owns the API key.
117
+ All data is scoped to the organization that owns the API key. Most tools are
118
+ read-only; the two `create_*` tools below spend tokens (`get_dive_status` only
119
+ polls a dive and is read-only) — see
120
+ [Creating dives & rank radars](#creating-dives--rank-radars).
106
121
 
107
- > **Coming in v1.1:** keyword roots, async niche dives with polling, rank-radar
108
- > creation, AI copywriter. We'll prioritize based on usage signal — if you
109
- > have a request, open an issue.
122
+ ### Creating dives & rank radars
123
+
124
+ `create_niche_dive` and `create_rank_radar` **consume billable tokens and cannot
125
+ be undone**, so they require an explicit `confirm: true` argument. The assistant
126
+ should confirm the cost with you before passing it. The amount scales with
127
+ `numberOfCompetitors` (dives) / `numberOfKeywords` (rank radars). Check remaining
128
+ balance any time with `get_quota`.
129
+
130
+ To skip the per-call confirmation (e.g. in an automated setup), set
131
+ `DATADIVE_AUTO_CONFIRM_WRITES=true` in your client config — then these tools run
132
+ without `confirm`.
133
+
134
+ Dives are **asynchronous**. `create_niche_dive` returns a `diveId` and an
135
+ estimated completion time immediately; poll `get_dive_status` with that `diveId`
136
+ until it reports `success`, which carries the new `nicheId` you then feed to
137
+ `list_niches`, `get_niche_keywords`, and the other niche tools.
138
+
139
+ > ⚠️ For `create_niche_dive`, `marketplace` uses full Amazon domain suffixes
140
+ > (`com`, `co.uk`, `com.mx`, `co.jp`, …) — e.g. the UK marketplace is `co.uk`,
141
+ > not `uk`.
110
142
 
111
143
  ## Configuration
112
144
 
@@ -114,6 +146,7 @@ Read-only. All data is scoped to the organization that owns the API key.
114
146
  |---|---|---|---|
115
147
  | `DATADIVE_API_KEY` | yes | — | Generate at https://2.datadive.tools/api-key |
116
148
  | `DATADIVE_API_BASE_URL` | no | `https://api.datadive.tools` | Override for staging |
149
+ | `DATADIVE_AUTO_CONFIRM_WRITES` | no | `false` | Set truthy to let `create_niche_dive` / `create_rank_radar` run without `confirm: true`. |
117
150
 
118
151
  ## Troubleshooting
119
152
 
package/dist/index.js CHANGED
@@ -15,7 +15,10 @@ function loadConfig(env = process.env) {
15
15
  }
16
16
  const rawBase = (env.DATADIVE_API_BASE_URL ?? DEFAULT_BASE_URL).trim();
17
17
  const baseUrl = rawBase.replace(/\/+$/, "");
18
- return { apiKey, baseUrl };
18
+ const autoConfirmWrites = ["1", "true", "yes"].includes(
19
+ (env.DATADIVE_AUTO_CONFIRM_WRITES ?? "").trim().toLowerCase()
20
+ );
21
+ return { apiKey, baseUrl, autoConfirmWrites };
19
22
  }
20
23
 
21
24
  // src/server.ts
@@ -100,7 +103,7 @@ function extractMessage(body) {
100
103
  }
101
104
 
102
105
  // package.json
103
- var version = "0.5.0";
106
+ var version = "0.7.0";
104
107
 
105
108
  // src/http/client.ts
106
109
  var PKG_VERSION = version;
@@ -145,9 +148,34 @@ async function httpGet(ctx, path, query) {
145
148
  }
146
149
  });
147
150
  } catch (e) {
148
- const msg = e instanceof Error ? e.message : String(e);
149
- throw new ApiError("network", 0, `Network error reaching ${url}: ${msg}`);
151
+ throw networkError(url, e);
150
152
  }
153
+ return handleResponse(res);
154
+ }
155
+ async function httpPost(ctx, path, body) {
156
+ const url = buildUrl(ctx.config.baseUrl, path);
157
+ let res;
158
+ try {
159
+ res = await fetch(url, {
160
+ method: "POST",
161
+ headers: {
162
+ "x-api-key": ctx.config.apiKey,
163
+ accept: "application/json",
164
+ "content-type": "application/json",
165
+ "user-agent": userAgent(ctx.toolName)
166
+ },
167
+ body: JSON.stringify(body)
168
+ });
169
+ } catch (e) {
170
+ throw networkError(url, e);
171
+ }
172
+ return handleResponse(res);
173
+ }
174
+ function networkError(url, e) {
175
+ const msg = e instanceof Error ? e.message : String(e);
176
+ return new ApiError("network", 0, `Network error reaching ${url}: ${msg}`);
177
+ }
178
+ async function handleResponse(res) {
151
179
  noteLatestVersion(res.headers.get(LATEST_VERSION_HEADER));
152
180
  const text = await res.text();
153
181
  let body;
@@ -303,6 +331,10 @@ var BILLABLE_FEATURE_TYPES = [
303
331
  "AI_COPYWRITER_PROMPTS",
304
332
  "RANK_RADAR_KEYWORDS"
305
333
  ];
334
+ var CATALOG_STATUSES = ["Active", "all"];
335
+ var LISTING_CHANGE_TYPES = ["Price", "Content", "Image"];
336
+ var LISTING_CHANGE_SORT_BY = ["date", "type"];
337
+ var SORT_ORDER = ["ASC", "DESC"];
306
338
 
307
339
  // src/tools/list-rank-radars.ts
308
340
  var inputSchema6 = {
@@ -356,22 +388,246 @@ var getRankRadarDataTool = {
356
388
  }
357
389
  };
358
390
 
359
- // src/tools/get-asin-inventory-distribution.ts
391
+ // src/tools/create-rank-radar.ts
360
392
  import { z as z8 } from "zod";
393
+
394
+ // src/tools/confirm.ts
395
+ function requireConfirmation(confirm, ctx, costNote) {
396
+ if (confirm === true || ctx.config.autoConfirmWrites) return null;
397
+ return {
398
+ status: "confirmation_required",
399
+ message: "This action spends billable tokens and cannot be undone. Confirm the cost with the user, then call again with `confirm: true` to proceed.",
400
+ costNote
401
+ };
402
+ }
403
+
404
+ // src/tools/create-rank-radar.ts
361
405
  var inputSchema8 = {
362
- sellerId: z8.string().min(1).describe(
363
- "Amazon seller account ID as connected to DataDive. Find it on the Connections page at https://2.datadive.tools \u2014 there is no MCP discovery tool for sellers yet."
406
+ asin: z8.string().min(1).describe("The ASIN to track keyword rankings for."),
407
+ numberOfKeywords: z8.number().int().min(1).describe("How many keywords to track (minimum 1). More keywords = broader tracking but more Search Term tokens."),
408
+ nicheId: z8.string().min(1).describe("The niche this Rank Radar belongs to. Get one from `list_niches`."),
409
+ confirm: z8.boolean().optional().describe(
410
+ "Must be true to proceed \u2014 creating a Rank Radar spends Search Term tokens. Confirm the cost with the user first."
411
+ )
412
+ };
413
+ var createRankRadarTool = {
414
+ name: "create_rank_radar",
415
+ title: "Create a Rank Radar",
416
+ description: "Use this to start tracking organic and sponsored keyword rankings for an ASIN within a niche. \u26A0\uFE0F Spends Search Term tokens (cost scales with `numberOfKeywords`) and cannot be undone \u2014 set `confirm: true` only after the user approves the cost. Returns the new `rankRadarId`; read its data later with `get_rank_radar_data`. Requires `asin`, `numberOfKeywords` (min 1), and a `nicheId` from `list_niches`.",
417
+ inputSchema: inputSchema8,
418
+ // destructiveHint is technically "additive" here (this creates a new Rank Radar, it
419
+ // doesn't destroy data), but we flag it destructive so clients prompt before the
420
+ // irreversible token spend. The confirm gate enforces this server-side regardless.
421
+ annotations: { readOnlyHint: false, destructiveHint: true },
422
+ handler: async (args, ctx) => {
423
+ const pending = requireConfirmation(
424
+ args.confirm,
425
+ ctx,
426
+ `Creating this Rank Radar consumes Search Term tokens \u2014 one per keyword tracked (${args.numberOfKeywords} requested).`
427
+ );
428
+ if (pending) return pending;
429
+ return await httpPost(
430
+ { config: ctx.config, toolName: "create_rank_radar" },
431
+ "/v1/niches/rank-radars",
432
+ {
433
+ asin: args.asin,
434
+ numberOfKeywords: args.numberOfKeywords,
435
+ nicheId: args.nicheId
436
+ }
437
+ );
438
+ }
439
+ };
440
+
441
+ // src/tools/create-niche-dive.ts
442
+ import { z as z9 } from "zod";
443
+ var inputSchema9 = {
444
+ marketplace: z9.enum(SUPPORTED_MARKETPLACES).describe(
445
+ "Amazon marketplace of the seed ASIN. Note these are full domain suffixes: com, ca, co.uk, com.mx, in, fr, de, es, it, co.jp (e.g. UK is `co.uk`, not `uk`)."
446
+ ),
447
+ asin: z9.string().min(1).describe("The seed ASIN to start the dive from (e.g. B08N5WRWNW). Competitors are built around it."),
448
+ numberOfCompetitors: z9.number().int().min(2).describe("How many competitors to analyze (minimum 2). More competitors = deeper niche but more dive tokens."),
449
+ confirm: z9.boolean().optional().describe("Must be true to proceed \u2014 creating a dive spends dive tokens. Confirm the cost with the user first.")
450
+ };
451
+ var createNicheDiveTool = {
452
+ name: "create_niche_dive",
453
+ title: "Create a Niche Dive",
454
+ description: "Use this to start new niche research from a seed ASIN. \u26A0\uFE0F Spends dive tokens (cost scales with `numberOfCompetitors`) and cannot be undone \u2014 set `confirm: true` only after the user approves the cost. The dive runs asynchronously: this returns immediately with a `diveId` and an `estimatedCompletionDate`. Poll `get_dive_status` with that `diveId` until it reports `success` (which carries the new `nicheId` for use with `list_niches`, `get_niche_keywords`, etc.). Requires `marketplace`, `asin`, and `numberOfCompetitors` (min 2).",
455
+ inputSchema: inputSchema9,
456
+ // destructiveHint is technically "additive" here (a dive creates a new niche, it
457
+ // doesn't destroy data), but we flag it destructive so clients prompt before the
458
+ // irreversible token spend. The confirm gate enforces this server-side regardless.
459
+ annotations: { readOnlyHint: false, destructiveHint: true },
460
+ handler: async (args, ctx) => {
461
+ const pending = requireConfirmation(
462
+ args.confirm,
463
+ ctx,
464
+ `Creating this dive consumes dive tokens \u2014 one batch per competitor analyzed (${args.numberOfCompetitors} requested).`
465
+ );
466
+ if (pending) return pending;
467
+ return await httpPost(
468
+ { config: ctx.config, toolName: "create_niche_dive" },
469
+ "/v1/niches/dives",
470
+ {
471
+ marketplace: args.marketplace,
472
+ asin: args.asin,
473
+ numberOfCompetitors: args.numberOfCompetitors
474
+ }
475
+ );
476
+ }
477
+ };
478
+
479
+ // src/tools/get-dive-status.ts
480
+ import { z as z10 } from "zod";
481
+ var inputSchema10 = {
482
+ diveId: z10.string().min(1).describe("The dive identifier returned by `create_niche_dive`.")
483
+ };
484
+ var getDiveStatusTool = {
485
+ name: "get_dive_status",
486
+ title: "Get Niche Dive Status",
487
+ description: "Use this to poll a niche dive started with `create_niche_dive` until it finishes. Returns one of three shapes keyed by `status`: `in_progress` (with `estimatedCompletionDate`), `success` (with the new `nicheId` plus `tokensUsed`/`tokensLeft`), or `error` (with an `error` message). On `success`, use the `nicheId` with `list_niches`, `get_niche_keywords`, `get_niche_competitors`, etc. Re-poll periodically \u2014 dives can take minutes; the `estimatedCompletionDate` hints at when to check.",
488
+ inputSchema: inputSchema10,
489
+ annotations: { readOnlyHint: true },
490
+ handler: async (args, ctx) => {
491
+ return await httpGet(
492
+ { config: ctx.config, toolName: "get_dive_status" },
493
+ `/v1/niches/dives/${encodeURIComponent(args.diveId)}`
494
+ );
495
+ }
496
+ };
497
+
498
+ // src/tools/list-seller-profiles.ts
499
+ import { z as z11 } from "zod";
500
+ var inputSchema11 = {
501
+ currentPage: z11.number().int().min(1).optional().describe("Page number, 1-indexed. Defaults to 1."),
502
+ pageSize: z11.number().int().min(1).max(50).optional().describe("Items per page (max 50). Defaults to 20.")
503
+ };
504
+ var listSellerProfilesTool = {
505
+ name: "list_seller_profiles",
506
+ title: "List Connected Amazon Seller Profiles",
507
+ description: 'Use this when the user asks which Amazon seller accounts are connected, or as the discovery step to find the `sellerId` and `marketplace` required by `get_asin_inventory_distribution`, `get_seller_catalog`, `get_seller_listing_changes`, and the alert tools. Returns a paginated list of the organization\'s connected seller profiles \u2014 each item has sellerId, sellerName, marketplace (e.g. "com", "co.uk"), hasAdApi (whether Advertising API credentials are connected), and createdAt \u2014 plus pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).',
508
+ inputSchema: inputSchema11,
509
+ annotations: { readOnlyHint: true },
510
+ handler: async (args, ctx) => {
511
+ return await httpGet(
512
+ { config: ctx.config, toolName: "list_seller_profiles" },
513
+ "/v1/seller_profiles",
514
+ {
515
+ currentPage: args.currentPage,
516
+ pageSize: args.pageSize
517
+ }
518
+ );
519
+ }
520
+ };
521
+
522
+ // src/tools/get-seller-catalog.ts
523
+ import { z as z13 } from "zod";
524
+
525
+ // src/tools/seller-scoped.ts
526
+ import { z as z12 } from "zod";
527
+ var sellerScopedInputSchema = {
528
+ sellerId: z12.string().min(1).describe(
529
+ "Amazon seller account ID. Get it from `list_seller_profiles`, or find it on the Connections page at https://2.datadive.tools."
530
+ ),
531
+ marketplace: z12.enum(SUPPORTED_MARKETPLACES).describe('Amazon marketplace code, e.g. "com" for amazon.com or "co.uk" for amazon.co.uk.')
532
+ };
533
+ function sellerMarketplacePath(sellerId, marketplace, suffix) {
534
+ return `/v1/seller_profiles/${encodeURIComponent(sellerId)}/marketplaces/${encodeURIComponent(
535
+ marketplace
536
+ )}/${suffix}`;
537
+ }
538
+
539
+ // src/tools/get-seller-catalog.ts
540
+ var inputSchema12 = {
541
+ ...sellerScopedInputSchema,
542
+ search: z13.string().min(1).optional().describe("Case-insensitive partial match on product title or brand."),
543
+ brand: z13.string().min(1).optional().describe("Case-insensitive partial match on brand name."),
544
+ status: z13.enum(CATALOG_STATUSES).optional().describe('Listing status filter. "Active" (default) or "all".'),
545
+ currentPage: z13.number().int().min(1).optional().describe("Page number, 1-indexed. Defaults to 1."),
546
+ pageSize: z13.number().int().min(1).max(50).optional().describe("Items per page (max 50). Defaults to 20.")
547
+ };
548
+ var getSellerCatalogTool = {
549
+ name: "get_seller_catalog",
550
+ title: "List Catalog ASINs for a Seller",
551
+ description: "Use this when the user wants to browse or search a seller's own Amazon catalog \u2014 the products they sell on a given marketplace. Requires a `sellerId` + `marketplace` (use `list_seller_profiles` to discover them). Filter by `search` (title/brand), `brand`, and `status` (Active by default, or all). Returns a paginated list where each item has asin, title, parentAsin, brand, status, imageUrl, and hasVariations, plus pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).",
552
+ inputSchema: inputSchema12,
553
+ annotations: { readOnlyHint: true },
554
+ handler: async (args, ctx) => {
555
+ return await httpGet(
556
+ { config: ctx.config, toolName: "get_seller_catalog" },
557
+ sellerMarketplacePath(args.sellerId, args.marketplace, "catalog"),
558
+ {
559
+ search: args.search,
560
+ brand: args.brand,
561
+ status: args.status,
562
+ currentPage: args.currentPage,
563
+ pageSize: args.pageSize
564
+ }
565
+ );
566
+ }
567
+ };
568
+
569
+ // src/tools/get-seller-listing-changes.ts
570
+ import { z as z14 } from "zod";
571
+ var inputSchema13 = {
572
+ ...sellerScopedInputSchema,
573
+ types: z14.array(z14.enum(LISTING_CHANGE_TYPES)).min(1).optional().describe('Filter to specific change types. Omit for all. Any of "Price", "Content", "Image".'),
574
+ asin: z14.string().min(1).optional().describe("Filter to an exact ASIN or parent ASIN."),
575
+ brand: z14.string().min(1).optional().describe("Case-insensitive partial match on brand name."),
576
+ search: z14.string().min(1).optional().describe("Case-insensitive partial match on product title or brand."),
577
+ startDate: z14.string().regex(ISO_8601, "startDate must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)").optional().describe("ISO-8601 date/timestamp; return only changes detected on or after this time."),
578
+ endDate: z14.string().regex(ISO_8601, "endDate must be an ISO-8601 date or timestamp (e.g. 2026-05-31 or 2026-05-31T23:59:59Z)").optional().describe("ISO-8601 date/timestamp; return only changes detected on or before this time."),
579
+ sortBy: z14.enum(LISTING_CHANGE_SORT_BY).optional().describe('Sort field. "date" (default) or "type".'),
580
+ sortOrder: z14.enum(SORT_ORDER).optional().describe('Sort direction. "DESC" (default) or "ASC".'),
581
+ includeCorrelations: z14.boolean().optional().describe(
582
+ "When true, include the ranking/conversion `correlation` object per change (CVR and search-term movement before vs after). Defaults to false."
583
+ ),
584
+ currentPage: z14.number().int().min(1).optional().describe("Page number, 1-indexed. Defaults to 1."),
585
+ pageSize: z14.number().int().min(1).max(50).optional().describe("Items per page (max 50). Defaults to 20.")
586
+ };
587
+ var getSellerListingChangesTool = {
588
+ name: "get_seller_listing_changes",
589
+ title: "List Listing Changes for a Seller",
590
+ description: "Use this when the user asks what changed on their Amazon listings \u2014 price, content (title/bullets/description), or image edits \u2014 for a seller account. Requires a `sellerId` + `marketplace` (use `list_seller_profiles` to discover them). Filter by `types`, `asin`/parent ASIN, `brand`, `search`, and a `startDate`/`endDate` range; sort with `sortBy`/`sortOrder`. Set `includeCorrelations: true` to attach the ranking/conversion impact per change. Returns a paginated list where each item has asin, title, imageUrl, date, type, contentType, description, previousValue, newValue, and (optionally) correlation, plus pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).",
591
+ inputSchema: inputSchema13,
592
+ annotations: { readOnlyHint: true },
593
+ handler: async (args, ctx) => {
594
+ return await httpGet(
595
+ { config: ctx.config, toolName: "get_seller_listing_changes" },
596
+ sellerMarketplacePath(args.sellerId, args.marketplace, "listing-changes"),
597
+ {
598
+ // The API accepts `types` as a comma-separated list.
599
+ types: args.types?.join(","),
600
+ asin: args.asin,
601
+ brand: args.brand,
602
+ search: args.search,
603
+ startDate: args.startDate,
604
+ endDate: args.endDate,
605
+ sortBy: args.sortBy,
606
+ sortOrder: args.sortOrder,
607
+ includeCorrelations: args.includeCorrelations,
608
+ currentPage: args.currentPage,
609
+ pageSize: args.pageSize
610
+ }
611
+ );
612
+ }
613
+ };
614
+
615
+ // src/tools/get-asin-inventory-distribution.ts
616
+ import { z as z15 } from "zod";
617
+ var inputSchema14 = {
618
+ sellerId: z15.string().min(1).describe(
619
+ "Amazon seller account ID as connected to DataDive. Get it from `list_seller_profiles`, or find it on the Connections page at https://2.datadive.tools."
364
620
  ),
365
- marketplace: z8.enum(SUPPORTED_MARKETPLACES).describe('Amazon marketplace code, e.g. "com" for amazon.com or "co.uk" for amazon.co.uk.'),
366
- asin: z8.string().regex(/^[A-Z0-9]{10}$/, "ASIN must be 10 uppercase alphanumeric characters (e.g. B08XYZ1234).").describe(
621
+ marketplace: z15.enum(SUPPORTED_MARKETPLACES).describe('Amazon marketplace code, e.g. "com" for amazon.com or "co.uk" for amazon.co.uk.'),
622
+ asin: z15.string().regex(/^[A-Z0-9]{10}$/, "ASIN must be 10 uppercase alphanumeric characters (e.g. B08XYZ1234).").describe(
367
623
  "Amazon Standard Identification Number (10 uppercase alphanumeric characters, e.g. B08XYZ1234)."
368
624
  )
369
625
  };
370
626
  var getAsinInventoryDistributionTool = {
371
627
  name: "get_asin_inventory_distribution",
372
628
  title: "Get Per-Fulfillment-Center Inventory Distribution for an ASIN",
373
- description: "Use this when the user asks about inventory levels, stock by fulfillment center, or where their units are sitting across Amazon's fulfillment network for a specific ASIN. Requires the Amazon sellerId from the user's DataDive Connections page (https://2.datadive.tools), the marketplace code, and the ASIN. Returns totalSellableUnits and a per-FC `distribution` array (fc, state, availableStock, availableStockPercentage). `lastUpdatedAt` may be null when no successful inventory ingestion has occurred in the last 30 days.",
374
- inputSchema: inputSchema8,
629
+ description: "Use this when the user asks about inventory levels, stock by fulfillment center, or where their units are sitting across Amazon's fulfillment network for a specific ASIN. Requires the Amazon sellerId (from `list_seller_profiles` or the user's DataDive Connections page at https://2.datadive.tools), the marketplace code, and the ASIN. Returns totalSellableUnits and a per-FC `distribution` array (fc, state, availableStock, availableStockPercentage). `lastUpdatedAt` may be null when no successful inventory ingestion has occurred in the last 30 days.",
630
+ inputSchema: inputSchema14,
375
631
  handler: async (args, ctx) => {
376
632
  return await httpGet(
377
633
  { config: ctx.config, toolName: "get_asin_inventory_distribution" },
@@ -383,18 +639,18 @@ var getAsinInventoryDistributionTool = {
383
639
  };
384
640
 
385
641
  // src/tools/alert-query.ts
386
- import { z as z9 } from "zod";
642
+ import { z as z16 } from "zod";
387
643
  var alertsQueryInputSchema = {
388
- sellerId: z9.string().min(1).max(50).optional().describe('Filter to a single connected Amazon seller account ID, e.g. "A1B2C3D4E5".'),
389
- marketplace: z9.enum(SUPPORTED_MARKETPLACES).optional().describe('Filter to a single Amazon marketplace code, e.g. "com" for amazon.com or "co.uk" for amazon.co.uk.'),
390
- status: z9.enum(ALERT_STATUSES).optional().describe(
644
+ sellerId: z16.string().min(1).max(50).optional().describe('Filter to a single connected Amazon seller account ID, e.g. "A1B2C3D4E5".'),
645
+ marketplace: z16.enum(SUPPORTED_MARKETPLACES).optional().describe('Filter to a single Amazon marketplace code, e.g. "com" for amazon.com or "co.uk" for amazon.co.uk.'),
646
+ status: z16.enum(ALERT_STATUSES).optional().describe(
391
647
  "Lifecycle filter. `active` (default) returns unresolved alerts, `resolved` returns resolved alerts, `all` returns both. Dismissed alerts are never returned."
392
648
  ),
393
- updatedSince: z9.string().regex(ISO_8601, "updatedSince must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)").optional().describe(
649
+ updatedSince: z16.string().regex(ISO_8601, "updatedSince must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)").optional().describe(
394
650
  "ISO-8601 timestamp; return only alerts surfaced at or after this time (filters on `lastAlertedAt`). Use it to incrementally sync since your last poll. Defaults to the last 30 days when omitted."
395
651
  ),
396
- currentPage: z9.number().int().min(1).optional().describe("Page number, 1-indexed. Defaults to 1."),
397
- pageSize: z9.number().int().min(1).max(50).optional().describe("Items per page (max 50). Defaults to 20.")
652
+ currentPage: z16.number().int().min(1).optional().describe("Page number, 1-indexed. Defaults to 1."),
653
+ pageSize: z16.number().int().min(1).max(50).optional().describe("Items per page (max 50). Defaults to 20.")
398
654
  };
399
655
 
400
656
  // src/tools/list-indexing-issue-alerts.ts
@@ -442,32 +698,32 @@ var listBlindSpendAlertsTool = {
442
698
  };
443
699
 
444
700
  // src/tools/get-quota.ts
445
- var inputSchema9 = {};
701
+ var inputSchema15 = {};
446
702
  var getQuotaTool = {
447
703
  name: "get_quota",
448
704
  title: "Get Quota Usage",
449
705
  description: "Use this when the user asks how much quota or how many tokens they have left, or before creating a Niche Dive or Rank Radar to check remaining headroom. Returns current quota usage and capacity for each billable feature \u2014 DIVED_ASINS (Dive tokens), RANK_RADAR_KEYWORDS (tracked keywords), PRODUCT_BRIEF_ASINS, and AI_COPYWRITER_PROMPTS \u2014 each with `used` and `capacity` (null when unlimited / not applicable), plus `nextRefreshDate` (ISO-8601 timestamp of the next quota reset, or null). Takes no arguments.",
450
- inputSchema: inputSchema9,
706
+ inputSchema: inputSchema15,
451
707
  handler: async (_args, ctx) => {
452
708
  return await httpGet({ config: ctx.config, toolName: "get_quota" }, "/v1/quota");
453
709
  }
454
710
  };
455
711
 
456
712
  // src/tools/list-usage.ts
457
- import { z as z10 } from "zod";
458
- var inputSchema10 = {
459
- type: z10.enum(BILLABLE_FEATURE_TYPES).optional().describe("Filter to a single billable feature type. Omit to return all types."),
460
- search: z10.string().min(1).optional().describe("Case-insensitive partial match on the user's name or email."),
461
- startDate: z10.string().regex(ISO_8601, "startDate must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)").optional().describe("ISO-8601 date/timestamp; return only usage logs recorded on or after this time."),
462
- endDate: z10.string().regex(ISO_8601, "endDate must be an ISO-8601 date or timestamp (e.g. 2026-05-31 or 2026-05-31T23:59:59Z)").optional().describe("ISO-8601 date/timestamp; return only usage logs recorded on or before this time."),
463
- currentPage: z10.number().int().min(1).optional().describe("Page number, 1-indexed. Defaults to 1."),
464
- pageSize: z10.number().int().min(1).max(200).optional().describe("Items per page (max 200). Defaults to 50.")
713
+ import { z as z17 } from "zod";
714
+ var inputSchema16 = {
715
+ type: z17.enum(BILLABLE_FEATURE_TYPES).optional().describe("Filter to a single billable feature type. Omit to return all types."),
716
+ search: z17.string().min(1).optional().describe("Case-insensitive partial match on the user's name or email."),
717
+ startDate: z17.string().regex(ISO_8601, "startDate must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)").optional().describe("ISO-8601 date/timestamp; return only usage logs recorded on or after this time."),
718
+ endDate: z17.string().regex(ISO_8601, "endDate must be an ISO-8601 date or timestamp (e.g. 2026-05-31 or 2026-05-31T23:59:59Z)").optional().describe("ISO-8601 date/timestamp; return only usage logs recorded on or before this time."),
719
+ currentPage: z17.number().int().min(1).optional().describe("Page number, 1-indexed. Defaults to 1."),
720
+ pageSize: z17.number().int().min(1).max(200).optional().describe("Items per page (max 200). Defaults to 50.")
465
721
  };
466
722
  var listUsageTool = {
467
723
  name: "list_usage",
468
724
  title: "List Billable Usage Logs",
469
725
  description: "Use this when the user asks who consumed tokens, how their quota was spent, or wants an audit of billable activity over a date range. Retrieves a paginated list of billable feature usage logs for the organization \u2014 each entry is a token-consumption event (a dive, rank-radar creation, AI copywriter prompt, etc.). Filter by `type` (billable feature), `search` (user name/email), and `startDate`/`endDate`. Each item includes name, email, qty (tokens consumed), type, action (specific operation), nicheId/nicheName, rankRadarId, and date, plus pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).",
470
- inputSchema: inputSchema10,
726
+ inputSchema: inputSchema16,
471
727
  handler: async (args, ctx) => {
472
728
  return await httpGet(
473
729
  { config: ctx.config, toolName: "list_usage" },
@@ -493,6 +749,12 @@ var allTools = [
493
749
  getRankingJuiceTool,
494
750
  listRankRadarsTool,
495
751
  getRankRadarDataTool,
752
+ createRankRadarTool,
753
+ createNicheDiveTool,
754
+ getDiveStatusTool,
755
+ listSellerProfilesTool,
756
+ getSellerCatalogTool,
757
+ getSellerListingChangesTool,
496
758
  getAsinInventoryDistributionTool,
497
759
  listIndexingIssueAlertsTool,
498
760
  listBlindSpendAlertsTool,
@@ -512,7 +774,8 @@ function buildServer(config) {
512
774
  {
513
775
  title: tool.title,
514
776
  description: tool.description,
515
- inputSchema: tool.inputSchema
777
+ inputSchema: tool.inputSchema,
778
+ annotations: tool.annotations
516
779
  },
517
780
  async (args) => {
518
781
  try {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/config.ts","../src/server.ts","../src/tools/list-niches.ts","../src/http/errors.ts","../package.json","../src/http/client.ts","../src/tools/get-niche-keywords.ts","../src/tools/get-niche-roots.ts","../src/tools/get-niche-competitors.ts","../src/tools/get-ranking-juice.ts","../src/tools/list-rank-radars.ts","../src/types/api.ts","../src/tools/get-rank-radar-data.ts","../src/tools/get-asin-inventory-distribution.ts","../src/tools/alert-query.ts","../src/tools/list-indexing-issue-alerts.ts","../src/tools/list-blind-spend-alerts.ts","../src/tools/get-quota.ts","../src/tools/list-usage.ts","../src/tools/index.ts"],"sourcesContent":["/**\n * Entry point for the datadive-mcp stdio binary.\n *\n * Wired via package.json#bin -> dist/index.js so `npx -y @datadive-tools/mcp` runs it.\n * The shebang is added at build time by tsup.config.ts (banner.js).\n */\n\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { loadConfig } from \"./config.js\";\nimport { buildServer } from \"./server.js\";\n\nasync function main() {\n let config;\n try {\n config = loadConfig();\n } catch (err) {\n // Config errors (e.g. missing API key) are user-facing; print to stderr and exit\n // non-zero so the MCP client surfaces a real error rather than silently disconnecting.\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[datadive-mcp] ${msg}\\n`);\n process.exit(1);\n }\n\n const server = buildServer(config);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nmain().catch((err) => {\n const msg = err instanceof Error ? (err.stack ?? err.message) : String(err);\n process.stderr.write(`[datadive-mcp] fatal: ${msg}\\n`);\n process.exit(1);\n});\n","/**\n * Loads and validates the server's runtime configuration from environment.\n *\n * Required:\n * DATADIVE_API_KEY - your DataDive API key (generate at 2.datadive.tools/api-key)\n *\n * Optional:\n * DATADIVE_API_BASE_URL - override the API base URL (defaults to https://api.datadive.tools)\n */\n\nexport interface Config {\n apiKey: string;\n baseUrl: string;\n}\n\nconst DEFAULT_BASE_URL = \"https://api.datadive.tools\";\nconst KEY_HELP_URL = \"https://2.datadive.tools/api-key\";\n\nexport function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {\n const apiKey = (env.DATADIVE_API_KEY ?? \"\").trim();\n if (!apiKey) {\n throw new Error(\n `DATADIVE_API_KEY environment variable is required. Generate one at ${KEY_HELP_URL} ` +\n `and add it to your MCP client config under env.DATADIVE_API_KEY.`,\n );\n }\n\n const rawBase = (env.DATADIVE_API_BASE_URL ?? DEFAULT_BASE_URL).trim();\n // Normalize: strip trailing slashes so we can append \"/v1/...\" paths cleanly.\n const baseUrl = rawBase.replace(/\\/+$/, \"\");\n\n return { apiKey, baseUrl };\n}\n","/**\n * Builds the MCP server: registers each tool from the registry with the SDK.\n *\n * Error handling: if a tool handler throws (most commonly an ApiError from the\n * HTTP client), we surface the message back through MCP as a tool-level error\n * (`isError: true`). The LLM sees the message and can react — e.g. tell the\n * user to regenerate their API key on a 401.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { Config } from \"./config.js\";\nimport { allTools } from \"./tools/index.js\";\nimport { ApiError } from \"./http/errors.js\";\nimport { PKG_VERSION, takeUpgradeNotice } from \"./http/client.js\";\n\nexport function buildServer(config: Config): McpServer {\n const server = new McpServer({\n name: \"datadive\",\n version: PKG_VERSION,\n });\n\n for (const tool of allTools) {\n server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema,\n },\n async (args: Record<string, unknown>) => {\n try {\n const data = await tool.handler(args, { config });\n const content = [\n {\n type: \"text\" as const,\n text: JSON.stringify(data, null, 2),\n },\n ];\n // If the backend signaled a newer release, append a one-time upgrade\n // nudge so the model relays it to the user. takeUpgradeNotice() returns\n // null after the first time, so this fires at most once per session.\n const notice = takeUpgradeNotice();\n if (notice) {\n content.push({\n type: \"text\" as const,\n text: `⚠️ datadive-mcp update available — ${notice}`,\n });\n }\n return { content };\n } catch (err) {\n return {\n isError: true,\n content: [\n {\n type: \"text\" as const,\n text: err instanceof ApiError ? err.message : err instanceof Error ? err.message : String(err),\n },\n ],\n };\n }\n },\n );\n }\n\n return server;\n}\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { NicheList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n currentPage: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Items per page (max 100). Defaults to 20.\"),\n};\n\nexport const listNichesTool: ToolDefinition<typeof inputSchema> = {\n name: \"list_niches\",\n title: \"List DataDive Niches\",\n description:\n \"Use this first when the user asks about their niches, or to find a `nicheId` for use with \" +\n \"`get_niche_keywords`, `get_niche_competitors`, or `get_ranking_juice`. \" +\n \"Retrieves a paginated list of Niches. Each Niche represents a market segment or product \" +\n \"category being tracked. Returns nicheId, heroKeyword, nicheLabel, marketplace (com/uk/de/...), \" +\n \"and latestResearchDate per niche, plus pagination metadata (currentPage, pageSize, total, \" +\n \"lastPage, hasNext, hasPrev).\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<NicheList>(\n { config: ctx.config, toolName: \"list_niches\" },\n \"/v1/niches\",\n { currentPage: args.currentPage, pageSize: args.pageSize },\n );\n },\n};\n","/**\n * Error mapping for the DataDive /v1 API.\n *\n * The MCP server is a thin HTTP shim — when api.datadive.tools returns an error,\n * we want the LLM (and ultimately the user) to see a useful, actionable message\n * rather than \"Request failed\". `ApiError.fromHttp` turns an HTTP status + body\n * into one of those messages.\n *\n * Source of truth for status semantics:\n * datadive-backend/src/external-api/auth/api-key.guard.ts (401/402 logic)\n * datadive-backend/src/external-api/external-api-v1.controller.ts (per-route docs)\n */\n\nconst KEY_HELP_URL = \"https://2.datadive.tools/api-key\";\n\nexport type ApiErrorKind =\n | \"auth\"\n | \"payment\"\n | \"forbidden\"\n | \"not_found\"\n | \"bad_request\"\n | \"rate_limit\"\n | \"server\"\n | \"network\"\n | \"http\";\n\nexport class ApiError extends Error {\n public readonly kind: ApiErrorKind;\n public readonly status: number;\n public readonly body: unknown;\n\n constructor(kind: ApiErrorKind, status: number, message: string, body?: unknown) {\n super(message);\n this.name = \"ApiError\";\n this.kind = kind;\n this.status = status;\n this.body = body;\n }\n\n static fromHttp(status: number, body: unknown): ApiError {\n const serverMsg = extractMessage(body);\n\n if (status === 400) {\n return new ApiError(\n \"bad_request\",\n 400,\n serverMsg ? `Bad request: ${serverMsg}` : \"Bad request: invalid parameters.\",\n body,\n );\n }\n if (status === 401) {\n return new ApiError(\n \"auth\",\n 401,\n `Authentication failed: your DATADIVE_API_KEY is invalid or expired. Generate a new key at ${KEY_HELP_URL}.`,\n body,\n );\n }\n if (status === 402) {\n return new ApiError(\n \"payment\",\n 402,\n \"Subscription is inactive or paused. Resume billing at https://2.datadive.tools to use the API.\",\n body,\n );\n }\n if (status === 403) {\n return new ApiError(\n \"forbidden\",\n 403,\n serverMsg\n ? `Forbidden: ${serverMsg}`\n : \"Forbidden: this API key cannot access the requested resource.\",\n body,\n );\n }\n if (status === 404) {\n return new ApiError(\"not_found\", 404, serverMsg ? `Not found: ${serverMsg}` : \"Resource not found.\", body);\n }\n if (status === 429) {\n return new ApiError(\"rate_limit\", 429, \"Rate limit exceeded. Wait a few seconds and retry.\", body);\n }\n if (status >= 500) {\n return new ApiError(\n \"server\",\n status,\n `DataDive API error (${status}). ${serverMsg ?? \"Please try again.\"}`.trim(),\n body,\n );\n }\n return new ApiError(\"http\", status, serverMsg ?? `HTTP ${status}`, body);\n }\n}\n\nfunction extractMessage(body: unknown): string | null {\n if (!body || typeof body !== \"object\") return null;\n const b = body as Record<string, unknown>;\n // NestJS conventional error shapes: { message: string | string[] } or { error, message }.\n if (typeof b.message === \"string\") return b.message;\n if (Array.isArray(b.message) && b.message.every((m) => typeof m === \"string\")) {\n return (b.message as string[]).join(\"; \");\n }\n if (typeof b.error === \"string\") return b.error;\n return null;\n}\n","{\n \"name\": \"@datadive-tools/mcp\",\n \"version\": \"0.5.0\",\n \"description\": \"MCP server for DataDive — query your niches, keywords, competitors, and Rank Radar data from Claude Desktop, Claude Code, or Cursor.\",\n \"type\": \"module\",\n \"bin\": {\n \"datadive-mcp\": \"./dist/index.js\"\n },\n \"main\": \"./dist/index.js\",\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"engines\": {\n \"node\": \">=22\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest run\",\n \"test:coverage\": \"vitest run --coverage --coverage.include=\\\"src/**\\\" --coverage.reporter=json-summary --coverage.reporter=text\",\n \"test:watch\": \"vitest\",\n \"test:smoke\": \"DATADIVE_SMOKE=1 vitest run test/smoke.test.ts\",\n \"lint\": \"eslint .\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"npm run lint && npm run typecheck && npm run test && npm run build\"\n },\n \"keywords\": [\n \"mcp\",\n \"model-context-protocol\",\n \"datadive\",\n \"amazon\",\n \"claude\"\n ],\n \"author\": \"DataDive\",\n \"license\": \"MIT\",\n \"homepage\": \"https://github.com/Data-Dive-Tools/datadive-mcp\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Data-Dive-Tools/datadive-mcp.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/Data-Dive-Tools/datadive-mcp/issues\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.0.0\",\n \"zod\": \"^3.23.0\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.0\",\n \"@types/node\": \"^20.0.0\",\n \"@typescript-eslint/eslint-plugin\": \"^8.0.0\",\n \"@typescript-eslint/parser\": \"^8.0.0\",\n \"@vitest/coverage-v8\": \"4.1.8\",\n \"eslint\": \"^9.0.0\",\n \"prettier\": \"^3.0.0\",\n \"tsup\": \"^8.0.0\",\n \"typescript\": \"~5.9.0\",\n \"vitest\": \"4.1.8\"\n }\n}\n","/**\n * HTTP client for the DataDive /v1 API.\n *\n * Responsibilities:\n * 1. Attach `x-api-key` from config to every request.\n * 2. Tag the User-Agent with the package version + tool name so backend access\n * logs can attribute usage per tool (no separate telemetry endpoint needed).\n * 3. Map HTTP errors via `ApiError.fromHttp`.\n * 4. Unwrap the `ResponseDto<T>` envelope (`{ message?, success?, data }`)\n * while preserving bare `PaginationResponse<T>` bodies (which need their\n * pagination metadata to reach the LLM).\n *\n * Envelope detection (verified against datadive-backend):\n * - GET /v1/niches -> NicheList extends PaginationResponse<NicheItem> (BARE)\n * - GET /v1/niches/rank-radars -> ResponseDto<ExternalRankRadarListResponseDto>\n * where the inner DTO IS itself paginated.\n * - All other read endpoints -> ResponseDto<T> (UNWRAP)\n *\n * Heuristic: if the body has `data` AND any pagination key (currentPage, lastPage,\n * hasNext, hasPrev, pageSize, total), it's a PaginationResponse — return as-is.\n * Otherwise if the body has `data`, it's a ResponseDto envelope — return body.data.\n *\n * Cite: datadive-backend/src/common/pagination/pagination.dto.ts (pagination keys)\n * datadive-backend/src/common/dto/response.dto.ts (envelope shape)\n */\n\nimport type { Config } from \"../config.js\";\nimport { ApiError } from \"./errors.js\";\nimport { version } from \"../../package.json\";\n\n/**\n * The running package version, inlined from package.json at build time by\n * tsup/esbuild (and by vite under vitest). Single source of truth — no manual\n * bump here, so it can never drift from what's published to npm.\n *\n * Written into the User-Agent header, and compared against the backend's\n * advertised latest version (see noteLatestVersion) to nudge stale installs.\n */\nexport const PKG_VERSION: string = version;\n\n/** Response header the DataDive backend uses to advertise the latest published MCP version. */\nconst LATEST_VERSION_HEADER = \"x-datadive-mcp-latest\";\n\n/**\n * One-time upgrade notice. Armed when the backend advertises a version newer than\n * the one we're running; consumed (and then suppressed for the rest of the session)\n * by takeUpgradeNotice(). We surface it once per process so we don't nag on every call.\n */\nlet pendingUpgradeNotice: string | null = null;\nlet hasWarned = false;\n\n/**\n * Compares dotted version strings (major.minor.patch). Pre-release / build suffixes\n * are stripped — a stable release is the signal we act on. Returns true iff `latest`\n * is strictly newer than `current`. Exported for unit testing.\n */\nexport function isNewerVersion(latest: string, current: string): boolean {\n const parse = (v: string) => v.split(/[-+]/)[0]!.split(\".\").map((n) => parseInt(n, 10) || 0);\n const a = parse(latest);\n const b = parse(current);\n for (let i = 0; i < 3; i++) {\n const da = a[i] ?? 0;\n const db = b[i] ?? 0;\n if (da !== db) return da > db;\n }\n return false;\n}\n\n/** Records the advertised latest version; arms a one-time notice if we're behind. Never throws. */\nfunction noteLatestVersion(latest: string | null): void {\n if (!latest || hasWarned) return;\n if (isNewerVersion(latest, PKG_VERSION)) {\n pendingUpgradeNotice =\n `A newer version of datadive-mcp is available (${latest}; you are running ${PKG_VERSION}). ` +\n `Update by reinstalling the latest from npm — e.g. \\`npm install -g @datadive-tools/mcp@latest\\` — ` +\n `or bump the @datadive-tools/mcp version in your MCP client config, then restart the client.`;\n }\n}\n\n/**\n * Returns a pending upgrade notice once, then suppresses further notices for the rest\n * of the session. Called when assembling a tool result so the LLM can relay it to the\n * user. Returns null when there's nothing to surface.\n */\nexport function takeUpgradeNotice(): string | null {\n if (!pendingUpgradeNotice) return null;\n const notice = pendingUpgradeNotice;\n pendingUpgradeNotice = null;\n hasWarned = true;\n return notice;\n}\n\nconst PAGINATION_KEYS = [\"currentPage\", \"lastPage\", \"hasNext\", \"hasPrev\", \"pageSize\", \"total\"] as const;\n\nexport interface RequestContext {\n config: Config;\n /** Tool name used to tag the User-Agent header for per-tool log attribution. */\n toolName: string;\n}\n\nexport async function httpGet<T>(ctx: RequestContext, path: string, query?: Record<string, unknown>): Promise<T> {\n const url = buildUrl(ctx.config.baseUrl, path, query);\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: \"GET\",\n headers: {\n \"x-api-key\": ctx.config.apiKey,\n accept: \"application/json\",\n \"user-agent\": userAgent(ctx.toolName),\n },\n });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new ApiError(\"network\", 0, `Network error reaching ${url}: ${msg}`);\n }\n\n // The backend advertises the latest published MCP version on every response\n // (including errors); arm a one-time upgrade notice if we're behind.\n noteLatestVersion(res.headers.get(LATEST_VERSION_HEADER));\n\n const text = await res.text();\n let body: unknown;\n try {\n body = text.length > 0 ? JSON.parse(text) : null;\n } catch {\n body = text;\n }\n\n if (!res.ok) {\n throw ApiError.fromHttp(res.status, body);\n }\n\n return unwrap<T>(body);\n}\n\nfunction buildUrl(baseUrl: string, path: string, query?: Record<string, unknown>): string {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n const u = new URL(`${baseUrl}${normalizedPath}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined || v === null) continue;\n u.searchParams.set(k, String(v));\n }\n }\n return u.toString();\n}\n\nfunction userAgent(toolName: string): string {\n return `datadive-mcp/${PKG_VERSION} tool/${toolName}`;\n}\n\n/**\n * Unwraps a ResponseDto<T> envelope while preserving bare PaginationResponse bodies.\n * Exported for unit testing.\n */\nexport function unwrap<T>(body: unknown): T {\n if (!isObject(body)) return body as T;\n if (!(\"data\" in body)) return body as T;\n // If pagination metadata is present at the top level, return as-is.\n for (const key of PAGINATION_KEYS) {\n if (key in body) return body as T;\n }\n // Plain ResponseDto envelope -> unwrap.\n return (body as { data: T }).data;\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { GetMasterKeywordListResult } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n nicheId: z.string().min(1).describe(\"The unique identifier of the Niche (from `list_niches`).\"),\n};\n\nexport const getNicheKeywordsTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_niche_keywords\",\n title: \"Get Master Keyword List for a Niche\",\n description:\n \"Use this when the user asks about keywords, search terms, or search volume for a niche. \" +\n \"Retrieves the master keyword list for the specified Niche — the relevant search terms \" +\n \"monitored for ranking and performance metrics. For each keyword, returns search volume, \" +\n \"relevancy (numeric score or \\\"Outlier\\\"), and competitor ASIN organic ranks \" +\n \"(asinRanks: { ASIN -> rank | null }). Also returns the latestResearchDate.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<GetMasterKeywordListResult>(\n { config: ctx.config, toolName: \"get_niche_keywords\" },\n `/v1/niches/${encodeURIComponent(args.nicheId)}/keywords`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { NicheRoots } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n nicheId: z.string().min(1).describe(\"The unique identifier of the Niche (from `list_niches`).\"),\n};\n\nexport const getNicheRootsTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_niche_roots\",\n title: \"Get Keyword Roots for a Niche\",\n description:\n \"Use this when the user wants to find the highest-impact words across a niche's keywords, asks about \" +\n \"'keyword roots', or wants to prioritize terms for a listing. \" +\n \"Retrieves the keyword lexical roots for the Niche — individual words or word-combinations extracted \" +\n \"from the Master Keyword List (e.g. 'bluetooth headphones' yields roots 'bluetooth', 'headphones', \" +\n \"'bluetooth headphones'). Returns `roots` and `normalizedRoots` tables, each item with root, frequency \" +\n \"(how many keywords contain it), broadSearchVolume (summed search volume of those keywords), and \" +\n \"broadSearchVolumeRatio (0-1, relative to the top root), plus the per-keyword breakdowns and \" +\n \"latestResearchDate.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<NicheRoots>(\n { config: ctx.config, toolName: \"get_niche_roots\" },\n `/v1/niches/${encodeURIComponent(args.nicheId)}/roots`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { GetCompetitorListResult } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n nicheId: z.string().min(1).describe(\"The unique identifier of the Niche (from `list_niches`).\"),\n};\n\nexport const getNicheCompetitorsTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_niche_competitors\",\n title: \"Get Competitors and Niche Statistics\",\n description:\n \"Use this for competitor ASINs, sales/revenue benchmarks, or niche opportunity scoring. \" +\n \"Retrieves the list of Competitors within the specified Niche along with Niche statistics. \" +\n \"For the Niche: keyword statistics, opportunity evaluation, benchmark median values, and \" +\n \"overall competitor strength assessment. For each Competitor: ASIN, sales, revenue, ratings, \" +\n \"reviews, price, image URL, and ranking data.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<GetCompetitorListResult>(\n { config: ctx.config, toolName: \"get_niche_competitors\" },\n `/v1/niches/${encodeURIComponent(args.nicheId)}/competitors`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { NicheRankingJuices } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n nicheId: z.string().min(1).describe(\"The unique identifier of the Niche (from `list_niches`).\"),\n};\n\nexport const getRankingJuiceTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_ranking_juice\",\n title: \"Get Ranking Juices for a Niche\",\n description:\n \"Use this when the user asks 'how do I rank higher', 'what's my ranking juice', or wants \" +\n \"listing-optimization guidance. \" +\n \"Retrieves the Ranking Juices for each Competitor within the specified Niche. Ranking Juice is \" +\n \"DataDive's proprietary metric identifying the key factors driving search-ranking success \" +\n \"for each Competitor's listing. Returns currentListing and optimizedListing breakdowns \" +\n \"(rankingJuice + per-property contributions: title, bullets, description) plus per-competitor \" +\n \"listing scores and the latestResearchDate.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<NicheRankingJuices>(\n { config: ctx.config, toolName: \"get_ranking_juice\" },\n `/v1/niches/${encodeURIComponent(args.nicheId)}/ranking-juices`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport { RANK_RADAR_STATUSES, type RankRadarList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Items per page (max 100). Defaults to 20.\"),\n nicheId: z\n .string()\n .min(1)\n .optional()\n .describe(\"Filter Rank Radars by Niche identifier. Use after `list_niches`.\"),\n status: z\n .enum(RANK_RADAR_STATUSES)\n .optional()\n .describe(\n \"Filter by Rank Radar status. By default, returns only ACTIVE Rank Radars. Allowed: ACTIVE, PAUSED, ARCHIVED.\",\n ),\n searchText: z.string().optional().describe(\"Filter Rank Radars by ASIN or product title.\"),\n};\n\nexport const listRankRadarsTool: ToolDefinition<typeof inputSchema> = {\n name: \"list_rank_radars\",\n title: \"List Rank Radars\",\n description:\n \"Use this to find a `rankRadarId` before calling `get_rank_radar_data`. Filter by `nicheId` \" +\n \"if the user has already identified a niche. \" +\n \"Retrieves a paginated list of Rank Radars — keyword-rank trackers monitoring organic and \" +\n \"sponsored positions for specific ASINs over time. Each item includes id, asin (with id, krtId, \" +\n \"asin), marketplace, keywordCount, title, imageUrl, and summary metrics: top10KW, top10SV, \" +\n \"top50KW, top50SV. Supports pagination metadata (currentPage, pageSize, total, lastPage, \" +\n \"hasNext, hasPrev).\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<RankRadarList>(\n { config: ctx.config, toolName: \"list_rank_radars\" },\n \"/v1/niches/rank-radars\",\n {\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n nicheId: args.nicheId,\n status: args.status,\n searchText: args.searchText,\n },\n );\n },\n};\n","/**\n * Hand-mirrored DTOs from the DataDive backend (v1 external API).\n *\n * Source of truth (in this priority order):\n * 1. Live Swagger: https://developer.datadive.tools/docs#/v1\n * (machine-readable: https://developer.datadive.tools/docs-json)\n * 2. Backend DTOs: datadive-backend/src/external-api/dto/*.ts\n * datadive-backend/src/niche-research/dto/rank-radar.response.dto.ts\n * datadive-backend/src/common/dto/response.dto.ts\n * datadive-backend/src/common/pagination/pagination.dto.ts\n * 3. Controller: datadive-backend/src/external-api/external-api-v1.controller.ts\n *\n * Last synced: 2026-06-17.\n *\n * The MCP server forwards JSON straight to the LLM, so deeply-nested DTOs are\n * intentionally typed loosely (with `unknown` or pass-through Records) where\n * the TS surface doesn't add safety. Pin tighter as use cases require.\n */\n\n// ─── Envelope + pagination ───────────────────────────────────────────────────\n\n/** Generic NestJS response envelope: { message?, success?, data? }. */\nexport interface ResponseEnvelope<T> {\n message?: string;\n /** @deprecated — use HTTP status as the success indicator. */\n success?: boolean;\n data?: T | null;\n}\n\n/** Standard pagination envelope returned by list endpoints. */\nexport interface PaginationResponse<T> {\n data: T[];\n currentPage: number;\n pageSize: number;\n total: number;\n lastPage: number;\n hasNext: boolean;\n hasPrev: boolean;\n}\n\n/**\n * ISO-8601 date or timestamp, mirroring the backend's `@IsISO8601()` (date-only\n * allowed). Shared by the date/timestamp query params across /v1 tools\n * (alerts `updatedSince`, usage `startDate`/`endDate`).\n */\nexport const ISO_8601 = /^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/**\n * Marketplace codes accepted by `marketplace` params across /v1 endpoints\n * (alerts, inventory). Mirrors the backend's `SupportedMarketplaceEnum`.\n */\nexport const SUPPORTED_MARKETPLACES = [\n \"com\",\n \"ca\",\n \"co.uk\",\n \"com.mx\",\n \"in\",\n \"fr\",\n \"de\",\n \"es\",\n \"it\",\n \"co.jp\",\n] as const;\n\n// ─── /v1/niches (NicheList = PaginationResponse<NicheItem>) ─────────────────\n\nexport interface NicheItem {\n nicheId: string;\n heroKeyword: string;\n nicheLabel: string;\n /** Amazon marketplace TLD: \"com\", \"uk\", \"de\", etc. */\n marketplace: string;\n /** ISO date string when the Niche was last researched. Nullable. */\n latestResearchDate: string | null;\n}\n\nexport type NicheList = PaginationResponse<NicheItem>;\n\n// ─── /v1/niches/:nicheId/keywords (GetMasterKeywordListResult, wrapped) ─────\n\n/** Map of competitor ASIN -> rank (or null when unranked). */\nexport type AsinRanks = Record<string, number | null>;\n\nexport interface MasterKeyword {\n keyword: string;\n searchVolume: number;\n /** \"Outlier\" or a numeric relevancy score. */\n relevancy: string | number;\n asinRanks: AsinRanks;\n}\n\nexport interface GetMasterKeywordListResult {\n keywords: MasterKeyword[];\n /** ISO date string. */\n latestResearchDate: string;\n}\n\n// ─── /v1/niches/:nicheId/competitors (GetCompetitorListResult, wrapped) ─────\n\n/**\n * Niche competitors response — many nested DTOs from the backend (MklStatisticsData,\n * OpportunityEvaluation, MklBenchmark, CompetitorsStrength, AsinListItem). We type\n * the outer shape and leave the inner objects as opaque records; the LLM sees the\n * full JSON and can reason about it. Tighten if a specific consumer needs it.\n */\nexport interface GetCompetitorListResult {\n /** Marketplace enum (AmazonStore in backend). */\n marketplace: string;\n statistics: Record<string, unknown>;\n opportunityEvaluation: Record<string, unknown>;\n benchmark: Record<string, unknown>;\n competitorsStrength: Record<string, unknown>;\n competitors: Array<Record<string, unknown>>;\n latestResearchDate: string;\n}\n\n// ─── /v1/niches/:nicheId/ranking-juices (NicheRankingJuices, wrapped) ───────\n\nexport interface RankingJuiceProperty {\n rankingJuice: number;\n}\n\nexport interface ListingRankingJuice {\n rankingJuice: number;\n title: RankingJuiceProperty;\n bullets: RankingJuiceProperty;\n description: RankingJuiceProperty;\n}\n\nexport interface CompetitorRankingJuice {\n asin: string;\n listing: ListingRankingJuice;\n}\n\nexport interface NicheRankingJuices {\n currentListing: ListingRankingJuice;\n optimizedListing: ListingRankingJuice;\n competitors: CompetitorRankingJuice[];\n latestResearchDate: string;\n}\n\n// ─── /v1/niches/rank-radars (ExternalRankRadarListResponseDto, wrapped) ─────\n\nexport interface RankRadarAsin {\n id: string;\n krtId: string;\n asin: string;\n}\n\nexport interface RankRadarItem {\n id: string;\n asin: RankRadarAsin;\n marketplace: string;\n keywordCount: number;\n title: string;\n imageUrl: string;\n top10KW: number | null;\n top10SV: number | null;\n top50KW: number | null;\n top50SV: number | null;\n}\n\nexport type RankRadarList = PaginationResponse<RankRadarItem>;\n\n/** Allowed values for the `status` query param on /v1/niches/rank-radars. */\nexport const RANK_RADAR_STATUSES = [\"ACTIVE\", \"PAUSED\", \"ARCHIVED\"] as const;\nexport type RankRadarStatus = (typeof RANK_RADAR_STATUSES)[number];\n\n// ─── /v1/niches/rank-radars/:rankRadarId (KrtKeywordResponseDto[], wrapped) ─\n\nexport interface KrtAsinRank {\n /** ISO date string. */\n date: string;\n organicRank?: number | null;\n impressionRank?: number | null;\n}\n\nexport interface KrtKeyword {\n id: string;\n keyword: string;\n searchVolume: number | null;\n ranks: KrtAsinRank[];\n /** Highlight annotations (KrtHighlightDto in backend); kept opaque for MVP. */\n highlights: Array<Record<string, unknown>>;\n}\n\nexport type RankRadarKeywordList = KrtKeyword[];\n\n// ─── /v1/sellers/:sellerId/marketplaces/:marketplace/asins/:asin/inventory ────\n// (InventoryByFcResponseDto, wrapped)\n\nexport interface InventoryByFcItem {\n /** Fulfillment center code. */\n fc: string;\n /** State or region code where the FC is located, when known. */\n state: string;\n /** Units of sellable inventory currently at this FC. May be 0 when stock is out. */\n availableStock: number;\n /** Share of the ASIN's total sellable inventory at this FC, as a 0..1 fraction. */\n availableStockPercentage: number;\n}\n\nexport interface InventoryByFcResponse {\n asin: string;\n sellerId: string;\n /** Marketplace enum: \"com\", \"ca\", \"co.uk\", \"com.mx\", \"in\", \"fr\", \"de\", \"es\", \"it\", \"co.jp\". */\n marketplace: string;\n /** ISO timestamp of last successful ingestion. Null if none in the last 30 days. */\n lastUpdatedAt: string | null;\n totalSellableUnits: number;\n distribution: InventoryByFcItem[];\n}\n\n// ─── /v1/alerts/indexing-issues (IndexingIssueAlertListDto, bare) ───────────\n\n/**\n * Allowed values for the `status` query param on the /v1/alerts/* endpoints.\n * `active` is the server-side default; dismissed alerts are never returned.\n */\nexport const ALERT_STATUSES = [\"active\", \"resolved\", \"all\"] as const;\nexport type AlertStatus = (typeof ALERT_STATUSES)[number];\n\nexport interface IndexingIssueAlertItem {\n id: number;\n /** The ASIN that is no longer indexed for its tracked keywords. */\n asin: string;\n title: string | null;\n imageUrl: string | null;\n /** True when the ASIN is a parent of a variation family. */\n isParent: boolean;\n sellerId: string;\n marketplace: string;\n /** ISO timestamp of when the alert was most recently surfaced. Updates each time it re-fires. */\n lastAlertedAt: string;\n /** ISO timestamp of when the alert was resolved, or null if still active. */\n resolvedAt: string | null;\n}\n\nexport type IndexingIssueAlertList = PaginationResponse<IndexingIssueAlertItem>;\n\n// ─── /v1/alerts/blind-spend (BlindSpendAlertListDto, bare) ──────────────────\n\nexport interface BlindSpendSearchTerm {\n /** The customer search term that wasted spend. */\n term: string;\n spend: number | null;\n sales: number | null;\n clicks: number | null;\n /** Conversion rate as a 0..1 fraction. */\n cvr: number | null;\n impressions: number | null;\n}\n\nexport interface BlindSpendAlertItem {\n id: number;\n asin: string | null;\n title: string | null;\n imageUrl: string | null;\n sellerId: string;\n marketplace: string;\n /** ISO timestamp of when the alert was most recently surfaced. Updates each time it re-fires. */\n lastAlertedAt: string;\n /** ISO timestamp of when the alert was resolved, or null if still active. */\n resolvedAt: string | null;\n /** Total ad spend across the unresolved wasted-spend search terms. */\n wastedSpend: number;\n totalKeywordCount: number;\n unresolvedKeywordCount: number;\n /** The unresolved wasted-spend search terms. */\n searchTerms: BlindSpendSearchTerm[];\n}\n\nexport type BlindSpendAlertList = PaginationResponse<BlindSpendAlertItem>;\n\n// ─── Billable features (shared by /v1/quota and /v1/usage) ───────────────────\n\n/**\n * Billable feature types. These are both the keys of the `quota.features` object\n * and the allowed values of the `type` filter on /v1/usage. Mirrors the backend's\n * billable-feature enum.\n */\nexport const BILLABLE_FEATURE_TYPES = [\n \"DIVED_ASINS\",\n \"PRODUCT_BRIEF_ASINS\",\n \"AI_COPYWRITER_PROMPTS\",\n \"RANK_RADAR_KEYWORDS\",\n] as const;\nexport type BillableFeatureType = (typeof BILLABLE_FEATURE_TYPES)[number];\n\n// ─── /v1/niches/:nicheId/roots (ExternalRootResponseDto[], wrapped) ─────────\n\nexport interface RootsTableItem {\n /** A word or word-combination extracted from the master keyword list. */\n root: string;\n /** Count of keywords in the master list that contain this root. */\n frequency: number;\n /** Sum of search volume across all original keywords containing this root. */\n broadSearchVolume: number;\n /** broadSearchVolume / maxBroadSearchVolume, as a 0..1 fraction. */\n broadSearchVolumeRatio: number;\n}\n\n/**\n * Keyword-roots analysis for a Niche. `keywords` and `consolidatedKeywords` are\n * the per-keyword breakdowns (kept opaque — the LLM sees the full JSON); `roots`\n * and `normalizedRoots` are the ranked root tables.\n *\n * Note: the OpenAPI spec types the endpoint's `data` as an array, but the live\n * API returns a single object (verified against api-qa, 2026-06-17). The client's\n * unwrap() strips the `{ data }` envelope, so the tool returns this object directly.\n */\nexport interface NicheRoots {\n keywords: Array<Record<string, unknown>>;\n consolidatedKeywords: Array<Record<string, unknown>>;\n roots: RootsTableItem[];\n normalizedRoots: RootsTableItem[];\n /** ISO date string of the last successful research for the niche. */\n latestResearchDate: string;\n}\n\n// ─── /v1/quota (ExternalQuotaResponseDto) ───────────────────────────────────\n\nexport interface QuotaFeature {\n /** Current usage count. Null when not applicable to the plan. */\n used: number | null;\n /** Quota capacity. Null when unlimited / not applicable. */\n capacity: number | null;\n}\n\nexport interface Quota {\n /** ISO-8601 timestamp of the next quota reset. Null when no reset is scheduled. */\n nextRefreshDate: string | null;\n /** Per-billable-feature usage and capacity. */\n features: Record<BillableFeatureType, QuotaFeature>;\n}\n\n// ─── /v1/usage (ExternalUsageLogListDto, bare PaginationResponse) ───────────\n\nexport interface UsageLogItem {\n /** Name of the user who performed the action. Null when unknown. */\n name: string | null;\n email: string;\n /** Number of tokens consumed. */\n qty: number;\n type: BillableFeatureType;\n /** Specific action performed (e.g. \"RANK_RADAR_CREATE\"). Null when not set. */\n action: string | null;\n nicheId: string | null;\n nicheName: string | null;\n rankRadarId: string | null;\n /** ISO timestamp of when the usage was recorded. */\n date: string;\n}\n\nexport type UsageLogList = PaginationResponse<UsageLogItem>;\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { RankRadarKeywordList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\n/** yyyy-mm-dd matcher used by both startDate and endDate. */\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nconst inputSchema = {\n rankRadarId: z\n .string()\n .uuid()\n .describe(\"The Rank Radar UUID (from `list_rank_radars`).\"),\n startDate: z\n .string()\n .regex(ISO_DATE, \"startDate must be in yyyy-mm-dd format\")\n .describe(\"Start date for the ranking data range, yyyy-mm-dd (e.g. 2024-03-26).\"),\n endDate: z\n .string()\n .regex(ISO_DATE, \"endDate must be in yyyy-mm-dd format\")\n .describe(\"End date for the ranking data range, yyyy-mm-dd (e.g. 2024-04-26). Must be on or after startDate.\"),\n};\n\nexport const getRankRadarDataTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_rank_radar_data\",\n title: \"Get Keyword Rankings for a Rank Radar\",\n description:\n \"Use this to analyze keyword ranking trends over time. Requires startDate and endDate (yyyy-mm-dd). \" +\n \"Retrieves historical keyword ranking data for the specified Rank Radar within the date range. \" +\n \"Returns an array of tracked keywords; each has id, keyword, searchVolume, ranks (per-day \" +\n \"{ date, organicRank, impressionRank }), and any highlight annotations. Use after \" +\n \"`list_rank_radars` to discover a `rankRadarId`.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<RankRadarKeywordList>(\n { config: ctx.config, toolName: \"get_rank_radar_data\" },\n `/v1/niches/rank-radars/${encodeURIComponent(args.rankRadarId)}`,\n { startDate: args.startDate, endDate: args.endDate },\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport { SUPPORTED_MARKETPLACES, type InventoryByFcResponse } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n sellerId: z\n .string()\n .min(1)\n .describe(\n \"Amazon seller account ID as connected to DataDive. Find it on the Connections page at https://2.datadive.tools — there is no MCP discovery tool for sellers yet.\",\n ),\n marketplace: z\n .enum(SUPPORTED_MARKETPLACES)\n .describe('Amazon marketplace code, e.g. \"com\" for amazon.com or \"co.uk\" for amazon.co.uk.'),\n asin: z\n .string()\n .regex(/^[A-Z0-9]{10}$/, \"ASIN must be 10 uppercase alphanumeric characters (e.g. B08XYZ1234).\")\n .describe(\n \"Amazon Standard Identification Number (10 uppercase alphanumeric characters, e.g. B08XYZ1234).\",\n ),\n};\n\nexport const getAsinInventoryDistributionTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_asin_inventory_distribution\",\n title: \"Get Per-Fulfillment-Center Inventory Distribution for an ASIN\",\n description:\n \"Use this when the user asks about inventory levels, stock by fulfillment center, \" +\n \"or where their units are sitting across Amazon's fulfillment network for a specific ASIN. \" +\n \"Requires the Amazon sellerId from the user's DataDive Connections page \" +\n \"(https://2.datadive.tools), the marketplace code, and the ASIN. Returns totalSellableUnits \" +\n \"and a per-FC `distribution` array (fc, state, availableStock, availableStockPercentage). \" +\n \"`lastUpdatedAt` may be null when no successful inventory ingestion has occurred in the last 30 days.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<InventoryByFcResponse>(\n { config: ctx.config, toolName: \"get_asin_inventory_distribution\" },\n `/v1/sellers/${encodeURIComponent(args.sellerId)}/marketplaces/${encodeURIComponent(\n args.marketplace,\n )}/asins/${encodeURIComponent(args.asin)}/inventory`,\n );\n },\n};\n","/**\n * Shared input schema for the /v1/alerts/* list tools. Both alert endpoints\n * accept the same backend query DTO (ExternalAlertsQueryDto), so the input\n * contract is defined once here and imported by each tool.\n */\n\nimport { z } from \"zod\";\nimport { ALERT_STATUSES, ISO_8601, SUPPORTED_MARKETPLACES } from \"../types/api.js\";\n\nexport const alertsQueryInputSchema = {\n sellerId: z\n .string()\n .min(1)\n .max(50)\n .optional()\n .describe('Filter to a single connected Amazon seller account ID, e.g. \"A1B2C3D4E5\".'),\n marketplace: z\n .enum(SUPPORTED_MARKETPLACES)\n .optional()\n .describe('Filter to a single Amazon marketplace code, e.g. \"com\" for amazon.com or \"co.uk\" for amazon.co.uk.'),\n status: z\n .enum(ALERT_STATUSES)\n .optional()\n .describe(\n \"Lifecycle filter. `active` (default) returns unresolved alerts, `resolved` returns resolved alerts, \" +\n \"`all` returns both. Dismissed alerts are never returned.\",\n ),\n updatedSince: z\n .string()\n .regex(ISO_8601, \"updatedSince must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)\")\n .optional()\n .describe(\n \"ISO-8601 timestamp; return only alerts surfaced at or after this time (filters on `lastAlertedAt`). \" +\n \"Use it to incrementally sync since your last poll. Defaults to the last 30 days when omitted.\",\n ),\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .describe(\"Items per page (max 50). Defaults to 20.\"),\n};\n","import { httpGet } from \"../http/client.js\";\nimport type { IndexingIssueAlertList } from \"../types/api.js\";\nimport { alertsQueryInputSchema } from \"./alert-query.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nexport const listIndexingIssueAlertsTool: ToolDefinition<typeof alertsQueryInputSchema> = {\n name: \"list_indexing_issue_alerts\",\n title: \"List Indexing-Issue Alerts\",\n description:\n \"Use this to find products that may have lost search visibility. Retrieves a paginated list of \" +\n \"indexing-issue alerts across the user's connected Amazon seller accounts — an alert fires when one of \" +\n \"their ASINs is no longer indexed for its tracked keywords. By default returns active (unresolved) alerts \" +\n \"from the last 30 days; filter by `sellerId`, `marketplace`, `status`, or `updatedSince` (for incremental \" +\n \"polling). Each item includes id, asin, title, imageUrl, isParent, sellerId, marketplace, lastAlertedAt, \" +\n \"and resolvedAt. Supports pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).\",\n inputSchema: alertsQueryInputSchema,\n handler: async (args, ctx) => {\n return await httpGet<IndexingIssueAlertList>(\n { config: ctx.config, toolName: \"list_indexing_issue_alerts\" },\n \"/v1/alerts/indexing-issues\",\n {\n sellerId: args.sellerId,\n marketplace: args.marketplace,\n status: args.status,\n updatedSince: args.updatedSince,\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","import { httpGet } from \"../http/client.js\";\nimport type { BlindSpendAlertList } from \"../types/api.js\";\nimport { alertsQueryInputSchema } from \"./alert-query.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nexport const listBlindSpendAlertsTool: ToolDefinition<typeof alertsQueryInputSchema> = {\n name: \"list_blind_spend_alerts\",\n title: \"List Blind-Spend (Wasted-Spend) Alerts\",\n description:\n \"Use this to find wasted PPC ad spend. Retrieves a paginated list of blind-spend alerts across the \" +\n \"user's connected Amazon seller accounts — an alert flags ad spend on customer search terms that produced \" +\n \"little or no sales. By default returns active (unresolved) alerts from the last 30 days; filter by \" +\n \"`sellerId`, `marketplace`, `status`, or `updatedSince` (for incremental polling). Each item includes id, \" +\n \"asin, title, imageUrl, sellerId, marketplace, lastAlertedAt, resolvedAt, wastedSpend (total ad spend \" +\n \"across unresolved terms), totalKeywordCount, unresolvedKeywordCount, and searchTerms — the unresolved \" +\n \"wasted-spend search terms, each with term, spend, sales, clicks, cvr (0-1), and impressions. Supports \" +\n \"pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).\",\n inputSchema: alertsQueryInputSchema,\n handler: async (args, ctx) => {\n return await httpGet<BlindSpendAlertList>(\n { config: ctx.config, toolName: \"list_blind_spend_alerts\" },\n \"/v1/alerts/blind-spend\",\n {\n sellerId: args.sellerId,\n marketplace: args.marketplace,\n status: args.status,\n updatedSince: args.updatedSince,\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","import { httpGet } from \"../http/client.js\";\nimport type { Quota } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {};\n\nexport const getQuotaTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_quota\",\n title: \"Get Quota Usage\",\n description:\n \"Use this when the user asks how much quota or how many tokens they have left, or before creating a \" +\n \"Niche Dive or Rank Radar to check remaining headroom. \" +\n \"Returns current quota usage and capacity for each billable feature — DIVED_ASINS (Dive tokens), \" +\n \"RANK_RADAR_KEYWORDS (tracked keywords), PRODUCT_BRIEF_ASINS, and AI_COPYWRITER_PROMPTS — each with \" +\n \"`used` and `capacity` (null when unlimited / not applicable), plus `nextRefreshDate` (ISO-8601 \" +\n \"timestamp of the next quota reset, or null). Takes no arguments.\",\n inputSchema,\n handler: async (_args, ctx) => {\n return await httpGet<Quota>({ config: ctx.config, toolName: \"get_quota\" }, \"/v1/quota\");\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport { BILLABLE_FEATURE_TYPES, ISO_8601, type UsageLogList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n type: z\n .enum(BILLABLE_FEATURE_TYPES)\n .optional()\n .describe(\"Filter to a single billable feature type. Omit to return all types.\"),\n search: z\n .string()\n .min(1)\n .optional()\n .describe(\"Case-insensitive partial match on the user's name or email.\"),\n startDate: z\n .string()\n .regex(ISO_8601, \"startDate must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)\")\n .optional()\n .describe(\"ISO-8601 date/timestamp; return only usage logs recorded on or after this time.\"),\n endDate: z\n .string()\n .regex(ISO_8601, \"endDate must be an ISO-8601 date or timestamp (e.g. 2026-05-31 or 2026-05-31T23:59:59Z)\")\n .optional()\n .describe(\"ISO-8601 date/timestamp; return only usage logs recorded on or before this time.\"),\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(200)\n .optional()\n .describe(\"Items per page (max 200). Defaults to 50.\"),\n};\n\nexport const listUsageTool: ToolDefinition<typeof inputSchema> = {\n name: \"list_usage\",\n title: \"List Billable Usage Logs\",\n description:\n \"Use this when the user asks who consumed tokens, how their quota was spent, or wants an audit of \" +\n \"billable activity over a date range. \" +\n \"Retrieves a paginated list of billable feature usage logs for the organization — each entry is a \" +\n \"token-consumption event (a dive, rank-radar creation, AI copywriter prompt, etc.). Filter by `type` \" +\n \"(billable feature), `search` (user name/email), and `startDate`/`endDate`. Each item includes name, \" +\n \"email, qty (tokens consumed), type, action (specific operation), nicheId/nicheName, rankRadarId, and \" +\n \"date, plus pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<UsageLogList>(\n { config: ctx.config, toolName: \"list_usage\" },\n \"/v1/usage\",\n {\n type: args.type,\n search: args.search,\n startDate: args.startDate,\n endDate: args.endDate,\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","/**\n * Tool registry. The order here is the order tools appear in `tools/list`\n * over the MCP transport, which biases LLM discovery — keep \"discovery\" tools\n * (the ones that return IDs needed by other tools) at the top.\n */\n\nimport { listNichesTool } from \"./list-niches.js\";\nimport { getNicheKeywordsTool } from \"./get-niche-keywords.js\";\nimport { getNicheRootsTool } from \"./get-niche-roots.js\";\nimport { getNicheCompetitorsTool } from \"./get-niche-competitors.js\";\nimport { getRankingJuiceTool } from \"./get-ranking-juice.js\";\nimport { listRankRadarsTool } from \"./list-rank-radars.js\";\nimport { getRankRadarDataTool } from \"./get-rank-radar-data.js\";\nimport { getAsinInventoryDistributionTool } from \"./get-asin-inventory-distribution.js\";\nimport { listIndexingIssueAlertsTool } from \"./list-indexing-issue-alerts.js\";\nimport { listBlindSpendAlertsTool } from \"./list-blind-spend-alerts.js\";\nimport { getQuotaTool } from \"./get-quota.js\";\nimport { listUsageTool } from \"./list-usage.js\";\nimport type { AnyTool } from \"./types.js\";\n\n// Note on the cast: each ToolDefinition<S> has a handler typed to its specific\n// schema; the registry needs a uniform shape. The MCP SDK validates incoming\n// args against `inputSchema` before calling the handler, so the cast is safe.\nexport const allTools: ReadonlyArray<AnyTool> = [\n listNichesTool,\n getNicheKeywordsTool,\n getNicheRootsTool,\n getNicheCompetitorsTool,\n getRankingJuiceTool,\n listRankRadarsTool,\n getRankRadarDataTool,\n getAsinInventoryDistributionTool,\n listIndexingIssueAlertsTool,\n listBlindSpendAlertsTool,\n getQuotaTool,\n listUsageTool,\n] as unknown as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C,MAAM;AAAA,YACpD,CAAC;AAAA,UACH;AACA,iBAAO,EAAE,QAAQ;AAAA,QACnB,SAAS,KAAK;AACZ,iBAAO;AAAA,YACL,SAAS;AAAA,YACT,SAAS;AAAA,cACP;AAAA,gBACE,MAAM;AAAA,gBACN,MAAM,eAAe,WAAW,IAAI,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,cAC/F;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;;;AFtDA,eAAe,OAAO;AACpB,MAAI;AACJ,MAAI;AACF,aAAS,WAAW;AAAA,EACtB,SAAS,KAAK;AAGZ,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,YAAQ,OAAO,MAAM,kBAAkB,GAAG;AAAA,CAAI;AAC9C,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,QAAM,SAAS,YAAY,MAAM;AACjC,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,QAAM,MAAM,eAAe,QAAS,IAAI,SAAS,IAAI,UAAW,OAAO,GAAG;AAC1E,UAAQ,OAAO,MAAM,yBAAyB,GAAG;AAAA,CAAI;AACrD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["KEY_HELP_URL","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","z","inputSchema","z","inputSchema","z"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/config.ts","../src/server.ts","../src/tools/list-niches.ts","../src/http/errors.ts","../package.json","../src/http/client.ts","../src/tools/get-niche-keywords.ts","../src/tools/get-niche-roots.ts","../src/tools/get-niche-competitors.ts","../src/tools/get-ranking-juice.ts","../src/tools/list-rank-radars.ts","../src/types/api.ts","../src/tools/get-rank-radar-data.ts","../src/tools/create-rank-radar.ts","../src/tools/confirm.ts","../src/tools/create-niche-dive.ts","../src/tools/get-dive-status.ts","../src/tools/list-seller-profiles.ts","../src/tools/get-seller-catalog.ts","../src/tools/seller-scoped.ts","../src/tools/get-seller-listing-changes.ts","../src/tools/get-asin-inventory-distribution.ts","../src/tools/alert-query.ts","../src/tools/list-indexing-issue-alerts.ts","../src/tools/list-blind-spend-alerts.ts","../src/tools/get-quota.ts","../src/tools/list-usage.ts","../src/tools/index.ts"],"sourcesContent":["/**\n * Entry point for the datadive-mcp stdio binary.\n *\n * Wired via package.json#bin -> dist/index.js so `npx -y @datadive-tools/mcp` runs it.\n * The shebang is added at build time by tsup.config.ts (banner.js).\n */\n\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { loadConfig } from \"./config.js\";\nimport { buildServer } from \"./server.js\";\n\nasync function main() {\n let config;\n try {\n config = loadConfig();\n } catch (err) {\n // Config errors (e.g. missing API key) are user-facing; print to stderr and exit\n // non-zero so the MCP client surfaces a real error rather than silently disconnecting.\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[datadive-mcp] ${msg}\\n`);\n process.exit(1);\n }\n\n const server = buildServer(config);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nmain().catch((err) => {\n const msg = err instanceof Error ? (err.stack ?? err.message) : String(err);\n process.stderr.write(`[datadive-mcp] fatal: ${msg}\\n`);\n process.exit(1);\n});\n","/**\n * Loads and validates the server's runtime configuration from environment.\n *\n * Required:\n * DATADIVE_API_KEY - your DataDive API key (generate at 2.datadive.tools/api-key)\n *\n * Optional:\n * DATADIVE_API_BASE_URL - override the API base URL (defaults to https://api.datadive.tools)\n * DATADIVE_AUTO_CONFIRM_WRITES - skip the confirm gate on token-spending write tools\n * (create_niche_dive, create_rank_radar). Truthy =\n * \"1\"/\"true\"/\"yes\" (case-insensitive). Defaults to false.\n */\n\nexport interface Config {\n apiKey: string;\n baseUrl: string;\n /**\n * When true, the token-spending write tools proceed without requiring `confirm: true`.\n * A user-controlled \"don't ask me again\" opt-out, set via DATADIVE_AUTO_CONFIRM_WRITES.\n */\n autoConfirmWrites: boolean;\n}\n\nconst DEFAULT_BASE_URL = \"https://api.datadive.tools\";\nconst KEY_HELP_URL = \"https://2.datadive.tools/api-key\";\n\nexport function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {\n const apiKey = (env.DATADIVE_API_KEY ?? \"\").trim();\n if (!apiKey) {\n throw new Error(\n `DATADIVE_API_KEY environment variable is required. Generate one at ${KEY_HELP_URL} ` +\n `and add it to your MCP client config under env.DATADIVE_API_KEY.`,\n );\n }\n\n const rawBase = (env.DATADIVE_API_BASE_URL ?? DEFAULT_BASE_URL).trim();\n // Normalize: strip trailing slashes so we can append \"/v1/...\" paths cleanly.\n const baseUrl = rawBase.replace(/\\/+$/, \"\");\n\n const autoConfirmWrites = [\"1\", \"true\", \"yes\"].includes(\n (env.DATADIVE_AUTO_CONFIRM_WRITES ?? \"\").trim().toLowerCase(),\n );\n\n return { apiKey, baseUrl, autoConfirmWrites };\n}\n","/**\n * Builds the MCP server: registers each tool from the registry with the SDK.\n *\n * Error handling: if a tool handler throws (most commonly an ApiError from the\n * HTTP client), we surface the message back through MCP as a tool-level error\n * (`isError: true`). The LLM sees the message and can react — e.g. tell the\n * user to regenerate their API key on a 401.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { Config } from \"./config.js\";\nimport { allTools } from \"./tools/index.js\";\nimport { ApiError } from \"./http/errors.js\";\nimport { PKG_VERSION, takeUpgradeNotice } from \"./http/client.js\";\n\nexport function buildServer(config: Config): McpServer {\n const server = new McpServer({\n name: \"datadive\",\n version: PKG_VERSION,\n });\n\n for (const tool of allTools) {\n server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema,\n annotations: tool.annotations,\n },\n async (args: Record<string, unknown>) => {\n try {\n const data = await tool.handler(args, { config });\n const content = [\n {\n type: \"text\" as const,\n text: JSON.stringify(data, null, 2),\n },\n ];\n // If the backend signaled a newer release, append a one-time upgrade\n // nudge so the model relays it to the user. takeUpgradeNotice() returns\n // null after the first time, so this fires at most once per session.\n const notice = takeUpgradeNotice();\n if (notice) {\n content.push({\n type: \"text\" as const,\n text: `⚠️ datadive-mcp update available — ${notice}`,\n });\n }\n return { content };\n } catch (err) {\n return {\n isError: true,\n content: [\n {\n type: \"text\" as const,\n text: err instanceof ApiError ? err.message : err instanceof Error ? err.message : String(err),\n },\n ],\n };\n }\n },\n );\n }\n\n return server;\n}\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { NicheList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n currentPage: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Items per page (max 100). Defaults to 20.\"),\n};\n\nexport const listNichesTool: ToolDefinition<typeof inputSchema> = {\n name: \"list_niches\",\n title: \"List DataDive Niches\",\n description:\n \"Use this first when the user asks about their niches, or to find a `nicheId` for use with \" +\n \"`get_niche_keywords`, `get_niche_competitors`, or `get_ranking_juice`. \" +\n \"Retrieves a paginated list of Niches. Each Niche represents a market segment or product \" +\n \"category being tracked. Returns nicheId, heroKeyword, nicheLabel, marketplace (com/uk/de/...), \" +\n \"and latestResearchDate per niche, plus pagination metadata (currentPage, pageSize, total, \" +\n \"lastPage, hasNext, hasPrev).\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<NicheList>(\n { config: ctx.config, toolName: \"list_niches\" },\n \"/v1/niches\",\n { currentPage: args.currentPage, pageSize: args.pageSize },\n );\n },\n};\n","/**\n * Error mapping for the DataDive /v1 API.\n *\n * The MCP server is a thin HTTP shim — when api.datadive.tools returns an error,\n * we want the LLM (and ultimately the user) to see a useful, actionable message\n * rather than \"Request failed\". `ApiError.fromHttp` turns an HTTP status + body\n * into one of those messages.\n *\n * Source of truth for status semantics:\n * datadive-backend/src/external-api/auth/api-key.guard.ts (401/402 logic)\n * datadive-backend/src/external-api/external-api-v1.controller.ts (per-route docs)\n */\n\nconst KEY_HELP_URL = \"https://2.datadive.tools/api-key\";\n\nexport type ApiErrorKind =\n | \"auth\"\n | \"payment\"\n | \"forbidden\"\n | \"not_found\"\n | \"bad_request\"\n | \"rate_limit\"\n | \"server\"\n | \"network\"\n | \"http\";\n\nexport class ApiError extends Error {\n public readonly kind: ApiErrorKind;\n public readonly status: number;\n public readonly body: unknown;\n\n constructor(kind: ApiErrorKind, status: number, message: string, body?: unknown) {\n super(message);\n this.name = \"ApiError\";\n this.kind = kind;\n this.status = status;\n this.body = body;\n }\n\n static fromHttp(status: number, body: unknown): ApiError {\n const serverMsg = extractMessage(body);\n\n if (status === 400) {\n return new ApiError(\n \"bad_request\",\n 400,\n serverMsg ? `Bad request: ${serverMsg}` : \"Bad request: invalid parameters.\",\n body,\n );\n }\n if (status === 401) {\n return new ApiError(\n \"auth\",\n 401,\n `Authentication failed: your DATADIVE_API_KEY is invalid or expired. Generate a new key at ${KEY_HELP_URL}.`,\n body,\n );\n }\n if (status === 402) {\n return new ApiError(\n \"payment\",\n 402,\n \"Subscription is inactive or paused. Resume billing at https://2.datadive.tools to use the API.\",\n body,\n );\n }\n if (status === 403) {\n return new ApiError(\n \"forbidden\",\n 403,\n serverMsg\n ? `Forbidden: ${serverMsg}`\n : \"Forbidden: this API key cannot access the requested resource.\",\n body,\n );\n }\n if (status === 404) {\n return new ApiError(\"not_found\", 404, serverMsg ? `Not found: ${serverMsg}` : \"Resource not found.\", body);\n }\n if (status === 429) {\n return new ApiError(\"rate_limit\", 429, \"Rate limit exceeded. Wait a few seconds and retry.\", body);\n }\n if (status >= 500) {\n return new ApiError(\n \"server\",\n status,\n `DataDive API error (${status}). ${serverMsg ?? \"Please try again.\"}`.trim(),\n body,\n );\n }\n return new ApiError(\"http\", status, serverMsg ?? `HTTP ${status}`, body);\n }\n}\n\nfunction extractMessage(body: unknown): string | null {\n if (!body || typeof body !== \"object\") return null;\n const b = body as Record<string, unknown>;\n // NestJS conventional error shapes: { message: string | string[] } or { error, message }.\n if (typeof b.message === \"string\") return b.message;\n if (Array.isArray(b.message) && b.message.every((m) => typeof m === \"string\")) {\n return (b.message as string[]).join(\"; \");\n }\n if (typeof b.error === \"string\") return b.error;\n return null;\n}\n","{\n \"name\": \"@datadive-tools/mcp\",\n \"version\": \"0.7.0\",\n \"description\": \"MCP server for DataDive — query your niches, keywords, competitors, and Rank Radar data from Claude Desktop, Claude Code, or Cursor.\",\n \"type\": \"module\",\n \"bin\": {\n \"datadive-mcp\": \"./dist/index.js\"\n },\n \"main\": \"./dist/index.js\",\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"engines\": {\n \"node\": \">=22\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest run\",\n \"test:coverage\": \"vitest run --coverage --coverage.include=\\\"src/**\\\" --coverage.reporter=json-summary --coverage.reporter=text\",\n \"test:watch\": \"vitest\",\n \"test:smoke\": \"DATADIVE_SMOKE=1 vitest run test/smoke.test.ts\",\n \"lint\": \"eslint .\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"npm run lint && npm run typecheck && npm run test && npm run build\"\n },\n \"keywords\": [\n \"mcp\",\n \"model-context-protocol\",\n \"datadive\",\n \"amazon\",\n \"claude\"\n ],\n \"author\": \"DataDive\",\n \"license\": \"MIT\",\n \"homepage\": \"https://github.com/Data-Dive-Tools/datadive-mcp\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Data-Dive-Tools/datadive-mcp.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/Data-Dive-Tools/datadive-mcp/issues\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.0.0\",\n \"zod\": \"^3.23.0\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.0\",\n \"@types/node\": \"^20.0.0\",\n \"@typescript-eslint/eslint-plugin\": \"^8.0.0\",\n \"@typescript-eslint/parser\": \"^8.0.0\",\n \"@vitest/coverage-v8\": \"4.1.8\",\n \"eslint\": \"^9.0.0\",\n \"prettier\": \"^3.0.0\",\n \"tsup\": \"^8.0.0\",\n \"typescript\": \"~5.9.0\",\n \"vitest\": \"4.1.8\"\n }\n}\n","/**\n * HTTP client for the DataDive /v1 API.\n *\n * Responsibilities:\n * 1. Attach `x-api-key` from config to every request.\n * 2. Tag the User-Agent with the package version + tool name so backend access\n * logs can attribute usage per tool (no separate telemetry endpoint needed).\n * 3. Map HTTP errors via `ApiError.fromHttp`.\n * 4. Unwrap the `ResponseDto<T>` envelope (`{ message?, success?, data }`)\n * while preserving bare `PaginationResponse<T>` bodies (which need their\n * pagination metadata to reach the LLM).\n *\n * Envelope detection (verified against datadive-backend):\n * - GET /v1/niches -> NicheList extends PaginationResponse<NicheItem> (BARE)\n * - GET /v1/niches/rank-radars -> ResponseDto<ExternalRankRadarListResponseDto>\n * where the inner DTO IS itself paginated.\n * - All other read endpoints -> ResponseDto<T> (UNWRAP)\n *\n * Heuristic: if the body has `data` AND any pagination key (currentPage, lastPage,\n * hasNext, hasPrev, pageSize, total), it's a PaginationResponse — return as-is.\n * Otherwise if the body has `data`, it's a ResponseDto envelope — return body.data.\n *\n * Cite: datadive-backend/src/common/pagination/pagination.dto.ts (pagination keys)\n * datadive-backend/src/common/dto/response.dto.ts (envelope shape)\n */\n\nimport type { Config } from \"../config.js\";\nimport { ApiError } from \"./errors.js\";\nimport { version } from \"../../package.json\";\n\n/**\n * The running package version, inlined from package.json at build time by\n * tsup/esbuild (and by vite under vitest). Single source of truth — no manual\n * bump here, so it can never drift from what's published to npm.\n *\n * Written into the User-Agent header, and compared against the backend's\n * advertised latest version (see noteLatestVersion) to nudge stale installs.\n */\nexport const PKG_VERSION: string = version;\n\n/** Response header the DataDive backend uses to advertise the latest published MCP version. */\nconst LATEST_VERSION_HEADER = \"x-datadive-mcp-latest\";\n\n/**\n * One-time upgrade notice. Armed when the backend advertises a version newer than\n * the one we're running; consumed (and then suppressed for the rest of the session)\n * by takeUpgradeNotice(). We surface it once per process so we don't nag on every call.\n */\nlet pendingUpgradeNotice: string | null = null;\nlet hasWarned = false;\n\n/**\n * Compares dotted version strings (major.minor.patch). Pre-release / build suffixes\n * are stripped — a stable release is the signal we act on. Returns true iff `latest`\n * is strictly newer than `current`. Exported for unit testing.\n */\nexport function isNewerVersion(latest: string, current: string): boolean {\n const parse = (v: string) => v.split(/[-+]/)[0]!.split(\".\").map((n) => parseInt(n, 10) || 0);\n const a = parse(latest);\n const b = parse(current);\n for (let i = 0; i < 3; i++) {\n const da = a[i] ?? 0;\n const db = b[i] ?? 0;\n if (da !== db) return da > db;\n }\n return false;\n}\n\n/** Records the advertised latest version; arms a one-time notice if we're behind. Never throws. */\nfunction noteLatestVersion(latest: string | null): void {\n if (!latest || hasWarned) return;\n if (isNewerVersion(latest, PKG_VERSION)) {\n pendingUpgradeNotice =\n `A newer version of datadive-mcp is available (${latest}; you are running ${PKG_VERSION}). ` +\n `Update by reinstalling the latest from npm — e.g. \\`npm install -g @datadive-tools/mcp@latest\\` — ` +\n `or bump the @datadive-tools/mcp version in your MCP client config, then restart the client.`;\n }\n}\n\n/**\n * Returns a pending upgrade notice once, then suppresses further notices for the rest\n * of the session. Called when assembling a tool result so the LLM can relay it to the\n * user. Returns null when there's nothing to surface.\n */\nexport function takeUpgradeNotice(): string | null {\n if (!pendingUpgradeNotice) return null;\n const notice = pendingUpgradeNotice;\n pendingUpgradeNotice = null;\n hasWarned = true;\n return notice;\n}\n\nconst PAGINATION_KEYS = [\"currentPage\", \"lastPage\", \"hasNext\", \"hasPrev\", \"pageSize\", \"total\"] as const;\n\nexport interface RequestContext {\n config: Config;\n /** Tool name used to tag the User-Agent header for per-tool log attribution. */\n toolName: string;\n}\n\nexport async function httpGet<T>(ctx: RequestContext, path: string, query?: Record<string, unknown>): Promise<T> {\n const url = buildUrl(ctx.config.baseUrl, path, query);\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: \"GET\",\n headers: {\n \"x-api-key\": ctx.config.apiKey,\n accept: \"application/json\",\n \"user-agent\": userAgent(ctx.toolName),\n },\n });\n } catch (e) {\n throw networkError(url, e);\n }\n\n return handleResponse<T>(res);\n}\n\n/**\n * POST a JSON body to a /v1 write endpoint. Mirrors httpGet (same auth/UA headers,\n * version notice, error mapping, and envelope unwrapping) but adds a JSON request\n * body. The create endpoints return bare objects (no ResponseDto envelope), which\n * unwrap() passes through untouched.\n */\nexport async function httpPost<T>(ctx: RequestContext, path: string, body: unknown): Promise<T> {\n const url = buildUrl(ctx.config.baseUrl, path);\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: \"POST\",\n headers: {\n \"x-api-key\": ctx.config.apiKey,\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"user-agent\": userAgent(ctx.toolName),\n },\n body: JSON.stringify(body),\n });\n } catch (e) {\n throw networkError(url, e);\n }\n\n return handleResponse<T>(res);\n}\n\nfunction networkError(url: string, e: unknown): ApiError {\n const msg = e instanceof Error ? e.message : String(e);\n return new ApiError(\"network\", 0, `Network error reaching ${url}: ${msg}`);\n}\n\n/**\n * Shared response handling for httpGet/httpPost: arm the one-time upgrade notice,\n * parse the body, map HTTP errors via ApiError, and unwrap the ResponseDto envelope.\n */\nasync function handleResponse<T>(res: Response): Promise<T> {\n // The backend advertises the latest published MCP version on every response\n // (including errors); arm a one-time upgrade notice if we're behind.\n noteLatestVersion(res.headers.get(LATEST_VERSION_HEADER));\n\n const text = await res.text();\n let body: unknown;\n try {\n body = text.length > 0 ? JSON.parse(text) : null;\n } catch {\n body = text;\n }\n\n if (!res.ok) {\n throw ApiError.fromHttp(res.status, body);\n }\n\n return unwrap<T>(body);\n}\n\nfunction buildUrl(baseUrl: string, path: string, query?: Record<string, unknown>): string {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n const u = new URL(`${baseUrl}${normalizedPath}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined || v === null) continue;\n u.searchParams.set(k, String(v));\n }\n }\n return u.toString();\n}\n\nfunction userAgent(toolName: string): string {\n return `datadive-mcp/${PKG_VERSION} tool/${toolName}`;\n}\n\n/**\n * Unwraps a ResponseDto<T> envelope while preserving bare PaginationResponse bodies.\n * Exported for unit testing.\n */\nexport function unwrap<T>(body: unknown): T {\n if (!isObject(body)) return body as T;\n if (!(\"data\" in body)) return body as T;\n // If pagination metadata is present at the top level, return as-is.\n for (const key of PAGINATION_KEYS) {\n if (key in body) return body as T;\n }\n // Plain ResponseDto envelope -> unwrap.\n return (body as { data: T }).data;\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { GetMasterKeywordListResult } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n nicheId: z.string().min(1).describe(\"The unique identifier of the Niche (from `list_niches`).\"),\n};\n\nexport const getNicheKeywordsTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_niche_keywords\",\n title: \"Get Master Keyword List for a Niche\",\n description:\n \"Use this when the user asks about keywords, search terms, or search volume for a niche. \" +\n \"Retrieves the master keyword list for the specified Niche — the relevant search terms \" +\n \"monitored for ranking and performance metrics. For each keyword, returns search volume, \" +\n \"relevancy (numeric score or \\\"Outlier\\\"), and competitor ASIN organic ranks \" +\n \"(asinRanks: { ASIN -> rank | null }). Also returns the latestResearchDate.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<GetMasterKeywordListResult>(\n { config: ctx.config, toolName: \"get_niche_keywords\" },\n `/v1/niches/${encodeURIComponent(args.nicheId)}/keywords`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { NicheRoots } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n nicheId: z.string().min(1).describe(\"The unique identifier of the Niche (from `list_niches`).\"),\n};\n\nexport const getNicheRootsTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_niche_roots\",\n title: \"Get Keyword Roots for a Niche\",\n description:\n \"Use this when the user wants to find the highest-impact words across a niche's keywords, asks about \" +\n \"'keyword roots', or wants to prioritize terms for a listing. \" +\n \"Retrieves the keyword lexical roots for the Niche — individual words or word-combinations extracted \" +\n \"from the Master Keyword List (e.g. 'bluetooth headphones' yields roots 'bluetooth', 'headphones', \" +\n \"'bluetooth headphones'). Returns `roots` and `normalizedRoots` tables, each item with root, frequency \" +\n \"(how many keywords contain it), broadSearchVolume (summed search volume of those keywords), and \" +\n \"broadSearchVolumeRatio (0-1, relative to the top root), plus the per-keyword breakdowns and \" +\n \"latestResearchDate.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<NicheRoots>(\n { config: ctx.config, toolName: \"get_niche_roots\" },\n `/v1/niches/${encodeURIComponent(args.nicheId)}/roots`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { GetCompetitorListResult } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n nicheId: z.string().min(1).describe(\"The unique identifier of the Niche (from `list_niches`).\"),\n};\n\nexport const getNicheCompetitorsTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_niche_competitors\",\n title: \"Get Competitors and Niche Statistics\",\n description:\n \"Use this for competitor ASINs, sales/revenue benchmarks, or niche opportunity scoring. \" +\n \"Retrieves the list of Competitors within the specified Niche along with Niche statistics. \" +\n \"For the Niche: keyword statistics, opportunity evaluation, benchmark median values, and \" +\n \"overall competitor strength assessment. For each Competitor: ASIN, sales, revenue, ratings, \" +\n \"reviews, price, image URL, and ranking data.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<GetCompetitorListResult>(\n { config: ctx.config, toolName: \"get_niche_competitors\" },\n `/v1/niches/${encodeURIComponent(args.nicheId)}/competitors`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { NicheRankingJuices } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n nicheId: z.string().min(1).describe(\"The unique identifier of the Niche (from `list_niches`).\"),\n};\n\nexport const getRankingJuiceTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_ranking_juice\",\n title: \"Get Ranking Juices for a Niche\",\n description:\n \"Use this when the user asks 'how do I rank higher', 'what's my ranking juice', or wants \" +\n \"listing-optimization guidance. \" +\n \"Retrieves the Ranking Juices for each Competitor within the specified Niche. Ranking Juice is \" +\n \"DataDive's proprietary metric identifying the key factors driving search-ranking success \" +\n \"for each Competitor's listing. Returns currentListing and optimizedListing breakdowns \" +\n \"(rankingJuice + per-property contributions: title, bullets, description) plus per-competitor \" +\n \"listing scores and the latestResearchDate.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<NicheRankingJuices>(\n { config: ctx.config, toolName: \"get_ranking_juice\" },\n `/v1/niches/${encodeURIComponent(args.nicheId)}/ranking-juices`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport { RANK_RADAR_STATUSES, type RankRadarList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Items per page (max 100). Defaults to 20.\"),\n nicheId: z\n .string()\n .min(1)\n .optional()\n .describe(\"Filter Rank Radars by Niche identifier. Use after `list_niches`.\"),\n status: z\n .enum(RANK_RADAR_STATUSES)\n .optional()\n .describe(\n \"Filter by Rank Radar status. By default, returns only ACTIVE Rank Radars. Allowed: ACTIVE, PAUSED, ARCHIVED.\",\n ),\n searchText: z.string().optional().describe(\"Filter Rank Radars by ASIN or product title.\"),\n};\n\nexport const listRankRadarsTool: ToolDefinition<typeof inputSchema> = {\n name: \"list_rank_radars\",\n title: \"List Rank Radars\",\n description:\n \"Use this to find a `rankRadarId` before calling `get_rank_radar_data`. Filter by `nicheId` \" +\n \"if the user has already identified a niche. \" +\n \"Retrieves a paginated list of Rank Radars — keyword-rank trackers monitoring organic and \" +\n \"sponsored positions for specific ASINs over time. Each item includes id, asin (with id, krtId, \" +\n \"asin), marketplace, keywordCount, title, imageUrl, and summary metrics: top10KW, top10SV, \" +\n \"top50KW, top50SV. Supports pagination metadata (currentPage, pageSize, total, lastPage, \" +\n \"hasNext, hasPrev).\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<RankRadarList>(\n { config: ctx.config, toolName: \"list_rank_radars\" },\n \"/v1/niches/rank-radars\",\n {\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n nicheId: args.nicheId,\n status: args.status,\n searchText: args.searchText,\n },\n );\n },\n};\n","/**\n * Hand-mirrored DTOs from the DataDive backend (v1 external API).\n *\n * Source of truth (in this priority order):\n * 1. Live Swagger: https://developer.datadive.tools/docs#/v1\n * (machine-readable: https://developer.datadive.tools/docs-json)\n * 2. Backend DTOs: datadive-backend/src/external-api/dto/*.ts\n * datadive-backend/src/niche-research/dto/rank-radar.response.dto.ts\n * datadive-backend/src/common/dto/response.dto.ts\n * datadive-backend/src/common/pagination/pagination.dto.ts\n * 3. Controller: datadive-backend/src/external-api/external-api-v1.controller.ts\n *\n * Last synced: 2026-06-19.\n *\n * The MCP server forwards JSON straight to the LLM, so deeply-nested DTOs are\n * intentionally typed loosely (with `unknown` or pass-through Records) where\n * the TS surface doesn't add safety. Pin tighter as use cases require.\n */\n\n// ─── Envelope + pagination ───────────────────────────────────────────────────\n\n/** Generic NestJS response envelope: { message?, success?, data? }. */\nexport interface ResponseEnvelope<T> {\n message?: string;\n /** @deprecated — use HTTP status as the success indicator. */\n success?: boolean;\n data?: T | null;\n}\n\n/** Standard pagination envelope returned by list endpoints. */\nexport interface PaginationResponse<T> {\n data: T[];\n currentPage: number;\n pageSize: number;\n total: number;\n lastPage: number;\n hasNext: boolean;\n hasPrev: boolean;\n}\n\n/**\n * ISO-8601 date or timestamp, mirroring the backend's `@IsISO8601()` (date-only\n * allowed). Shared by the date/timestamp query params across /v1 tools\n * (alerts `updatedSince`, usage `startDate`/`endDate`).\n */\nexport const ISO_8601 = /^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/**\n * Marketplace codes accepted by `marketplace` params across /v1 endpoints\n * (alerts, inventory). Mirrors the backend's `SupportedMarketplaceEnum`.\n */\nexport const SUPPORTED_MARKETPLACES = [\n \"com\",\n \"ca\",\n \"co.uk\",\n \"com.mx\",\n \"in\",\n \"fr\",\n \"de\",\n \"es\",\n \"it\",\n \"co.jp\",\n] as const;\n\n// ─── /v1/niches (NicheList = PaginationResponse<NicheItem>) ─────────────────\n\nexport interface NicheItem {\n nicheId: string;\n heroKeyword: string;\n nicheLabel: string;\n /** Amazon marketplace TLD: \"com\", \"uk\", \"de\", etc. */\n marketplace: string;\n /** ISO date string when the Niche was last researched. Nullable. */\n latestResearchDate: string | null;\n}\n\nexport type NicheList = PaginationResponse<NicheItem>;\n\n// ─── /v1/niches/:nicheId/keywords (GetMasterKeywordListResult, wrapped) ─────\n\n/** Map of competitor ASIN -> rank (or null when unranked). */\nexport type AsinRanks = Record<string, number | null>;\n\nexport interface MasterKeyword {\n keyword: string;\n searchVolume: number;\n /** \"Outlier\" or a numeric relevancy score. */\n relevancy: string | number;\n asinRanks: AsinRanks;\n}\n\nexport interface GetMasterKeywordListResult {\n keywords: MasterKeyword[];\n /** ISO date string. */\n latestResearchDate: string;\n}\n\n// ─── /v1/niches/:nicheId/competitors (GetCompetitorListResult, wrapped) ─────\n\n/**\n * Niche competitors response — many nested DTOs from the backend (MklStatisticsData,\n * OpportunityEvaluation, MklBenchmark, CompetitorsStrength, AsinListItem). We type\n * the outer shape and leave the inner objects as opaque records; the LLM sees the\n * full JSON and can reason about it. Tighten if a specific consumer needs it.\n */\nexport interface GetCompetitorListResult {\n /** Marketplace enum (AmazonStore in backend). */\n marketplace: string;\n statistics: Record<string, unknown>;\n opportunityEvaluation: Record<string, unknown>;\n benchmark: Record<string, unknown>;\n competitorsStrength: Record<string, unknown>;\n competitors: Array<Record<string, unknown>>;\n latestResearchDate: string;\n}\n\n// ─── /v1/niches/:nicheId/ranking-juices (NicheRankingJuices, wrapped) ───────\n\nexport interface RankingJuiceProperty {\n rankingJuice: number;\n}\n\nexport interface ListingRankingJuice {\n rankingJuice: number;\n title: RankingJuiceProperty;\n bullets: RankingJuiceProperty;\n description: RankingJuiceProperty;\n}\n\nexport interface CompetitorRankingJuice {\n asin: string;\n listing: ListingRankingJuice;\n}\n\nexport interface NicheRankingJuices {\n currentListing: ListingRankingJuice;\n optimizedListing: ListingRankingJuice;\n competitors: CompetitorRankingJuice[];\n latestResearchDate: string;\n}\n\n// ─── /v1/niches/rank-radars (ExternalRankRadarListResponseDto, wrapped) ─────\n\nexport interface RankRadarAsin {\n id: string;\n krtId: string;\n asin: string;\n}\n\nexport interface RankRadarItem {\n id: string;\n asin: RankRadarAsin;\n marketplace: string;\n keywordCount: number;\n title: string;\n imageUrl: string;\n top10KW: number | null;\n top10SV: number | null;\n top50KW: number | null;\n top50SV: number | null;\n}\n\nexport type RankRadarList = PaginationResponse<RankRadarItem>;\n\n/** Allowed values for the `status` query param on /v1/niches/rank-radars. */\nexport const RANK_RADAR_STATUSES = [\"ACTIVE\", \"PAUSED\", \"ARCHIVED\"] as const;\nexport type RankRadarStatus = (typeof RANK_RADAR_STATUSES)[number];\n\n// ─── POST /v1/niches/rank-radars (CreateRankRadarSuccessResponseDto, bare) ──\n\n/** Result of creating a Rank Radar. */\nexport interface CreateRankRadarResult {\n rankRadarId: string;\n}\n\n// ─── POST /v1/niches/dives (CreateNicheDiveSuccessResponseDto, bare) ────────\n\n/** Result of kicking off a Niche Dive. Poll get_dive_status with `diveId`. */\nexport interface CreateNicheDiveResult {\n diveId: string;\n /** ISO-8601 estimated completion timestamp. */\n estimatedCompletionDate: string;\n}\n\n// ─── GET /v1/niches/dives/:diveId (NicheDiveStatus*ResponseDto, bare oneOf) ──\n\n/**\n * Niche Dive status, discriminated on `status`:\n * - \"in_progress\" → estimatedCompletionDate\n * - \"success\" → nicheId + token usage (feed nicheId to list_niches / get_niche_*)\n * - \"error\" → error message\n */\nexport type DiveStatus =\n | { diveId: string; status: \"in_progress\"; estimatedCompletionDate: string }\n | { diveId: string; status: \"success\"; nicheId: string; tokensUsed: number; tokensLeft: number }\n | { diveId: string; status: \"error\"; error: string };\n\n// ─── /v1/niches/rank-radars/:rankRadarId (KrtKeywordResponseDto[], wrapped) ─\n\nexport interface KrtAsinRank {\n /** ISO date string. */\n date: string;\n organicRank?: number | null;\n impressionRank?: number | null;\n}\n\nexport interface KrtKeyword {\n id: string;\n keyword: string;\n searchVolume: number | null;\n ranks: KrtAsinRank[];\n /** Highlight annotations (KrtHighlightDto in backend); kept opaque for MVP. */\n highlights: Array<Record<string, unknown>>;\n}\n\nexport type RankRadarKeywordList = KrtKeyword[];\n\n// ─── /v1/sellers/:sellerId/marketplaces/:marketplace/asins/:asin/inventory ────\n// (InventoryByFcResponseDto, wrapped)\n\nexport interface InventoryByFcItem {\n /** Fulfillment center code. */\n fc: string;\n /** State or region code where the FC is located, when known. */\n state: string;\n /** Units of sellable inventory currently at this FC. May be 0 when stock is out. */\n availableStock: number;\n /** Share of the ASIN's total sellable inventory at this FC, as a 0..1 fraction. */\n availableStockPercentage: number;\n}\n\nexport interface InventoryByFcResponse {\n asin: string;\n sellerId: string;\n /** Marketplace enum: \"com\", \"ca\", \"co.uk\", \"com.mx\", \"in\", \"fr\", \"de\", \"es\", \"it\", \"co.jp\". */\n marketplace: string;\n /** ISO timestamp of last successful ingestion. Null if none in the last 30 days. */\n lastUpdatedAt: string | null;\n totalSellableUnits: number;\n distribution: InventoryByFcItem[];\n}\n\n// ─── /v1/alerts/indexing-issues (IndexingIssueAlertListDto, bare) ───────────\n\n/**\n * Allowed values for the `status` query param on the /v1/alerts/* endpoints.\n * `active` is the server-side default; dismissed alerts are never returned.\n */\nexport const ALERT_STATUSES = [\"active\", \"resolved\", \"all\"] as const;\nexport type AlertStatus = (typeof ALERT_STATUSES)[number];\n\nexport interface IndexingIssueAlertItem {\n id: number;\n /** The ASIN that is no longer indexed for its tracked keywords. */\n asin: string;\n title: string | null;\n imageUrl: string | null;\n /** True when the ASIN is a parent of a variation family. */\n isParent: boolean;\n sellerId: string;\n marketplace: string;\n /** ISO timestamp of when the alert was most recently surfaced. Updates each time it re-fires. */\n lastAlertedAt: string;\n /** ISO timestamp of when the alert was resolved, or null if still active. */\n resolvedAt: string | null;\n}\n\nexport type IndexingIssueAlertList = PaginationResponse<IndexingIssueAlertItem>;\n\n// ─── /v1/alerts/blind-spend (BlindSpendAlertListDto, bare) ──────────────────\n\nexport interface BlindSpendSearchTerm {\n /** The customer search term that wasted spend. */\n term: string;\n spend: number | null;\n sales: number | null;\n clicks: number | null;\n /** Conversion rate as a 0..1 fraction. */\n cvr: number | null;\n impressions: number | null;\n}\n\nexport interface BlindSpendAlertItem {\n id: number;\n asin: string | null;\n title: string | null;\n imageUrl: string | null;\n sellerId: string;\n marketplace: string;\n /** ISO timestamp of when the alert was most recently surfaced. Updates each time it re-fires. */\n lastAlertedAt: string;\n /** ISO timestamp of when the alert was resolved, or null if still active. */\n resolvedAt: string | null;\n /** Total ad spend across the unresolved wasted-spend search terms. */\n wastedSpend: number;\n totalKeywordCount: number;\n unresolvedKeywordCount: number;\n /** The unresolved wasted-spend search terms. */\n searchTerms: BlindSpendSearchTerm[];\n}\n\nexport type BlindSpendAlertList = PaginationResponse<BlindSpendAlertItem>;\n\n// ─── Billable features (shared by /v1/quota and /v1/usage) ───────────────────\n\n/**\n * Billable feature types. These are both the keys of the `quota.features` object\n * and the allowed values of the `type` filter on /v1/usage. Mirrors the backend's\n * billable-feature enum.\n */\nexport const BILLABLE_FEATURE_TYPES = [\n \"DIVED_ASINS\",\n \"PRODUCT_BRIEF_ASINS\",\n \"AI_COPYWRITER_PROMPTS\",\n \"RANK_RADAR_KEYWORDS\",\n] as const;\nexport type BillableFeatureType = (typeof BILLABLE_FEATURE_TYPES)[number];\n\n// ─── /v1/niches/:nicheId/roots (ExternalRootResponseDto[], wrapped) ─────────\n\nexport interface RootsTableItem {\n /** A word or word-combination extracted from the master keyword list. */\n root: string;\n /** Count of keywords in the master list that contain this root. */\n frequency: number;\n /** Sum of search volume across all original keywords containing this root. */\n broadSearchVolume: number;\n /** broadSearchVolume / maxBroadSearchVolume, as a 0..1 fraction. */\n broadSearchVolumeRatio: number;\n}\n\n/**\n * Keyword-roots analysis for a Niche. `keywords` and `consolidatedKeywords` are\n * the per-keyword breakdowns (kept opaque — the LLM sees the full JSON); `roots`\n * and `normalizedRoots` are the ranked root tables.\n *\n * Note: the OpenAPI spec types the endpoint's `data` as an array, but the live\n * API returns a single object (verified against api-qa, 2026-06-17). The client's\n * unwrap() strips the `{ data }` envelope, so the tool returns this object directly.\n */\nexport interface NicheRoots {\n keywords: Array<Record<string, unknown>>;\n consolidatedKeywords: Array<Record<string, unknown>>;\n roots: RootsTableItem[];\n normalizedRoots: RootsTableItem[];\n /** ISO date string of the last successful research for the niche. */\n latestResearchDate: string;\n}\n\n// ─── /v1/quota (ExternalQuotaResponseDto) ───────────────────────────────────\n\nexport interface QuotaFeature {\n /** Current usage count. Null when not applicable to the plan. */\n used: number | null;\n /** Quota capacity. Null when unlimited / not applicable. */\n capacity: number | null;\n}\n\nexport interface Quota {\n /** ISO-8601 timestamp of the next quota reset. Null when no reset is scheduled. */\n nextRefreshDate: string | null;\n /** Per-billable-feature usage and capacity. */\n features: Record<BillableFeatureType, QuotaFeature>;\n}\n\n// ─── /v1/usage (ExternalUsageLogListDto, bare PaginationResponse) ───────────\n\nexport interface UsageLogItem {\n /** Name of the user who performed the action. Null when unknown. */\n name: string | null;\n email: string;\n /** Number of tokens consumed. */\n qty: number;\n type: BillableFeatureType;\n /** Specific action performed (e.g. \"RANK_RADAR_CREATE\"). Null when not set. */\n action: string | null;\n nicheId: string | null;\n nicheName: string | null;\n rankRadarId: string | null;\n /** ISO timestamp of when the usage was recorded. */\n date: string;\n}\n\nexport type UsageLogList = PaginationResponse<UsageLogItem>;\n\n// ─── /v1/seller_profiles (SellerProfileListDto, bare PaginationResponse) ─────\n\nexport interface SellerProfileItem {\n /** Amazon seller account ID — the value other seller-scoped tools require. */\n sellerId: string;\n /** Display name of the connected seller account. */\n sellerName: string;\n /** Marketplace code, e.g. \"com\", \"co.uk\" (see SUPPORTED_MARKETPLACES). */\n marketplace: string;\n /** True when Amazon Advertising API credentials are connected for this account. */\n hasAdApi: boolean;\n /** ISO timestamp of when the account was connected to DataDive. */\n createdAt: string;\n}\n\nexport type SellerProfileList = PaginationResponse<SellerProfileItem>;\n\n// ─── /v1/seller_profiles/:sellerId/marketplaces/:marketplace/catalog ──────────\n// (CatalogAsinListDto, bare PaginationResponse)\n\n/** Allowed values for the `status` query param on the seller catalog endpoint. */\nexport const CATALOG_STATUSES = [\"Active\", \"all\"] as const;\nexport type CatalogStatus = (typeof CATALOG_STATUSES)[number];\n\nexport interface CatalogAsinItem {\n asin: string;\n title: string;\n /** Parent ASIN for a variation child, or null for standalone/parent ASINs. */\n parentAsin: string | null;\n brand: string | null;\n /** Listing status, e.g. \"Active\". */\n status: string;\n imageUrl: string | null;\n /** True when the ASIN has variation children. Null when unknown. */\n hasVariations: boolean | null;\n}\n\nexport type SellerCatalogList = PaginationResponse<CatalogAsinItem>;\n\n// ─── /v1/seller_profiles/:sellerId/marketplaces/:marketplace/listing-changes ──\n// (ListingChangeExternalListDto, bare PaginationResponse)\n\n/** Allowed values for the `types` query param on the listing-changes endpoint. */\nexport const LISTING_CHANGE_TYPES = [\"Price\", \"Content\", \"Image\"] as const;\nexport type ListingChangeType = (typeof LISTING_CHANGE_TYPES)[number];\n\n/** Allowed values for the `sortBy` query param on the listing-changes endpoint. */\nexport const LISTING_CHANGE_SORT_BY = [\"date\", \"type\"] as const;\nexport type ListingChangeSortBy = (typeof LISTING_CHANGE_SORT_BY)[number];\n\n/** Generic sort direction, shared where a `sortOrder` query param is accepted. */\nexport const SORT_ORDER = [\"ASC\", \"DESC\"] as const;\nexport type SortOrder = (typeof SORT_ORDER)[number];\n\n/**\n * Optional ranking/conversion correlation for a listing change, present only when\n * `includeCorrelations=true`. Sub-objects (salesCvr, top10/top50SearchTerms) carry\n * before/after figures and are kept loosely typed per this file's convention.\n */\nexport interface ListingChangeCorrelation {\n /** \"PENDING\" | \"AVAILABLE\" | \"UNAVAILABLE_NO_ACTIVE_RANK_RADAR\" | \"UNAVAILABLE\". */\n status: string;\n message: string | null;\n salesCvr: Record<string, unknown> | null;\n top10SearchTerms: Record<string, unknown> | null;\n top50SearchTerms: Record<string, unknown> | null;\n}\n\nexport interface ListingChangeItem {\n asin: string;\n title: string | null;\n imageUrl: string | null;\n /** ISO timestamp of when the change was detected. */\n date: string;\n /** \"Price\" | \"Content\" | \"Image\". */\n type: string;\n /** Sub-type for content changes (e.g. title/bullets/description); null otherwise. */\n contentType: string | null;\n description: string;\n /** Prior value of the changed field. Shape varies by change type; kept opaque. */\n previousValue: Record<string, unknown> | null;\n /** New value of the changed field. Shape varies by change type; kept opaque. */\n newValue: Record<string, unknown> | null;\n /** Present only when `includeCorrelations=true`; null otherwise. */\n correlation: ListingChangeCorrelation | null;\n}\n\nexport type ListingChangeList = PaginationResponse<ListingChangeItem>;\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { RankRadarKeywordList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\n/** yyyy-mm-dd matcher used by both startDate and endDate. */\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nconst inputSchema = {\n rankRadarId: z\n .string()\n .uuid()\n .describe(\"The Rank Radar UUID (from `list_rank_radars`).\"),\n startDate: z\n .string()\n .regex(ISO_DATE, \"startDate must be in yyyy-mm-dd format\")\n .describe(\"Start date for the ranking data range, yyyy-mm-dd (e.g. 2024-03-26).\"),\n endDate: z\n .string()\n .regex(ISO_DATE, \"endDate must be in yyyy-mm-dd format\")\n .describe(\"End date for the ranking data range, yyyy-mm-dd (e.g. 2024-04-26). Must be on or after startDate.\"),\n};\n\nexport const getRankRadarDataTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_rank_radar_data\",\n title: \"Get Keyword Rankings for a Rank Radar\",\n description:\n \"Use this to analyze keyword ranking trends over time. Requires startDate and endDate (yyyy-mm-dd). \" +\n \"Retrieves historical keyword ranking data for the specified Rank Radar within the date range. \" +\n \"Returns an array of tracked keywords; each has id, keyword, searchVolume, ranks (per-day \" +\n \"{ date, organicRank, impressionRank }), and any highlight annotations. Use after \" +\n \"`list_rank_radars` to discover a `rankRadarId`.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<RankRadarKeywordList>(\n { config: ctx.config, toolName: \"get_rank_radar_data\" },\n `/v1/niches/rank-radars/${encodeURIComponent(args.rankRadarId)}`,\n { startDate: args.startDate, endDate: args.endDate },\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpPost } from \"../http/client.js\";\nimport type { CreateRankRadarResult } from \"../types/api.js\";\nimport { requireConfirmation } from \"./confirm.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n asin: z.string().min(1).describe(\"The ASIN to track keyword rankings for.\"),\n numberOfKeywords: z\n .number()\n .int()\n .min(1)\n .describe(\"How many keywords to track (minimum 1). More keywords = broader tracking but more Search Term tokens.\"),\n nicheId: z\n .string()\n .min(1)\n .describe(\"The niche this Rank Radar belongs to. Get one from `list_niches`.\"),\n confirm: z\n .boolean()\n .optional()\n .describe(\n \"Must be true to proceed — creating a Rank Radar spends Search Term tokens. Confirm the cost with the user first.\",\n ),\n};\n\nexport const createRankRadarTool: ToolDefinition<typeof inputSchema> = {\n name: \"create_rank_radar\",\n title: \"Create a Rank Radar\",\n description:\n \"Use this to start tracking organic and sponsored keyword rankings for an ASIN within a niche. \" +\n \"⚠️ Spends Search Term tokens (cost scales with `numberOfKeywords`) and cannot be undone — set \" +\n \"`confirm: true` only after the user approves the cost. Returns the new `rankRadarId`; read its data \" +\n \"later with `get_rank_radar_data`. Requires `asin`, `numberOfKeywords` (min 1), and a `nicheId` from `list_niches`.\",\n inputSchema,\n // destructiveHint is technically \"additive\" here (this creates a new Rank Radar, it\n // doesn't destroy data), but we flag it destructive so clients prompt before the\n // irreversible token spend. The confirm gate enforces this server-side regardless.\n annotations: { readOnlyHint: false, destructiveHint: true },\n handler: async (args, ctx) => {\n const pending = requireConfirmation(\n args.confirm,\n ctx,\n `Creating this Rank Radar consumes Search Term tokens — one per keyword tracked (${args.numberOfKeywords} requested).`,\n );\n if (pending) return pending;\n\n return await httpPost<CreateRankRadarResult>(\n { config: ctx.config, toolName: \"create_rank_radar\" },\n \"/v1/niches/rank-radars\",\n {\n asin: args.asin,\n numberOfKeywords: args.numberOfKeywords,\n nicheId: args.nicheId,\n },\n );\n },\n};\n","/**\n * Shared confirm gate for token-spending write tools (create_niche_dive,\n * create_rank_radar).\n *\n * Creating a Dive or Rank Radar consumes billable tokens irreversibly, so these\n * tools require an explicit `confirm: true` before they hit the API. When the flag\n * is missing, requireConfirmation returns a structured (non-error) payload telling\n * the model to confirm the token spend with the user and re-call with `confirm: true`;\n * the handler returns that payload early WITHOUT calling the API.\n *\n * The user can opt out of the gate entirely by setting DATADIVE_AUTO_CONFIRM_WRITES\n * (see config.ts) — a persistent \"don't ask me again\".\n */\n\nimport type { HandlerContext } from \"./types.js\";\n\nexport interface ConfirmationRequired {\n status: \"confirmation_required\";\n message: string;\n /** Human-readable note on what this action will cost in tokens. */\n costNote: string;\n}\n\n/**\n * Returns a ConfirmationRequired payload if the action is not yet confirmed, or null\n * if the handler should proceed (confirm:true was passed, or the opt-out is set).\n */\nexport function requireConfirmation(\n confirm: boolean | undefined,\n ctx: HandlerContext,\n costNote: string,\n): ConfirmationRequired | null {\n if (confirm === true || ctx.config.autoConfirmWrites) return null;\n return {\n status: \"confirmation_required\",\n message:\n \"This action spends billable tokens and cannot be undone. Confirm the cost with \" +\n \"the user, then call again with `confirm: true` to proceed.\",\n costNote,\n };\n}\n","import { z } from \"zod\";\nimport { httpPost } from \"../http/client.js\";\nimport { SUPPORTED_MARKETPLACES, type CreateNicheDiveResult } from \"../types/api.js\";\nimport { requireConfirmation } from \"./confirm.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n marketplace: z\n .enum(SUPPORTED_MARKETPLACES)\n .describe(\n \"Amazon marketplace of the seed ASIN. Note these are full domain suffixes: com, ca, \" +\n \"co.uk, com.mx, in, fr, de, es, it, co.jp (e.g. UK is `co.uk`, not `uk`).\",\n ),\n asin: z\n .string()\n .min(1)\n .describe(\"The seed ASIN to start the dive from (e.g. B08N5WRWNW). Competitors are built around it.\"),\n numberOfCompetitors: z\n .number()\n .int()\n .min(2)\n .describe(\"How many competitors to analyze (minimum 2). More competitors = deeper niche but more dive tokens.\"),\n confirm: z\n .boolean()\n .optional()\n .describe(\"Must be true to proceed — creating a dive spends dive tokens. Confirm the cost with the user first.\"),\n};\n\nexport const createNicheDiveTool: ToolDefinition<typeof inputSchema> = {\n name: \"create_niche_dive\",\n title: \"Create a Niche Dive\",\n description:\n \"Use this to start new niche research from a seed ASIN. ⚠️ Spends dive tokens (cost scales with \" +\n \"`numberOfCompetitors`) and cannot be undone — set `confirm: true` only after the user approves the cost. \" +\n \"The dive runs asynchronously: this returns immediately with a `diveId` and an `estimatedCompletionDate`. \" +\n \"Poll `get_dive_status` with that `diveId` until it reports `success` (which carries the new `nicheId` for \" +\n \"use with `list_niches`, `get_niche_keywords`, etc.). Requires `marketplace`, `asin`, and `numberOfCompetitors` (min 2).\",\n inputSchema,\n // destructiveHint is technically \"additive\" here (a dive creates a new niche, it\n // doesn't destroy data), but we flag it destructive so clients prompt before the\n // irreversible token spend. The confirm gate enforces this server-side regardless.\n annotations: { readOnlyHint: false, destructiveHint: true },\n handler: async (args, ctx) => {\n const pending = requireConfirmation(\n args.confirm,\n ctx,\n `Creating this dive consumes dive tokens — one batch per competitor analyzed (${args.numberOfCompetitors} requested).`,\n );\n if (pending) return pending;\n\n return await httpPost<CreateNicheDiveResult>(\n { config: ctx.config, toolName: \"create_niche_dive\" },\n \"/v1/niches/dives\",\n {\n marketplace: args.marketplace,\n asin: args.asin,\n numberOfCompetitors: args.numberOfCompetitors,\n },\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { DiveStatus } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n diveId: z.string().min(1).describe(\"The dive identifier returned by `create_niche_dive`.\"),\n};\n\nexport const getDiveStatusTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_dive_status\",\n title: \"Get Niche Dive Status\",\n description:\n \"Use this to poll a niche dive started with `create_niche_dive` until it finishes. \" +\n \"Returns one of three shapes keyed by `status`: `in_progress` (with `estimatedCompletionDate`), \" +\n \"`success` (with the new `nicheId` plus `tokensUsed`/`tokensLeft`), or `error` (with an `error` message). \" +\n \"On `success`, use the `nicheId` with `list_niches`, `get_niche_keywords`, `get_niche_competitors`, etc. \" +\n \"Re-poll periodically — dives can take minutes; the `estimatedCompletionDate` hints at when to check.\",\n inputSchema,\n annotations: { readOnlyHint: true },\n handler: async (args, ctx) => {\n return await httpGet<DiveStatus>(\n { config: ctx.config, toolName: \"get_dive_status\" },\n `/v1/niches/dives/${encodeURIComponent(args.diveId)}`,\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport type { SellerProfileList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .describe(\"Items per page (max 50). Defaults to 20.\"),\n};\n\nexport const listSellerProfilesTool: ToolDefinition<typeof inputSchema> = {\n name: \"list_seller_profiles\",\n title: \"List Connected Amazon Seller Profiles\",\n description:\n \"Use this when the user asks which Amazon seller accounts are connected, or as the discovery \" +\n \"step to find the `sellerId` and `marketplace` required by `get_asin_inventory_distribution`, \" +\n \"`get_seller_catalog`, `get_seller_listing_changes`, and the alert tools. \" +\n \"Returns a paginated list of the organization's connected seller profiles — each item has \" +\n \"sellerId, sellerName, marketplace (e.g. \\\"com\\\", \\\"co.uk\\\"), hasAdApi (whether Advertising API \" +\n \"credentials are connected), and createdAt — plus pagination metadata (currentPage, pageSize, \" +\n \"total, lastPage, hasNext, hasPrev).\",\n inputSchema,\n annotations: { readOnlyHint: true },\n handler: async (args, ctx) => {\n return await httpGet<SellerProfileList>(\n { config: ctx.config, toolName: \"list_seller_profiles\" },\n \"/v1/seller_profiles\",\n {\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport { CATALOG_STATUSES, type SellerCatalogList } from \"../types/api.js\";\nimport { sellerMarketplacePath, sellerScopedInputSchema } from \"./seller-scoped.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n ...sellerScopedInputSchema,\n search: z\n .string()\n .min(1)\n .optional()\n .describe(\"Case-insensitive partial match on product title or brand.\"),\n brand: z.string().min(1).optional().describe(\"Case-insensitive partial match on brand name.\"),\n status: z\n .enum(CATALOG_STATUSES)\n .optional()\n .describe('Listing status filter. \"Active\" (default) or \"all\".'),\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .describe(\"Items per page (max 50). Defaults to 20.\"),\n};\n\nexport const getSellerCatalogTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_seller_catalog\",\n title: \"List Catalog ASINs for a Seller\",\n description:\n \"Use this when the user wants to browse or search a seller's own Amazon catalog — the products \" +\n \"they sell on a given marketplace. Requires a `sellerId` + `marketplace` (use `list_seller_profiles` \" +\n \"to discover them). Filter by `search` (title/brand), `brand`, and `status` (Active by default, or \" +\n \"all). Returns a paginated list where each item has asin, title, parentAsin, brand, status, imageUrl, \" +\n \"and hasVariations, plus pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).\",\n inputSchema,\n annotations: { readOnlyHint: true },\n handler: async (args, ctx) => {\n return await httpGet<SellerCatalogList>(\n { config: ctx.config, toolName: \"get_seller_catalog\" },\n sellerMarketplacePath(args.sellerId, args.marketplace, \"catalog\"),\n {\n search: args.search,\n brand: args.brand,\n status: args.status,\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","/**\n * Shared input fields + path builder for the seller+marketplace-scoped tools\n * (/v1/seller_profiles/:sellerId/marketplaces/:marketplace/*). Defined once here\n * and spread into each tool's inputSchema, mirroring alert-query.ts.\n */\n\nimport { z } from \"zod\";\nimport { SUPPORTED_MARKETPLACES } from \"../types/api.js\";\n\nexport const sellerScopedInputSchema = {\n sellerId: z\n .string()\n .min(1)\n .describe(\n \"Amazon seller account ID. Get it from `list_seller_profiles`, or find it on the Connections page at https://2.datadive.tools.\",\n ),\n marketplace: z\n .enum(SUPPORTED_MARKETPLACES)\n .describe('Amazon marketplace code, e.g. \"com\" for amazon.com or \"co.uk\" for amazon.co.uk.'),\n};\n\n/** Builds a `/v1/seller_profiles/:sellerId/marketplaces/:marketplace/<suffix>` path with both params URL-encoded. */\nexport function sellerMarketplacePath(sellerId: string, marketplace: string, suffix: string): string {\n return `/v1/seller_profiles/${encodeURIComponent(sellerId)}/marketplaces/${encodeURIComponent(\n marketplace,\n )}/${suffix}`;\n}\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport {\n ISO_8601,\n LISTING_CHANGE_SORT_BY,\n LISTING_CHANGE_TYPES,\n SORT_ORDER,\n type ListingChangeList,\n} from \"../types/api.js\";\nimport { sellerMarketplacePath, sellerScopedInputSchema } from \"./seller-scoped.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n ...sellerScopedInputSchema,\n types: z\n .array(z.enum(LISTING_CHANGE_TYPES))\n .min(1)\n .optional()\n .describe('Filter to specific change types. Omit for all. Any of \"Price\", \"Content\", \"Image\".'),\n asin: z\n .string()\n .min(1)\n .optional()\n .describe(\"Filter to an exact ASIN or parent ASIN.\"),\n brand: z.string().min(1).optional().describe(\"Case-insensitive partial match on brand name.\"),\n search: z\n .string()\n .min(1)\n .optional()\n .describe(\"Case-insensitive partial match on product title or brand.\"),\n startDate: z\n .string()\n .regex(ISO_8601, \"startDate must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)\")\n .optional()\n .describe(\"ISO-8601 date/timestamp; return only changes detected on or after this time.\"),\n endDate: z\n .string()\n .regex(ISO_8601, \"endDate must be an ISO-8601 date or timestamp (e.g. 2026-05-31 or 2026-05-31T23:59:59Z)\")\n .optional()\n .describe(\"ISO-8601 date/timestamp; return only changes detected on or before this time.\"),\n sortBy: z\n .enum(LISTING_CHANGE_SORT_BY)\n .optional()\n .describe('Sort field. \"date\" (default) or \"type\".'),\n sortOrder: z.enum(SORT_ORDER).optional().describe('Sort direction. \"DESC\" (default) or \"ASC\".'),\n includeCorrelations: z\n .boolean()\n .optional()\n .describe(\n \"When true, include the ranking/conversion `correlation` object per change (CVR and search-term \" +\n \"movement before vs after). Defaults to false.\",\n ),\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .describe(\"Items per page (max 50). Defaults to 20.\"),\n};\n\nexport const getSellerListingChangesTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_seller_listing_changes\",\n title: \"List Listing Changes for a Seller\",\n description:\n \"Use this when the user asks what changed on their Amazon listings — price, content (title/bullets/\" +\n \"description), or image edits — for a seller account. Requires a `sellerId` + `marketplace` (use \" +\n \"`list_seller_profiles` to discover them). Filter by `types`, `asin`/parent ASIN, `brand`, `search`, \" +\n \"and a `startDate`/`endDate` range; sort with `sortBy`/`sortOrder`. Set `includeCorrelations: true` to \" +\n \"attach the ranking/conversion impact per change. Returns a paginated list where each item has asin, \" +\n \"title, imageUrl, date, type, contentType, description, previousValue, newValue, and (optionally) \" +\n \"correlation, plus pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).\",\n inputSchema,\n annotations: { readOnlyHint: true },\n handler: async (args, ctx) => {\n return await httpGet<ListingChangeList>(\n { config: ctx.config, toolName: \"get_seller_listing_changes\" },\n sellerMarketplacePath(args.sellerId, args.marketplace, \"listing-changes\"),\n {\n // The API accepts `types` as a comma-separated list.\n types: args.types?.join(\",\"),\n asin: args.asin,\n brand: args.brand,\n search: args.search,\n startDate: args.startDate,\n endDate: args.endDate,\n sortBy: args.sortBy,\n sortOrder: args.sortOrder,\n includeCorrelations: args.includeCorrelations,\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport { SUPPORTED_MARKETPLACES, type InventoryByFcResponse } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n sellerId: z\n .string()\n .min(1)\n .describe(\n \"Amazon seller account ID as connected to DataDive. Get it from `list_seller_profiles`, or find it on the Connections page at https://2.datadive.tools.\",\n ),\n marketplace: z\n .enum(SUPPORTED_MARKETPLACES)\n .describe('Amazon marketplace code, e.g. \"com\" for amazon.com or \"co.uk\" for amazon.co.uk.'),\n asin: z\n .string()\n .regex(/^[A-Z0-9]{10}$/, \"ASIN must be 10 uppercase alphanumeric characters (e.g. B08XYZ1234).\")\n .describe(\n \"Amazon Standard Identification Number (10 uppercase alphanumeric characters, e.g. B08XYZ1234).\",\n ),\n};\n\nexport const getAsinInventoryDistributionTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_asin_inventory_distribution\",\n title: \"Get Per-Fulfillment-Center Inventory Distribution for an ASIN\",\n description:\n \"Use this when the user asks about inventory levels, stock by fulfillment center, \" +\n \"or where their units are sitting across Amazon's fulfillment network for a specific ASIN. \" +\n \"Requires the Amazon sellerId (from `list_seller_profiles` or the user's DataDive Connections \" +\n \"page at https://2.datadive.tools), the marketplace code, and the ASIN. Returns totalSellableUnits \" +\n \"and a per-FC `distribution` array (fc, state, availableStock, availableStockPercentage). \" +\n \"`lastUpdatedAt` may be null when no successful inventory ingestion has occurred in the last 30 days.\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<InventoryByFcResponse>(\n { config: ctx.config, toolName: \"get_asin_inventory_distribution\" },\n `/v1/sellers/${encodeURIComponent(args.sellerId)}/marketplaces/${encodeURIComponent(\n args.marketplace,\n )}/asins/${encodeURIComponent(args.asin)}/inventory`,\n );\n },\n};\n","/**\n * Shared input schema for the /v1/alerts/* list tools. Both alert endpoints\n * accept the same backend query DTO (ExternalAlertsQueryDto), so the input\n * contract is defined once here and imported by each tool.\n */\n\nimport { z } from \"zod\";\nimport { ALERT_STATUSES, ISO_8601, SUPPORTED_MARKETPLACES } from \"../types/api.js\";\n\nexport const alertsQueryInputSchema = {\n sellerId: z\n .string()\n .min(1)\n .max(50)\n .optional()\n .describe('Filter to a single connected Amazon seller account ID, e.g. \"A1B2C3D4E5\".'),\n marketplace: z\n .enum(SUPPORTED_MARKETPLACES)\n .optional()\n .describe('Filter to a single Amazon marketplace code, e.g. \"com\" for amazon.com or \"co.uk\" for amazon.co.uk.'),\n status: z\n .enum(ALERT_STATUSES)\n .optional()\n .describe(\n \"Lifecycle filter. `active` (default) returns unresolved alerts, `resolved` returns resolved alerts, \" +\n \"`all` returns both. Dismissed alerts are never returned.\",\n ),\n updatedSince: z\n .string()\n .regex(ISO_8601, \"updatedSince must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)\")\n .optional()\n .describe(\n \"ISO-8601 timestamp; return only alerts surfaced at or after this time (filters on `lastAlertedAt`). \" +\n \"Use it to incrementally sync since your last poll. Defaults to the last 30 days when omitted.\",\n ),\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .describe(\"Items per page (max 50). Defaults to 20.\"),\n};\n","import { httpGet } from \"../http/client.js\";\nimport type { IndexingIssueAlertList } from \"../types/api.js\";\nimport { alertsQueryInputSchema } from \"./alert-query.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nexport const listIndexingIssueAlertsTool: ToolDefinition<typeof alertsQueryInputSchema> = {\n name: \"list_indexing_issue_alerts\",\n title: \"List Indexing-Issue Alerts\",\n description:\n \"Use this to find products that may have lost search visibility. Retrieves a paginated list of \" +\n \"indexing-issue alerts across the user's connected Amazon seller accounts — an alert fires when one of \" +\n \"their ASINs is no longer indexed for its tracked keywords. By default returns active (unresolved) alerts \" +\n \"from the last 30 days; filter by `sellerId`, `marketplace`, `status`, or `updatedSince` (for incremental \" +\n \"polling). Each item includes id, asin, title, imageUrl, isParent, sellerId, marketplace, lastAlertedAt, \" +\n \"and resolvedAt. Supports pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).\",\n inputSchema: alertsQueryInputSchema,\n handler: async (args, ctx) => {\n return await httpGet<IndexingIssueAlertList>(\n { config: ctx.config, toolName: \"list_indexing_issue_alerts\" },\n \"/v1/alerts/indexing-issues\",\n {\n sellerId: args.sellerId,\n marketplace: args.marketplace,\n status: args.status,\n updatedSince: args.updatedSince,\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","import { httpGet } from \"../http/client.js\";\nimport type { BlindSpendAlertList } from \"../types/api.js\";\nimport { alertsQueryInputSchema } from \"./alert-query.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nexport const listBlindSpendAlertsTool: ToolDefinition<typeof alertsQueryInputSchema> = {\n name: \"list_blind_spend_alerts\",\n title: \"List Blind-Spend (Wasted-Spend) Alerts\",\n description:\n \"Use this to find wasted PPC ad spend. Retrieves a paginated list of blind-spend alerts across the \" +\n \"user's connected Amazon seller accounts — an alert flags ad spend on customer search terms that produced \" +\n \"little or no sales. By default returns active (unresolved) alerts from the last 30 days; filter by \" +\n \"`sellerId`, `marketplace`, `status`, or `updatedSince` (for incremental polling). Each item includes id, \" +\n \"asin, title, imageUrl, sellerId, marketplace, lastAlertedAt, resolvedAt, wastedSpend (total ad spend \" +\n \"across unresolved terms), totalKeywordCount, unresolvedKeywordCount, and searchTerms — the unresolved \" +\n \"wasted-spend search terms, each with term, spend, sales, clicks, cvr (0-1), and impressions. Supports \" +\n \"pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).\",\n inputSchema: alertsQueryInputSchema,\n handler: async (args, ctx) => {\n return await httpGet<BlindSpendAlertList>(\n { config: ctx.config, toolName: \"list_blind_spend_alerts\" },\n \"/v1/alerts/blind-spend\",\n {\n sellerId: args.sellerId,\n marketplace: args.marketplace,\n status: args.status,\n updatedSince: args.updatedSince,\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","import { httpGet } from \"../http/client.js\";\nimport type { Quota } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {};\n\nexport const getQuotaTool: ToolDefinition<typeof inputSchema> = {\n name: \"get_quota\",\n title: \"Get Quota Usage\",\n description:\n \"Use this when the user asks how much quota or how many tokens they have left, or before creating a \" +\n \"Niche Dive or Rank Radar to check remaining headroom. \" +\n \"Returns current quota usage and capacity for each billable feature — DIVED_ASINS (Dive tokens), \" +\n \"RANK_RADAR_KEYWORDS (tracked keywords), PRODUCT_BRIEF_ASINS, and AI_COPYWRITER_PROMPTS — each with \" +\n \"`used` and `capacity` (null when unlimited / not applicable), plus `nextRefreshDate` (ISO-8601 \" +\n \"timestamp of the next quota reset, or null). Takes no arguments.\",\n inputSchema,\n handler: async (_args, ctx) => {\n return await httpGet<Quota>({ config: ctx.config, toolName: \"get_quota\" }, \"/v1/quota\");\n },\n};\n","import { z } from \"zod\";\nimport { httpGet } from \"../http/client.js\";\nimport { BILLABLE_FEATURE_TYPES, ISO_8601, type UsageLogList } from \"../types/api.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\nconst inputSchema = {\n type: z\n .enum(BILLABLE_FEATURE_TYPES)\n .optional()\n .describe(\"Filter to a single billable feature type. Omit to return all types.\"),\n search: z\n .string()\n .min(1)\n .optional()\n .describe(\"Case-insensitive partial match on the user's name or email.\"),\n startDate: z\n .string()\n .regex(ISO_8601, \"startDate must be an ISO-8601 date or timestamp (e.g. 2026-05-01 or 2026-05-01T00:00:00Z)\")\n .optional()\n .describe(\"ISO-8601 date/timestamp; return only usage logs recorded on or after this time.\"),\n endDate: z\n .string()\n .regex(ISO_8601, \"endDate must be an ISO-8601 date or timestamp (e.g. 2026-05-31 or 2026-05-31T23:59:59Z)\")\n .optional()\n .describe(\"ISO-8601 date/timestamp; return only usage logs recorded on or before this time.\"),\n currentPage: z.number().int().min(1).optional().describe(\"Page number, 1-indexed. Defaults to 1.\"),\n pageSize: z\n .number()\n .int()\n .min(1)\n .max(200)\n .optional()\n .describe(\"Items per page (max 200). Defaults to 50.\"),\n};\n\nexport const listUsageTool: ToolDefinition<typeof inputSchema> = {\n name: \"list_usage\",\n title: \"List Billable Usage Logs\",\n description:\n \"Use this when the user asks who consumed tokens, how their quota was spent, or wants an audit of \" +\n \"billable activity over a date range. \" +\n \"Retrieves a paginated list of billable feature usage logs for the organization — each entry is a \" +\n \"token-consumption event (a dive, rank-radar creation, AI copywriter prompt, etc.). Filter by `type` \" +\n \"(billable feature), `search` (user name/email), and `startDate`/`endDate`. Each item includes name, \" +\n \"email, qty (tokens consumed), type, action (specific operation), nicheId/nicheName, rankRadarId, and \" +\n \"date, plus pagination metadata (currentPage, pageSize, total, lastPage, hasNext, hasPrev).\",\n inputSchema,\n handler: async (args, ctx) => {\n return await httpGet<UsageLogList>(\n { config: ctx.config, toolName: \"list_usage\" },\n \"/v1/usage\",\n {\n type: args.type,\n search: args.search,\n startDate: args.startDate,\n endDate: args.endDate,\n currentPage: args.currentPage,\n pageSize: args.pageSize,\n },\n );\n },\n};\n","/**\n * Tool registry. The order here is the order tools appear in `tools/list`\n * over the MCP transport, which biases LLM discovery — keep \"discovery\" tools\n * (the ones that return IDs needed by other tools) at the top.\n */\n\nimport { listNichesTool } from \"./list-niches.js\";\nimport { getNicheKeywordsTool } from \"./get-niche-keywords.js\";\nimport { getNicheRootsTool } from \"./get-niche-roots.js\";\nimport { getNicheCompetitorsTool } from \"./get-niche-competitors.js\";\nimport { getRankingJuiceTool } from \"./get-ranking-juice.js\";\nimport { listRankRadarsTool } from \"./list-rank-radars.js\";\nimport { getRankRadarDataTool } from \"./get-rank-radar-data.js\";\nimport { createRankRadarTool } from \"./create-rank-radar.js\";\nimport { createNicheDiveTool } from \"./create-niche-dive.js\";\nimport { getDiveStatusTool } from \"./get-dive-status.js\";\nimport { listSellerProfilesTool } from \"./list-seller-profiles.js\";\nimport { getSellerCatalogTool } from \"./get-seller-catalog.js\";\nimport { getSellerListingChangesTool } from \"./get-seller-listing-changes.js\";\nimport { getAsinInventoryDistributionTool } from \"./get-asin-inventory-distribution.js\";\nimport { listIndexingIssueAlertsTool } from \"./list-indexing-issue-alerts.js\";\nimport { listBlindSpendAlertsTool } from \"./list-blind-spend-alerts.js\";\nimport { getQuotaTool } from \"./get-quota.js\";\nimport { listUsageTool } from \"./list-usage.js\";\nimport type { AnyTool } from \"./types.js\";\n\n// Note on the cast: each ToolDefinition<S> has a handler typed to its specific\n// schema; the registry needs a uniform shape. The MCP SDK validates incoming\n// args against `inputSchema` before calling the handler, so the cast is safe.\nexport const allTools: ReadonlyArray<AnyTool> = [\n listNichesTool,\n getNicheKeywordsTool,\n getNicheRootsTool,\n getNicheCompetitorsTool,\n getRankingJuiceTool,\n listRankRadarsTool,\n getRankRadarDataTool,\n createRankRadarTool,\n createNicheDiveTool,\n getDiveStatusTool,\n listSellerProfilesTool,\n getSellerCatalogTool,\n getSellerListingChangesTool,\n getAsinInventoryDistributionTool,\n listIndexingIssueAlertsTool,\n listBlindSpendAlertsTool,\n getQuotaTool,\n listUsageTool,\n] as unknown as ReadonlyArray<AnyTool>;\n\nexport type { ToolDefinition, AnyTool } from \"./types.js\";\n"],"mappings":";;;AAOA,SAAS,4BAA4B;;;ACgBrC,IAAM,mBAAmB;AACzB,IAAM,eAAe;AAEd,SAAS,WAAW,MAAyB,QAAQ,KAAa;AACvE,QAAM,UAAU,IAAI,oBAAoB,IAAI,KAAK;AACjD,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR,sEAAsE,YAAY;AAAA,IAEpF;AAAA,EACF;AAEA,QAAM,WAAW,IAAI,yBAAyB,kBAAkB,KAAK;AAErE,QAAM,UAAU,QAAQ,QAAQ,QAAQ,EAAE;AAE1C,QAAM,oBAAoB,CAAC,KAAK,QAAQ,KAAK,EAAE;AAAA,KAC5C,IAAI,gCAAgC,IAAI,KAAK,EAAE,YAAY;AAAA,EAC9D;AAEA,SAAO,EAAE,QAAQ,SAAS,kBAAkB;AAC9C;;;ACnCA,SAAS,iBAAiB;;;ACT1B,SAAS,SAAS;;;ACalB,IAAMA,gBAAe;AAad,IAAM,WAAN,MAAM,kBAAiB,MAAM;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,MAAoB,QAAgB,SAAiB,MAAgB;AAC/E,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AAAA,EAEA,OAAO,SAAS,QAAgB,MAAyB;AACvD,UAA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UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;;;AFvDA,eAAe,OAAO;AACpB,MAAI;AACJ,MAAI;AACF,aAAS,WAAW;AAAA,EACtB,SAAS,KAAK;AAGZ,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,YAAQ,OAAO,MAAM,kBAAkB,GAAG;AAAA,CAAI;AAC9C,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,QAAM,SAAS,YAAY,MAAM;AACjC,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,QAAM,MAAM,eAAe,QAAS,IAAI,SAAS,IAAI,UAAW,OAAO,GAAG;AAC1E,UAAQ,OAAO,MAAM,yBAAyB,GAAG;AAAA,CAAI;AACrD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["KEY_HELP_URL","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","z","z","inputSchema","z","z","inputSchema","z","z","inputSchema","z","z","z","inputSchema","z","inputSchema","z"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datadive-tools/mcp",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "MCP server for DataDive — query your niches, keywords, competitors, and Rank Radar data from Claude Desktop, Claude Code, or Cursor.",
5
5
  "type": "module",
6
6
  "bin": {