@kantadev/cli 0.1.2 → 0.1.5
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 +5 -3
- package/package.json +1 -1
- package/server.json +2 -2
- package/src/cli/bulkRun.js +66 -0
- package/src/cli/commands/db/index.js +18 -0
- package/src/cli/commands/find.js +19 -13
- package/src/cli/commands/jobs.js +1 -1
- package/src/cli/commands/verify.js +15 -12
- package/src/cli/context.js +12 -4
- package/src/cli/index.js +8 -1
- package/src/cli/updateNotice.js +49 -0
- package/src/core/bulkInput.js +64 -0
- package/src/core/client.js +6 -0
- package/src/core/creditGuard.js +29 -0
- package/src/core/errors.js +13 -1
- package/src/core/jobs.js +19 -0
- package/src/mcp/register.js +3 -1
- package/src/mcp/server.js +2 -1
- package/src/mcp/tools/customer.js +116 -20
- package/src/mcp/tools/database.js +63 -9
- package/src/version.js +4 -0
package/README.md
CHANGED
|
@@ -81,7 +81,9 @@ kanta logout --profile personal
|
|
|
81
81
|
|
|
82
82
|
```bash
|
|
83
83
|
kanta verify name@example.com
|
|
84
|
-
kanta verify bulk contacts.csv #
|
|
84
|
+
kanta verify bulk contacts.csv # email column detected ("email", "Email Address", "Work Email", ...)
|
|
85
|
+
kanta verify bulk contacts.csv -o results.csv # wait for the job, then save every result
|
|
86
|
+
kanta verify bulk contacts.csv --max-credits 5000 # refuse if it would cost more
|
|
85
87
|
kanta find Ada Lovelace analytical.co # synchronous — prints the email (or "no email found")
|
|
86
88
|
kanta find bulk people.csv # CSV needs first_name,last_name,company; prints a job id
|
|
87
89
|
kanta jobs list [--status <s>]
|
|
@@ -186,10 +188,10 @@ See the config block at the top of this file. Admin tools appear in
|
|
|
186
188
|
|
|
187
189
|
- Verify / Find / jobs: `kanta_verify_email`, `kanta_verify_bulk`,
|
|
188
190
|
`kanta_find_email`, `kanta_find_bulk`, `kanta_jobs_list`, `kanta_job_get`,
|
|
189
|
-
`kanta_job_results`, `kanta_job_cancel`, `kanta_job_resume`, `kanta_job_delete`, `kanta_account`,
|
|
191
|
+
`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
192
|
`kanta_credits`
|
|
191
193
|
- Database: `kanta_db_count`, `kanta_db_search`, `kanta_db_facets`,
|
|
192
|
-
`kanta_db_lookup`, `kanta_db_export
|
|
194
|
+
`kanta_db_lookup`, `kanta_db_export` (pass `output` to wait and save), `kanta_db_export_status`, `kanta_db_export_download`,
|
|
193
195
|
`kanta_db_companies_count`, `kanta_db_companies_search`,
|
|
194
196
|
`kanta_db_companies_facets`, `kanta_db_company_contacts`
|
|
195
197
|
- 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
|
+
"version": "0.1.5",
|
|
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.
|
|
5
|
+
"version": "0.1.5",
|
|
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.
|
|
15
|
+
"version": "0.1.5",
|
|
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>')
|
package/src/cli/commands/find.js
CHANGED
|
@@ -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
|
|
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,
|
|
40
|
-
const rows = readCsv(file, ['first_name', 'last_name', 'company']
|
|
41
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/cli/commands/jobs.js
CHANGED
|
@@ -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,6 +1,8 @@
|
|
|
1
1
|
import { basename } from 'node:path';
|
|
2
2
|
import { action, getClient, globalOpts, readCsv, CliExit } from '../context.js';
|
|
3
|
-
import {
|
|
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
|
|
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)
|
|
30
|
-
if (emails.length === 0) throw new CliExit('No non-empty
|
|
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
|
-
|
|
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
|
}
|
package/src/cli/context.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Shared helpers for CLI commands.
|
|
2
|
+
import { resolveColumns } from '../core/bulkInput.js';
|
|
2
3
|
import { readFileSync, existsSync, writeFileSync } from 'node:fs';
|
|
3
4
|
import { createInterface } from 'node:readline';
|
|
4
5
|
import { parse as csvParse } from 'csv-parse/sync';
|
|
@@ -40,6 +41,9 @@ export function defaultDeps() {
|
|
|
40
41
|
whoamiFn(o) {
|
|
41
42
|
return whoami({ profile: o.profile, apiKey: o.apiKey, baseUrl: o.baseUrl });
|
|
42
43
|
},
|
|
44
|
+
sleep(ms) {
|
|
45
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
46
|
+
},
|
|
43
47
|
confirm(question) {
|
|
44
48
|
return defaultConfirm(question);
|
|
45
49
|
},
|
|
@@ -105,7 +109,9 @@ export function action(fn) {
|
|
|
105
109
|
};
|
|
106
110
|
}
|
|
107
111
|
|
|
108
|
-
|
|
112
|
+
// Returns rows keyed by the canonical column names (email / first_name / last_name /
|
|
113
|
+
// company), whatever the file's own headers are; see core/bulkInput.js for accepted spellings.
|
|
114
|
+
export function readCsv(path, requiredColumns, overrides = {}) {
|
|
109
115
|
if (!existsSync(path)) throw new CliExit(`File not found: ${path}`);
|
|
110
116
|
const raw = readFileSync(path, 'utf8');
|
|
111
117
|
if (!raw.trim()) throw new CliExit(`File is empty: ${path}`);
|
|
@@ -117,16 +123,18 @@ export function readCsv(path, requiredColumns) {
|
|
|
117
123
|
}
|
|
118
124
|
if (records.length === 0) throw new CliExit(`No data rows in ${path}`);
|
|
119
125
|
const found = Object.keys(records[0]);
|
|
120
|
-
const missing =
|
|
126
|
+
const { map, missing } = resolveColumns(found, requiredColumns, overrides);
|
|
121
127
|
if (missing.length) {
|
|
128
|
+
const flags = missing.map((c) => `--${c.replace('_name', '').replace('_', '-')}-col`).join(', ');
|
|
122
129
|
throw new CliExit(
|
|
123
|
-
`CSV ${path} is missing column(s): ${missing.join(', ')}.
|
|
130
|
+
`CSV ${path} is missing column(s): ${missing.join(', ')}. Found: ${found.join(', ')}. ` +
|
|
131
|
+
`Rename the header or name it with ${flags}.`,
|
|
124
132
|
);
|
|
125
133
|
}
|
|
126
134
|
if (records.length > MAX_ROWS) {
|
|
127
135
|
throw new CliExit(`${records.length} rows exceeds the ${MAX_ROWS} per-job limit. Split the file.`);
|
|
128
136
|
}
|
|
129
|
-
return records;
|
|
137
|
+
return records.map((r) => Object.fromEntries(requiredColumns.map((c) => [c, r[map[c]]])));
|
|
130
138
|
}
|
|
131
139
|
|
|
132
140
|
export function writeOut(path, content) {
|
package/src/cli/index.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
+
import { VERSION } from '../version.js';
|
|
3
|
+
import { updateNotice } from './updateNotice.js';
|
|
2
4
|
import { defaultDeps } from './context.js';
|
|
3
5
|
import { registerVerify } from './commands/verify.js';
|
|
4
6
|
import { registerFind } from './commands/find.js';
|
|
@@ -16,7 +18,7 @@ export function createProgram(deps = {}) {
|
|
|
16
18
|
program
|
|
17
19
|
.name('kanta')
|
|
18
20
|
.description('Kanta CLI — verify, find, and manage email jobs over api.kanta.dev')
|
|
19
|
-
.version(
|
|
21
|
+
.version(VERSION)
|
|
20
22
|
.option('--profile <name>', 'config profile to use')
|
|
21
23
|
.option('--api-key <key>', 'API key (overrides profile/env; never persisted)')
|
|
22
24
|
.option('--base-url <url>', 'API base URL override')
|
|
@@ -49,5 +51,10 @@ export function createProgram(deps = {}) {
|
|
|
49
51
|
export async function run(argv = process.argv, deps = {}) {
|
|
50
52
|
const program = createProgram(deps);
|
|
51
53
|
await program.parseAsync(argv);
|
|
54
|
+
// The MCP server owns stdio; JSON output is for scripts. Neither gets the notice.
|
|
55
|
+
if (!argv.includes('--json') && !argv.includes('mcp')) {
|
|
56
|
+
const msg = await updateNotice({ current: VERSION }).catch(() => null);
|
|
57
|
+
if (msg) process.stderr.write(`\n${msg}\n`);
|
|
58
|
+
}
|
|
52
59
|
return program;
|
|
53
60
|
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Once-a-day "newer version on npm" notice for the CLI (never for the MCP server).
|
|
2
|
+
// Reads ~/.kanta/update-check.json; refreshes it from the npm registry when it is
|
|
3
|
+
// older than a day. Every failure is swallowed — this must never break a command.
|
|
4
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { configDir } from '../core/config.js';
|
|
7
|
+
|
|
8
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
9
|
+
const LATEST_URL = 'https://registry.npmjs.org/@kantadev%2fcli/latest';
|
|
10
|
+
|
|
11
|
+
export function isNewer(candidate, current) {
|
|
12
|
+
const a = String(candidate).split('.').map(Number);
|
|
13
|
+
const b = String(current).split('.').map(Number);
|
|
14
|
+
for (let i = 0; i < 3; i += 1) {
|
|
15
|
+
if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
|
|
16
|
+
}
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function updateNotice({
|
|
21
|
+
current,
|
|
22
|
+
dir = configDir(),
|
|
23
|
+
env = process.env,
|
|
24
|
+
isTTY = Boolean(process.stderr.isTTY),
|
|
25
|
+
now = Date.now(),
|
|
26
|
+
fetchImpl = globalThis.fetch,
|
|
27
|
+
} = {}) {
|
|
28
|
+
if (env.KANTA_NO_UPDATE_NOTIFIER || env.CI || !isTTY) return null;
|
|
29
|
+
const file = join(dir, 'update-check.json');
|
|
30
|
+
let cache = {};
|
|
31
|
+
try { cache = JSON.parse(readFileSync(file, 'utf8')); } catch { /* no cache yet */ }
|
|
32
|
+
|
|
33
|
+
if (!cache.checked_at || now - cache.checked_at > DAY_MS) {
|
|
34
|
+
let latest = cache.latest || null;
|
|
35
|
+
try {
|
|
36
|
+
const res = await fetchImpl(LATEST_URL, { signal: AbortSignal.timeout(1500) });
|
|
37
|
+
if (res.ok) latest = (await res.json()).version || latest;
|
|
38
|
+
} catch { /* offline or slow: try again tomorrow */ }
|
|
39
|
+
cache = { checked_at: now, latest };
|
|
40
|
+
try {
|
|
41
|
+
mkdirSync(dir, { recursive: true });
|
|
42
|
+
writeFileSync(file, JSON.stringify(cache));
|
|
43
|
+
} catch { /* read-only home: skip caching */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (!cache.latest || !isNewer(cache.latest, current)) return null;
|
|
47
|
+
return `A newer Kanta CLI is available: ${current} -> ${cache.latest}. ` +
|
|
48
|
+
'Update with: npm install -g @kantadev/cli@latest';
|
|
49
|
+
}
|
|
@@ -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
|
+
}
|
package/src/core/client.js
CHANGED
|
@@ -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
|
+
}
|
package/src/core/errors.js
CHANGED
|
@@ -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
|
-
|
|
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;
|
package/src/core/jobs.js
ADDED
|
@@ -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
|
+
}
|
package/src/mcp/register.js
CHANGED
|
@@ -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
|
};
|
package/src/mcp/server.js
CHANGED
|
@@ -12,6 +12,7 @@ import { KantaClient } from '../core/client.js';
|
|
|
12
12
|
import { resolveKey } from '../core/auth.js';
|
|
13
13
|
import { whoami } from '../core/identity.js';
|
|
14
14
|
import { buildToolList, wrapHandler } from './register.js';
|
|
15
|
+
import { VERSION } from '../version.js';
|
|
15
16
|
|
|
16
17
|
// Resolve the caller's scope via GET /me, but never block startup on it:
|
|
17
18
|
// the server must boot offline (first-run UX, sandboxed clients). On any
|
|
@@ -40,7 +41,7 @@ export async function startServer() {
|
|
|
40
41
|
const handlers = new Map(tools.map(t => [t.name, wrapHandler(t, { client })]));
|
|
41
42
|
|
|
42
43
|
const server = new Server(
|
|
43
|
-
{ name: 'kanta', version:
|
|
44
|
+
{ name: 'kanta', version: VERSION },
|
|
44
45
|
{ capabilities: { tools: {} } },
|
|
45
46
|
);
|
|
46
47
|
|
|
@@ -1,36 +1,76 @@
|
|
|
1
1
|
// Customer MCP tools. Each entry: { name, description, inputSchema, handler }.
|
|
2
2
|
// handler(args, { client }) -> any JSON-serialisable value.
|
|
3
|
-
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { toCsv } from '../../cli/format.js';
|
|
4
6
|
import { parse as csvParse } from 'csv-parse/sync';
|
|
5
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';
|
|
6
11
|
|
|
7
12
|
const INLINE_ROW_CAP = 100;
|
|
8
13
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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.');
|
|
14
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);
|
|
15
29
|
throw new Error('Provide either "emails" (array) or "path" (CSV with an email column).');
|
|
16
30
|
}
|
|
17
31
|
|
|
18
32
|
function loadContacts(args) {
|
|
19
33
|
if (Array.isArray(args.contacts)) return args.contacts;
|
|
20
34
|
if (args.path) {
|
|
21
|
-
|
|
22
|
-
|
|
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 }));
|
|
23
38
|
}
|
|
24
|
-
throw new Error('Provide either "contacts" (array) or "path" (CSV with
|
|
39
|
+
throw new Error('Provide either "contacts" (array) or "path" (CSV with first name, last name, company columns).');
|
|
25
40
|
}
|
|
26
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 });
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
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
|
+
|
|
27
67
|
function capResults(out) {
|
|
28
68
|
const rows = out.results || [];
|
|
29
69
|
if (rows.length > INLINE_ROW_CAP) {
|
|
30
70
|
return {
|
|
31
71
|
job_id: out.job_id,
|
|
32
72
|
total: out.total,
|
|
33
|
-
note: `${rows.length} rows — too many to return inline. Re-run with an "output" path or use the CLI: kanta jobs results ${out.job_id} -o results.csv`,
|
|
73
|
+
note: `${rows.length} rows — too many to return inline. Re-run with an "output" file path to save every row, or use the CLI: kanta jobs results ${out.job_id} -o results.csv`,
|
|
34
74
|
sample: rows.slice(0, INLINE_ROW_CAP),
|
|
35
75
|
};
|
|
36
76
|
}
|
|
@@ -40,7 +80,7 @@ function capResults(out) {
|
|
|
40
80
|
export const customerTools = [
|
|
41
81
|
{
|
|
42
82
|
name: 'kanta_verify_email',
|
|
43
|
-
description: 'Verify a single email address. Returns status (valid/invalid/risky/unknown)
|
|
83
|
+
description: 'Verify a single email address (1 verify credit). Returns status (valid/invalid/risky/catch_all/disposable/unknown), signal flags and credits_remaining.',
|
|
44
84
|
inputSchema: {
|
|
45
85
|
type: 'object',
|
|
46
86
|
properties: { email: { type: 'string', description: 'Email address to verify' } },
|
|
@@ -50,18 +90,28 @@ export const customerTools = [
|
|
|
50
90
|
},
|
|
51
91
|
{
|
|
52
92
|
name: 'kanta_verify_bulk',
|
|
53
|
-
description:
|
|
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.',
|
|
54
97
|
inputSchema: {
|
|
55
98
|
type: 'object',
|
|
56
99
|
properties: {
|
|
57
100
|
emails: { type: 'array', items: { type: 'string' } },
|
|
58
|
-
path: { type: 'string', description: 'Path to a CSV file with an
|
|
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' },
|
|
59
103
|
filename: { type: 'string' },
|
|
60
104
|
webhook: { type: 'string' },
|
|
105
|
+
...WAIT_PROPS,
|
|
61
106
|
},
|
|
62
107
|
},
|
|
63
|
-
handler: (a,
|
|
64
|
-
|
|
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
|
+
},
|
|
65
115
|
},
|
|
66
116
|
{
|
|
67
117
|
name: 'kanta_find_email',
|
|
@@ -83,7 +133,11 @@ export const customerTools = [
|
|
|
83
133
|
},
|
|
84
134
|
{
|
|
85
135
|
name: 'kanta_find_bulk',
|
|
86
|
-
description:
|
|
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.',
|
|
87
141
|
inputSchema: {
|
|
88
142
|
type: 'object',
|
|
89
143
|
properties: {
|
|
@@ -99,10 +153,20 @@ export const customerTools = [
|
|
|
99
153
|
},
|
|
100
154
|
},
|
|
101
155
|
path: { type: 'string' },
|
|
156
|
+
first_name_column: { type: 'string' },
|
|
157
|
+
last_name_column: { type: 'string' },
|
|
158
|
+
company_column: { type: 'string' },
|
|
102
159
|
filename: { type: 'string' },
|
|
160
|
+
...WAIT_PROPS,
|
|
103
161
|
},
|
|
104
162
|
},
|
|
105
|
-
handler: (a,
|
|
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
|
+
},
|
|
106
170
|
},
|
|
107
171
|
{
|
|
108
172
|
name: 'kanta_jobs_list',
|
|
@@ -129,13 +193,45 @@ export const customerTools = [
|
|
|
129
193
|
},
|
|
130
194
|
{
|
|
131
195
|
name: 'kanta_job_results',
|
|
132
|
-
description:
|
|
196
|
+
description:
|
|
197
|
+
'Fetch job results. Inline output is capped at 100 rows (larger jobs return a sample). ' +
|
|
198
|
+
'Pass "output" (a local file path) to write every row to a CSV instead; you get back the row count.',
|
|
133
199
|
inputSchema: {
|
|
134
200
|
type: 'object',
|
|
135
|
-
properties: {
|
|
201
|
+
properties: {
|
|
202
|
+
id: { type: 'string' },
|
|
203
|
+
output: { type: 'string', description: 'Local CSV path to write all rows to (overwritten if it exists)' },
|
|
204
|
+
},
|
|
205
|
+
required: ['id'],
|
|
206
|
+
},
|
|
207
|
+
handler: async (a, { client }) => {
|
|
208
|
+
const out = await client.getJobResults(a.id);
|
|
209
|
+
if (!a.output) return capResults(out);
|
|
210
|
+
if (!out || !Array.isArray(out.results)) {
|
|
211
|
+
throw new Error(`Job not complete (status: ${out?.status ?? 'unknown'}); nothing written.`);
|
|
212
|
+
}
|
|
213
|
+
const path = resolve(a.output);
|
|
214
|
+
writeFileSync(path, toCsv(out.results));
|
|
215
|
+
return { job_id: out.job_id ?? a.id, rows_written: out.results.length, output: path };
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
{
|
|
219
|
+
name: 'kanta_job_wait',
|
|
220
|
+
description:
|
|
221
|
+
'Wait for a job to finish (complete, failed, cancelled, or paused) and return its final state. ' +
|
|
222
|
+
'Use this instead of calling kanta_job_get repeatedly. Default timeout 10 minutes, max 60.',
|
|
223
|
+
inputSchema: {
|
|
224
|
+
type: 'object',
|
|
225
|
+
properties: {
|
|
226
|
+
id: { type: 'string' },
|
|
227
|
+
timeout_seconds: { type: 'integer', minimum: 1, maximum: 3600, description: 'default 600' },
|
|
228
|
+
interval_seconds: { type: 'integer', minimum: 2, maximum: 60, description: 'poll interval, default 5' },
|
|
229
|
+
},
|
|
136
230
|
required: ['id'],
|
|
137
231
|
},
|
|
138
|
-
handler:
|
|
232
|
+
handler: (a, { client, sleep, now }) => waitForJob(client, a.id, {
|
|
233
|
+
timeoutSeconds: a.timeout_seconds ?? 600, intervalSeconds: a.interval_seconds ?? 5, sleep, now,
|
|
234
|
+
}),
|
|
139
235
|
},
|
|
140
236
|
{
|
|
141
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,
|
|
@@ -10,7 +13,12 @@ const FILTER_SCHEMA = {
|
|
|
10
13
|
'Kanta DB person filter. Keys: query (free text), seniority[] (C-Suite, VP, Director, Manager, …), ' +
|
|
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
|
-
'verification_status[] is admin-only. All list keys accept a bare string too.'
|
|
16
|
+
'verification_status[] is admin-only. All list keys accept a bare string too. ' +
|
|
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.',
|
|
14
22
|
};
|
|
15
23
|
|
|
16
24
|
const COMPANY_FILTER_SCHEMA = {
|
|
@@ -19,14 +27,40 @@ const COMPANY_FILTER_SCHEMA = {
|
|
|
19
27
|
description:
|
|
20
28
|
'Kanta DB company filter. Keys: query, domain[], industry[], employee_range[], hq_country[], ' +
|
|
21
29
|
'hq_state[], funding_stage[], employees_min, employees_max, revenue_min_k, revenue_max_k, ' +
|
|
22
|
-
'founded_after (year), min_contacts.'
|
|
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.',
|
|
23
33
|
};
|
|
24
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
|
+
|
|
25
48
|
function errResult(text) {
|
|
26
49
|
return { isError: true, content: [{ type: 'text', text }] };
|
|
27
50
|
}
|
|
28
51
|
|
|
29
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
|
+
},
|
|
30
64
|
{
|
|
31
65
|
name: 'kanta_db_count',
|
|
32
66
|
description: 'Count people in the Kanta Database matching a filter. Free.',
|
|
@@ -102,7 +136,8 @@ export const databaseTools = [
|
|
|
102
136
|
description:
|
|
103
137
|
'Export matching people to a CSV job. Costs 1 db_credit per row delivered (admin keys are not charged). ' +
|
|
104
138
|
'Call kanta_db_count first, then set confirm_credits to the number of credits you intend to spend ' +
|
|
105
|
-
'(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).',
|
|
106
141
|
inputSchema: {
|
|
107
142
|
type: 'object',
|
|
108
143
|
properties: {
|
|
@@ -113,17 +148,23 @@ export const databaseTools = [
|
|
|
113
148
|
minimum: 1,
|
|
114
149
|
description: 'credits you authorize spending; must equal the API-computed estimated_max',
|
|
115
150
|
},
|
|
151
|
+
output: { type: 'string', description: 'wait for the export, then save the CSV to this local path' },
|
|
116
152
|
},
|
|
117
153
|
required: ['filter', 'max', 'confirm_credits'],
|
|
118
154
|
},
|
|
119
|
-
handler: async (a, { client }) => {
|
|
155
|
+
handler: async (a, { client, sleep = realSleep }) => {
|
|
120
156
|
try {
|
|
121
157
|
const job = await client.dbExport(a.filter || {}, a.max, a.confirm_credits);
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
estimated_max: job.estimated_max,
|
|
125
|
-
|
|
126
|
-
|
|
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)) };
|
|
127
168
|
} catch (err) {
|
|
128
169
|
if (err && err.code === 'confirm_credits_required') {
|
|
129
170
|
const est = err.extra && err.extra.estimated_max;
|
|
@@ -147,6 +188,19 @@ export const databaseTools = [
|
|
|
147
188
|
},
|
|
148
189
|
handler: (a, { client }) => client.getExport(a.id),
|
|
149
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
|
+
},
|
|
150
204
|
{
|
|
151
205
|
name: 'kanta_db_companies_count',
|
|
152
206
|
description: 'Count companies (organizations) in the Kanta Database matching a filter. Free.',
|
package/src/version.js
ADDED