findymail-mcp 0.1.16 → 0.1.17

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
@@ -130,6 +130,12 @@ PORT=3456 node src/http.js
130
130
 
131
131
  Requests to `/mcp` without a valid `Authorization: Bearer <token>` header will be rejected with a 401 error.
132
132
 
133
+ ### Optional settings
134
+
135
+ | Variable | Default | Effect |
136
+ |---|---|---|
137
+ | `FINDYMAIL_API_TIMEOUT_MS` | `100000` | How long a call to the Findymail API may take before the tool gives up. A value that is not a whole number between 1 and 2147483647 is ignored, with a warning in the logs. |
138
+
133
139
  ## Usage Examples
134
140
 
135
141
  Once configured, you can ask your AI assistant:
@@ -162,6 +168,9 @@ npm install
162
168
 
163
169
  # Run locally
164
170
  FINDYMAIL_API_KEY=your-key npm start
171
+
172
+ # Run the tests (Node 18.2+, no network access or API key needed)
173
+ npm test
165
174
  ```
166
175
 
167
176
  ## Deployment
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "findymail-mcp",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "MCP server for Findymail - Find verified B2B emails, phone numbers, and company data",
5
5
  "type": "module",
6
6
  "main": "src/stdio.js",
@@ -12,7 +12,8 @@
12
12
  ],
13
13
  "scripts": {
14
14
  "start": "node src/stdio.js",
15
- "start:http": "node src/http.js"
15
+ "start:http": "node src/http.js",
16
+ "test": "node --test"
16
17
  },
17
18
  "keywords": [
18
19
  "mcp",
package/src/api.js CHANGED
@@ -1,5 +1,28 @@
1
+ // Fixed on purpose: every call carries the user's API key, so the host it goes
2
+ // to is not something configuration should be able to change.
1
3
  const API_BASE_URL = "https://app.findymail.com/api";
2
4
 
5
+ // Cloudflare gives up on the origin at 100s, so no call can still succeed past
6
+ // that. Without a deadline at all, an upstream that stopped answering held the
7
+ // tool call open forever — and a session with a request in flight is never
8
+ // reclaimed, so each one leaked.
9
+ const DEFAULT_API_TIMEOUT_MS = 100 * 1000;
10
+ // Timers cannot go past a signed 32-bit millisecond count: AbortSignal.timeout
11
+ // throws below 0 and silently fires after 1ms above this.
12
+ const MAX_TIMER_MS = 2 ** 31 - 1;
13
+ const API_TIMEOUT_MS = apiTimeoutFromEnv(process.env.FINDYMAIL_API_TIMEOUT_MS);
14
+
15
+ // A bad value must not break every call, so fall back to the default — loudly.
16
+ function apiTimeoutFromEnv(raw) {
17
+ if (raw === undefined || raw === "") return DEFAULT_API_TIMEOUT_MS;
18
+
19
+ const ms = Number(raw);
20
+ if (Number.isInteger(ms) && ms >= 1 && ms <= MAX_TIMER_MS) return ms;
21
+
22
+ log(`FINDYMAIL_API_TIMEOUT_MS=${raw} is not a whole number of milliseconds between 1 and ${MAX_TIMER_MS} — using ${DEFAULT_API_TIMEOUT_MS}`);
23
+ return DEFAULT_API_TIMEOUT_MS;
24
+ }
25
+
3
26
  /**
4
27
  * Log to stderr (stdout is reserved for MCP protocol in stdio mode)
5
28
  */
@@ -152,71 +175,111 @@ async function apiError(response) {
152
175
  return error;
153
176
  }
154
177
 
155
- /**
156
- * Make authenticated POST request to Findymail API
157
- */
158
- export async function apiPost(endpoint, body = {}, apiKey) {
159
- if (!apiKey) apiKey = getApiKey();
178
+ // A write that failed after it was sent is not a failed write: the API may have
179
+ // finished it after we stopped listening. Say so, or the agent's natural move is
180
+ // to replay a call it cannot see the result of — a paid one, for a POST. Only
181
+ // POSTs spend credits; a DELETE removes exclusion domains, which costs nothing.
182
+ function mayHaveCompleted(method) {
183
+ const cost = method === "POST" ? ", credits included" : "";
184
+ return `The request may still have completed on Findymail's side${cost} — check its effect before sending it again`;
185
+ }
160
186
 
161
- const response = await fetch(`${API_BASE_URL}${endpoint}`, {
162
- method: "POST",
163
- headers: {
164
- "Authorization": `Bearer ${apiKey}`,
165
- "Content-Type": "application/json",
166
- "Accept": "application/json",
167
- },
168
- body: JSON.stringify(body),
169
- });
170
-
171
- if (!response.ok) {
172
- throw await apiError(response);
173
- }
187
+ function timeoutError(method, timeoutMs) {
188
+ const seconds = timeoutMs / 1000;
189
+ const message = method === "GET"
190
+ ? `Findymail did not answer within ${seconds}s — retry in a few seconds`
191
+ : `Findymail did not answer within ${seconds}s. ${mayHaveCompleted(method)}`;
192
+
193
+ // get_lead_list_results tells a slow check apart from a real failure by this.
194
+ const error = new Error(message);
195
+ error.code = "timeout";
196
+ return error;
197
+ }
198
+
199
+ // Failures that happen before a connection exists: the request never left, so
200
+ // even a write is safe to send again.
201
+ const NOT_SENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT"]);
174
202
 
