@kantadev/cli 0.1.3 → 0.1.6

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
@@ -13,7 +13,8 @@ Find**, and the **Kanta Database**. Thin wrapper over the `api.kanta.dev` and
13
13
 
14
14
  ```bash
15
15
  npm install -g @kantadev/cli
16
- kanta login # paste your API key from app.kanta.dev
16
+ kanta login # opens app.kanta.dev in your browser; approve the code shown
17
+ # --no-browser prints the link; --key pastes an API key instead
17
18
  ```
18
19
 
19
20
  Local/dev:
@@ -71,7 +72,7 @@ same key: `--db-url` → `KANTA_DB_URL` → profile `db_base_url` →
71
72
  ```
72
73
 
73
74
  ```bash
74
- kanta login --profile personal # prompts for the key (hidden), validates via GET /me
75
+ kanta login --profile personal # browser sign-in, saved as the "personal" profile
75
76
  kanta whoami
76
77
  kanta config show # resolved config, key masked
77
78
  kanta logout --profile personal
@@ -81,7 +82,9 @@ kanta logout --profile personal
81
82
 
82
83
  ```bash
83
84
  kanta verify name@example.com
84
- kanta verify bulk contacts.csv # CSV needs an "email" column
85
+ kanta verify bulk contacts.csv # email column detected ("email", "Email Address", "Work Email", ...)
86
+ kanta verify bulk contacts.csv -o results.csv # wait for the job, then save every result
87
+ kanta verify bulk contacts.csv --max-credits 5000 # refuse if it would cost more
85
88
  kanta find Ada Lovelace analytical.co # synchronous — prints the email (or "no email found")
86
89
  kanta find bulk people.csv # CSV needs first_name,last_name,company; prints a job id
87
90
  kanta jobs list [--status <s>]
@@ -174,7 +177,7 @@ Admin capability is **not** self-service. It requires an `api_keys` row with
174
177
  2. Generate a normal key from `app.kanta.dev` for the operator.
175
178
  3. In Supabase Studio → Table Editor → `api_keys`, find that row (match on
176
179
  `label` or `last_used_at`) and set `scope` to `admin`. Save.
177
- 4. `kanta login --profile admin` with that key.
180
+ 4. `kanta login --profile admin --key` with that key.
178
181
 
179
182
  Revoke by setting `scope` back to `user`. No API path or dashboard UI reads or
180
183
  writes `scope`, so a leaked standard key can never reach `/admin/*`.
@@ -189,7 +192,7 @@ See the config block at the top of this file. Admin tools appear in
189
192
  `kanta_job_results` (pass `output` to save every row to a CSV), `kanta_job_wait`, `kanta_job_cancel`, `kanta_job_resume`, `kanta_job_delete`, `kanta_account`,
190
193
  `kanta_credits`
191
194
  - Database: `kanta_db_count`, `kanta_db_search`, `kanta_db_facets`,
192
- `kanta_db_lookup`, `kanta_db_export`, `kanta_db_export_status`,
195
+ `kanta_db_lookup`, `kanta_db_export` (pass `output` to wait and save), `kanta_db_export_status`, `kanta_db_export_download`,
193
196
  `kanta_db_companies_count`, `kanta_db_companies_search`,
194
197
  `kanta_db_companies_facets`, `kanta_db_company_contacts`
195
198
  - Admin: `kanta_admin_credits_add`, `kanta_admin_jobs_list`, `kanta_admin_user`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kantadev/cli",
3
- "version": "0.1.3",
3
+ "version": "0.1.6",
4
4
  "description": "Kanta CLI + MCP server — email verification, email finding, and the Kanta B2B contact database from your terminal or an MCP client.",
5
5
  "mcpName": "dev.kanta/cli",
6
6
  "type": "module",
package/server.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "dev.kanta/cli",
4
4
  "description": "Kanta Verify, Find, and Database: email verification, email finding, and B2B contact search.",
5
- "version": "0.1.3",
5
+ "version": "0.1.6",
6
6
  "repository": {
7
7
  "url": "https://github.com/griffinkanta/kanta-dev",
8
8
  "source": "github",
@@ -12,7 +12,7 @@
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "@kantadev/cli",
15
- "version": "0.1.3",
15
+ "version": "0.1.6",
16
16
  "runtimeHint": "npx",
17
17
  "packageArguments": [
18
18
  {
@@ -0,0 +1,66 @@
1
+ // After a bulk submit: optionally wait for the job (progress on stderr) and save its results.
2
+ import { rootProgram, globalOpts, writeOut, CliExit } from './context.js';
3
+ import { toCsv, printJson, printTable } from './format.js';
4
+ import { waitForJob } from '../core/jobs.js';
5
+ import { creditCheck, CreditCapError } from '../core/creditGuard.js';
6
+
7
+ // Print the cost/balance line (stderr) and stop if --max-credits would be exceeded.
8
+ export async function guardCredits(cmd, client, opts) {
9
+ let check;
10
+ try {
11
+ check = await creditCheck(client, { ...opts, capName: '--max-credits' });
12
+ } catch (err) {
13
+ if (err instanceof CreditCapError) throw new CliExit(err.message);
14
+ throw err;
15
+ }
16
+ if (!globalOpts(cmd).json) process.stderr.write(`${check.line}\n`);
17
+ if (check.warning) process.stderr.write(`Warning: ${check.warning}\n`);
18
+ return check;
19
+ }
20
+
21
+ export async function finishBulk(cmd, client, submitted, { wait, output, timeout, duplicatesRemoved }) {
22
+ const json = globalOpts(cmd).json;
23
+ const summary = { ...submitted, duplicates_removed: duplicatesRemoved };
24
+ if (duplicatesRemoved && !json) {
25
+ process.stderr.write(`Removed ${duplicatesRemoved} duplicate${duplicatesRemoved === 1 ? '' : 's'} before submitting.\n`);
26
+ }
27
+ if (!wait && !output) {
28
+ if (json) return printJson(summary);
29
+ printTable([submitted], [
30
+ { key: 'job_id', label: 'JOB ID' },
31
+ { key: 'total', label: 'TOTAL' },
32
+ { key: 'status', label: 'STATUS' },
33
+ ]);
34
+ process.stdout.write(`\nTrack it: kanta jobs get ${submitted.job_id}\n`);
35
+ return summary;
36
+ }
37
+
38
+ const sleep = rootProgram(cmd)._deps.sleep;
39
+ const tty = Boolean(process.stderr.isTTY) && !json;
40
+ const job = await waitForJob(client, submitted.job_id, {
41
+ sleep,
42
+ timeoutSeconds: timeout ? Number(timeout) : 3600,
43
+ onProgress: (j) => {
44
+ if (tty) process.stderr.write(`\r${j.status} ${j.completed ?? 0}/${j.total ?? '?'} `);
45
+ },
46
+ });
47
+ if (tty) process.stderr.write('\n');
48
+ if (job.timed_out) {
49
+ throw new CliExit(`Still ${job.status} after waiting. Check later: kanta jobs get ${submitted.job_id}`);
50
+ }
51
+ if (job.status !== 'complete') throw new CliExit(`Job ${submitted.job_id} ended ${job.status}.`);
52
+
53
+ const result = { ...summary, status: job.status, completed: job.completed };
54
+ if (output) {
55
+ const res = await client.getJobResults(submitted.job_id);
56
+ const rows = res.results || [];
57
+ writeOut(output, toCsv(rows));
58
+ result.rows_written = rows.length;
59
+ result.output = output;
60
+ if (!json) process.stdout.write(`Wrote ${rows.length} row${rows.length === 1 ? "" : "s"} to ${output}\n`);
61
+ } else if (!json) {
62
+ process.stdout.write(`Job ${submitted.job_id} complete (${job.completed}/${job.total}). Results: kanta jobs results ${submitted.job_id}\n`);
63
+ }
64
+ if (json) printJson(result);
65
+ return result;
66
+ }
@@ -141,6 +141,24 @@ export function registerDb(program) {
141
141
  }),
142
142
  );
143
143
 
144
+ db.command('industries')
145
+ .description('List industry names for --industry, with contact counts (sub-industries indented)')
146
+ .option('--min <n>', 'only industries with at least this many contacts', '0')
147
+ .action(
148
+ action(async (opts, cmd) => {
149
+ const client = getClient(cmd);
150
+ const res = await client.dbIndustries({ minContacts: parseInt(opts.min, 10) || 0 });
151
+ if (globalOpts(cmd).json) return printJson(res);
152
+ const walk = (nodes, depth) => {
153
+ for (const n of nodes) {
154
+ process.stdout.write(`${Number(n.contacts).toLocaleString('en-US').padStart(12)} ${' '.repeat(depth)}${n.name}\n`);
155
+ if (n.children) walk(n.children, depth + 1);
156
+ }
157
+ };
158
+ walk(res.industries || [], 0);
159
+ }),
160
+ );
161
+
144
162
  db.command('lookup')
145
163
  .description('Find one person by email, LinkedIn URL, or name + domain')
146
164
  .option('--email <email>')
@@ -1,5 +1,7 @@
1
1
  import { basename } from 'node:path';
2
2
  import { action, getClient, globalOpts, readCsv } from '../context.js';
3
+ import { dedupeContacts } from '../../core/bulkInput.js';
4
+ import { finishBulk, guardCredits } from '../bulkRun.js';
3
5
  import { printJson, printTable } from '../format.js';
4
6
 
5
7
  export function registerFind(program) {
@@ -33,25 +35,29 @@ export function registerFind(program) {
33
35
 
34
36
  find
35
37
  .command('bulk')
36
- .description('Submit a CSV of contacts as a bulk find job')
37
- .argument('<file>', 'CSV with first_name, last_name, company columns')
38
+ .description('Submit a CSV of contacts as a bulk find job (duplicates are removed first)')
39
+ .argument('<file>', 'CSV with first name, last name and company (or domain) columns')
40
+ .option('--first-col <name>', 'name of the first-name column, if it is not detected')
41
+ .option('--last-col <name>', 'name of the last-name column, if it is not detected')
42
+ .option('--company-col <name>', 'name of the company/domain column, if it is not detected')
43
+ .option('--wait', 'wait for the job to finish')
44
+ .option('-o, --output <file>', 'wait, then write the results to this CSV')
45
+ .option('--timeout <seconds>', 'give up waiting after this long (default 3600)')
46
+ .option('--max-credits <n>', 'refuse to submit if the job could cost more than this')
38
47
  .action(
39
- action(async (file, _opts, cmd) => {
40
- const rows = readCsv(file, ['first_name', 'last_name', 'company']);
41
- const contacts = rows.map(r => ({
48
+ action(async (file, opts, cmd) => {
49
+ const rows = readCsv(file, ['first_name', 'last_name', 'company'], {
50
+ first_name: opts.firstCol, last_name: opts.lastCol, company: opts.companyCol,
51
+ });
52
+ const { items: contacts, removed } = dedupeContacts(rows.map(r => ({
42
53
  firstName: r.first_name,
43
54
  lastName: r.last_name,
44
55
  company: r.company,
45
- }));
56
+ })));
46
57
  const client = getClient(cmd);
58
+ await guardCredits(cmd, client, { product: 'find', units: contacts.length, upperBound: true, maxCredits: opts.maxCredits });
47
59
  const res = await client.findBulk(contacts, { filename: basename(file) });
48
- if (globalOpts(cmd).json) return printJson(res);
49
- printTable([res], [
50
- { key: 'job_id', label: 'JOB ID' },
51
- { key: 'total', label: 'TOTAL' },
52
- { key: 'status', label: 'STATUS' },
53
- ]);
54
- process.stdout.write(`\nTrack it: kanta jobs get ${res.job_id}\n`);
60
+ await finishBulk(cmd, client, res, { ...opts, duplicatesRemoved: removed });
55
61
  }),
56
62
  );
57
63
  }
@@ -69,7 +69,7 @@ export function registerJobs(program) {
69
69
  const rows = out.results || [];
70
70
  if (opts.output) {
71
71
  writeOut(opts.output, toCsv(rows));
72
- process.stdout.write(`Wrote ${rows.length} rows to ${opts.output}\n`);
72
+ process.stdout.write(`Wrote ${rows.length} row${rows.length === 1 ? "" : "s"} to ${opts.output}\n`);
73
73
  return;
74
74
  }
75
75
  if (globalOpts(cmd).json) return printJson(out);
@@ -1,4 +1,5 @@
1
1
  import { createInterface } from 'node:readline';
2
+ import { hostname } from 'node:os';
2
3
  import { action, globalOpts, rootProgram, CliExit } from '../context.js';
3
4
  import {
4
5
  loadConfig,
@@ -43,20 +44,46 @@ async function readKey() {
43
44
  export function registerLogin(program) {
44
45
  program
45
46
  .command('login')
46
- .description('Validate an API key and save it as a profile')
47
+ .description('Sign in through your browser (or paste a key with --key) and save it as a profile')
47
48
  .option('--profile <name>', 'profile name to save under', 'personal')
48
49
  .option('--base-url <url>', 'API base URL', DEFAULT_BASE_URL)
50
+ .option('--key', 'paste an API key instead of signing in through the browser')
51
+ .option('--no-browser', 'print the sign-in link instead of opening a browser')
49
52
  .action(
50
53
  action(async (opts, cmd) => {
54
+ const deps = rootProgram(cmd)._deps;
55
+ // `--profile` also exists on the root program and is parsed there first.
56
+ const profile = globalOpts(cmd).profile || opts.profile;
57
+ const baseUrl = opts.baseUrl || DEFAULT_BASE_URL;
58
+ const json = globalOpts(cmd).json;
59
+ // Piped input (echo $KEY | kanta login) keeps working as a key login.
60
+ if (!opts.key && deps.stdinIsTTY) {
61
+ const { apiKey, email } = await deps.browserLogin({
62
+ baseUrl,
63
+ clientName: `${hostname()} (kanta CLI)`.slice(0, 64),
64
+ openUrl: opts.browser ? undefined : () => { throw new Error('no browser'); },
65
+ onCode: (s) => {
66
+ if (json) return;
67
+ process.stdout.write(
68
+ `Your code: ${s.user_code}\n` +
69
+ `${opts.browser ? 'Opening' : 'Open'} ${s.verification_uri_complete}\n` +
70
+ 'Approve it in the browser; waiting...\n',
71
+ );
72
+ },
73
+ }).catch((err) => { throw new CliExit(err.message); });
74
+ setProfile(profile, { key: apiKey, base_url: baseUrl });
75
+ if (json) return printJson({ saved: profile, email });
76
+ process.stdout.write(`Signed in as ${email || 'your account'}. Saved profile "${profile}" to ${configPath()}\n`);
77
+ return;
78
+ }
51
79
  const key = await readKey();
52
80
  if (!key) throw new CliExit('No key entered.');
53
- const baseUrl = opts.baseUrl || DEFAULT_BASE_URL;
54
81
  const client = new KantaClient({ key, baseUrl });
55
82
  const me = await client.getMe();
56
- setProfile(opts.profile, { key, base_url: baseUrl });
57
- if (globalOpts(cmd).json) return printJson({ saved: opts.profile, email: me.email, scope: me.scope });
83
+ setProfile(profile, { key, base_url: baseUrl });
84
+ if (globalOpts(cmd).json) return printJson({ saved: profile, email: me.email, scope: me.scope });
58
85
  process.stdout.write(
59
- `Saved profile "${opts.profile}" (${me.email}, scope: ${me.scope}) to ${configPath()}\n`,
86
+ `Saved profile "${profile}" (${me.email}, scope: ${me.scope}) to ${configPath()}\n`,
60
87
  );
61
88
  }),
62
89
  );
@@ -68,7 +95,7 @@ export function registerLogin(program) {
68
95
  .action(
69
96
  action(async (opts, cmd) => {
70
97
  const config = loadConfig();
71
- const name = opts.profile || config.default_profile;
98
+ const name = globalOpts(cmd).profile || opts.profile || config.default_profile;
72
99
  if (!name) throw new CliExit('No profile specified and no default set.');
73
100
  removeProfile(name);
74
101
  if (globalOpts(cmd).json) return printJson({ removed: name });
@@ -1,6 +1,8 @@
1
1
  import { basename } from 'node:path';
2
2
  import { action, getClient, globalOpts, readCsv, CliExit } from '../context.js';
3
- import { printJson, printTable } from '../format.js';
3
+ import { dedupeEmails } from '../../core/bulkInput.js';
4
+ import { finishBulk, guardCredits } from '../bulkRun.js';
5
+ import { printJson } from '../format.js';
4
6
 
5
7
  export function registerVerify(program) {
6
8
  const verify = program
@@ -20,25 +22,26 @@ export function registerVerify(program) {
20
22
 
21
23
  verify
22
24
  .command('bulk')
23
- .description('Submit a CSV of emails as a bulk verify job')
24
- .argument('<file>', 'CSV file with an "email" column')
25
+ .description('Submit a CSV of emails as a bulk verify job (duplicates are removed first)')
26
+ .argument('<file>', 'CSV with an email column ("email", "Email Address", "Work Email", ...)')
27
+ .option('--email-col <name>', 'name of the email column, if it is not detected')
25
28
  .option('--webhook <url>', 'webhook URL to notify on completion')
29
+ .option('--wait', 'wait for the job to finish')
30
+ .option('-o, --output <file>', 'wait, then write the results to this CSV')
31
+ .option('--timeout <seconds>', 'give up waiting after this long (default 3600)')
32
+ .option('--max-credits <n>', 'refuse to submit if the job would cost more than this')
26
33
  .action(
27
34
  action(async (file, opts, cmd) => {
28
- const rows = readCsv(file, ['email']);
29
- const emails = rows.map(r => r.email).filter(Boolean);
30
- if (emails.length === 0) throw new CliExit('No non-empty "email" values in the file.');
35
+ const rows = readCsv(file, ['email'], { email: opts.emailCol });
36
+ const { items: emails, removed } = dedupeEmails(rows.map(r => r.email));
37
+ if (emails.length === 0) throw new CliExit('No non-empty email values in the file.');
31
38
  const client = getClient(cmd);
39
+ await guardCredits(cmd, client, { product: 'verify', units: emails.length, maxCredits: opts.maxCredits });
32
40
  const res = await client.verifyBulk(emails, {
33
41
  filename: basename(file),
34
42
  webhook: opts.webhook,
35
43
  });
36
- if (globalOpts(cmd).json) return printJson(res);
37
- printTable([res], [
38
- { key: 'job_id', label: 'JOB ID' },
39
- { key: 'total', label: 'TOTAL' },
40
- { key: 'status', label: 'STATUS' },
41
- ]);
44
+ await finishBulk(cmd, client, res, { ...opts, duplicatesRemoved: removed });
42
45
  }),
43
46
  );
44
47
  }
@@ -1,4 +1,6 @@
1
1
  // Shared helpers for CLI commands.
2
+ import { browserLogin as realBrowserLogin } from '../core/browserLogin.js';
3
+ import { resolveColumns } from '../core/bulkInput.js';
2
4
  import { readFileSync, existsSync, writeFileSync } from 'node:fs';
3
5
  import { createInterface } from 'node:readline';
4
6
  import { parse as csvParse } from 'csv-parse/sync';
@@ -40,6 +42,10 @@ export function defaultDeps() {
40
42
  whoamiFn(o) {
41
43
  return whoami({ profile: o.profile, apiKey: o.apiKey, baseUrl: o.baseUrl });
42
44
  },
45
+ browserLogin(opts) {
46
+ return realBrowserLogin(opts);
47
+ },
48
+ stdinIsTTY: Boolean(process.stdin.isTTY),
43
49
  confirm(question) {
44
50
  return defaultConfirm(question);
45
51
  },
@@ -105,7 +111,9 @@ export function action(fn) {
105
111
  };
106
112
  }
107
113
 
108
- export function readCsv(path, requiredColumns) {
114
+ // Returns rows keyed by the canonical column names (email / first_name / last_name /
115
+ // company), whatever the file's own headers are; see core/bulkInput.js for accepted spellings.
116
+ export function readCsv(path, requiredColumns, overrides = {}) {
109
117
  if (!existsSync(path)) throw new CliExit(`File not found: ${path}`);
110
118
  const raw = readFileSync(path, 'utf8');
111
119
  if (!raw.trim()) throw new CliExit(`File is empty: ${path}`);
@@ -117,16 +125,18 @@ export function readCsv(path, requiredColumns) {
117
125
  }
118
126
  if (records.length === 0) throw new CliExit(`No data rows in ${path}`);
119
127
  const found = Object.keys(records[0]);
120
- const missing = requiredColumns.filter(c => !found.includes(c));
128
+ const { map, missing } = resolveColumns(found, requiredColumns, overrides);
121
129
  if (missing.length) {
130
+ const flags = missing.map((c) => `--${c.replace('_name', '').replace('_', '-')}-col`).join(', ');
122
131
  throw new CliExit(
123
- `CSV ${path} is missing column(s): ${missing.join(', ')}. Expected: ${requiredColumns.join(', ')}. Found: ${found.join(', ')}.`,
132
+ `CSV ${path} is missing column(s): ${missing.join(', ')}. Found: ${found.join(', ')}. ` +
133
+ `Rename the header or name it with ${flags}.`,
124
134
  );
125
135
  }
126
136
  if (records.length > MAX_ROWS) {
127
137
  throw new CliExit(`${records.length} rows exceeds the ${MAX_ROWS} per-job limit. Split the file.`);
128
138
  }
129
- return records;
139
+ return records.map((r) => Object.fromEntries(requiredColumns.map((c) => [c, r[map[c]]])));
130
140
  }
131
141
 
132
142
  export function writeOut(path, content) {
@@ -0,0 +1,52 @@
1
+ // Browser sign-in (device authorization flow) against the Kanta API:
2
+ // start -> show the code and open the approval page -> poll until the user
3
+ // approves in the web app -> receive a freshly created API key (handed out once).
4
+ import { spawn } from 'node:child_process';
5
+
6
+ export function openInBrowser(url) {
7
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [url]]
8
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]]
9
+ : ['xdg-open', [url]];
10
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
11
+ child.on('error', () => {});
12
+ child.unref();
13
+ }
14
+
15
+ const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
16
+
17
+ async function post(fetchImpl, url, body) {
18
+ const res = await fetchImpl(url, {
19
+ method: 'POST',
20
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
21
+ body: JSON.stringify(body),
22
+ });
23
+ let data = {};
24
+ try { data = await res.json(); } catch { /* empty body */ }
25
+ return { status: res.status, ok: res.ok, data };
26
+ }
27
+
28
+ export async function browserLogin({
29
+ baseUrl, clientName, fetchImpl = globalThis.fetch, openUrl = openInBrowser,
30
+ onCode = () => {}, sleep = realSleep, now = Date.now,
31
+ }) {
32
+ const base = String(baseUrl).replace(/\/+$/, '');
33
+ const start = await post(fetchImpl, `${base}/cli/auth/start`, { client_name: clientName });
34
+ if (!start.ok) throw new Error(`Could not start sign-in (${start.data.error || `HTTP ${start.status}`}).`);
35
+ const s = start.data;
36
+ onCode(s);
37
+ try { openUrl(s.verification_uri_complete); } catch { /* headless: the URL is printed */ }
38
+
39
+ let intervalMs = (s.interval || 3) * 1000;
40
+ const deadline = now() + (s.expires_in || 600) * 1000;
41
+ while (now() < deadline) {
42
+ await sleep(intervalMs);
43
+ const p = await post(fetchImpl, `${base}/cli/auth/poll`, { device_code: s.device_code });
44
+ if (p.status === 429) { intervalMs += 5000; continue; }
45
+ if (!p.ok) throw new Error(`Sign-in failed (${p.data.error || `HTTP ${p.status}`}).`);
46
+ const st = p.data.status;
47
+ if (st === 'approved') return { apiKey: p.data.api_key, email: p.data.email };
48
+ if (st === 'denied') throw new Error('Sign-in was denied in the browser.');
49
+ if (st === 'expired') throw new Error('The sign-in code expired. Run kanta login again.');
50
+ }
51
+ throw new Error('The sign-in code expired. Run kanta login again.');
52
+ }
@@ -0,0 +1,64 @@
1
+ // Shared input handling for bulk verify/find (CLI and MCP): find the right CSV
2
+ // columns under common header spellings, and drop duplicate rows before they
3
+ // are submitted (every submitted row costs a credit).
4
+
5
+ const ALIASES = {
6
+ email: ['email', 'e-mail', 'email address', 'email_address', 'work email', 'business email', 'contact email', 'mail'],
7
+ first_name: ['first_name', 'first name', 'firstname', 'first', 'given name', 'fname'],
8
+ last_name: ['last_name', 'last name', 'lastname', 'last', 'surname', 'family name', 'lname'],
9
+ company: ['company', 'company name', 'company_name', 'organization', 'organisation', 'account name',
10
+ 'company domain', 'company_domain', 'domain', 'website', 'company website'],
11
+ };
12
+
13
+ export const COLUMN_ALIASES = ALIASES;
14
+
15
+ const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
16
+
17
+ // headers: CSV header row; wanted: canonical names; overrides: { email: 'Backup Email' }.
18
+ // Returns { map: { canonical: header }, missing: [canonical...] }.
19
+ export function resolveColumns(headers, wanted, overrides = {}) {
20
+ const map = {};
21
+ const missing = [];
22
+ for (const w of wanted) {
23
+ if (overrides[w]) {
24
+ const hit = headers.find((h) => h === overrides[w]) ?? headers.find((h) => norm(h) === norm(overrides[w]));
25
+ if (hit !== undefined) map[w] = hit; else missing.push(w);
26
+ continue;
27
+ }
28
+ let hit;
29
+ for (const alias of ALIASES[w] || [w]) {
30
+ hit = headers.find((h) => norm(h) === norm(alias));
31
+ if (hit !== undefined) break;
32
+ }
33
+ if (hit !== undefined) map[w] = hit; else missing.push(w);
34
+ }
35
+ return { map, missing };
36
+ }
37
+
38
+ function dedupe(items, keyOf) {
39
+ const seen = new Set();
40
+ const out = [];
41
+ let removed = 0;
42
+ for (const item of items) {
43
+ const key = keyOf(item);
44
+ if (!key) continue;
45
+ if (seen.has(key)) { removed += 1; continue; }
46
+ seen.add(key);
47
+ out.push(item);
48
+ }
49
+ return { items: out, removed };
50
+ }
51
+
52
+ const clean = (s) => String(s ?? '').trim().toLowerCase();
53
+
54
+ export function dedupeEmails(emails) {
55
+ const r = dedupe(emails.map((e) => String(e ?? '').trim()), (e) => clean(e));
56
+ return r;
57
+ }
58
+
59
+ export function dedupeContacts(contacts) {
60
+ return dedupe(contacts, (c) => {
61
+ const parts = [c.firstName, c.lastName, c.company].map(clean);
62
+ return parts.some(Boolean) ? parts.join('|') : '';
63
+ });
64
+ }
@@ -233,6 +233,12 @@ export class KantaClient {
233
233
  return this._dbRequest('POST', '/db/search', { body: { filter, limit, cursor }, retry: true });
234
234
  }
