@kantadev/cli 0.1.7 → 0.1.9

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
@@ -1,12 +1,10 @@
1
1
  # @kantadev/cli
2
2
 
3
- Terminal (`kanta`) and MCP server (`kanta-mcp`) for **Kanta Verify**, **Kanta
4
- Find**, and the **Kanta Database**. Thin wrapper over the `api.kanta.dev` and
5
- `database.kanta.dev` REST APIs — no product logic lives here.
3
+ Terminal (`kanta`) and MCP server (`kanta-mcp`) for **Kanta Verify** and **Kanta
4
+ Find**. Thin wrapper over the `api.kanta.dev` REST API — no product logic lives here.
6
5
 
7
6
  - Node 20+, ESM.
8
- - Design specs: `docs/superpowers/specs/2026-09-04-kanta-cli-mcp-verify-find-admin-design.md`,
9
- `docs/superpowers/specs/2026-09-04-kanta-database-api-mcp-design.md`
7
+ - Design spec: `docs/superpowers/specs/2026-09-04-kanta-cli-mcp-verify-find-admin-design.md`
10
8
  - Full command reference: [`docs/cli.md`](../docs/cli.md)
11
9
 
12
10
  ## Install
@@ -50,23 +48,19 @@ unreachable it still boots with the customer tool set (admin tools appear once
50
48
  Key resolution order (first match wins):
51
49
 
52
50
  1. `--api-key <key>` global flag (never persisted)
53
- 2. `KANTA_API_KEY` env var (optionally `KANTA_BASE_URL`, `KANTA_DB_URL`)
51
+ 2. `KANTA_API_KEY` env var (optionally `KANTA_BASE_URL`)
54
52
  3. `--profile <name>` from `~/.kanta/config.json`
55
53
  4. `default_profile` from `~/.kanta/config.json`
56
54
  5. Error — run `kanta login`
57
55
 
58
- The Kanta Database API is a **second base URL**, resolved independently with the
59
- same key: `--db-url` → `KANTA_DB_URL` → profile `db_base_url` →
60
- `https://database.kanta.dev/v1`.
61
-
62
56
  `~/.kanta/config.json` is written mode `0600`:
63
57
 
64
58
  ```json
65
59
  {
66
60
  "default_profile": "personal",
67
61
  "profiles": {
68
- "personal": { "key": "kdev_live_…", "base_url": "https://api.kanta.dev", "db_base_url": "https://database.kanta.dev/v1" },
69
- "admin": { "key": "kdev_live_…", "base_url": "https://api.kanta.dev", "db_base_url": "https://database.kanta.dev/v1" }
62
+ "personal": { "key": "kdev_live_…", "base_url": "https://api.kanta.dev" },
63
+ "admin": { "key": "kdev_live_…", "base_url": "https://api.kanta.dev" }
70
64
  }
71
65
  }
72
66
  ```
@@ -97,58 +91,12 @@ kanta credits
97
91
 
98
92
  Add `--json` to any command for machine output.
99
93
 
100
- ## Kanta Database
101
-
102
- Search, count, facet, and export the B2B contact database. Search/count/facets
103
- are free; `export` costs 1 db credit per row delivered (admin keys are not
104
- charged).
105
-
106
- ```bash
107
- kanta db count --seniority c-suite --industry software
108
- kanta db search --function marketing --has-email --limit 25 [-o people.csv]
109
- kanta db facets --industry software --field seniority --field person_state
110
- kanta db lookup --email jane@acme.com
111
- kanta db lookup --name "Jane Doe" --domain acme.com
112
-
113
- kanta db export --seniority vp --industry software --max 5000 -o leads.csv
114
- kanta db exports # your recent export jobs
115
- kanta db export-status <id>
116
- kanta db download <id> -o leads.csv
117
-
118
- kanta db companies count --industry software --employees-min 50
119
- kanta db companies search --hq-country "United States" --min-contacts 5
120
- kanta db companies export --industry fintech --max 2000 -o firms.csv
121
- kanta db company contacts <kanta_org_id> --limit 25
122
-
123
- kanta --profile admin db ca-count # CCPA California-record monitor (admin)
124
- ```
94
+ ## Internal: Kanta Database
125
95
 
126
- ### Person filter flags
127
-
128
- | Flag | Meaning |
129
- |---|---|
130
- | `--query <text>` | free text over name / title / company |
131
- | `--seniority <label…>` | `c-suite`, `vp`, `director`, `manager`, … (case-insensitive) |
132
- | `--function <name…>` | job function(s) |
133
- | `--title <text>` | title prefix match |
134
- | `--title-exact <text…>` | exact normalized title(s) |
135
- | `--country <name…>` / `--state <name…>` | person location |
136
- | `--company <text>` | company name prefix |
137
- | `--company-domain <domain…>` | company domain(s) |
138
- | `--industry <name…>` | company industry/industries |
139
- | `--employee-range <range…>` | e.g. `51-200` |
140
- | `--has-email` / `--has-linkedin` / `--has-phone` | presence filters |
141
- | `--verification-status <s…>` | admin only (else the API returns 403) |
142
- | `--filter-file <path>` | raw JSON filter object, merged under the flags |
143
-
144
- Company flags: `--query`, `--domain`, `--industry`, `--employee-range`,
145
- `--hq-country`, `--hq-state`, `--employees-min/max`,
146
- `--revenue-min-k/max-k`, `--founded-after`, `--min-contacts`, `--filter-file`.
147
-
148
- The `db export` flow prints the match count and credit cost, prompts for
149
- confirmation (skip with `-y`), submits the job, polls until it finishes, and
150
- writes the CSV to `-o`. A `confirm_credits_required` response is retried once
151
- with the API's capped `estimated_max`.
96
+ The Database commands (`kanta db ...`) and MCP tools (`kanta_db_*`) are not part
97
+ of the public release and are off by default. Accounts with access set
98
+ `KANTA_ENABLE_DB=1`; the Database API URL can then be overridden with
99
+ `--db-url` / `KANTA_DB_URL`. Command reference: [`docs/cli.md`](../docs/cli.md).
152
100
 
153
101
  ## Admin commands (admin-scoped key only)
154
102
 
@@ -191,21 +139,13 @@ See the config block at the top of this file. Admin tools appear in
191
139
  `kanta_find_email`, `kanta_find_bulk`, `kanta_jobs_list`, `kanta_job_get`,
192
140
  `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`,
193
141
  `kanta_credits`
194
- - Database: `kanta_db_count`, `kanta_db_search`, `kanta_db_facets`,
195
- `kanta_db_lookup`, `kanta_db_export` (pass `output` to wait and save), `kanta_db_export_status`, `kanta_db_export_download`,
196
- `kanta_db_companies_count`, `kanta_db_companies_search`,
197
- `kanta_db_companies_facets`, `kanta_db_company_contacts`
198
142
  - Admin: `kanta_admin_credits_add`, `kanta_admin_jobs_list`, `kanta_admin_user`,
199
- `kanta_admin_verify`, `kanta_admin_suppress_add`, `kanta_admin_suppress_check`,
200
- `kanta_db_ca_count`
143
+ `kanta_admin_verify`, `kanta_admin_suppress_add`, `kanta_admin_suppress_check`
201
144
 
202
145
  `kanta_find_email` is synchronous — it returns `{ email, confidence, method, pattern }`
203
146
  inline (or `{ email: null }`) and charges a find credit only on a hit. Bulk tools
204
147
  accept either an inline array or a `path` to a CSV and return a `job_id`. Result
205
148
  tools cap inline output at 100 rows and otherwise return a sample plus a CLI hint.
206
- `kanta_db_export` **requires** a `confirm_credits` integer — call
207
- `kanta_db_count` first, then pass the number of credits you intend to spend; on
208
- `confirm_credits_required` the tool returns the `estimated_max` to retry with.
209
149
 
210
150
  ## Tests
211
151
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kantadev/cli",
3
- "version": "0.1.7",
4
- "description": "Kanta CLI + MCP server — email verification, email finding, and the Kanta B2B contact database from your terminal or an MCP client.",
3
+ "version": "0.1.9",
4
+ "description": "Kanta CLI + MCP server — email verification and email finding from your terminal or an MCP client.",
5
5
  "mcpName": "dev.kanta/cli",
6
6
  "type": "module",
7
7
  "bin": {
@@ -38,7 +38,6 @@
38
38
  "kanta",
39
39
  "email-verification",
40
40
  "email-finder",
41
- "b2b-data",
42
41
  "mcp",
43
42
  "modelcontextprotocol",
44
43
  "cli"
package/server.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "dev.kanta/cli",
4
- "description": "Kanta Verify, Find, and Database: email verification, email finding, and B2B contact search.",
5
- "version": "0.1.7",
4
+ "description": "Kanta Verify and Find: email verification and email finding.",
5
+ "version": "0.1.9",
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.7",
15
+ "version": "0.1.9",
16
16
  "runtimeHint": "npx",
17
17
  "packageArguments": [
18
18
  {
@@ -35,11 +35,6 @@
35
35
  "description": "Override the EmailVerifier (Verify/Find) API base URL",
36
36
  "isRequired": false
37
37
  },
38
- {
39
- "name": "KANTA_DB_URL",
40
- "description": "Override the Kanta Database API base URL",
41
- "isRequired": false
42
- },
43
38
  {
44
39
  "name": "KANTA_PROFILE",
45
40
  "description": "Named profile from ~/.kanta/config.json to use instead of KANTA_API_KEY",
@@ -1,5 +1,6 @@
1
1
  import { action, getClient, globalOpts } from '../context.js';
2
2
  import { printJson, printTable } from '../format.js';
3
+ import { databaseEnabled } from '../../core/features.js';
3
4
 
4
5
  export function registerAccount(program) {
5
6
  program
@@ -15,7 +16,7 @@ export function registerAccount(program) {
15
16
  { field: 'plan', value: me.plan },
16
17
  { field: 'verify credits', value: me.verify_credits },
17
18
  { field: 'find credits', value: me.find_credits },
18
- { field: 'db credits', value: me.db_credits },
19
+ ...(databaseEnabled() ? [{ field: 'db credits', value: me.db_credits }] : []),
19
20
  ], [{ key: 'field', label: 'FIELD' }, { key: 'value', label: 'VALUE' }]);
20
21
  }),
21
22
  );
@@ -1,5 +1,6 @@
1
1
  import { action, getClient, globalOpts } from '../context.js';
2
2
  import { printJson, printTable } from '../format.js';
3
+ import { databaseEnabled } from '../../core/features.js';
3
4
 
4
5
  export function registerCredits(program) {
5
6
  program
@@ -11,7 +12,7 @@ export function registerCredits(program) {
11
12
  const data = await client.getCredits();
12
13
  if (globalOpts(cmd).json) return printJson(data);
13
14
  process.stdout.write(
14
- `verify: ${data.balance} find: ${data.find_balance} db: ${data.db_balance}\n\n`,
15
+ `verify: ${data.balance} find: ${data.find_balance}${databaseEnabled() ? ` db: ${data.db_balance}` : ''}\n\n`,
15
16
  );
16
17
  printTable(data.ledger || [], [
17
18
  { key: 'created_at', label: 'DATE' },
@@ -63,6 +63,7 @@ export async function runExportFlow(config, client, deps = {}) {
63
63
 
64
64
  const parts = [`Delivered ${Number(status.delivered || 0).toLocaleString()} rows`];
65
65
  if (status.suppressed) parts.push(`${Number(status.suppressed).toLocaleString()} suppressed`);
66
+ if (status.duplicates) parts.push(`${Number(status.duplicates).toLocaleString()} duplicates skipped (same email or LinkedIn profile)`);
66
67
  if (status.truncated) parts.push('truncated (credit balance ran out)');
67
68
  const msg = `${parts.join(', ')} -> ${config.output}`;
68
69
  process.stdout.write(msg + '\n');
@@ -3,6 +3,7 @@ import { printJson, printTable, toCsv } from '../../format.js';
3
3
  import { buildPersonFilter } from '../../../core/dbFilter.js';
4
4
  import { registerDbExport } from './export.js';
5
5
  import { registerDbCompanies } from './companies.js';
6
+ import { DATABASE_DISABLED_MESSAGE } from '../../../core/features.js';
6
7
 
7
8
  // Attach the shared person-filter flags (spec §5) to a command.
8
9
  export function personFilterOptions(cmd) {
@@ -17,11 +18,11 @@ export function personFilterOptions(cmd) {
17
18
  .option('--company <text>', 'company name (prefix match)')
18
19
  .option('--company-domain <domain...>', 'company domain(s)')
19
20
  .option('--industry <name...>', 'company industry/industries')
20
- .option('--employee-range <range...>', 'company employee range(s), e.g. 51-200')
21
+ .option('--employee-range <range...>', 'company size band(s): 1-10, 11-50, 51-199, 200-499, 500-999, 1000-4999, 5000-9999, 10000-49999, 50000+, Unknown')
21
22
  .option('--has-email', 'only records with an email')
22
23
  .option('--has-linkedin', 'only records with a LinkedIn URL')
23
24
  .option('--has-phone', 'only records with a phone')
24
- .option('--verification-status <s...>', 'email verification status (admin only)')
25
+ .option('--verification-status <s...>', 'email status: valid, catch_all, risky, unknown, invalid')
25
26
  .option('--filter-file <path>', 'raw JSON filter object, merged under the flags');
26
27
  }
27
28
 
@@ -68,7 +69,17 @@ const PERSON_TABLE_COLUMNS = [
68
69
 
69
70
  export { personRow, PERSON_TABLE_COLUMNS };
70
71
 
71
- export function registerDb(program) {
72
+ export function registerDb(program, { enabled = true } = {}) {
73
+ if (!enabled) {
74
+ // Hidden from help; any `kanta db ...` explains how to turn it on.
75
+ program.command('db', { hidden: true })
76
+ .allowUnknownOption()
77
+ .allowExcessArguments()
78
+ .helpOption(false)
79
+ .argument('[args...]')
80
+ .action(action(async () => { throw new CliExit(DATABASE_DISABLED_MESSAGE); }));
81
+ return;
82
+ }
72
83
  const db = program.command('db').description('Kanta Database — search, count, facet, and export B2B contacts');
73
84
 
74
85
  personFilterOptions(db.command('count'))
@@ -41,13 +41,21 @@ async function readKey() {
41
41
  return Buffer.concat(chunks).toString('utf8').trim();
42
42
  }
43
43
 
44
+ async function saveKey(key, { profile, baseUrl, json }) {
45
+ const client = new KantaClient({ key, baseUrl });
46
+ const me = await client.getMe();
47
+ setProfile(profile, { key, base_url: baseUrl });
48
+ if (json) return printJson({ saved: profile, email: me.email, scope: me.scope });
49
+ process.stdout.write(`Saved profile "${profile}" (${me.email}, scope: ${me.scope}) to ${configPath()}\n`);
50
+ }
51
+
44
52
  export function registerLogin(program) {
45
53
  program
46
54
  .command('login')
47
55
  .description('Sign in through your browser (or paste a key with --key) and save it as a profile')
48
56
  .option('--profile <name>', 'profile name to save under', 'personal')
49
57
  .option('--base-url <url>', 'API base URL', DEFAULT_BASE_URL)
50
- .option('--key', 'paste an API key instead of signing in through the browser')
58
+ .option('--key [key]', 'use an API key instead of browser sign-in: give it here, or leave it off to paste it at a prompt (keeps it out of shell history)')
51
59
  .option('--no-browser', 'print the sign-in link instead of opening a browser')
52
60
  .action(
53
61
  action(async (opts, cmd) => {
@@ -56,34 +64,45 @@ export function registerLogin(program) {
56
64
  const profile = globalOpts(cmd).profile || opts.profile;
57
65
  const baseUrl = opts.baseUrl || DEFAULT_BASE_URL;
58
66
  const json = globalOpts(cmd).json;
67
+ if (opts.key) {
68
+ const key = typeof opts.key === 'string' ? opts.key.trim() : await readKey();
69
+ if (!key) throw new CliExit('No key entered.');
70
+ return saveKey(key, { profile, baseUrl, json });
71
+ }
59
72
  // 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({
73
+ const piped = deps.stdinIsTTY ? '' : await deps.readPipedInput();
74
+ if (piped) return saveKey(piped, { profile, baseUrl, json });
75
+ // Ctrl+C while waiting: say what happened instead of dying mid-line.
76
+ const onInterrupt = () => {
77
+ process.stdout.write('\nSign-in cancelled. Nothing was saved.\n');
78
+ deps.exit(130);
79
+ };
80
+ process.once('SIGINT', onInterrupt);
81
+ let result;
82
+ try {
83
+ result = await deps.browserLogin({
62
84
  baseUrl,
63
85
  clientName: `${hostname()} (kanta CLI)`.slice(0, 64),
64
86
  openUrl: opts.browser ? undefined : () => { throw new Error('no browser'); },
65
87
  onCode: (s) => {
66
88
  if (json) return;
89
+ const mins = Math.max(1, Math.round((s.expires_in || 600) / 60));
67
90
  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',
91
+ `Code ${s.user_code}: ${opts.browser ? 'opening' : 'open'} ${s.verification_uri_complete}\n` +
92
+ `Waiting for approval\u2026 (expires in ${mins} min)\n`,
71
93
  );
72
94
  },
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;
95
+ });
96
+ } catch (err) {
97
+ throw new CliExit(err.message);
98
+ } finally {
99
+ process.removeListener('SIGINT', onInterrupt);
78
100
  }
79
- const key = await readKey();
80
- if (!key) throw new CliExit('No key entered.');
81
- const client = new KantaClient({ key, baseUrl });
82
- const me = await client.getMe();
83
- setProfile(profile, { key, base_url: baseUrl });
84
- if (globalOpts(cmd).json) return printJson({ saved: profile, email: me.email, scope: me.scope });
101
+ const { apiKey, email } = result;
102
+ setProfile(profile, { key: apiKey, base_url: baseUrl });
103
+ if (json) return printJson({ saved: profile, email });
85
104
  process.stdout.write(
86
- `Saved profile "${profile}" (${me.email}, scope: ${me.scope}) to ${configPath()}\n`,
105
+ `Signed in as ${email || 'your account'}. Saved profile "${profile}". You can close the browser tab.\n`,
87
106
  );
88
107
  }),
89
108
  );
@@ -1,5 +1,6 @@
1
1
  // Shared helpers for CLI commands.
2
2
  import { browserLogin as realBrowserLogin } from '../core/browserLogin.js';
3
+ import { readPipedInput } from '../core/stdin.js';
3
4
  import { resolveColumns } from '../core/bulkInput.js';
4
5
  import { readFileSync, existsSync, writeFileSync } from 'node:fs';
5
6
  import { createInterface } from 'node:readline';
@@ -46,6 +47,12 @@ export function defaultDeps() {
46
47
  return realBrowserLogin(opts);
47
48
  },
48
49
  stdinIsTTY: Boolean(process.stdin.isTTY),
50
+ exit(code) {
51
+ process.exit(code);
52
+ },
53
+ readPipedInput() {
54
+ return readPipedInput();
55
+ },
49
56
  confirm(question) {
50
57
  return defaultConfirm(question);
51
58
  },
package/src/cli/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Command } from 'commander';
1
+ import { Command, Option } from 'commander';
2
2
  import { VERSION } from '../version.js';
3
3
  import { updateNotice } from './updateNotice.js';
4
4
  import { defaultDeps } from './context.js';
@@ -10,10 +10,12 @@ import { registerCredits } from './commands/credits.js';
10
10
  import { registerLogin } from './commands/login.js';
11
11
  import { registerAdmin } from './commands/admin/index.js';
12
12
  import { registerDb } from './commands/db/index.js';
13
+ import { databaseEnabled } from '../core/features.js';
13
14
 
14
15
  export function createProgram(deps = {}) {
15
16
  const program = new Command();
16
17
  program._deps = { ...defaultDeps(), ...deps };
18
+ const db = program._deps.dbEnabled ?? databaseEnabled();
17
19
 
18
20
  program
19
21
  .name('kanta')
@@ -22,7 +24,7 @@ export function createProgram(deps = {}) {
22
24
  .option('--profile <name>', 'config profile to use')
23
25
  .option('--api-key <key>', 'API key (overrides profile/env; never persisted)')
24
26
  .option('--base-url <url>', 'API base URL override')
25
- .option('--db-url <url>', 'Kanta Database API base URL override')
27
+ .addOption(new Option('--db-url <url>', 'Kanta Database API base URL override').hideHelp(!db))
26
28
  .option('--json', 'machine-readable JSON output', false);
27
29
 
28
30
  registerVerify(program);
@@ -32,7 +34,7 @@ export function createProgram(deps = {}) {
32
34
  registerCredits(program);
33
35
  registerLogin(program);
34
36
  registerAdmin(program);
35
- registerDb(program);
37
+ registerDb(program, { enabled: db });
36
38
 
37
39
  // `kanta mcp` runs the stdio MCP server — the same thing as the `kanta-mcp`
38
40
  // bin. Having it as a subcommand makes `npx @kantadev/cli mcp` work (npx
@@ -17,6 +17,20 @@ export class KantaConfigError extends Error {
17
17
  }
18
18
  }
19
19
 
20
+ // What an MCP client should tell the user when there is no usable key: the
21
+ // client can't run the login for them, and a new key only loads on restart.
22
+ export const MCP_SIGN_IN_MESSAGE =
23
+ 'Not signed in to Kanta. Run `npx @kantadev/cli login` in a terminal, then restart your MCP client.';
24
+
25
+ const REJECTED_KEY_CODES = new Set(['invalid_api_key', 'missing_api_key', 'api_key_expired']);
26
+
27
+ // True for "no credentials" and for a key the API turned down.
28
+ export function isSignInError(err) {
29
+ if (!err) return false;
30
+ if (err.name === 'KantaAuthError') return true;
31
+ return err.status === 401 || REJECTED_KEY_CODES.has(err.code);
32
+ }
33
+
20
34
  export class KantaAuthError extends Error {
21
35
  constructor(message) {
22
36
  super(message);
@@ -0,0 +1,10 @@
1
+ // The Kanta Database is not part of the public launch (Verify + Find only,
2
+ // Griffin 2026-12-01). Its CLI commands and MCP tools stay in the package but
3
+ // are off unless KANTA_ENABLE_DB is set, so internal setups can still use them.
4
+ export function databaseEnabled(env = process.env) {
5
+ const v = String(env.KANTA_ENABLE_DB ?? '').trim().toLowerCase();
6
+ return v === '1' || v === 'true' || v === 'yes';
7
+ }
8
+
9
+ export const DATABASE_DISABLED_MESSAGE =
10
+ 'The Kanta Database is not available. Set KANTA_ENABLE_DB=1 if your account has access.';
@@ -0,0 +1,24 @@
1
+ // Non-interactive stdin: a piped key (echo $KEY | kanta login) arrives at once.
2
+ // An empty or idle stdin (scripts, IDEs, agents) means there's no key to read,
3
+ // so the caller falls back to browser sign-in instead of failing.
4
+ export function readPipedInput({ stdin = process.stdin, waitMs = 1000 } = {}) {
5
+ return new Promise((resolve) => {
6
+ const chunks = [];
7
+ let done = false;
8
+ const finish = () => {
9
+ if (done) return;
10
+ done = true;
11
+ clearTimeout(timer);
12
+ stdin.removeListener('data', onData);
13
+ stdin.removeListener('end', finish);
14
+ stdin.removeListener('error', finish);
15
+ stdin.destroy?.();
16
+ resolve(Buffer.concat(chunks).toString('utf8').trim());
17
+ };
18
+ const onData = (c) => chunks.push(Buffer.from(c));
19
+ const timer = setTimeout(() => { if (!chunks.length) finish(); }, waitMs);
20
+ stdin.on('data', onData);
21
+ stdin.on('end', finish);
22
+ stdin.on('error', finish);
23
+ });
24
+ }
@@ -1,12 +1,15 @@
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
+ import { apiErrorDetail, isSignInError, MCP_SIGN_IN_MESSAGE } from '../core/errors.js';
5
5
  import { customerTools } from './tools/customer.js';
6
6
  import { adminTools } from './tools/admin.js';
7
+ import { databaseEnabled } from '../core/features.js';
7
8
 
8
- export function buildToolList(scope) {
9
- return scope === 'admin' ? [...customerTools, ...adminTools] : [...customerTools];
9
+ // Database tools (kanta_db_*) are left out unless KANTA_ENABLE_DB is set.
10
+ export function buildToolList(scope, { db = databaseEnabled() } = {}) {
11
+ const tools = scope === 'admin' ? [...customerTools, ...adminTools] : [...customerTools];
12
+ return db ? tools : tools.filter(t => !t.name.startsWith('kanta_db_'));
10
13
  }
11
14
 
12
15
  // Wrap a tool handler so it never throws raw — errors come back as MCP isError content.
@@ -22,6 +25,9 @@ export function wrapHandler(tool, { client }) {
22
25
  content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
23
26
  };
24
27
  } catch (err) {
28
+ if (isSignInError(err)) {
29
+ return { isError: true, content: [{ type: 'text', text: MCP_SIGN_IN_MESSAGE }] };
30
+ }
25
31
  const detail = err?.status ? ` (HTTP ${err.status}${err.code ? `, ${err.code}` : ''})` : '';
26
32
  const explain = apiErrorDetail(err);
27
33
  return {
package/src/mcp/server.js CHANGED
@@ -13,6 +13,8 @@ import { resolveKey } from '../core/auth.js';
13
13
  import { whoami } from '../core/identity.js';
14
14
  import { buildToolList, wrapHandler } from './register.js';
15
15
  import { VERSION } from '../version.js';
16
+ import { databaseEnabled } from '../core/features.js';
17
+ import { isSignInError, MCP_SIGN_IN_MESSAGE } from '../core/errors.js';
16
18
 
17
19
  // Resolve the caller's scope via GET /me, but never block startup on it:
18
20
  // the server must boot offline (first-run UX, sandboxed clients). On any
@@ -21,7 +23,11 @@ export async function resolveIdentity() {
21
23
  try {
22
24
  return await whoami({});
23
25
  } catch (err) {
24
- const rejected = err?.status === 401 || err?.status === 403;
26
+ if (isSignInError(err)) {
27
+ process.stderr.write(`kanta-mcp: ${MCP_SIGN_IN_MESSAGE}\n`);
28
+ return { scope: 'user', offline: true, signedOut: true };
29
+ }
30
+ const rejected = err?.status === 403;
25
31
  process.stderr.write(rejected
26
32
  ? `kanta-mcp: the API rejected your API key (${err?.code || err?.message || err}). ` +
27
33
  'Check KANTA_API_KEY (or your profile); every tool call will fail until it is fixed.\n'
@@ -31,18 +37,63 @@ export async function resolveIdentity() {
31
37
  }
32
38
  }
33
39
 
40
+ // Told to the MCP client on connect, so the agent knows whose account (and
41
+ // credits) every tool call uses before it plans a search or an export.
42
+ export function identityInstructions(identity, { db = databaseEnabled() } = {}) {
43
+ if (identity?.signedOut) return MCP_SIGN_IN_MESSAGE;
44
+ if (!identity || identity.offline) {
45
+ return 'Kanta could not confirm which account this API key belongs to at startup. ' +
46
+ 'Call kanta_account before spending credits to see the account and its balances.';
47
+ }
48
+ const fmt = n => Number(n ?? 0).toLocaleString('en-US');
49
+ const c = identity.credits || {};
50
+ const lines = [
51
+ `Kanta tools act as ${identity.email} (${identity.plan || 'free'} plan, ${identity.scope} key).`,
52
+ `Balances at startup: Verify ${fmt(c.verify)}, Find ${fmt(c.find)}${db ? `, Database ${fmt(c.db)}` : ''}. Call kanta_account for current balances.`,
53
+ ];
54
+ if (db && identity.scope !== 'admin') {
55
+ lines.push('kanta_db_search masks email and phone on this key; kanta_db_export returns them at 1 Database credit per row.');
56
+ if (!c.db) lines.push('This account has no Database credits, so kanta_db_export will fail until credits are added.');
57
+ }
58
+ return lines.join(' ');
59
+ }
60
+
61
+ // Tools that start a job answer with `job_id`, while the follow-up tools take `id`.
62
+ // Clients pass back what they were given, so accept `job_id` wherever `id` is the
63
+ // parameter (it was failing as a 404 export_not_found / job_not_found).
64
+ export function normalizeArgs(tool, args) {
65
+ const a = args || {};
66
+ if (a.id == null && a.job_id != null && tool?.inputSchema?.properties?.id) {
67
+ const { job_id, ...rest } = a;
68
+ return { ...rest, id: job_id };
69
+ }
70
+ return a;
71
+ }
72
+
73
+ // With no usable credentials the server still starts, so the client can list
74
+ // the tools; every call then answers with how to sign in instead of crashing.
75
+ export function mcpClient({ resolve = resolveKey, env = process.env } = {}) {
76
+ try {
77
+ const { key, baseUrl, dbBaseUrl } = resolve({ profile: env.KANTA_PROFILE });
78
+ return new KantaClient({ key, baseUrl, dbBaseUrl });
79
+ } catch (err) {
80
+ if (!isSignInError(err)) throw err;
81
+ return new Proxy({}, { get: (_t, prop) => (prop === 'then' ? undefined : async () => { throw err; }) });
82
+ }
83
+ }
84
+
34
85
  export async function startServer() {
35
- const { key, baseUrl, dbBaseUrl } = resolveKey({
36
- profile: process.env.KANTA_PROFILE,
37
- });
38
- const client = new KantaClient({ key, baseUrl, dbBaseUrl });
86
+ const client = mcpClient();
39
87
  const identity = await resolveIdentity();
40
88
  const tools = buildToolList(identity.scope);
41
- const handlers = new Map(tools.map(t => [t.name, wrapHandler(t, { client })]));
89
+ const handlers = new Map(tools.map(t => {
90
+ const run = wrapHandler(t, { client });
91
+ return [t.name, args => run(normalizeArgs(t, args))];
92
+ }));
42
93
 
43
94
  const server = new Server(
44
95
  { name: 'kanta', version: VERSION },
45
- { capabilities: { tools: {} } },
96
+ { capabilities: { tools: {} }, instructions: identityInstructions(identity) },
46
97
  );
47
98
 
48
99
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
@@ -12,12 +12,13 @@ const FILTER_SCHEMA = {
12
12
  description:
13
13
  'Kanta DB person filter. Keys: query (free text), seniority[] (C-Suite, VP, Director, Manager, …), ' +
14
14
  'function[], title, title_exact[], person_country[], person_state[], company, company_domain[], ' +
15
- 'industry[], employee_range[] (e.g. "51-200"), has_email, has_linkedin, has_phone. ' +
16
- 'verification_status[] is admin-only. All list keys accept a bare string too. ' +
15
+ 'industry[], employee_range[] (e.g. "51-199"), has_email, has_linkedin, has_phone. ' +
16
+ 'verification_status[] (valid, catch_all, risky, unknown, invalid). All list keys accept a bare string too. ' +
17
17
  'industry takes industry names case-insensitively (e.g. "Software Development", "software") and ' +
18
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+. ' +
19
+ 'person_state (abbreviations like "CA", "ON") and function match case-insensitively; a function also ' +
20
+ 'matches people listed under several functions. employee_range takes size bands: 1-10, 11-50, 51-199, ' +
21
+ '200-499, 500-999, 1000-4999, 5000-9999, 10000-49999, 50000+, Unknown (by headcount where known). ' +
21
22
  'Unknown values return suggestions. title_exact matches exactly.',
22
23
  };
23
24
 
@@ -29,7 +30,8 @@ const COMPANY_FILTER_SCHEMA = {
29
30
  'hq_state[], employees_min, employees_max, revenue_min_k, revenue_max_k, ' +
30
31
  'founded_after (year), min_contacts. industry takes industry names case-insensitively and includes ' +
31
32
  'sub-industries; hq_country / hq_state accept aliases and abbreviations; employee_range takes the ' +
32
- 'size bands 1-10 ... 10001+. domain matches stored values exactly.',
33
+ 'size bands 1-10, 11-50, 51-199, 200-499, 500-999, 1000-4999, 5000-9999, 10000-49999, 50000+, Unknown. ' +
34
+ 'domain matches stored values exactly.',
33
35
  };
34
36
 
35
37
  const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -42,7 +44,7 @@ async function saveExport(client, id, output) {
42
44
  const path = resolve(output);
43
45
  writeFileSync(path, csv);
44
46
  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 };
47
+ return { id, rows, output: path, delivered: status.delivered, suppressed: status.suppressed, duplicates: status.duplicates ?? 0, truncated: status.truncated };
46
48
  }
47
49
 
48
50
  function errResult(text) {
@@ -180,7 +182,7 @@ export const databaseTools = [
180
182
  },
181
183
  {
182
184
  name: 'kanta_db_export_status',
183
- description: 'Check a Kanta Database export job: status, rows delivered, rows suppressed.',
185
+ description: 'Check a Kanta Database export job: status, rows delivered, rows suppressed, duplicates skipped (same email or LinkedIn profile).',
184
186
  inputSchema: {
185
187
  type: 'object',
186
188
  properties: { id: { type: 'string' } },