175
- return response.json();
203
+ // fetch() reports every transport failure as a bare "fetch failed"; the reason
204
+ // (connection refused, reset, DNS) is on `cause`.
205
+ function networkError(method, error) {
206
+ const reason = error.cause?.code || error.cause?.message || error.message;
207
+ const message = method === "GET" || NOT_SENT.has(error.cause?.code)
208
+ ? `Could not reach Findymail (${reason}) — retry in a few seconds`
209
+ : `The connection to Findymail broke (${reason}). ${mayHaveCompleted(method)}`;
210
+
211
+ return new Error(message);
176
212
  }
177
213
 
178
- /**
179
- * Make authenticated GET request to Findymail API
180
- */
181
- export async function apiGet(endpoint, apiKey) {
214
+ async function request(method, endpoint, { apiKey, body, timeoutMs = API_TIMEOUT_MS } = {}) {
182
215
  if (!apiKey) apiKey = getApiKey();
183
216
 
184
- const response = await fetch(`${API_BASE_URL}${endpoint}`, {
185
- method: "GET",
186
- headers: {
187
- "Authorization": `Bearer ${apiKey}`,
188
- "Accept": "application/json",
189
- },
190
- });
217
+ const headers = {
218
+ "Authorization": `Bearer ${apiKey}`,
219
+ "Accept": "application/json",
220
+ };
221
+ if (body !== undefined) headers["Content-Type"] = "application/json";
191
222
 
192
- if (!response.ok) {
193
- throw await apiError(response);
194
- }
223
+ // The query string carries user input (a search filter, a run hash), so only
224
+ // the path reaches the logs — and never the token.
225
+ const path = endpoint.split("?")[0];
226
+ const startedAt = Date.now();
227
+ const elapsed = () => `${Date.now() - startedAt}ms`;
228
+
229
+ // Kept in hand so a timeout is recognised by the signal itself, not by the
230
+ // name of whatever error the runtime rejects with when it fires.
231
+ const signal = AbortSignal.timeout(timeoutMs);
195
232
 
196
- return response.json();
233
+ try {
234
+ // The signal also bounds reading the body, not just the headers.
235
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
236
+ method,
237
+ headers,
238
+ body: body === undefined ? undefined : JSON.stringify(body),
239
+ signal,
240
+ });
241
+
242
+ if (!response.ok) {
243
+ const error = await apiError(response);
244
+ log(`API ${method} ${path} → ${response.status} in ${elapsed()}`);
245
+ throw error;
246
+ }
247
+
248
+ const data = await response.json();
249
+ log(`API ${method} ${path} → ${response.status} in ${elapsed()}`);
250
+ return data;
251
+ } catch (error) {
252
+ if (error.status) throw error;
253
+
254
+ if (signal.aborted) {
255
+ log(`API ${method} ${path} → timeout in ${elapsed()}`);
256
+ throw timeoutError(method, timeoutMs);
257
+ }
258
+
259
+ log(`API ${method} ${path} → ${error.cause?.code || error.name} in ${elapsed()}`);
260
+ throw error instanceof SyntaxError ? error : networkError(method, error);
261
+ }
197
262
  }
198
263
 
199
264
  /**
200
- * Make authenticated DELETE request to Findymail API
265
+ * Make authenticated POST request to Findymail API
201
266
  */