235
235
 
236
+ // Canonical industry names (a tree, with contact counts) usable in the industry filter.
237
+ dbIndustries({ minContacts } = {}) {
238
+ const q = minContacts ? `?min_contacts=${encodeURIComponent(minContacts)}` : '';
239
+ return this._dbRequest('GET', `/db/industries${q}`, { retry: true });
240
+ }
241
+
236
242
  dbCount(filter) {
237
243
  return this._dbRequest('POST', '/db/count', { body: { filter }, retry: true });
238
244
  }
@@ -0,0 +1,29 @@
1
+ // Before a bulk job: work out its credit cost, read the balance, and enforce a
2
+ // caller-set cap. A low balance is only a warning — unlimited accounts report a
3
+ // normal balance, and the API deducts (or refuses) atomically at submit time.
4
+ export class CreditCapError extends Error {}
5
+
6
+ export async function creditCheck(client, { product, units, upperBound = false, maxCredits, capName = 'max_credits' }) {
7
+ const label = `${product} credit${units === 1 ? '' : 's'}`;
8
+ if (maxCredits != null && maxCredits !== '' && units > Number(maxCredits)) {
9
+ throw new CreditCapError(`This job costs ${upperBound ? 'up to ' : ''}${units} ${label}, over ${capName} ${maxCredits}.`);
10
+ }
11
+ let balance = null;
12
+ try {
13
+ const acct = await client.getAccount();
14
+ const v = acct?.[`${product}_credits`];
15
+ balance = typeof v === 'number' ? v : null;
16
+ } catch { /* balance unknown: the API still enforces it */ }
17
+
18
+ const costText = `${upperBound ? 'up to ' : ''}${units.toLocaleString('en-US')} ${label}`;
19
+ const line = `This job uses ${costText}${upperBound ? ' (charged only per email found)' : ''}` +
20
+ (balance != null ? ` (balance ${balance.toLocaleString('en-US')}).` : '.');
21
+ const warning = !upperBound && balance != null && units > balance
22
+ ? `This job needs ${units} ${label}; balance is ${balance}. The API will refuse it unless the account is unlimited.`
23
+ : null;
24
+ return {
25
+ line,
26
+ warning,
27
+ summary: { product, [upperBound ? 'max_cost' : 'cost']: units, balance_before: balance },
28
+ };
29
+ }
@@ -24,6 +24,14 @@ export class KantaAuthError extends Error {
24
24
  }