202
- export async function apiDelete(endpoint, body = {}, apiKey) {
203
- if (!apiKey) apiKey = getApiKey();
267
+ export function apiPost(endpoint, body = {}, apiKey, options = {}) {
268
+ return request("POST", endpoint, { ...options, apiKey, body });
269
+ }
204
270
 
205
- const response = await fetch(`${API_BASE_URL}${endpoint}`, {
206
- method: "DELETE",
207
- headers: {
208
- "Authorization": `Bearer ${apiKey}`,
209
- "Content-Type": "application/json",
210
- "Accept": "application/json",
211
- },
212
- body: JSON.stringify(body),
213
- });
214
-
215
- if (!response.ok) {
216
- throw await apiError(response);
217
- }
271
+ /**
272
+ * Make authenticated GET request to Findymail API
273
+ */
274
+ export function apiGet(endpoint, apiKey, options = {}) {
275
+ return request("GET", endpoint, { ...options, apiKey });
276
+ }
218
277
 
219
- return response.json();
278
+ /**
279
+ * Make authenticated DELETE request to Findymail API
280
+ */
281
+ export function apiDelete(endpoint, body = {}, apiKey, options = {}) {
282
+ return request("DELETE", endpoint, { ...options, apiKey, body });
220
283
  }
221
284
 
222
285
  /**
package/src/http.js CHANGED
@@ -208,6 +208,24 @@ app.all("/mcp", async (req, res) => {
208
208
  // hand it to the transport, which cannot re-read a consumed stream.
209
209
  const body = await readJsonBody(req);
210
210
 
211
+ if (body === TOO_LARGE) {
212
+ log(`Session-less ${req.method} over ${MAX_BODY_BYTES} bytes — rejected`);
213
+ return res.status(413).json({
214
+ jsonrpc: "2.0",
215
+ error: { code: -32000, message: `Request body exceeds ${MAX_BODY_BYTES} bytes` },
216
+ id: null,
217
+ });
218
+ }
219
+
220
+ if (body === UNPARSABLE) {
221
+ log(`Session-less ${req.method} with a body that is not JSON — rejected`);
222
+ return res.status(400).json({
223
+ jsonrpc: "2.0",
224
+ error: { code: -32700, message: "Parse error: request body is not valid JSON" },
225
+ id: null,
226
+ });
227
+ }
228
+
211
229
  if (!isInitializeRequest(body)) {
212
230
  log(`Session-less ${req.method} that is not an initialize — rejected`);
213
231
  return res.status(400).json({
@@ -269,26 +287,43 @@ app.all("/mcp", async (req, res) => {
269
287
  }
270
288
  });
271
289
 
290
+ const TOO_LARGE = Symbol("too large");
291
+ const UNPARSABLE = Symbol("unparsable");
292
+
272
293
  // The transport parses the body itself, but it cannot do that once we have read
273
294
  // the stream to find out whether this is an initialize — so parse it here and
274
295
  // pass it down through handleRequest's parsedBody argument.
296
+ //
297
+ // Going over the limit used to destroy the socket mid-upload, so the client saw
298
+ // a dropped connection — which reads as a network fault and invites sending the
299
+ // same body again — instead of a 413 it could act on. Answering early and
300
+ // closing fails the same way for a client still writing, so do what body-parser
301
+ // does: stop buffering, discard the rest, answer once the upload ends. Node's
302
+ // requestTimeout bounds how long that can take. Bytes are counted, not characters.
275
303
  function readJsonBody(req) {
276
304
  return new Promise(resolve => {
277
- let raw = "";
278
- req.setEncoding("utf8");
305
+ const chunks = [];
306
+ let size = 0;
307
+ let tooLarge = Number(req.headers["content-length"]) > MAX_BODY_BYTES;
308
+
279
309
  req.on("data", chunk => {
280
- raw += chunk;
281
- if (raw.length > MAX_BODY_BYTES) {
282
- raw = "";
283
- req.destroy();
284
- resolve(undefined);
310
+ if (tooLarge) return;
311
+ size += chunk.length;
312
+ if (size > MAX_BODY_BYTES) {
313
+ tooLarge = true;
314
+ chunks.length = 0;
315
+ return;
285
316
  }
317
+ chunks.push(chunk);
286
318
  });
287
319
  req.on("end", () => {
320
+ if (tooLarge) return resolve(TOO_LARGE);
321
+ const raw = Buffer.concat(chunks).toString("utf8");
322
+ if (!raw) return resolve(undefined);
288
323
  try {
289
- resolve(raw ? JSON.parse(raw) : undefined);
324
+ resolve(JSON.parse(raw));
290
325
  } catch {
291
- resolve(undefined);
326
+ resolve(UNPARSABLE);
292
327
  }
293
328
  });
294
329
  req.on("error", () => resolve(undefined));
@@ -331,9 +366,10 @@ const server = app.listen(PORT, () => {
331
366
 
332
367
  // A client that vanishes without closing its TCP connection — a laptop going to
333
368
  // sleep, a NAT dropping the mapping — leaves its SSE stream open forever. No
334
- // "close" event fires, so activeRequests never drops back to zero and the
335
- // session escapes both the idle sweep and the capacity eviction: enough of them
336
- // and every new session is refused for good. Node cuts nothing on its own here
369
+ // "close" event fires, so a POST answered as a stream keeps `pending` above
370
+ // zero and its session escapes both the idle sweep and the capacity eviction:
371
+ // enough of them and every new session is refused for good. (The standalone GET
372
+ // stream is not counted — see trackRequest.) Node cuts nothing on its own here
337
373
  // (`server.timeout` is 0 by default and applies to the request, not the stream),
338
374
  // so lean on TCP keepalive to notice the dead peer.
339
375
  const KEEPALIVE_MS = Number(process.env.MCP_TCP_KEEPALIVE_MS) || 60 * 1000;
package/src/tools.js CHANGED
@@ -10,6 +10,12 @@ import { log, apiPost, apiGet, apiDelete, resolveApiKey, formatResponse, formatE
10
10
  const READS = { readOnlyHint: true, openWorldHint: true };
11
11
  const LOOKUP = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true };
12
12
 
13
+ // MCP clients give up on a request after 60s by default (the SDK's
14
+ // DEFAULT_REQUEST_TIMEOUT_MSEC), so get_lead_list_results answers within 50s
15
+ // whatever each upstream call does, leaving room for the network and the reply.
16
+ const LEAD_LIST_BUDGET_MS = 50 * 1000;
17
+ const POLL_INTERVAL_MS = 3000;
18
+
13
19
  // `title` became a top-level field on Tool in the 2025-06-18 spec, but clients
14
20
  // and review tooling written against the earlier shape still read it out of
15
21
  // `annotations` — declare it in both places from the one source.
@@ -17,10 +23,13 @@ function toolConfig({ title, description, inputSchema = {}, annotations }) {
17
23
  return { title, description, inputSchema, annotations: { title, ...annotations } };
18
24
  }
19
25
 
26
+ // Logs end up in PM2 and Datadog. Record which tool ran and the shape of the
27
+ // call — never the names, emails, LinkedIn URLs, domains or queries it was
28
+ // given: those are personal data or a customer's prospecting targets.
20
29
  /**
21
30
  * Register all Findymail tools on an MCP server
22
31
  */
23
- export function registerTools(server) {
32
+ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS } = {}) {
24
33
  // ===========================================================================
25
34
  // Tool: find_email
26
35
  // ===========================================================================
@@ -37,7 +46,7 @@ export function registerTools(server) {
37
46
  annotations: LOOKUP,
38
47
  }),
39
48
  async (params, extra) => {
40
- log(`find_email: ${JSON.stringify(params)}`);
49
+ log(`find_email: by ${params.linkedin_url ? "linkedin_url" : "name+domain"}`);
41
50
 
42
51
  try {
43
52
  const apiKey = resolveApiKey(extra);
@@ -74,15 +83,13 @@ export function registerTools(server) {
74
83
  description: "Find employees at a company by job title. Given a company website or domain and a list of target job titles, returns matching contacts with name, job title, company and LinkedIn URL. Email addresses are not part of the response: to get a verified email for a contact, pass the returned name and domain — or the returned LinkedIn URL — to `find_email`. Use it to build a shortlist of people to reach at a known company; to discover the companies themselves, use `generate_lead_list` or `lookalike_search` first. Costs 1 finder credit per contact returned.",
75
84
  inputSchema: {
76
85
  website: z.string().describe("Company website or domain (e.g., \"findymail.com\")"),
77
- job_titles: z.array(z.string()).describe("Target job titles (max 10, each max 50 characters, e.g., [\"CTO\", \"VP Engineering\"])"),
78
- count: z.number().optional().default(1).describe("Number of contacts to return (min: 1, max: 5, default: 1)"),
86
+ job_titles: z.array(z.string().max(50)).min(1).max(10).describe("Target job titles (max 10, each max 50 characters, e.g., [\"CTO\", \"VP Engineering\"])"),
87
+ count: z.number().int().min(1).max(5).optional().default(1).describe("Number of contacts to return (min: 1, max: 5, default: 1)"),
79
88
  },
80
89
  annotations: LOOKUP,
81
90
  }),
82
91
  async ({ website, job_titles, count = 1 }, extra) => {
83
- log(`find_employees: website="${website}" job_titles=${JSON.stringify(job_titles)} count=${count}`);
84
-
85
- const validatedCount = Math.min(Math.max(1, count), 5);
92
+ log(`find_employees: ${job_titles.length} job title(s), count=${count}`);
86
93
 
87
94
  try {
88
95
  const apiKey = resolveApiKey(extra);
@@ -90,7 +97,7 @@ export function registerTools(server) {
90
97
  const data = await apiPost("/search/employees", {
91
98
  website,
92
99
  job_titles,
93
- count: validatedCount,
100
+ count,
94
101
  }, apiKey);
95
102
 
96
103
  return formatResponse(data);
@@ -114,7 +121,7 @@ export function registerTools(server) {
114
121
  annotations: LOOKUP,
115
122
  }),
116
123
  async ({ linkedin_url }, extra) => {
117
- log(`find_phone: ${linkedin_url}`);
124
+ log("find_phone");
118
125
 
119
126
  try {
120
127
  const apiKey = resolveApiKey(extra);
@@ -135,12 +142,12 @@ export function registerTools(server) {
135
142
  title: "Verify Email",
136
143
  description: "Check whether an email address is deliverable, without sending anything to it. Use it on addresses that came from elsewhere (a CRM export, a spreadsheet, the user) before adding them to an outreach sequence. Addresses returned by `find_email` and `generate_lead_list` are already verified and do not need a second pass. Costs 1 verifier credit per address checked — verifier credits are a separate pool from the finder credits the lookup tools spend.",
137
144
  inputSchema: {
138
- email: z.string().describe("Email address to verify"),
145
+ email: z.string().trim().email().describe("Email address to verify"),
139
146
  },
140
147
  annotations: LOOKUP,
141
148
  }),
142
149
  async ({ email }, extra) => {
143
- log(`verify_email: ${email}`);
150
+ log("verify_email");
144
151
 
145
152
  try {
146
153
  const apiKey = resolveApiKey(extra);
@@ -168,7 +175,7 @@ export function registerTools(server) {
168
175
  annotations: LOOKUP,
169
176
  }),
170
177
  async (params, extra) => {
171
- log(`enrich_company: ${JSON.stringify(params)}`);
178
+ log(`enrich_company: by ${Object.keys(params).filter(key => params[key]).join("+")}`);
172
179
 
173
180
  try {
174
181
  const apiKey = resolveApiKey(extra);
@@ -199,13 +206,13 @@ export function registerTools(server) {
199
206
  title: "Reverse Email Lookup",
200
207
  description: "Identify the person behind an email address. Returns their LinkedIn profile URL; set with_profile to also return the full LinkedIn profile (name, job title, company etc.). Use it to put a name and a company on an address that arrived without context — an inbound reply, a CRM row, an imported list — and chain the returned LinkedIn URL into `find_phone` when you need to reach them by phone. It says nothing about deliverability: use `verify_email` for that. Costs 1 finder credit per contact found, or 2 finder credits when with_profile returns complete profile data; an address that matches nobody is not charged.",
201
208
  inputSchema: {
202
- email: z.string().describe("Email address to lookup"),
209
+ email: z.string().trim().email().describe("Email address to lookup"),
203
210
  with_profile: z.boolean().optional().default(false).describe("Include full LinkedIn profile data"),
204
211
  },
205
212
  annotations: LOOKUP,
206
213
  }),
207
214
  async ({ email, with_profile }, extra) => {
208
- log(`reverse_email_lookup: ${email}`);
215
+ log(`reverse_email_lookup: with_profile=${with_profile}`);
209
216
 
210
217
  try {
211
218
  const apiKey = resolveApiKey(extra);
@@ -229,8 +236,8 @@ export function registerTools(server) {
229
236
  seed: z.string().describe("The domain or URL of the seed company to find lookalikes for (e.g. \"stripe.com\" or \"https://www.stripe.com/pricing\"). URLs are automatically resolved to their root domain."),
230
237
  same_country: z.boolean().optional().default(false).describe("When true, only return companies located in the same country as the seed company"),
231
238
  same_size: z.boolean().optional().default(false).describe("When true, only return companies with a similar employee count range as the seed company"),
232
- limit: z.number().optional().default(100).describe("Maximum number of results to return (min: 1, max: 10,000)"),
233
- exclusion_list_ids: z.array(z.number()).optional().default([]).describe("IDs of exclusion lists whose domains should be removed from results. Unlike `generate_lead_list`, this parameter does NOT accept the [0] / [-1] markers — pass real list IDs only (from `list_exclusion_lists`), or leave it empty for no filtering."),
239
+ limit: z.number().int().min(1).max(10000).optional().default(100).describe("Maximum number of results to return (min: 1, max: 10,000)"),
240
+ exclusion_list_ids: z.array(z.number().int().positive()).optional().default([]).describe("IDs of exclusion lists whose domains should be removed from results. Unlike `generate_lead_list`, this parameter does NOT accept the [0] / [-1] markers — pass real list IDs only (from `list_exclusion_lists`), or leave it empty for no filtering."),
234
241
  },
235
242
  annotations: LOOKUP,
236
243
  }),
@@ -243,9 +250,7 @@ export function registerTools(server) {
243
250
  exclusion_list_ids = [],
244
251
  } = params;
245
252
 
246
- log(`lookalike_search: seed="${seed}" (limit: ${limit})`);
247
-
248
- const validatedLimit = Math.min(Math.max(1, limit), 10000);
253
+ log(`lookalike_search: limit=${limit} same_country=${same_country} same_size=${same_size}`);
249
254
 
250
255
  try {
251
256
  const apiKey = resolveApiKey(extra);
@@ -254,7 +259,7 @@ export function registerTools(server) {
254
259
  seed,
255
260
  same_country,
256
261
  same_size,
257
- limit: validatedLimit,
262
+ limit,
258
263
  exclusion_list_ids,
259
264
  }, apiKey);
260
265
 
@@ -274,15 +279,21 @@ export function registerTools(server) {
274
279
  title: "Generate Lead List",
275
280
  description: "Start a company discovery run from a natural language description of an ideal customer profile. This is a semantic search, not a database lookup, so describe the kind of company you are looking for rather than listing exact filter values (e.g. \"SaaS companies in the USA with 50+ employees\", \"tech startups offering insurance services in NYC\"). Use 'targeted' mode to return only companies strictly matching the description (narrower) or `broad` mode to return companies loosely matching the description (broader). Matching companies can be enriched with contacts, verified email addresses and phone numbers. The run is asynchronous and this call returns only a hash: pass that hash to `get_lead_list_results` to follow progress and retrieve the results. Credit cost depends on the options chosen — 1 finder credit per 10 companies in 'broad' mode or 1 per company in 'targeted' mode, plus 1 per contact found, 1 per email found and 10 per phone number found.",
276
281
  inputSchema: {
277
- query: z.string().describe("Natural language description of what you're looking for (max 1000 characters)"),
278
- limit: z.number().optional().default(100).describe("Maximum number of results (default: 100, max: 5000)"),
282
+ query: z.string().max(1000).describe("Natural language description of what you're looking for (max 1000 characters)"),
283
+ limit: z.number().int().min(1).max(5000).optional().default(100).describe("Maximum number of results (default: 100, max: 5000)"),
279
284
  mode: z.enum(["broad", "targeted"]).optional().default("broad").describe("'broad' = fast export (1 credit/10 companies), 'targeted' = AI-qualified results (1 credit/company)"),
280
285
  find_contact: z.boolean().optional().default(true).describe("Search for contacts at each company (+1 credit/contact found)"),
281
286
  target_job_titles: z.array(z.string()).optional().default(["CEO"]).describe("Job titles to target when find_contact is true (e.g., ['CEO', 'CTO', 'VP Sales'])"),
282
287
  find_email: z.boolean().optional().default(true).describe("Enrich contacts with email (+1 credit/email found). Requires find_contact: true"),
283
288
  find_phone: z.boolean().optional().default(false).describe("Enrich contacts with phone (+10 credits/phone found). Requires find_contact: true"),
284
- exclusion_list_ids: z.array(z.number()).optional().describe("IDs of exclusion lists whose domains must be filtered out of the results. Omit this parameter to keep the default behaviour. [0] means \"every exclusion source you can reach\" (your global exclusions plus every list you own or share) — NOT just the global one. [-1] disables exclusion filtering entirely, and so does an empty array. Never mix these markers with real list IDs: [0, 12] silently ignores 12 and filters on everything, and [-1, 12] silently disables filtering altogether. Pass either exactly [0], exactly [-1], or real list IDs — never a mixture. Get them from `list_exclusion_lists`."),
285
- add_to_exclusion_list_id: z.number().optional().describe("ID of an exclusion list to automatically add every exported company domain to, so later searches never return them again. The domains are written once, at the very end of the export: nothing is added if the export fails, and if that final write itself fails the export is still reported as successful — check with `list_exclusion_domains` when it matters. Only pass an ID returned by `list_exclusion_lists`, or create one with `create_exclusion_list`."),
289
+ // The API resolves a mix silently and wrongly (see the description), so
290
+ // refuse it here rather than documenting the trap and hoping.
291
+ exclusion_list_ids: z.array(z.number().int().min(-1))
292
+ .refine(ids => ids.length <= 1 || ids.every(id => id > 0), {
293
+ message: "Pass exactly [0], exactly [-1], or real list ids — never a marker mixed with other ids",
294
+ })
295
+ .optional().describe("IDs of exclusion lists whose domains must be filtered out of the results. Omit this parameter to keep the default behaviour. [0] means \"every exclusion source you can reach\" (your global exclusions plus every list you own or share) — NOT just the global one. [-1] disables exclusion filtering entirely, and so does an empty array. Never mix these markers with real list IDs: [0, 12] silently ignores 12 and filters on everything, and [-1, 12] silently disables filtering altogether. Pass either exactly [0], exactly [-1], or real list IDs — never a mixture. Get them from `list_exclusion_lists`."),
296
+ add_to_exclusion_list_id: z.number().int().positive().optional().describe("ID of an exclusion list to automatically add every exported company domain to, so later searches never return them again. The domains are written once, at the very end of the export: nothing is added if the export fails, and if that final write itself fails the export is still reported as successful — check with `list_exclusion_domains` when it matters. Only pass an ID returned by `list_exclusion_lists`, or create one with `create_exclusion_list`."),
286
297
  },
287
298
  // Each call starts a new run and spends credits again, so it is not
288
299
  // idempotent: an identical query is a second export, not a replay.
@@ -301,9 +312,7 @@ export function registerTools(server) {
301
312
  add_to_exclusion_list_id,
302
313
  } = params;
303
314
 
304
- log(`generate_lead_list: "${query}" (limit: ${limit}, mode: ${mode})`);
305
-
306
- const validatedLimit = Math.min(Math.max(1, limit), 5000);
315
+ log(`generate_lead_list: limit=${limit} mode=${mode} find_contact=${find_contact} find_email=${find_email} find_phone=${find_phone}`);
307
316
 
308
317
  try {
309
318
  const apiKey = resolveApiKey(extra);
@@ -330,7 +339,7 @@ export function registerTools(server) {
330
339
 
331
340
  const startResult = await apiPost("/intellimatch/search", {
332
341
  query,
333
- limit: validatedLimit,
342
+ limit,
334
343
  config,
335
344
  }, apiKey);
336
345
 
@@ -338,7 +347,7 @@ export function registerTools(server) {
338
347
  return formatError("Failed to start search");
339
348
  }
340
349
 
341
- log(`generate_lead_list: search started with hash ${startResult.hash}`);
350
+ log("generate_lead_list: search started");
342
351
 
343
352
  return formatResponse({
344
353
  hash: startResult.hash,
@@ -358,26 +367,37 @@ export function registerTools(server) {
358
367
  "get_lead_list_results",
359
368
  toolConfig({
360
369
  title: "Get Lead List Results",
361
- description: "Retrieve results from a lead list search started with `generate_lead_list`. Takes the hash returned by `generate_lead_list`. Polls the search status for up to 60 seconds. If the search completes within that time, returns the full data. If still processing after 60s, returns the current progress — call again to continue waiting. Consumes no credits: the run itself was charged by `generate_lead_list`.",
370
+ description: "Retrieve results from a lead list search started with `generate_lead_list`. Takes the hash returned by `generate_lead_list`. Polls the search status for up to 50 seconds. If the search completes within that time, returns the full data. If still processing after 50s, returns the current progress — call again to continue waiting. Consumes no credits: the run itself was charged by `generate_lead_list`.",
362
371
  inputSchema: {
363
372
  hash: z.string().describe("The hash returned by generate_lead_list"),
364
373
  },
365
374
  annotations: READS,
366
375
  }),
367
376
  async ({ hash }, extra) => {
368
- log(`get_lead_list_results: hash=${hash}`);
377
+ log("get_lead_list_results");
369
378
 
370
379
  const progressToken = extra._meta?.progressToken;
371
380
 
372
381
  try {
373
382
  const apiKey = resolveApiKey(extra);
374
383
 
375
- const maxAttempts = 20; // 20 × 3s = 60s max (under MCP client timeout)
376
- const pollInterval = 3000; // 3 seconds
377
-
378
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
379
- const statusResult = await apiGet(`/intellimatch/status?hash=${hash}`, apiKey);
380
- log(`get_lead_list_results: status=${statusResult.status}, attempt ${attempt + 1}/${maxAttempts}`);
384
+ const deadline = Date.now() + leadListBudgetMs;
385
+ // Each call gets what is left of the budget, never less than 1ms.
386
+ const remaining = () => Math.max(1, deadline - Date.now());
387
+ const stillProcessing = message => formatResponse({ status: "processing", hash, message });
388
+
389
+ for (let attempt = 1; ; attempt++) {
390
+ let statusResult;
391
+ try {
392
+ statusResult = await apiGet(`/intellimatch/status?hash=${encodeURIComponent(hash)}`, apiKey, { timeoutMs: remaining() });
393
+ } catch (error) {
394
+ // A slow status check says nothing about the run itself: it is
395
+ // still processing as far as we know.
396
+ if (error.code !== "timeout") throw error;
397
+ log(`get_lead_list_results: status check timed out, attempt ${attempt}`);
398
+ statusResult = { status: "processing" };
399
+ }
400
+ log(`get_lead_list_results: status=${statusResult.status}, attempt ${attempt}`);
381
401
 
382
402
  if (statusResult.status === "success") {
383
403
  // Send 100% progress before fetching data
@@ -395,26 +415,41 @@ export function registerTools(server) {
395
415
  let lastPage = 1;
396
416
  const perPage = 100;
397
417
 
398
- do {
399
- const dataResult = await apiGet(`/intellimatch/data?hash=${hash}&page=${currentPage}&per_page=${perPage}`, apiKey);
400
-
401
- if (dataResult.data && Array.isArray(dataResult.data)) {
402
- allData.push(...dataResult.data);
403
- }
404
-
405
- if (dataResult.meta) {
406
- lastPage = dataResult.meta.last_page || 1;
407
- }
408
-
409
- currentPage++;
410
- } while (currentPage <= lastPage);
418
+ try {
419
+ do {
420
+ const dataResult = await apiGet(`/intellimatch/data?hash=${encodeURIComponent(hash)}&page=${currentPage}&per_page=${perPage}`, apiKey, { timeoutMs: remaining() });
421
+
422
+ if (dataResult.data && Array.isArray(dataResult.data)) {
423
+ allData.push(...dataResult.data);
424
+ }
425
+
426
+ if (dataResult.meta) {
427
+ lastPage = dataResult.meta.last_page || 1;
428
+ }
429
+
430
+ currentPage++;
431
+ } while (currentPage <= lastPage);
432
+ } catch (error) {
433
+ // The run is done; only fetching it ran out of time. A new call
434
+ // starts with a full budget and finds the status already done.
435
+ if (error.code !== "timeout") throw error;
436
+ log(`get_lead_list_results: data fetch timed out after ${allData.length} results`);
437
+ return stillProcessing("Search is complete but its results could not be fetched in time. Call get_lead_list_results again to fetch them.");
438
+ }
411
439
 
412
440
  log(`get_lead_list_results: fetched ${allData.length} results`);
413
441
  return formatResponse({ status: "success", data: allData, total: allData.length });
414
442
  }
415
443
 
444
+ // An unknown hash is a 200 with this status, not a 4xx: waiting on it
445
+ // would only burn the budget and send the agent back for more.
446
+ if (statusResult.status === "not_found") {
447
+ return formatError("No lead list search matches this hash — pass the exact hash returned by generate_lead_list");
448
+ }
449
+
450
+ // The API gives the reason under `error`, not `message`.
416
451
  if (statusResult.status === "failed") {
417
- return formatError(statusResult.message || "Search failed");
452
+ return formatError(statusResult.message || statusResult.error || "Search failed");
418
453
  }
419
454
 
420
455
  if (statusResult.status === "cancelled") {
@@ -437,18 +472,13 @@ export function registerTools(server) {
437
472
  }
438
473
  log(`get_lead_list_results: progress ${statusResult.progress ?? "in preparation"}`);
439
474
 
440
- // Don't sleep after the last attempt
441
- if (attempt < maxAttempts - 1) {
442
- await new Promise(resolve => setTimeout(resolve, pollInterval));
443
- }
475
+ // Stop when a wait would leave no time for another check
476
+ if (deadline - Date.now() <= POLL_INTERVAL_MS) break;
477
+ await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS));
444
478
  }
445
479
 
446
- // Still processing after 60s — return progress so the model can call again
447
- return formatResponse({
448
- status: "processing",
449
- hash,
450
- message: "Search is still processing after 60 seconds. Call get_lead_list_results again to continue waiting.",
451
- });
480
+ // Out of time — return progress so the model can call again
481
+ return stillProcessing(`Search is still processing after ${leadListBudgetMs / 1000} seconds. Call get_lead_list_results again to continue waiting.`);
452
482
  } catch (error) {
453
483
  return formatError(error.message);
454
484
  }
@@ -488,7 +518,7 @@ export function registerTools(server) {
488
518
  title: "Create Exclusion List",
489
519
  description: "Create a new, empty exclusion list and return its id. Add domains to it with `add_exclusion_domains`, or let a search fill it automatically via `generate_lead_list`'s add_to_exclusion_list_id. List names must be unique per user. If is_shared is true and you do not belong to a team, the list is still created but the call returns an error — do not retry with the same name, it would then fail as a duplicate. Call `list_exclusion_lists` to check before retrying. Consumes no credits.",
490
520
  inputSchema: {
491
- name: z.string().describe("Name of the list (max 255 characters, must be unique among your lists, e.g. \"Competitors\")"),
521
+ name: z.string().max(255).describe("Name of the list (max 255 characters, must be unique among your lists, e.g. \"Competitors\")"),
492
522
  is_shared: z.boolean().optional().default(false).describe("Share the list with your current team. Fails if you do not belong to a team."),
493
523
  },
494
524
  // Names are unique per user, so a repeated call fails as a duplicate
@@ -496,7 +526,7 @@ export function registerTools(server) {
496
526
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
497
527
  }),
498
528
  async ({ name, is_shared = false }, extra) => {
499
- log(`create_exclusion_list: name="${name}" is_shared=${is_shared}`);
529
+ log(`create_exclusion_list: is_shared=${is_shared}`);
500
530
 
501
531
  try {
502
532
  const apiKey = resolveApiKey(extra);
@@ -517,22 +547,22 @@ export function registerTools(server) {
517
547
  title: "List Excluded Domains",
518
548
  description: "List the domains held by an exclusion list, paginated. Each domain is returned with its own id — those ids are what `remove_exclusion_domains` needs, so call this first when you want to remove domains. Omitting list_id does NOT return only your global exclusions: it returns EVERY domain you can reach — your global ones, every list you own, AND every list shared with your team. To act on the global exclusions only, keep the entries whose `excluded_domain_list_id` is null. Always pass an explicit list_id before deleting anything. Results are ordered by domain name alone, so an entry can move between pages — re-read the page before using an id. Consumes no credits.",
519
549
  inputSchema: {
520
- list_id: z.number().optional().describe("Exclusion list to read. Must be >= 1 — passing 0 returns a 422 error. Omit the parameter to list every domain you can reach (see the tool description). Get ids from `list_exclusion_lists`."),
521
- query: z.string().optional().describe("Filter domains containing this text (max 100 characters, e.g. \"competitor\")"),
522
- page: z.number().optional().default(1).describe("Page number (default: 1)"),
523
- per_page: z.number().optional().default(15).describe("Domains per page (default: 15, max: 100)"),
550
+ list_id: z.number().int().min(1).optional().describe("Exclusion list to read. Must be >= 1 — 0 is refused. Omit the parameter to list every domain you can reach (see the tool description). Get ids from `list_exclusion_lists`."),
551
+ query: z.string().max(100).optional().describe("Filter domains containing this text (max 100 characters, e.g. \"competitor\")"),
552
+ page: z.number().int().min(1).optional().default(1).describe("Page number (default: 1)"),
553
+ per_page: z.number().int().min(1).max(100).optional().default(15).describe("Domains per page (default: 15, max: 100)"),
524
554
  },
525
555
  annotations: READS,
526
556
  }),
527
557
  async ({ list_id, query, page = 1, per_page = 15 }, extra) => {
528
- log(`list_exclusion_domains: list_id=${list_id ?? "global"} query=${query ?? "-"} page=${page}`);
558
+ log(`list_exclusion_domains: list_id=${list_id ?? "all"} filtered=${Boolean(query)} page=${page}`);
529
559
 
530
560
  try {
531
561
  const apiKey = resolveApiKey(extra);
532
562
 
533
563
  const searchParams = new URLSearchParams({
534
- page: String(Math.max(1, page)),
535
- per_page: String(Math.min(Math.max(1, per_page), 100)),
564
+ page: String(page),
565
+ per_page: String(per_page),
536
566
  });
537
567
  if (list_id !== undefined) searchParams.set("list_id", String(list_id));
538
568
  if (query) searchParams.set("query", query);
@@ -554,8 +584,8 @@ export function registerTools(server) {
554
584
  title: "Add Excluded Domains",
555
585
  description: "Add company domains to an exclusion list so they stop appearing in search results. Omit list_id to add them to your global exclusions instead. Domains are reduced to their registrable form before storage: protocol, path and ALL subdomains are stripped, so \"careers.acme.com\" and \"https://www.acme.com/jobs\" both become \"acme.com\" and exclude the whole company. Entries that cannot be parsed as a domain are dropped silently and are not reported back. The response counters do NOT reflect what was stored: `total` and `processed_immediately` count the entries you sent, dropped ones included, so `total: 4` can mean 3 domains excluded — read the list back with `list_exclusion_domains` to know what landed. Large batches are accepted (max 10,000): the first 50 domains are applied immediately and the rest are queued in the background, so a search started right away will only account for the first 50. Consumes no credits.",
556
586
  inputSchema: {
557
- domains: z.array(z.string()).describe("Company domains to exclude (max 10,000, each max 255 characters, e.g. [\"competitor.com\", \"blocked.io\"])"),
558
- list_id: z.number().optional().describe("Exclusion list to add the domains to. Omit to add them as global exclusions — 0 does the same here, unlike `list_exclusion_domains` where 0 is rejected with a 422. Get ids from `list_exclusion_lists`."),
587
+ domains: z.array(z.string().max(255)).min(1).max(10000).describe("Company domains to exclude (max 10,000, each max 255 characters, e.g. [\"competitor.com\", \"blocked.io\"])"),
588
+ list_id: z.number().int().min(0).optional().describe("Exclusion list to add the domains to. Omit to add them as global exclusions — 0 does the same here, unlike `list_exclusion_domains` where 0 is refused. Get ids from `list_exclusion_lists`."),
559
589
  },
560
590
  // Re-adding a domain that is already on the list leaves the same state.
561
591
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
@@ -586,7 +616,7 @@ export function registerTools(server) {
586
616
  title: "Remove Excluded Domains",
587
617
  description: "Remove domains from an exclusion list, making them eligible for search results again. Takes domain ids, NOT domain names — call `list_exclusion_domains` first to resolve names into ids. Deletion is permanent: there is no undo and no soft delete. If none of the ids are yours to delete the call fails with a 403 rather than reporting a count of zero; if only some are, the others are dropped silently and the response does not say which. On a team-shared list you are allowed to delete domains added by teammates, so check the list before deleting. Ids obtained right after a large `add_exclusion_domains` may be stale. Consumes no credits.",
588
618
  inputSchema: {
589
- ids: z.array(z.number()).describe("Ids of the domains to remove (max 1000), as returned by `list_exclusion_domains`"),
619
+ ids: z.array(z.number().int().positive()).min(1).max(1000).describe("Ids of the domains to remove (max 1000), as returned by `list_exclusion_domains`"),
590
620
  },
591
621
  // Permanent deletion, and a repeated call fails with a 403 once the ids
592
622
  // are gone rather than succeeding as a no-op.