25
25
  }
26
26
 
27
+ // The API's own explanation: "detail" plus any "suggestions" (e.g. industry names).
28
+ export function apiErrorDetail(err) {
29
+ const detail = err?.extra?.detail ? String(err.extra.detail) : '';
30
+ const sugg = Array.isArray(err?.extra?.suggestions) && err.extra.suggestions.length
31
+ ? `Did you mean: ${err.extra.suggestions.map((v) => `"${v}"`).join(', ')}?` : '';
32
+ return [detail, sugg].filter(Boolean).join('. ');
33
+ }
34
+
27
35
  // Map a KantaApiError (or network error) to a human sentence for the CLI.
28
36
  export function humanizeError(err, { baseUrl } = {}) {
29
37
  if (err instanceof KantaApiError) {
@@ -38,6 +46,8 @@ export function humanizeError(err, { baseUrl } = {}) {
38
46
  return 'This command requires an admin profile. The active profile is a standard key.';
39
47
  case 'admin_filter':
40
48
  return 'The --verification-status filter requires an admin profile.';
49
+ case 'unknown_industry':
50
+ return apiErrorDetail(err) || 'No industry matches that name. Run: kanta db facets --field industry';
41
51
  case 'es_unavailable':
42
52
  return 'Kanta Database is temporarily unavailable. Try again shortly.';
43
53
  case 'confirm_credits_required': {
@@ -53,7 +63,9 @@ export function humanizeError(err, { baseUrl } = {}) {
53
63
  if (err.status === 401) return 'Key rejected. Run: kanta login';
54
64
  if (err.status === 403) return 'This command requires an admin profile. The active profile is a standard key.';
55
65
  if (err.status === 429) return 'Rate limited — retry in a few seconds.';
56
- return err.message || `Request failed (${err.status}).`;
66
+ const extra = apiErrorDetail(err);
67
+ const base = err.message || `Request failed (${err.status}).`;
68
+ return extra ? `${base}: ${extra}` : base;
57
69
  }
58
70
  if (err instanceof KantaConfigError || err instanceof KantaAuthError) {
59
71
  return err.message;
@@ -0,0 +1,19 @@
1
+ // Poll a verify/find job until it stops (complete, failed, cancelled, paused) or times out.
2
+ export const FINAL_STATUSES = new Set(['complete', 'failed', 'cancelled', 'paused']);
3
+ const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
4
+
5
+ export async function waitForJob(client, id, {
6
+ timeoutSeconds = 600, intervalSeconds = 5, sleep = realSleep, now = Date.now, onProgress,
7
+ } = {}) {
8
+ const timeoutMs = Math.min(timeoutSeconds, 3600) * 1000;
9
+ const intervalMs = Math.max(intervalSeconds, 2) * 1000;
10
+ const started = now();
11
+ for (;;) {
12
+ const job = await client.getJob(id);
13
+ if (onProgress) onProgress(job);
14
+ const waited = Math.round((now() - started) / 1000);
15
+ if (FINAL_STATUSES.has(job.status)) return { ...job, waited_seconds: waited, timed_out: false };
16
+ if (now() - started + intervalMs > timeoutMs) return { ...job, waited_seconds: waited, timed_out: true };
17
+ await sleep(intervalMs);
18
+ }
19
+ }
@@ -1,6 +1,7 @@
1
1
  // Build the MCP tool list. Admin tools are appended only when scope === 'admin'.
2
2
  // customerTools / adminTools already include the Kanta Database tools
3
3
  // (tools/database.js is spread into them).
4
+ import { apiErrorDetail } from '../core/errors.js';
4
5
  import { customerTools } from './tools/customer.js';
5
6
  import { adminTools } from './tools/admin.js';
6
7
 
@@ -22,9 +23,10 @@ export function wrapHandler(tool, { client }) {
22
23
  };
23
24
  } catch (err) {
24
25
  const detail = err?.status ? ` (HTTP ${err.status}${err.code ? `, ${err.code}` : ''})` : '';
26
+ const explain = apiErrorDetail(err);
25
27
  return {
26
28
  isError: true,
27
- content: [{ type: 'text', text: `${err?.message || 'Tool failed'}${detail}` }],
29
+ content: [{ type: 'text', text: `${err?.message || 'Tool failed'}${detail}${explain ? `\n${explain}` : ''}` }],
28
30
  };
29
31
  }
30
32
  };
@@ -5,29 +5,65 @@ import { resolve } from 'node:path';
5
5
  import { toCsv } from '../../cli/format.js';
6
6
  import { parse as csvParse } from 'csv-parse/sync';
7
7
  import { databaseTools } from './database.js';
8
+ import { resolveColumns, dedupeEmails, dedupeContacts } from '../../core/bulkInput.js';
9
+ import { waitForJob } from '../../core/jobs.js';
10
+ import { creditCheck } from '../../core/creditGuard.js';
8
11
 
9
12
  const INLINE_ROW_CAP = 100;
10
- const FINAL_STATUSES = new Set(['complete', 'failed', 'cancelled', 'paused']);
11
- const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
13
 
13
- function loadEmails(args) {
14
- if (Array.isArray(args.emails)) return args.emails.filter(Boolean);
15
- if (args.path) {
16
- const rows = csvParse(readFileSync(args.path, 'utf8'), { columns: true, skip_empty_lines: true, trim: true });
17
- return rows.map(r => r.email).filter(Boolean);
14
+
15
+ function readCsvColumns(path, wanted, overrides) {
16
+ const rows = csvParse(readFileSync(path, 'utf8'), { columns: true, skip_empty_lines: true, trim: true });
17
+ if (!rows.length) throw new Error(`No data rows in ${path}.`);
18
+ const { map, missing } = resolveColumns(Object.keys(rows[0]), wanted, overrides);
19
+ if (missing.length) {
20
+ throw new Error(`${path} has no ${missing.join(', ')} column (found: ${Object.keys(rows[0]).join(', ')}). ` +
21
+ 'Name it with the matching *_column argument.');
18
22
  }
23
+ return rows.map((r) => Object.fromEntries(wanted.map((w) => [w, r[map[w]]])));
24
+ }
25
+
26
+ function loadEmails(args) {
27
+ if (Array.isArray(args.emails)) return args.emails;
28
+ if (args.path) return readCsvColumns(args.path, ['email'], { email: args.email_column }).map((r) => r.email);
19
29
  throw new Error('Provide either "emails" (array) or "path" (CSV with an email column).');
20
30
  }
21
31
 
22
32
  function loadContacts(args) {
23
33
  if (Array.isArray(args.contacts)) return args.contacts;
24
34
  if (args.path) {
25
- const rows = csvParse(readFileSync(args.path, 'utf8'), { columns: true, skip_empty_lines: true, trim: true });
26
- return rows.map(r => ({ firstName: r.first_name, lastName: r.last_name, company: r.company }));
35
+ return readCsvColumns(args.path, ['first_name', 'last_name', 'company'], {
36
+ first_name: args.first_name_column, last_name: args.last_name_column, company: args.company_column,
37
+ }).map((r) => ({ firstName: r.first_name, lastName: r.last_name, company: r.company }));
38
+ }
39
+ throw new Error('Provide either "contacts" (array) or "path" (CSV with first name, last name, company columns).');
40
+ }
41
+
42
+ // After a bulk submit: optionally wait for the job and write its results to a local CSV.
43
+ async function finishBulk(submitted, removed, a, ctx) {
44
+ const out = { ...submitted, duplicates_removed: removed };
45
+ if (!a.wait && !a.output) return out;
46
+ const job = await waitForJob(ctx.client, submitted.job_id, {
47
+ timeoutSeconds: a.timeout_seconds ?? 600, sleep: ctx.sleep, now: ctx.now,
48
+ });
49
+ Object.assign(out, { status: job.status, completed: job.completed, waited_seconds: job.waited_seconds, timed_out: job.timed_out });
50
+ if (a.output && job.status === 'complete') {
51
+ const res = await ctx.client.getJobResults(submitted.job_id);
52
+ const rows = res.results || [];
53
+ const path = resolve(a.output);
54
+ writeFileSync(path, toCsv(rows));
55
+ Object.assign(out, { rows_written: rows.length, output: path });
27
56
  }
28
- throw new Error('Provide either "contacts" (array) or "path" (CSV with first_name,last_name,company).');
57
+ return out;
29
58
  }
30
59
 
60
+ const WAIT_PROPS = {
61
+ max_credits: { type: 'integer', minimum: 1, description: 'refuse to submit if the job could cost more than this' },
62
+ wait: { type: 'boolean', description: 'wait for the job to finish (default false)' },
63
+ output: { type: 'string', description: 'wait, then write all results to this local CSV path' },
64
+ timeout_seconds: { type: 'integer', minimum: 1, maximum: 3600, description: 'max wait, default 600' },
65
+ };
66
+
31
67
  function capResults(out) {
32
68
  const rows = out.results || [];
33
69
  if (rows.length > INLINE_ROW_CAP) {
@@ -44,7 +80,7 @@ function capResults(out) {
44
80
  export const customerTools = [
45
81
  {
46
82
  name: 'kanta_verify_email',
47
- description: 'Verify a single email address. Returns status (valid/invalid/risky/catch_all/disposable/unknown) and signal flags.',
83
+ description: 'Verify a single email address (1 verify credit). Returns status (valid/invalid/risky/catch_all/disposable/unknown), signal flags and credits_remaining.',
48
84
  inputSchema: {
49
85
  type: 'object',
50
86
  properties: { email: { type: 'string', description: 'Email address to verify' } },
@@ -54,18 +90,28 @@ export const customerTools = [
54
90
  },
55
91
  {
56
92
  name: 'kanta_verify_bulk',
57
- description: 'Submit a bulk email verification job. Provide "emails" (array) or "path" (CSV with an email column). Returns a job_id.',
93
+ description:
94
+ 'Submit a bulk email verification job (1 verify credit per email). Provide "emails" (array) or "path" ' +
95
+ '(CSV; the email column is detected from common headers like "Email Address"). Duplicates are removed ' +
96
+ 'before submitting. Set "output" to wait and save every result to a local CSV in one call.',
58
97
  inputSchema: {
59
98
  type: 'object',
60
99
  properties: {
61
100
  emails: { type: 'array', items: { type: 'string' } },
62
- path: { type: 'string', description: 'Path to a CSV file with an "email" column' },
101
+ path: { type: 'string', description: 'Path to a CSV file with an email column' },
102
+ email_column: { type: 'string', description: 'email column name, if it is not detected' },
63
103
  filename: { type: 'string' },
64
104
  webhook: { type: 'string' },
105
+ ...WAIT_PROPS,
65
106
  },
66
107
  },
67
- handler: (a, { client }) =>
68
- client.verifyBulk(loadEmails(a), { filename: a.filename, webhook: a.webhook }),
108
+ handler: async (a, ctx) => {
109
+ const { items, removed } = dedupeEmails(loadEmails(a));
110
+ if (!items.length) throw new Error('No email addresses to verify.');
111
+ const check = await creditCheck(ctx.client, { product: 'verify', units: items.length, maxCredits: a.max_credits });
112
+ const job = await ctx.client.verifyBulk(items, { filename: a.filename, webhook: a.webhook });
113
+ return { ...(await finishBulk(job, removed, a, ctx)), credits: check.summary, ...(check.warning ? { warning: check.warning } : {}) };
114
+ },
69
115
  },
70
116
  {
71
117
  name: 'kanta_find_email',
@@ -87,7 +133,11 @@ export const customerTools = [
87
133
  },
88
134
  {
89
135
  name: 'kanta_find_bulk',
90
- description: 'Submit a bulk find job. Provide "contacts" (array of {firstName,lastName,company}) or "path" (CSV). Returns a job_id.',
136
+ description:
137
+ 'Submit a bulk find job (a find credit is charged only per email found). Provide "contacts" ' +
138
+ '(array of {firstName,lastName,company}) or "path" (CSV; columns detected from headers like ' +
139
+ '"First Name", "Last Name", "Company Domain"). Duplicates are removed before submitting. ' +
140
+ 'Set "output" to wait and save every result to a local CSV in one call.',
91
141
  inputSchema: {
92
142
  type: 'object',
93
143
  properties: {
@@ -103,10 +153,20 @@ export const customerTools = [
103
153
  },
104
154
  },
105
155
  path: { type: 'string' },
156
+ first_name_column: { type: 'string' },
157
+ last_name_column: { type: 'string' },
158
+ company_column: { type: 'string' },
106
159
  filename: { type: 'string' },
160
+ ...WAIT_PROPS,
107
161
  },
108
162
  },
109
- handler: (a, { client }) => client.findBulk(loadContacts(a), { filename: a.filename }),
163
+ handler: async (a, ctx) => {
164
+ const { items, removed } = dedupeContacts(loadContacts(a));
165
+ if (!items.length) throw new Error('No contacts to find.');
166
+ const check = await creditCheck(ctx.client, { product: 'find', units: items.length, upperBound: true, maxCredits: a.max_credits });
167
+ const job = await ctx.client.findBulk(items, { filename: a.filename });
168
+ return { ...(await finishBulk(job, removed, a, ctx)), credits: check.summary };
169
+ },
110
170
  },
111
171
  {
112
172
  name: 'kanta_jobs_list',
@@ -169,18 +229,9 @@ export const customerTools = [
169
229
  },
170
230
  required: ['id'],
171
231
  },
172
- handler: async (a, { client, sleep = realSleep, now = Date.now }) => {
173
- const timeoutMs = Math.min(a.timeout_seconds ?? 600, 3600) * 1000;
174
- const intervalMs = Math.max(a.interval_seconds ?? 5, 2) * 1000;
175
- const started = now();
176
- for (;;) {
177
- const job = await client.getJob(a.id);
178
- const waited = Math.round((now() - started) / 1000);
179
- if (FINAL_STATUSES.has(job.status)) return { ...job, waited_seconds: waited, timed_out: false };
180
- if (now() - started + intervalMs > timeoutMs) return { ...job, waited_seconds: waited, timed_out: true };
181
- await sleep(intervalMs);
182
- }
183
- },
232
+ handler: (a, { client, sleep, now }) => waitForJob(client, a.id, {
233
+ timeoutSeconds: a.timeout_seconds ?? 600, intervalSeconds: a.interval_seconds ?? 5, sleep, now,
234
+ }),
184
235
  },
185
236
  {
186
237
  name: 'kanta_job_cancel',
@@ -3,6 +3,9 @@
3
3
  // A handler MAY instead return a ready MCP result ({ content } / { isError })
4
4
  // and register.js#wrapHandler will pass it through untouched.
5
5
 
6
+ import { writeFileSync } from 'node:fs';
7
+ import { resolve } from 'node:path';
8
+
6
9
  const FILTER_SCHEMA = {
7
10
  type: 'object',
8
11
  additionalProperties: true,
@@ -11,10 +14,11 @@ const FILTER_SCHEMA = {
11
14
  'function[], title, title_exact[], person_country[], person_state[], company, company_domain[], ' +
12
15
  'industry[], employee_range[] (e.g. "51-200"), has_email, has_linkedin, has_phone. ' +
13
16
  'verification_status[] is admin-only. All list keys accept a bare string too. ' +
14
- 'Values must match the stored labels exactly (case-sensitive), and one concept often has ' +
15
- 'several labels (e.g. "computer software", "Software Development", "custom software & it services"). ' +
16
- 'Before filtering on industry, function, seniority, or location, call kanta_db_facets on that ' +
17
- 'field to see the real values, then pass every relevant one as a list.',
17
+ 'industry takes industry names case-insensitively (e.g. "Software Development", "software") and ' +
18
+ 'includes sub-industries; kanta_db_industries lists them. person_country (aliases like "USA", "UK"), ' +
19
+ 'person_state (abbreviations like "CA", "ON") and function match case-insensitively. employee_range ' +
20
+ 'takes size bands: 1-10, 11-50, 51-200, 201-500, 501-1000, 1001-5000, 5001-10000, 10001+. ' +
21
+ 'Unknown values return suggestions. title_exact matches exactly.',
18
22
  };
19
23
 
20
24
  const COMPANY_FILTER_SCHEMA = {
@@ -23,15 +27,40 @@ const COMPANY_FILTER_SCHEMA = {
23
27
  description:
24
28
  'Kanta DB company filter. Keys: query, domain[], industry[], employee_range[], hq_country[], ' +
25
29
  'hq_state[], funding_stage[], employees_min, employees_max, revenue_min_k, revenue_max_k, ' +
26
- 'founded_after (year), min_contacts. Values match stored labels exactly (case-sensitive); call ' +
27
- 'kanta_db_companies_facets on a field first to see the real values and pass every relevant one.',
30
+ 'founded_after (year), min_contacts. industry takes industry names case-insensitively and includes ' +
31
+ 'sub-industries; hq_country / hq_state accept aliases and abbreviations; employee_range takes the ' +
32
+ 'size bands 1-10 ... 10001+. funding_stage and domain match stored values exactly.',
28
33
  };
29
34
 
35
+ const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
36
+
37
+ async function saveExport(client, id, output) {
38
+ const status = await client.getExport(id);
39
+ if (status.status === 'failed') throw new Error(`Export ${id} failed: ${status.error || 'unknown error'}`);
40
+ if (status.status !== 'complete') throw new Error(`Export ${id} is not finished (status: ${status.status}).`);
41
+ const csv = await client.downloadExport(id);
42
+ const path = resolve(output);
43
+ writeFileSync(path, csv);
44
+ const rows = Math.max(0, String(csv).trim().split('\n').length - 1);
45
+ return { id, rows, output: path, delivered: status.delivered, suppressed: status.suppressed, truncated: status.truncated };
46
+ }
47
+
30
48
  function errResult(text) {
31
49
  return { isError: true, content: [{ type: 'text', text }] };
32
50
  }
33
51
 
34
52
  export const databaseTools = [
53
+ {
54
+ name: 'kanta_db_industries',
55
+ description:
56
+ 'List the industry names usable in the "industry" filter, as a tree with contact counts ' +
57
+ '(a parent includes its sub-industries). Free. Defaults to industries with 10,000+ contacts.',
58
+ inputSchema: {
59
+ type: 'object',
60
+ properties: { min_contacts: { type: 'integer', minimum: 0, description: 'default 10000' } },
61
+ },
62
+ handler: (a, { client }) => client.dbIndustries({ minContacts: a.min_contacts ?? 10000 }),
63
+ },
35
64
  {
36
65
  name: 'kanta_db_count',
37
66
  description: 'Count people in the Kanta Database matching a filter. Free.',
@@ -107,7 +136,8 @@ export const databaseTools = [
107
136
  description:
108
137
  'Export matching people to a CSV job. Costs 1 db_credit per row delivered (admin keys are not charged). ' +
109
138
  'Call kanta_db_count first, then set confirm_credits to the number of credits you intend to spend ' +
110
- '(normally equal to max). Poll the job with kanta_db_export_status.',
139
+ '(normally equal to max). Poll the job with kanta_db_export_status, or pass "output" to wait and ' +
140
+ 'save the CSV locally in one call (kanta_db_export_download saves a finished export).',
111
141
  inputSchema: {
112
142
  type: 'object',
113
143
  properties: {
@@ -118,17 +148,23 @@ export const databaseTools = [
118
148
  minimum: 1,
119
149
  description: 'credits you authorize spending; must equal the API-computed estimated_max',
120
150
  },
151
+ output: { type: 'string', description: 'wait for the export, then save the CSV to this local path' },
121
152
  },
122
153
  required: ['filter', 'max', 'confirm_credits'],
123
154
  },
124
- handler: async (a, { client }) => {
155
+ handler: async (a, { client, sleep = realSleep }) => {
125
156
  try {
126
157
  const job = await client.dbExport(a.filter || {}, a.max, a.confirm_credits);
127
- return {
128
- job_id: job.job_id || job.id,
129
- estimated_max: job.estimated_max,
130
- note: 'Export started. Poll kanta_db_export_status with this job_id.',
131
- };
158
+ const id = job.job_id || job.id;
159
+ if (!a.output) {
160
+ return { job_id: id, estimated_max: job.estimated_max, note: 'Export started. Poll kanta_db_export_status with this job_id.' };
161
+ }
162
+ let status = await client.getExport(id);
163
+ for (let i = 0; i < 900 && (status.status === 'pending' || status.status === 'running'); i += 1) {
164
+ await sleep(2000);
165
+ status = await client.getExport(id);
166
+ }
167
+ return { job_id: id, ...(await saveExport(client, id, a.output)) };
132
168
  } catch (err) {
133
169
  if (err && err.code === 'confirm_credits_required') {
134
170
  const est = err.extra && err.extra.estimated_max;
@@ -152,6 +188,19 @@ export const databaseTools = [
152
188
  },
153
189
  handler: (a, { client }) => client.getExport(a.id),
154
190
  },
191
+ {
192
+ name: 'kanta_db_export_download',
193
+ description: 'Save a finished Kanta Database export to a local CSV file. Returns the row count and path.',
194
+ inputSchema: {
195
+ type: 'object',
196
+ properties: {
197
+ id: { type: 'string' },
198
+ output: { type: 'string', description: 'local CSV path to write (overwritten if it exists)' },
199
+ },
200
+ required: ['id', 'output'],
201
+ },
202
+ handler: (a, { client }) => saveExport(client, a.id, a.output),
203
+ },
155
204
  {
156
205
  name: 'kanta_db_companies_count',
157
206
  description: 'Count companies (organizations) in the Kanta Database matching a filter. Free.',